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:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user