Events 3.3.0, Accounts 1.3.0, contracts 1.11.0: Accounts looks like Events, backups; sign-out and upload fixes

- Accounts: account and admin pages in Cross Events' layout (top bar, sidebar,
  a page per section, dark footer); quick links to the church's sites
  (GET /me/apps); nightly pg_dump backups with Admin -> Backups (run, keep,
  download, audited; heartbeat lastBackupAt); a fuller built-in privacy notice
  with headings and bullets; a fixed favicon. /backups/ ignored (anchored, so
  src/backups is kept).
- Contracts 1.11.0: people.removeDemo (only @example.com, never an admin).
- Events: uploads served from the folder they're saved in (a backend started
  outside backend/ answered 404 for a logo it had just saved); Branding checks
  the file loads before saving; logout waits for the sign-out call so Accounts
  signs out too; set-demo removes the last demo's people from Accounts.
Tests: Accounts 62 + e2e 8, Events 782, contracts 225; npm run check passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 11:19:57 +02:00
co-authored by Claude Opus 5.5
parent 8ee64bb9c9
commit 8856d6b35d
61 changed files with 1514 additions and 162 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "3.2.0",
"version": "3.3.0",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
+15 -4
View File
@@ -1888,6 +1888,9 @@ async function main() {
if (profile.campuses) assignCampuses();
buildAnalytics();
// 3.3.0: the church accounts of the people about to be cleared, so the old demo people leave
// Accounts too (only demo addresses; Accounts checks).
const oldSubs = (await prisma.user.findMany({ where: { id: { not: admin.id }, accountId: { not: null } }, select: { accountId: true } })).map(u => u.accountId);
const cleared = await prisma.$transaction(async (tx) => {
const result = await clearData(tx);
for (const model of INSERT_ORDER) {
@@ -1904,7 +1907,7 @@ async function main() {
}, { maxWait: 10 * 1000, timeout: 5 * 60 * 1000 });
clearScheduledEmails();
const pastFinancials = await closePastEvents();
const accounts = await demoAccounts();
const accounts = await demoAccounts(oldSubs);
const count = (model, where = () => true) => (rows[model] || []).filter(where).length;
console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`);
@@ -1954,18 +1957,21 @@ async function main() {
for (const s of staffTeam) console.log(` ${s.role.padEnd(10)} ${s.email}`);
console.log(`Every other demo person also uses ${DEMO_PASSWORD}.`);
if (accounts) {
if (accounts.removed) console.log(`The ${accounts.removed} demo people of the last demo were removed from the church's Accounts.`);
console.log(`Sign-in goes through the church's Accounts: ${accounts.moved} demo people have church accounts with that password${accounts.refused.length ? ` (${accounts.refused.length} couldn't: ${accounts.refused.map(r => `${r.email} ${r.reason}`).join('; ')})` : ''}.`);
}
}
/**
* 3.0.0: with sign-in through the church's Accounts, the demo people are moved there too (with the
* demo password), so they can sign in (src/accounts/move.ts moveNewPeople). A demo person whose
* demo password), so they can sign in (src/accounts/move.ts moveNewPeople). 3.3.0: first, the last
* demo's people (`oldSubs`) are removed from Accounts (removeDemoPeople), so Accounts has the
* same people as the site. A demo person whose
* email already has an account from an earlier demo is linked to it. The compiled code (dist/) on a
* server; the TypeScript through tsx in development.
*/
let accountsDb = null;
async function demoAccounts() {
async function demoAccounts(oldSubs = []) {
const dist = path.join(__dirname, '..', 'dist', 'accounts', 'move.js');
let move;
if (fs.existsSync(dist)) {
@@ -1978,7 +1984,12 @@ async function demoAccounts() {
const mode = await prisma.appSetting.findUnique({ where: { key: 'auth_mode' } });
if (mode?.value !== 'accounts') return null;
try {
return await move.moveNewPeople(admin.accountId || null);
// Accounts before 1.3.0 doesn't know the request: the new demo still moves, the old stays.
const gone = await move.removeDemoPeople(oldSubs, admin.accountId || null).catch((e) => {
console.warn(`[warn] The last demo's people couldn't be removed from Accounts (${e.message}); they stay there until Accounts is updated to 1.3.0 and the demo is loaded again.`);
return { removed: 0 };
});
return { ...(await move.moveNewPeople(admin.accountId || null)), removed: gone.removed };
} catch (e) {
console.warn(`[warn] The demo people couldn't be moved to Accounts (${e.message}). Run the demo again once Accounts can be reached.`);
process.exitCode = 1;
+21 -1
View File
@@ -14,7 +14,7 @@
* deleted people stay Events-only. Recovery codes don't move (decision 2): Accounts shows new ones.
*/
import crypto from 'node:crypto';
import { IMPORT_BATCH_MAX, phoneSchema, type ImportPerson, type ImportResult } from '@crosscode/contracts';
import { IMPORT_BATCH_MAX, phoneSchema, REMOVE_DEMO_MAX, type ImportPerson, type ImportResult } from '@crosscode/contracts';
import { siteUrl } from '../feed/context';
import { accounts, accountsLink, AccountsUnavailable } from './client';
import { accountsMessaging } from './messaging';
@@ -263,6 +263,26 @@ export async function moveNewPeople(actor: string | null = null): Promise<{ move
}
}
/**
* 3.3.0: new demo data replaced the old (set-demo), so the old demo people's church accounts go
* too (contracts 1.11.0 `people.removeDemo`). Accounts removes only demo addresses
* (`@example.com`) it knows through this site, never an Accounts admin. Only while sign-in goes
* through Accounts; returns how many went and how many it kept.
*/
export async function removeDemoPeople(subs: string[], actor: string | null = null): Promise<{ removed: number; kept: number }> {
const unique = [...new Set(subs.filter(Boolean))];
if ((await authMode()) !== 'accounts' || !unique.length) return { removed: 0, kept: 0 };
const auth = await accounts();
let removed = 0;
let kept = 0;
for (const batch of chunk(unique, REMOVE_DEMO_MAX)) {
const r = await auth.request<{ removed: number; kept: unknown[] }>({ type: 'people.removeDemo', actor, subs: batch }, { timeoutMs: 120000 });
removed += r.removed;
kept += r.kept.length;
}
return { removed, kept };
}
/** The move. Throws MoveError when it doesn't finish; nothing changes for anyone then. */
export async function move(opts: { actor: { id: string; role: string; name?: string }; adminIds: string[]; keepAccountsNotices?: boolean; ip?: string | null }): Promise<MoveReport> {
const auth = await connected();
+3 -10
View File
@@ -196,18 +196,11 @@ app.get('/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
// Pre-warm the settings cache so synchronous helpers have DB values from startup
const { getSettingSync, warmCache } = require('./utils/settingsCache');
warmCache().catch(() => {});
// Uploaded branding assets can include SVGs, which may embed <script>/event
// handlers. Serving them inline lets a compromised/malicious upload run script
// in the site's origin if opened directly, so pin the safe response headers
// (no inline execution, no MIME-sniffing to HTML/script) on every asset here.
// Uploaded files, with safe headers (utils/uploads.js): served from the folder they're saved in
// (3.3.0; before, from one relative to where the process started, so a new logo could be "missing").
// Stored paths stay "/uploads/…"; they're given out as /api/uploads/… (v2/schemas.ts absoluteUrl).
// /uploads still answers for links made before 2.2.0.
const uploads = express.static('public/uploads', {
setHeaders: (res) => {
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
res.setHeader('X-Content-Type-Options', 'nosniff');
},
});
const uploads = require('./utils/uploads').serveUploads();
app.use('/api/uploads', uploads, notFound); // a missing file is 404, not "API v1 removed"
app.use('/uploads', uploads);
@@ -2,6 +2,7 @@ const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const multer = require('multer');
const { UPLOADS_DIR } = require('../utils/uploads');
// Builds a filename multer can never be tricked into escaping the upload
// directory with — extension only, no attacker-controlled path segments.
@@ -13,7 +14,7 @@ function safeFilename(prefix, ext) {
// Setup multer storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
const uploadPath = path.join(__dirname, '..', '..','public', 'uploads', 'events');
const uploadPath = path.join(UPLOADS_DIR, 'events');
// Check if the upload location exists
try {
@@ -52,7 +53,7 @@ const upload = multer({
// Logo storage (separate subfolder)
const logoStorage = multer.diskStorage({
destination: function (req, file, cb) {
const uploadPath = path.join(__dirname, '..', '..', 'public', 'uploads', 'branding');
const uploadPath = path.join(UPLOADS_DIR, 'branding');
try {
if (!fs.existsSync(uploadPath)) fs.mkdirSync(uploadPath, { recursive: true });
cb(null, uploadPath);
@@ -80,7 +81,7 @@ const uploadLogo = multer({
// Favicon storage (same subfolder as the logo — both are "branding" assets)
const faviconStorage = multer.diskStorage({
destination: function (req, file, cb) {
const uploadPath = path.join(__dirname, '..', '..', 'public', 'uploads', 'branding');
const uploadPath = path.join(UPLOADS_DIR, 'branding');
try {
if (!fs.existsSync(uploadPath)) fs.mkdirSync(uploadPath, { recursive: true });
cb(null, uploadPath);
+29
View File
@@ -0,0 +1,29 @@
// Where uploaded files live, and how they're served (3.3.0). One folder for saving and serving:
// backend/public/uploads, the same from src/ and dist/. Before 3.3.0 the files were served from
// "public/uploads" relative to wherever the process was started, so a backend started from
// another folder saved a logo in one place and answered 404 for it from another.
const path = require('path');
const express = require('express');
const UPLOADS_DIR = path.join(__dirname, '..', '..', 'public', 'uploads');
/** The folder for one kind of upload (e.g. "branding"), made if it isn't there yet. */
function uploadsDir(sub) {
const dir = path.join(UPLOADS_DIR, sub);
require('fs').mkdirSync(dir, { recursive: true });
return dir;
}
// Uploaded branding assets can include SVGs, which may embed <script>/event handlers. Serving
// them inline lets a malicious upload run script in the site's origin if opened directly, so pin
// the safe response headers (no inline execution, no MIME-sniffing to HTML/script) on every file.
function serveUploads() {
return express.static(UPLOADS_DIR, {
setHeaders: (res) => {
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
res.setHeader('X-Content-Type-Options', 'nosniff');
},
});
}
module.exports = { UPLOADS_DIR, uploadsDir, serveUploads };
@@ -0,0 +1,39 @@
// 3.3.0: new demo data (set-demo) removes the last demo's people from the church's Accounts
// (contracts 1.11.0 people.removeDemo), only while sign-in goes through Accounts.
const mockRequests: Record<string, unknown>[] = [];
let mockMode = 'accounts';
jest.mock('../src/config/db', () => ({}));
jest.mock('../src/accounts/client', () => ({
accounts: async () => ({
request: async (body: { subs: string[] }) => { mockRequests.push(body); return { removed: body.subs.length - 1, kept: [{ sub: body.subs[0], reason: 'not_demo' }] }; },
}),
accountsLink: async () => null,
AccountsUnavailable: class extends Error {},
}));
jest.mock('../src/accounts/mode', () => ({
...jest.requireActual('../src/accounts/mode'),
authMode: async () => mockMode,
}));
import { removeDemoPeople } from '../src/accounts/move';
const sub = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
beforeEach(() => { mockRequests.length = 0; mockMode = 'accounts'; });
test('asks Accounts to remove each old demo person once, a thousand at a time', async () => {
const subs = Array.from({ length: 1500 }, (_, i) => sub(i));
const r = await removeDemoPeople([...subs, subs[0]!, ''], 'admin-sub');
expect(mockRequests.map((q) => (q.subs as string[]).length)).toEqual([1000, 500]);
expect(mockRequests[0]).toMatchObject({ type: 'people.removeDemo', actor: 'admin-sub' });
expect(r).toEqual({ removed: 1498, kept: 2 });
});
test('nothing to ask while sign-in is Events\' own, or with nobody to remove', async () => {
mockMode = 'events';
expect(await removeDemoPeople([sub(1)])).toEqual({ removed: 0, kept: 0 });
mockMode = 'accounts';
expect(await removeDemoPeople([])).toEqual({ removed: 0, kept: 0 });
expect(mockRequests).toHaveLength(0);
});
@@ -0,0 +1,74 @@
// Branding uploads end to end (3.3.0): the real v2 upload routes (multer saving to disk) and the
// real file serving, as app.js mounts them. The logo and favicon saved are the files the returned
// address serves, wherever the backend was started from (before 3.3.0 a backend started outside
// backend/ answered 404 for a logo it had just saved). Only the database is a stand-in (no admin
// yet, so the upload is allowed as during setup).
import express from 'express';
import fs from 'fs';
import os from 'os';
import path from 'path';
import request from 'supertest';
import { v2Router } from '../src/v2';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const { serveUploads } = require('../src/utils/uploads');
/* eslint-enable @typescript-eslint/no-require-imports */
function site() {
const app = express();
app.use(express.json());
app.use('/api/v2', v2Router());
app.use('/api/uploads', serveUploads());
return app;
}
// Any model, any call: nothing found, no users (as before setup).
jest.mock('../src/config/db', () => {
const anything: unknown = new Proxy(function () { /* callable */ }, {
get: (_t, key) => (key === 'then' ? undefined : key === 'count' ? async () => 0 : anything),
apply: async () => null,
});
return anything;
});
// The real upload folder of this checkout (as multer writes it), cleaned up after.
const BRANDING = path.join(__dirname, '..', 'public', 'uploads', 'branding');
const made: string[] = [];
afterAll(() => { for (const f of made) fs.rmSync(path.join(BRANDING, f), { force: true }); });
const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', 'base64');
describe('branding uploads', () => {
const startedIn = process.cwd();
// PM2 or a script may start the backend from anywhere: the served files mustn't depend on it.
beforeAll(() => process.chdir(fs.mkdtempSync(path.join(os.tmpdir(), 'events-cwd-'))));
afterAll(() => process.chdir(startedIn));
test.each([['logo', 'logo.png'], ['favicon', 'icon.png']])('a %s upload is served at the address it answers with', async (kind, name) => {
const app = site();
const up = await request(app).post(`/api/v2/uploads/${kind}`).attach('image', PNG, { filename: name, contentType: 'image/png' });
expect(up.status).toBe(200);
const saved = String(up.body.data.path);
expect(saved).toMatch(new RegExp(`^/uploads/branding/${kind}-[\\w-]+\\.png$`));
made.push(path.basename(saved));
expect(fs.existsSync(path.join(BRANDING, path.basename(saved)))).toBe(true);
const got = await request(app).get(new URL(up.body.data.url).pathname);
expect(got.status).toBe(200);
expect(Buffer.compare(got.body as Buffer, PNG)).toBe(0);
});
test('app.js serves uploads from that same folder, never one relative to where it started', () => {
const source = fs.readFileSync(path.join(__dirname, '..', 'src', 'app.js'), 'utf8');
expect(source).toContain("require('./utils/uploads').serveUploads()");
expect(source).not.toMatch(/express\.static\(\s*['"`]/);
});
test('a file that isn\'t an image is refused, and nothing is saved', async () => {
const app = site();
const before = fs.existsSync(BRANDING) ? fs.readdirSync(BRANDING).length : 0;
const up = await request(app).post('/api/v2/uploads/logo').attach('image', Buffer.from('<html>'), { filename: 'page.html', contentType: 'text/html' });
expect(up.status).toBe(400);
expect((fs.existsSync(BRANDING) ? fs.readdirSync(BRANDING).length : 0)).toBe(before);
});
});