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:
@@ -14,7 +14,8 @@ For Cross Events 3.0 (docs/EVENTS-3.0-PLAN.md §8), with contracts 1.8.0.
|
||||
Accounts' key at rest), lockout, news consent and its history, notice acceptance, last sign-in
|
||||
and status; ticked Events admins become Accounts admins. An email that already has an account is
|
||||
**linked** (that account and its password stay). A check (`check: true`) writes nothing.
|
||||
`import.finish` compares the count and a hash of the subs. Events' privacy notice versions are
|
||||
`import.finish` checks every sub the product relies on is an account here, not deleted, and
|
||||
known to that product, and lists the ones that aren't. Events' privacy notice versions are
|
||||
taken when Accounts has published none; an empty church name and colour are filled from Events.
|
||||
- **New recovery codes after the first sign-in** for people moved in with 2FA (their Events codes
|
||||
can't move): shown once after the second step, whatever step comes next.
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
|
||||
type IdentityRequest, type ImportPerson, type ImportResult,
|
||||
} from '@crosscode/contracts';
|
||||
import { importIdsHash, LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
|
||||
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { ProductLink } from '../generated/prisma/client.js';
|
||||
import { limit } from '../http.js';
|
||||
@@ -196,12 +196,15 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
}
|
||||
case 'import.finish': {
|
||||
if (!link.importStartedAt) throw new RequestError('There\'s no move under way.', 'NOT_MOVING', 409);
|
||||
const rows = await ctx.db.productPerson.findMany({ where: { linkId: link.installId, via: 'import' } });
|
||||
const subs = rows.map((x) => x.accountId);
|
||||
const matched = subs.length === r.count && importIdsHash(subs) === r.idsHash;
|
||||
// Every account the product relies on must be here, not deleted, and known to it.
|
||||
const wanted = [...new Set(r.subs)];
|
||||
const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: wanted } } })).map((x) => x.accountId));
|
||||
const live = new Set((await ctx.db.account.findMany({ where: { id: { in: wanted }, status: { not: 'deleted' } }, select: { id: true } })).map((x) => x.id as string));
|
||||
const missing = wanted.filter((s) => !known.has(s) || !live.has(s));
|
||||
const matched = missing.length === 0;
|
||||
if (matched) await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: null } });
|
||||
await logRequest(ctx, link, r, matched ? 'import_finished' : 'import_mismatch', null, req, { count: subs.length, expected: r.count });
|
||||
return reply({ matched, count: subs.length });
|
||||
await logRequest(ctx, link, r, matched ? 'import_finished' : 'import_mismatch', null, req, { count: wanted.length - missing.length, expected: wanted.length });
|
||||
return reply({ matched, count: wanted.length - missing.length, missing: missing.slice(0, 100) });
|
||||
}
|
||||
case 'import.abort': {
|
||||
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { importStartedAt: null } });
|
||||
|
||||
@@ -6,7 +6,7 @@ import crypto from 'node:crypto';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, type ImportPerson } from '@crosscode/contracts';
|
||||
import { ed25519PublicToPem, generateEd25519, importIdsHash, LINK_HEADERS, newLinkSecret, sealLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { ed25519PublicToPem, generateEd25519, LINK_HEADERS, newLinkSecret, sealLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
|
||||
import { codeAt, generateSecret } from '../src/lib/totp.js';
|
||||
|
||||
@@ -86,7 +86,13 @@ describe('moving Cross Events\' users in', () => {
|
||||
// bcrypt is replaced with Argon2id at the first sign-in.
|
||||
assert.match(String((await h.db.account.findUnique({ where: { id: thandi.id } }))!.passwordHash), /^\$argon2id\$/);
|
||||
|
||||
const finish = await ask({ type: 'import.finish', count: 2, idsHash: importIdsHash([thandi.id, sipho.id]) });
|
||||
// A sub Accounts doesn't hold for this product keeps the move open.
|
||||
const stranger = crypto.randomUUID();
|
||||
const short = await ask({ type: 'import.finish', subs: [thandi.id, sipho.id, stranger] });
|
||||
assert.equal(short.body.matched, false);
|
||||
assert.deepEqual(short.body.missing, [stranger]);
|
||||
assert.ok((await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.importStartedAt);
|
||||
const finish = await ask({ type: 'import.finish', subs: [thandi.id, sipho.id] });
|
||||
assert.equal(finish.body.matched, true, JSON.stringify(finish.body));
|
||||
assert.equal((await h.db.productLink.findUnique({ where: { installId: EVENTS_ID } }))!.importStartedAt, null);
|
||||
});
|
||||
|
||||
@@ -43,6 +43,12 @@ for people until an admin moves sign-in; see MIGRATING-TO-3.md.
|
||||
clears Events' passwords, authenticator secrets, recovery codes and trusted devices 14 days after
|
||||
the move, and sign-in records after 40 days.
|
||||
- `npm run test:accounts` (backend): Events' sign-in and move against the real Accounts app.
|
||||
- **Connects to the church's Accounts by itself** once the Hub lists it (once: a later Disconnect
|
||||
stays), so a new install from Hub 2.5.0 needs no Connect.
|
||||
- **Demo data** with sign-in through Accounts: the demo people get church accounts with the demo
|
||||
password (`moveNewPeople`, also for anyone added here later without signing in through Accounts).
|
||||
- `e2e/sign-in-accounts.spec.ts`: the move on Settings → Sign-in and signing in at Accounts' real
|
||||
pages from a deep link, with Accounts in memory.
|
||||
|
||||
### Changed
|
||||
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import path from "path";
|
||||
import { test, expect, loginAs, API, type Page } from "./fixtures";
|
||||
|
||||
// Signing in through the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §12, the ROADMAP-v3 §9
|
||||
// release checks): an admin checks and moves sign-in on Settings → Sign-in; then a member signs in
|
||||
// at Accounts with their old Cross Events password and lands on the exact page they started from; a
|
||||
// foreign return address ends on the home page; Events' own sign-in says it moved. Accounts runs in
|
||||
// memory (e2e/support/accounts-server.mts). Afterwards sign-in goes back to Cross Events, 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_PAGES = "http://127.0.0.1:3221";
|
||||
const ACCOUNTS_API = "http://127.0.0.1:5221";
|
||||
const ACCOUNTS_ID = "7e2d1c0b-9a8f-4e6d-8c5b-4a3f2e1d0c9b";
|
||||
const EVENTS_ID = "5c4b3a29-1807-4f6e-9d5c-4b3a29180716";
|
||||
const SITE = "http://localhost:3100";
|
||||
|
||||
async function sql<T = Record<string, unknown>>(text: string, values: unknown[] = []): Promise<T[]> {
|
||||
const client = new Client({ connectionString: e2eDatabaseUrl() });
|
||||
await client.connect();
|
||||
try {
|
||||
return (await client.query(text, values)).rows as T[];
|
||||
} finally {
|
||||
await client.end();
|
||||
}
|
||||
}
|
||||
const setSetting = (key: string, value: string) =>
|
||||
sql(`INSERT INTO "AppSetting" (key, value, "updatedAt") VALUES ($1, $2, now()) ON CONFLICT (key) DO UPDATE SET value = $2, "updatedAt" = now()`, [key, value]);
|
||||
|
||||
let installIdBefore: string | null = null;
|
||||
|
||||
test.describe.serial("signing in through the church's Accounts", () => {
|
||||
test.beforeAll(async () => {
|
||||
// Connect, as Linked products would: the same secret on both sides.
|
||||
const secret = signing.newLinkSecret();
|
||||
installIdBefore = (await sql<{ value: string }>(`SELECT value FROM "AppSetting" WHERE key = 'hub_install_id'`))[0]?.value ?? null;
|
||||
const eventsId = installIdBefore ?? EVENTS_ID;
|
||||
if (!installIdBefore) await setSetting("hub_install_id", eventsId);
|
||||
const linked = await fetch(`${ACCOUNTS_API}/test/link`, { method: "POST", body: JSON.stringify({ installId: eventsId, url: SITE, secret }) });
|
||||
expect(linked.ok).toBe(true);
|
||||
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_PAGES, encrypt(secret)],
|
||||
);
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
// Back to Cross Events' own sign-in for the specs that follow.
|
||||
await sql(`DELETE FROM "AppSetting" WHERE key IN ('auth_mode', 'auth_moved_at', 'auth_move_report', 'auth_move_running', 'accounts_auto_connected')`);
|
||||
await sql(`UPDATE "User" SET "accountId" = NULL`);
|
||||
await sql(`DELETE FROM "ProductLink" WHERE product = 'accounts'`);
|
||||
if (!installIdBefore) await sql(`DELETE FROM "AppSetting" WHERE key = 'hub_install_id'`);
|
||||
});
|
||||
|
||||
test("an admin checks the move, then moves sign-in", async ({ page }) => {
|
||||
page.on("dialog", (d) => d.accept());
|
||||
await loginAs(page, "admin");
|
||||
await page.goto("/dashboard/admin/settings?tab=signin");
|
||||
await expect(page.getByRole("heading", { name: "Sign-in", exact: true })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Check the move" }).click();
|
||||
await expect(page.getByText(/people move with their current password/)).toBeVisible();
|
||||
// Ada stays an Events admin only (an Accounts admin would need two-step sign-in to sign in).
|
||||
const admins = page.locator("fieldset").filter({ hasText: "Accounts admins" });
|
||||
for (const box of await admins.getByRole("checkbox").all()) await box.uncheck();
|
||||
await page.getByRole("button", { name: "Move sign-in to Accounts" }).click();
|
||||
await expect(page.getByText("Sign-in now goes through your church's Accounts.")).toBeVisible();
|
||||
await expect(page.getByText("Through Accounts")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "Undo the move" })).toBeVisible();
|
||||
});
|
||||
|
||||
async function signInAtAccounts(page: Page, email: string, password: string) {
|
||||
await expect(page).toHaveURL(new RegExp(`^${ACCOUNTS_PAGES}/signin`));
|
||||
await expect(page.getByRole("heading", { name: "Sign in to E2E Church" })).toBeVisible();
|
||||
await page.getByLabel("Email address").fill(email);
|
||||
await page.getByLabel("Password").fill(password);
|
||||
await page.getByRole("button", { name: "Sign in" }).click();
|
||||
// A privacy notice published by an earlier spec, or the news question: answer and carry on.
|
||||
const accept = page.getByRole("button", { name: "I've read it" });
|
||||
const cont = page.getByRole("button", { name: "Continue" });
|
||||
for (let i = 0; i < 10 && new URL(page.url()).origin !== SITE; i++) {
|
||||
if (await accept.isVisible()) await accept.click();
|
||||
else if (await cont.isVisible()) await cont.click();
|
||||
else await page.waitForTimeout(500);
|
||||
}
|
||||
await page.waitForURL((u) => u.origin === SITE);
|
||||
}
|
||||
|
||||
test("a member signs in with their Cross Events password and lands on the page they started on", async ({ page }) => {
|
||||
await page.goto("/login?redirect=/dashboard/user/profile");
|
||||
await signInAtAccounts(page, "user@e2e.test", "E2e-password-123");
|
||||
await expect(page).toHaveURL(`${SITE}/dashboard/user/profile`);
|
||||
await expect(page.getByRole("heading", { name: "On your church account" })).toBeVisible();
|
||||
await expect(page.locator("#profile-email-address")).toHaveValue("user@e2e.test");
|
||||
await expect(page.locator("#profile-email-address")).toHaveAttribute("readonly", "");
|
||||
});
|
||||
|
||||
test("a foreign return address ends on the home page", async ({ page }) => {
|
||||
await page.goto(`/login?redirect=${encodeURIComponent("//evil.example/steal")}`);
|
||||
await signInAtAccounts(page, "staff@e2e.test", "E2e-password-123");
|
||||
await expect(page).toHaveURL(new RegExp(`^${SITE}/dashboard`));
|
||||
});
|
||||
|
||||
test("Events' own sign-in says it moved; old reset links say so too", async ({ page, request }) => {
|
||||
const res = await request.post(`${API}/api/v2/auth/login`, { data: { identifier: "user@e2e.test", password: "E2e-password-123" } });
|
||||
expect(res.status()).toBe(409);
|
||||
expect((await res.json()).error.code).toBe("SIGN_IN_MOVED");
|
||||
await page.goto("/reset-password?token=old");
|
||||
await expect(page.getByRole("heading", { name: "Sign-in has moved" })).toBeVisible();
|
||||
});
|
||||
|
||||
test("signing out ends the session here and at Accounts", async ({ page }) => {
|
||||
await page.goto("/login?redirect=/dashboard/user");
|
||||
await signInAtAccounts(page, "user@e2e.test", "E2e-password-123");
|
||||
await expect(page).toHaveURL(`${SITE}/dashboard/user`);
|
||||
const token = await page.evaluate(() => localStorage.getItem("hope_events_token"));
|
||||
const out = await page.request.post(`${API}/api/auth/signout`, { headers: { authorization: `Bearer ${token}` }, data: {} });
|
||||
expect((await out.json()).data.url).toMatch(new RegExp(`^${ACCOUNTS_PAGES}/api/oidc/session/end`));
|
||||
const me = await page.request.get(`${API}/api/v2/me`, { headers: { authorization: `Bearer ${token}` } });
|
||||
expect(me.status()).toBe(401);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* The church's Accounts for Cross Events' end-to-end tests (3.0.0, playwright.config.ts): the real
|
||||
* Accounts backend on 127.0.0.1:5221 with its in-memory database (no Postgres of its own), behind
|
||||
* its pages on 127.0.0.1:3221 (`next dev` in apps/accounts/frontend). Its own address (127.0.0.1)
|
||||
* differs from the Events site's (localhost), so their cookies stay apart as on two domains.
|
||||
*
|
||||
* Test helper: POST /test/link { installId, url, secret } links Events, as Connect would.
|
||||
*/
|
||||
import http from 'node:http';
|
||||
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||
import { createApp } from '../../../accounts/backend/src/app.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';
|
||||
import { createProvider } from '../../../accounts/backend/src/oidc/provider.ts';
|
||||
import { memoryDb } from '../../../accounts/backend/tests/support/memoryDb.ts';
|
||||
|
||||
const WEB = 'http://127.0.0.1:3221';
|
||||
const db = memoryDb();
|
||||
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: new MemoryMessenger() });
|
||||
await ctx.settings.setMany({
|
||||
hub_install_id: '7e2d1c0b-9a8f-4e6d-8c5b-4a3f2e1d0c9b',
|
||||
church_profile: JSON.stringify({ name: 'E2E Church', shortName: 'E2E' }),
|
||||
});
|
||||
const provider = await createProvider(ctx);
|
||||
const app = createApp(ctx, provider);
|
||||
|
||||
http.createServer((req, res) => {
|
||||
if (req.method === 'POST' && req.url === '/test/link') {
|
||||
let body = '';
|
||||
req.on('data', (c) => { body += c; });
|
||||
req.on('end', async () => {
|
||||
const { installId, url, secret } = JSON.parse(body) as { installId: string; url: string; secret: string };
|
||||
const data = { product: 'events', url, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: ctx.secrets.encrypt(secret), connectedAt: new Date() };
|
||||
await db.productLink.upsert({ where: { installId }, create: { installId, ...data }, update: data });
|
||||
res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ ok: true }));
|
||||
});
|
||||
return;
|
||||
}
|
||||
app(req, res);
|
||||
}).listen(5221, '127.0.0.1', () => console.log('[e2e] Accounts on 5221'));
|
||||
@@ -12,6 +12,11 @@ const nextConfig: NextConfig = {
|
||||
compiler: {
|
||||
removeConsole: process.env.NODE_ENV === 'production',
|
||||
},
|
||||
// The end-to-end tests only (3.0.0): the site and its API on one address, as nginx does on a
|
||||
// server, so Accounts' sign-in comes back to <site>/api/auth/callback. Unset everywhere else.
|
||||
...(process.env.E2E_API_PROXY
|
||||
? { async rewrites() { return [{ source: '/api/:path*', destination: `${process.env.E2E_API_PROXY}/api/:path*` }]; } }
|
||||
: {}),
|
||||
};
|
||||
|
||||
// A no-op wrap when SENTRY_DSN isn't configured for this deployment — safe in
|
||||
|
||||
@@ -67,9 +67,30 @@ export default defineConfig({
|
||||
env: {
|
||||
NEXT_PUBLIC_API_URL: `http://localhost:${API_PORT}`,
|
||||
API_URL: `http://localhost:${API_PORT}`,
|
||||
// 3.0.0: the site and its API on one address (as nginx does), for Accounts' callback.
|
||||
E2E_API_PROXY: `http://localhost:${API_PORT}`,
|
||||
NEXT_DIST_DIR: ci ? ".next" : ".next-e2e",
|
||||
NEXT_TELEMETRY_DISABLED: "1",
|
||||
},
|
||||
},
|
||||
// 3.0.0 (sign-in-accounts.spec.ts): the church's Accounts, in memory, and its pages.
|
||||
{
|
||||
command: "npx tsx e2e/support/accounts-server.mts",
|
||||
url: "http://127.0.0.1:5221/api/health",
|
||||
timeout: 120_000,
|
||||
reuseExistingServer: !ci,
|
||||
stdout: "ignore",
|
||||
stderr: "pipe",
|
||||
},
|
||||
{
|
||||
command: "npx next dev -p 3221 -H 127.0.0.1",
|
||||
cwd: "../accounts/frontend",
|
||||
url: "http://127.0.0.1:3221/privacy",
|
||||
timeout: 300_000,
|
||||
reuseExistingServer: !ci,
|
||||
stdout: "ignore",
|
||||
stderr: "pipe",
|
||||
env: { ACCOUNTS_API_URL: "http://127.0.0.1:5221", NEXT_TELEMETRY_DISABLED: "1" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user