Events 3.6.0, Accounts 1.5.0, contracts 1.14.0: the nightly people check
- Contracts 1.14.0: people.check in crosscode.identity-request/1 (500 subs) and its reply (active / deactivated / deleted / unknown, profile for the first two). - Accounts 1.5.0: answers people.check with profiles only for people the product knows; the reply isn't stored. - Events 3.6.0: accounts-people-check job (04:30): fixes out-of-date copies, handles deleted accounts as user.deleted, counts unknown people and stops (changing nothing) when most of a page is unknown; skipped with an Accounts older than 1.5.0. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,21 @@ 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.6.0] - 2026-11-20
|
||||
|
||||
Works with any Accounts; the people check needs Accounts 1.5.0 (with an older one it's skipped).
|
||||
|
||||
### Added
|
||||
|
||||
- **The nightly people check** (`accounts-people-check`, 04:30, `ACCOUNTS_PEOPLE_CHECK_ENABLED`,
|
||||
`src/accounts/peopleCheck.ts`). In Accounts mode it sends every linked person's `sub` to
|
||||
Accounts, 500 at a time (`people.check`, contracts 1.14.0), and: updates the local copy where the
|
||||
name, email, phone or news choices differ (as `user.updated`); handles deleted accounts as
|
||||
`user.deleted` (anonymised, or deferred while there's a registration for an event that hasn't
|
||||
ended); counts deactivated and unknown people. When more than half a page (10+) is unknown, the
|
||||
site is probably linked to the wrong Accounts: the check stops, changes nothing for them, fails
|
||||
(Background jobs, the Hub's "jobs failing") and records why (the Hub's "sign-in failed" alert).
|
||||
|
||||
## [3.5.0] - 2026-11-20
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -12,6 +12,13 @@ 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.6.0
|
||||
|
||||
- **People's details are checked every night.** Cross Events compares everyone's name, email,
|
||||
phone and news choices with their church account and fixes any that are out of date, and handles
|
||||
accounts that were deleted, in case a change never reached this site. You can see it, run it or
|
||||
switch it off under Settings → Background jobs. It needs Accounts 1.5.0.
|
||||
|
||||
## 3.5.0
|
||||
|
||||
- **Fix:** after loading demo data, nobody could sign in: the site forgot its link to the church's
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.5.0",
|
||||
"version": "3.6.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* The nightly people check (3.6.0, contracts 1.14.0 `people.check`, Accounts 1.5.0): Accounts tells
|
||||
* Events about every change (`user.updated`, `user.deleted`), retried for about a week; this catches
|
||||
* whatever never arrived (a link that was down, as after a demo load before 3.5.0). For everyone here
|
||||
* with an account it asks Accounts, a page at a time, and:
|
||||
*
|
||||
* - updates the local copy when the profile differs (as `user.updated` does);
|
||||
* - handles a deleted account as `user.deleted` does (anonymised, or deferred while the person has a
|
||||
* registration for an event that hasn't ended);
|
||||
* - only counts people Accounts doesn't know through this site (`unknown`). When most of a page is
|
||||
* unknown, Events is probably linked to the wrong Accounts: the check stops and fails, so it
|
||||
* shows on Background jobs and the Hub, and nothing is changed for those people.
|
||||
*/
|
||||
import { PEOPLE_CHECK_MAX, peopleCheckReplySchema, type PeopleCheckReply, type Profile } from '@crosscode/contracts';
|
||||
import { accounts, accountsLink } from './client';
|
||||
import { handleAccountsCall } from './calls';
|
||||
import { viaAccounts } from './mode';
|
||||
import { recordSignInError } from './status';
|
||||
import { updateLocalCopy } from './signin';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const prisma = require('../config/db');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
type Local = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
|
||||
export type PeopleCheckResult = { checked: number; updated: number; deleted: number; deferred: number; deactivated: number; unknown: number } | { skipped: string };
|
||||
|
||||
/** Asks Accounts about these subs (tests replace it). */
|
||||
export type Ask = (subs: string[]) => Promise<PeopleCheckReply>;
|
||||
|
||||
const defaultAsk: Ask = async (subs) => {
|
||||
const auth = await accounts();
|
||||
const raw = await auth.request({ type: 'people.check', actor: null, subs }, { timeoutMs: 120000 });
|
||||
return peopleCheckReplySchema.parse(raw);
|
||||
};
|
||||
|
||||
/** Whether the local copy already says what the profile says (only what Events keeps). */
|
||||
export function sameAsLocal(u: Local, p: Profile): boolean {
|
||||
return u.name === p.name
|
||||
&& u.email.toLowerCase() === p.email.toLowerCase()
|
||||
&& (u.phoneNumber ?? null) === (p.phone_number ?? null)
|
||||
&& u.newsEmail === p.news_consent.email
|
||||
&& u.newsWhatsApp === p.news_consent.whatsapp;
|
||||
}
|
||||
|
||||
/** More than this share of a page unknown (with at least MIN_FOR_ALARM people) stops the check. */
|
||||
const UNKNOWN_ALARM = 0.5;
|
||||
const MIN_FOR_ALARM = 10;
|
||||
|
||||
export async function runPeopleCheck(opts: { ask?: Ask; pageSize?: number } = {}): Promise<PeopleCheckResult> {
|
||||
if (!(await viaAccounts())) return { skipped: 'This site uses its own sign-in.' };
|
||||
if (!(await accountsLink())) return { skipped: 'Accounts isn\'t linked.' };
|
||||
const ask = opts.ask ?? defaultAsk;
|
||||
const size = Math.min(opts.pageSize ?? PEOPLE_CHECK_MAX, PEOPLE_CHECK_MAX);
|
||||
const out = { checked: 0, updated: 0, deleted: 0, deferred: 0, deactivated: 0, unknown: 0 };
|
||||
let cursor: string | undefined;
|
||||
for (;;) {
|
||||
const page: Local[] = await prisma.user.findMany({
|
||||
where: { accountId: { not: null } },
|
||||
select: { id: true, accountId: true, name: true, email: true, phoneNumber: true, newsEmail: true, newsWhatsApp: true },
|
||||
orderBy: { id: 'asc' },
|
||||
take: size,
|
||||
...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
|
||||
});
|
||||
if (!page.length) break;
|
||||
cursor = page[page.length - 1]!.id;
|
||||
const bySub = new Map(page.map((u) => [u.accountId, u]));
|
||||
let reply: PeopleCheckReply;
|
||||
try {
|
||||
reply = await ask(page.map((u) => u.accountId));
|
||||
} catch (e) {
|
||||
// Accounts before 1.5.0 doesn't know people.check: nothing to do until it's updated.
|
||||
const err = e as { code?: string; message?: string };
|
||||
if (err.code === 'INVALID_REQUEST' && /\btype\b/.test(err.message ?? '')) return { skipped: 'The church\'s Accounts is older than 1.5.0, which this check needs.' };
|
||||
throw e;
|
||||
}
|
||||
const unknown = reply.people.filter((p) => p.status === 'unknown').length;
|
||||
if (page.length >= MIN_FOR_ALARM && unknown / page.length > UNKNOWN_ALARM) {
|
||||
const message = `Accounts doesn't know ${unknown} of ${page.length} people here: is this site linked to the church's own Accounts? Nothing was changed for them.`;
|
||||
await recordSignInError('PEOPLE_UNKNOWN', message);
|
||||
throw new Error(message);
|
||||
}
|
||||
for (const p of reply.people) {
|
||||
const u = bySub.get(p.sub);
|
||||
if (!u) continue; // not one we asked about
|
||||
out.checked++;
|
||||
if (p.status === 'unknown') { out.unknown++; continue; }
|
||||
if (p.status === 'deleted') {
|
||||
const r = await handleAccountsCall({ type: 'user.deleted', sub: p.sub } as never) as { status?: string };
|
||||
if (r.status === 'deferred') out.deferred++; else out.deleted++;
|
||||
continue;
|
||||
}
|
||||
if (p.status === 'deactivated') out.deactivated++;
|
||||
if (p.profile && !sameAsLocal(u, p.profile)) {
|
||||
await updateLocalCopy(u.id, p.profile);
|
||||
out.updated++;
|
||||
}
|
||||
}
|
||||
if (page.length < size) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -98,6 +98,11 @@ const JOBS = [
|
||||
name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED',
|
||||
run: async () => ({ file: (await require('../utils/backupUtils').runBackup()).filename }),
|
||||
},
|
||||
{
|
||||
// 3.6.0: catch any change from Accounts that never arrived (accounts/peopleCheck.ts).
|
||||
name: 'accounts-people-check', label: 'Accounts: check everyone\'s details here match their church account', cron: '30 4 * * *', env: 'ACCOUNTS_PEOPLE_CHECK_ENABLED',
|
||||
run: () => require('../accounts/peopleCheck').runPeopleCheck(),
|
||||
},
|
||||
{
|
||||
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §5): 14 days after sign-in moved to Accounts, Events' old
|
||||
// passwords and 2FA secrets go; sign-in records (for signing out of Accounts) after 40 days.
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// 3.6.0: the nightly people check against Accounts (contracts 1.14.0 people.check).
|
||||
type U = { id: string; accountId: string; name: string; email: string; phoneNumber: string | null; newsEmail: boolean; newsWhatsApp: boolean };
|
||||
let mockUsers: U[] = [];
|
||||
const mockUpdated: string[] = [];
|
||||
const mockCalls: { type: string; sub: string }[] = [];
|
||||
const mockErrors: string[] = [];
|
||||
let mockMode = true;
|
||||
let mockLinked = true;
|
||||
let mockDeferred = new Set<string>();
|
||||
|
||||
jest.mock('../src/config/db', () => ({
|
||||
user: {
|
||||
findMany: async ({ take, cursor }: { take: number; cursor?: { id: string } }) => {
|
||||
const sorted = [...mockUsers].sort((a, b) => a.id.localeCompare(b.id));
|
||||
const start = cursor ? sorted.findIndex((u) => u.id === cursor.id) + 1 : 0;
|
||||
return sorted.slice(start, start + take);
|
||||
},
|
||||
},
|
||||
}));
|
||||
jest.mock('../src/accounts/mode', () => ({ viaAccounts: async () => mockMode }));
|
||||
jest.mock('../src/accounts/client', () => ({ accountsLink: async () => (mockLinked ? { installId: 'acc-1' } : null), accounts: async () => { throw new Error('not in tests'); } }));
|
||||
jest.mock('../src/accounts/signin', () => ({ updateLocalCopy: async (id: string) => { mockUpdated.push(id); } }));
|
||||
jest.mock('../src/accounts/calls', () => ({
|
||||
handleAccountsCall: async (c: { type: string; sub: string }) => { mockCalls.push(c); return { status: mockDeferred.has(c.sub) ? 'deferred' : 'deleted' }; },
|
||||
}));
|
||||
jest.mock('../src/accounts/status', () => ({ recordSignInError: async (_c: string, m: string) => { mockErrors.push(m); } }));
|
||||
|
||||
import type { PeopleCheckReply, Profile } from '@crosscode/contracts';
|
||||
import { runPeopleCheck, sameAsLocal } from '../src/accounts/peopleCheck';
|
||||
|
||||
const sub = (n: number) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
|
||||
const user = (n: number, over: Partial<U> = {}): U => ({ id: `u${String(n).padStart(3, '0')}`, accountId: sub(n), name: `Person ${n}`, email: `p${n}@hope.test`, phoneNumber: null, newsEmail: false, newsWhatsApp: false, ...over });
|
||||
const profile = (u: U, over: Partial<Profile> = {}): Profile => ({ name: u.name, given_name: null, family_name: null, email: u.email, email_verified: true, phone_number: u.phoneNumber, phone_number_verified: false, news_consent: { email: u.newsEmail, whatsapp: u.newsWhatsApp }, ...over });
|
||||
|
||||
beforeEach(() => {
|
||||
mockUsers = []; mockUpdated.length = 0; mockCalls.length = 0; mockErrors.length = 0;
|
||||
mockMode = true; mockLinked = true; mockDeferred = new Set();
|
||||
});
|
||||
|
||||
test('updates only copies that differ, handles deleted accounts as user.deleted does, counts the rest', async () => {
|
||||
mockUsers = [user(1), user(2), user(3), user(4), user(5)];
|
||||
mockDeferred = new Set([sub(4)]);
|
||||
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({
|
||||
schema: 'crosscode.identity-request/1',
|
||||
people: subs.map((s) => {
|
||||
const u = mockUsers.find((x) => x.accountId === s)!;
|
||||
if (s === sub(1)) return { sub: s, status: 'active' as const, profile: profile(u) };
|
||||
if (s === sub(2)) return { sub: s, status: 'active' as const, profile: profile(u, { name: 'New Name', news_consent: { email: true, whatsapp: false } }) };
|
||||
if (s === sub(3) || s === sub(4)) return { sub: s, status: 'deleted' as const, profile: null };
|
||||
return { sub: s, status: 'unknown' as const, profile: null };
|
||||
}),
|
||||
});
|
||||
expect(await runPeopleCheck({ ask, pageSize: 2 })).toEqual({ checked: 5, updated: 1, deleted: 1, deferred: 1, deactivated: 0, unknown: 1 });
|
||||
expect(mockUpdated).toEqual(['u002']);
|
||||
expect(mockCalls.map((c) => [c.type, c.sub])).toEqual([['user.deleted', sub(3)], ['user.deleted', sub(4)]]);
|
||||
});
|
||||
|
||||
test('stops, changing nothing, when Accounts knows hardly anyone (linked to the wrong Accounts?)', async () => {
|
||||
mockUsers = Array.from({ length: 12 }, (_, i) => user(i + 1));
|
||||
const ask = async (subs: string[]): Promise<PeopleCheckReply> => ({ schema: 'crosscode.identity-request/1', people: subs.map((s) => ({ sub: s, status: 'unknown' as const, profile: null })) });
|
||||
await expect(runPeopleCheck({ ask })).rejects.toThrow(/doesn't know 12 of 12/);
|
||||
expect(mockCalls).toEqual([]);
|
||||
expect(mockErrors).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('skipped on its own sign-in, or without a link', async () => {
|
||||
mockMode = false;
|
||||
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
|
||||
mockMode = true; mockLinked = false;
|
||||
expect(await runPeopleCheck({ ask: async () => { throw new Error('asked'); } })).toEqual({ skipped: expect.any(String) });
|
||||
});
|
||||
|
||||
test('sameAsLocal ignores email case and what Events doesn\'t keep', () => {
|
||||
const u = user(1, { email: 'Jane@Hope.test' });
|
||||
expect(sameAsLocal(u, profile(u, { email: 'jane@hope.test', email_verified: false, given_name: 'Jane' }))).toBe(true);
|
||||
expect(sameAsLocal(u, profile(u, { phone_number: '+27821234567' }))).toBe(false);
|
||||
});
|
||||
|
||||
test('an Accounts before 1.5.0 (people.check unknown there) skips the check instead of failing every night', async () => {
|
||||
mockUsers = [user(1)];
|
||||
const ask = async () => { throw Object.assign(new Error('Not a crosscode.identity-request/1 request: type Invalid input'), { code: 'INVALID_REQUEST' }); };
|
||||
expect(await runPeopleCheck({ ask })).toEqual({ skipped: expect.stringContaining('1.5.0') });
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.5.0",
|
||||
"version": "3.6.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events",
|
||||
"version": "3.5.0",
|
||||
"version": "3.6.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
|
||||
Reference in New Issue
Block a user