Compare commits
70
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ed7201efa | ||
|
|
138c73e20c | ||
|
|
58960b5e93 | ||
|
|
79121bc447 | ||
|
|
36ceb358b8 | ||
|
|
a3a158faa8 | ||
|
|
ae604268e0 | ||
|
|
ae122a664a | ||
|
|
62d9728b95 | ||
|
|
ee129fbd87 | ||
|
|
10be55d261 | ||
|
|
ed97956a2f | ||
|
|
e79e5a11f9 | ||
|
|
66557c7f1d | ||
|
|
f4b6a41f83 | ||
|
|
2eaedb8cec | ||
|
|
45a2edd4cc | ||
|
|
0e3534f29f | ||
|
|
9954e66c33 | ||
|
|
9523976044 | ||
|
|
06eedd0499 | ||
|
|
75aeae1ff2 | ||
|
|
d0df78abe3 | ||
|
|
029d3f4e89 | ||
|
|
0b500934cb | ||
|
|
86ddc2e6d9 | ||
|
|
5fbfd28014 | ||
|
|
703fa7804f | ||
|
|
9eb4d345c6 | ||
|
|
e4730120ab | ||
|
|
ac6800d9de | ||
|
|
fc1e97eba8 | ||
|
|
cd84838e78 | ||
|
|
6c03a10a24 | ||
|
|
fe54d9ab7b | ||
|
|
0d48f81c02 | ||
|
|
c1383d62aa | ||
|
|
9dc42e7481 | ||
|
|
a01465a4bb | ||
|
|
e59e7488a3 | ||
|
|
1fe94bf70e | ||
|
|
970a60d55f | ||
|
|
da0a7b5f15 | ||
|
|
e5bb98c81f | ||
|
|
9dd599cd80 | ||
|
|
8dc2c8ad68 | ||
|
|
1bb64b1902 | ||
|
|
3d28ec6edb | ||
|
|
d7f30d348a | ||
|
|
87069c85dd | ||
|
|
1f9f2f4640 | ||
|
|
544cd30656 | ||
|
|
55a924afb6 | ||
|
|
e9f1e46781 | ||
|
|
3e85921a35 | ||
|
|
8899c97a9c | ||
|
|
e04bfac208 | ||
|
|
7677f54056 | ||
|
|
ce1c978f21 | ||
|
|
8542d19be0 | ||
|
|
4cc30c1445 | ||
|
|
d91d956e78 | ||
|
|
9f07ecf0dd | ||
|
|
74df4aa7b5 | ||
|
|
72a6283024 | ||
|
|
86711699cf | ||
|
|
d28029e96e | ||
|
|
e65e26202a | ||
|
|
ca55142f6f | ||
|
|
1b94814f67 |
@@ -2,6 +2,90 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## events@3.7.0 + @crosscode/ui 0.3.0 - 2026-11-24
|
||||
|
||||
Cross Events' public pages use the church's brand style and the shared footer (WEBSITE-1.0-PLAN §9).
|
||||
Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
- **Events 3.7.0:** the church profile from Accounts (`GET /api/v2/church`), its fonts and corners
|
||||
on the public pages, `ChurchFooter` and links to the church's other sites; `church.changed` is
|
||||
accepted at `/api/church/v1/changed`. Dashboard and setup unchanged. No migrations.
|
||||
- **`@crosscode/ui` 0.3.0:** `ChurchFooter` takes `bottom` (a product's own links).
|
||||
|
||||
## contracts@1.17.0 + accounts@1.7.0 + @crosscode/ui 0.2.0 - 2026-11-24
|
||||
|
||||
The first release of the Church Website 1.0.0 work (WEBSITE-1.0-PLAN §12). The contracts are
|
||||
additive and optional: products on 1.16.0 keep working. Accounts 1.7.0 ships with them because it
|
||||
answers the new `church.update` request. Details of Accounts in `apps/accounts/CHANGELOG.md`.
|
||||
|
||||
- **Brand style** (`./style`): the 8 font pairings confirmed on 2026-11-24 (`FONT_PAIRINGS`:
|
||||
`classic`, `scholarly`, `editorial`, `impact`, `contemporary`, `friendly`, `warm`, `modern`, each
|
||||
with its heading and body font), the corner styles (`CORNERS`, `DEFAULT_CORNERS` = `soft`), the
|
||||
Website's templates (`WEBSITE_TEMPLATES`) and the three pairings each recommends
|
||||
(`TEMPLATE_FONT_PAIRINGS`, default first). The ids are stored in profiles and never change.
|
||||
- **`crosscode.church/1`:** optional `branding.style` (`fontPairing`, `corners`, each nullable). An
|
||||
id a product doesn't know yet reads as null, so a newer Accounts never breaks an older product.
|
||||
- **`crosscode.church-export/1`:** an optional `website` part (template, first publish, style
|
||||
settings, pages with their sections, messages, simple events, the publish history's notes and
|
||||
the media library's alt text). New sample `church-export-website.json`.
|
||||
- **`church.update`** (identity request, product → Accounts, signed with the link's secret): the
|
||||
Website's admin changes shared profile facts (plan decision 10). The product checks the person's
|
||||
role and sends them as `actor`; only the fields given change (`branding` field by field); live at
|
||||
once, then `church.changed`. Optional `ifUpdatedAt` refuses with the new error code
|
||||
`PROFILE_CHANGED` when someone saved in between. Reply: the profile (`churchUpdateReplySchema`).
|
||||
Accounts 1.7.0 takes it from the Website only.
|
||||
- **Licence:** optional `limits.storageBytes`, the Website's storage limit including add-ons (plan
|
||||
decision 12). New sample `hub-licence-payload-website.json`.
|
||||
- **Accounts 1.7.0:** the brand style in Admin → Church profile, the church's fonts, corners and
|
||||
shared footer on its pages, and `church.update` from the Website. Update Accounts before (or with)
|
||||
anything that sends `church.update`; nothing does until the Website.
|
||||
- **`@crosscode/ui` 0.2.0:** `fonts.css` (the 8 pairings' fonts, Latin and Latin Extended, from the
|
||||
pinned `@fontsource-variable` packages, with Capsize size-matched fallbacks on Arial or Georgia;
|
||||
generated by `scripts/fonts.mjs`, checked by `npm test`, at most 160 KB per pairing for an
|
||||
English page), `brandAttributes`, `ChurchFooter`, `productLinks`; the components' corners follow
|
||||
`--cc-radius` and headings the pairing's heading font. Apps without a pairing look as before.
|
||||
- `package-lock.json` catches up with the agent's and contracts' versions.
|
||||
|
||||
## agent@1.5.0 + contracts@1.16.0 + crosscode script - 2026-11-23
|
||||
|
||||
- **Fix: uninstalling one product removed the whole church.** `crosscode uninstall <church>` only
|
||||
knew whole churches, while the Hub uninstalls per product: uninstalling cross-events-demo's
|
||||
Events also removed its Accounts, which the Hub still showed as live, and its own uninstall
|
||||
failed later ("No church cross-events-demo on this server").
|
||||
- **`crosscode uninstall|export|purge <church> [product …]`.** With products named, only those
|
||||
are backed up, kept (`.removed/<church>-<date>/<product>`) and removed; the church keeps the
|
||||
others in church.env. Naming every product it still has removes the church (folder and app
|
||||
user), so the last product to go always takes the church with it. The report gives `products`
|
||||
and `remaining`. `purge` with products deletes only what was kept of those, also while the
|
||||
church still has others. Without products, as before.
|
||||
- **Agent 1.5.0** passes `products` through. **Contracts 1.16.0:** optional `products` on the
|
||||
`export`, `uninstall` and `purge` job arguments, and `PRODUCT_UNINSTALL_MIN_AGENT` (an older
|
||||
agent refuses the key). Hub 2.12.0 uses them.
|
||||
- The Church Website plan's versions move up one again: contracts 1.17.0, Hub 2.13.0.
|
||||
|
||||
## agent@1.4.0 + contracts@1.15.0 - 2026-11-21
|
||||
|
||||
- **Agent 1.4.0: frp's config, wherever it is.** The agent no longer assumes
|
||||
`/etc/frp/frps.ini`: it uses the path set on the Hub, else the `-c` in the frps/frpc systemd
|
||||
unit, else the usual places (`/etc/frp`, `/usr/local/frp`, `/opt/frp` …), and reads TOML
|
||||
(`proxyBindAddr`, `allowPorts = [{ start, end }]`) as well as INI. The central server's check
|
||||
after an install failed with "No frps.ini at /etc/frp/frps.ini" on a server that keeps it
|
||||
elsewhere. Stats say which file it uses (`frpConfigPath`). `crosscode` gets `FRPC_INI` for it
|
||||
on church servers.
|
||||
- **New jobs** (both modes): `frp-read` (the config, secrets hidden), `frp-write` (secrets put
|
||||
back, `frp* verify`, backup, restart, the old file back if frp doesn't start) and
|
||||
`probe-ports` (which of these ports are free here). Contracts 1.15.0: the job arguments,
|
||||
`frpReadResultSchema`, `probePortsResultSchema`, `FRP_JOBS_MIN_AGENT`, `FRP_HIDDEN`,
|
||||
`agentStats.frpConfigPath`. The Hub needs agent 1.4.0 on a server for these (Hub 2.11.0).
|
||||
- The Church Website plan's versions move up one: contracts 1.16.0, Hub 2.12.0.
|
||||
|
||||
## crosscode script - 2026-11-20 (no tag: servers run `main`)
|
||||
|
||||
- **Fix:** the database dump made before each Accounts deploy (`apps/accounts/backend/backups/`)
|
||||
counted as a file added by hand on Accounts below 1.3.0 (no `.gitignore` for it yet), so the
|
||||
next deploy stopped with "changed or added by hand". Untracked files in that folder no longer
|
||||
count (`CROSSCODE_OWN_DIRS` in `lib/common.sh`).
|
||||
|
||||
## events@3.6.1 - 2026-11-20
|
||||
|
||||
- **Events 3.6.1 (fix):** uploading a logo or favicon failed with "uploaded, but the site can't
|
||||
|
||||
@@ -1,5 +1,31 @@
|
||||
# Changelog — Accounts
|
||||
|
||||
## [1.7.0] - 2026-11-24
|
||||
|
||||
Needs contracts 1.17.0. The first part of the Church Website 1.0.0 (WEBSITE-1.0-PLAN §11).
|
||||
|
||||
### Added
|
||||
|
||||
- **Brand style** in the church profile (`branding.style`: font pairing and corners, contracts
|
||||
1.17.0). Admin → Church profile → **Brand style** shows each of the 8 pairings in its own fonts,
|
||||
and the three corner styles. Served in `GET /api/church/v1` and `/api/v2/branding`.
|
||||
- **The church's fonts and corners on Accounts' pages**: `@crosscode/ui/fonts.css` (self-hosted, no
|
||||
font requests to anyone else) and `brandAttributes` on `<html>`. Without a pairing the pages
|
||||
keep the device fonts, so nothing changes until an admin picks one.
|
||||
- **The shared footer** (`ChurchFooter` from `@crosscode/ui`) on the public pages (sign in, forgot
|
||||
and reset password, signed out, confirm email): service times, address, contact, social links,
|
||||
links to the church's other sites and the privacy notice, from the church profile.
|
||||
- **`church.update`** (contracts 1.17.0): the church's Website changes shared profile facts for its
|
||||
admins (WEBSITE-1.0-PLAN decision 10). Only from a product linked as `website`
|
||||
(`WRONG_PRODUCT`), only for an `actor` who signs in through it (`NOT_ALLOWED`), and refused
|
||||
with `PROFILE_CHANGED` (409) when `ifUpdatedAt` is out of date. Live at once; linked products get
|
||||
`church.changed`; audited as `church_profile_changed_by_product` with the fields changed.
|
||||
|
||||
### Changed
|
||||
|
||||
- Saving the profile merges `branding` field by field (`mergeProfile`), so a form or product that
|
||||
sends only part of it (the colours without the style, or only the style) never drops the rest.
|
||||
|
||||
## [1.6.0] - 2026-11-20
|
||||
|
||||
### Added
|
||||
|
||||
@@ -3,6 +3,17 @@
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
|
||||
## 1.7.0
|
||||
|
||||
- **Choose your church's fonts and corners.** Admin → Church profile → **Brand style** has 8 font
|
||||
pairings, each shown in its own fonts, and sharp, soft or round corners. Your sign-in pages use
|
||||
them now, and your new Church Website and Cross Events' public pages will too, so all your sites
|
||||
look like one church. Until you pick, nothing changes.
|
||||
- **A footer with your church's details** under the sign-in pages: service times, address, contact
|
||||
details and links to your church's other sites, from the church profile.
|
||||
- Getting ready for the **Church Website**: its admins will be able to change your service times,
|
||||
logo and contact details from the website, and they'll change everywhere at once.
|
||||
|
||||
## 1.6.0
|
||||
|
||||
- **You're told about each sign-in.** After someone signs in, they get an email saying when, roughly
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.0",
|
||||
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -69,10 +69,37 @@ export class ProfileError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves an admin's changes (merged onto what's there), and tells the linked products. */
|
||||
export async function updateProfile(ctx: Ctx, input: unknown): Promise<Church> {
|
||||
/** The profile changed since the editor loaded it (`church.update` with `ifUpdatedAt`). */
|
||||
export class ProfileChangedError extends Error {
|
||||
constructor(public updatedAt: string) {
|
||||
super('The church profile was changed by someone else since you opened it.');
|
||||
}
|
||||
}
|
||||
|
||||
const isObject = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
|
||||
|
||||
/**
|
||||
* The fields given replace what's there; `branding` is merged field by field (1.7.0), so a form
|
||||
* that doesn't know `branding.style` (or sends only the style) never drops the rest.
|
||||
*/
|
||||
export function mergeProfile(base: Record<string, unknown>, input: unknown): Record<string, unknown> {
|
||||
if (!isObject(input)) return { ...base };
|
||||
const next: Record<string, unknown> = { ...base, ...input };
|
||||
if (isObject(input.branding)) next.branding = { ...(isObject(base.branding) ? base.branding : {}), ...input.branding };
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves changes (merged onto what's there) from an admin here or a product (`church.update`),
|
||||
* and tells the linked products. With `ifUpdatedAt`, refuses if someone saved since.
|
||||
*/
|
||||
export async function updateProfile(ctx: Ctx, input: unknown, opts: { ifUpdatedAt?: string } = {}): Promise<Church> {
|
||||
const current = await storedProfile(ctx);
|
||||
const next = { ...DEFAULTS(ctx), ...current, ...(input && typeof input === 'object' ? input : {}) };
|
||||
if (opts.ifUpdatedAt) {
|
||||
const now = current.updatedAt ?? new Date(0).toISOString();
|
||||
if (new Date(now).getTime() !== new Date(opts.ifUpdatedAt).getTime()) throw new ProfileChangedError(now);
|
||||
}
|
||||
const next = mergeProfile({ ...DEFAULTS(ctx), ...current }, input);
|
||||
const check = profileInputSchema.safeParse(next);
|
||||
if (!check.success) {
|
||||
const fields = Object.fromEntries(check.error.issues.map((i) => [i.path.join('.'), i.message]));
|
||||
@@ -92,6 +119,7 @@ export async function branding(ctx: Ctx) {
|
||||
shortName: c.shortName,
|
||||
logoUrl: c.branding.logoUrl,
|
||||
colours: c.branding.colours,
|
||||
style: { fontPairing: c.branding.style?.fontPairing ?? null, corners: c.branding.style?.corners ?? null },
|
||||
signupEnabled: await ctx.settings.bool('signup_enabled', true),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@ import { emailProblem, normaliseEmail, profileChanged, profileOf, setNewsConsent
|
||||
import { turnOff } from '../accounts/twoFactor.js';
|
||||
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||
import { anonymise } from '../privacy/deletion.js';
|
||||
import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js';
|
||||
|
||||
/** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */
|
||||
const PROFILE_EDITORS = new Set(['website']);
|
||||
|
||||
/** A demo person's address (contracts DEMO_EMAIL_DOMAIN, reserved: no real person has one). */
|
||||
export const isDemoEmail = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
|
||||
@@ -319,6 +323,22 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
|
||||
return reply({ people });
|
||||
}
|
||||
case 'church.update': {
|
||||
// The product checked the person's role (Accounts doesn't know the Website's); Accounts
|
||||
// checks it's the Website, that the person signs in through it, and audits it as theirs.
|
||||
if (!PROFILE_EDITORS.has(link.product)) throw new RequestError("Only the church's Website changes the church profile from outside Accounts.", 'WRONG_PRODUCT', 403);
|
||||
const known = await ctx.db.productPerson.findFirst({ where: { linkId: link.installId, accountId: r.actor } });
|
||||
if (!known) throw new RequestError("The person making the change isn't someone who signs in to this product.", 'NOT_ALLOWED', 403);
|
||||
try {
|
||||
const church = await updateProfile(ctx, r.church, { ifUpdatedAt: r.ifUpdatedAt });
|
||||
await logRequest(ctx, link, r, 'church_profile_changed_by_product', null, req, { fields: Object.keys(r.church) });
|
||||
return reply({ church });
|
||||
} catch (e) {
|
||||
if (e instanceof ProfileChangedError) throw new RequestError(e.message, 'PROFILE_CHANGED', 409);
|
||||
if (e instanceof ProfileError) throw new RequestError(`${e.message} ${Object.entries(e.fields).map(([k, v]) => `${k}: ${v}`).join('; ')}`.trim(), 'INVALID_REQUEST', 400);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
case 'church.branding': {
|
||||
const changed = await applyLook(ctx, r.church, r.overwrite);
|
||||
await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite });
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// church.update (contracts 1.17.0, Accounts 1.7.0, WEBSITE-1.0-PLAN decision 10): the Website's
|
||||
// admin changes shared profile facts through Accounts, and the brand style is kept by every save.
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { startHarness, type Harness } from './support/harness.js';
|
||||
import { church, mergeProfile, updateProfile } from '../src/church/profile.js';
|
||||
|
||||
const WEBSITE_ID = '7e2a1c3d-9b4f-4d6e-8f70-2b3c4d5e6f70';
|
||||
const EVENTS_ID = '8f3b2d4e-0c5a-4e7f-9a81-3c4d5e6f7a81';
|
||||
let h: Harness;
|
||||
const secrets: Record<string, string> = {};
|
||||
let editor: string;
|
||||
|
||||
before(async () => {
|
||||
h = await startHarness();
|
||||
for (const [id, product] of [[WEBSITE_ID, 'website'], [EVENTS_ID, 'events']] as const) {
|
||||
secrets[id] = newLinkSecret();
|
||||
await h.db.productLink.create({
|
||||
data: { installId: id, product, url: `https://${product}.hope.test`, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secrets[id]!), connectedAt: new Date() },
|
||||
});
|
||||
}
|
||||
const a = await h.makeAccount({ email: 'editor@hope.test' });
|
||||
editor = a.id as string;
|
||||
for (const linkId of [WEBSITE_ID, EVENTS_ID]) await h.db.productPerson.create({ data: { linkId, accountId: editor, via: 'sign_in', createdAt: new Date() } });
|
||||
await updateProfile(h.ctx, { name: 'Hope Family Church', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#1f4e79', accent: '#f2a900' } } });
|
||||
});
|
||||
after(async () => { await h.close(); });
|
||||
|
||||
async function ask(body: Record<string, unknown>, from = WEBSITE_ID) {
|
||||
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: editor, type: 'church.update', ...body });
|
||||
const headers = signedHeaders(LINK_HEADERS, { senderId: from, secret: secrets[from]!, rawBody: raw });
|
||||
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...headers } });
|
||||
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
describe('church.update from the Website', () => {
|
||||
test('changes only the style, keeps the colours and logo, and goes live at once', async () => {
|
||||
const res = await ask({ church: { branding: { style: { fontPairing: 'warm', corners: 'round' } } } });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
const c = await church(h.ctx);
|
||||
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'round' });
|
||||
assert.equal(c.branding.colours.primary, '#1f4e79');
|
||||
assert.equal(c.name, 'Hope Family Church');
|
||||
assert.deepEqual((res.body.church as { branding: unknown }).branding, c.branding);
|
||||
});
|
||||
|
||||
test('tells every linked product the profile changed, and audits it as the editor', async () => {
|
||||
const before = await h.db.delivery.count();
|
||||
const res = await ask({ church: { shortName: 'Hope Family' } });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
assert.ok((await h.db.delivery.count()) > before);
|
||||
const log = await h.db.auditLog.findFirst({ where: { action: 'church_profile_changed_by_product' }, orderBy: { createdAt: 'desc' } });
|
||||
assert.equal(log?.actorId, editor);
|
||||
});
|
||||
|
||||
test('refuses another product, someone who doesn\'t sign in through the Website, and a stale edit', async () => {
|
||||
const events = await ask({ church: { name: 'Hijacked' } }, EVENTS_ID);
|
||||
assert.equal(events.status, 403);
|
||||
assert.equal(events.body.code, 'WRONG_PRODUCT');
|
||||
|
||||
const stranger = await h.makeAccount({ email: 'stranger@hope.test' });
|
||||
const notKnown = await ask({ actor: stranger.id as string, church: { name: 'Hijacked' } });
|
||||
assert.equal(notKnown.status, 403);
|
||||
assert.equal(notKnown.body.code, 'NOT_ALLOWED');
|
||||
|
||||
const stale = await ask({ ifUpdatedAt: '2020-01-01T00:00:00.000Z', church: { name: 'Hijacked' } });
|
||||
assert.equal(stale.status, 409);
|
||||
assert.equal(stale.body.code, 'PROFILE_CHANGED');
|
||||
assert.equal((await church(h.ctx)).name, 'Hope Family Church');
|
||||
});
|
||||
|
||||
test('takes an edit made on the current version', async () => {
|
||||
const current = await church(h.ctx);
|
||||
const res = await ask({ ifUpdatedAt: current.updatedAt, church: { serviceTimes: [{ day: 'sunday', time: '09:00', label: null, campus: null, note: null }] } });
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
assert.equal((await church(h.ctx)).serviceTimes.length, 1);
|
||||
});
|
||||
|
||||
test('an invalid value is refused with what\'s wrong', async () => {
|
||||
const res = await ask({ church: { contact: { email: null, phone: '016 123', whatsapp: null, address: null } } });
|
||||
assert.equal(res.status, 400);
|
||||
assert.equal(res.body.code, 'INVALID_REQUEST');
|
||||
});
|
||||
});
|
||||
|
||||
describe('saving the profile keeps the brand style', () => {
|
||||
test('an admin form that sends branding without the style doesn\'t drop it', async () => {
|
||||
await updateProfile(h.ctx, { branding: { style: { fontPairing: 'classic', corners: 'sharp' } } });
|
||||
await updateProfile(h.ctx, { branding: { logoUrl: null, iconUrl: null, colours: { primary: '#204060', accent: null } } });
|
||||
const c = await church(h.ctx);
|
||||
assert.deepEqual(c.branding.style, { fontPairing: 'classic', corners: 'sharp' });
|
||||
assert.equal(c.branding.colours.primary, '#204060');
|
||||
});
|
||||
|
||||
test('mergeProfile replaces other fields whole and merges branding', () => {
|
||||
const merged = mergeProfile({ name: 'A', social: [1], branding: { logoUrl: 'x', colours: { primary: '#000000' } } }, { social: [], branding: { colours: { primary: '#ffffff' } } });
|
||||
assert.deepEqual(merged, { name: 'A', social: [], branding: { logoUrl: 'x', colours: { primary: '#ffffff' } } });
|
||||
});
|
||||
|
||||
test('the sign-in pages get the style', async () => {
|
||||
const res = await fetch(`${h.publicUrl}/api/v2/branding`);
|
||||
const b = (await res.json()) as { style: unknown };
|
||||
assert.deepEqual(b.style, { fontPairing: 'classic', corners: 'sharp' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import AxeBuilder from "@axe-core/playwright";
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
// 1.7.0 (WEBSITE-1.0-PLAN §3, §9): the church's brand style and shared footer on Accounts' public
|
||||
// pages. The e2e church (e2e/server.ts) has the "warm" pairing, round corners and service times.
|
||||
const PRODUCT = "http://localhost:5211";
|
||||
|
||||
test("the sign-in page uses the church's fonts and corners, and shows its footer", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?returnTo=/`);
|
||||
await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible();
|
||||
await expect(page.locator("html")).toHaveAttribute("data-cc-fonts", "warm");
|
||||
await expect(page.locator("html")).toHaveAttribute("data-cc-corners", "round");
|
||||
|
||||
const heading = page.getByRole("heading", { name: "Sign in to Hope Family Church" });
|
||||
expect(await heading.evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Fraunces");
|
||||
expect(await page.locator("body").evaluate((el) => getComputedStyle(el).fontFamily)).toContain("CC Nunito Sans");
|
||||
// The font files themselves load from this site (self-hosted), not from anyone else.
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
expect(await page.evaluate(() => document.fonts.check('600 20px "CC Fraunces"'))).toBe(true);
|
||||
expect(await page.getByRole("button", { name: "Sign in" }).evaluate((el) => getComputedStyle(el).borderRadius)).toBe("9999px");
|
||||
|
||||
const footer = page.locator("footer");
|
||||
await expect(footer.getByRole("heading", { name: "Service times" })).toBeVisible();
|
||||
await expect(footer).toContainText("Sundays 09:00");
|
||||
await expect(footer.getByRole("link", { name: "office@hope.test" })).toHaveAttribute("href", "mailto:office@hope.test");
|
||||
await expect(footer.getByRole("link", { name: "Website" })).toHaveAttribute("href", PRODUCT);
|
||||
await expect(footer.getByRole("link", { name: "Privacy notice" })).toHaveAttribute("href", "/privacy");
|
||||
});
|
||||
|
||||
test("fonts never come from another site", async ({ page }) => {
|
||||
const foreign: string[] = [];
|
||||
page.on("request", (r) => { if (/\.(woff2?|ttf|otf)(\?|$)/.test(r.url()) && !r.url().startsWith("http://localhost:3210/")) foreign.push(r.url()); });
|
||||
await page.goto(`${PRODUCT}/start?returnTo=/`);
|
||||
await page.evaluate(() => document.fonts.ready);
|
||||
expect(foreign).toEqual([]);
|
||||
});
|
||||
|
||||
test("the sign-in page with the footer passes axe (WCAG 2.2 AA)", async ({ page }) => {
|
||||
await page.goto(`${PRODUCT}/start?returnTo=/`);
|
||||
await expect(page.locator("footer")).toBeVisible();
|
||||
const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"]).analyze();
|
||||
expect(results.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]);
|
||||
});
|
||||
@@ -29,7 +29,13 @@ const messenger = new MemoryMessenger();
|
||||
const ctx = createCtx(loadConfig({ ACCOUNTS_URL: WEB, NODE_ENV: 'test', JOBS_ENABLED: 'false', LINKS_ALLOW_PRIVATE: 'true', HUB_URL: 'http://127.0.0.1:1', TRUST_PROXY: 'true' }), db as never, { messenger });
|
||||
await ctx.settings.setMany({
|
||||
hub_install_id: '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c',
|
||||
church_profile: JSON.stringify({ name: 'Hope Family Church', shortName: 'Hope', branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' } } }),
|
||||
// 1.7.0: a brand style, service times and contact details, so the pages show the church's fonts and footer.
|
||||
church_profile: JSON.stringify({
|
||||
name: 'Hope Family Church', shortName: 'Hope',
|
||||
branding: { logoUrl: null, iconUrl: null, colours: { primary: '#7c2d12', accent: '#f2a900' }, style: { fontPairing: 'warm', corners: 'round' } },
|
||||
serviceTimes: [{ day: 'sunday', time: '09:00', label: 'Morning service', campus: null, note: null }],
|
||||
contact: { email: 'office@hope.test', phone: '+27161234567', whatsapp: null, address: null },
|
||||
}),
|
||||
});
|
||||
const linkSecret = newLinkSecret();
|
||||
await db.productLink.create({ data: { installId: PRODUCT_ID, product: 'website', url: PRODUCT, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(linkSecret), connectedAt: new Date() } });
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.6.0",
|
||||
"version": "1.7.0",
|
||||
"private": true,
|
||||
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { Card, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { Card, Heading, Notice } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call, selfSignIn } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
@@ -20,12 +21,12 @@ export function ConfirmEmail({ token }: { token: string }) {
|
||||
return () => { alive = false; };
|
||||
}, [token]);
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<PublicShell>
|
||||
<Card>
|
||||
<Heading>Your email address</Heading>
|
||||
{state ? <Notice tone={state.ok ? "success" : "error"}>{state.text}</Notice> : <p className="text-gray-600">Confirming…</p>}
|
||||
<Link href="/account" className="text-brand underline">Back to your account</Link>
|
||||
</Card>
|
||||
</Shell>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Card, Heading } from "@/components/Panel";
|
||||
import { call, selfSignIn } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
import { ADMIN_SECTIONS, type AdminSection } from "@/lib/sections";
|
||||
import { BrandStyle } from "./BrandStyle";
|
||||
|
||||
|
||||
const when = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
|
||||
@@ -55,7 +56,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
|
||||
{section === "people" && <People flash={flash} />}
|
||||
<div className="max-w-3xl">
|
||||
{section === "deletions" && <Deletions flash={flash} />}
|
||||
{section === "church" && <Church flash={flash} />}
|
||||
{section === "church" && <><Church flash={flash} /><BrandStyle flash={flash} /></>}
|
||||
{section === "linked" && <Linked flash={flash} />}
|
||||
{section === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "signin_notices", "session_days"]} />}
|
||||
{section === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { CORNERS, FONT_PAIRING_IDS, FONT_PAIRINGS, type Corners, type FontPairing } from "@crosscode/contracts";
|
||||
import { Button } from "@crosscode/ui";
|
||||
import { Card, Heading } from "@/components/Panel";
|
||||
import { call } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
type Style = { fontPairing: FontPairing | null; corners: Corners | null };
|
||||
type ChurchStyle = { branding: { style?: Style } };
|
||||
|
||||
const CORNER_LABELS: Record<Corners, { name: string; radius: string }> = {
|
||||
sharp: { name: "Sharp", radius: "0" },
|
||||
soft: { name: "Soft", radius: "0.5rem" },
|
||||
round: { name: "Round", radius: "9999px" },
|
||||
};
|
||||
|
||||
/**
|
||||
* The church's brand style (1.7.0, WEBSITE-1.0-PLAN §3): a font pairing and corners, shared by
|
||||
* Accounts' pages, the Website and Cross Events. Each option is shown in its own fonts (fonts.css
|
||||
* is loaded on every page; a pairing's files download only when shown).
|
||||
*/
|
||||
export function BrandStyle({ flash }: { flash: (tone: "success" | "error", text: string) => void }) {
|
||||
const router = useRouter();
|
||||
const [saved, setSaved] = useState<Style | null>(null);
|
||||
const [style, setStyle] = useState<Style>({ fontPairing: null, corners: null });
|
||||
const [busy, setBusy] = useState(false);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call<ChurchStyle>("GET", "/admin/church").then((r) => {
|
||||
if (!alive || !r.ok) return;
|
||||
const s = { fontPairing: r.data.branding.style?.fontPairing ?? null, corners: r.data.branding.style?.corners ?? null };
|
||||
setSaved(s);
|
||||
setStyle(s);
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
if (!saved) return null;
|
||||
const changed = saved.fontPairing !== style.fontPairing || saved.corners !== style.corners;
|
||||
|
||||
const option = (selected: boolean) => `block cursor-pointer rounded-xl border p-4 transition focus-within:ring-2 focus-within:ring-brand/50 ${selected ? "border-brand bg-brand/5 ring-1 ring-brand" : "border-gray-200 hover:border-gray-300"}`;
|
||||
|
||||
return (
|
||||
<Card className="mt-6">
|
||||
<Heading sub="How the church's sites look: these sign-in pages, the website and Cross Events' public pages. Colours and logo are above.">Brand style</Heading>
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
const r = await call<ChurchStyle>("PUT", "/admin/church", { branding: { style } });
|
||||
setBusy(false);
|
||||
if (r.ok) {
|
||||
setSaved(style);
|
||||
flash("success", "Saved. The church's sites use the new style.");
|
||||
router.refresh();
|
||||
} else flash("error", r.error.message);
|
||||
}}>
|
||||
<fieldset className="mb-6">
|
||||
<legend className="mb-1 text-sm font-semibold text-gray-900">Fonts</legend>
|
||||
<p className="mb-3 text-sm text-gray-600">A font for headings and one for text. The website's template recommends three, but any works.</p>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<label className={option(style.fontPairing === null)}>
|
||||
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === null} onChange={() => setStyle({ ...style, fontPairing: null })} />
|
||||
<span className="block text-lg font-semibold [font-family:ui-sans-serif,system-ui,sans-serif]">Device fonts</span>
|
||||
<span className="mt-1 block text-sm text-gray-600 [font-family:ui-sans-serif,system-ui,sans-serif]">Each phone and computer's own. The website uses its template's fonts.</span>
|
||||
</label>
|
||||
{FONT_PAIRING_IDS.map((id) => {
|
||||
const p = FONT_PAIRINGS[id];
|
||||
return (
|
||||
<label key={id} className={option(style.fontPairing === id)} data-cc-fonts={id}>
|
||||
<input type="radio" name="fontPairing" className="sr-only" checked={style.fontPairing === id} onChange={() => setStyle({ ...style, fontPairing: id })} />
|
||||
<span className="block text-lg font-semibold [font-family:var(--cc-font-heading)] [font-variation-settings:var(--cc-heading-variation,normal)]">{p.name}: Welcome home</span>
|
||||
<span className="mt-1 block text-sm text-gray-700 [font-family:var(--cc-font-body)]">{p.feel}. <em>Sundays at 09:00.</em></span>
|
||||
<span className="mt-2 block text-xs text-gray-500 [font-family:ui-sans-serif,system-ui,sans-serif]">{p.heading.family}{p.body.family !== p.heading.family && ` and ${p.body.family}`}</span>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset className="mb-6">
|
||||
<legend className="mb-1 text-sm font-semibold text-gray-900">Corners</legend>
|
||||
<p className="mb-3 text-sm text-gray-600">Of buttons, cards, photos and fields.</p>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{CORNERS.map((id) => (
|
||||
<label key={id} className={option((style.corners ?? "soft") === id)}>
|
||||
<input type="radio" name="corners" className="sr-only" checked={(style.corners ?? "soft") === id} onChange={() => setStyle({ ...style, corners: id })} />
|
||||
<span className="mb-2 block h-8 w-full bg-brand" style={{ borderRadius: CORNER_LABELS[id].radius }} aria-hidden />
|
||||
<span className="block text-sm font-medium">{CORNER_LABELS[id].name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
<Button type="submit" busy={busy} disabled={!changed}>Save</Button>
|
||||
</form>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { KeyRound } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call } from "@/lib/api";
|
||||
|
||||
@@ -12,7 +13,7 @@ export function Forgot({ uid }: { uid: string | null }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<PublicShell>
|
||||
<Card>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
|
||||
{sent ? (
|
||||
@@ -32,6 +33,6 @@ export function Forgot({ uid }: { uid: string | null }) {
|
||||
)}
|
||||
{uid && <p className="mt-4 text-sm"><a href={`/signin?uid=${encodeURIComponent(uid)}`} className="text-brand underline">Back to sign in</a></p>}
|
||||
</Card>
|
||||
</Shell>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,4 +10,11 @@
|
||||
|
||||
body {
|
||||
@apply bg-gray-50 text-gray-900 antialiased;
|
||||
/* 1.7.0: the church's font pairing when it has one (@crosscode/ui fonts.css), else the system font. */
|
||||
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");
|
||||
}
|
||||
|
||||
h1, h2, h3 {
|
||||
font-family: var(--cc-font-heading, inherit);
|
||||
font-variation-settings: var(--cc-heading-variation, normal);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import "@crosscode/ui/fonts.css";
|
||||
import "./globals.css";
|
||||
import { brandAttributes } from "@crosscode/ui";
|
||||
import { BrandingProvider } from "@/components/BrandingProvider";
|
||||
import { loadBranding, rgbVars } from "@/lib/branding";
|
||||
import { loadBranding, loadChurch, rgbVars } from "@/lib/branding";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const b = await loadBranding();
|
||||
@@ -12,15 +14,16 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const nonce = (await headers()).get("x-nonce") ?? undefined;
|
||||
const b = await loadBranding();
|
||||
const [b, church] = await Promise.all([loadBranding(), loadChurch()]);
|
||||
const vars = rgbVars(b.colours.primary);
|
||||
// 1.7.0: the church's font pairing and corners (fonts.css), shared with its other sites.
|
||||
return (
|
||||
<html lang="en-ZA">
|
||||
<html lang="en-ZA" {...brandAttributes(b.style)}>
|
||||
<head>
|
||||
<style nonce={nonce}>{`:root{--brand:${vars.brand};--brand-dark:${vars.dark}}`}</style>
|
||||
</head>
|
||||
<body>
|
||||
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded }}>
|
||||
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded, church }}>
|
||||
{children}
|
||||
</BrandingProvider>
|
||||
</body>
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { KeyRound } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { Button, Card, Field, Heading, Notice } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call, selfSignIn } from "@/lib/api";
|
||||
|
||||
@@ -11,7 +12,7 @@ export function Reset({ token }: { token: string | null }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<PublicShell>
|
||||
<Card>
|
||||
<Heading icon={<KeyRound className="h-5 w-5" />} sub="At least 8 characters.">Choose a new password</Heading>
|
||||
{error && <Notice tone="error">{error}</Notice>}
|
||||
@@ -29,6 +30,6 @@ export function Reset({ token }: { token: string | null }) {
|
||||
<Button type="submit" busy={busy} className="w-full">Save and sign in</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Shell>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
"use client";
|
||||
|
||||
import { LogOut } from "lucide-react";
|
||||
import { Card, Heading, Shell } from "@crosscode/ui";
|
||||
import { Card, Heading } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { selfSignIn } from "@/lib/api";
|
||||
|
||||
export default function SignedOutPage() {
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<PublicShell>
|
||||
<Card>
|
||||
<Heading icon={<LogOut className="h-5 w-5" />} sub={`You've been signed out of all of ${branding.name}'s sites.`}>You're signed out</Heading>
|
||||
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
|
||||
</Card>
|
||||
</Shell>
|
||||
</PublicShell>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
import { AlertTriangle, FileText, KeyRound, LogIn, Mail, Megaphone, ShieldCheck, UserPlus } from "lucide-react";
|
||||
import React, { useState } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { Button, Card, Checkbox, Field, Heading, Notice } from "@crosscode/ui";
|
||||
import { PublicShell } from "@/components/PublicShell";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { NoticeText } from "@/components/NoticeText";
|
||||
import { call, type ApiError } from "@/lib/api";
|
||||
@@ -82,7 +83,7 @@ export function SignIn({ uid }: { uid: string }) {
|
||||
return r;
|
||||
};
|
||||
|
||||
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
|
||||
const frame = (children: React.ReactNode) => <PublicShell><Card>{children}</Card></PublicShell>;
|
||||
|
||||
if (codes) {
|
||||
return frame(<RecoveryCodes codes={codes.codes} onDone={() => { const next = codes.next; setCodes(null); go(next); }} />);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext } from "react";
|
||||
import type { FooterChurch } from "@crosscode/ui";
|
||||
|
||||
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean };
|
||||
/** `church` (1.7.0): the profile for the shared footer, null when it couldn't be loaded. */
|
||||
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean; church?: FooterChurch | null };
|
||||
|
||||
const Ctx = createContext<ClientBranding>({ name: "Sign in", shortName: null, logoUrl: null, signupEnabled: true, setupNeeded: false });
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { ChurchFooter, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
|
||||
/**
|
||||
* The frame of the public pages (sign in, forgot, reset, signed out, confirm email) with the
|
||||
* church's shared footer (1.7.0, WEBSITE-1.0-PLAN §9): its service times, contact and links to its
|
||||
* other sites, as on the Website and Cross Events.
|
||||
*/
|
||||
export function PublicShell({ children }: { children: React.ReactNode }) {
|
||||
const branding = useBranding();
|
||||
const footer = branding.church ? <ChurchFooter church={branding.church} current="accounts" privacyUrl="/privacy" /> : undefined;
|
||||
return <Shell branding={branding} footer={footer}>{children}</Shell>;
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
import type { FooterChurch } from "@crosscode/ui";
|
||||
|
||||
/** The church's branding from the backend, for the server-rendered frame of every page. */
|
||||
export type BrandingData = {
|
||||
name: string;
|
||||
shortName: string | null;
|
||||
logoUrl: string | null;
|
||||
colours: { primary: string; accent: string | null };
|
||||
/** 1.7.0: the font pairing and corners (null: not picked). */
|
||||
style?: { fontPairing: string | null; corners: string | null };
|
||||
signupEnabled: boolean;
|
||||
setupNeeded: boolean;
|
||||
};
|
||||
@@ -20,6 +24,17 @@ export async function loadBranding(): Promise<BrandingData> {
|
||||
return { name: "Sign in", shortName: null, logoUrl: null, colours: { primary: "#1f4e79", accent: null }, signupEnabled: true, setupNeeded: false };
|
||||
}
|
||||
|
||||
/** The church profile (`crosscode.church/1`) for the shared footer (1.7.0), or null while it can't be had. */
|
||||
export async function loadChurch(): Promise<FooterChurch | null> {
|
||||
try {
|
||||
const res = await fetch(`${api}/api/church/v1`, { next: { revalidate: 60 } });
|
||||
if (res.ok) return (await res.json()) as FooterChurch;
|
||||
} catch {
|
||||
// As loadBranding: the page works without it.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** "#1f4e79" → "31 78 121" (Tailwind's rgb(var(--brand) / alpha)), and a darker shade for hover. */
|
||||
export function rgbVars(hex: string): { brand: string; dark: string } {
|
||||
const m = /^#([0-9a-f]{6})$/i.exec(hex) ?? ["", "1f4e79"];
|
||||
|
||||
@@ -13,8 +13,9 @@ curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/ma
|
||||
| sudo bash -s -- --hub https://hub.crosscode.co.za --token <token>
|
||||
```
|
||||
|
||||
Add `--central` on the central (FastPanel) server: there the agent is read-only and only runs
|
||||
`check-ports` and `status`. The script installs Node 24 if needed, the agent in
|
||||
Add `--central` on the central (FastPanel) server: there the agent only runs `check-ports`,
|
||||
`probe-ports`, `status`, `update-agent`, and `frp-read` / `frp-write` (frps's config, from the
|
||||
server's page on the Hub; agent 1.4.0+). The script installs Node 24 if needed, the agent in
|
||||
`/opt/crosscode/agent/releases/<version>` (with `current` pointing at it), the `crosscode` script in
|
||||
`/opt/crosscode/tools` (church servers), makes the server's two key pairs, joins, and starts
|
||||
`crosscode-agent.service`.
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# What's new in the server agent
|
||||
|
||||
What each version of the Cross Code server agent changes, for whoever runs the Hub. The Hub shows
|
||||
these notes on its Releases page and when you pick a version under Update agent.
|
||||
|
||||
<!--
|
||||
How this file is used: the Cross Code Hub reads it from main every 15 minutes (release source
|
||||
"Server agent", tags agent@1.2.3) and shows a section only once its version is tagged, so write it
|
||||
before tagging; fixes to old sections show straight away. Each version is a "## 1.2.3" heading; add
|
||||
"— urgent" (or "security") to the heading for a security or serious bug fix. Under it, lines
|
||||
starting with "- " show as a list and other lines as paragraphs.
|
||||
Write for the person updating servers: what the agent can now do from the Hub, and which Hub or
|
||||
contracts version needs it. The developer log is the commit history of apps/agent.
|
||||
-->
|
||||
|
||||
## 1.5.0
|
||||
|
||||
- **One product of a church at a time.** Uninstall, export and purge jobs can name products: only
|
||||
those go, and the church keeps the others. Naming every product it still has removes the whole
|
||||
church, so the last product to go takes the church with it. Before, uninstalling a church's Cross
|
||||
Events also removed its Accounts.
|
||||
- The Hub (2.12.0 and later) uninstalls one product only on servers with this agent; older agents
|
||||
can only remove the whole church.
|
||||
|
||||
## 1.4.0
|
||||
|
||||
- **frp's config from the Hub.** The agent finds frps's config (central server) or frpc's (church
|
||||
server) wherever it is: the path set on the Hub, the `-c` in the systemd unit, or the usual places.
|
||||
It reads INI and TOML.
|
||||
- **Changing it from the Hub:** the agent checks the new file with `frp* verify`, keeps a backup,
|
||||
restarts frp if asked, and puts the old file back if frp doesn't start. Secret values never leave
|
||||
the server.
|
||||
- **Ports checked before an install:** the Hub asks this server and the central server which ports
|
||||
are free, so a new install gets ports free on both.
|
||||
- Needed for frp config on a server's page and port checks (Hub 2.11.0).
|
||||
|
||||
## 1.3.1
|
||||
|
||||
- **Fix:** 1.3.0 reported itself as 1.2.0, so the Hub refused its .env jobs. It now reports its
|
||||
real version. Install this instead of 1.3.0.
|
||||
|
||||
## 1.3.0
|
||||
|
||||
- **A site's .env from the Hub.** The agent reads an install's .env (secret values hidden) and
|
||||
changes it: one file at a time, rebuilding the site when its frontend settings changed,
|
||||
restarting it, and putting the old file back if the site doesn't answer.
|
||||
- Needed for the Settings (.env) tab on an install's page (Hub 2.8.0).
|
||||
|
||||
## 1.2.0
|
||||
|
||||
- **Demo data from the Hub.** The agent loads a demo profile onto a site marked as a demo: a backup
|
||||
first, then the demo data, keeping one admin account.
|
||||
- Needed for demo sites (Hub 2.4.0).
|
||||
|
||||
## 1.1.1
|
||||
|
||||
- **Fix:** the server's stats now keep going while a long job runs. Before, a 30-minute install
|
||||
stopped them and the Hub alerted that the server was down.
|
||||
- **Fix:** 1.1.0 reported itself as 1.0.1; it now reports its real version.
|
||||
|
||||
## 1.1.0
|
||||
|
||||
- **Accounts installs.** The agent installs Accounts, and adds a product next to a church's others
|
||||
on the same server (with the ports and release the Hub chose).
|
||||
|
||||
## 1.0.1
|
||||
|
||||
- **Fix:** on the central server, Check status failed (it has no `crosscode` script). It now answers
|
||||
with its own stats, including whether frps is running.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
- **The first server agent.** It polls the Hub every 30 seconds for signed jobs, runs the
|
||||
`crosscode` script for them (install, update, status, export, uninstall), sends the results, and
|
||||
sends the server's stats every minute. It listens on no port: every request goes out to the Hub.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/agent",
|
||||
"version": "1.3.1",
|
||||
"version": "1.5.0",
|
||||
"private": true,
|
||||
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
|
||||
"license": "UNLICENSED",
|
||||
|
||||
+17
-48
@@ -1,51 +1,15 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import { paths } from "./paths";
|
||||
import type { FrpSettings } from "./frp";
|
||||
import { portAllowed } from "./frp";
|
||||
|
||||
export { parseFrpsIni, portAllowed } from "./frp";
|
||||
|
||||
/**
|
||||
* The central server (AGENT-1.0-PLAN §6): read-only checks of frps for `check-ports`. Nothing on
|
||||
* the central server is ever changed: no frps edits, no firewall, no FastPanel.
|
||||
* The central server (AGENT-1.0-PLAN §6): the `check-ports` job after an install. Are the new
|
||||
* tunnel's ports allowed by frps, open, and bound to 127.0.0.1 only? frps's config is found and
|
||||
* read by ./frp.ts (INI or TOML, wherever it is).
|
||||
*/
|
||||
|
||||
export interface FrpsSettings {
|
||||
proxyBindAddr: string | null;
|
||||
allowPorts: string | null;
|
||||
}
|
||||
|
||||
/** frps.ini's [common] proxy_bind_addr and allow_ports (null when not set or no file). */
|
||||
export function parseFrpsIni(text: string): FrpsSettings {
|
||||
let inCommon = false;
|
||||
const out: FrpsSettings = { proxyBindAddr: null, allowPorts: null };
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (/^\[.*\]$/.test(line)) { inCommon = line === "[common]"; continue; }
|
||||
if (!inCommon || line.startsWith("#") || line.startsWith(";")) continue;
|
||||
const m = /^([a-z_]+)\s*=\s*(.*)$/.exec(line);
|
||||
if (!m) continue;
|
||||
if (m[1] === "proxy_bind_addr") out.proxyBindAddr = m[2]!.trim() || null;
|
||||
if (m[1] === "allow_ports") out.allowPorts = m[2]!.trim() || null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function readFrps(file = paths.frpsIni): FrpsSettings | null {
|
||||
try {
|
||||
return parseFrpsIni(fs.readFileSync(file, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
|
||||
export function portAllowed(port: number, allowPorts: string | null): boolean {
|
||||
if (!allowPorts) return true;
|
||||
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
|
||||
const [a, b] = range.split("-").map((n) => Number(n.trim()));
|
||||
if (!Number.isFinite(a)) return false;
|
||||
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
|
||||
});
|
||||
}
|
||||
|
||||
/** Listening TCP sockets from `ss -ltnH`: port → local addresses. */
|
||||
export function parseSs(text: string): Map<number, string[]> {
|
||||
const out = new Map<number, string[]>();
|
||||
@@ -72,11 +36,16 @@ export interface PortCheck {
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export function checkPorts(ports: number[], frps: FrpsSettings | null, listening: Map<number, string[]>): { ports: PortCheck[]; proxyBindAddr: string | null; warnings: string[] } {
|
||||
export function checkPorts(
|
||||
ports: number[],
|
||||
frps: Pick<FrpSettings, "proxyBindAddr" | "allowPorts"> | null,
|
||||
listening: Map<number, string[]>,
|
||||
configPath: string | null = null,
|
||||
): { ports: PortCheck[]; proxyBindAddr: string | null; configPath: string | null; warnings: string[] } {
|
||||
const warnings: string[] = [];
|
||||
if (!frps) warnings.push(`No frps.ini at ${paths.frpsIni}.`);
|
||||
if (!frps) warnings.push(configPath ? `frps's config isn't at ${configPath} (Hub → the central server → frp config).` : "frps's config wasn't found (Hub → the central server → frp config: set where it is).");
|
||||
const bind = frps?.proxyBindAddr ?? null;
|
||||
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 in frps.ini.`);
|
||||
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 (frps.toml: proxyBindAddr = "127.0.0.1") in ${configPath ?? "frps's config"}.`);
|
||||
const results = ports.map((port) => {
|
||||
const addrs = listening.get(port) ?? [];
|
||||
const allowed = portAllowed(port, frps?.allowPorts ?? null);
|
||||
@@ -86,9 +55,9 @@ export function checkPorts(ports: number[], frps: FrpsSettings | null, listening
|
||||
for (const r of results) {
|
||||
if (!r.allowed) warnings.push(`Port ${r.port} isn't in allow_ports.`);
|
||||
else if (!r.listening) warnings.push(`Port ${r.port} isn't open in frps (is the church server's frpc connected?).`);
|
||||
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1.`);
|
||||
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1 (${(listening.get(r.port) ?? []).join(", ")}).`);
|
||||
}
|
||||
return { ports: results, proxyBindAddr: bind, warnings };
|
||||
return { ports: results, proxyBindAddr: bind, configPath, warnings };
|
||||
}
|
||||
|
||||
export function listeningNow(): Promise<Map<number, string[]>> {
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { agent } from "@crosscode/contracts";
|
||||
/**
|
||||
* The `crosscode` arguments for a job (AGENT-1.0-PLAN §4): built from the checked arguments only,
|
||||
* as an array passed straight to the process (never through a shell). Jobs the agent handles
|
||||
* itself (update-agent, check-ports) have none.
|
||||
* itself (update-agent, check-ports, frp-read, frp-write, probe-ports) have none.
|
||||
*
|
||||
* `--config <file>` is added by the runner when the job brings config; `--json` always.
|
||||
*/
|
||||
@@ -62,15 +62,19 @@ export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string }
|
||||
return ["demo", job.args.church, "--profile", job.args.profile, ...(job.args.adminEmail ? ["--admin-email", job.args.adminEmail] : [])];
|
||||
case "export":
|
||||
if (!opts.exportFile) throw new Error("export needs a file to write");
|
||||
return ["export", job.args.church, "--out", opts.exportFile];
|
||||
return ["export", job.args.church, ...(job.args.products ?? []), "--out", opts.exportFile];
|
||||
case "uninstall":
|
||||
return ["uninstall", job.args.church, "--confirm", job.args.church];
|
||||
// 1.5.0: only the products named go (the church keeps its others); none named: the church.
|
||||
return ["uninstall", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
|
||||
case "purge":
|
||||
return ["purge", job.args.church, "--confirm", job.args.church];
|
||||
return ["purge", job.args.church, ...(job.args.products ?? []), "--confirm", job.args.church];
|
||||
case "status":
|
||||
return ["status", ...(job.args.church ? [job.args.church] : []), "--no-fetch"];
|
||||
case "update-agent":
|
||||
case "check-ports":
|
||||
case "frp-read":
|
||||
case "frp-write":
|
||||
case "probe-ports":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,454 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* frp's config on this server (agent 1.4.0): frps's on the central server, frpc's on a church
|
||||
* server. The agent finds the file itself (the path set from the Hub, else the systemd unit's
|
||||
* `-c`, else a usual place), reads frp's two formats (INI and TOML), hides secret values before
|
||||
* anything leaves the server, and writes a new file from the Hub the careful way: secrets put
|
||||
* back, `verify`, a backup, a restart, and the old file back when the service doesn't come up.
|
||||
*/
|
||||
|
||||
export type FrpService = "frps" | "frpc";
|
||||
export type FrpSource = (typeof agent.FRP_CONFIG_SOURCES)[number];
|
||||
export const serviceFor = (mode: agent.AgentMode): FrpService => (mode === "central" ? "frps" : "frpc");
|
||||
|
||||
// ─── Where the file is ────────────────────────────────────────────────────────
|
||||
|
||||
/** frps.toml, frpc.ini, frps-main.toml … */
|
||||
const FRP_FILE = /^frp[A-Za-z0-9._-]*\.(ini|toml)$/;
|
||||
|
||||
const rememberedFile = () => path.join(paths.stateDir, "frp.json");
|
||||
|
||||
/** The path set from the Hub (an `frp-read` with a path), if any. */
|
||||
export function rememberedPath(): string | null {
|
||||
try {
|
||||
const p = JSON.parse(fs.readFileSync(rememberedFile(), "utf8")).path;
|
||||
return typeof p === "string" && path.isAbsolute(p) && FRP_FILE.test(path.basename(p)) ? p : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberPath(p: string): void {
|
||||
fs.mkdirSync(paths.stateDir, { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(rememberedFile(), `${JSON.stringify({ path: p, at: new Date().toISOString() })}\n`, { mode: 0o600 });
|
||||
}
|
||||
|
||||
/** `-c <file>`, `-c=<file>`, `--config <file>` or `--config=<file>` in a command line. */
|
||||
export function configFromCommand(argv: string): string | null {
|
||||
const parts = argv.trim().split(/\s+/);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const a = parts[i]!;
|
||||
const eq = /^(?:-c|--config)=(.+)$/.exec(a);
|
||||
if (eq) return eq[1]!;
|
||||
if ((a === "-c" || a === "--config") && parts[i + 1]) return parts[i + 1]!;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The config and the binary from `systemctl show <unit> -p ExecStart --value` ("{ path=… ; argv[]=… ; … }"). */
|
||||
export function parseExecStart(text: string): { config: string | null; bin: string | null } {
|
||||
const argv = /argv\[\]=([^;]*)/.exec(text)?.[1]?.trim() ?? text.trim();
|
||||
const bin = argv.split(/\s+/)[0] || null;
|
||||
return { config: configFromCommand(argv), bin: bin && bin.startsWith("/") ? bin : null };
|
||||
}
|
||||
|
||||
function execText(cmd: string, args: string[], timeout = 10_000): Promise<{ ok: boolean; out: string; err: string; missing: boolean }> {
|
||||
return new Promise((resolve) => {
|
||||
execFile(cmd, args, { timeout }, (err, stdout, stderr) => resolve({
|
||||
ok: !err, out: String(stdout ?? ""), err: String(stderr ?? "") || (err ? err.message : ""), missing: (err as NodeJS.ErrnoException | null)?.code === "ENOENT",
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function fromSystemd(service: FrpService): Promise<{ config: string | null; bin: string | null }> {
|
||||
const r = await execText("systemctl", ["show", service, "-p", "ExecStart", "--value"]);
|
||||
return r.ok ? parseExecStart(r.out) : { config: null, bin: null };
|
||||
}
|
||||
|
||||
/** Where frp is usually kept, in the order the agent looks. */
|
||||
export function usualPlaces(service: FrpService): string[] {
|
||||
const dirs = ["/etc/frp", `/etc/${service}`, "/usr/local/etc/frp", "/usr/local/frp", "/opt/frp", `/opt/${service}`, "/root/frp"];
|
||||
return dirs.flatMap((d) => [`${d}/${service}.toml`, `${d}/${service}.ini`]);
|
||||
}
|
||||
|
||||
export interface FoundConfig {
|
||||
path: string | null;
|
||||
source: FrpSource | null;
|
||||
/** frps / frpc as the systemd unit runs it (for `verify`), else the name on PATH. */
|
||||
bin: string;
|
||||
looked: string[];
|
||||
}
|
||||
|
||||
const exists = (f: string) => { try { return fs.statSync(f).isFile(); } catch { return false; } };
|
||||
|
||||
let cache: { at: number; mode: agent.AgentMode; found: FoundConfig } | null = null;
|
||||
|
||||
/** The config this server's frp uses. The Hub's path wins (even when the file isn't there: the Hub then says so). */
|
||||
export async function findConfig(mode: agent.AgentMode, opts: { fresh?: boolean } = {}): Promise<FoundConfig> {
|
||||
if (!opts.fresh && cache && cache.mode === mode && Date.now() - cache.at < 5 * 60_000) return cache.found;
|
||||
const service = serviceFor(mode);
|
||||
const unit = await fromSystemd(service);
|
||||
const bin = unit.bin ?? service;
|
||||
const looked: string[] = [];
|
||||
let found: FoundConfig | null = null;
|
||||
const hub = rememberedPath();
|
||||
// The old setting (agent 1.0–1.3) still works, for a server that set it in the unit.
|
||||
const env = mode === "central" ? process.env.CROSSCODE_FRPS_INI : process.env.CROSSCODE_FRPC_INI;
|
||||
if (hub) found = { path: hub, source: "hub", bin, looked };
|
||||
else if (env) found = { path: env, source: "hub", bin, looked };
|
||||
else {
|
||||
const candidates: Array<[string, FrpSource]> = [];
|
||||
if (unit.config) candidates.push([unit.config, "systemd"]);
|
||||
for (const p of usualPlaces(service)) candidates.push([p, "usual-place"]);
|
||||
for (const [p, source] of candidates) {
|
||||
looked.push(p);
|
||||
if (exists(p)) { found = { path: p, source, bin, looked: [] }; break; }
|
||||
}
|
||||
}
|
||||
const result = found ?? { path: null, source: null, bin, looked: looked.slice(0, 20) };
|
||||
cache = { at: Date.now(), mode, found: result };
|
||||
return result;
|
||||
}
|
||||
|
||||
export function forgetFound(): void {
|
||||
cache = null;
|
||||
}
|
||||
|
||||
// ─── Reading INI and TOML ─────────────────────────────────────────────────────
|
||||
|
||||
export type FrpFormat = "ini" | "toml";
|
||||
export const formatOf = (file: string, text = ""): FrpFormat => (file.endsWith(".toml") ? "toml" : file.endsWith(".ini") ? "ini" : /^\s*\[common\]/m.test(text) ? "ini" : "toml");
|
||||
|
||||
interface Line {
|
||||
/** `[common]`, `[[proxies]]`: the header the line is under ("" before any), with how many came before it. */
|
||||
section: string;
|
||||
sectionIndex: number;
|
||||
key: string;
|
||||
/** The value as written, after `=` (quotes kept, comments after it dropped for TOML). */
|
||||
raw: string;
|
||||
/** The value without quotes. */
|
||||
value: string;
|
||||
/** Where `raw` starts and ends in the line. */
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
function unquote(v: string): string {
|
||||
const t = v.trim();
|
||||
if ((t.startsWith('"') && t.endsWith('"') && t.length >= 2) || (t.startsWith("'") && t.endsWith("'") && t.length >= 2)) return t.slice(1, -1);
|
||||
return t;
|
||||
}
|
||||
|
||||
/** Each `key = value` line, with the section it's in. */
|
||||
export function lines(text: string, format: FrpFormat): Array<Line | null> {
|
||||
let section = "";
|
||||
const seen = new Map<string, number>();
|
||||
let sectionIndex = 0;
|
||||
return text.split("\n").map((rawLine) => {
|
||||
const line = rawLine.replace(/\r$/, "");
|
||||
const t = line.trim();
|
||||
if (!t || t.startsWith("#") || t.startsWith(";")) return null;
|
||||
const header = /^(\[\[?[^\]]+\]\]?)\s*(#.*)?$/.exec(t);
|
||||
if (header) {
|
||||
section = header[1]!.replace(/\s+/g, "");
|
||||
sectionIndex = seen.get(section) ?? 0;
|
||||
seen.set(section, sectionIndex + 1);
|
||||
return null;
|
||||
}
|
||||
const m = /^(\s*)([A-Za-z0-9_.-]+|"[^"]+")(\s*=\s*)(.*)$/.exec(line);
|
||||
if (!m) return null;
|
||||
let raw = m[4]!;
|
||||
if (format === "toml") {
|
||||
// A comment after the value (outside quotes).
|
||||
let q: string | null = null;
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const c = raw[i]!;
|
||||
if (q) { if (c === q && raw[i - 1] !== "\\") q = null; continue; }
|
||||
if (c === '"' || c === "'") q = c;
|
||||
else if (c === "#") { raw = raw.slice(0, i); break; }
|
||||
}
|
||||
}
|
||||
raw = raw.replace(/\s+$/, "");
|
||||
const start = m[1]!.length + m[2]!.length + m[3]!.length;
|
||||
return { section, sectionIndex, key: m[2]!.replace(/"/g, ""), raw, value: unquote(raw), start, end: start + raw.length };
|
||||
});
|
||||
}
|
||||
|
||||
export interface FrpSettings {
|
||||
proxyBindAddr: string | null;
|
||||
allowPorts: string | null;
|
||||
/** Ports frpc's proxies use (remote and local), or frps's own ports (bind, dashboard …). */
|
||||
usedPorts: number[];
|
||||
}
|
||||
|
||||
/** TOML's allowPorts = [{ start = 2000, end = 3000 }, { single = 3001 }] → "2000-3000,3001". */
|
||||
export function tomlAllowPorts(text: string): string | null {
|
||||
const m = /^\s*allowPorts\s*=\s*\[([\s\S]*?)\]\s*$/m.exec(text);
|
||||
if (!m) return null;
|
||||
const out: string[] = [];
|
||||
for (const obj of m[1]!.matchAll(/\{([^}]*)\}/g)) {
|
||||
const single = /single\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
|
||||
const start = /start\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
|
||||
const end = /end\s*=\s*(\d+)/.exec(obj[1]!)?.[1];
|
||||
if (single) out.push(single);
|
||||
else if (start && end) out.push(`${start}-${end}`);
|
||||
else if (start) out.push(start);
|
||||
}
|
||||
return out.length ? out.join(",") : null;
|
||||
}
|
||||
|
||||
const PORT_KEYS = /^(remote_?port|remotePort|local_?port|localPort|bind_?port|bindPort|kcp_?bind_?port|kcpBindPort|quic_?bind_?port|quicBindPort|vhost_?http_?port|vhostHTTPPort|vhost_?https_?port|vhostHTTPSPort|dashboard_?port|admin_?port|webServer\.port|port|tcpmux_?httpconnect_?port|tcpmuxHTTPConnectPort)$/;
|
||||
|
||||
export function parseSettings(text: string, format: FrpFormat): FrpSettings {
|
||||
const all = lines(text, format).filter((l): l is Line => !!l);
|
||||
const used = new Set<number>();
|
||||
for (const l of all) {
|
||||
if (!PORT_KEYS.test(l.key)) continue;
|
||||
// INI: `remote_port = 6000`; frpc's `local_port` of a proxy is a port on the server too.
|
||||
for (const n of l.value.split(/[,\s]+/)) if (/^\d+$/.test(n)) used.add(Number(n));
|
||||
}
|
||||
if (format === "ini") {
|
||||
const common = all.filter((l) => l.section === "[common]");
|
||||
const get = (k: string) => common.find((l) => l.key === k)?.value || null;
|
||||
return { proxyBindAddr: get("proxy_bind_addr"), allowPorts: get("allow_ports"), usedPorts: [...used].sort((a, b) => a - b) };
|
||||
}
|
||||
const top = all.filter((l) => l.section === "");
|
||||
return {
|
||||
proxyBindAddr: top.find((l) => l.key === "proxyBindAddr")?.value || null,
|
||||
allowPorts: tomlAllowPorts(text),
|
||||
usedPorts: [...used].sort((a, b) => a - b),
|
||||
};
|
||||
}
|
||||
|
||||
/** Keeps the old helper's shape (agent ≤ 1.3 tests and stats). */
|
||||
export function parseFrpsIni(text: string): { proxyBindAddr: string | null; allowPorts: string | null } {
|
||||
const s = parseSettings(text, "ini");
|
||||
return { proxyBindAddr: s.proxyBindAddr, allowPorts: s.allowPorts };
|
||||
}
|
||||
|
||||
// ─── Secrets ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/** token, auth.token, dashboard_pwd, webServer.password, oidc client secret, privilege_token … */
|
||||
const SECRET_KEY = /(token|pwd|passw(or)?d|secret|private_?key|privateKey|credential)/i;
|
||||
export const isSecretKey = (key: string): boolean => SECRET_KEY.test(key);
|
||||
/** A secret key, or an inline table with one in it (auth = { token = "…" }). */
|
||||
const INLINE_SECRET = /[{,]\s*[A-Za-z0-9_.]*(token|pwd|passw(or)?d|secret|private_?key|credential)[A-Za-z0-9_]*\s*=/i;
|
||||
const isSecretLine = (l: Line): boolean => isSecretKey(l.key) || INLINE_SECRET.test(l.raw);
|
||||
|
||||
const idOf = (l: Line) => `${l.section}#${l.sectionIndex}/${l.key}`;
|
||||
const nameOf = (l: Line) => (l.section && !l.section.startsWith("[[") && l.section !== "[common]" ? `${l.section.replace(/[[\]]/g, "")}.${l.key}` : l.key);
|
||||
|
||||
function hiddenRaw(raw: string): string {
|
||||
const t = raw.trim();
|
||||
if (t.startsWith('"')) return `"${agent.FRP_HIDDEN}"`;
|
||||
if (t.startsWith("'")) return `'${agent.FRP_HIDDEN}'`;
|
||||
return agent.FRP_HIDDEN;
|
||||
}
|
||||
|
||||
/** The file with secret values replaced, and their names. */
|
||||
export function hideSecrets(text: string, format: FrpFormat): { content: string; hidden: string[] } {
|
||||
const hidden: string[] = [];
|
||||
const src = text.split("\n");
|
||||
lines(text, format).forEach((l, i) => {
|
||||
if (!l || !isSecretLine(l) || !l.value) return;
|
||||
const line = src[i]!;
|
||||
src[i] = line.slice(0, l.start) + hiddenRaw(l.raw) + line.slice(l.end);
|
||||
hidden.push(nameOf(l));
|
||||
});
|
||||
return { content: src.join("\n"), hidden: [...new Set(hidden)].slice(0, 50) };
|
||||
}
|
||||
|
||||
/**
|
||||
* A file from the Hub with the server's secret values put back. Refused when it changes a secret,
|
||||
* or has a hidden value the server's file has no value for.
|
||||
*/
|
||||
export function restoreSecrets(incoming: string, current: string, format: FrpFormat): { ok: true; content: string } | { ok: false; message: string } {
|
||||
const now = new Map<string, Line>();
|
||||
for (const l of lines(current, format)) if (l && isSecretLine(l)) now.set(idOf(l), l);
|
||||
const src = incoming.split("\n");
|
||||
const parsed = lines(incoming, format);
|
||||
for (let i = 0; i < parsed.length; i++) {
|
||||
const l = parsed[i];
|
||||
if (!l || !isSecretLine(l)) continue;
|
||||
const old = now.get(idOf(l));
|
||||
if (l.value === agent.FRP_HIDDEN) {
|
||||
if (!old) return { ok: false, message: `${nameOf(l)} shows ${agent.FRP_HIDDEN}, but the file on the server has no value for it there. Secrets are set on the server.` };
|
||||
src[i] = src[i]!.slice(0, l.start) + old.raw + src[i]!.slice(l.end);
|
||||
} else if (l.value && (!old || old.value !== l.value)) {
|
||||
return { ok: false, message: `${nameOf(l)} is a secret: it can't be set or changed from the Hub. Change it on the server.` };
|
||||
}
|
||||
}
|
||||
return { ok: true, content: src.join("\n") };
|
||||
}
|
||||
|
||||
// ─── Read, write ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** systemd's view of a unit: true / false, or null when there's no systemctl. */
|
||||
export async function serviceActive(unit: string): Promise<boolean | null> {
|
||||
const r = await execText("systemctl", ["is-active", unit]);
|
||||
if (r.missing) return null;
|
||||
return r.out.trim() === "active";
|
||||
}
|
||||
|
||||
export interface FrpDeps {
|
||||
/** For tests: systemctl and `frp* verify`. */
|
||||
exec?: (cmd: string, args: string[]) => Promise<{ ok: boolean; out: string; err: string; missing: boolean }>;
|
||||
wait?: (ms: number) => Promise<void>;
|
||||
}
|
||||
|
||||
export async function readConfig(mode: agent.AgentMode, opts: { path?: string } = {}, deps: FrpDeps = {}): Promise<agent.FrpReadResult> {
|
||||
const service = serviceFor(mode);
|
||||
if (opts.path) {
|
||||
if (exists(opts.path)) rememberPath(opts.path);
|
||||
forgetFound();
|
||||
}
|
||||
const found = opts.path ? { ...(await findConfig(mode, { fresh: true })), ...(exists(opts.path) ? {} : { path: opts.path, source: "hub" as const }) } : await findConfig(mode, { fresh: true });
|
||||
const exec = deps.exec ?? execText;
|
||||
const running = await (async () => { const r = await exec("systemctl", ["is-active", service]); return r.missing ? null : r.out.trim() === "active"; })();
|
||||
const base = { service, path: found.path, source: found.source, serviceRunning: running, readAt: new Date().toISOString() };
|
||||
let text: string | null = null;
|
||||
if (found.path) {
|
||||
try {
|
||||
const st = fs.statSync(found.path);
|
||||
if (st.size > agent.FRP_CONFIG_MAX) throw new Error(`${found.path} is ${st.size} bytes; the Hub shows files up to ${agent.FRP_CONFIG_MAX}.`);
|
||||
text = fs.readFileSync(found.path, "utf8");
|
||||
} catch (e) {
|
||||
if ((e as NodeJS.ErrnoException).code !== "ENOENT") throw e;
|
||||
}
|
||||
}
|
||||
if (text === null) {
|
||||
return { ...base, found: false, format: null, content: null, hidden: [], proxyBindAddr: null, allowPorts: null, looked: found.path ? [found.path] : found.looked };
|
||||
}
|
||||
const format = formatOf(found.path!, text);
|
||||
const settings = parseSettings(text, format);
|
||||
const { content, hidden } = hideSecrets(text, format);
|
||||
return {
|
||||
...base, found: true, format, content, hidden,
|
||||
proxyBindAddr: service === "frps" ? settings.proxyBindAddr : null,
|
||||
allowPorts: service === "frps" ? settings.allowPorts : null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface WriteOutcome {
|
||||
status: agent.JobStatus;
|
||||
message?: string;
|
||||
steps: agent.ReportStep[];
|
||||
result: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const stamp = () => new Date().toISOString().replace(/[-:]/g, "").replace(/\..*$/, "");
|
||||
|
||||
export async function writeConfig(mode: agent.AgentMode, args: { path: string; content: string; restart: boolean }, deps: FrpDeps = {}): Promise<WriteOutcome> {
|
||||
const exec = deps.exec ?? execText;
|
||||
const wait = deps.wait ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
||||
const service = serviceFor(mode);
|
||||
const steps: agent.ReportStep[] = [];
|
||||
const step = (name: string, outcome: agent.ReportStep["outcome"], detail?: string) => {
|
||||
const at = new Date().toISOString();
|
||||
steps.push({ name, startedAt: at, finishedAt: at, outcome, ...(detail ? { detail: detail.slice(0, 2000) } : {}) });
|
||||
};
|
||||
const refuse = (message: string): WriteOutcome => ({ status: "refused", message, steps, result: {} });
|
||||
|
||||
const found = await findConfig(mode, { fresh: true });
|
||||
if (found.path !== args.path) return refuse(`This server's ${service} config is ${found.path ?? "not found"}, not ${args.path}. Read it again on the Hub first.`);
|
||||
if (!path.basename(args.path).startsWith(service)) return refuse(`${args.path} isn't ${service}'s config (the name must start with ${service}).`);
|
||||
let current: string;
|
||||
try { current = fs.readFileSync(args.path, "utf8"); } catch { return refuse(`There's no file at ${args.path} to replace.`); }
|
||||
const format = formatOf(args.path, current);
|
||||
const restored = restoreSecrets(args.content.replace(/\r\n/g, "\n"), current, format);
|
||||
if (!restored.ok) return refuse(restored.message);
|
||||
const next = restored.content.endsWith("\n") ? restored.content : `${restored.content}\n`;
|
||||
if (next === current) {
|
||||
step("Compare", "skipped", "The file is already like this; nothing changed.");
|
||||
return { status: "succeeded", message: "Nothing changed: the file is already like this.", steps, result: await readConfig(mode, {}, deps) as unknown as Record<string, unknown> };
|
||||
}
|
||||
|
||||
const dir = path.dirname(args.path);
|
||||
const tmp = path.join(dir, `.${path.basename(args.path)}.crosscode-${process.pid}${path.extname(args.path)}`);
|
||||
const mode0 = fs.statSync(args.path).mode & 0o777;
|
||||
fs.writeFileSync(tmp, next, { mode: mode0 });
|
||||
try {
|
||||
const v = await exec(found.bin, ["verify", "-c", tmp]);
|
||||
if (v.missing) { step(`${service} verify`, "failed", `${found.bin} wasn't found.`); return { status: "failed", message: `${found.bin} wasn't found, so the new config couldn't be checked; nothing changed.`, steps, result: {} }; }
|
||||
if (!v.ok) { step(`${service} verify`, "failed", `${v.out}\n${v.err}`.trim()); return { status: "failed", message: `${service} verify refused the new config, so nothing changed: ${(v.err || v.out).trim().slice(0, 500)}`, steps, result: {} }; }
|
||||
step(`${service} verify`, "ok");
|
||||
} catch (e) {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
throw e;
|
||||
}
|
||||
|
||||
const backups = path.join(dir, "backups");
|
||||
fs.mkdirSync(backups, { recursive: true, mode: 0o700 });
|
||||
const backup = path.join(backups, `${path.basename(args.path)}.${stamp()}`);
|
||||
fs.copyFileSync(args.path, backup);
|
||||
fs.chmodSync(backup, mode0);
|
||||
fs.renameSync(tmp, args.path);
|
||||
step("Replace the config", "ok", `Backup: ${backup}`);
|
||||
|
||||
if (!args.restart) {
|
||||
step(`Restart ${service}`, "skipped", "Not asked: the new config is used when frp next starts.");
|
||||
return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } };
|
||||
}
|
||||
const restart = await exec("systemctl", ["restart", service]);
|
||||
await wait(3000);
|
||||
const up = (await exec("systemctl", ["is-active", service])).out.trim() === "active";
|
||||
if (restart.ok && up) {
|
||||
step(`Restart ${service}`, "ok");
|
||||
return { status: "succeeded", steps, result: { ...(await readConfig(mode, {}, deps)), backup } };
|
||||
}
|
||||
step(`Restart ${service}`, "failed", restart.err || `${service} isn't running after the restart.`);
|
||||
fs.copyFileSync(backup, args.path);
|
||||
await exec("systemctl", ["restart", service]);
|
||||
await wait(3000);
|
||||
const back = (await exec("systemctl", ["is-active", service])).out.trim() === "active";
|
||||
step("Put the old config back", back ? "rolled-back" : "failed", back ? `${service} runs with the old config again.` : `${service} isn't running with the old config either: look at it on the server (journalctl -u ${service}).`);
|
||||
return {
|
||||
status: back ? "rolled-back" : "failed",
|
||||
message: back ? `${service} didn't start with the new config, so the old one was put back.` : `${service} didn't start with the new config, and isn't running after putting the old one back either.`,
|
||||
steps,
|
||||
result: { ...(await readConfig(mode, {}, deps)), backup },
|
||||
};
|
||||
}
|
||||
|
||||
// ─── Free ports (probe-ports) ─────────────────────────────────────────────────
|
||||
|
||||
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
|
||||
export function portAllowed(port: number, allowPorts: string | null): boolean {
|
||||
if (!allowPorts) return true;
|
||||
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
|
||||
const [a, b] = range.split("-").map((n) => Number(n.trim()));
|
||||
if (!Number.isFinite(a)) return false;
|
||||
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
|
||||
});
|
||||
}
|
||||
|
||||
export function probePorts(ports: number[], mode: agent.AgentMode, settings: FrpSettings | null, listening: Map<number, string[]>, configPath: string | null): agent.ProbePortsResult {
|
||||
const used = new Set(settings?.usedPorts ?? []);
|
||||
return {
|
||||
configPath,
|
||||
ports: ports.map((port) => {
|
||||
const addrs = listening.get(port);
|
||||
if (addrs?.length) return { port, free: false, reason: `In use: something listens on ${[...new Set(addrs)].join(", ")}.` };
|
||||
if (mode === "central" && settings && !portAllowed(port, settings.allowPorts)) return { port, free: false, reason: "Not in frps's allow_ports." };
|
||||
if (used.has(port)) return { port, free: false, reason: `Used in ${mode === "central" ? "frps" : "frpc"}'s config.` };
|
||||
return { port, free: true, reason: null };
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The settings of the config this server uses, or null when there's none. */
|
||||
export async function currentSettings(mode: agent.AgentMode): Promise<{ path: string | null; settings: FrpSettings | null }> {
|
||||
const found = await findConfig(mode);
|
||||
if (!found.path) return { path: null, settings: null };
|
||||
try {
|
||||
const text = fs.readFileSync(found.path, "utf8");
|
||||
return { path: found.path, settings: parseSettings(text, formatOf(found.path, text)) };
|
||||
} catch {
|
||||
return { path: found.path, settings: null };
|
||||
}
|
||||
}
|
||||
+23
-3
@@ -2,7 +2,8 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { encryptExport } from "@crosscode/contracts/signing";
|
||||
import { checkPorts, listeningNow, readFrps } from "./central";
|
||||
import { checkPorts, listeningNow } from "./central";
|
||||
import { currentSettings, findConfig, probePorts, readConfig, writeConfig } from "./frp";
|
||||
import { crosscodeArgs } from "./command";
|
||||
import type { AgentConfig, Keys } from "./config";
|
||||
import { type HubClient, HubRequestError } from "./hub";
|
||||
@@ -153,10 +154,25 @@ export class Agent {
|
||||
return { status: u.status, steps: u.steps, result: u.result, message: u.message, log: [], startedAt, finishedAt: new Date().toISOString(), restart: u.restart };
|
||||
}
|
||||
case "check-ports": {
|
||||
const res = checkPorts(job.args.ports, readFrps(), await listeningNow());
|
||||
const { path: configPath, settings } = await currentSettings("central");
|
||||
const res = checkPorts(job.args.ports, settings, await listeningNow(), configPath);
|
||||
const ok = res.ports.every((p) => p.ok) && res.warnings.length === 0;
|
||||
return { status: ok ? "succeeded" : "failed", steps: [], result: res as unknown as Record<string, unknown>, message: res.warnings.join(" ") || undefined, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "frp-read": {
|
||||
const result = await readConfig(this.deps.config.mode, { path: job.args.path });
|
||||
const message = result.found ? undefined : `No ${result.service} config found${result.path ? ` at ${result.path}` : ""}.`;
|
||||
return { status: result.found ? "succeeded" : "failed", steps: [], result: result as unknown as Record<string, unknown>, message, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "frp-write": {
|
||||
const w = await writeConfig(this.deps.config.mode, job.args);
|
||||
return { status: w.status, steps: w.steps, result: w.result, message: w.message, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "probe-ports": {
|
||||
const { path: configPath, settings } = await currentSettings(this.deps.config.mode);
|
||||
const result = probePorts(job.args.ports, this.deps.config.mode, settings, await listeningNow(), configPath);
|
||||
return { status: "succeeded", steps: [], result: result as unknown as Record<string, unknown>, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "export":
|
||||
return await this.runExport(job, limit);
|
||||
case "status":
|
||||
@@ -181,7 +197,11 @@ export class Agent {
|
||||
|
||||
private run(args: string[], job: agent.AgentJob, limit: number): Promise<RunResult> {
|
||||
if (this.deps.run) return this.deps.run(args, job);
|
||||
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit });
|
||||
return (async () => {
|
||||
// crosscode edits frpc's config on installs: tell it where the file is (agent 1.4.0).
|
||||
const frpc = this.deps.config.mode === "church" ? (await findConfig("church").catch(() => null))?.path : null;
|
||||
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit, env: frpc ? { FRPC_INI: frpc } : {} });
|
||||
})();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -15,8 +15,6 @@ export const paths = {
|
||||
get crosscode() { return env("CROSSCODE_BIN", "/usr/local/bin/crosscode"); },
|
||||
/** Agent releases: releases/<version>/ (checkouts), current → the running one, previous. */
|
||||
get agentRoot() { return env("CROSSCODE_AGENT_ROOT", "/opt/crosscode/agent"); },
|
||||
/** frps.ini on the central server. */
|
||||
get frpsIni() { return env("CROSSCODE_FRPS_INI", "/etc/frp/frps.ini"); },
|
||||
/** The churches on a church server. */
|
||||
get sites() { return env("CROSSCODE_SITES", "/var/www/sites"); },
|
||||
};
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface RunOptions {
|
||||
sealedConfig?: agent.Sealed | null;
|
||||
x25519Pem: string;
|
||||
timeLimitMinutes: number;
|
||||
/** Extra environment for crosscode (FRPC_INI). */
|
||||
env?: Record<string, string>;
|
||||
/** For tests. */
|
||||
bin?: string;
|
||||
}
|
||||
@@ -59,7 +61,7 @@ export async function runCrosscode(opts: RunOptions): Promise<RunResult> {
|
||||
const child = spawn(opts.bin ?? paths.crosscode, args, {
|
||||
detached: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
|
||||
env: { ...process.env, ...opts.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
|
||||
});
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { agent } from "@crosscode/contracts";
|
||||
import { readFrps } from "./central";
|
||||
import { currentSettings, serviceActive } from "./frp";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
@@ -12,7 +12,7 @@ import { paths } from "./paths";
|
||||
* the tools that are there; anything missing is null rather than an error.
|
||||
*/
|
||||
|
||||
export const AGENT_VERSION = "1.3.1";
|
||||
export const AGENT_VERSION = "1.5.0";
|
||||
|
||||
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
@@ -159,9 +159,10 @@ export async function collectStats(mode: agent.AgentMode): Promise<agent.AgentSt
|
||||
frpcRunning,
|
||||
processes,
|
||||
};
|
||||
const frp = await currentSettings(mode).catch(() => ({ path: null, settings: null }));
|
||||
stats.frpConfigPath = frp.path;
|
||||
if (mode === "central") {
|
||||
const frps = readFrps();
|
||||
stats.central = { proxyBindAddr: frps?.proxyBindAddr ?? null, allowPorts: frps?.allowPorts ?? null, frpsRunning: await active("frps") };
|
||||
stats.central = { proxyBindAddr: frp.settings?.proxyBindAddr ?? null, allowPorts: frp.settings?.allowPorts ?? null, frpsRunning: await serviceActive("frps") };
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
|
||||
@@ -36,6 +36,10 @@ describe("crosscode arguments for each job", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "restart", args: { church: "hope" } }))).toEqual(["restart", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope" } }))).toEqual(["uninstall", "hope", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope" } }))).toEqual(["purge", "hope", "--confirm", "hope"]);
|
||||
// 1.5.0: one product of the church.
|
||||
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope", products: ["events"] } }))).toEqual(["uninstall", "hope", "events", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope", products: ["events"] } }))).toEqual(["purge", "hope", "events", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh", products: ["accounts"] } }), { exportFile: "/x/e.zip" })).toEqual(["export", "hope", "accounts", "--out", "/x/e.zip"]);
|
||||
expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import {
|
||||
configFromCommand, findConfig, forgetFound, hideSecrets, parseExecStart, parseSettings, probePorts, readConfig, restoreSecrets, writeConfig,
|
||||
} from "../src/frp";
|
||||
import { tempState } from "./helpers";
|
||||
|
||||
const H = agent.FRP_HIDDEN;
|
||||
|
||||
const TOML = `bindPort = 7000
|
||||
proxyBindAddr = "127.0.0.1"
|
||||
auth.token = "s3cret-token" # the shared token
|
||||
allowPorts = [
|
||||
{ start = 20000, end = 29999 },
|
||||
{ single = 3001 },
|
||||
]
|
||||
|
||||
[webServer]
|
||||
port = 7500
|
||||
password = 'dash-pass'
|
||||
`;
|
||||
|
||||
const FRPC_INI = `[common]
|
||||
server_addr = 203.0.113.10
|
||||
server_port = 7000
|
||||
token = abc123
|
||||
|
||||
[hope-events-web]
|
||||
type = tcp
|
||||
local_ip = 127.0.0.1
|
||||
local_port = 20010
|
||||
remote_port = 20010
|
||||
`;
|
||||
|
||||
const noSystemd = async () => ({ ok: false, out: "", err: "", missing: true });
|
||||
|
||||
describe("finding frp's config", () => {
|
||||
it("reads -c from the systemd unit", () => {
|
||||
expect(configFromCommand("/usr/local/bin/frps -c /usr/local/frp/frps.toml")).toBe("/usr/local/frp/frps.toml");
|
||||
expect(configFromCommand("/usr/bin/frps --config=/etc/frps/frps.ini")).toBe("/etc/frps/frps.ini");
|
||||
expect(configFromCommand("/usr/bin/frps")).toBeNull();
|
||||
expect(parseExecStart("{ path=/usr/local/bin/frps ; argv[]=/usr/local/bin/frps -c /opt/frp/frps.toml ; ignore_errors=no ; start_time=[n/a] }"))
|
||||
.toEqual({ config: "/opt/frp/frps.toml", bin: "/usr/local/bin/frps" });
|
||||
});
|
||||
|
||||
it("the path from the Hub wins, and is remembered", async () => {
|
||||
const dir = tempState();
|
||||
const file = path.join(dir, "frps.toml");
|
||||
fs.writeFileSync(file, TOML);
|
||||
forgetFound();
|
||||
const exec = async () => ({ ok: true, out: "active\n", err: "", missing: false });
|
||||
const r = await readConfig("central", { path: file }, { exec });
|
||||
expect(r).toMatchObject({ found: true, source: "hub", path: file, format: "toml", proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001", serviceRunning: true });
|
||||
forgetFound();
|
||||
expect((await findConfig("central", { fresh: true })).path).toBe(file);
|
||||
});
|
||||
|
||||
it("a path that isn't there is reported, not remembered", async () => {
|
||||
const dir = tempState();
|
||||
forgetFound();
|
||||
const r = await readConfig("central", { path: path.join(dir, "nope", "frps.ini") }, { exec: noSystemd });
|
||||
expect(r).toMatchObject({ found: false, content: null });
|
||||
expect(fs.existsSync(path.join(dir, "frp.json"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("frp settings, INI and TOML", () => {
|
||||
it("TOML", () => {
|
||||
expect(parseSettings(TOML, "toml")).toMatchObject({ proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3001" });
|
||||
expect(parseSettings(TOML, "toml").usedPorts).toEqual(expect.arrayContaining([7000, 7500]));
|
||||
});
|
||||
it("INI: frpc's tunnels use their ports", () => {
|
||||
expect(parseSettings(FRPC_INI, "ini").usedPorts).toEqual([20010]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("secrets never leave the server", () => {
|
||||
it("are hidden in TOML and INI, keeping the quotes", () => {
|
||||
const t = hideSecrets(TOML, "toml");
|
||||
expect(t.content).toContain(`auth.token = "${H}" # the shared token`);
|
||||
expect(t.content).toContain(`password = '${H}'`);
|
||||
expect(t.content).not.toMatch(/s3cret|dash-pass/);
|
||||
expect(t.hidden).toEqual(["auth.token", "webServer.password"]);
|
||||
const i = hideSecrets(FRPC_INI, "ini");
|
||||
expect(i.content).toContain(`token = ${H}`);
|
||||
expect(i.content).not.toContain("abc123");
|
||||
});
|
||||
it("in inline tables too", () => {
|
||||
expect(hideSecrets(`auth = { method = "token", token = "zzz" }\n`, "toml").content).not.toContain("zzz");
|
||||
});
|
||||
it("are put back on write, and can't be changed from the Hub", () => {
|
||||
const shown = hideSecrets(TOML, "toml").content.replace("bindPort = 7000", "bindPort = 7001");
|
||||
const back = restoreSecrets(shown, TOML, "toml");
|
||||
expect(back.ok && back.content).toBe(TOML.replace("bindPort = 7000", "bindPort = 7001"));
|
||||
expect(restoreSecrets(shown.replace(`"${H}"`, '"new"'), TOML, "toml")).toMatchObject({ ok: false, message: expect.stringMatching(/auth.token is a secret/) });
|
||||
expect(restoreSecrets(`${shown}\n[extra]\ntoken = "${H}"\n`, TOML, "toml")).toMatchObject({ ok: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("writing the config", () => {
|
||||
const setup = () => {
|
||||
const dir = tempState();
|
||||
const file = path.join(dir, "frps.toml");
|
||||
fs.writeFileSync(file, TOML);
|
||||
fs.writeFileSync(path.join(dir, "frp.json"), JSON.stringify({ path: file }));
|
||||
forgetFound();
|
||||
return { dir, file };
|
||||
};
|
||||
const shown = () => hideSecrets(TOML, "toml").content;
|
||||
|
||||
it("verify, backup, replace, restart", async () => {
|
||||
const { dir, file } = setup();
|
||||
const calls: string[] = [];
|
||||
const exec = async (cmd: string, args: string[]) => { calls.push(`${cmd} ${args.join(" ")}`); return { ok: true, out: "active", err: "", missing: false }; };
|
||||
const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} });
|
||||
expect(r.status).toBe("succeeded");
|
||||
expect(fs.readFileSync(file, "utf8")).toContain("bindPort = 7001");
|
||||
expect(fs.readFileSync(file, "utf8")).toContain("s3cret-token");
|
||||
expect(fs.readdirSync(path.join(dir, "backups"))).toHaveLength(1);
|
||||
expect(calls.some((c) => / verify -c /.test(c))).toBe(true);
|
||||
expect(calls).toContain("systemctl restart frps");
|
||||
expect(JSON.stringify(r.result)).not.toContain("s3cret");
|
||||
});
|
||||
|
||||
it("verify refuses: nothing changes", async () => {
|
||||
const { file } = setup();
|
||||
const exec = async (cmd: string) => ({ ok: cmd === "systemctl", out: "", err: "bad key", missing: false });
|
||||
const r = await writeConfig("central", { path: file, content: "nonsense = [", restart: true }, { exec, wait: async () => {} });
|
||||
expect(r.status).toBe("failed");
|
||||
expect(fs.readFileSync(file, "utf8")).toBe(TOML);
|
||||
});
|
||||
|
||||
it("frps doesn't come back: the old file is put back", async () => {
|
||||
const { file } = setup();
|
||||
let restarts = 0;
|
||||
const exec = async (_cmd: string, args: string[]) => {
|
||||
if (args[0] === "restart") restarts++;
|
||||
if (args[0] === "is-active") return { ok: true, out: restarts >= 2 ? "active" : "failed", err: "", missing: false };
|
||||
return { ok: true, out: "", err: "", missing: false };
|
||||
};
|
||||
const r = await writeConfig("central", { path: file, content: shown().replace("bindPort = 7000", "bindPort = 7001"), restart: true }, { exec, wait: async () => {} });
|
||||
expect(r.status).toBe("rolled-back");
|
||||
expect(fs.readFileSync(file, "utf8")).toBe(TOML);
|
||||
});
|
||||
|
||||
it("only the file the agent uses", async () => {
|
||||
const { dir } = setup();
|
||||
const r = await writeConfig("central", { path: path.join(dir, "frpc.toml"), content: "x = 1", restart: false }, { exec: noSystemd });
|
||||
expect(r.status).toBe("refused");
|
||||
});
|
||||
});
|
||||
|
||||
describe("free ports before an install", () => {
|
||||
it("central: not listening and inside allow_ports", () => {
|
||||
const listening = new Map([[20001, ["0.0.0.0"]]]);
|
||||
const r = probePorts([20000, 20001, 30000], "central", parseSettings(TOML, "toml"), listening, "/etc/frp/frps.toml");
|
||||
expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20000, true], [20001, false], [30000, false]]);
|
||||
});
|
||||
it("church: not listening and not in frpc's tunnels", () => {
|
||||
const r = probePorts([20010, 20011], "church", parseSettings(FRPC_INI, "ini"), new Map(), "/etc/frp/frpc.ini");
|
||||
expect(r.ports.map((p) => [p.port, p.free])).toEqual([[20010, false], [20011, true]]);
|
||||
});
|
||||
it("with no config found, listening is all it can check", () => {
|
||||
expect(probePorts([20010], "central", null, new Map(), null).ports[0]!.free).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,38 @@ All notable changes to this project are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.7.0] - 2026-11-24
|
||||
|
||||
The church's look from its Accounts (docs/WEBSITE-1.0-PLAN.md §9). **Requires Accounts 1.7.0**
|
||||
(WHATS-NEW.md says so, and the Hub updates Accounts first) for the brand style. No migrations, no
|
||||
new settings.
|
||||
|
||||
### Added
|
||||
|
||||
- **The church's fonts and corners on the public pages.** The backend reads the church profile from
|
||||
Accounts (`GET /api/church/v1`, kept for 10 minutes; `src/accounts/church.ts`) and the public
|
||||
pages get it from the new `GET /api/v2/church` (public). `<html>` gets `brandAttributes(style)`
|
||||
from `@crosscode/ui` and the root layout imports `@crosscode/ui/fonts.css` (self-hosted, so no
|
||||
font is loaded from another site). Body text and h1–h3 use `--cc-font-body` and
|
||||
`--cc-font-heading` when the church picked a pairing, and `--radius` follows the corner style
|
||||
(`soft` is 0.5rem, the same as before). The dashboard and setup screens (`data-cc-staff`) keep
|
||||
the system fonts and 0.5rem.
|
||||
- **`church.changed` from Accounts** at `POST /api/church/v1/changed` (signed with the Accounts
|
||||
link, `LINK_HEADERS`): the profile is fetched again on the next page. Before 3.7.0 this answered
|
||||
404 and Accounts kept retrying for a week.
|
||||
- **The shared church footer** (`ChurchFooter`, `@crosscode/ui` 0.3.0) on the public pages when
|
||||
Accounts is connected: name and logo, service times, address, contact, social links and links
|
||||
to the church's other sites and the privacy notice, with Terms of Use and cookie settings below.
|
||||
Without Accounts, and on the dashboard (`<Footer plain />`), the footer is as before.
|
||||
- **Links to the church's other sites** in the header of the public pages (its Website, later its
|
||||
App), from the profile's `links`.
|
||||
|
||||
### Changed
|
||||
|
||||
- `@crosscode/ui` 0.3.0: `ChurchFooter` takes `bottom` (a product's own links after the copyright).
|
||||
- Frontend: `transpilePackages: ["@crosscode/ui"]`; Tailwind scans `packages/ui/src` and has
|
||||
`brand` (brand-700) for the shared footer.
|
||||
|
||||
## [3.6.1] - 2026-11-20
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -12,6 +12,14 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 3.7.0 — requires accounts 1.7.0
|
||||
|
||||
- **Your public pages look like the rest of your church's sites.** With sign-in through your
|
||||
church's Accounts, the event pages use the fonts and corner style picked under Accounts → Admin →
|
||||
Brand style (as your sign-in pages, and later your church website, do), and a new footer shows your service times,
|
||||
address, contact details, social links and links to your other sites. The dashboard looks the same
|
||||
as before.
|
||||
|
||||
## 3.6.1
|
||||
|
||||
- **Fix:** uploading a logo or site icon under Settings → Branding could fail with "uploaded, but
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): the brand
|
||||
* style (fonts and corners) and what the shared footer shows (service times, address, contact,
|
||||
* social, the church's other sites). Accounts owns it and serves it publicly at
|
||||
* `GET /api/church/v1`; this keeps a copy in memory for the public pages (`GET /api/v2/church`).
|
||||
*
|
||||
* Fetched again after 10 minutes, or at once when Accounts sends `church.changed`
|
||||
* (`POST /api/church/v1/changed`, src/links/routes.ts). While Accounts can't be reached the last
|
||||
* copy is kept and it's tried again after a minute; a site without Accounts has none, and its
|
||||
* pages look as they always have.
|
||||
*/
|
||||
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
|
||||
import { accountsLink } from './client';
|
||||
|
||||
const FRESH_MS = 10 * 60e3;
|
||||
const RETRY_MS = 60e3;
|
||||
const TIMEOUT_MS = 5000;
|
||||
|
||||
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
|
||||
let cached: Cached | null = null;
|
||||
let pending: Promise<Church | null> | null = null;
|
||||
|
||||
async function fetchProfile(accountsUrl: string): Promise<Church> {
|
||||
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
|
||||
const parsed = churchSchema.safeParse(await res.json());
|
||||
if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
/** The church's profile, or null when Accounts isn't connected or hasn't answered yet. Never throws. */
|
||||
export async function churchProfile(): Promise<Church | null> {
|
||||
let link;
|
||||
try {
|
||||
link = await accountsLink();
|
||||
} catch {
|
||||
return cached?.church ?? null;
|
||||
}
|
||||
if (!link) return null;
|
||||
const url = link.url;
|
||||
if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
|
||||
if (!pending) {
|
||||
const last = cached?.url === url ? cached.church : null;
|
||||
pending = fetchProfile(url)
|
||||
.then((church) => {
|
||||
cached = { url, church, at: Date.now(), ok: true };
|
||||
return church;
|
||||
}, (e: Error) => {
|
||||
console.warn('[church] profile not fetched from Accounts:', e.message);
|
||||
cached = { url, church: last, at: Date.now(), ok: false };
|
||||
return last;
|
||||
})
|
||||
.finally(() => { pending = null; });
|
||||
}
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** `church.changed`: the next `churchProfile()` fetches it again (the last copy is shown meanwhile). */
|
||||
export function churchChanged(): void {
|
||||
if (cached) cached = { ...cached, at: 0 };
|
||||
}
|
||||
|
||||
/** Tests: start with nothing. */
|
||||
export function resetChurchProfile(): void {
|
||||
cached = null;
|
||||
pending = null;
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
*
|
||||
* 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/church/v1/changed church.changed from the church's Accounts (3.7.0)
|
||||
* POST /api/links/v1/connect crosscode.link/1 link.connect → link.connected
|
||||
* POST /api/links/v1/disconnect crosscode.link/1 link.disconnect → link.disconnected
|
||||
*
|
||||
@@ -11,11 +12,12 @@
|
||||
*/
|
||||
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 { CHURCH_PATHS, churchChangedSchema, 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';
|
||||
import { churchChanged } from '../accounts/church';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
@@ -74,6 +76,25 @@ export function crossProductRouter(): Router {
|
||||
}
|
||||
});
|
||||
|
||||
// 3.7.0: the church profile changed in Accounts (its brand style, footer details): fetch it again.
|
||||
router.post(CHURCH_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 || link.product !== 'accounts') return fail(res, 404, 'NOT_LINKED', 'This site has no link with that Accounts.');
|
||||
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 (!churchChangedSchema.safeParse(body).success) return fail(res, 400, 'INVALID_REQUEST', "That isn't a church.changed message.");
|
||||
churchChanged();
|
||||
return res.status(202).json({ accepted: true });
|
||||
} 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)));
|
||||
|
||||
@@ -26,6 +26,7 @@ import './resources/ai';
|
||||
import './resources/feedback';
|
||||
import './resources/linkedProducts';
|
||||
import './resources/signIn';
|
||||
import './resources/church';
|
||||
|
||||
const pkg = require('../../package.json') as { version: string };
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { churchSchema } from '@crosscode/contracts';
|
||||
import { defineRoute } from '../route';
|
||||
import { single } from '../paging';
|
||||
import { churchProfile } from '../../accounts/church';
|
||||
|
||||
/**
|
||||
* The church profile for the public pages (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): its brand style
|
||||
* (fonts, corners) and the shared footer's details, from the church's Accounts
|
||||
* (src/accounts/church.ts). null when Accounts isn't connected.
|
||||
*/
|
||||
export const getChurch = defineRoute({
|
||||
method: 'get',
|
||||
path: '/church',
|
||||
tag: 'Site',
|
||||
summary: "The church's profile",
|
||||
description: "The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.",
|
||||
access: 'public',
|
||||
response: single(churchSchema.nullable()),
|
||||
async handler({ res }) {
|
||||
res.setHeader('Cache-Control', 'public, max-age=60');
|
||||
return { data: await churchProfile() };
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
// 3.7.0 (docs/WEBSITE-1.0-PLAN.md §9): the church profile from Accounts for the public pages (its
|
||||
// brand style and the shared footer), kept in memory and fetched again on church.changed.
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import express from 'express';
|
||||
import request from 'supertest';
|
||||
|
||||
type Link = { installId: string; product: string; url: string; secret: string; updatedAt: Date };
|
||||
const mockLinks: Link[] = [];
|
||||
jest.mock('../src/config/db', () => ({
|
||||
productLink: {
|
||||
findFirst: async ({ where }: { where: { product: string } }) => mockLinks.find((l) => l.product === where.product) ?? null,
|
||||
findUnique: async ({ where }: { where: { installId: string } }) => mockLinks.find((l) => l.installId === where.installId) ?? null,
|
||||
},
|
||||
}));
|
||||
jest.mock('../src/jobs', () => ({ enqueueTask: async () => ({ queued: true }) }));
|
||||
|
||||
process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption';
|
||||
|
||||
import { CHURCH_PATHS } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { churchProfile, resetChurchProfile } from '../src/accounts/church';
|
||||
import { crossProductRouter } from '../src/links/routes';
|
||||
import { getChurch } from '../src/v2/resources/church';
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports -- CommonJS
|
||||
const { encrypt } = require('../src/utils/encryption') as { encrypt(v: string): string };
|
||||
|
||||
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
|
||||
const sample = (name: string) => JSON.parse(fs.readFileSync(path.join(SAMPLES, name), 'utf8'));
|
||||
const ACCOUNTS_ID = '5c1d2e3f-4a5b-4c6d-8e7f-9a0b1c2d3e4f';
|
||||
const SECRET = 'link-secret-for-the-test-0123456789';
|
||||
|
||||
let profile = sample('church.json');
|
||||
let answers: (number | 'down')[] = [];
|
||||
let fetches = 0;
|
||||
const realFetch = global.fetch;
|
||||
|
||||
beforeAll(() => {
|
||||
global.fetch = (async (url: string) => {
|
||||
fetches++;
|
||||
expect(url).toBe(`https://accounts.hope.test${CHURCH_PATHS.profile}`);
|
||||
const next = answers.shift() ?? 200;
|
||||
if (next === 'down') throw new Error('connect ECONNREFUSED');
|
||||
return new Response(JSON.stringify(profile), { status: next, headers: { 'content-type': 'application/json' } });
|
||||
}) as typeof fetch;
|
||||
});
|
||||
afterAll(() => { global.fetch = realFetch; });
|
||||
|
||||
beforeEach(() => {
|
||||
resetChurchProfile();
|
||||
mockLinks.length = 0;
|
||||
answers = [];
|
||||
fetches = 0;
|
||||
profile = sample('church.json');
|
||||
jest.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
});
|
||||
afterEach(() => { jest.restoreAllMocks(); });
|
||||
|
||||
const connectAccounts = () => mockLinks.push({ installId: ACCOUNTS_ID, product: 'accounts', url: 'https://accounts.hope.test/', secret: encrypt(SECRET), updatedAt: new Date() });
|
||||
|
||||
function app() {
|
||||
const a = express();
|
||||
a.use('/api', crossProductRouter());
|
||||
return a;
|
||||
}
|
||||
|
||||
function changed(body: object, { from = ACCOUNTS_ID, secret = SECRET } = {}) {
|
||||
const raw = JSON.stringify(body);
|
||||
const headers = signedHeaders(LINK_HEADERS, { senderId: from, secret, rawBody: raw });
|
||||
return request(app()).post(CHURCH_PATHS.changed).set({ 'content-type': 'application/json', ...headers }).send(raw);
|
||||
}
|
||||
|
||||
describe('the church profile', () => {
|
||||
test('none without Accounts, and nothing is fetched', async () => {
|
||||
expect(await churchProfile()).toBeNull();
|
||||
expect(fetches).toBe(0);
|
||||
});
|
||||
|
||||
test("fetched from the church's Accounts, with its brand style, and kept", async () => {
|
||||
connectAccounts();
|
||||
const c = await churchProfile();
|
||||
expect(c?.branding.style).toEqual({ fontPairing: 'warm', corners: 'soft' });
|
||||
expect(c?.name).toBe(profile.name);
|
||||
await churchProfile();
|
||||
expect(fetches).toBe(1);
|
||||
});
|
||||
|
||||
test('a pairing this version doesn\'t know reads as none, so the page keeps its fonts', async () => {
|
||||
connectAccounts();
|
||||
profile.branding.style = { fontPairing: 'from-the-future', corners: 'round' };
|
||||
expect((await churchProfile())?.branding.style).toEqual({ fontPairing: null, corners: 'round' });
|
||||
});
|
||||
|
||||
test('Accounts down: none at first, then the last copy is kept while it is down', async () => {
|
||||
connectAccounts();
|
||||
answers = ['down'];
|
||||
expect(await churchProfile()).toBeNull();
|
||||
resetChurchProfile();
|
||||
expect((await churchProfile())?.name).toBe(profile.name);
|
||||
});
|
||||
|
||||
test('a profile that isn\'t crosscode.church/1 isn\'t used', async () => {
|
||||
connectAccounts();
|
||||
profile = { hello: 'world' };
|
||||
expect(await churchProfile()).toBeNull();
|
||||
});
|
||||
|
||||
test('GET /api/v2/church answers it, cacheable for a minute', async () => {
|
||||
connectAccounts();
|
||||
const headers: Record<string, string> = {};
|
||||
const res = { setHeader: (k: string, v: string) => { headers[k] = v; } };
|
||||
const out = await getChurch.handler({ res } as never);
|
||||
expect(getChurch.response.safeParse(out).success).toBe(true);
|
||||
expect((out as { data: { name: string } }).data.name).toBe(profile.name);
|
||||
expect(headers['Cache-Control']).toBe('public, max-age=60');
|
||||
});
|
||||
});
|
||||
|
||||
describe('church.changed from Accounts', () => {
|
||||
test('fetches the profile again (the last copy until then)', async () => {
|
||||
connectAccounts();
|
||||
await churchProfile();
|
||||
profile.branding.style = { fontPairing: 'classic', corners: 'sharp' };
|
||||
expect((await churchProfile())?.branding.style?.fontPairing).toBe('warm');
|
||||
const res = await changed(sample('church-changed.json'));
|
||||
expect(res.status).toBe(202);
|
||||
expect((await churchProfile())?.branding.style).toEqual({ fontPairing: 'classic', corners: 'sharp' });
|
||||
expect(fetches).toBe(2);
|
||||
});
|
||||
|
||||
test('refuses a wrong signature, a sender that isn\'t Accounts and a body that isn\'t church.changed', async () => {
|
||||
connectAccounts();
|
||||
mockLinks.push({ installId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', product: 'website', url: 'https://www.hope.test', secret: encrypt(SECRET), updatedAt: new Date() });
|
||||
expect((await changed(sample('church-changed.json'), { secret: 'not-the-secret-at-all-0123456789' })).status).toBe(401);
|
||||
expect((await changed(sample('church-changed.json'), { from: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' })).status).toBe(404);
|
||||
const bad = await changed({ type: 'something.else' });
|
||||
expect(bad.status).toBe(400);
|
||||
expect(bad.body.code).toBe('INVALID_REQUEST');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
import path from "path";
|
||||
import AxeBuilder from "@axe-core/playwright";
|
||||
import { test, expect, loginAs, seed } from "./fixtures";
|
||||
|
||||
// 3.7.0 (docs/WEBSITE-1.0-PLAN.md §9 and §13): with the church's Accounts connected, the public
|
||||
// pages use the church's fonts and corners from its profile and the shared church footer, as the
|
||||
// Website and Accounts' own pages do. The dashboard stays as it is. Accounts runs in memory
|
||||
// (e2e/support/accounts-server.mts); afterwards the link is removed, so the other specs see the
|
||||
// site as before.
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */
|
||||
const backend = path.join(__dirname, "..", "backend");
|
||||
require(require.resolve("dotenv", { paths: [backend] })).config({ path: path.join(backend, ".env") });
|
||||
const { Client } = require(require.resolve("pg", { paths: [backend] }));
|
||||
const { e2eDatabaseUrl } = require("./support/db-url");
|
||||
const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] }));
|
||||
const { encrypt } = require(path.join(backend, "src", "utils", "encryption"));
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const ACCOUNTS_API = "http://127.0.0.1:5221";
|
||||
const ACCOUNTS_ID = "7e2d1c0b-9a8f-4e6d-8c5b-4a3f2e1d0c9b";
|
||||
const TAGS = ["wcag2a", "wcag2aa", "wcag21a", "wcag21aa", "wcag22aa"];
|
||||
|
||||
async function sql(text: string, values: unknown[] = []) {
|
||||
const client = new Client({ connectionString: e2eDatabaseUrl() });
|
||||
await client.connect();
|
||||
try {
|
||||
return (await client.query(text, values)).rows;
|
||||
} finally {
|
||||
await client.end();
|
||||
}
|
||||
}
|
||||
|
||||
test.describe.serial("the church's brand style and footer", () => {
|
||||
test.beforeAll(async () => {
|
||||
const profile = await fetch(`${ACCOUNTS_API}/test/profile`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: "E2E Church",
|
||||
branding: { style: { fontPairing: "warm", corners: "round" } },
|
||||
serviceTimes: [{ day: "sunday", time: "09:00", label: "Morning service", campus: null, note: null }],
|
||||
contact: { email: "office@e2e.test", phone: "+27161234567", whatsapp: null, address: { line1: "1 Church Street", line2: null, suburb: null, city: "Vereeniging", postalCode: "1939" } },
|
||||
}),
|
||||
});
|
||||
expect(profile.ok, await profile.text()).toBe(true);
|
||||
// Linked to Accounts, as Connect would (the backend reads the profile from this address).
|
||||
await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`);
|
||||
await sql(
|
||||
`INSERT INTO "ProductLink" ("installId", product, url, "publicKey", secret, "connectedAt", "createdAt", "updatedAt") VALUES ($1, 'accounts', $2, 'x', $3, now(), now(), now())`,
|
||||
[ACCOUNTS_ID, ACCOUNTS_API, encrypt(signing.newLinkSecret())],
|
||||
);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`);
|
||||
});
|
||||
|
||||
test("public pages: the church's fonts, round corners and the shared footer, all from this site", async ({ page }) => {
|
||||
const elsewhere: string[] = [];
|
||||
page.on("request", (r) => {
|
||||
if (r.resourceType() === "font" && !r.url().startsWith("http://localhost:3100/")) elsewhere.push(r.url());
|
||||
});
|
||||
// The site keeps the profile for a minute; reload until it's there.
|
||||
await expect(async () => {
|
||||
await page.goto("/events");
|
||||
await expect(page.locator("html")).toHaveAttribute("data-cc-fonts", "warm", { timeout: 1000 });
|
||||
}).toPass({ timeout: 90_000 });
|
||||
await expect(page.locator("html")).toHaveAttribute("data-cc-corners", "round");
|
||||
await expect(page.getByText("E2E Free Evening")).toBeVisible();
|
||||
|
||||
const fonts = await page.evaluate(async () => {
|
||||
await document.fonts.ready;
|
||||
const h1 = document.querySelector("h1");
|
||||
return {
|
||||
body: getComputedStyle(document.body).fontFamily,
|
||||
heading: h1 ? getComputedStyle(h1).fontFamily : "",
|
||||
radius: getComputedStyle(document.documentElement).getPropertyValue("--radius").trim(),
|
||||
loaded: [...document.fonts].filter((f) => f.status === "loaded").map((f) => f.family.replace(/"/g, "")),
|
||||
};
|
||||
});
|
||||
expect(fonts.body).toContain("CC Nunito Sans");
|
||||
expect(fonts.heading).toContain("CC Fraunces");
|
||||
expect(fonts.radius).toBe("0.75rem");
|
||||
expect(fonts.loaded).toContain("CC Nunito Sans");
|
||||
|
||||
const footer = page.locator("footer");
|
||||
await expect(footer.getByRole("heading", { name: "Service times" })).toBeVisible();
|
||||
await expect(footer).toContainText("Sundays 09:00");
|
||||
await expect(footer).toContainText("1 Church Street");
|
||||
await expect(footer.getByRole("link", { name: "+27161234567" })).toHaveAttribute("href", "tel:+27161234567");
|
||||
await expect(footer.getByRole("link", { name: "Your account" })).toHaveAttribute("href", /127\.0\.0\.1/);
|
||||
await expect(footer.getByRole("link", { name: "Privacy notice" })).toHaveAttribute("href", "/legal/privacy");
|
||||
await expect(footer.getByRole("link", { name: "Terms of Use" })).toBeVisible();
|
||||
await expect(footer.getByRole("button", { name: /cookie/i })).toBeVisible();
|
||||
|
||||
await page.goto(`/events/${seed().events.course}`);
|
||||
await expect(page.getByRole("heading", { name: "E2E Alpha Course" })).toBeVisible();
|
||||
await expect(page.locator("footer").getByRole("heading", { name: "Service times" })).toBeVisible();
|
||||
await page.waitForLoadState("networkidle");
|
||||
const results = await new AxeBuilder({ page }).withTags(TAGS).analyze();
|
||||
expect(results.violations.map((v) => `${v.id}: ${v.nodes.map((n) => n.target.join(" ")).join(", ")}`)).toEqual([]);
|
||||
expect(elsewhere).toEqual([]);
|
||||
});
|
||||
|
||||
test("the dashboard keeps its own fonts, corners and footer", async ({ page }) => {
|
||||
await loginAs(page, "admin");
|
||||
await page.goto("/dashboard");
|
||||
await expect(page.locator("[data-cc-staff]").first()).toBeVisible();
|
||||
await expect(page.locator("main")).toBeVisible();
|
||||
const look = await page.evaluate(() => ({
|
||||
body: getComputedStyle(document.body).fontFamily,
|
||||
radius: getComputedStyle(document.documentElement).getPropertyValue("--radius").trim(),
|
||||
}));
|
||||
expect(look.body).not.toContain("CC ");
|
||||
expect(look.radius).toBe("0.5rem");
|
||||
await expect(page.locator("footer")).toContainText("All rights reserved");
|
||||
});
|
||||
});
|
||||
@@ -5,11 +5,13 @@
|
||||
* differs from the Events site's (localhost), so their cookies stay apart as on two domains.
|
||||
*
|
||||
* Test helpers: POST /test/link { installId, url, secret } links Events, as Connect would;
|
||||
* GET /test/code?to=<email> answers the last code emailed to that address.
|
||||
* GET /test/code?to=<email> answers the last code emailed to that address; POST /test/profile changes
|
||||
* the church profile (3.7.0, church-brand.spec.ts), as an admin's save in Accounts would.
|
||||
*/
|
||||
import http from 'node:http';
|
||||
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||
import { createApp } from '../../../accounts/backend/src/app.ts';
|
||||
import { updateProfile } from '../../../accounts/backend/src/church/profile.ts';
|
||||
import { createCtx } from '../../../accounts/backend/src/context.ts';
|
||||
import { loadConfig } from '../../../accounts/backend/src/lib/config.ts';
|
||||
import { MemoryMessenger } from '../../../accounts/backend/src/lib/messages.ts';
|
||||
@@ -33,6 +35,19 @@ http.createServer((req, res) => {
|
||||
res.writeHead(200, { 'content-type': 'text/plain' }).end(messenger.lastCode(to) ?? '');
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/test/profile') {
|
||||
let body = '';
|
||||
req.on('data', (c) => { body += c; });
|
||||
req.on('end', async () => {
|
||||
try {
|
||||
const church = await updateProfile(ctx, JSON.parse(body));
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(church));
|
||||
} catch (e) {
|
||||
res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({ message: (e as Error).message }));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/test/link') {
|
||||
let body = '';
|
||||
req.on('data', (c) => { body += c; });
|
||||
|
||||
@@ -14,6 +14,8 @@ const nextConfig: NextConfig = {
|
||||
// The end-to-end tests run their own dev server; a separate build folder keeps it
|
||||
// from clashing with one already running.
|
||||
distDir: process.env.NEXT_DIST_DIR || ".next",
|
||||
// The shared fonts and footer (3.7.0) are TypeScript source.
|
||||
transpilePackages: ["@crosscode/ui"],
|
||||
images: {
|
||||
// (images.domains is deprecated in Next 16.)
|
||||
remotePatterns: [{ protocol: 'https', hostname: 'images.unsplash.com' }],
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@@ -12,6 +12,7 @@
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
"@crosscode/ui": "*",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@hookform/resolvers": "^5.2.1",
|
||||
"@radix-ui/react-accordion": "^1.2.11",
|
||||
|
||||
@@ -75,7 +75,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
// Don't render protected content until auth state is known
|
||||
if (loading || !user) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div data-cc-staff className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-sm text-gray-400">Loading…</div>
|
||||
</div>
|
||||
);
|
||||
@@ -88,7 +88,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
// scroll) so the sidebar can be a plain sibling column that never
|
||||
// scrolls — only the content column (main + footer) scrolls internally.
|
||||
return (
|
||||
<div className="h-screen flex flex-col overflow-hidden">
|
||||
<div data-cc-staff className="h-screen flex flex-col overflow-hidden">
|
||||
<Navbar />
|
||||
<LicenceBanner />
|
||||
<ProviderNotices />
|
||||
@@ -99,7 +99,7 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
<Sidebar />
|
||||
<div className="flex-1 min-w-0 flex flex-col overflow-y-auto">
|
||||
<main className="flex-1 p-6 bg-gray-50">{children}</main>
|
||||
<Footer />
|
||||
<Footer plain />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -107,14 +107,14 @@ export default function DashboardLayout({ children }: { children: React.ReactNod
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<div data-cc-staff className="min-h-screen flex flex-col">
|
||||
<Navbar />
|
||||
<LicenceBanner />
|
||||
<ProviderNotices />
|
||||
<PrivacyPrompts />
|
||||
<CommandPalette />
|
||||
<main className="flex-1 p-6 bg-gray-50">{children}</main>
|
||||
<Footer />
|
||||
<Footer plain />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
--input: 214.3 31.8% 91.4%;
|
||||
--ring: 243 75% 59%;
|
||||
|
||||
--radius: 0.5rem;
|
||||
/* The church's corners (3.7.0, @crosscode/ui fonts.css): soft (0.5rem) unless it picked others. */
|
||||
--radius: var(--cc-radius-sm, 0.5rem);
|
||||
|
||||
/* Fallback brand scale (matches the pre-branding-feature default indigo, brand-600 #4F46E5) */
|
||||
--brand-50: #EEF2FF;
|
||||
@@ -73,6 +74,30 @@ html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
/*
|
||||
* The church's fonts (3.7.0, docs/WEBSITE-1.0-PLAN.md §3 and §9): <html> gets
|
||||
* data-cc-fonts from its brand style in Accounts, and @crosscode/ui/fonts.css sets these
|
||||
* variables. Without a pairing they're unset and the page keeps Tailwind's system fonts.
|
||||
* The dashboard and setup screens (data-cc-staff) stay as they are.
|
||||
*/
|
||||
@layer base {
|
||||
body {
|
||||
font-family: var(--cc-font-body, theme("fontFamily.sans"));
|
||||
}
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
font-family: var(--cc-font-heading, inherit);
|
||||
font-variation-settings: var(--cc-heading-variation, normal);
|
||||
}
|
||||
html:has([data-cc-staff]) {
|
||||
--cc-font-body: initial;
|
||||
--cc-font-heading: initial;
|
||||
--cc-heading-variation: initial;
|
||||
--cc-radius-sm: initial;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Accessibility (WCAG 2.2 AA, 1.50.0): a clear focus ring for keyboard users on every
|
||||
* focusable element (mouse clicks don't show it), in the brand colour with a white halo
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { Metadata } from "next";
|
||||
import "@crosscode/ui/fonts.css";
|
||||
import "./globals.css";
|
||||
import { brandAttributes } from "@crosscode/ui";
|
||||
import { AuthProvider } from "@/contexts/AuthContext";
|
||||
import { SiteSettingsProvider } from "@/contexts/SiteSettingsContext";
|
||||
import { ToastProvider } from "@/components/shared/ToastProvider";
|
||||
@@ -11,6 +13,8 @@ import { ImpersonationBanner } from "@/components/shared/ImpersonationBanner";
|
||||
import { SkipLink } from "@/components/layout/SkipLink";
|
||||
import { resolveToApiOrigin } from "@/lib/api";
|
||||
import { getServerSettings } from "@/lib/serverSettings";
|
||||
import { getServerChurch } from "@/lib/serverChurch";
|
||||
import { ChurchProvider } from "@/contexts/ChurchContext";
|
||||
import { buildThemeCssVars } from "@/lib/colorScale";
|
||||
import { appUrl } from "@/lib/siteConfig";
|
||||
|
||||
@@ -49,7 +53,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
}
|
||||
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const settings = await getServerSettings();
|
||||
const [settings, church] = await Promise.all([getServerSettings(), getServerChurch()]);
|
||||
const cssVars = buildThemeCssVars({
|
||||
primary: settings.primary_color || settings.accent_color,
|
||||
secondary: settings.secondary_color,
|
||||
@@ -57,12 +61,15 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
});
|
||||
|
||||
return (
|
||||
<html lang="en">
|
||||
// The church's fonts and corners from Accounts (3.7.0): used by the public pages; the
|
||||
// dashboard and setup screens keep their own (globals.css, data-cc-staff).
|
||||
<html lang="en" {...brandAttributes(church?.branding.style)}>
|
||||
<body>
|
||||
{cssVars && (
|
||||
<style id="brand-theme" dangerouslySetInnerHTML={{ __html: `:root{${cssVars}}` }} />
|
||||
)}
|
||||
<SkipLink />
|
||||
<ChurchProvider church={church}>
|
||||
<SiteSettingsProvider initialSettings={settings}>
|
||||
<AuthProvider>
|
||||
<ToastProvider>
|
||||
@@ -75,6 +82,7 @@ export default async function RootLayout({ children }: { children: React.ReactNo
|
||||
</ToastProvider>
|
||||
</AuthProvider>
|
||||
</SiteSettingsProvider>
|
||||
</ChurchProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
@@ -247,7 +247,7 @@ export default function SetupPage() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gradient-to-br from-brand-50 to-brand-100 flex items-center justify-center p-4">
|
||||
<div data-cc-staff className="min-h-screen bg-gradient-to-br from-brand-50 to-brand-100 flex items-center justify-center p-4">
|
||||
<div className={`bg-white rounded-2xl shadow-lg w-full p-8 transition-all ${step === 3 ? "max-w-4xl" : "max-w-lg"}`}>
|
||||
|
||||
{/* Heading */}
|
||||
|
||||
@@ -1,30 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { ChurchFooter } from "@crosscode/ui";
|
||||
import { appName } from "@/lib/siteConfig";
|
||||
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
||||
import { useChurch } from "@/contexts/ChurchContext";
|
||||
import { CookieSettingsButton } from "@/components/shared/CookieSettingsButton";
|
||||
|
||||
export const Footer = () => {
|
||||
/**
|
||||
* The public pages' footer. With the church's Accounts connected (3.7.0) it's the shared church
|
||||
* footer (as on the Website and Accounts' pages): name and logo, service times, address, contact,
|
||||
* social links and the church's other sites, with this site's terms and cookie settings below.
|
||||
* `plain`: the dashboard's own footer, as before.
|
||||
*/
|
||||
export const Footer = ({ plain = false }: { plain?: boolean }) => {
|
||||
const { settings } = useSiteSettings();
|
||||
const church = useChurch();
|
||||
const displayName = settings.org_name || appName;
|
||||
|
||||
return (
|
||||
<>
|
||||
<footer className="bg-gray-900 text-white py-6 text-center text-sm">
|
||||
<p>© {new Date().getFullYear()} {displayName}. All rights reserved.</p>
|
||||
<div className="mt-2 space-x-4">
|
||||
<Link href="/legal/terms" className="hover:underline text-gray-300">
|
||||
Terms of Use
|
||||
</Link>
|
||||
<Link href="/legal/privacy" className="hover:underline text-gray-300">
|
||||
Privacy Policy
|
||||
</Link>
|
||||
<CookieSettingsButton className="hover:underline text-gray-300" />
|
||||
</div>
|
||||
</footer>
|
||||
{church && !plain ? (
|
||||
<ChurchFooter
|
||||
church={church}
|
||||
current="events"
|
||||
privacyUrl="/legal/privacy"
|
||||
bottom={
|
||||
<>
|
||||
<Link href="/legal/terms" className="hover:underline">Terms of Use</Link>
|
||||
<CookieSettingsButton className="hover:underline" />
|
||||
</>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<footer className="bg-gray-900 text-white py-6 text-center text-sm">
|
||||
<p>© {new Date().getFullYear()} {displayName}. All rights reserved.</p>
|
||||
<div className="mt-2 space-x-4">
|
||||
<Link href="/legal/terms" className="hover:underline text-gray-300">
|
||||
Terms of Use
|
||||
</Link>
|
||||
<Link href="/legal/privacy" className="hover:underline text-gray-300">
|
||||
Privacy Policy
|
||||
</Link>
|
||||
<CookieSettingsButton className="hover:underline text-gray-300" />
|
||||
</div>
|
||||
</footer>
|
||||
)}
|
||||
{/* Spacer so content isn't hidden behind the fixed mobile bottom nav */}
|
||||
<div className="h-16 md:hidden" aria-hidden="true" />
|
||||
</>
|
||||
);
|
||||
};
|
||||
};
|
||||
|
||||
@@ -9,6 +9,8 @@ import { BottomNav } from "./BottomNav";
|
||||
import defaultLogo from "@/app/default_logo.png";
|
||||
import { appName } from "@/lib/siteConfig";
|
||||
import { resolveToApiOrigin } from "@/lib/api";
|
||||
import { productLinks } from "@crosscode/ui";
|
||||
import { useChurch } from "@/contexts/ChurchContext";
|
||||
|
||||
type NavLink = {
|
||||
href: string;
|
||||
@@ -20,6 +22,10 @@ export const Navbar = () => {
|
||||
const { user, loading: authLoading, logout } = useAuth();
|
||||
const { settings, loading: settingsLoading } = useSiteSettings();
|
||||
const pathname = usePathname();
|
||||
const church = useChurch();
|
||||
// The church's other sites from its profile in Accounts (3.7.0): its Website, later its App.
|
||||
// Not on the dashboard, which stays as it is.
|
||||
const otherSites = church && !pathname?.startsWith("/dashboard") ? productLinks(church.links, "events") : [];
|
||||
const displayName = settings.org_name || appName;
|
||||
const logoSrc = settings.logo_url ? resolveToApiOrigin(settings.logo_url) : null;
|
||||
|
||||
@@ -94,6 +100,11 @@ export const Navbar = () => {
|
||||
{link.label}
|
||||
</Link>
|
||||
))}
|
||||
{otherSites.map(site => (
|
||||
<a key={site.href} href={site.href} className="text-sm pb-0.5 border-b-2 border-transparent text-gray-700 transition-colors hover:text-brand-600">
|
||||
{site.label}
|
||||
</a>
|
||||
))}
|
||||
|
||||
{/* Auth links are only known once the token has been validated —
|
||||
rendering nothing here (instead of guessing "logged out") avoids
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext } from "react";
|
||||
import type { Church } from "@crosscode/contracts";
|
||||
|
||||
/** The church profile from Accounts (3.7.0), fetched once by the root layout; null without Accounts. */
|
||||
const ChurchContext = createContext<Church | null>(null);
|
||||
|
||||
export function ChurchProvider({ church, children }: { church: Church | null; children: React.ReactNode }) {
|
||||
return <ChurchContext.Provider value={church}>{children}</ChurchContext.Provider>;
|
||||
}
|
||||
|
||||
export const useChurch = () => useContext(ChurchContext);
|
||||
@@ -74271,6 +74271,648 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/church": {
|
||||
"get": {
|
||||
"tags": [
|
||||
"Site"
|
||||
],
|
||||
"summary": "The church's profile",
|
||||
"description": "The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.\n\n**Who:** Anyone.",
|
||||
"operationId": "getChurch",
|
||||
"parameters": [],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.church/1"
|
||||
},
|
||||
"customerId": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"shortName": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 30
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"timezone": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$"
|
||||
},
|
||||
"locale": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z]{2,3}(-[A-Z]{2})?$"
|
||||
},
|
||||
"branding": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"logoUrl": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"iconUrl": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"colours": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"primary": {
|
||||
"type": "string",
|
||||
"pattern": "^#[0-9a-fA-F]{6}$"
|
||||
},
|
||||
"accent": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^#[0-9a-fA-F]{6}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"primary",
|
||||
"accent"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"style": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"fontPairing": {
|
||||
"default": null,
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"classic",
|
||||
"scholarly",
|
||||
"editorial",
|
||||
"impact",
|
||||
"contemporary",
|
||||
"friendly",
|
||||
"warm",
|
||||
"modern"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"corners": {
|
||||
"default": null,
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"sharp",
|
||||
"soft",
|
||||
"round"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"fontPairing",
|
||||
"corners"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"logoUrl",
|
||||
"iconUrl",
|
||||
"colours"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"campuses": {
|
||||
"maxItems": 50,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"slug": {
|
||||
"type": "string",
|
||||
"maxLength": 100,
|
||||
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"address": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"line1": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"line2": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"suburb": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"city": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 100
|
||||
},
|
||||
"province": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"postalCode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 20
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"country": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Z]{2}$"
|
||||
},
|
||||
"geo": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"lat": {
|
||||
"type": "number",
|
||||
"minimum": -90,
|
||||
"maximum": 90
|
||||
},
|
||||
"lng": {
|
||||
"type": "number",
|
||||
"minimum": -180,
|
||||
"maximum": 180
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"lat",
|
||||
"lng"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"line1",
|
||||
"line2",
|
||||
"suburb",
|
||||
"city",
|
||||
"province",
|
||||
"postalCode",
|
||||
"country",
|
||||
"geo"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"slug",
|
||||
"name",
|
||||
"address"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"serviceTimes": {
|
||||
"maxItems": 100,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"day": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"monday",
|
||||
"tuesday",
|
||||
"wednesday",
|
||||
"thursday",
|
||||
"friday",
|
||||
"saturday",
|
||||
"sunday"
|
||||
]
|
||||
},
|
||||
"time": {
|
||||
"type": "string",
|
||||
"pattern": "^([01]\\d|2[0-3]):[0-5]\\d$"
|
||||
},
|
||||
"label": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"campus": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100,
|
||||
"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"note": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 300
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"day",
|
||||
"time",
|
||||
"label",
|
||||
"campus",
|
||||
"note"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"contact": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 254,
|
||||
"format": "email",
|
||||
"pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"phone": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^\\+[1-9]\\d{6,14}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^\\+[1-9]\\d{6,14}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"address": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"line1": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"line2": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"suburb": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"city": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 100
|
||||
},
|
||||
"province": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"postalCode": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 20
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"country": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Z]{2}$"
|
||||
},
|
||||
"geo": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"lat": {
|
||||
"type": "number",
|
||||
"minimum": -90,
|
||||
"maximum": 90
|
||||
},
|
||||
"lng": {
|
||||
"type": "number",
|
||||
"minimum": -180,
|
||||
"maximum": 180
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"lat",
|
||||
"lng"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"line1",
|
||||
"line2",
|
||||
"suburb",
|
||||
"city",
|
||||
"province",
|
||||
"postalCode",
|
||||
"country",
|
||||
"geo"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"phone",
|
||||
"whatsapp",
|
||||
"address"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"social": {
|
||||
"maxItems": 20,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"network": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"facebook",
|
||||
"instagram",
|
||||
"youtube",
|
||||
"tiktok",
|
||||
"x",
|
||||
"spotify",
|
||||
"whatsapp-channel",
|
||||
"other"
|
||||
]
|
||||
},
|
||||
"url": {
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"network",
|
||||
"url"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"links": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"website": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"events": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"app": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"accounts": {
|
||||
"type": "string",
|
||||
"maxLength": 2048,
|
||||
"format": "uri"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"website",
|
||||
"events",
|
||||
"app",
|
||||
"accounts"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"customerId",
|
||||
"updatedAt",
|
||||
"name",
|
||||
"shortName",
|
||||
"timezone",
|
||||
"locale",
|
||||
"branding",
|
||||
"campuses",
|
||||
"serviceTimes",
|
||||
"contact",
|
||||
"social",
|
||||
"links"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"components": {
|
||||
|
||||
+125
@@ -7760,6 +7760,28 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/church": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
/**
|
||||
* The church's profile
|
||||
* @description The church profile (crosscode.church/1) from the church's Accounts: name, logo, brand style, service times, contact details, social links and its other sites. null when sign-in doesn't go through Accounts yet. Kept for up to 10 minutes, or until Accounts says it changed.
|
||||
*
|
||||
* **Who:** Anyone.
|
||||
*/
|
||||
get: operations["getChurch"];
|
||||
put?: never;
|
||||
post?: never;
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
}
|
||||
export type webhooks = Record<string, never>;
|
||||
export interface components {
|
||||
@@ -40739,4 +40761,107 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
getChurch: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
/** @constant */
|
||||
schema: "crosscode.church/1";
|
||||
/** Format: uuid */
|
||||
customerId: string;
|
||||
/** Format: date-time */
|
||||
updatedAt: string;
|
||||
name: string;
|
||||
shortName: string | null;
|
||||
timezone: string;
|
||||
locale: string;
|
||||
branding: {
|
||||
logoUrl: string | null;
|
||||
iconUrl: string | null;
|
||||
colours: {
|
||||
primary: string;
|
||||
accent: string | null;
|
||||
};
|
||||
style?: {
|
||||
/** @default null */
|
||||
fontPairing: ("classic" | "scholarly" | "editorial" | "impact" | "contemporary" | "friendly" | "warm" | "modern") | null;
|
||||
/** @default null */
|
||||
corners: ("sharp" | "soft" | "round") | null;
|
||||
};
|
||||
};
|
||||
campuses: {
|
||||
slug: string;
|
||||
name: string;
|
||||
address: {
|
||||
line1: string;
|
||||
line2: string | null;
|
||||
suburb: string | null;
|
||||
city: string;
|
||||
province: string | null;
|
||||
postalCode: string | null;
|
||||
country: string;
|
||||
geo: {
|
||||
lat: number;
|
||||
lng: number;
|
||||
} | null;
|
||||
} | null;
|
||||
}[];
|
||||
serviceTimes: {
|
||||
/** @enum {string} */
|
||||
day: "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
|
||||
time: string;
|
||||
label: string | null;
|
||||
campus: string | null;
|
||||
note: string | null;
|
||||
}[];
|
||||
contact: {
|
||||
email: string | null;
|
||||
phone: string | null;
|
||||
whatsapp: string | null;
|
||||
address: {
|
||||
line1: string;
|
||||
line2: string | null;
|
||||
suburb: string | null;
|
||||
city: string;
|
||||
province: string | null;
|
||||
postalCode: string | null;
|
||||
country: string;
|
||||
geo: {
|
||||
lat: number;
|
||||
lng: number;
|
||||
} | null;
|
||||
} | null;
|
||||
};
|
||||
social: {
|
||||
/** @enum {string} */
|
||||
network: "facebook" | "instagram" | "youtube" | "tiktok" | "x" | "spotify" | "whatsapp-channel" | "other";
|
||||
/** Format: uri */
|
||||
url: string;
|
||||
}[];
|
||||
links: {
|
||||
website: string | null;
|
||||
events: string | null;
|
||||
app: string | null;
|
||||
/** Format: uri */
|
||||
accounts: string;
|
||||
};
|
||||
} | null;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Church } from "@crosscode/contracts";
|
||||
import { API_BASE } from "@/lib/api";
|
||||
|
||||
/**
|
||||
* The church profile from the church's Accounts (3.7.0), through the backend's
|
||||
* `GET /api/v2/church`: the brand style for `<html>` and the shared footer. null when Accounts
|
||||
* isn't connected or the backend can't be reached, and the pages look as they always have.
|
||||
* Fetched the same way as getServerSettings, so Next dedupes it within a request.
|
||||
*/
|
||||
export async function getServerChurch(): Promise<Church | null> {
|
||||
if (!API_BASE) return null;
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/api/v2/church`, { next: { revalidate: 60 } });
|
||||
if (!res.ok) return null;
|
||||
return ((await res.json())?.data as Church | null) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
module.exports = {
|
||||
content: [
|
||||
"./src/**/*.{js,ts,jsx,tsx}",
|
||||
// The shared footer (3.7.0)
|
||||
"../../../packages/ui/src/**/*.{ts,tsx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
@@ -47,6 +49,8 @@ module.exports = {
|
||||
// colorScale.ts's buildBrandScale + globals.css for the static
|
||||
// fallback defaults used when no setting is saved yet).
|
||||
brand: {
|
||||
// `brand` alone (the shared footer's links, @crosscode/ui)
|
||||
DEFAULT: "var(--brand-700)",
|
||||
50: "var(--brand-50)",
|
||||
100: "var(--brand-100)",
|
||||
200: "var(--brand-200)",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events",
|
||||
"version": "3.6.1",
|
||||
"version": "3.7.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# this install's PM2 config (made from ecosystem.config.example.cjs by the crosscode script)
|
||||
/ecosystem.config.cjs
|
||||
@@ -0,0 +1,45 @@
|
||||
# Changelog — Church Website
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
- The app's skeleton (WEBSITE-1.0-PLAN §1): an Express + Prisma backend with `/api/health` and
|
||||
`/api/v1/site/status` (Coming soon until the first publish), the content model and its first
|
||||
migration, the section variants per template (§3, decision 16) with the template switch rules, and
|
||||
a Next.js frontend with the Coming soon page, an admin placeholder and `robots.txt`.
|
||||
- **Signing in to the admin through the church's Accounts** (§10), as Cross Events 3.x: the Hub
|
||||
client (protocol v2, product `website`, registers from `HUB_LICENCE_KEY`, heartbeats with
|
||||
aggregate counts), links (`crosscode.link/1`; the Website connects itself to the church's Accounts
|
||||
once the Hub lists it), `/api/auth/signin`, `/callback`, `/me`, `/signout` (then Accounts'
|
||||
sign-out), back-channel logout and Accounts' calls (`user.updated`, `user.export`,
|
||||
`user.deleted`). The Website keeps its own session (`ccw_session`, only a hash stored) and its own
|
||||
roles; the **first Owner** is whoever signs in with the Hub's admin email (`HUB_ADMIN_EMAIL`,
|
||||
verified in Accounts) while the site has none. Owners and Admins sign in with a second step
|
||||
(`two_factor_required_for_admins`, on by default); asked of Accounts once, then explained.
|
||||
- **The four templates and the public site** (§3, §5, §6): Heritage, Bold, Community and Clean,
|
||||
each drawing all 26 section variants its own way, with its headers, homepage order and style
|
||||
settings (section colour, spacing, buttons, image treatment). The church's colours are made safe
|
||||
by the backend (`site/palette.ts`: tints, shades and text colours checked against WCAG AA, with a
|
||||
note for the admin when one is changed); fonts and corners come from its shared brand style, else
|
||||
the template's suggestion. Pages: home, every page kind (visit, about, ministries, leadership,
|
||||
events, messages, give, contact, custom) with its blocks, simple event pages, a real 404,
|
||||
Coming soon from the church profile, `sitemap.xml` and `robots.txt`. Every page has a title,
|
||||
description, canonical, Open Graph and one `<h1>`; home and contact have the church's JSON-LD.
|
||||
Messages load YouTube (youtube-nocookie) or Spotify only when clicked; maps are OpenStreetMap.
|
||||
- **Publishing** (`site/snapshot.ts`): Publish copies the working copy into a numbered version;
|
||||
visitors see the latest (`GET /api/v1/site/content`, with live messages and events and the church
|
||||
profile from Accounts, kept 10 minutes). Section data is checked per type (`site/sections.ts`); a
|
||||
section that doesn't fit is left out, never shown broken. Uploads are served from
|
||||
`/api/uploads/` (SVGs sandboxed).
|
||||
- **The demo church** (`npm run demo -- --template <id>`): Acacia Hill Church, fictional, with
|
||||
illustrated images; refuses to replace a site its admins published unless `--force`.
|
||||
- **End to end** (`npx playwright test` in apps/website, no database): every template's pages pass
|
||||
axe (WCAG 2.2 AA) and the SEO basics; screenshots at phone and desktop in `e2e/screens/`.
|
||||
- The admin page signs people in and out; `/auth/problem` explains a refused sign-in.
|
||||
- **The church's export** (`scripts/export-church.ts`): `export.json` in
|
||||
`crosscode.church-export/1` with its `website` part, for `crosscode export` and uninstall.
|
||||
- **`crosscode`:** `scripts/products/website.sh` (the same hooks as Accounts, ports 5300 / 3300,
|
||||
uploads in the export), `crosscode add <church> website` (needs the church's Accounts; served on
|
||||
`www.<address>`, or the Cross Code address itself), and the installer shared by Accounts and the
|
||||
Website (`install_app`).
|
||||
+26
-1
@@ -1,3 +1,28 @@
|
||||
# Church Website
|
||||
|
||||
Placeholder: the church's public website and its admin. Built in phase 4 of ROADMAP-v3 (see §6 there).
|
||||
The church's public website and its admin (ROADMAP-v3 §6, phase 5; plan and decisions in
|
||||
[docs/WEBSITE-1.0-PLAN.md](../../docs/WEBSITE-1.0-PLAN.md)). Served at `www.<church's address>` (or
|
||||
`<church>.crosscode.co.za`), with the admin at `/admin`, signed in through the church's Accounts.
|
||||
The church picks one of four templates (Heritage, Bold, Community, Clean) and makes it its own with
|
||||
section variants and style settings. Changes are drafts until an editor previews the whole site and
|
||||
presses Publish; until the first publish visitors see Coming soon.
|
||||
|
||||
**State:** being built (2026-11-25): signing in through Accounts, the four templates and the public
|
||||
site, publishing, and the demo church. The admin's editing screens are next. Not released;
|
||||
`website@1.0.0` is tagged when the plan is built.
|
||||
|
||||
**Signing in** (`backend/src/auth/`): the Website registers with the Hub (its install id is its
|
||||
client id at Accounts), links itself to the church's Accounts once the Hub lists it, and signs
|
||||
admins in through `@crosscode/auth-client`. Roles are the Website's own; the first Owner is whoever
|
||||
signs in with the Hub's admin email (`HUB_ADMIN_EMAIL`), verified in Accounts. Locally, set
|
||||
`LINKS_ALLOW_PRIVATE=true` to link to an Accounts on http://localhost.
|
||||
|
||||
- `backend/`: Express + Prisma (ES modules), as Accounts. `npm run dev`, `npm test` (Node's test
|
||||
runner through tsx), `npm run build`. The content model is in `prisma/schema.prisma`; the section
|
||||
variants per template (plan §3, decision 16) in `src/site/variants.ts`.
|
||||
- `frontend/`: Next.js 16. The public site (server-rendered from the latest published version) and
|
||||
the admin.
|
||||
|
||||
Local development: Postgres in `backend/.env` (`DATABASE_URL`, `WEBSITE_URL=http://localhost:3300`),
|
||||
`npx prisma migrate deploy`, then `npm run dev` in both folders (the frontend runs on 3300 and sends
|
||||
/api to the backend on 5300).
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
# What's new in the Church Website
|
||||
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
@@ -0,0 +1,7 @@
|
||||
node_modules/
|
||||
dist/
|
||||
src/generated/
|
||||
.env
|
||||
uploads/
|
||||
exports/
|
||||
/backups/
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "0.1.0",
|
||||
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsx watch src/index.ts",
|
||||
"build": "tsc -p tsconfig.build.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "node --import tsx --test --test-reporter=spec \"tests/**/*.test.ts\"",
|
||||
"postinstall": "prisma generate",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"prisma:status": "prisma migrate status",
|
||||
"demo": "tsx scripts/demo.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
"@crosscode/contracts": "*",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^5.3.0",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/express": "^5.0.6",
|
||||
"@types/node": "^20.19.43",
|
||||
"@types/supertest": "^7.2.1",
|
||||
"prisma": "^7.10.1",
|
||||
"supertest": "^7.3.1",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// Prisma CLI config (migrate, generate). Prisma 7 doesn't load .env or read the URL from the schema.
|
||||
import 'dotenv/config';
|
||||
import { defineConfig } from 'prisma/config';
|
||||
|
||||
export default defineConfig({
|
||||
schema: 'prisma/schema.prisma',
|
||||
migrations: { path: 'prisma/migrations' },
|
||||
// process.env, so `prisma generate` works on a machine with no DATABASE_URL (it never connects).
|
||||
datasource: { url: process.env.DATABASE_URL ?? '' },
|
||||
});
|
||||
@@ -0,0 +1,336 @@
|
||||
-- Church Website 1.0.0: the first schema (docs/WEBSITE-1.0-PLAN.md §1, §2, §4, §10).
|
||||
|
||||
-- CreateSchema
|
||||
CREATE SCHEMA IF NOT EXISTS "public";
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "WebsiteRole" AS ENUM ('owner', 'admin', 'editor', 'ministry_leader', 'viewer');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "PageKind" AS ENUM ('home', 'visit', 'about', 'leadership', 'ministries', 'events', 'messages', 'give', 'contact', 'terms', 'safeguarding', 'custom');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "MessageSource" AS ENUM ('youtube_feed', 'youtube', 'spotify');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SiteDesign" (
|
||||
"id" INTEGER NOT NULL DEFAULT 1,
|
||||
"template" TEXT NOT NULL,
|
||||
"variants" JSONB NOT NULL,
|
||||
"home" JSONB NOT NULL,
|
||||
"style" JSONB NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "SiteDesign_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Page" (
|
||||
"id" TEXT NOT NULL,
|
||||
"kind" "PageKind" NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"seoTitle" TEXT,
|
||||
"description" TEXT,
|
||||
"navLabel" TEXT,
|
||||
"inNav" BOOLEAN NOT NULL DEFAULT true,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"imageId" TEXT,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Page_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Section" (
|
||||
"id" TEXT NOT NULL,
|
||||
"pageId" TEXT NOT NULL,
|
||||
"type" TEXT NOT NULL,
|
||||
"variant" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"hidden" BOOLEAN NOT NULL DEFAULT false,
|
||||
"data" JSONB NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Section_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Ministry" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"summary" TEXT,
|
||||
"body" TEXT,
|
||||
"imageId" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Ministry_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Leader" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" TEXT,
|
||||
"bio" TEXT,
|
||||
"photoId" TEXT,
|
||||
"position" INTEGER NOT NULL DEFAULT 0,
|
||||
"archivedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Leader_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MessageSeries" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"summary" TEXT,
|
||||
"imageId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "MessageSeries_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Message" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"date" TIMESTAMP(3) NOT NULL,
|
||||
"source" "MessageSource" NOT NULL,
|
||||
"mediaUrl" TEXT NOT NULL,
|
||||
"externalId" TEXT,
|
||||
"thumbnailUrl" TEXT,
|
||||
"speaker" TEXT,
|
||||
"passage" TEXT,
|
||||
"notes" TEXT,
|
||||
"seriesId" TEXT,
|
||||
"hidden" BOOLEAN NOT NULL DEFAULT false,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "Message_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SimpleEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"slug" TEXT NOT NULL,
|
||||
"title" TEXT NOT NULL,
|
||||
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||
"endsAt" TIMESTAMP(3),
|
||||
"allDay" BOOLEAN NOT NULL DEFAULT false,
|
||||
"timezone" TEXT NOT NULL DEFAULT 'Africa/Johannesburg',
|
||||
"location" TEXT,
|
||||
"description" TEXT,
|
||||
"imageId" TEXT,
|
||||
"link" TEXT,
|
||||
"cancelled" BOOLEAN NOT NULL DEFAULT false,
|
||||
"publishedAt" TIMESTAMP(3),
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"updatedBy" TEXT,
|
||||
|
||||
CONSTRAINT "SimpleEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ImportedEvent" (
|
||||
"id" TEXT NOT NULL,
|
||||
"originProduct" TEXT NOT NULL,
|
||||
"originId" TEXT NOT NULL,
|
||||
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||
"data" JSONB NOT NULL,
|
||||
"syncedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "ImportedEvent_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "MediaAsset" (
|
||||
"id" TEXT NOT NULL,
|
||||
"filename" TEXT NOT NULL,
|
||||
"mime" TEXT NOT NULL,
|
||||
"bytes" INTEGER NOT NULL,
|
||||
"width" INTEGER,
|
||||
"height" INTEGER,
|
||||
"alt" TEXT NOT NULL DEFAULT '',
|
||||
"sizes" JSONB,
|
||||
"uploadedBy" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "MediaAsset_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "SiteVersion" (
|
||||
"id" TEXT NOT NULL,
|
||||
"number" INTEGER NOT NULL,
|
||||
"snapshot" JSONB NOT NULL,
|
||||
"note" TEXT,
|
||||
"publishedBy" TEXT NOT NULL,
|
||||
"publishedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "SiteVersion_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "PreviewLink" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"createdBy" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"revokedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "PreviewLink_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "WebsiteUser" (
|
||||
"id" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" "WebsiteRole" NOT NULL,
|
||||
"ministryId" TEXT,
|
||||
"lastSignInAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "WebsiteUser_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Session" (
|
||||
"id" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"sid" TEXT,
|
||||
"mfa" BOOLEAN NOT NULL DEFAULT false,
|
||||
"idToken" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"lastSeenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "Session_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "ProductLink" (
|
||||
"installId" TEXT NOT NULL,
|
||||
"product" TEXT NOT NULL,
|
||||
"url" TEXT NOT NULL,
|
||||
"publicKey" TEXT NOT NULL,
|
||||
"secret" TEXT NOT NULL,
|
||||
"connectedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"connectedById" TEXT,
|
||||
"lastSyncError" TEXT,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "ProductLink_pkey" PRIMARY KEY ("installId")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "LinkNonce" (
|
||||
"nonce" TEXT NOT NULL,
|
||||
"seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "LinkNonce_pkey" PRIMARY KEY ("nonce")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AuditLog" (
|
||||
"id" TEXT NOT NULL,
|
||||
"actorId" TEXT,
|
||||
"actorRole" TEXT NOT NULL,
|
||||
"action" TEXT NOT NULL,
|
||||
"targetType" TEXT NOT NULL,
|
||||
"targetId" TEXT,
|
||||
"metadata" JSONB,
|
||||
"ip" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AppSetting" (
|
||||
"key" TEXT NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "AppSetting_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Page_slug_key" ON "Page"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Page_kind_idx" ON "Page"("kind");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Section_pageId_position_idx" ON "Section"("pageId", "position");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Ministry_slug_key" ON "Ministry"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "MessageSeries_slug_key" ON "MessageSeries"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Message_slug_key" ON "Message"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Message_externalId_key" ON "Message"("externalId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Message_date_idx" ON "Message"("date");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SimpleEvent_slug_key" ON "SimpleEvent"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "SimpleEvent_startsAt_idx" ON "SimpleEvent"("startsAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "ImportedEvent_startsAt_idx" ON "ImportedEvent"("startsAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "ImportedEvent_originProduct_originId_key" ON "ImportedEvent"("originProduct", "originId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "SiteVersion_number_key" ON "SiteVersion"("number");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "PreviewLink_tokenHash_key" ON "PreviewLink"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Session_tokenHash_key" ON "Session"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Session_userId_idx" ON "Session"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Session_sid_idx" ON "Session"("sid");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Section" ADD CONSTRAINT "Section_pageId_fkey" FOREIGN KEY ("pageId") REFERENCES "Page"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "Message" ADD CONSTRAINT "Message_seriesId_fkey" FOREIGN KEY ("seriesId") REFERENCES "MessageSeries"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "WebsiteUser" ADD CONSTRAINT "WebsiteUser_ministryId_fkey" FOREIGN KEY ("ministryId") REFERENCES "Ministry"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,301 @@
|
||||
// Church Website 1.0.0 (docs/WEBSITE-1.0-PLAN.md). One database per church.
|
||||
//
|
||||
// The content tables are the **working copy** the admin edits (§4). Publishing writes an immutable
|
||||
// snapshot of them to SiteVersion; visitors always see the latest SiteVersion, the preview sees the
|
||||
// working copy. Shared facts (name, logo, colours, service times, contact, the brand style) are the
|
||||
// church profile's, in Accounts (§2), and are never stored here.
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client"
|
||||
// Its own output, so hoisted clients of other apps never overwrite it (EVENTS-2.2-PLAN §2).
|
||||
output = "../src/generated/prisma"
|
||||
moduleFormat = "esm"
|
||||
importFileExtension = "js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
}
|
||||
|
||||
/// Website roles (§10). Held here, per product: an Events role gives nothing in the Website.
|
||||
enum WebsiteRole {
|
||||
owner
|
||||
admin
|
||||
editor
|
||||
ministry_leader
|
||||
viewer
|
||||
}
|
||||
|
||||
enum PageKind {
|
||||
home
|
||||
visit
|
||||
about
|
||||
leadership
|
||||
ministries
|
||||
events
|
||||
messages
|
||||
give
|
||||
contact
|
||||
terms
|
||||
safeguarding
|
||||
custom
|
||||
}
|
||||
|
||||
enum MessageSource {
|
||||
youtube_feed
|
||||
youtube
|
||||
spotify
|
||||
}
|
||||
|
||||
/// The site's design in the working copy (one row, id 1): template, section variants, homepage
|
||||
/// order and the Website-only style settings (src/site/variants.ts). Fonts and corners are shared.
|
||||
model SiteDesign {
|
||||
id Int @id @default(1)
|
||||
template String
|
||||
variants Json
|
||||
home Json
|
||||
style Json
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
}
|
||||
|
||||
/// A page: the fixed ones (§6) and custom pages built from blocks.
|
||||
model Page {
|
||||
id String @id @default(uuid())
|
||||
kind PageKind
|
||||
slug String @unique
|
||||
title String
|
||||
/// Per-page SEO (ROADMAP-v3 §11); null uses the generated one.
|
||||
seoTitle String?
|
||||
description String?
|
||||
navLabel String?
|
||||
inNav Boolean @default(true)
|
||||
position Int @default(0)
|
||||
imageId String?
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
sections Section[]
|
||||
|
||||
@@index([kind])
|
||||
}
|
||||
|
||||
/// A section or block on a page. `data` is validated with the zod schema for its `type`; `variant`
|
||||
/// is one of that type's ids. Content is never tied to a template (§2).
|
||||
model Section {
|
||||
id String @id @default(uuid())
|
||||
pageId String
|
||||
page Page @relation(fields: [pageId], references: [id], onDelete: Cascade)
|
||||
type String
|
||||
variant String?
|
||||
position Int @default(0)
|
||||
hidden Boolean @default(false)
|
||||
data Json
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@index([pageId, position])
|
||||
}
|
||||
|
||||
model Ministry {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
name String
|
||||
summary String?
|
||||
body String?
|
||||
imageId String?
|
||||
position Int @default(0)
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
leaders WebsiteUser[]
|
||||
}
|
||||
|
||||
model Leader {
|
||||
id String @id @default(uuid())
|
||||
name String
|
||||
role String?
|
||||
bio String?
|
||||
photoId String?
|
||||
position Int @default(0)
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
}
|
||||
|
||||
model MessageSeries {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
title String
|
||||
summary String?
|
||||
imageId String?
|
||||
createdAt DateTime @default(now())
|
||||
messages Message[]
|
||||
}
|
||||
|
||||
/// A message (sermon), from the YouTube feed or added by hand (§7). Published on its own, not with
|
||||
/// the site's Publish (decision 9). Audio and video are linked, never uploaded.
|
||||
model Message {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
title String
|
||||
date DateTime
|
||||
source MessageSource
|
||||
mediaUrl String
|
||||
/// The YouTube video id or Spotify episode id: one message per video, whichever way it came in.
|
||||
externalId String? @unique
|
||||
thumbnailUrl String?
|
||||
speaker String?
|
||||
passage String?
|
||||
notes String?
|
||||
seriesId String?
|
||||
series MessageSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
|
||||
hidden Boolean @default(false)
|
||||
publishedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@index([date])
|
||||
}
|
||||
|
||||
/// A simple event made in the Website (§8). Registrations and payments are only Cross Events'.
|
||||
model SimpleEvent {
|
||||
id String @id @default(uuid())
|
||||
slug String @unique
|
||||
title String
|
||||
startsAt DateTime
|
||||
endsAt DateTime?
|
||||
allDay Boolean @default(false)
|
||||
timezone String @default("Africa/Johannesburg")
|
||||
location String?
|
||||
description String?
|
||||
imageId String?
|
||||
link String?
|
||||
cancelled Boolean @default(false)
|
||||
publishedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
updatedBy String?
|
||||
|
||||
@@index([startsAt])
|
||||
}
|
||||
|
||||
/// A read-only copy of a sibling's event from the feed (crosscode.event/1, ROADMAP-v3 §4).
|
||||
model ImportedEvent {
|
||||
id String @id @default(uuid())
|
||||
originProduct String
|
||||
originId String
|
||||
startsAt DateTime
|
||||
data Json
|
||||
syncedAt DateTime @default(now())
|
||||
|
||||
@@unique([originProduct, originId])
|
||||
@@index([startsAt])
|
||||
}
|
||||
|
||||
/// An upload: counted towards storage (§10) until neither the working copy nor the last 10
|
||||
/// published versions use it.
|
||||
model MediaAsset {
|
||||
id String @id @default(uuid())
|
||||
filename String
|
||||
mime String
|
||||
bytes Int
|
||||
width Int?
|
||||
height Int?
|
||||
alt String @default("")
|
||||
/// The resized files (WebP and JPEG per width) and their sizes, counted with `bytes`.
|
||||
sizes Json?
|
||||
uploadedBy String?
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// A published version: an immutable snapshot of the working copy (§4). Restore copies one back.
|
||||
model SiteVersion {
|
||||
id String @id @default(uuid())
|
||||
number Int @unique
|
||||
snapshot Json
|
||||
note String?
|
||||
publishedBy String
|
||||
publishedAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// A shared preview link (§4): the token is stored hashed, expires after 7 days or when revoked.
|
||||
model PreviewLink {
|
||||
id String @id @default(uuid())
|
||||
tokenHash String @unique
|
||||
createdBy String
|
||||
createdAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
revokedAt DateTime?
|
||||
}
|
||||
|
||||
/// Someone who can use the admin: keyed by their account's `sub` from Accounts.
|
||||
model WebsiteUser {
|
||||
id String @id
|
||||
email String
|
||||
name String
|
||||
role WebsiteRole
|
||||
/// A Ministry leader edits only their own ministry.
|
||||
ministryId String?
|
||||
ministry Ministry? @relation(fields: [ministryId], references: [id], onDelete: SetNull)
|
||||
lastSignInAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
/// A signed-in admin session (the `ccw_session` cookie holds the token; only its SHA-256 is kept).
|
||||
/// `sid` is Accounts' session id, so a back-channel logout ends the matching sessions.
|
||||
model Session {
|
||||
id String @id @default(uuid())
|
||||
tokenHash String @unique
|
||||
userId String
|
||||
sid String?
|
||||
/// Whether Accounts did a second step for this sign-in (`amr` has `mfa`).
|
||||
mfa Boolean @default(false)
|
||||
/// The ID token (encrypted), for "Sign out" at Accounts (`id_token_hint`).
|
||||
idToken String?
|
||||
createdAt DateTime @default(now())
|
||||
lastSeenAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
|
||||
@@index([userId])
|
||||
@@index([sid])
|
||||
}
|
||||
|
||||
/// A link to another of the church's products (`crosscode.link/1`, as Events 2.4): Accounts, for
|
||||
/// signing in, and Events / the App for the event feed. The secret is encrypted.
|
||||
model ProductLink {
|
||||
installId String @id
|
||||
product String
|
||||
url String
|
||||
publicKey String
|
||||
secret String
|
||||
connectedAt DateTime @default(now())
|
||||
connectedById String?
|
||||
lastSyncError String?
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
|
||||
/// Nonces of link messages seen in the last hour (replays are refused).
|
||||
model LinkNonce {
|
||||
nonce String @id
|
||||
seenAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model AuditLog {
|
||||
id String @id @default(uuid())
|
||||
actorId String?
|
||||
actorRole String
|
||||
action String
|
||||
targetType String
|
||||
targetId String?
|
||||
metadata Json?
|
||||
ip String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
model AppSetting {
|
||||
key String @id
|
||||
value String
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* Loads the demo church (src/demo/demoChurch.ts) into a template and publishes it.
|
||||
*
|
||||
* npm run demo -- --template heritage|bold|community|clean [--force]
|
||||
*
|
||||
* It replaces the site's content, so a site that has been published needs --force.
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { websiteTemplateSchema } from '@crosscode/contracts';
|
||||
import { PrismaClient } from '../src/generated/prisma/client.js';
|
||||
import { createCtx } from '../src/context.js';
|
||||
import { loadDemo } from '../src/demo/demoChurch.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
|
||||
const arg = (name: string) => {
|
||||
const i = process.argv.indexOf(`--${name}`);
|
||||
return i > 0 ? process.argv[i + 1] : undefined;
|
||||
};
|
||||
const template = websiteTemplateSchema.safeParse(arg('template') ?? 'heritage');
|
||||
if (!template.success) {
|
||||
console.error('Usage: npm run demo -- --template heritage|bold|community|clean [--force]');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||
const ctx = createCtx(loadConfig(), db);
|
||||
const published = await db.siteVersion.findFirst({ where: { NOT: { publishedBy: 'demo' } } });
|
||||
if (published && !process.argv.includes('--force')) {
|
||||
console.error('This site has been published by its admins: loading the demo would replace their content. Add --force to do it anyway.');
|
||||
await db.$disconnect();
|
||||
process.exit(1);
|
||||
}
|
||||
const version = await loadDemo(ctx, template.data);
|
||||
console.log(`Demo church loaded on ${template.data} and published (version ${version.number}).`);
|
||||
await db.$disconnect();
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* The Website's part of a church's export (`crosscode export` / uninstall): `export.json` in
|
||||
* --out-dir (src/export/churchExport.ts). The crosscode script adds the uploads next to it.
|
||||
*
|
||||
* npx tsx scripts/export-church.ts --out-dir <dir>
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from '../src/generated/prisma/client.js';
|
||||
import { createCtx } from '../src/context.js';
|
||||
import { buildExport } from '../src/export/churchExport.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
|
||||
const i = process.argv.indexOf('--out-dir');
|
||||
const out = i > 0 ? process.argv[i + 1] : null;
|
||||
if (!out) {
|
||||
console.error('Usage: export-church.ts --out-dir <dir>');
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||
const data = await buildExport(createCtx(loadConfig(), db));
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
fs.writeFileSync(path.join(out, 'export.json'), JSON.stringify(data, null, 2), { mode: 0o600 });
|
||||
console.log(` export.json: ${data.website!.pages.length} pages, ${data.website!.messages.length} messages, ${data.files.length} files`);
|
||||
await db.$disconnect();
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* The Express app (docs/WEBSITE-1.0-PLAN.md §1). Everything is under /api, so the site and its API
|
||||
* share one address (as Events and Accounts): nginx sends /api to this backend and the rest to Next.js.
|
||||
*
|
||||
* /api/health version and database, for monitoring, `crosscode deploy` and the Hub
|
||||
* /api/v1/site/… the public site (what visitors see: the latest published version)
|
||||
* /api/uploads/… the church's uploaded images
|
||||
* /api/auth/… signing in to the admin through the church's Accounts
|
||||
* /api/accounts/v1/events Accounts' signed calls (user.updated / export / deleted)
|
||||
* /api/links/v1/… Connect and Disconnect with the church's other products
|
||||
* /api/v1/admin/… the admin (signed in, by role)
|
||||
*
|
||||
* To come (§1): the admin's content, publish and preview links, uploading, the event feed.
|
||||
*/
|
||||
import path from 'node:path';
|
||||
import express from 'express';
|
||||
import type { Ctx } from './context.js';
|
||||
import { authRouter } from './auth/routes.js';
|
||||
import { requireRole } from './auth/sessions.js';
|
||||
import { dbUp } from './hub/client.js';
|
||||
import { ApiError, handle, sendError } from './http.js';
|
||||
import { appVersion } from './lib/version.js';
|
||||
import { linksRouter } from './links/routes.js';
|
||||
import { defaultUploadDir } from './demo/demoChurch.js';
|
||||
import { siteContent } from './site/content.js';
|
||||
import { siteStatus } from './site/status.js';
|
||||
|
||||
export function createApp(ctx: Ctx) {
|
||||
const app = express();
|
||||
app.disable('x-powered-by');
|
||||
if (ctx.config.trustProxySetting !== false) app.set('trust proxy', ctx.config.trustProxySetting);
|
||||
|
||||
app.use((_req, res, next) => {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||
// The API is never a page of its own in search results; the public pages are (ROADMAP-v3 §11).
|
||||
res.setHeader('X-Robots-Tag', 'noindex');
|
||||
next();
|
||||
});
|
||||
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
const db = await dbUp(ctx);
|
||||
res.status(db ? 200 : 503).json({ status: db ? 'ok' : 'error', product: 'website', version: appVersion(), db });
|
||||
});
|
||||
|
||||
const site = express.Router();
|
||||
site.get('/status', handle(() => siteStatus(ctx)));
|
||||
site.get('/content', handle(async (_req, res) => {
|
||||
// Short: Publish shows within a minute even where a proxy caches.
|
||||
res.set('Cache-Control', 'public, max-age=30');
|
||||
return siteContent(ctx);
|
||||
}));
|
||||
app.use('/api/v1/site', site);
|
||||
|
||||
// Uploaded files: never a directory listing, never outside the folder (express.static checks).
|
||||
app.use('/api/uploads', express.static(path.resolve(ctx.config.uploadDir ?? defaultUploadDir()), {
|
||||
index: false, dotfiles: 'deny', fallthrough: false, maxAge: '7d',
|
||||
setHeaders: (res) => {
|
||||
// An uploaded SVG is shown as an image, never run as a page.
|
||||
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||
},
|
||||
}));
|
||||
|
||||
app.use('/api', authRouter(ctx));
|
||||
app.use('/api', linksRouter(ctx));
|
||||
|
||||
const admin = express.Router();
|
||||
admin.use(express.json({ limit: '256kb' }));
|
||||
admin.use(requireRole(ctx, 'viewer'));
|
||||
admin.get('/me', handle(async (req) => ({ user: req.signed!.user, mfa: req.signed!.mfa })));
|
||||
app.use('/api/v1/admin', admin);
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such API endpoint.' } });
|
||||
});
|
||||
|
||||
app.use((err: unknown, _req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||
if (res.headersSent) return next(err);
|
||||
if (err instanceof ApiError) return sendError(res, err);
|
||||
const e = err as { type?: string; status?: number };
|
||||
if (e?.type === 'entity.parse.failed') return sendError(res, new ApiError(400, 'VALIDATION', 'The body must be JSON.'));
|
||||
// A missing upload (express.static), or another known client error.
|
||||
if (typeof e?.status === 'number' && e.status >= 400 && e.status < 500) return sendError(res, new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : 'BAD_REQUEST', e.status === 404 ? 'There is no such file.' : "That request isn't valid."));
|
||||
return sendError(res, err);
|
||||
});
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* The church's Accounts, as this site's OIDC client (WEBSITE-1.0-PLAN §1, §10), built on
|
||||
* `@crosscode/auth-client` from the Accounts link (links/connect.ts). Its address is the one the
|
||||
* Hub listed; the client id is this site's Hub install id and the client secret comes from the
|
||||
* link's secret, so there's no `.env` setting for any of it (as Cross Events 3.x).
|
||||
*/
|
||||
import type * as AuthClient from '@crosscode/auth-client';
|
||||
import type { AccountsClient } from '@crosscode/auth-client';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
|
||||
export type AuthClientModule = typeof AuthClient;
|
||||
|
||||
export const loadAuthClient = (): Promise<AuthClientModule> => import('@crosscode/auth-client');
|
||||
|
||||
export class AccountsUnavailable extends ApiError {
|
||||
constructor(message: string) {
|
||||
super(503, 'ACCOUNTS_UNAVAILABLE', message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The Accounts link, or null while the Website isn't linked to Accounts. */
|
||||
export async function accountsLink(ctx: Ctx) {
|
||||
return ctx.db.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
|
||||
}
|
||||
|
||||
const cache = new WeakMap<Ctx, { key: string; client: Promise<AccountsClient> }>();
|
||||
|
||||
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
|
||||
export async function accounts(ctx: Ctx): Promise<AccountsClient> {
|
||||
const link = await accountsLink(ctx);
|
||||
if (!link) throw new AccountsUnavailable('The Website isn\'t linked to the church\'s Accounts yet. It links by itself within 15 minutes of being installed.');
|
||||
const clientId = await ctx.settings.get('hub_install_id');
|
||||
if (!clientId) throw new AccountsUnavailable('The Website isn\'t connected to the Hub yet.');
|
||||
const key = `${link.installId}|${link.updatedAt.getTime()}|${clientId}|${ctx.config.publicUrl}`;
|
||||
let hit = cache.get(ctx);
|
||||
if (!hit || hit.key !== key) {
|
||||
const client = ctx.authClient().then((m) => m.accountsClient({
|
||||
accountsUrl: link.url,
|
||||
productUrl: ctx.config.publicUrl,
|
||||
clientId,
|
||||
linkSecret: ctx.secrets.decrypt(link.secret),
|
||||
allowInsecure: !ctx.config.production && link.url.startsWith('http:'),
|
||||
}));
|
||||
// A failed discovery (Accounts down for a moment) is tried again next time.
|
||||
client.catch(() => { if (cache.get(ctx)?.key === key) cache.delete(ctx); });
|
||||
hit = { key, client };
|
||||
cache.set(ctx, hit);
|
||||
}
|
||||
try {
|
||||
return await hit.client;
|
||||
} catch (e) {
|
||||
throw new AccountsUnavailable(`The church's Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* Signing in to the Website's admin through the church's Accounts (WEBSITE-1.0-PLAN §10, as Cross
|
||||
* Events 3.x), under /api:
|
||||
*
|
||||
* GET /auth/signin?returnTo=…[&mfa=1] PKCE + state in a short-lived cookie, then off to Accounts
|
||||
* GET /auth/callback back from Accounts: the Website's own session, then returnTo
|
||||
* GET /auth/me who's signed in (the admin pages ask)
|
||||
* POST /auth/signout ends this session, then Accounts' sign-out (all the church's sites)
|
||||
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
|
||||
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
|
||||
*
|
||||
* Who may use the admin is the Website's own business (roles are never in the claims). The first
|
||||
* Owner is whoever signs in with the church's admin email from the Hub (HUB_ADMIN_EMAIL), verified
|
||||
* in Accounts, while the site has no Owner; everyone else is added by an Owner or Admin.
|
||||
*/
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import { ACCOUNTS_CALL_PATH, IDENTITY_SCHEMA, OIDC_CLIENT_PATHS, safeReturnPath, type AccountsCall, type IdentityClaims, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { WebsiteRole } from '../generated/prisma/client.js';
|
||||
import { handle, sendError } from '../http.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { accounts, AccountsUnavailable } from './accounts.js';
|
||||
import { cookieOptions, currentSession, needsTwoFactor, readCookies, SESSION_COOKIE, startSession } from './sessions.js';
|
||||
|
||||
const PENDING_COOKIE = 'ccw_signin';
|
||||
const MFA_COOKIE = 'ccw_signin_mfa';
|
||||
const COOKIE_PATH = '/api/auth';
|
||||
const PENDING_MINUTES = 10;
|
||||
|
||||
/** A page of this site, absolute (in development the API and the pages are on different ports). */
|
||||
const page = (ctx: Ctx, path: string) => `${ctx.config.publicUrl}${path}`;
|
||||
|
||||
/** The problem page: a short reason and "Try again" with the same return path. */
|
||||
const problem = (ctx: Ctx, res: Response, code: string, returnTo = '/admin') =>
|
||||
res.redirect(303, page(ctx, `/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
|
||||
|
||||
type UserRow = { id: string; name: string; email: string; role: WebsiteRole };
|
||||
|
||||
/**
|
||||
* The Website user for a sign-in: by `sub`; else the first Owner, when the site has none and this is
|
||||
* the Hub's admin email (verified); else nobody (no access to this admin).
|
||||
*/
|
||||
export async function userForClaims(ctx: Ctx, claims: IdentityClaims): Promise<{ user: UserRow | null; created?: boolean }> {
|
||||
const known = await ctx.db.websiteUser.findUnique({ where: { id: claims.sub } });
|
||||
if (known) {
|
||||
const user = await ctx.db.websiteUser.update({ where: { id: known.id }, data: { name: claims.name, email: claims.email.toLowerCase(), lastSignInAt: ctx.now() } });
|
||||
return { user };
|
||||
}
|
||||
const adminEmail = ctx.config.hubAdminEmail;
|
||||
if (!adminEmail || !claims.email_verified || claims.email.toLowerCase() !== adminEmail) return { user: null };
|
||||
if (await ctx.db.websiteUser.findFirst({ where: { role: 'owner' } })) return { user: null };
|
||||
const user = await ctx.db.websiteUser.create({
|
||||
data: { id: claims.sub, name: claims.name, email: claims.email.toLowerCase(), role: 'owner', lastSignInAt: ctx.now() },
|
||||
});
|
||||
return { user, created: true };
|
||||
}
|
||||
|
||||
export function authRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
|
||||
r.get('/auth/signin', async (req, res) => {
|
||||
const returnTo = safeReturnPath(req.query.returnTo);
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
const requireTwoFactor = req.query.mfa === '1';
|
||||
const { url, cookie } = await auth.startSignIn(returnTo, { requireTwoFactor });
|
||||
const opts = { ...cookieOptions(ctx, COOKIE_PATH), maxAge: PENDING_MINUTES * 60e3 };
|
||||
res.cookie(PENDING_COOKIE, cookie, opts);
|
||||
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', opts);
|
||||
else res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
return res.redirect(303, url);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return problem(ctx, res, 'ACCOUNTS_UNAVAILABLE', returnTo);
|
||||
console.error('[auth] Starting a sign-in failed:', e);
|
||||
return problem(ctx, res, 'SIGNIN_FAILED', returnTo);
|
||||
}
|
||||
});
|
||||
|
||||
r.get(OIDC_CLIENT_PATHS.callback.replace(/^\/api/, ''), async (req, res) => {
|
||||
const cookies = readCookies(req);
|
||||
const askedForTwoFactor = cookies[MFA_COOKIE] === '1';
|
||||
res.clearCookie(PENDING_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
res.clearCookie(MFA_COOKIE, cookieOptions(ctx, COOKIE_PATH));
|
||||
let result: Awaited<ReturnType<Awaited<ReturnType<typeof accounts>>['finishSignIn']>>;
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
result = await auth.finishSignIn(new URL(req.originalUrl, ctx.config.publicUrl), cookies[PENDING_COOKIE]);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return problem(ctx, res, 'ACCOUNTS_UNAVAILABLE');
|
||||
const code = (e as { code?: string }).code;
|
||||
// The person pressed Cancel at Accounts, or the pending cookie expired.
|
||||
if (req.query.error === 'access_denied') return res.redirect(303, page(ctx, '/'));
|
||||
return problem(ctx, res, code === 'NO_PENDING' ? 'EXPIRED' : 'SIGNIN_FAILED');
|
||||
}
|
||||
const { claims, returnTo, idToken } = result;
|
||||
const { user, created } = await userForClaims(ctx, claims);
|
||||
if (!user) {
|
||||
await audit(ctx, { actorId: claims.sub, actorRole: 'none', action: 'admin_sign_in_refused', targetType: 'website_user', targetId: claims.sub, ip: clientIp(req) });
|
||||
return problem(ctx, res, 'NO_ACCESS', returnTo);
|
||||
}
|
||||
const mfa = claims.amr.includes('mfa');
|
||||
if (!mfa && (await needsTwoFactor(ctx, user.role))) {
|
||||
// Once: ask Accounts again with a second step. If it still comes back without one, say why.
|
||||
if (askedForTwoFactor) return problem(ctx, res, 'TWO_FACTOR_NEEDED', returnTo);
|
||||
return res.redirect(303, page(ctx, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`));
|
||||
}
|
||||
// Accounts' session id, when its token carries one (not part of crosscode.identity/1's claims).
|
||||
const sid = (claims as unknown as { sid?: string }).sid ?? null;
|
||||
await startSession(ctx, res, { userId: user.id, sid, mfa, idToken });
|
||||
await audit(ctx, { actorId: user.id, actorRole: user.role, action: created ? 'first_owner_signed_in' : 'admin_signed_in', targetType: 'website_user', targetId: user.id, ip: clientIp(req) });
|
||||
return res.redirect(303, page(ctx, returnTo));
|
||||
});
|
||||
|
||||
r.get('/auth/me', handle(async (req, res) => {
|
||||
const s = await currentSession(ctx, req);
|
||||
if (!s) {
|
||||
res.status(401).json({ error: { code: 'SIGNED_OUT', message: 'Please sign in.' } });
|
||||
return undefined;
|
||||
}
|
||||
return { user: s.user, mfa: s.mfa };
|
||||
}));
|
||||
|
||||
r.post('/auth/signout', async (req, res) => {
|
||||
const s = await currentSession(ctx, req).catch(() => null);
|
||||
res.clearCookie(SESSION_COOKIE, cookieOptions(ctx));
|
||||
if (s) {
|
||||
await ctx.db.session.delete({ where: { id: s.sessionId } }).catch(() => {});
|
||||
await audit(ctx, { actorId: s.user.id, actorRole: s.user.role, action: 'admin_signed_out', targetType: 'website_user', targetId: s.user.id, ip: clientIp(req) });
|
||||
}
|
||||
// Then Accounts, so the person is signed out of all the church's sites and comes back here.
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
return res.redirect(303, auth.signOutUrl(s?.idToken ?? undefined));
|
||||
} catch {
|
||||
return res.redirect(303, page(ctx, '/'));
|
||||
}
|
||||
});
|
||||
|
||||
r.post(OIDC_CLIENT_PATHS.backchannelLogout.replace(/^\/api/, ''), express.urlencoded({ extended: false, limit: '16kb' }), async (req, res) => {
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
const { sub, sid } = await auth.verifyLogoutToken(String(req.body?.logout_token ?? ''));
|
||||
// That Accounts session's sign-ins here, and any whose session id wasn't known.
|
||||
await ctx.db.session.deleteMany({ where: sid ? { userId: sub, OR: [{ sid }, { sid: null }] } : { userId: sub } });
|
||||
res.set('Cache-Control', 'no-store').status(200).end();
|
||||
} catch (e) {
|
||||
const code = (e as { code?: string }).code;
|
||||
res.status(code === 'BAD_TOKEN' ? 400 : 503).json({ error: 'invalid_request' });
|
||||
}
|
||||
});
|
||||
|
||||
r.post(ACCOUNTS_CALL_PATH.replace(/^\/api/, ''), express.raw({ type: '*/*', limit: '256kb' }), async (req, res) => {
|
||||
let call: AccountsCall;
|
||||
try {
|
||||
const auth = await accounts(ctx);
|
||||
call = auth.verifyAccountsCall(req.body as Buffer, req.headers);
|
||||
} catch (e) {
|
||||
if (e instanceof AccountsUnavailable) return sendError(res, e);
|
||||
return res.status(401).json({ error: { code: (e as { code?: string }).code ?? 'BAD_SIGNATURE', message: (e as Error).message } });
|
||||
}
|
||||
try {
|
||||
return res.json(await handleAccountsCall(ctx, call, req));
|
||||
} catch (e) {
|
||||
return sendError(res, e);
|
||||
}
|
||||
});
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/**
|
||||
* Accounts' signed calls. The Website only keeps an admin's name, email and role, so: update the
|
||||
* copy, export it, or remove the person (and their sessions). Someone the Website doesn't know is
|
||||
* answered as done.
|
||||
*/
|
||||
export async function handleAccountsCall(ctx: Ctx, call: AccountsCall, req?: Request): Promise<object> {
|
||||
const user = await ctx.db.websiteUser.findUnique({ where: { id: call.sub } });
|
||||
switch (call.type) {
|
||||
case 'user.updated': {
|
||||
if (user) await ctx.db.websiteUser.update({ where: { id: user.id }, data: { name: call.profile.name, email: call.profile.email.toLowerCase() } });
|
||||
return { schema: IDENTITY_SCHEMA, ok: true };
|
||||
}
|
||||
case 'user.export': {
|
||||
const reply: UserExportReply = {
|
||||
schema: IDENTITY_SCHEMA, exportId: call.exportId, sub: call.sub, product: 'website', generatedAt: ctx.now().toISOString(),
|
||||
sections: user ? [{
|
||||
key: 'website_admin',
|
||||
title: 'Your access to the church\'s website admin',
|
||||
records: [{ name: user.name, email: user.email, role: user.role, since: user.createdAt.toISOString(), lastSignIn: user.lastSignInAt?.toISOString() ?? null }],
|
||||
}] : [],
|
||||
};
|
||||
return reply;
|
||||
}
|
||||
case 'user.deleted': {
|
||||
if (user) {
|
||||
await ctx.db.session.deleteMany({ where: { userId: user.id } });
|
||||
await ctx.db.websiteUser.delete({ where: { id: user.id } });
|
||||
await audit(ctx, { actorId: null, actorRole: 'accounts', action: 'website_user_deleted', targetType: 'website_user', targetId: user.id, metadata: { role: user.role }, ip: clientIp(req) });
|
||||
}
|
||||
return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Admin sessions and roles (WEBSITE-1.0-PLAN §10). The Website keeps its own session after a
|
||||
* sign-in through Accounts: an HttpOnly cookie with a random token, of which only the SHA-256 is
|
||||
* stored. Roles are the Website's own (keyed by the account's `sub`); Accounts never says them.
|
||||
*/
|
||||
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { WebsiteRole } from '../generated/prisma/client.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
|
||||
export const SESSION_COOKIE = 'ccw_session';
|
||||
|
||||
/** Lowest to highest. A role can do what every role before it can. */
|
||||
export const ROLES: readonly WebsiteRole[] = ['viewer', 'ministry_leader', 'editor', 'admin', 'owner'];
|
||||
export const atLeast = (role: WebsiteRole, min: WebsiteRole) => ROLES.indexOf(role) >= ROLES.indexOf(min);
|
||||
|
||||
/** Roles that need a second step at sign-in (on by default, §10; AppSetting `two_factor_required_for_admins`). */
|
||||
export async function needsTwoFactor(ctx: Ctx, role: WebsiteRole): Promise<boolean> {
|
||||
return atLeast(role, 'admin') && (await ctx.settings.bool('two_factor_required_for_admins', true));
|
||||
}
|
||||
|
||||
export function readCookies(req: Request): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of String(req.headers.cookie || '').split(';')) {
|
||||
const i = part.indexOf('=');
|
||||
if (i > 0) {
|
||||
try {
|
||||
out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
|
||||
} catch {
|
||||
// A cookie this site didn't write: ignored.
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const cookieOptions = (ctx: Ctx, path = '/') => ({ httpOnly: true, sameSite: 'lax' as const, secure: ctx.config.production, path });
|
||||
|
||||
export async function startSession(ctx: Ctx, res: Response, s: { userId: string; sid: string | null; mfa: boolean; idToken: string }) {
|
||||
const token = randomToken();
|
||||
const now = ctx.now();
|
||||
const expiresAt = new Date(now.getTime() + ctx.config.sessionDays * 24 * 3600e3);
|
||||
await ctx.db.session.create({
|
||||
data: { tokenHash: hashToken(token), userId: s.userId, sid: s.sid, mfa: s.mfa, idToken: ctx.secrets.encrypt(s.idToken), createdAt: now, lastSeenAt: now, expiresAt },
|
||||
});
|
||||
res.cookie(SESSION_COOKIE, token, { ...cookieOptions(ctx), expires: expiresAt });
|
||||
}
|
||||
|
||||
export type Signed = {
|
||||
sessionId: string;
|
||||
idToken: string | null;
|
||||
mfa: boolean;
|
||||
user: { id: string; name: string; email: string; role: WebsiteRole; ministryId: string | null };
|
||||
};
|
||||
|
||||
/** The signed-in admin for this request, or null. */
|
||||
export async function currentSession(ctx: Ctx, req: Request): Promise<Signed | null> {
|
||||
const token = readCookies(req)[SESSION_COOKIE];
|
||||
if (!token) return null;
|
||||
const session = await ctx.db.session.findUnique({ where: { tokenHash: hashToken(token) } });
|
||||
if (!session) return null;
|
||||
const now = ctx.now();
|
||||
if (session.expiresAt <= now) {
|
||||
await ctx.db.session.delete({ where: { id: session.id } }).catch(() => {});
|
||||
return null;
|
||||
}
|
||||
const user = await ctx.db.websiteUser.findUnique({ where: { id: session.userId } });
|
||||
if (!user) return null;
|
||||
// Seen at most once a minute, so reading pages doesn't write on every request.
|
||||
if (now.getTime() - session.lastSeenAt.getTime() > 60_000) {
|
||||
await ctx.db.session.update({ where: { id: session.id }, data: { lastSeenAt: now } }).catch(() => {});
|
||||
}
|
||||
let idToken: string | null;
|
||||
try {
|
||||
idToken = session.idToken ? ctx.secrets.decrypt(session.idToken) : null;
|
||||
} catch {
|
||||
idToken = null;
|
||||
}
|
||||
return {
|
||||
sessionId: session.id,
|
||||
idToken,
|
||||
mfa: session.mfa,
|
||||
user: { id: user.id, name: user.name, email: user.email, role: user.role, ministryId: user.ministryId },
|
||||
};
|
||||
}
|
||||
|
||||
declare module 'express-serve-static-core' {
|
||||
interface Request {
|
||||
signed?: Signed;
|
||||
}
|
||||
}
|
||||
|
||||
/** Only signed-in admins with at least `min`. 401 when signed out, 403 when the role is too low. */
|
||||
export function requireRole(ctx: Ctx, min: WebsiteRole = 'viewer'): RequestHandler {
|
||||
return (req: Request, res: Response, next: NextFunction) => {
|
||||
currentSession(ctx, req).then((s) => {
|
||||
if (!s) return next(new ApiError(401, 'SIGNED_OUT', 'Please sign in.'));
|
||||
if (!atLeast(s.user.role, min)) return next(new ApiError(403, 'FORBIDDEN', 'Your role on this website can\'t do that.'));
|
||||
req.signed = s;
|
||||
return next();
|
||||
}).catch(next);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* The church profile (`crosscode.church/1`) from the church's Accounts (WEBSITE-1.0-PLAN §2): name,
|
||||
* logo, colours, brand style, service times, contact, social, the church's other sites. Accounts
|
||||
* owns it; the Website shows it and never stores it (§2: shared facts aren't drafts). As Events
|
||||
* 3.7's accounts/church.ts: kept in memory for 10 minutes, the last copy kept while Accounts can't
|
||||
* be reached (tried again after a minute).
|
||||
*
|
||||
* Before the Website is linked to Accounts (and in local development) the profile saved in
|
||||
* AppSetting `church_profile_local` is used, if any (`npm run demo` saves the demo church's).
|
||||
*/
|
||||
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { accountsLink } from '../auth/accounts.js';
|
||||
|
||||
const FRESH_MS = 10 * 60e3;
|
||||
const RETRY_MS = 60e3;
|
||||
const TIMEOUT_MS = 5000;
|
||||
|
||||
type Cached = { url: string; church: Church | null; at: number; ok: boolean };
|
||||
const caches = new WeakMap<Ctx, { cached: Cached | null; pending: Promise<Church | null> | null }>();
|
||||
|
||||
async function fetchProfile(accountsUrl: string): Promise<Church> {
|
||||
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
|
||||
const parsed = churchSchema.safeParse(await res.json());
|
||||
if (!parsed.success) throw new Error(`the profile isn't crosscode.church/1 (${parsed.error.issues[0]?.message ?? 'invalid'})`);
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
async function localProfile(ctx: Ctx): Promise<Church | null> {
|
||||
const raw = await ctx.settings.json<unknown>('church_profile_local', null);
|
||||
const parsed = raw ? churchSchema.safeParse(raw) : null;
|
||||
return parsed?.success ? parsed.data : null;
|
||||
}
|
||||
|
||||
/** The church's profile, or null when there's none yet. Never throws. */
|
||||
export async function churchProfile(ctx: Ctx): Promise<Church | null> {
|
||||
let link;
|
||||
try {
|
||||
link = await accountsLink(ctx);
|
||||
} catch {
|
||||
link = null;
|
||||
}
|
||||
if (!link) return localProfile(ctx).catch(() => null);
|
||||
let state = caches.get(ctx);
|
||||
if (!state) caches.set(ctx, (state = { cached: null, pending: null }));
|
||||
const { cached } = state;
|
||||
const url = link.url;
|
||||
if (cached && cached.url === url && ctx.now().getTime() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
|
||||
if (!state.pending) {
|
||||
const last = cached?.url === url ? cached.church : null;
|
||||
const s = state;
|
||||
s.pending = fetchProfile(url)
|
||||
.then((church) => {
|
||||
s.cached = { url, church, at: ctx.now().getTime(), ok: true };
|
||||
return church;
|
||||
}, (e: Error) => {
|
||||
console.warn('[church] profile not fetched from Accounts:', e.message);
|
||||
s.cached = { url, church: last, at: ctx.now().getTime(), ok: false };
|
||||
return last;
|
||||
})
|
||||
.finally(() => { s.pending = null; });
|
||||
}
|
||||
return state.pending;
|
||||
}
|
||||
|
||||
/** `church.changed` from Accounts: fetched again next time (the last copy is shown meanwhile). */
|
||||
export function churchChanged(ctx: Ctx): void {
|
||||
const state = caches.get(ctx);
|
||||
if (state?.cached) state.cached = { ...state.cached, at: 0 };
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Everything a request handler or job needs, passed in rather than imported, so tests can run the
|
||||
* whole app against an in-memory database and a stand-in Accounts (tests/support/).
|
||||
*/
|
||||
import type { PrismaClient } from './generated/prisma/client.js';
|
||||
import type { Config } from './lib/config.js';
|
||||
import { Secrets } from './lib/crypto.js';
|
||||
import { Settings } from './lib/settings.js';
|
||||
import { loadAuthClient, type AuthClientModule } from './auth/accounts.js';
|
||||
|
||||
export type Db = PrismaClient;
|
||||
|
||||
export type Ctx = {
|
||||
config: Config;
|
||||
db: Db;
|
||||
secrets: Secrets;
|
||||
settings: Settings;
|
||||
/** `@crosscode/auth-client` (tests give a stand-in). */
|
||||
authClient: () => Promise<AuthClientModule>;
|
||||
now: () => Date;
|
||||
};
|
||||
|
||||
export function createCtx(config: Config, db: Db, opts: { now?: () => Date; authClient?: () => Promise<AuthClientModule> } = {}): Ctx {
|
||||
const secrets = new Secrets(config.secret);
|
||||
const partial = { config, db, secrets } as Ctx;
|
||||
partial.settings = new Settings(partial);
|
||||
partial.authClient = opts.authClient ?? loadAuthClient;
|
||||
partial.now = opts.now ?? (() => new Date());
|
||||
return partial;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* The demo church (WEBSITE-1.0-PLAN §11, "Demo church"): a fictional church, fictional people and
|
||||
* illustrated images (no photos of anyone), loaded into a template for development, the Hub's demo
|
||||
* sites and the crosscode-site screenshots. `npm run demo -- --template bold`.
|
||||
*
|
||||
* It replaces the Website's content (never the admins), so the script refuses on a site that has
|
||||
* been published unless told otherwise.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { CHURCH_SCHEMA, type Church, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { SectionData } from '../site/sections.js';
|
||||
import { publish } from '../site/snapshot.js';
|
||||
import { defaultDesign } from '../site/variants.js';
|
||||
|
||||
export const DEMO_COLOURS = { primary: '#1d5c63', accent: '#e0a458' };
|
||||
|
||||
export function demoProfile(publicUrl: string): Church {
|
||||
return {
|
||||
schema: CHURCH_SCHEMA,
|
||||
customerId: '00000000-0000-4000-8000-000000000001',
|
||||
updatedAt: '2026-11-25T08:00:00.000Z',
|
||||
name: 'Acacia Hill Church',
|
||||
shortName: 'Acacia Hill',
|
||||
timezone: 'Africa/Johannesburg',
|
||||
locale: 'en-ZA',
|
||||
branding: { logoUrl: null, iconUrl: null, colours: DEMO_COLOURS, style: { fontPairing: null, corners: null } },
|
||||
campuses: [],
|
||||
serviceTimes: [
|
||||
{ day: 'sunday', time: '08:30', label: 'Early service', campus: null, note: null },
|
||||
{ day: 'sunday', time: '10:00', label: 'Family service', campus: null, note: 'Kids church during the service' },
|
||||
{ day: 'wednesday', time: '18:30', label: 'Midweek prayer', campus: null, note: null },
|
||||
],
|
||||
contact: {
|
||||
email: 'hello@acaciahill.example',
|
||||
phone: '+27125550123',
|
||||
whatsapp: '+27825550123',
|
||||
address: { line1: '12 Acacia Avenue', line2: null, suburb: 'Westridge', city: 'Pretoria', province: 'Gauteng', postalCode: '0181', country: 'ZA', geo: { lat: -25.7461, lng: 28.1881 } },
|
||||
},
|
||||
social: [
|
||||
{ network: 'facebook', url: 'https://www.facebook.com/acaciahill.example' },
|
||||
{ network: 'youtube', url: 'https://www.youtube.com/@acaciahill.example' },
|
||||
],
|
||||
links: { website: publicUrl, events: null, app: null, accounts: 'https://accounts.acaciahill.example' },
|
||||
} as Church;
|
||||
}
|
||||
|
||||
/** An illustrated "photo": hills, a sun and a path in the church's colours (SVG, no people). */
|
||||
function illustration(seed: number, w = 1600, h = 1000): string {
|
||||
const hues = [DEMO_COLOURS.primary, DEMO_COLOURS.accent, '#7fb7be', '#f3e3c3', '#284b52'];
|
||||
const c = (i: number) => hues[(seed + i) % hues.length];
|
||||
const y = (f: number) => Math.round(h * f);
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${w} ${h}" width="${w}" height="${h}">
|
||||
<defs><linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="${c(3)}"/><stop offset="1" stop-color="#fffaf0"/></linearGradient></defs>
|
||||
<rect width="${w}" height="${h}" fill="url(#sky)"/>
|
||||
<circle cx="${Math.round(w * (0.2 + (seed % 5) * 0.15))}" cy="${y(0.3)}" r="${Math.round(h * 0.12)}" fill="${c(1)}" opacity="0.85"/>
|
||||
<path d="M0 ${y(0.62)} Q ${w * 0.25} ${y(0.45)} ${w * 0.5} ${y(0.6)} T ${w} ${y(0.55)} V ${h} H 0 Z" fill="${c(2)}"/>
|
||||
<path d="M0 ${y(0.75)} Q ${w * 0.35} ${y(0.6)} ${w * 0.7} ${y(0.74)} T ${w} ${y(0.7)} V ${h} H 0 Z" fill="${c(0)}"/>
|
||||
<path d="M${w * 0.45} ${h} C ${w * 0.5} ${y(0.85)} ${w * 0.6} ${y(0.8)} ${w * 0.62} ${y(0.72)}" stroke="${c(3)}" stroke-width="${Math.round(h * 0.03)}" fill="none" stroke-linecap="round"/>
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
type Ids = Record<string, string>;
|
||||
|
||||
async function demoMedia(ctx: Ctx, uploadDir: string): Promise<Ids> {
|
||||
const items: [string, string, number][] = [
|
||||
['hero', 'The hills behind Acacia Hill at sunrise (illustration)', 0],
|
||||
['collage2', 'A path through the veld (illustration)', 1],
|
||||
['collage3', 'Evening over the valley (illustration)', 2],
|
||||
['welcome', 'The church garden (illustration)', 3],
|
||||
['pastor', 'Illustration standing in for the pastor\'s photo', 4],
|
||||
['invite', 'A sunny Sunday morning (illustration)', 5],
|
||||
['kids', 'Illustration for Kids church', 6],
|
||||
['youth', 'Illustration for Youth', 7],
|
||||
['care', 'Illustration for Care and prayer', 8],
|
||||
['music', 'Illustration for Worship', 9],
|
||||
];
|
||||
const ids: Ids = {};
|
||||
fs.mkdirSync(path.join(uploadDir, 'demo'), { recursive: true });
|
||||
for (const [key, alt, seed] of items) {
|
||||
const filename = `demo/${key}.svg`;
|
||||
const svg = illustration(seed);
|
||||
fs.writeFileSync(path.join(uploadDir, filename), svg);
|
||||
const row = await ctx.db.mediaAsset.create({ data: { filename, mime: 'image/svg+xml', bytes: Buffer.byteLength(svg), width: 1600, height: 1000, alt } });
|
||||
ids[key] = row.id;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export const defaultUploadDir = () => path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'uploads');
|
||||
|
||||
/** Replaces the content with the demo church's on `template`, then publishes it. */
|
||||
export async function loadDemo(ctx: Ctx, template: WebsiteTemplate, opts: { uploadDir?: string; publishedBy?: string } = {}) {
|
||||
const db = ctx.db;
|
||||
const uploadDir = opts.uploadDir ?? ctx.config.uploadDir ?? defaultUploadDir();
|
||||
for (const m of ['section', 'page', 'ministry', 'leader', 'message', 'messageSeries', 'simpleEvent', 'mediaAsset', 'siteVersion', 'siteDesign'] as const) {
|
||||
await (db[m] as unknown as { deleteMany: (a?: object) => Promise<unknown> }).deleteMany({});
|
||||
}
|
||||
const img = await demoMedia(ctx, uploadDir);
|
||||
const design = defaultDesign(template);
|
||||
await db.siteDesign.create({ data: { id: 1, template, variants: design.variants as never, home: design.home as never, style: design.style as never } });
|
||||
await ctx.settings.set('church_profile_local', JSON.stringify(demoProfile(ctx.config.publicUrl)));
|
||||
|
||||
const home: SectionData = {
|
||||
hero: { headline: 'A home for everyone on the hill', subline: 'Sundays at 08:30 and 10:00 in Westridge, Pretoria. Come as you are.', images: [img.hero!, img.collage2!, img.collage3!], videoId: null, button: { label: 'Plan your visit', href: '/visit' } },
|
||||
serviceTimes: { heading: 'Join us this Sunday', note: 'Kids church runs during the 10:00 service. Parking on Acacia Avenue and behind the hall.' },
|
||||
welcome: {
|
||||
heading: 'Welcome to Acacia Hill', mission: 'Loving God, loving our neighbours, from Westridge to the nations.',
|
||||
body: 'We are a family of ordinary people who have found good news in Jesus. Whether you have followed him for years or are just curious, there is a seat for you here, and coffee after the service.',
|
||||
imageId: img.welcome!, pastor: { name: 'Pastor Thandi Mokoena', role: 'Lead pastor', quote: 'We would love to meet you. Come and say hello at the welcome table.', photoId: img.pastor! },
|
||||
},
|
||||
ministries: { heading: 'Find your place', intro: 'There is something for every age and stage.' },
|
||||
team: { heading: 'Our team', intro: null },
|
||||
events: { heading: 'Coming up', count: 3 },
|
||||
latestMessage: { heading: 'Latest message' },
|
||||
invitation: { heading: 'We saved you a seat', text: 'New here? Let us know you are coming and we will meet you at the door.', button: { label: 'Plan your visit', href: '/visit' }, imageId: img.invite! },
|
||||
};
|
||||
const pages: { kind: string; slug: string; title: string; position: number; description: string; sections: { type: string; variant?: string; data: unknown }[] }[] = [
|
||||
{ kind: 'home', slug: 'home', title: 'Home', position: 0, description: 'Acacia Hill Church in Westridge, Pretoria: Sundays at 08:30 and 10:00. Come as you are.', sections: Object.entries(home).map(([type, data]) => ({ type, data })) },
|
||||
{
|
||||
kind: 'visit', slug: 'visit', title: 'Plan your visit', position: 1, description: 'What to expect on your first Sunday at Acacia Hill Church.', sections: [
|
||||
{ type: 'text', data: { heading: 'What to expect', body: 'Services last about an hour and a quarter. We sing together, pray, and hear a message from the Bible. Dress is casual.' } },
|
||||
{ type: 'image-text', variant: 'image-text', data: { heading: 'Bringing children', body: 'Kids church (ages 3 to 12) runs during the 10:00 service. Sign your children in at the kids desk in the hall.', imageId: img.kids, button: null } },
|
||||
{ type: 'cta', data: { heading: 'Questions before you come?', text: 'Send us a WhatsApp and we will get back to you.', button: { label: 'Contact us', href: '/contact' } } },
|
||||
],
|
||||
},
|
||||
{
|
||||
kind: 'about', slug: 'about', title: 'About us', position: 2, description: 'Our story, what we believe and what we value.', sections: [
|
||||
{ type: 'text', data: { heading: 'Our story', body: 'Acacia Hill began in 1998 as a Bible study in a lounge in Westridge. Today we are a church of all ages that meets in the old school hall on Acacia Avenue.' } },
|
||||
{ type: 'quote', data: { quote: 'Love one another. As I have loved you, so you must love one another.', by: 'John 13:34' } },
|
||||
],
|
||||
},
|
||||
{ kind: 'ministries', slug: 'ministries', title: 'Ministries', position: 3, description: 'Kids, youth, worship, care and prayer at Acacia Hill.', sections: [] },
|
||||
{ kind: 'leadership', slug: 'leadership', title: 'Leadership', position: 4, description: 'The team who lead Acacia Hill Church.', sections: [] },
|
||||
{ kind: 'events', slug: 'events', title: 'Events', position: 5, description: 'What is coming up at Acacia Hill Church.', sections: [] },
|
||||
{ kind: 'messages', slug: 'messages', title: 'Messages', position: 6, description: 'Sunday messages from Acacia Hill Church.', sections: [] },
|
||||
{
|
||||
kind: 'give', slug: 'give', title: 'Give', position: 7, description: 'How to give to Acacia Hill Church.', sections: [
|
||||
{ type: 'text', data: { heading: 'Giving', body: 'Thank you for giving. You can give by EFT to Acacia Hill Church (demo details only: this is not a real account).' } },
|
||||
],
|
||||
},
|
||||
{ kind: 'contact', slug: 'contact', title: 'Contact', position: 8, description: 'Find Acacia Hill Church in Westridge, Pretoria.', sections: [] },
|
||||
];
|
||||
for (const p of pages) {
|
||||
const page = await db.page.create({ data: { kind: p.kind as never, slug: p.slug, title: p.title, position: p.position, description: p.description } });
|
||||
let i = 0;
|
||||
for (const s of p.sections) await db.section.create({ data: { pageId: page.id, type: s.type, variant: s.variant ?? null, position: i++, data: s.data as never } });
|
||||
}
|
||||
|
||||
const ministries: [string, string, string, string][] = [
|
||||
['kids', 'Kids church', 'Ages 3 to 12, every Sunday at 10:00.', img.kids!],
|
||||
['youth', 'Youth', 'High schoolers, Friday nights at 18:30.', img.youth!],
|
||||
['worship', 'Worship', 'Musicians and sound, rehearsing on Thursdays.', img.music!],
|
||||
['care', 'Care and prayer', 'Meals, visits and prayer for anyone who needs it.', img.care!],
|
||||
];
|
||||
let n = 0;
|
||||
for (const [slug, name, summary, imageId] of ministries) await db.ministry.create({ data: { slug, name, summary, imageId, position: n++ } });
|
||||
const leaders: [string, string, string | null][] = [
|
||||
['Thandi Mokoena', 'Lead pastor', img.pastor!],
|
||||
['Pieter van Wyk', 'Associate pastor', null],
|
||||
['Lerato Dlamini', 'Kids and families', null],
|
||||
['Johan Botha', 'Worship', null],
|
||||
];
|
||||
n = 0;
|
||||
for (const [name, role, photoId] of leaders) await db.leader.create({ data: { name, role, photoId, position: n++ } });
|
||||
|
||||
const now = ctx.now();
|
||||
const day = 864e5;
|
||||
const series = await db.messageSeries.create({ data: { slug: 'hope-for-today', title: 'Hope for today' } });
|
||||
const messages: [string, string, number][] = [['hope-that-holds', 'A hope that holds', 3], ['bread-for-the-road', 'Bread for the road', 10], ['the-good-shepherd', 'The good shepherd', 17]];
|
||||
for (const [slug, title, ago] of messages) {
|
||||
await db.message.create({ data: { slug, title, date: new Date(now.getTime() - ago * day), source: 'youtube', mediaUrl: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', speaker: 'Pastor Thandi Mokoena', passage: 'Psalm 23', seriesId: series.id, publishedAt: now } });
|
||||
}
|
||||
const events: [string, string, number, string][] = [
|
||||
['family-picnic', 'Family picnic', 6, 'Bring a blanket and something to share. Games for the kids.'],
|
||||
['carols-by-candlelight', 'Carols by candlelight', 20, 'Our Christmas carol service on the lawn.'],
|
||||
['new-here-lunch', 'New here lunch', 34, 'Meet the pastors over lunch after the 10:00 service.'],
|
||||
];
|
||||
for (const [slug, title, inDays, description] of events) {
|
||||
const startsAt = new Date(Math.floor((now.getTime() + inDays * day) / day) * day + 8 * 3600e3);
|
||||
await db.simpleEvent.create({ data: { slug, title, startsAt, endsAt: new Date(startsAt.getTime() + 3 * 3600e3), location: 'Acacia Hill Church', description, publishedAt: now } });
|
||||
}
|
||||
return publish(ctx, { id: opts.publishedBy ?? 'demo', role: 'system' }, `Demo church on ${template}`);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* The Website's part of a church's export when it leaves (`crosscode export` / uninstall,
|
||||
* WEBSITE-1.0-PLAN §11): `crosscode.church-export/1` with its `website` part, in plain terms and
|
||||
* our own field names (no table names or internal ids; records refer to each other by refs made
|
||||
* for the export). The uploads are copied next to it by the crosscode script (`uploads/`).
|
||||
*
|
||||
* The content is the working copy, including changes not yet published, as the admins left it.
|
||||
*/
|
||||
import { churchExportSchema, type ChurchExport, type ExportWebsite, type WebsiteTemplate, WEBSITE_TEMPLATES } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { appVersion } from '../lib/version.js';
|
||||
|
||||
const iso = (d: Date | null | undefined) => (d ? d.toISOString() : null);
|
||||
const uploadPath = (filename: string) => `uploads/${filename.replace(/[^A-Za-z0-9._/-]/g, '-')}`;
|
||||
const ROLE_NAMES: Record<string, string> = { owner: 'website owner', admin: 'website admin', editor: 'website editor', ministry_leader: 'ministry leader', viewer: 'website viewer' };
|
||||
|
||||
export async function buildExport(ctx: Ctx): Promise<ChurchExport> {
|
||||
const db = ctx.db;
|
||||
const [design, pages, messages, events, versions, media, users] = await Promise.all([
|
||||
db.siteDesign.findUnique({ where: { id: 1 } }),
|
||||
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
|
||||
db.message.findMany({ orderBy: { date: 'asc' }, include: { series: true } }),
|
||||
db.simpleEvent.findMany({ orderBy: { startsAt: 'asc' } }),
|
||||
db.siteVersion.findMany({ orderBy: { number: 'asc' } }),
|
||||
db.mediaAsset.findMany({ orderBy: { createdAt: 'asc' } }),
|
||||
db.websiteUser.findMany({ orderBy: { name: 'asc' } }),
|
||||
]);
|
||||
const mediaPath = new Map(media.map((m) => [m.id, uploadPath(m.filename)]));
|
||||
const names = new Map(users.map((u) => [u.id, u.name]));
|
||||
const template: WebsiteTemplate = (WEBSITE_TEMPLATES as readonly string[]).includes(design?.template ?? '') ? (design!.template as WebsiteTemplate) : 'heritage';
|
||||
|
||||
const website: ExportWebsite = {
|
||||
template,
|
||||
firstPublishedAt: iso(versions[0]?.publishedAt),
|
||||
style: Object.fromEntries(Object.entries((design?.style ?? {}) as Record<string, unknown>).filter(([, v]) => typeof v === 'string')) as Record<string, string>,
|
||||
pages: pages.map((p, n) => ({
|
||||
ref: `g${n + 1}`,
|
||||
title: p.title,
|
||||
path: p.kind === 'home' ? '/' : `/${p.slug}`,
|
||||
kind: p.kind,
|
||||
inNavigation: p.inNav,
|
||||
seo: { title: p.seoTitle, description: p.description },
|
||||
sections: p.sections.map((s) => ({ type: s.type, variant: s.variant ?? '', hidden: s.hidden, content: (s.data ?? {}) as Record<string, never> })),
|
||||
})),
|
||||
messages: messages.map((m, n) => ({
|
||||
ref: `m${n + 1}`, title: m.title, date: iso(m.date), speaker: m.speaker, series: m.series?.title ?? null, passage: m.passage, notes: m.notes,
|
||||
url: m.mediaUrl, source: m.source === 'youtube_feed' ? 'youtube-feed' as const : 'manual' as const, hidden: m.hidden,
|
||||
})),
|
||||
events: events.map((e, n) => ({
|
||||
ref: `w${n + 1}`, title: e.title, description: e.description, startsAt: iso(e.startsAt), endsAt: iso(e.endsAt), location: e.location,
|
||||
link: e.link, image: e.imageId ? mediaPath.get(e.imageId) ?? null : null, published: e.publishedAt !== null,
|
||||
})),
|
||||
versions: versions.map((v) => ({ number: v.number, publishedAt: iso(v.publishedAt), by: names.get(v.publishedBy) ?? null, note: v.note })),
|
||||
media: media.map((m) => ({ path: uploadPath(m.filename), alt: m.alt || null, caption: null })),
|
||||
};
|
||||
|
||||
return churchExportSchema.parse({
|
||||
schema: 'crosscode.church-export/1',
|
||||
exportedAt: ctx.now().toISOString(),
|
||||
product: 'website',
|
||||
productVersion: appVersion(),
|
||||
church: { name: (await ctx.settings.get('church_name')) || 'Church Website', timezone: ctx.config.timezone },
|
||||
people: users.map((u, n) => ({
|
||||
ref: `p${n + 1}`, name: u.name, email: u.email, phone: null, role: ROLE_NAMES[u.role] ?? u.role, createdAt: iso(u.createdAt),
|
||||
consent: { email: null, whatsapp: null, privacyNoticeAcceptedAt: null },
|
||||
})),
|
||||
events: [], registrations: [], payments: [], checkIns: [], rosters: [],
|
||||
settings: { address: ctx.config.publicUrl },
|
||||
files: media.map((m) => ({ path: uploadPath(m.filename), bytes: m.bytes })),
|
||||
website,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Shared bits for the API: errors as `{ error: { code, message, fields? } }` (as Accounts and
|
||||
* Events' /api/v2) and async handlers.
|
||||
*/
|
||||
import type { Request, RequestHandler, Response } from 'express';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(public status: number, public code: string, message: string, public fields?: Record<string, string>) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Known errors carry a status and code; anything else is a 500. */
|
||||
export function sendError(res: Response, e: unknown) {
|
||||
if (e instanceof ApiError) {
|
||||
return res.status(e.status).json({ error: { code: e.code, message: e.message, ...(e.fields ? { fields: e.fields } : {}) } });
|
||||
}
|
||||
console.error('[api]', e);
|
||||
return res.status(500).json({ error: { code: 'INTERNAL', message: 'Something went wrong. Please try again.' } });
|
||||
}
|
||||
|
||||
export const handle = (fn: (req: Request, res: Response) => Promise<unknown>): RequestHandler => (req, res) => {
|
||||
fn(req, res).then((out) => {
|
||||
if (out !== undefined && !res.headersSent) res.json(out);
|
||||
}).catch((e) => sendError(res, e));
|
||||
};
|
||||
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* The Website and the Hub (docs/hub-protocol.md §6, protocol v2, product `website`), as Accounts'
|
||||
* hub/client.ts: register with a `CCW-` licence key (by itself from HUB_LICENCE_KEY on a Hub
|
||||
* install), then a signed heartbeat every 15 minutes with aggregate counts only. The reply's
|
||||
* `linkedProducts` (the church's other installs) is cached for Connect, and the Website connects
|
||||
* itself to the church's Accounts once the Hub lists it (links/connect.ts).
|
||||
*
|
||||
* The install id the Hub gives is also this site's OIDC client id at Accounts.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { appVersion } from '../lib/version.js';
|
||||
import { connectAccountsIfListed } from '../links/connect.js';
|
||||
import { keyPair, saveLinkedProducts } from '../links/store.js';
|
||||
import { hubPublicKey, verifyToken } from './licence.js';
|
||||
|
||||
export const PROTOCOL_VERSION = 2;
|
||||
const TIMEOUT_MS = 15000;
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
const STARTED_AT = Date.now();
|
||||
/** 5 GB included (ROADMAP-v3 §10); the licence's `limits.storageBytes` says more when steps were bought. */
|
||||
export const INCLUDED_STORAGE_BYTES = 5 * 1024 ** 3;
|
||||
|
||||
export class HubError extends Error {
|
||||
constructor(message: string, public code: string, public status: number) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function post(ctx: Ctx, path: string, body: unknown, sign?: { installId: string; secret: string }): Promise<Record<string, unknown>> {
|
||||
const raw = JSON.stringify(body);
|
||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||
if (sign) {
|
||||
const timestamp = ctx.now().toISOString();
|
||||
headers['X-Hub-Install'] = sign.installId;
|
||||
headers['X-Hub-Timestamp'] = timestamp;
|
||||
headers['X-Hub-Signature'] = crypto.createHmac('sha256', sign.secret).update(`${timestamp}.${raw}`).digest('hex');
|
||||
}
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`${ctx.config.hubUrl}${path}`, { method: 'POST', headers, body: raw, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
} catch (e) {
|
||||
throw new HubError(`The Hub (${ctx.config.hubUrl}) could not be reached: ${(e as Error).message}`, 'HUB_UNREACHABLE', 502);
|
||||
}
|
||||
const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
|
||||
if (!res.ok) throw new HubError(String(data.message || `The Hub answered ${res.status}`), String(data.code || 'HUB_ERROR'), res.status);
|
||||
return data;
|
||||
}
|
||||
|
||||
export async function dbUp(ctx: Ctx): Promise<boolean> {
|
||||
try {
|
||||
await ctx.db.$queryRaw`SELECT 1`;
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function health(ctx: Ctx) {
|
||||
return {
|
||||
uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000),
|
||||
db: await dbUp(ctx),
|
||||
jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 },
|
||||
lastBackupAt: null,
|
||||
disk: null,
|
||||
errorsLast24h: null,
|
||||
pendingMigrations: 0,
|
||||
};
|
||||
}
|
||||
|
||||
/** Aggregate counts only (hub.websiteStatsSchema): never anyone's details. */
|
||||
export async function stats(ctx: Ctx) {
|
||||
const now = ctx.now();
|
||||
const since = new Date(now.getTime() - 30 * DAY);
|
||||
const [published, drafts, total, last30d, upcomingSimple, imported, editors, media] = await Promise.all([
|
||||
ctx.db.siteVersion.count(),
|
||||
ctx.db.page.count({ where: { archivedAt: null } }),
|
||||
ctx.db.message.count({ where: { hidden: false } }),
|
||||
ctx.db.message.count({ where: { hidden: false, date: { gte: since } } }),
|
||||
ctx.db.simpleEvent.count({ where: { startsAt: { gte: now }, publishedAt: { not: null } } }),
|
||||
ctx.db.importedEvent.count({ where: { startsAt: { gte: now } } }),
|
||||
ctx.db.websiteUser.count({ where: { role: { not: 'viewer' } } }),
|
||||
ctx.db.mediaAsset.aggregate({ _sum: { bytes: true } }),
|
||||
]);
|
||||
return {
|
||||
// Until pages are published one by one, "published" is whether the site has been (0 or 1+ versions).
|
||||
pages: { published: published > 0 ? drafts : 0, drafts: published > 0 ? 0 : drafts },
|
||||
messages: { total, last30d },
|
||||
events: { upcomingSimple, imported },
|
||||
editors,
|
||||
storage: { usedBytes: media._sum.bytes ?? 0, includedBytes: INCLUDED_STORAGE_BYTES },
|
||||
};
|
||||
}
|
||||
|
||||
/** Register with a licence key (HUB_LICENCE_KEY). */
|
||||
export async function connect(ctx: Ctx, licenceKey: string, adminContact: { name: string | null; email: string | null } | null) {
|
||||
if (!/^https?:\/\//.test(ctx.config.publicUrl)) throw new HubError('WEBSITE_URL isn\'t set.', 'NO_SITE_URL', 400);
|
||||
const { publicKeyPem } = await keyPair(ctx);
|
||||
const body = {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
licenceKey: licenceKey.trim().toUpperCase(),
|
||||
product: 'website',
|
||||
install: {
|
||||
name: 'Website',
|
||||
url: ctx.config.publicUrl,
|
||||
adminContact,
|
||||
version: appVersion(),
|
||||
timezone: ctx.config.timezone,
|
||||
server: { node: process.versions.node, postgres: null, os: `${process.platform}` },
|
||||
features: {},
|
||||
publicKey: publicKeyPem,
|
||||
},
|
||||
};
|
||||
const check = hub.registerRequestSchema.safeParse(body);
|
||||
if (!check.success) throw new HubError('That doesn\'t look like a Website licence key (CCW-…).', 'INVALID_REQUEST', 400);
|
||||
const data = await post(ctx, '/api/installs/register', check.data);
|
||||
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||
if (!claims || claims.installId !== data.installId) throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL right?', 'BAD_LICENCE', 502);
|
||||
await ctx.settings.setMany({
|
||||
hub_install_id: String(data.installId),
|
||||
hub_install_secret: String(data.installSecret),
|
||||
hub_licence: String(data.licence),
|
||||
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||
hub_last_error: null,
|
||||
hub_public_key_status: 'matches',
|
||||
});
|
||||
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||
await connectAccountsIfListed(ctx);
|
||||
return claims;
|
||||
}
|
||||
|
||||
/** The heartbeat (every 15 minutes). Skips quietly when not connected. */
|
||||
export async function heartbeat(ctx: Ctx) {
|
||||
const installId = await ctx.settings.get('hub_install_id');
|
||||
const secret = await ctx.settings.get('hub_install_secret');
|
||||
if (!installId || !secret) return { skipped: 'not connected' };
|
||||
const status = await ctx.settings.get('hub_public_key_status');
|
||||
const { publicKeyPem } = await keyPair(ctx);
|
||||
const body = {
|
||||
protocolVersion: PROTOCOL_VERSION,
|
||||
product: 'website',
|
||||
version: appVersion(),
|
||||
health: await health(ctx),
|
||||
stats: await stats(ctx),
|
||||
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
|
||||
};
|
||||
try {
|
||||
const data = await post(ctx, '/api/installs/heartbeat', body, { installId, secret });
|
||||
const claims = verifyToken(String(data.licence || ''), hubPublicKey(ctx));
|
||||
await ctx.settings.setMany({
|
||||
...(claims && claims.installId === installId ? { hub_licence: String(data.licence) } : {}),
|
||||
hub_last_heartbeat_at: ctx.now().toISOString(),
|
||||
hub_last_error: null,
|
||||
...(typeof data.publicKeyStatus === 'string' ? { hub_public_key_status: data.publicKeyStatus } : {}),
|
||||
});
|
||||
await saveLinkedProducts(ctx, data.linkedProducts);
|
||||
await connectAccountsIfListed(ctx);
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
const err = e as HubError;
|
||||
await ctx.settings.set('hub_last_error', `${ctx.now().toISOString()} ${err.code || ''} ${err.message}`.slice(0, 500));
|
||||
if (err.code === 'INSTALL_NOT_FOUND') {
|
||||
await ctx.settings.setMany({ hub_install_id: null, hub_install_secret: null, hub_licence: null });
|
||||
return { ok: false, reconnect: true };
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** A Hub install registers by itself on first start from HUB_LICENCE_KEY. Never throws. */
|
||||
export async function connectFromEnv(ctx: Ctx, { attempts = 5, delayMs = 60_000 } = {}) {
|
||||
const key = ctx.config.hubLicenceKey;
|
||||
if (!key) return { connected: false, reason: 'no_key' };
|
||||
for (let i = 1; i <= attempts; i++) {
|
||||
try {
|
||||
if (await ctx.settings.get('hub_install_id')) return { connected: false, reason: 'already' };
|
||||
await connect(ctx, key, ctx.config.hubAdminName || ctx.config.hubAdminEmail ? { name: ctx.config.hubAdminName, email: ctx.config.hubAdminEmail } : null);
|
||||
return { connected: true };
|
||||
} catch (e) {
|
||||
const err = e as HubError;
|
||||
console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, err.message);
|
||||
if (err.status >= 400 && err.status < 500) return { connected: false, reason: err.code };
|
||||
if (i < attempts) await new Promise((r) => setTimeout(r, delayMs).unref?.());
|
||||
}
|
||||
}
|
||||
return { connected: false, reason: 'unreachable' };
|
||||
}
|
||||
|
||||
/** Heartbeats every 15 minutes until stopped (pg-boss comes with the Website's other jobs). */
|
||||
export function startHeartbeats(ctx: Ctx): () => void {
|
||||
if (!ctx.config.jobsEnabled) return () => {};
|
||||
const timer = setInterval(() => {
|
||||
heartbeat(ctx).catch((e) => console.warn('[hub] Heartbeat failed:', (e as Error).message));
|
||||
}, 15 * 60 * 1000);
|
||||
timer.unref?.();
|
||||
return () => clearInterval(timer);
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* The licence token from the Hub (docs/hub-protocol.md §4), checked offline with the Hub's public
|
||||
* key, as Cross Events does. A lapsed licence never takes the public site down (the Hub is never on the runtime path,
|
||||
* ROADMAP-v3 §1): admins see a banner.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
/** The production Hub's licence key (as in Cross Events' hub/publicKey.js). HUB_PUBLIC_KEY overrides it. */
|
||||
export const PRODUCTION_PUBLIC_KEY = 'MCowBQYDK2VwAyEAcKpEo/JdS96wR3r9yh8uFUxBlzPUd2YKbC60fNRUhoU=';
|
||||
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
|
||||
/** A public key as PEM, however it was pasted (real line breaks, "\n", one line, or only the base64). */
|
||||
export function normalisePem(input: string | null | undefined): string | null {
|
||||
const text = String(input || '').replace(/\\n/g, '\n').trim();
|
||||
if (!text) return null;
|
||||
const body = text.replace(/-----BEGIN PUBLIC KEY-----/, '').replace(/-----END PUBLIC KEY-----/, '').replace(/\s+/g, '');
|
||||
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(body)) return text;
|
||||
return `-----BEGIN PUBLIC KEY-----\n${body.match(/.{1,64}/g)!.join('\n')}\n-----END PUBLIC KEY-----\n`;
|
||||
}
|
||||
|
||||
export function hubPublicKey(ctx: Pick<Ctx, 'config'>): string | null {
|
||||
return normalisePem(ctx.config.hubPublicKey) || normalisePem(PRODUCTION_PUBLIC_KEY);
|
||||
}
|
||||
|
||||
export type LicenceClaims = {
|
||||
v: number; installId: string; customerId?: string; product?: string; customer: string; status: string;
|
||||
licenceExpiresAt: string | null; validUntil: string; graceDays: number;
|
||||
};
|
||||
|
||||
export function verifyToken(token: string | null | undefined, pem: string | null): LicenceClaims | null {
|
||||
if (!pem) return null;
|
||||
const parts = String(token || '').split('.');
|
||||
if (parts.length !== 3 || parts[0] !== 'hel1') return null;
|
||||
try {
|
||||
const ok = crypto.verify(null, Buffer.from(`${parts[0]}.${parts[1]}`), crypto.createPublicKey(pem), Buffer.from(parts[2]!, 'base64url'));
|
||||
return ok ? (JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as LicenceClaims) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export type LicenceState = 'active' | 'grace' | 'lapsed' | 'revoked' | 'unlicensed';
|
||||
|
||||
/** The state for verified claims. Pure. */
|
||||
export function stateFor(claims: LicenceClaims | null, installId: string | null, now = new Date()): { state: LicenceState; endsAt: Date | null; daysLeft: number | null } {
|
||||
if (!claims || (installId && claims.installId !== installId)) return { state: 'unlicensed', endsAt: null, daysLeft: null };
|
||||
const ends = [claims.licenceExpiresAt, claims.validUntil].filter(Boolean).map((d) => new Date(d!));
|
||||
const endsAt = ends.length ? new Date(Math.min(...ends.map((d) => d.getTime()))) : null;
|
||||
const graceEnds = endsAt ? new Date(endsAt.getTime() + (claims.graceDays || 0) * DAY) : null;
|
||||
if (claims.status === 'revoked') return { state: 'revoked', endsAt, daysLeft: null };
|
||||
if (claims.status === 'suspended') return { state: 'lapsed', endsAt, daysLeft: null };
|
||||
if (!endsAt || now < endsAt) return { state: 'active', endsAt, daysLeft: null };
|
||||
if (graceEnds && now < graceEnds) return { state: 'grace', endsAt, daysLeft: Math.ceil((graceEnds.getTime() - now.getTime()) / DAY) };
|
||||
return { state: 'lapsed', endsAt, daysLeft: null };
|
||||
}
|
||||
|
||||
export async function licenceStatus(ctx: Ctx) {
|
||||
const [installId, token] = await Promise.all([ctx.settings.get('hub_install_id'), ctx.settings.get('hub_licence')]);
|
||||
const claims = verifyToken(token, hubPublicKey(ctx));
|
||||
const valid = claims && claims.installId === installId ? claims : null;
|
||||
return { connected: !!installId, installId, claims: valid, ...stateFor(valid, installId, ctx.now()) };
|
||||
}
|
||||
|
||||
/** The church's Hub customer id (the same for every product), once the licence says it. */
|
||||
export async function customerId(ctx: Ctx): Promise<string | null> {
|
||||
return (await licenceStatus(ctx)).claims?.customerId ?? null;
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Starts the Church Website's backend: database, HTTP server, and (on a Hub install) registering
|
||||
* with the Hub from HUB_LICENCE_KEY, then heartbeats, which also link the site to the church's
|
||||
* Accounts once the Hub lists it. The other jobs (YouTube feed, storage count, sitemap, feed sync)
|
||||
* come with their features (docs/WEBSITE-1.0-PLAN.md §1).
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { PrismaClient } from './generated/prisma/client.js';
|
||||
import { createApp } from './app.js';
|
||||
import { createCtx } from './context.js';
|
||||
import { connectFromEnv, heartbeat, startHeartbeats } from './hub/client.js';
|
||||
import { loadConfig } from './lib/config.js';
|
||||
|
||||
async function main() {
|
||||
const config = loadConfig();
|
||||
const url = process.env.DATABASE_URL;
|
||||
if (!url) throw new Error('DATABASE_URL isn\'t set.');
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: url, connectionTimeoutMillis: 5000 }) });
|
||||
const ctx = createCtx(config, db);
|
||||
const app = createApp(ctx);
|
||||
const server = app.listen(config.port, () => console.log(`[website] Listening on ${config.port} (${config.publicUrl}).`));
|
||||
const stopHeartbeats = startHeartbeats(ctx);
|
||||
|
||||
connectFromEnv(ctx).then((r) => {
|
||||
if (r.connected || r.reason === 'already') heartbeat(ctx).catch(() => {});
|
||||
}).catch(() => {});
|
||||
|
||||
const stop = async () => {
|
||||
stopHeartbeats();
|
||||
server.close();
|
||||
await db.$disconnect();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on('SIGTERM', stop);
|
||||
process.on('SIGINT', stop);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error('[website] Failed to start:', e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* The admin audit log (who changed what, WEBSITE-1.0-PLAN §4). Logging never breaks the
|
||||
* action it records.
|
||||
*/
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export function clientIp(req: Request | undefined): string | null {
|
||||
return req ? (req.ip ?? req.socket?.remoteAddress ?? null) : null;
|
||||
}
|
||||
|
||||
export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole: string; action: string; targetType: string; targetId?: string | null; metadata?: object; ip?: string | null }) {
|
||||
try {
|
||||
await ctx.db.auditLog.create({ data: { ...entry, targetId: entry.targetId ?? null, metadata: (entry.metadata ?? undefined) as never, ip: entry.ip ?? null } });
|
||||
} catch (e) {
|
||||
console.error('[audit]', (e as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* The server's settings, from the environment (`.env`, built from `env.template.json`). Read once;
|
||||
* tests pass their own with `loadConfig({...})`.
|
||||
*/
|
||||
export type TrustProxy = false | number | string | string[];
|
||||
|
||||
export type Config = {
|
||||
/** The public address, e.g. https://www.hopefamily.co.za (no trailing slash). */
|
||||
publicUrl: string;
|
||||
port: number;
|
||||
/** Signs preview links and cookies, encrypts stored secrets. Generated on the server, never sent anywhere. */
|
||||
secret: string;
|
||||
production: boolean;
|
||||
/** Express's "trust proxy" (TRUST_PROXY, read as Accounts reads it), or false when off. */
|
||||
trustProxySetting: TrustProxy;
|
||||
hubUrl: string;
|
||||
hubLicenceKey: string | null;
|
||||
hubPublicKey: string | null;
|
||||
/** The church's contact from the Hub: the first person to sign in with this (verified) email becomes the Owner. */
|
||||
hubAdminName: string | null;
|
||||
hubAdminEmail: string | null;
|
||||
timezone: string;
|
||||
jobsEnabled: boolean;
|
||||
/** Where uploads go; default backend/uploads. */
|
||||
uploadDir: string | null;
|
||||
/** Local testing only: linked products (Accounts) on http or private addresses. */
|
||||
allowPrivateLinks: boolean;
|
||||
/** How long an admin stays signed in (days). */
|
||||
sessionDays: number;
|
||||
};
|
||||
|
||||
const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true');
|
||||
|
||||
/** As Accounts' trustProxyFrom: `loopback`, a hop count, addresses, `true` (one hop) or `false`. */
|
||||
export function trustProxyFrom(v: string | undefined, production: boolean): TrustProxy {
|
||||
const raw = (v ?? '').trim();
|
||||
if (raw === '') return production ? 1 : false;
|
||||
const lower = raw.toLowerCase();
|
||||
if (lower === 'true') return 1;
|
||||
if (lower === 'false') return false;
|
||||
if (/^\d+$/.test(raw)) return Number(raw) || false;
|
||||
return raw.includes(',') ? raw.split(',').map((s) => s.trim()).filter(Boolean) : raw;
|
||||
}
|
||||
|
||||
export function loadConfig(env: Record<string, string | undefined> = process.env): Config {
|
||||
const production = env.NODE_ENV === 'production';
|
||||
const secret = env.WEBSITE_SECRET || '';
|
||||
if (production && secret.length < 32) throw new Error('WEBSITE_SECRET must be set (at least 32 characters) in production.');
|
||||
return {
|
||||
publicUrl: String(env.WEBSITE_URL || 'http://localhost:3300').replace(/\/+$/, ''),
|
||||
port: Number(env.PORT || 5300),
|
||||
secret: secret || 'development-only-secret-change-me-0123456789',
|
||||
production,
|
||||
trustProxySetting: trustProxyFrom(env.TRUST_PROXY, production),
|
||||
hubUrl: String(env.HUB_URL || 'https://hub.crosscode.co.za').replace(/\/+$/, ''),
|
||||
hubLicenceKey: env.HUB_LICENCE_KEY?.trim() || null,
|
||||
hubPublicKey: env.HUB_PUBLIC_KEY?.trim() || null,
|
||||
hubAdminName: env.HUB_ADMIN_NAME?.trim() || null,
|
||||
hubAdminEmail: env.HUB_ADMIN_EMAIL?.trim().toLowerCase() || null,
|
||||
timezone: env.APP_TIMEZONE || 'Africa/Johannesburg',
|
||||
jobsEnabled: bool(env.JOBS_ENABLED, true),
|
||||
uploadDir: env.UPLOAD_DIR?.trim() || null,
|
||||
allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false),
|
||||
sessionDays: Math.min(90, Math.max(1, Number(env.SESSION_DAYS) || 14)),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Secrets at rest (AES-256-GCM, as Accounts' lib/crypto.ts), and tokens. The key comes from
|
||||
* WEBSITE_SECRET; encrypted values start with "enc:".
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
|
||||
const SENTINEL = 'enc:';
|
||||
|
||||
export class Secrets {
|
||||
private readonly key: Buffer;
|
||||
|
||||
constructor(secret: string) {
|
||||
this.key = crypto.scryptSync(secret, 'crosscode-website-aes256gcm-v1', 32);
|
||||
}
|
||||
|
||||
encrypt(plain: string): string {
|
||||
if (plain.startsWith(SENTINEL)) return plain;
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', this.key, iv);
|
||||
const data = Buffer.concat([cipher.update(plain, 'utf8'), cipher.final()]);
|
||||
return `${SENTINEL}${iv.toString('hex')}:${cipher.getAuthTag().toString('hex')}:${data.toString('hex')}`;
|
||||
}
|
||||
|
||||
/** Throws if the value was changed or encrypted with another key. */
|
||||
decrypt(value: string): string {
|
||||
if (!value.startsWith(SENTINEL)) return value;
|
||||
const [iv, tag, data] = value.slice(SENTINEL.length).split(':');
|
||||
if (!iv || !tag || data === undefined) throw new Error('Invalid encrypted value');
|
||||
const decipher = crypto.createDecipheriv('aes-256-gcm', this.key, Buffer.from(iv, 'hex'));
|
||||
decipher.setAuthTag(Buffer.from(tag, 'hex'));
|
||||
return Buffer.concat([decipher.update(Buffer.from(data, 'hex')), decipher.final()]).toString('utf8');
|
||||
}
|
||||
}
|
||||
|
||||
/** A random token for a cookie (32 bytes, base64url). */
|
||||
export const randomToken = () => crypto.randomBytes(32).toString('base64url');
|
||||
|
||||
/** What's stored for a token: only its SHA-256. */
|
||||
export const hashToken = (token: string) => crypto.createHash('sha256').update(token).digest('hex');
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* Site settings in `AppSetting` (key → string), as Accounts' lib/settings.ts. Secret ones are
|
||||
* encrypted at rest and never sent to the browser. A short cache keeps pages from reading the
|
||||
* table on every request.
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export const SECRET_SETTINGS = new Set(['hub_install_secret', 'hub_private_key']);
|
||||
|
||||
const TTL_MS = 30_000;
|
||||
|
||||
export class Settings {
|
||||
private cache = new Map<string, { value: string | null; at: number }>();
|
||||
|
||||
constructor(private readonly ctx: Pick<Ctx, 'db' | 'secrets'>) {}
|
||||
|
||||
async get(key: string): Promise<string | null> {
|
||||
const hit = this.cache.get(key);
|
||||
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
|
||||
const row = await this.ctx.db.appSetting.findUnique({ where: { key } });
|
||||
let value = row?.value ?? null;
|
||||
if (value !== null && SECRET_SETTINGS.has(key)) {
|
||||
try {
|
||||
value = this.ctx.secrets.decrypt(value);
|
||||
} catch {
|
||||
value = null;
|
||||
}
|
||||
}
|
||||
this.cache.set(key, { value, at: Date.now() });
|
||||
return value;
|
||||
}
|
||||
|
||||
async bool(key: string, fallback: boolean): Promise<boolean> {
|
||||
const v = await this.get(key);
|
||||
return v === null || v === '' ? fallback : v === 'true';
|
||||
}
|
||||
|
||||
async json<T>(key: string, fallback: T): Promise<T> {
|
||||
const v = await this.get(key);
|
||||
if (!v) return fallback;
|
||||
try {
|
||||
return JSON.parse(v) as T;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
async set(key: string, value: string | null): Promise<void> {
|
||||
if (value === null) await this.ctx.db.appSetting.deleteMany({ where: { key } });
|
||||
else {
|
||||
const stored = SECRET_SETTINGS.has(key) ? this.ctx.secrets.encrypt(value) : value;
|
||||
await this.ctx.db.appSetting.upsert({ where: { key }, update: { value: stored }, create: { key, value: stored } });
|
||||
}
|
||||
this.cache.delete(key);
|
||||
}
|
||||
|
||||
async setMany(values: Record<string, string | null>): Promise<void> {
|
||||
for (const [k, v] of Object.entries(values)) await this.set(k, v);
|
||||
}
|
||||
|
||||
forget(): void {
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* The running version, from the backend's package.json (src/lib → ../../package.json in development,
|
||||
* dist/lib → ../../package.json when built), so /api/health tells `crosscode deploy` the truth
|
||||
* however the process was started (PM2 doesn't set npm_package_version).
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
let cached: string | null = null;
|
||||
|
||||
export function appVersion(): string {
|
||||
if (!cached) {
|
||||
try {
|
||||
const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
|
||||
cached = (JSON.parse(fs.readFileSync(file, 'utf8')) as { version: string }).version;
|
||||
} catch {
|
||||
cached = '0.0.0';
|
||||
}
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Connect and Disconnect (`crosscode.link/1`, as Cross Events 2.4 and Accounts). The Website links
|
||||
* to the church's **Accounts** (signing in: the link's secret is where the client secret comes
|
||||
* from, and Accounts registers this site as an OIDC client when it accepts) and, for the event
|
||||
* feed, to **Events** and later the **App**.
|
||||
*
|
||||
* Trust comes from the Hub's list on both sides: a message is accepted only from an install in this
|
||||
* site's cached `linkedProducts` (same church), signed with the key the Hub listed for it.
|
||||
*/
|
||||
import {
|
||||
LINK_PATHS, LINK_SCHEMA, linkConnectedSchema, linkConnectSchema, linkDisconnectSchema,
|
||||
type hub, type LinkConnect, type LinkConnected, type LinkDisconnect,
|
||||
} from '@crosscode/contracts';
|
||||
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||
import type { Request } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit, clientIp } from '../lib/audit.js';
|
||||
import { callSibling, LinkCallError, siblingUrl } from './http.js';
|
||||
import { keyPair, linkedProducts, listedProduct } from './store.js';
|
||||
|
||||
export class LinkError extends Error {
|
||||
constructor(message: string, public code: string, public status = 400) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The products the Website links to. */
|
||||
const LINKABLE = new Set(['accounts', 'events', 'app']);
|
||||
const NONCE_KEEP_MS = 60 * 60 * 1000;
|
||||
|
||||
type Actor = { id: string | null; role: string };
|
||||
|
||||
async function self(ctx: Ctx) {
|
||||
const installId = await ctx.settings.get('hub_install_id');
|
||||
if (!installId) throw new LinkError('The Website isn\'t connected to the Hub yet, so it can\'t link to other products.', 'LINKS_UNAVAILABLE', 503);
|
||||
const { privateKeyPem } = await keyPair(ctx);
|
||||
return { installId, url: ctx.config.publicUrl, privateKeyPem };
|
||||
}
|
||||
|
||||
const party = (s: { installId: string; url: string }) => ({ product: 'website' as const, installId: s.installId, url: s.url });
|
||||
|
||||
async function firstUse(ctx: Ctx, nonce: string): Promise<boolean> {
|
||||
const now = ctx.now();
|
||||
await ctx.db.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
|
||||
try {
|
||||
await ctx.db.linkNonce.create({ data: { nonce, seenAt: now } });
|
||||
return true;
|
||||
} catch (e) {
|
||||
if ((e as { code?: string }).code === 'P2002') return false;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveLink(ctx: Ctx, sibling: hub.LinkedProduct, secret: string, connectedById: string | null) {
|
||||
const data = { product: sibling.product, url: sibling.url.replace(/\/+$/, ''), publicKey: sibling.publicKey, secret: ctx.secrets.encrypt(secret), connectedAt: ctx.now(), connectedById, lastSyncError: null };
|
||||
return ctx.db.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
|
||||
}
|
||||
|
||||
const logLink = (ctx: Ctx, action: string, link: { installId: string; product: string }, actor: Actor | null, req: Request | undefined, by: string) =>
|
||||
audit(ctx, { actorId: actor?.id ?? null, actorRole: actor?.role ?? 'linked_product', action, targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, by }, ip: clientIp(req) });
|
||||
|
||||
/** This site connects (an admin pressed Connect, or the automatic connect to Accounts below). */
|
||||
export async function connectTo(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
|
||||
const sibling = await listedProduct(ctx, installId);
|
||||
if (!sibling || !LINKABLE.has(sibling.product)) 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(ctx);
|
||||
const secret = newLinkSecret();
|
||||
const message = signLink<Omit<LinkConnect, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connect', from: party(me), to: { installId: sibling.installId }, secret, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
let reply: unknown;
|
||||
try {
|
||||
reply = await callSibling(await siblingUrl(ctx, 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;
|
||||
if (!verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey, { now: ctx.now() }).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(ctx, sibling, secret, actor.id);
|
||||
await logLink(ctx, 'product_link_connected', link, actor, req, 'website');
|
||||
return link;
|
||||
}
|
||||
|
||||
/** Answers `POST /api/links/v1/connect` (a sibling's admin pressed Connect there). */
|
||||
export async function acceptConnect(ctx: Ctx, body: unknown, req?: Request): 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(ctx);
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const sibling = await listedProduct(ctx, m.from.installId);
|
||||
if (!sibling || sibling.product !== m.from.product || !LINKABLE.has(sibling.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: ctx.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(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
const link = await saveLink(ctx, sibling, m.secret, null);
|
||||
await logLink(ctx, 'product_link_connected', link, null, req, sibling.product);
|
||||
return signLink<Omit<LinkConnected, 'signature'>>({
|
||||
schema: LINK_SCHEMA, type: 'link.connected', from: party(me), to: { installId: sibling.installId }, inReplyTo: m.nonce, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce(),
|
||||
}, me.privateKeyPem);
|
||||
}
|
||||
|
||||
/** This site ends a link. The local link goes even if the sibling can't be reached. */
|
||||
export async function disconnectFrom(ctx: Ctx, installId: string, actor: Actor, req?: Request) {
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId } });
|
||||
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
|
||||
let told = false;
|
||||
let problem: string | null = null;
|
||||
try {
|
||||
const me = await self(ctx);
|
||||
const message = signLink<Omit<LinkDisconnect, 'signature'>>({ schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: ctx.now().toISOString(), nonce: newLinkNonce() }, me.privateKeyPem);
|
||||
await callSibling(await siblingUrl(ctx, link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
|
||||
told = true;
|
||||
} catch (e) {
|
||||
problem = (e as Error).message;
|
||||
}
|
||||
await ctx.db.productLink.delete({ where: { installId } });
|
||||
await logLink(ctx, 'product_link_disconnected', link, actor, req, 'website');
|
||||
return { told, problem };
|
||||
}
|
||||
|
||||
/** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */
|
||||
export async function acceptDisconnect(ctx: Ctx, body: unknown, req?: Request): 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(ctx);
|
||||
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||
const link = await ctx.db.productLink.findUnique({ where: { installId: m.from.installId } });
|
||||
if (!link) return;
|
||||
if (!verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now: ctx.now() }).ok) throw new LinkError('The signature doesn\'t match this link.', 'BAD_SIGNATURE', 401);
|
||||
if (!(await firstUse(ctx, m.nonce))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||
await ctx.db.productLink.delete({ where: { installId: link.installId } });
|
||||
await logLink(ctx, 'product_link_disconnected', link, null, req, link.product);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Website signs in through Accounts, so it connects to the church's Accounts by itself once the
|
||||
* Hub lists one and nothing is linked yet (as Events 3.x's autoConnect). Run after each heartbeat.
|
||||
* Never throws: a failure is tried again at the next heartbeat.
|
||||
*/
|
||||
export async function connectAccountsIfListed(ctx: Ctx): Promise<'connected' | 'skipped' | 'failed'> {
|
||||
if (await ctx.db.productLink.findFirst({ where: { product: 'accounts' } })) return 'skipped';
|
||||
const listed = (await linkedProducts(ctx)).find((p) => p.product === 'accounts');
|
||||
if (!listed) return 'skipped';
|
||||
try {
|
||||
await connectTo(ctx, listed.installId, { id: null, role: 'system' });
|
||||
return 'connected';
|
||||
} catch (e) {
|
||||
console.warn('[links] Connecting to Accounts failed:', (e as Error).message);
|
||||
return 'failed';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* Calls to a linked product: https only, never a private address (unless LINKS_ALLOW_PRIVATE for
|
||||
* local testing), no redirects, a timeout and a size limit (as Cross Events 2.4's links/http.ts).
|
||||
*/
|
||||
import dns from 'node:dns/promises';
|
||||
import net from 'node:net';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
export function isPrivateAddress(ip: string): boolean {
|
||||
if (net.isIPv4(ip)) {
|
||||
const [a, b] = ip.split('.').map(Number) as [number, number];
|
||||
return a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
|
||||
}
|
||||
if (net.isIPv6(ip)) {
|
||||
const v = ip.toLowerCase();
|
||||
if (v === '::1' || v === '::') return true;
|
||||
const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(v);
|
||||
if (mapped) return isPrivateAddress(mapped[1]!);
|
||||
return /^f[cd]/.test(v) || /^fe[89ab]/.test(v);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function siblingUrl(ctx: Ctx, base: string, path: 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);
|
||||
}
|
||||
const allow = ctx.config.allowPrivateLinks;
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allow)) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
|
||||
if (!allow) {
|
||||
const addrs = net.isIP(url.hostname) ? [{ address: url.hostname }] : await dns.lookup(url.hostname, { all: true }).catch(() => []);
|
||||
if (!addrs.length || addrs.some((a) => isPrivateAddress(a.address))) throw new LinkCallError(`${url.hostname} points to a private network address`, 'PRIVATE_ADDRESS', 400);
|
||||
}
|
||||
return url;
|
||||
}
|
||||
|
||||
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}`, 'UNREACHABLE');
|
||||
}
|
||||
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
|
||||
const text = await res.text();
|
||||
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
|
||||
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,34 @@
|
||||
/**
|
||||
* 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 }`.
|
||||
*/
|
||||
import express from 'express';
|
||||
import { LINK_PATHS } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from './connect.js';
|
||||
|
||||
export function linksRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
const json = express.json({ limit: '32kb' });
|
||||
const fail = (res: express.Response, e: unknown) => {
|
||||
if (e instanceof LinkError) return res.status(e.status).json({ code: e.code, message: e.message });
|
||||
console.error('[links]', e);
|
||||
return res.status(500).json({ code: 'INTERNAL', message: 'Something went wrong.' });
|
||||
};
|
||||
r.post(LINK_PATHS.connect.replace(/^\/api/, ''), json, async (req, res) => {
|
||||
try {
|
||||
res.json(await acceptConnect(ctx, req.body, req));
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
});
|
||||
r.post(LINK_PATHS.disconnect.replace(/^\/api/, ''), json, async (req, res) => {
|
||||
try {
|
||||
await acceptDisconnect(ctx, req.body, req);
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
fail(res, e);
|
||||
}
|
||||
});
|
||||
return r;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* This install's Ed25519 key pair and the church's other installs as the Hub last listed them
|
||||
* (as Cross Events 2.4's links/store.ts). Settings: hub_private_key (encrypted), hub_public_key,
|
||||
* hub_linked_products.
|
||||
*/
|
||||
import { hub } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
type LinkedProduct = hub.LinkedProduct;
|
||||
|
||||
export async function keyPair(ctx: Ctx): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
|
||||
const [priv, pub] = await Promise.all([ctx.settings.get('hub_private_key'), ctx.settings.get('hub_public_key')]);
|
||||
if (priv && pub) return { privateKeyPem: priv, publicKeyPem: pub };
|
||||
const pair = generateEd25519();
|
||||
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
|
||||
await ctx.settings.setMany({ hub_private_key: pair.privateKeyPem, hub_public_key: publicKeyPem });
|
||||
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
|
||||
}
|
||||
|
||||
export async function linkedProducts(ctx: Ctx): Promise<LinkedProduct[]> {
|
||||
const list = await ctx.settings.json<unknown[]>('hub_linked_products', []);
|
||||
return Array.isArray(list) ? (list.filter((l) => hub.linkedProductSchema.safeParse(l).success) as LinkedProduct[]) : [];
|
||||
}
|
||||
|
||||
export async function saveLinkedProducts(ctx: Ctx, list: unknown): Promise<void> {
|
||||
if (!Array.isArray(list)) return;
|
||||
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data).slice(0, 10);
|
||||
await ctx.settings.set('hub_linked_products', JSON.stringify(clean));
|
||||
}
|
||||
|
||||
export async function listedProduct(ctx: Ctx, installId: string): Promise<LinkedProduct | null> {
|
||||
return (await linkedProducts(ctx)).find((l) => l.installId === installId) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
/**
|
||||
* Everything the public site needs to draw a page (WEBSITE-1.0-PLAN §1): the latest published
|
||||
* snapshot, the church profile from Accounts, the colours made safe, the fonts and corners, and
|
||||
* the messages and events (which publish on their own, so they're read live). Before the first
|
||||
* publish: Coming soon, from the profile alone (§5).
|
||||
*/
|
||||
import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { churchProfile } from '../church/profile.js';
|
||||
import { buildPalette, type Palette } from './palette.js';
|
||||
import { mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
|
||||
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
|
||||
|
||||
export type SiteEvent = {
|
||||
title: string;
|
||||
summary: string | null;
|
||||
startsAt: string;
|
||||
endsAt: string | null;
|
||||
allDay: boolean;
|
||||
location: string | null;
|
||||
image: Image | null;
|
||||
/** The event's page: on this site, or at its origin (Cross Events, for registering). */
|
||||
url: string;
|
||||
from: 'website' | 'events' | 'app';
|
||||
registration: { status: string; priceFromCents: number | null } | null;
|
||||
};
|
||||
|
||||
export type SiteMessage = {
|
||||
slug: string;
|
||||
title: string;
|
||||
date: string;
|
||||
speaker: string | null;
|
||||
series: string | null;
|
||||
passage: string | null;
|
||||
source: 'youtube' | 'spotify';
|
||||
/** For the embed (youtube-nocookie) or the Spotify player, loaded only when clicked. */
|
||||
embedUrl: string | null;
|
||||
url: string;
|
||||
thumbnail: string | null;
|
||||
};
|
||||
|
||||
type Common = {
|
||||
church: Church | null;
|
||||
palette: Palette;
|
||||
/** The shared brand style, else what the template suggests (§3). */
|
||||
style: { fontPairing: string; corners: string };
|
||||
};
|
||||
|
||||
export type SiteContent =
|
||||
| (Common & { mode: 'coming-soon'; template: WebsiteTemplate; comingSoonText: string })
|
||||
| (Common & {
|
||||
mode: 'published';
|
||||
version: number;
|
||||
snapshot: Snapshot;
|
||||
/** Per page path: whether the header sits over the hero (Bold's transparent header, §3). */
|
||||
transparentHeader: Record<string, boolean>;
|
||||
messages: SiteMessage[];
|
||||
events: SiteEvent[];
|
||||
});
|
||||
|
||||
const DEFAULT_COLOUR = '#1f4e79';
|
||||
|
||||
function brandFor(church: Church | null, template: WebsiteTemplate) {
|
||||
return {
|
||||
palette: buildPalette(church?.branding.colours.primary ?? DEFAULT_COLOUR, church?.branding.colours.accent ?? null),
|
||||
style: {
|
||||
fontPairing: church?.branding.style?.fontPairing ?? TEMPLATE_FONT_PAIRINGS[template][0],
|
||||
corners: church?.branding.style?.corners ?? TEMPLATE_STYLE[template].suggestedCorners,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** `https://www.youtube.com/watch?v=abc` → its id; null for anything else. */
|
||||
export function youtubeId(url: string): string | null {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
if (u.hostname === 'youtu.be') return u.pathname.slice(1) || null;
|
||||
if (/(^|\.)youtube(-nocookie)?\.com$/.test(u.hostname)) return u.searchParams.get('v') ?? (/^\/(embed|shorts|live)\/([\w-]+)/.exec(u.pathname)?.[2] ?? null);
|
||||
} catch {
|
||||
// Not a URL.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** `https://open.spotify.com/episode/abc` → the embed address; null for anything else. */
|
||||
export function spotifyEmbed(url: string): string | null {
|
||||
const m = /^https:\/\/open\.spotify\.com\/(episode|show)\/([A-Za-z0-9]+)/.exec(url);
|
||||
return m ? `https://open.spotify.com/embed/${m[1]}/${m[2]}` : null;
|
||||
}
|
||||
|
||||
async function liveMessages(ctx: Ctx): Promise<SiteMessage[]> {
|
||||
const rows = await ctx.db.message.findMany({ where: { hidden: false, publishedAt: { not: null } }, orderBy: { date: 'desc' }, take: 24, include: { series: true } });
|
||||
return rows.map((m) => {
|
||||
const yt = m.source === 'spotify' ? null : youtubeId(m.mediaUrl);
|
||||
return {
|
||||
slug: m.slug, title: m.title, date: m.date.toISOString(), speaker: m.speaker, series: m.series?.title ?? null, passage: m.passage,
|
||||
source: m.source === 'spotify' ? 'spotify' : 'youtube',
|
||||
embedUrl: yt ? `https://www.youtube-nocookie.com/embed/${yt}?autoplay=1` : spotifyEmbed(m.mediaUrl),
|
||||
url: m.mediaUrl,
|
||||
thumbnail: m.thumbnailUrl ?? (yt ? `https://i.ytimg.com/vi/${yt}/hqdefault.jpg` : null),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
|
||||
const now = ctx.now();
|
||||
const [simple, imported, media] = await Promise.all([
|
||||
ctx.db.simpleEvent.findMany({ where: { publishedAt: { not: null }, cancelled: false, OR: [{ startsAt: { gte: now } }, { endsAt: { gte: now } }] }, orderBy: { startsAt: 'asc' }, take: 50 }),
|
||||
ctx.db.importedEvent.findMany({ where: { startsAt: { gte: new Date(now.getTime() - 7 * 864e5) } }, orderBy: { startsAt: 'asc' }, take: 50 }),
|
||||
ctx.db.mediaAsset.findMany(),
|
||||
]);
|
||||
const image = (id: string | null) => {
|
||||
const m = id ? media.find((x) => x.id === id) : null;
|
||||
return m ? { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } : null;
|
||||
};
|
||||
const own: SiteEvent[] = simple.map((e) => ({
|
||||
title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null,
|
||||
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, from: 'website', registration: null,
|
||||
}));
|
||||
const copies: SiteEvent[] = imported.flatMap((row) => {
|
||||
const e = row.data as unknown as CrosscodeEvent;
|
||||
if (!e?.title || (e.endsAt ? new Date(e.endsAt) < now : new Date(e.startsAt) < now)) return [];
|
||||
return [{
|
||||
title: e.title, summary: e.summary ?? null, startsAt: e.startsAt, endsAt: e.endsAt ?? null, allDay: !!e.allDay, location: e.location?.name ?? null,
|
||||
image: e.imageUrl ? { url: e.imageUrl, alt: e.title, width: null, height: null } : null, url: e.origin.url, from: e.origin.product,
|
||||
registration: e.registration ? { status: e.registration.status, priceFromCents: e.registration.priceFrom?.amountCents ?? null } : null,
|
||||
} satisfies SiteEvent];
|
||||
});
|
||||
return [...own, ...copies].sort((a, b) => a.startsAt.localeCompare(b.startsAt));
|
||||
}
|
||||
|
||||
export async function siteContent(ctx: Ctx): Promise<SiteContent> {
|
||||
const [church, published] = await Promise.all([churchProfile(ctx), publishedSnapshot(ctx)]);
|
||||
if (!published) {
|
||||
const design = await ctx.db.siteDesign.findUnique({ where: { id: 1 }, select: { template: true } });
|
||||
const template = (design?.template ?? 'heritage') as WebsiteTemplate;
|
||||
return {
|
||||
mode: 'coming-soon', template, church, ...brandFor(church, template),
|
||||
comingSoonText: (await ctx.settings.get('coming_soon_text')) || 'Our new website is on its way.',
|
||||
};
|
||||
}
|
||||
const { snapshot } = published;
|
||||
const template = snapshot.design.template;
|
||||
const transparentHeader = Object.fromEntries(snapshot.pages.map((p) => {
|
||||
const hero = p.sections[0]?.type === 'hero' ? (p.sections[0].variant as Variant<'hero'>) : null;
|
||||
return [p.path, headerIsTransparent(template, snapshot.design.style.header, hero)];
|
||||
}));
|
||||
const [messages, events] = await Promise.all([liveMessages(ctx), liveEvents(ctx)]);
|
||||
return { mode: 'published', version: published.number, snapshot, transparentHeader, church, ...brandFor(church, template), messages, events };
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* The site's colours from the church's two (WEBSITE-1.0-PLAN §3, "Colours from the church, made
|
||||
* safe"): tints and shades, the text colour on each, all checked against WCAG AA (4.5:1 for text).
|
||||
* A colour that fails is darkened (or lightened) until it passes, and the admin is told why.
|
||||
*/
|
||||
|
||||
export type Rgb = [number, number, number];
|
||||
|
||||
const AA = 4.5;
|
||||
const WHITE: Rgb = [255, 255, 255];
|
||||
const INK: Rgb = [17, 24, 39];
|
||||
|
||||
export function hexToRgb(hex: string): Rgb {
|
||||
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
|
||||
const n = parseInt(m ? m[1]! : '1f4e79', 16);
|
||||
return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||
}
|
||||
|
||||
export const rgbToHex = (c: Rgb) => `#${c.map((x) => Math.round(x).toString(16).padStart(2, '0')).join('')}`;
|
||||
|
||||
/** "31 78 121": for Tailwind's `rgb(var(--brand) / <alpha-value>)`. */
|
||||
export const triple = (c: Rgb) => c.map((x) => Math.round(x)).join(' ');
|
||||
|
||||
function luminance([r, g, b]: Rgb): number {
|
||||
const lin = (v: number) => {
|
||||
const s = v / 255;
|
||||
return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
|
||||
};
|
||||
return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
|
||||
}
|
||||
|
||||
export function contrast(a: Rgb, b: Rgb): number {
|
||||
const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p) as [number, number];
|
||||
return (x + 0.05) / (y + 0.05);
|
||||
}
|
||||
|
||||
/** `c` mixed with `to` by `t` (0 = c, 1 = to). */
|
||||
export const mix = (c: Rgb, to: Rgb, t: number): Rgb => [0, 1, 2].map((i) => c[i]! + (to[i]! - c[i]!) * t) as Rgb;
|
||||
|
||||
/** The nearest shade of `c` (towards black) that reaches `ratio` against `against`. */
|
||||
function darkenUntil(c: Rgb, against: Rgb, ratio = AA): Rgb {
|
||||
for (let t = 0; t <= 1; t += 0.02) {
|
||||
const d = mix(c, [0, 0, 0], t);
|
||||
if (contrast(d, against) >= ratio) return d;
|
||||
}
|
||||
return [0, 0, 0];
|
||||
}
|
||||
|
||||
export type Palette = {
|
||||
/** The church's colour as a background (buttons, bands), with `onBrand` text on it. */
|
||||
brand: string;
|
||||
brandDark: string;
|
||||
onBrand: string;
|
||||
/** The church's colour as text or a link on white: darkened when it's too light to read. */
|
||||
brandText: string;
|
||||
/** A soft background in the church's colour (Section colour "Tinted"). */
|
||||
brandTint: string;
|
||||
accent: string;
|
||||
onAccent: string;
|
||||
/** What was changed and why, for the admin (§3: "the admin is told why"). */
|
||||
notes: string[];
|
||||
};
|
||||
|
||||
export function buildPalette(primaryHex: string, accentHex: string | null): Palette {
|
||||
const notes: string[] = [];
|
||||
const primary = hexToRgb(primaryHex);
|
||||
const accent = accentHex ? hexToRgb(accentHex) : mix(primary, WHITE, 0.25);
|
||||
|
||||
// Text on the brand colour: white when it reads, else dark ink; if neither reaches AA, the
|
||||
// background is darkened until white does.
|
||||
let brand = primary;
|
||||
let onBrand = contrast(WHITE, brand) >= AA ? WHITE : contrast(INK, brand) >= AA ? INK : null;
|
||||
if (!onBrand) {
|
||||
brand = darkenUntil(primary, WHITE);
|
||||
onBrand = WHITE;
|
||||
notes.push(`Your main colour ${rgbToHex(primary)} is darkened to ${rgbToHex(brand)} behind text, so the text on buttons and bands can be read.`);
|
||||
}
|
||||
|
||||
const brandTextRgb = contrast(primary, WHITE) >= AA ? primary : darkenUntil(primary, WHITE);
|
||||
if (brandTextRgb !== primary) notes.push(`Links and headings in your main colour use a darker shade (${rgbToHex(brandTextRgb)}), so they can be read on white.`);
|
||||
|
||||
const onAccent = contrast(WHITE, accent) >= AA ? WHITE : INK;
|
||||
if (contrast(onAccent, accent) < AA) notes.push(`Your accent colour ${rgbToHex(accent)} is only used for decoration: text on it would be hard to read.`);
|
||||
|
||||
return {
|
||||
brand: triple(brand),
|
||||
brandDark: triple(mix(brand, [0, 0, 0], 0.2)),
|
||||
onBrand: triple(onBrand),
|
||||
brandText: triple(brandTextRgb),
|
||||
brandTint: triple(mix(primary, WHITE, 0.92)),
|
||||
accent: triple(accent),
|
||||
onAccent: triple(onAccent),
|
||||
notes,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* What an admin fills in for each homepage section (WEBSITE-1.0-PLAN §2: "every section stores its
|
||||
* data, validated with a zod schema per section type"). Never tied to a template: every template
|
||||
* draws every variant from the same data (§3). Lists (ministries, leaders, events, messages) come
|
||||
* from their own tables; the section only holds its heading and intro.
|
||||
*
|
||||
* Images are media ids here; the published snapshot turns them into `{ url, alt }`.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import type { SectionType } from './variants.js';
|
||||
|
||||
const text = (max: number) => z.string().trim().max(max);
|
||||
const optional = (max: number) => text(max).nullable().default(null);
|
||||
const mediaId = z.string().uuid();
|
||||
/** A link on the site (`/visit`) or elsewhere (https only). */
|
||||
const href = z.string().trim().max(500).refine((v) => /^\/(?!\/)/.test(v) || /^https:\/\//.test(v), 'A page of this site (/visit) or an https:// address');
|
||||
const button = z.object({ label: text(60).min(1), href }).nullable().default(null);
|
||||
|
||||
export const SECTION_SCHEMAS = {
|
||||
hero: z.object({
|
||||
headline: text(120).min(1),
|
||||
subline: optional(300),
|
||||
/** `photo` and `split` use the first; `collage` up to three. */
|
||||
images: z.array(mediaId).max(3).default([]),
|
||||
/** `video`: a short muted loop (an uploaded .mp4) shown over its still (the first image). */
|
||||
videoId: mediaId.nullable().default(null),
|
||||
button,
|
||||
}),
|
||||
serviceTimes: z.object({
|
||||
heading: optional(80),
|
||||
/** E.g. "Kids church during the morning service". Times and address come from the church profile. */
|
||||
note: optional(300),
|
||||
}),
|
||||
welcome: z.object({
|
||||
heading: optional(120),
|
||||
/** The mission line, above the introduction in every variant (§3). */
|
||||
mission: optional(200),
|
||||
body: text(4000).default(''),
|
||||
imageId: mediaId.nullable().default(null),
|
||||
pastor: z.object({ name: text(120).min(1), role: optional(80), quote: optional(400), photoId: mediaId.nullable().default(null) }).nullable().default(null),
|
||||
}),
|
||||
ministries: z.object({ heading: optional(80), intro: optional(400) }),
|
||||
team: z.object({ heading: optional(80), intro: optional(400) }),
|
||||
events: z.object({ heading: optional(80), count: z.int().min(2).max(12).default(3) }),
|
||||
latestMessage: z.object({ heading: optional(80) }),
|
||||
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null) }),
|
||||
} as const satisfies Record<SectionType, z.ZodType>;
|
||||
|
||||
export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)[S]> };
|
||||
|
||||
/** Blocks for the other pages and custom pages (§3, "Pages from blocks"); more come with the admin. */
|
||||
export const BLOCK_SCHEMAS = {
|
||||
text: z.object({ heading: optional(120), body: text(20000) }),
|
||||
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button }),
|
||||
quote: z.object({ quote: text(600).min(1), by: optional(120) }),
|
||||
cta: z.object({ heading: text(120).min(1), text: optional(400), button }),
|
||||
} as const;
|
||||
|
||||
export type BlockType = keyof typeof BLOCK_SCHEMAS;
|
||||
export const isBlockType = (t: string): t is BlockType => t in BLOCK_SCHEMAS;
|
||||
|
||||
/** A section's or block's data, checked; null when it doesn't fit (it's then left out, never shown broken). */
|
||||
export function parseSectionData(type: string, data: unknown): Record<string, unknown> | null {
|
||||
const schema = (SECTION_SCHEMAS as Record<string, z.ZodType>)[type] ?? (BLOCK_SCHEMAS as Record<string, z.ZodType>)[type];
|
||||
if (!schema) return null;
|
||||
const r = schema.safeParse(data ?? {});
|
||||
return r.success ? (r.data as Record<string, unknown>) : null;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Published versions (WEBSITE-1.0-PLAN §4): Publish copies the working copy into an immutable
|
||||
* snapshot (`SiteVersion.snapshot`), and visitors always see the latest. The snapshot holds the
|
||||
* site's design and every page with its sections, ministries and leaders, with images already
|
||||
* turned into `{ url, alt }`, so showing the site never reads the working copy.
|
||||
*
|
||||
* Messages and simple events aren't in it: they publish on their own (decision 9) and are read
|
||||
* live (content.ts).
|
||||
*/
|
||||
import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { parseSectionData } from './sections.js';
|
||||
import { defaultDesign, isVariant, SECTION_TYPES, type SectionType, type SiteDesign } from './variants.js';
|
||||
|
||||
export const SNAPSHOT_VERSION = 1;
|
||||
|
||||
export type Image = { url: string; alt: string; width: number | null; height: number | null };
|
||||
|
||||
export type SnapshotSection = { type: string; variant: string | null; data: Record<string, unknown> };
|
||||
|
||||
export type SnapshotPage = {
|
||||
kind: string;
|
||||
slug: string;
|
||||
/** `/` for home, else `/<slug>`. */
|
||||
path: string;
|
||||
title: string;
|
||||
seoTitle: string | null;
|
||||
description: string | null;
|
||||
navLabel: string;
|
||||
inNav: boolean;
|
||||
image: Image | null;
|
||||
sections: SnapshotSection[];
|
||||
};
|
||||
|
||||
export type Snapshot = {
|
||||
v: typeof SNAPSHOT_VERSION;
|
||||
design: SiteDesign;
|
||||
pages: SnapshotPage[];
|
||||
ministries: { slug: string; name: string; summary: string | null; body: string | null; image: Image | null }[];
|
||||
leaders: { name: string; role: string | null; bio: string | null; photo: Image | null }[];
|
||||
/** Every image the sections refer to, by media id. */
|
||||
media: Record<string, Image>;
|
||||
};
|
||||
|
||||
export const mediaUrl = (filename: string) => `/api/uploads/${filename.split('/').map(encodeURIComponent).join('/')}`;
|
||||
|
||||
/** The design as saved, made safe: an unknown template, variant or section falls back to the default. */
|
||||
export function cleanDesign(saved: { template: string; variants: unknown; home: unknown; style: unknown } | null): SiteDesign {
|
||||
const template: WebsiteTemplate = saved && (WEBSITE_TEMPLATES as readonly string[]).includes(saved.template) ? (saved.template as WebsiteTemplate) : 'heritage';
|
||||
const base = defaultDesign(template);
|
||||
if (!saved) return base;
|
||||
const variants = { ...base.variants } as Record<SectionType, string>;
|
||||
const v = (saved.variants ?? {}) as Record<string, unknown>;
|
||||
for (const s of SECTION_TYPES) if (typeof v[s] === 'string' && isVariant(s, v[s] as string)) variants[s] = v[s] as string;
|
||||
const home = Array.isArray(saved.home)
|
||||
? (saved.home as { section?: unknown; hidden?: unknown }[]).filter((e) => SECTION_TYPES.includes(e?.section as SectionType)).map((e) => ({ section: e.section as SectionType, hidden: !!e.hidden }))
|
||||
: base.home;
|
||||
// Every section listed once: any missing one is added at the end, hidden.
|
||||
for (const s of SECTION_TYPES) if (!home.some((e) => e.section === s)) home.push({ section: s, hidden: true });
|
||||
const style = { ...base.style, ...Object.fromEntries(Object.entries((saved.style ?? {}) as Record<string, unknown>).filter(([, x]) => typeof x === 'string')) };
|
||||
return { template, variants: variants as SiteDesign['variants'], home: home.filter((e, i) => home.findIndex((x) => x.section === e.section) === i), style };
|
||||
}
|
||||
|
||||
/** The working copy as a snapshot. */
|
||||
export async function buildSnapshot(ctx: Ctx): Promise<Snapshot> {
|
||||
const db = ctx.db;
|
||||
const [design, pages, ministries, leaders, media] = await Promise.all([
|
||||
db.siteDesign.findUnique({ where: { id: 1 } }),
|
||||
db.page.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { title: 'asc' }], include: { sections: { orderBy: { position: 'asc' } } } }),
|
||||
db.ministry.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
db.leader.findMany({ where: { archivedAt: null }, orderBy: [{ position: 'asc' }, { name: 'asc' }] }),
|
||||
db.mediaAsset.findMany(),
|
||||
]);
|
||||
const images = new Map(media.map((m) => [m.id, { url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height } satisfies Image]));
|
||||
const image = (id: string | null | undefined) => (id ? images.get(id) ?? null : null);
|
||||
const used: Record<string, Image> = {};
|
||||
const collect = (data: unknown) => {
|
||||
// Every media id anywhere in a section's data (images, videoId, imageId, photoId).
|
||||
const walk = (x: unknown) => {
|
||||
if (typeof x === 'string' && images.has(x)) used[x] = images.get(x)!;
|
||||
else if (Array.isArray(x)) x.forEach(walk);
|
||||
else if (x && typeof x === 'object') Object.values(x).forEach(walk);
|
||||
};
|
||||
walk(data);
|
||||
};
|
||||
const d = cleanDesign(design);
|
||||
const snapshotPages: SnapshotPage[] = pages.map((p) => {
|
||||
const sections: SnapshotSection[] = [];
|
||||
if (p.kind === 'home') {
|
||||
// The homepage: the design's order and variants, each section's data from the page.
|
||||
const byType = new Map(p.sections.map((s) => [s.type, s]));
|
||||
for (const entry of d.home) {
|
||||
if (entry.hidden) continue;
|
||||
const data = parseSectionData(entry.section, byType.get(entry.section)?.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: entry.section, variant: d.variants[entry.section], data });
|
||||
}
|
||||
} else {
|
||||
for (const s of p.sections) {
|
||||
if (s.hidden) continue;
|
||||
const data = parseSectionData(s.type, s.data);
|
||||
if (!data) continue;
|
||||
collect(data);
|
||||
sections.push({ type: s.type, variant: s.variant, data });
|
||||
}
|
||||
}
|
||||
return {
|
||||
kind: p.kind, slug: p.slug, path: p.kind === 'home' ? '/' : `/${p.slug}`, title: p.title, seoTitle: p.seoTitle, description: p.description,
|
||||
navLabel: p.navLabel || p.title, inNav: p.inNav && p.kind !== 'home', image: image(p.imageId), sections,
|
||||
};
|
||||
});
|
||||
return {
|
||||
v: SNAPSHOT_VERSION,
|
||||
design: d,
|
||||
pages: snapshotPages,
|
||||
ministries: ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
|
||||
leaders: leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
|
||||
media: used,
|
||||
};
|
||||
}
|
||||
|
||||
/** Publish (§4): the whole working copy becomes the next version, at once. */
|
||||
export async function publish(ctx: Ctx, by: { id: string; role: string }, note: string | null = null) {
|
||||
const snapshot = await buildSnapshot(ctx);
|
||||
const last = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true } });
|
||||
const version = await ctx.db.siteVersion.create({
|
||||
data: { number: (last?.number ?? 0) + 1, snapshot: snapshot as never, note, publishedBy: by.id, publishedAt: ctx.now() },
|
||||
});
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'site_published', targetType: 'site_version', targetId: String(version.number), metadata: { note } });
|
||||
return version;
|
||||
}
|
||||
|
||||
/** The latest published snapshot, or null before the first publish (Coming soon). */
|
||||
export async function publishedSnapshot(ctx: Ctx): Promise<{ number: number; publishedAt: Date; snapshot: Snapshot } | null> {
|
||||
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' } });
|
||||
if (!latest) return null;
|
||||
const snap = latest.snapshot as unknown as Snapshot;
|
||||
if (!snap || snap.v !== SNAPSHOT_VERSION) return null;
|
||||
return { number: latest.number, publishedAt: latest.publishedAt, snapshot: { ...snap, design: cleanDesign(snap.design as never) } };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* What the public site shows right now: Coming soon until the first publish (§5, decision 3), then
|
||||
* the latest published version. After the first publish there's no going back to Coming soon.
|
||||
*/
|
||||
import { WEBSITE_TEMPLATES, type WebsiteTemplate } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
export type SiteStatus =
|
||||
| { mode: 'coming-soon' }
|
||||
| { mode: 'published'; version: number; publishedAt: string; template: WebsiteTemplate | null };
|
||||
|
||||
export async function siteStatus(ctx: Ctx): Promise<SiteStatus> {
|
||||
const latest = await ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { number: true, publishedAt: true, snapshot: true } });
|
||||
if (!latest) return { mode: 'coming-soon' };
|
||||
const t = (latest.snapshot as { design?: { template?: unknown } } | null)?.design?.template;
|
||||
const template = (WEBSITE_TEMPLATES as readonly unknown[]).includes(t) ? (t as WebsiteTemplate) : null;
|
||||
return { mode: 'published', version: latest.number, publishedAt: latest.publishedAt.toISOString(), template };
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Section variants per template (docs/WEBSITE-1.0-PLAN.md §3, "Section variants per template",
|
||||
* decision 16, confirmed 2026-11-25).
|
||||
*
|
||||
* Every template draws every variant, so nothing is ever unavailable and a template switch never
|
||||
* needs a fallback. A template only sets which variant each section starts with, which ones it
|
||||
* recommends, its header options, its homepage order and its style defaults.
|
||||
*
|
||||
* The ids are stored on each section (`hero.variant = "photo"`), so **an id never changes or goes
|
||||
* away** once released, like the font pairing ids in `@crosscode/contracts`.
|
||||
*/
|
||||
import { z } from 'zod';
|
||||
import type { Corners, WebsiteTemplate } from '@crosscode/contracts';
|
||||
|
||||
/** The homepage section types and their variant ids. */
|
||||
export const SECTION_VARIANTS = {
|
||||
hero: ['photo', 'video', 'collage', 'split', 'text'],
|
||||
serviceTimes: ['panel', 'strip', 'map'],
|
||||
welcome: ['text', 'image-text', 'pastor'],
|
||||
ministries: ['cards', 'list', 'bands'],
|
||||
team: ['faces', 'list', 'featured'],
|
||||
events: ['cards', 'list', 'calendar'],
|
||||
latestMessage: ['video', 'card', 'compact'],
|
||||
invitation: ['banner', 'centred', 'image'],
|
||||
} as const;
|
||||
|
||||
export type SectionType = keyof typeof SECTION_VARIANTS;
|
||||
export type Variant<S extends SectionType = SectionType> = (typeof SECTION_VARIANTS)[S][number];
|
||||
export const SECTION_TYPES = Object.keys(SECTION_VARIANTS) as [SectionType, ...SectionType[]];
|
||||
export const sectionTypeSchema = z.enum(SECTION_TYPES);
|
||||
|
||||
/** Whether `variant` is one of `section`'s ids. */
|
||||
export function isVariant<S extends SectionType>(section: S, variant: string): variant is Variant<S> {
|
||||
return (SECTION_VARIANTS[section] as readonly string[]).includes(variant);
|
||||
}
|
||||
|
||||
/** Per section: the default first, then the other recommended variants. */
|
||||
type Recommendations = { [S in SectionType]: readonly [Variant<S>, ...Variant<S>[]] };
|
||||
|
||||
export const TEMPLATE_VARIANTS: Record<WebsiteTemplate, Recommendations> = {
|
||||
heritage: {
|
||||
hero: ['photo', 'split', 'text'],
|
||||
serviceTimes: ['panel', 'map'],
|
||||
welcome: ['pastor', 'text'],
|
||||
ministries: ['list', 'cards'],
|
||||
team: ['featured', 'faces'],
|
||||
events: ['list', 'calendar'],
|
||||
latestMessage: ['card', 'video'],
|
||||
invitation: ['centred', 'banner'],
|
||||
},
|
||||
bold: {
|
||||
hero: ['video', 'photo', 'split'],
|
||||
serviceTimes: ['strip', 'map'],
|
||||
welcome: ['image-text', 'pastor'],
|
||||
ministries: ['bands', 'cards'],
|
||||
team: ['faces', 'featured'],
|
||||
events: ['cards', 'calendar'],
|
||||
latestMessage: ['video', 'card'],
|
||||
invitation: ['image', 'banner'],
|
||||
},
|
||||
community: {
|
||||
hero: ['collage', 'photo', 'split'],
|
||||
serviceTimes: ['map', 'panel'],
|
||||
welcome: ['pastor', 'image-text'],
|
||||
ministries: ['cards', 'bands'],
|
||||
team: ['faces', 'featured'],
|
||||
events: ['cards', 'calendar'],
|
||||
latestMessage: ['card', 'video'],
|
||||
invitation: ['banner', 'image'],
|
||||
},
|
||||
clean: {
|
||||
hero: ['text', 'split', 'photo'],
|
||||
serviceTimes: ['strip', 'panel'],
|
||||
welcome: ['text', 'image-text'],
|
||||
ministries: ['list', 'cards'],
|
||||
team: ['list', 'faces'],
|
||||
events: ['list', 'calendar'],
|
||||
latestMessage: ['compact', 'card'],
|
||||
invitation: ['centred', 'banner'],
|
||||
},
|
||||
};
|
||||
|
||||
export function defaultVariant<S extends SectionType>(template: WebsiteTemplate, section: S): Variant<S> {
|
||||
return (TEMPLATE_VARIANTS[template][section] as readonly Variant<S>[])[0]!;
|
||||
}
|
||||
|
||||
export function isRecommended(template: WebsiteTemplate, section: SectionType, variant: string): boolean {
|
||||
return (TEMPLATE_VARIANTS[template][section] as readonly string[]).includes(variant);
|
||||
}
|
||||
|
||||
/** The "Header" style setting: each template's options, default first. */
|
||||
export const TEMPLATE_HEADERS = {
|
||||
heritage: ['centred', 'centred-top-bar'],
|
||||
bold: ['transparent', 'solid'],
|
||||
community: ['logo-left-button', 'logo-left-tinted'],
|
||||
clean: ['small', 'small-menu'],
|
||||
} as const satisfies Record<WebsiteTemplate, readonly [string, ...string[]]>;
|
||||
|
||||
/**
|
||||
* The transparent header only sits over a photo, video or collage hero; on any other first section
|
||||
* it's drawn solid, so it never puts white text on white.
|
||||
*/
|
||||
export function headerIsTransparent(template: WebsiteTemplate, header: string, heroVariant: Variant<'hero'> | null): boolean {
|
||||
return template === 'bold' && header === 'transparent' && heroVariant !== null && ['photo', 'video', 'collage'].includes(heroVariant);
|
||||
}
|
||||
|
||||
/** A homepage entry: the section and whether it shows. */
|
||||
export type HomeEntry = { section: SectionType; hidden: boolean };
|
||||
|
||||
const order = (shown: SectionType[], hidden: SectionType[] = []): HomeEntry[] => [
|
||||
...shown.map((section) => ({ section, hidden: false })),
|
||||
...hidden.map((section) => ({ section, hidden: true })),
|
||||
];
|
||||
|
||||
/** The default homepage order (the church can reorder, hide and show). Every section is listed once. */
|
||||
export const TEMPLATE_HOME_ORDER: Record<WebsiteTemplate, HomeEntry[]> = {
|
||||
heritage: order(['hero', 'serviceTimes', 'welcome', 'latestMessage', 'ministries', 'team', 'events', 'invitation']),
|
||||
bold: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'ministries', 'invitation'], ['team']),
|
||||
community: order(['hero', 'welcome', 'serviceTimes', 'ministries', 'team', 'events', 'latestMessage', 'invitation']),
|
||||
clean: order(['hero', 'serviceTimes', 'welcome', 'events', 'latestMessage', 'invitation'], ['ministries', 'team']),
|
||||
};
|
||||
|
||||
/** The Website-only style settings (§3, "Style settings"). Fonts and corners are the church's, shared. */
|
||||
export const SECTION_COLOURS = ['light', 'tinted', 'mixed'] as const;
|
||||
export const SPACINGS = ['airy', 'compact'] as const;
|
||||
export const BUTTONS = ['solid', 'outline', 'pill'] as const;
|
||||
export const IMAGE_TREATMENTS = ['natural', 'mono', 'duotone'] as const;
|
||||
|
||||
export type SiteStyle = {
|
||||
sectionColour: (typeof SECTION_COLOURS)[number];
|
||||
spacing: (typeof SPACINGS)[number];
|
||||
buttons: (typeof BUTTONS)[number];
|
||||
images: (typeof IMAGE_TREATMENTS)[number];
|
||||
header: string;
|
||||
};
|
||||
|
||||
export const TEMPLATE_STYLE: Record<WebsiteTemplate, SiteStyle & { suggestedCorners: Corners }> = {
|
||||
heritage: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'centred', suggestedCorners: 'sharp' },
|
||||
bold: { sectionColour: 'mixed', spacing: 'compact', buttons: 'solid', images: 'natural', header: 'transparent', suggestedCorners: 'sharp' },
|
||||
community: { sectionColour: 'tinted', spacing: 'airy', buttons: 'pill', images: 'natural', header: 'logo-left-button', suggestedCorners: 'round' },
|
||||
clean: { sectionColour: 'light', spacing: 'airy', buttons: 'outline', images: 'natural', header: 'small', suggestedCorners: 'soft' },
|
||||
};
|
||||
|
||||
const STYLE_KEYS = ['sectionColour', 'spacing', 'buttons', 'images', 'header'] as const;
|
||||
|
||||
/** The site's design: what a template switch changes. Content is never part of it. */
|
||||
export type SiteDesign = {
|
||||
template: WebsiteTemplate;
|
||||
variants: { [S in SectionType]: Variant<S> };
|
||||
home: HomeEntry[];
|
||||
style: SiteStyle;
|
||||
};
|
||||
|
||||
/** A fresh site on `template`: every default. */
|
||||
export function defaultDesign(template: WebsiteTemplate): SiteDesign {
|
||||
const variants = Object.fromEntries(SECTION_TYPES.map((s) => [s, defaultVariant(template, s)])) as SiteDesign['variants'];
|
||||
const { suggestedCorners: _c, ...style } = TEMPLATE_STYLE[template];
|
||||
return { template, variants, home: TEMPLATE_HOME_ORDER[template].map((e) => ({ ...e })), style };
|
||||
}
|
||||
|
||||
export type DesignChange = { what: string; from: string; to: string };
|
||||
|
||||
const sameOrder = (a: HomeEntry[], b: HomeEntry[]) =>
|
||||
a.length === b.length && a.every((e, i) => e.section === b[i]!.section && e.hidden === b[i]!.hidden);
|
||||
|
||||
/**
|
||||
* Switching template (§3, "Switching template"): anything still on the old template's default
|
||||
* moves to the new template's default; anything the church chose stays. Returns the new design and
|
||||
* what moved, for the Publish screen ("Hero: Collage → Text only, Clean's default").
|
||||
*/
|
||||
export function switchTemplate(current: SiteDesign, to: WebsiteTemplate): { design: SiteDesign; changes: DesignChange[] } {
|
||||
if (current.template === to) return { design: current, changes: [] };
|
||||
const from = current.template;
|
||||
const target = defaultDesign(to);
|
||||
const changes: DesignChange[] = [{ what: 'template', from, to }];
|
||||
|
||||
const variants = { ...current.variants } as Record<SectionType, string>;
|
||||
for (const s of SECTION_TYPES) {
|
||||
const next = target.variants[s];
|
||||
if (current.variants[s] === defaultVariant(from, s) && next !== current.variants[s]) {
|
||||
changes.push({ what: `${s}.variant`, from: current.variants[s], to: next });
|
||||
variants[s] = next;
|
||||
}
|
||||
}
|
||||
|
||||
const homeUntouched = sameOrder(current.home, TEMPLATE_HOME_ORDER[from]);
|
||||
const home = homeUntouched ? target.home : current.home.map((e) => ({ ...e }));
|
||||
if (homeUntouched && !sameOrder(current.home, target.home)) changes.push({ what: 'home', from: `${from} order`, to: `${to} order` });
|
||||
|
||||
const style = { ...current.style };
|
||||
const oldStyle = TEMPLATE_STYLE[from];
|
||||
for (const k of STYLE_KEYS) {
|
||||
// A header from the old template's options means nothing in the new one, so it always moves.
|
||||
const untouched = current.style[k] === oldStyle[k] || (k === 'header' && !(TEMPLATE_HEADERS[to] as readonly string[]).includes(current.style.header));
|
||||
if (untouched && current.style[k] !== target.style[k]) {
|
||||
changes.push({ what: `style.${k}`, from: current.style[k], to: target.style[k] });
|
||||
(style as Record<string, string>)[k] = target.style[k];
|
||||
}
|
||||
}
|
||||
|
||||
return { design: { template: to, variants: variants as SiteDesign['variants'], home, style }, changes };
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import request from 'supertest';
|
||||
import { createApp } from '../src/app.js';
|
||||
import { createCtx, type Db } from '../src/context.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
import { appVersion } from '../src/lib/version.js';
|
||||
|
||||
type Version = { number: number; publishedAt: Date; snapshot: unknown };
|
||||
|
||||
/** Just what the app uses so far: a ping and the latest published version. */
|
||||
function fakeDb(opts: { up?: boolean; versions?: Version[] } = {}): Db {
|
||||
const versions = opts.versions ?? [];
|
||||
return {
|
||||
$queryRaw: async () => {
|
||||
if (opts.up === false) throw new Error('down');
|
||||
return [{ '?column?': 1 }];
|
||||
},
|
||||
siteVersion: {
|
||||
findFirst: async () => [...versions].sort((a, b) => b.number - a.number)[0] ?? null,
|
||||
},
|
||||
} as unknown as Db;
|
||||
}
|
||||
|
||||
const app = (db: Db) => createApp(createCtx(loadConfig({}), db));
|
||||
|
||||
describe('the app', () => {
|
||||
it('answers /api/health with the product and version', async () => {
|
||||
const res = await request(app(fakeDb())).get('/api/health');
|
||||
assert.equal(res.status, 200);
|
||||
assert.deepEqual(res.body, { status: 'ok', product: 'website', version: appVersion(), db: true });
|
||||
});
|
||||
|
||||
it('says 503 when the database is down', async () => {
|
||||
const res = await request(app(fakeDb({ up: false }))).get('/api/health');
|
||||
assert.equal(res.status, 503);
|
||||
assert.equal(res.body.db, false);
|
||||
});
|
||||
|
||||
it('shows Coming soon until the first publish', async () => {
|
||||
const res = await request(app(fakeDb())).get('/api/v1/site/status');
|
||||
assert.deepEqual(res.body, { mode: 'coming-soon' });
|
||||
});
|
||||
|
||||
it('shows the latest published version after it', async () => {
|
||||
const at = new Date('2026-12-01T08:00:00Z');
|
||||
const res = await request(app(fakeDb({ versions: [
|
||||
{ number: 1, publishedAt: new Date('2026-11-30T08:00:00Z'), snapshot: { design: { template: 'heritage' } } },
|
||||
{ number: 2, publishedAt: at, snapshot: { design: { template: 'clean' } } },
|
||||
] }))).get('/api/v1/site/status');
|
||||
assert.deepEqual(res.body, { mode: 'published', version: 2, publishedAt: at.toISOString(), template: 'clean' });
|
||||
});
|
||||
|
||||
it('answers unknown API paths with a JSON 404 and keeps the API out of search', async () => {
|
||||
const res = await request(app(fakeDb())).get('/api/nothing');
|
||||
assert.equal(res.status, 404);
|
||||
assert.equal(res.body.error.code, 'NOT_FOUND');
|
||||
assert.equal(res.headers['x-robots-tag'], 'noindex');
|
||||
assert.equal(res.headers['x-powered-by'], undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('config', () => {
|
||||
it('refuses production without a secret', () => {
|
||||
assert.throws(() => loadConfig({ NODE_ENV: 'production' }), /WEBSITE_SECRET/);
|
||||
});
|
||||
|
||||
it('defaults to the development ports', () => {
|
||||
const c = loadConfig({});
|
||||
assert.equal(c.port, 5300);
|
||||
assert.equal(c.publicUrl, 'http://localhost:3300');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
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 } 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);
|
||||
});
|
||||
});
|
||||
|
||||
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)), []);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import request from 'supertest';
|
||||
import { cookieHeader, cookiesFrom, harness, SITE } from './support/harness.js';
|
||||
|
||||
const OWNER = '11111111-1111-4111-8111-111111111111';
|
||||
const OTHER = '22222222-2222-4222-8222-222222222222';
|
||||
|
||||
/** Signs in from `returnTo` through the stand-in Accounts; returns the callback's response and the cookies after it. */
|
||||
async function signIn(h: Awaited<ReturnType<typeof harness>>, returnTo = '/admin/pages?x=1', cookies: Record<string, string> = {}, mfa = false) {
|
||||
const start = await request(h.app).get(`/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}${mfa ? '&mfa=1' : ''}`).set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(start.status, 303);
|
||||
const after = cookiesFrom(start, cookies);
|
||||
const back = await request(h.app).get('/api/auth/callback?code=abc&state=xyz').set('Cookie', cookieHeader(after));
|
||||
return { start, back, cookies: cookiesFrom(back, after) };
|
||||
}
|
||||
|
||||
describe('signing in to the admin through Accounts', () => {
|
||||
it('sends people to Accounts with the page they were on', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin%2Fpages');
|
||||
assert.equal(res.status, 303);
|
||||
assert.match(res.headers.location!, /^https:\/\/accounts\.hope\.test\//);
|
||||
assert.deepEqual(h.fake.started, [{ returnTo: '/admin/pages', requireTwoFactor: false }]);
|
||||
assert.match(String(res.headers['set-cookie']), /ccw_signin=.*Path=\/api\/auth.*HttpOnly/);
|
||||
});
|
||||
|
||||
it('refuses a foreign return address (back to the home page instead)', async () => {
|
||||
const h = await harness();
|
||||
await request(h.app).get('/api/auth/signin?returnTo=https%3A%2F%2Fevil.test%2F');
|
||||
assert.equal(h.fake.started[0]!.returnTo, '/');
|
||||
});
|
||||
|
||||
it('says so when the Website isn\'t linked to Accounts yet', async () => {
|
||||
const h = await harness({ linked: false });
|
||||
const res = await request(h.app).get('/api/auth/signin?returnTo=%2Fadmin');
|
||||
assert.equal(res.status, 303);
|
||||
assert.equal(res.headers.location, `${SITE}/auth/problem?code=ACCOUNTS_UNAVAILABLE&returnTo=%2Fadmin`);
|
||||
});
|
||||
|
||||
it('makes the Hub\'s admin email (verified) the first Owner and lands on the page they started from', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER, email: 'Pastor@Hope.test' };
|
||||
const { back, cookies } = await signIn(h);
|
||||
assert.equal(back.headers.location, `${SITE}/admin/pages?x=1`);
|
||||
assert.ok(cookies.ccw_session);
|
||||
assert.match(String(back.headers['set-cookie']), /ccw_session=.*HttpOnly/);
|
||||
|
||||
const me = await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(me.status, 200);
|
||||
assert.equal(me.body.user.role, 'owner');
|
||||
assert.equal(me.body.user.email, 'pastor@hope.test');
|
||||
assert.equal(me.body.mfa, true);
|
||||
const audit = await h.db.auditLog.findMany({ where: { action: 'first_owner_signed_in' } });
|
||||
assert.equal(audit.length, 1);
|
||||
});
|
||||
|
||||
it('never makes a second Owner, nor one from an unverified email', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER, email_verified: false };
|
||||
assert.match((await signIn(h)).back.headers.location!, /code=NO_ACCESS/);
|
||||
assert.equal(await h.db.websiteUser.count(), 0);
|
||||
|
||||
h.fake.next = { sub: OWNER };
|
||||
await signIn(h);
|
||||
h.fake.next = { sub: OTHER };
|
||||
const { back, cookies } = await signIn(h);
|
||||
assert.match(back.headers.location!, /code=NO_ACCESS/);
|
||||
assert.equal(cookies.ccw_session, undefined);
|
||||
assert.equal(await h.db.websiteUser.count(), 1);
|
||||
});
|
||||
|
||||
it('gives someone without a role on the Website no session', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OTHER, email: 'member@hope.test' };
|
||||
const { back, cookies } = await signIn(h);
|
||||
assert.match(back.headers.location!, /\/auth\/problem\?code=NO_ACCESS/);
|
||||
assert.equal(cookies.ccw_session, undefined);
|
||||
});
|
||||
|
||||
it('asks Accounts again with a second step for an Owner who signed in without one, once', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER, amr: ['pwd'] };
|
||||
const first = await signIn(h, '/admin');
|
||||
assert.equal(first.back.headers.location, `${SITE}/api/auth/signin?mfa=1&returnTo=%2Fadmin`);
|
||||
assert.equal(first.cookies.ccw_session, undefined);
|
||||
|
||||
// Accounts still says no second step: explained, not looped.
|
||||
const second = await signIn(h, '/admin', first.cookies, true);
|
||||
assert.equal(h.fake.started.at(-1)!.requireTwoFactor, true);
|
||||
assert.match(second.back.headers.location!, /code=TWO_FACTOR_NEEDED/);
|
||||
|
||||
// With it: signed in.
|
||||
h.fake.next = { sub: OWNER, amr: ['pwd', 'mfa'] };
|
||||
const third = await signIn(h, '/admin', {}, true);
|
||||
assert.ok(third.cookies.ccw_session);
|
||||
});
|
||||
|
||||
it('lets an Editor in without a second step, and Owners too when the church turned the rule off', async () => {
|
||||
const h = await harness();
|
||||
await h.db.websiteUser.create({ data: { id: OTHER, name: 'Ed', email: 'ed@hope.test', role: 'editor' } });
|
||||
h.fake.next = { sub: OTHER, email: 'ed@hope.test', amr: ['pwd'] };
|
||||
assert.ok((await signIn(h)).cookies.ccw_session);
|
||||
|
||||
await h.ctx.settings.set('two_factor_required_for_admins', 'false');
|
||||
h.fake.next = { sub: OWNER, amr: ['pwd'] };
|
||||
assert.ok((await signIn(h)).cookies.ccw_session);
|
||||
});
|
||||
|
||||
it('keeps the admin API to signed-in people', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).get('/api/v1/admin/me');
|
||||
assert.equal(res.status, 401);
|
||||
assert.equal(res.body.error.code, 'SIGNED_OUT');
|
||||
const me = await request(h.app).get('/api/auth/me').set('Cookie', 'ccw_session=made-up');
|
||||
assert.equal(me.status, 401);
|
||||
});
|
||||
|
||||
it('signs out here, then at Accounts (all the church\'s sites)', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER };
|
||||
const { cookies } = await signIn(h);
|
||||
const out = await request(h.app).post('/api/auth/signout').set('Cookie', cookieHeader(cookies));
|
||||
assert.equal(out.status, 303);
|
||||
assert.equal(out.headers.location, `https://accounts.hope.test/api/oidc/session/end?id_token_hint=id-token-for-${OWNER}`);
|
||||
assert.equal(await h.db.session.count(), 0);
|
||||
assert.equal((await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies))).status, 401);
|
||||
});
|
||||
|
||||
it('ends the person\'s sessions when Accounts says they signed out somewhere', async () => {
|
||||
const h = await harness();
|
||||
h.fake.next = { sub: OWNER };
|
||||
const { cookies } = await signIn(h);
|
||||
const res = await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: JSON.stringify({ sub: OWNER, sid: 'abc' }) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await request(h.app).get('/api/v1/admin/me').set('Cookie', cookieHeader(cookies))).status, 401);
|
||||
assert.equal((await request(h.app).post('/api/auth/backchannel-logout').type('form').send({ logout_token: 'nonsense' })).status, 400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Accounts' calls", () => {
|
||||
const call = (type: string, extra: object) => JSON.stringify({ schema: 'crosscode.identity/1', callId: '33333333-3333-4333-8333-333333333333', occurredAt: new Date().toISOString(), sub: OWNER, type, ...extra });
|
||||
|
||||
it('refuses a call Accounts didn\'t sign', async () => {
|
||||
const h = await harness();
|
||||
const res = await request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').send(call('user.updated', {}));
|
||||
assert.equal(res.status, 401);
|
||||
});
|
||||
|
||||
it('keeps the admin\'s name and email current, exports them, and removes them when the account goes', async () => {
|
||||
const h = await harness();
|
||||
await h.db.websiteUser.create({ data: { id: OWNER, name: 'Sam', email: 'pastor@hope.test', role: 'owner' } });
|
||||
await h.db.session.create({ data: { tokenHash: 'x', userId: OWNER, expiresAt: new Date(Date.now() + 1e9) } });
|
||||
const send = (body: string) => request(h.app).post('/api/accounts/v1/events').set('Content-Type', 'application/json').set('x-test-signed', 'yes').send(body);
|
||||
|
||||
const profile = { name: 'Pastor Samuel', email: 'Sam@Hope.test', email_verified: true, phone_number: null, news_consent: { email: false, whatsapp: false } };
|
||||
assert.deepEqual((await send(call('user.updated', { profile }))).body, { schema: 'crosscode.identity/1', ok: true });
|
||||
const u = await h.db.websiteUser.findUnique({ where: { id: OWNER } });
|
||||
assert.equal(u!.name, 'Pastor Samuel');
|
||||
assert.equal(u!.email, 'sam@hope.test');
|
||||
|
||||
const exp = await send(call('user.export', { exportId: '44444444-4444-4444-8444-444444444444' }));
|
||||
assert.equal(exp.body.product, 'website');
|
||||
assert.equal(exp.body.sections[0].records[0].role, 'owner');
|
||||
|
||||
const del = await send(call('user.deleted', {}));
|
||||
assert.equal(del.body.status, 'deleted');
|
||||
assert.equal(await h.db.websiteUser.count(), 0);
|
||||
assert.equal(await h.db.session.count(), 0);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user