Events 3.0: auto-connect, demo people in Accounts, e2e; import.finish checks the subs
- contracts 1.8.0 / Accounts 1.1.0: import.finish lists the subs the product relies on; Accounts checks each is held, not deleted and known to it (the count+hash failed a second move after Undo once someone had joined through Accounts). - Events: connects to the church's Accounts once the Hub lists it; moveNewPeople (demo data, people added after the move); set-demo moves demo people; e2e/sign-in-accounts.spec.ts with Accounts in memory and an e2e-only /api rewrite. test:accounts 14/14; Jest auto-connect tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1904,6 +1904,7 @@ async function main() {
|
||||
}, { maxWait: 10 * 1000, timeout: 5 * 60 * 1000 });
|
||||
clearScheduledEmails();
|
||||
const pastFinancials = await closePastEvents();
|
||||
const accounts = await demoAccounts();
|
||||
|
||||
const count = (model, where = () => true) => (rows[model] || []).filter(where).length;
|
||||
console.log(`\nCleared ${cleared.tables} tables and ${cleared.users} users.`);
|
||||
@@ -1952,9 +1953,40 @@ async function main() {
|
||||
console.log(`Demo staff logins (password ${DEMO_PASSWORD}):`);
|
||||
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) {
|
||||
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
|
||||
* 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() {
|
||||
const dist = path.join(__dirname, '..', 'dist', 'accounts', 'move.js');
|
||||
let move;
|
||||
if (fs.existsSync(dist)) {
|
||||
move = require(dist);
|
||||
accountsDb = require(path.join(__dirname, '..', 'dist', 'config', 'db'));
|
||||
} else {
|
||||
require('tsx/cjs');
|
||||
move = require('../src/accounts/move.ts');
|
||||
}
|
||||
const mode = await prisma.appSetting.findUnique({ where: { key: 'auth_mode' } });
|
||||
if (mode?.value !== 'accounts') return null;
|
||||
try {
|
||||
return await move.moveNewPeople(admin.accountId || null);
|
||||
} 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;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(err => { console.error(err); process.exitCode = 1; })
|
||||
// The cashup code used by closePastEvents has its own client (src/config/db).
|
||||
.finally(() => Promise.all([prisma.$disconnect(), require('../src/config/db').$disconnect()]));
|
||||
.finally(() => Promise.all([prisma.$disconnect(), require('../src/config/db').$disconnect(), accountsDb?.$disconnect()]));
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Cross Events 3.0 connects itself to the church's Accounts (docs/EVENTS-3.0-PLAN.md §9, Hub
|
||||
* 2.5.0): after a heartbeat, when the Hub lists an Accounts for this church and this site isn't
|
||||
* linked to one, it connects (as an admin pressing Connect under Linked products would). Once
|
||||
* only: after it worked (`accounts_auto_connected`), an admin's Disconnect stays as it is.
|
||||
*/
|
||||
import { connectTo } from '../links/connect';
|
||||
import { linkedProducts } from '../links/store';
|
||||
import { accountsLink } from './client';
|
||||
import { getSetting, setSetting } from './mode';
|
||||
|
||||
export const AUTO_KEY = 'accounts_auto_connected';
|
||||
|
||||
export async function connectAccountsIfListed(now = new Date()): Promise<'connected' | 'skipped'> {
|
||||
if (await getSetting(AUTO_KEY)) return 'skipped';
|
||||
if (await accountsLink()) {
|
||||
await setSetting(AUTO_KEY, now.toISOString());
|
||||
return 'skipped';
|
||||
}
|
||||
const listed = (await linkedProducts()).find((p) => p.product === 'accounts');
|
||||
if (!listed) return 'skipped';
|
||||
await connectTo(listed.installId, { id: null, role: 'system' }, null, now);
|
||||
await setSetting(AUTO_KEY, now.toISOString());
|
||||
return 'connected';
|
||||
}
|
||||
@@ -15,7 +15,6 @@
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { IMPORT_BATCH_MAX, phoneSchema, type ImportPerson, type ImportResult } from '@crosscode/contracts';
|
||||
import { importIdsHash } from '@crosscode/contracts/signing';
|
||||
import { siteUrl } from '../feed/context';
|
||||
import { accounts, accountsLink, AccountsUnavailable } from './client';
|
||||
import { authMode, CLEARED_KEY, getSetting, MODE_KEY, MOVED_AT_KEY, REPORT_KEY, setSetting, UNDO_DAYS } from './mode';
|
||||
@@ -214,6 +213,52 @@ export type MoveReport = {
|
||||
notices: 'events' | 'accounts';
|
||||
};
|
||||
|
||||
/**
|
||||
* Ends a move: Accounts checks it holds every account this site now relies on (everyone linked,
|
||||
* including a move run again after a failure, and people who signed up through Accounts since).
|
||||
*/
|
||||
async function finishMove(auth: Awaited<ReturnType<typeof accounts>>, actor: string | null) {
|
||||
const linkedRows: { accountId: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { accountId: true } });
|
||||
const subs = [...new Set(linkedRows.map((x) => x.accountId))];
|
||||
const finish = await auth.request<{ matched: boolean; count: number; missing: string[] }>({ type: 'import.finish', actor, subs });
|
||||
if (!finish.matched) {
|
||||
throw new MoveError(`Accounts holds ${finish.count} of the ${subs.length} people this site relies on (missing, for example, ${finish.missing.slice(0, 3).join(', ')}). Nothing was switched; run the move again.`, 'MISMATCH');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* People added here after sign-in moved, without signing in through Accounts (demo data, an
|
||||
* import): moved into Accounts the same way, so they can sign in. Only while sign-in goes through
|
||||
* Accounts; returns how many were moved.
|
||||
*/
|
||||
export async function moveNewPeople(actor: string | null = null): Promise<{ moved: number; refused: { email: string; reason: string }[] }> {
|
||||
if ((await authMode()) !== 'accounts') return { moved: 0, refused: [] };
|
||||
const people = await peopleToMove();
|
||||
if (!people.length) return { moved: 0, refused: [] };
|
||||
const auth = await accounts();
|
||||
await auth.request({ type: 'import.begin', actor, check: false, notices: [], church: { name: null, primaryColour: null } });
|
||||
try {
|
||||
const byId = new Map(people.map((p) => [p.id, p]));
|
||||
let moved = 0;
|
||||
const refused: { email: string; reason: string }[] = [];
|
||||
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
|
||||
const built = await Promise.all(batch.map((u) => person(u, { admins: new Set(), seal: (v) => auth.seal(v), keepAccountsNotices: false })));
|
||||
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor, check: false, people: built }, { timeoutMs: 120000 });
|
||||
for (const res of r.results) {
|
||||
if (res.sub && res.outcome !== 'refused') {
|
||||
await prisma.user.update({ where: { id: res.id }, data: { accountId: res.sub } });
|
||||
moved++;
|
||||
} else refused.push({ email: byId.get(res.id)?.email ?? res.id, reason: res.reason ?? '' });
|
||||
}
|
||||
}
|
||||
await finishMove(auth, actor);
|
||||
return { moved, refused };
|
||||
} catch (e) {
|
||||
await auth.request({ type: 'import.abort', actor }).catch(() => {});
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/** 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();
|
||||
@@ -245,11 +290,7 @@ export async function move(opts: { actor: { id: string; role: string; name?: str
|
||||
}
|
||||
results.push(...r.results);
|
||||
}
|
||||
// Everyone this site has linked, including a move run again after a failure.
|
||||
const linkedRows: { accountId: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { accountId: true } });
|
||||
const subs = [...new Set(linkedRows.map((x) => x.accountId))];
|
||||
const finish = await auth.request<{ matched: boolean; count: number }>({ type: 'import.finish', actor: opts.actor.id, count: subs.length, idsHash: importIdsHash(subs) });
|
||||
if (!finish.matched) throw new MoveError(`Accounts holds ${finish.count} people from this site, but ${subs.length} were sent. Nothing was switched; run the move again.`, 'MISMATCH');
|
||||
await finishMove(auth, opts.actor.id);
|
||||
|
||||
const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' });
|
||||
const report: MoveReport = {
|
||||
|
||||
@@ -92,6 +92,8 @@ export async function userForClaims(claims: IdentityClaims): Promise<{ user: Eve
|
||||
email,
|
||||
password: NO_PASSWORD(),
|
||||
role: 'user',
|
||||
isActive: true,
|
||||
tokenVersion: 0,
|
||||
newsEmail: claims.news_consent.email,
|
||||
newsWhatsApp: claims.news_consent.whatsapp,
|
||||
newsAskedAt: new Date(),
|
||||
|
||||
@@ -245,6 +245,8 @@ async function heartbeat() {
|
||||
try {
|
||||
await store.saveLinkedProducts(data.linkedProducts);
|
||||
if (typeof data.publicKeyStatus === 'string') await store.setPublicKeyStatus(data.publicKeyStatus);
|
||||
// 3.0.0: connect to the church's Accounts once the Hub lists it (accounts/autoConnect.ts).
|
||||
require('../accounts/autoConnect').connectAccountsIfListed().catch((e) => console.warn('[accounts] Could not connect to Accounts yet:', e?.message || e));
|
||||
} catch (e) {
|
||||
console.warn('[hub] Could not save the linked products:', e?.message || e);
|
||||
}
|
||||
|
||||
@@ -61,7 +61,7 @@ async function firstUse(nonce: string, now: Date): Promise<boolean> {
|
||||
}
|
||||
}
|
||||
|
||||
async function audit(action: string, link: { installId: string; product: string }, actor: { id: string; role: string } | null, ip: string | null, metadata: object = {}) {
|
||||
async function audit(action: string, link: { installId: string; product: string }, actor: { id: string | null; role: string } | null, ip: string | null, metadata: object = {}) {
|
||||
await logAdminAction({
|
||||
actorId: actor?.id ?? null,
|
||||
actorRole: actor?.role ?? 'linked_product',
|
||||
@@ -80,7 +80,7 @@ async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedByI
|
||||
|
||||
// ─── This site connects (an admin clicked Connect) ─────────────────────────────
|
||||
|
||||
export async function connectTo(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()) {
|
||||
export async function connectTo(installId: string, actor: { id: string | null; role: string }, ip: string | null, now = new Date()) {
|
||||
const sibling = await listedProduct(installId);
|
||||
if (!sibling) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
|
||||
const me = await self();
|
||||
|
||||
@@ -231,6 +231,23 @@ describe('signing out, and Accounts\' calls', () => {
|
||||
assert.equal((await eventsDb.user.findUnique({ where: { id: ids.thandi } }) as { name: string }).name, 'Thandi M. Mokoena');
|
||||
});
|
||||
|
||||
test('people added here after the move (demo data) are moved too, and can sign in', async () => {
|
||||
const id = crypto.randomUUID();
|
||||
await eventsUser({ id, name: 'Demo Person', email: 'demo.person@hope.test', password: await bcrypt.hash('Demo-pass-123', 4) });
|
||||
const r = await move.moveNewPeople(null);
|
||||
assert.equal(r.moved, 1);
|
||||
assert.equal((await eventsDb.user.findUnique({ where: { id } }) as { accountId: string }).accountId, id);
|
||||
const signed = await signInThroughEvents(new Browser(), 'demo.person@hope.test', 'Demo-pass-123', '/');
|
||||
assert.ok('token' in signed && signed.token);
|
||||
});
|
||||
|
||||
test('someone new to Events signs in with a church account they made elsewhere', async () => {
|
||||
const a = await h.makeAccount({ email: 'newcomer@hope.test', password: 'Newcomer-pass-1', name: 'Newcomer' });
|
||||
const r = await signInThroughEvents(new Browser(), 'newcomer@hope.test', 'Newcomer-pass-1', '/events');
|
||||
assert.ok('token' in r && r.token, JSON.stringify(r));
|
||||
assert.equal((await eventsDb.user.findUnique({ where: { id: r.user.id } }) as { accountId: string; role: string }).accountId, a.id);
|
||||
});
|
||||
|
||||
test('Undo goes back to Events\' own sign-in', async () => {
|
||||
await move.undo({ id: ids.sam, role: 'admin' });
|
||||
mode.forgetMode();
|
||||
@@ -239,3 +256,14 @@ describe('signing out, and Accounts\' calls', () => {
|
||||
assert.equal(res.status, 200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('moving again after Undo', () => {
|
||||
test('works, including someone who joined through Accounts in between', async () => {
|
||||
mode.forgetMode();
|
||||
assert.equal(await mode.authMode(), 'local');
|
||||
const report = await move.move({ actor: { id: ids.sam, role: 'admin' }, adminIds: [] });
|
||||
assert.equal(report.created, 0, 'nobody new to move');
|
||||
mode.forgetMode();
|
||||
assert.equal(await mode.authMode(), 'accounts');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §9): connecting to the church's Accounts once the Hub lists it.
|
||||
const mockSettings = new Map<string, string>();
|
||||
const mockConnects: unknown[][] = [];
|
||||
let mockListed: { installId: string; product: string }[] = [];
|
||||
let mockLink: object | null = null;
|
||||
|
||||
jest.mock('../src/links/connect', () => ({ connectTo: async (...args: unknown[]) => { mockConnects.push(args); mockLink = { installId: args[0] }; } }));
|
||||
jest.mock('../src/links/store', () => ({ linkedProducts: async () => mockListed }));
|
||||
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => mockLink }));
|
||||
jest.mock('../src/accounts/mode', () => ({
|
||||
getSetting: async (k: string) => mockSettings.get(k) ?? null,
|
||||
setSetting: async (k: string, v: string | null) => { if (v === null) mockSettings.delete(k); else mockSettings.set(k, v); },
|
||||
}));
|
||||
|
||||
import { AUTO_KEY, connectAccountsIfListed } from '../src/accounts/autoConnect';
|
||||
|
||||
const ACCOUNTS = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
|
||||
|
||||
beforeEach(() => {
|
||||
mockSettings.clear();
|
||||
mockConnects.length = 0;
|
||||
mockListed = [];
|
||||
mockLink = null;
|
||||
});
|
||||
|
||||
test('connects to the Accounts the Hub lists, as the system, once', async () => {
|
||||
mockListed = [{ installId: 'w1', product: 'website' }, { installId: ACCOUNTS, product: 'accounts' }];
|
||||
expect(await connectAccountsIfListed()).toBe('connected');
|
||||
expect(mockConnects).toEqual([[ACCOUNTS, { id: null, role: 'system' }, null, expect.any(Date)]]);
|
||||
expect(mockSettings.has(AUTO_KEY)).toBe(true);
|
||||
// An admin disconnects later: it isn't connected again.
|
||||
mockLink = null;
|
||||
expect(await connectAccountsIfListed()).toBe('skipped');
|
||||
expect(mockConnects).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('nothing listed yet: tries again at the next heartbeat', async () => {
|
||||
expect(await connectAccountsIfListed()).toBe('skipped');
|
||||
expect(mockSettings.has(AUTO_KEY)).toBe(false);
|
||||
});
|
||||
|
||||
test('already connected by an admin: just remembers it', async () => {
|
||||
mockLink = { installId: ACCOUNTS };
|
||||
mockListed = [{ installId: ACCOUNTS, product: 'accounts' }];
|
||||
expect(await connectAccountsIfListed()).toBe('skipped');
|
||||
expect(mockConnects).toEqual([]);
|
||||
expect(mockSettings.has(AUTO_KEY)).toBe(true);
|
||||
});
|
||||
Reference in New Issue
Block a user