Cross Events 3.0.0: sign-in through the church's Accounts

Settings -> Sign-in: check, move (everyone into Accounts with their password
hashes and authenticator apps, count/hash check, then switch) and undo for
14 days. Sign-in through auth-client with a one-time handoff to Events' own
token; staff roles stepped up to mfa; sign-out and back-channel logout;
user.updated/export/deleted; admin 2FA reset, unlock and profile changes via
Accounts; /login, /register, /forgot-password forward once moved; Events'
own sign-in endpoints answer SIGN_IN_MOVED. User.accountId, AccountsSignIn.

npm run test:accounts runs Events' code against the real Accounts app (11
tests); 5 new Jest tests. MIGRATING-TO-3.md, plan "Changes while building".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 14:10:30 +02:00
co-authored by Claude Opus 5.5
parent 56cbef1d9b
commit c627c61de1
49 changed files with 4094 additions and 245 deletions
+4 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-backend",
"version": "2.4.1",
"version": "3.0.0",
"description": "Event Management System Backend",
"main": "src/index.js",
"scripts": {
@@ -18,10 +18,12 @@
"build": "tsc -p tsconfig.json && node -e \"require('fs').writeFileSync('dist/build.json', JSON.stringify({ version: require('./package.json').version, builtAt: new Date().toISOString() }))\"",
"typecheck": "tsc -p tsconfig.json --noEmit",
"openapi": "tsx scripts/openapi.ts",
"ai:eval": "tsx scripts/ai-eval.ts"
"ai:eval": "tsx scripts/ai-eval.ts",
"test:accounts": "node --import tsx --test --test-reporter=spec tests/accounts-integration/*.int.mts"
},
"dependencies": {
"@cj-tech-master/excelts": "^10.2.0",
"@crosscode/auth-client": "*",
"@crosscode/contracts": "*",
"@node-rs/argon2": "^2.2.2",
"@prisma/adapter-pg": "^7.10.1",
@@ -0,0 +1,41 @@
-- 3.0.0: signing in through the church's Accounts (docs/EVENTS-3.0-PLAN.md).
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_started';
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_finished';
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_failed';
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_move_undone';
ALTER TYPE "AdminAuditAction" ADD VALUE 'sign_in_secrets_cleared';
ALTER TYPE "AdminAuditAction" ADD VALUE 'account_changed_in_accounts';
-- AlterTable
ALTER TABLE "User" ADD COLUMN "accountId" TEXT;
-- CreateIndex
CREATE UNIQUE INDEX "User_accountId_key" ON "User"("accountId");
-- CreateTable
CREATE TABLE "AccountsSignIn" (
"id" TEXT NOT NULL,
"userId" TEXT NOT NULL,
"codeHash" TEXT,
"codeExpires" TIMESTAMP(3),
"codeUsedAt" TIMESTAMP(3),
"returnTo" TEXT NOT NULL,
"idToken" TEXT,
"sid" TEXT,
"mfa" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT "AccountsSignIn_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "AccountsSignIn_codeHash_key" ON "AccountsSignIn"("codeHash");
-- CreateIndex
CREATE INDEX "AccountsSignIn_userId_idx" ON "AccountsSignIn"("userId");
-- CreateIndex
CREATE INDEX "AccountsSignIn_createdAt_idx" ON "AccountsSignIn"("createdAt");
-- AddForeignKey
ALTER TABLE "AccountsSignIn" ADD CONSTRAINT "AccountsSignIn_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+244 -213
View File
@@ -66,6 +66,10 @@ enum TwoFactorMethod {
model User {
id String @id @default(uuid())
// 3.0.0: the church's account (Accounts' `sub`) this user signs in with. Equal to `id` for
// everyone moved in (docs/EVENTS-3.0-PLAN.md §2); another sub when their email already had an
// account; null for guests, deleted people, and everyone before the move.
accountId String? @unique
name String
email String @unique
password String
@@ -108,76 +112,77 @@ model User {
Event Event[]
FormDraft FormDraft[]
eventsClosed Event[] @relation("EventClosedBy")
eventsReopened Event[] @relation("EventReopenedBy")
eventsClosed Event[] @relation("EventClosedBy")
eventsReopened Event[] @relation("EventReopenedBy")
cashupsPerformed EventCashup[]
pendingResolved EventCashupPendingResolution[] @relation("PendingResolutionBy")
notifyForEvents Event[] @relation("EventNotifyRecipients")
notifyForEvents Event[] @relation("EventNotifyRecipients")
personCashCountsFor EventCashupPersonCount[] @relation("EventCashupPersonCountFor")
personCashCountsEntered EventCashupPersonCount[] @relation("EventCashupPersonCountEnteredBy")
securityEvents SecurityEvent[]
adminAuditLogs AdminAuditLog[] @relation("AdminAuditActor")
securityEvents SecurityEvent[]
accountsSignIns AccountsSignIn[]
adminAuditLogs AdminAuditLog[] @relation("AdminAuditActor")
couponsCreated Coupon[] @relation("CouponCreatedBy")
couponAccess CouponUser[]
couponRedemptions CouponRedemption[] @relation("CouponRedemptionUser")
couponsApplied CouponRedemption[] @relation("CouponRedemptionAppliedBy")
attendeeProfiles Attendee[]
heldTickets Ticket[] @relation("TicketHolder")
waitlistEntries WaitlistEntry[]
scanLocks ScanLock[] @relation("ScanLockOwner")
transfersTo TicketTransfer[] @relation("TransferRecipient")
transfersBy TicketTransfer[] @relation("TransferActor")
ledGroups AllocationGroup[] @relation("AllocationGroupLeader")
feedbackInvites FeedbackInvite[]
feedbackGiven FeedbackResponse[]
impersonationsDone ImpersonationSession[] @relation("ImpersonationAdmin")
attendeeProfiles Attendee[]
heldTickets Ticket[] @relation("TicketHolder")
waitlistEntries WaitlistEntry[]
scanLocks ScanLock[] @relation("ScanLockOwner")
transfersTo TicketTransfer[] @relation("TransferRecipient")
transfersBy TicketTransfer[] @relation("TransferActor")
ledGroups AllocationGroup[] @relation("AllocationGroupLeader")
feedbackInvites FeedbackInvite[]
feedbackGiven FeedbackResponse[]
impersonationsDone ImpersonationSession[] @relation("ImpersonationAdmin")
transferRequests TicketTransferRequest[] @relation("TransferRequester")
impersonatedIn ImpersonationSession[] @relation("ImpersonationTarget")
scanLocksForced ScanLock[] @relation("ScanLockForcedBy")
syncReportsDone OfflineSyncReport[] @relation("SyncReportReviewer")
impersonatedIn ImpersonationSession[] @relation("ImpersonationTarget")
scanLocksForced ScanLock[] @relation("ScanLockForcedBy")
syncReportsDone OfflineSyncReport[] @relation("SyncReportReviewer")
twoFactorChallenges TwoFactorChallenge[]
trustedDevices TrustedDevice[]
certificates Certificate[]
certificatesIssued Certificate[] @relation("CertificateIssuedBy")
twoFactorChallenges TwoFactorChallenge[]
trustedDevices TrustedDevice[]
certificates Certificate[]
certificatesIssued Certificate[] @relation("CertificateIssuedBy")
communicationConsents CommunicationConsent[]
dataRequests DataRequest[]
dataRequestsHandled DataRequest[] @relation("DataRequestHandledBy")
noticesPublished PrivacyNotice[]
noticeAcceptances NoticeAcceptance[]
dataAccessLogs DataAccessLog[]
breachesRecorded SecurityBreach[]
dataRequests DataRequest[]
dataRequestsHandled DataRequest[] @relation("DataRequestHandledBy")
noticesPublished PrivacyNotice[]
noticeAcceptances NoticeAcceptance[]
dataAccessLogs DataAccessLog[]
breachesRecorded SecurityBreach[]
// Multi-campus (only used while Site settings → Campuses is on).
homeCampusId String?
homeCampus Campus? @relation("UserHomeCampus", fields: [homeCampusId], references: [id], onDelete: SetNull)
campusSummaries Campus[] @relation("CampusNotifyRecipients")
homeCampusId String?
homeCampus Campus? @relation("UserHomeCampus", fields: [homeCampusId], references: [id], onDelete: SetNull)
campusSummaries Campus[] @relation("CampusNotifyRecipients")
// Campus-scoped staff (1.44.0): a supervisor/staff member limited to these campuses (their
// events plus events for all campuses). Empty = unscoped. Ignored for admins and while
// campuses are off (utils/campusScope.js).
scopedCampuses Campus[] @relation("UserCampusScope")
scopedCampuses Campus[] @relation("UserCampusScope")
// Kids check-in (1.45.0): the family this person is a parent in (at most one).
familyMembership FamilyMember?
kidsCheckInsDone KidsCheckIn[] @relation("KidsCheckInBy")
kidsCheckOutsDone KidsCheckIn[] @relation("KidsCheckOutBy")
kidsAlertsRaised KidsAlert[]
kidsRoomDuties KidsRoomDuty[]
familyMembership FamilyMember?
kidsCheckInsDone KidsCheckIn[] @relation("KidsCheckInBy")
kidsCheckOutsDone KidsCheckIn[] @relation("KidsCheckOutBy")
kidsAlertsRaised KidsAlert[]
kidsRoomDuties KidsRoomDuty[]
// Volunteer rosters (1.46.0)
volunteerSlots VolunteerSlot[] @relation("VolunteerSlotUser")
volunteersAssigned VolunteerSlot[] @relation("VolunteerSlotAssignedBy")
volunteersCheckedIn VolunteerSlot[] @relation("VolunteerSlotCheckedInBy")
volunteerSlots VolunteerSlot[] @relation("VolunteerSlotUser")
volunteersAssigned VolunteerSlot[] @relation("VolunteerSlotAssignedBy")
volunteersCheckedIn VolunteerSlot[] @relation("VolunteerSlotCheckedInBy")
seriesFollows SeriesFollow[]
seasonPassPurchases SeasonPassPurchase[]
savedFilters SavedFilter[]
aiCalls AiCall[]
swapsAsked VolunteerSwap[] @relation("VolunteerSwapFrom")
swapsTaken VolunteerSwap[] @relation("VolunteerSwapTo")
swapsAsked VolunteerSwap[] @relation("VolunteerSwapFrom")
swapsTaken VolunteerSwap[] @relation("VolunteerSwapTo")
@@index([homeCampusId])
}
@@ -318,27 +323,27 @@ model Event {
// tickets. Each child gets a free place on `kidsOptionId` (a main-ticket option of this
// event) the first time, so they show on the attendance register; rooms are the groups of
// the allocation set `kidsRoomSetId`. Plain ids (checked in utils/kids.js), not relations.
kidsCheckIn Boolean @default(false)
kidsOptionId String?
kidsRoomSetId String?
kidsPickupCodes KidsPickupCode[]
kidsCheckIns KidsCheckIn[]
kidsAlerts KidsAlert[]
kidsCheckIn Boolean @default(false)
kidsOptionId String?
kidsRoomSetId String?
kidsPickupCodes KidsPickupCode[]
kidsCheckIns KidsCheckIn[]
kidsAlerts KidsAlert[]
// Volunteer rosters (1.46.0): serving roles for the event or one of its sessions. When
// `volunteerOptionId` is set (a main ticket of this event; off by default), each volunteer
// gets a free place on it. `volunteerCheckInToken` is in the check-in QR code volunteers scan
// on the day (made the first time the QR code is shown). Plain id, checked in utils/volunteers.js.
servingRoles ServingRole[]
volunteerOptionId String?
volunteerCheckInToken String? @unique
servingRoles ServingRole[]
volunteerOptionId String?
volunteerCheckInToken String? @unique
// Event series (1.47.1): separate events grouped on one series page (Camp 2025, Camp 2026).
// seriesAnnouncedAt: when followers were emailed that this event is out (once, when it goes live).
seriesId String?
series EventSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
seasonPassItems SeasonPassItem[]
seriesAnnouncedAt DateTime?
seriesId String?
series EventSeries? @relation(fields: [seriesId], references: [id], onDelete: SetNull)
seasonPassItems SeasonPassItem[]
seriesAnnouncedAt DateTime?
@@index([createdById])
@@index([closedById])
@@ -502,47 +507,47 @@ model OptionVariant {
}
model Registration {
id String @id @default(uuid())
userId String
eventId String
status RegistrationStatus @default(pending)
checkoutId String? @unique
id String @id @default(uuid())
userId String
eventId String
status RegistrationStatus @default(pending)
checkoutId String? @unique
// Sum of this registration's discounts: bundle deals plus active coupon discounts,
// kept in step with bundleApplications and couponRedemptions. Stored here so every
// total-due calculation sees it no matter which relations the caller loaded (see
// utils/pricing.js computeRegistrationTotalDue).
discountTotal Float @default(0)
discountTotal Float @default(0)
// The bundle-deal part of discountTotal (the rest is coupons).
bundleDiscount Float @default(0)
bundleDiscount Float @default(0)
// Where named attendees' tickets go: all to the payer, or each to the attendee.
ticketDelivery TicketDelivery @default(payer)
ticketDelivery TicketDelivery @default(payer)
// Corrections (1.52.0). The attendee form can come later: tickets don't wait for it ("Fill in
// later" at the door or in Manual registrations, or an admin in Corrections).
formWaivedAt DateTime?
formWaivedById String?
formWaivedAt DateTime?
formWaivedById String?
// An admin issued the tickets before it was paid ("pay later"): the balance is still owed.
ticketsReleasedAt DateTime?
ticketsReleasedById String?
ticketsReleasedAt DateTime?
ticketsReleasedById String?
// A balance an admin wrote off ("make it free"); part of discountTotal (utils/coupons.js).
complimentaryDiscount Float @default(0)
analyticsSessionId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
registrationOptions RegistrationOption[]
payments Payment[]
formResponses FormResponse[]
formDrafts FormDraft[]
couponRedemptions CouponRedemption[]
bundleApplications RegistrationBundle[]
complimentaryDiscount Float @default(0)
analyticsSessionId String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
registrationOptions RegistrationOption[]
payments Payment[]
formResponses FormResponse[]
formDrafts FormDraft[]
couponRedemptions CouponRedemption[]
bundleApplications RegistrationBundle[]
// Season pass (1.47.3): one registration per event on the pass, its line priced at that
// event's share of the pass price (never repriced, no coupons, options not editable).
seasonPassPurchaseId String?
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
attendees Attendee[]
waitlistEntries WaitlistEntry[]
volunteerSlots VolunteerSlot[]
seasonPassPurchaseId String?
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
attendees Attendee[]
waitlistEntries WaitlistEntry[]
volunteerSlots VolunteerSlot[]
@@index([userId])
@@index([eventId])
@@ -603,37 +608,37 @@ model RegistrationOptionTranche {
}
model Payment {
id String @id @default(uuid())
amount Float
method String
userId String
recordedById String?
registrationId String?
eventId String?
isDonation Boolean @default(false)
id String @id @default(uuid())
amount Float
method String
userId String
recordedById String?
registrationId String?
eventId String?
isDonation Boolean @default(false)
// A "sponsor a spot" donation (also isDonation): goes into the event's sponsorship pool.
isSponsorship Boolean @default(false)
sponsorName String?
sponsorMessage String?
sponsorAnonymous Boolean @default(false)
externalId String? @unique
status String?
originalPaymentId String?
isSponsorship Boolean @default(false)
sponsorName String?
sponsorMessage String?
sponsorAnonymous Boolean @default(false)
externalId String? @unique
status String?
originalPaymentId String?
// Online payments: the payment provider that took it (src/payments, e.g. "yoco"). Null for
// payments recorded by staff. Payment.method stays the wallet type (card, apple_pay, …).
provider String?
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
recordedBy User? @relation("PaymentRecordedBy", fields: [recordedById], references: [id], onDelete: SetNull)
registration Registration? @relation(fields: [registrationId], references: [id], onDelete: SetNull)
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
originalPayment Payment? @relation("SplitPayments", fields: [originalPaymentId], references: [id], onDelete: SetNull)
splitPayments Payment[] @relation("SplitPayments")
provider String?
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
recordedBy User? @relation("PaymentRecordedBy", fields: [recordedById], references: [id], onDelete: SetNull)
registration Registration? @relation(fields: [registrationId], references: [id], onDelete: SetNull)
event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull)
originalPayment Payment? @relation("SplitPayments", fields: [originalPaymentId], references: [id], onDelete: SetNull)
splitPayments Payment[] @relation("SplitPayments")
providerTransactions ProviderTransaction[]
// Season pass: one provider payment is recorded as one Payment per event on the pass (its
// share), all linked to the purchase. Only the first carries the provider's externalId.
seasonPassPurchaseId String?
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
seasonPassPurchase SeasonPassPurchase? @relation(fields: [seasonPassPurchaseId], references: [id], onDelete: SetNull)
@@index([userId])
@@index([recordedById])
@@ -644,25 +649,25 @@ model Payment {
}
model Ticket {
id String @id @default(uuid())
qrCode String @unique
id String @id @default(uuid())
qrCode String @unique
registrationOptionId String
userId String
eventId String
quantity Int @default(1)
isUsed Boolean @default(false)
emailSent Boolean @default(false)
quantity Int @default(1)
isUsed Boolean @default(false)
emailSent Boolean @default(false)
// Set on a named (group) ticket: the person it's for, and their account when it
// matched one. userId stays the payer.
attendeeId String? @unique
attendee Attendee? @relation(fields: [attendeeId], references: [id], onDelete: SetNull)
attendeeId String? @unique
attendee Attendee? @relation(fields: [attendeeId], references: [id], onDelete: SetNull)
holderUserId String?
holder User? @relation("TicketHolder", fields: [holderUserId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
registrationOption RegistrationOption @relation(fields: [registrationOptionId], references: [id], onDelete: Restrict)
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
holder User? @relation("TicketHolder", fields: [holderUserId], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
registrationOption RegistrationOption @relation(fields: [registrationOptionId], references: [id], onDelete: Restrict)
user User @relation(fields: [userId], references: [id], onDelete: Restrict)
event Event @relation(fields: [eventId], references: [id], onDelete: Restrict)
usages TicketUsage[]
transfers TicketTransfer[]
transferRequests TicketTransferRequest[]
@@ -676,25 +681,25 @@ model Ticket {
}
model TicketUsage {
id String @id @default(uuid())
id String @id @default(uuid())
ticketId String
scannedById String
scannedAt DateTime @default(now())
quantityRedeemed Int @default(1)
scannedAt DateTime @default(now())
quantityRedeemed Int @default(1)
// Offline scanning: the device's id for the scan (makes syncing idempotent), and
// the offline lock it was made under.
clientScanId String? @unique
offline Boolean @default(false)
clientScanId String? @unique
offline Boolean @default(false)
scanLockId String?
syncedAt DateTime?
// Multi-day events: the session this check-in counts for (null on single-date events).
sessionId String?
session EventSession? @relation(fields: [sessionId], references: [id], onDelete: Restrict)
// Ticked present by a supervisor from the attendance register, not scanned.
manual Boolean @default(false)
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Restrict)
scannedBy User @relation(fields: [scannedById], references: [id], onDelete: Restrict)
scanLock ScanLock? @relation(fields: [scanLockId], references: [id], onDelete: SetNull)
manual Boolean @default(false)
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Restrict)
scannedBy User @relation(fields: [scannedById], references: [id], onDelete: Restrict)
scanLock ScanLock? @relation(fields: [scanLockId], references: [id], onDelete: SetNull)
@@index([ticketId])
@@index([scannedAt])
@@ -718,19 +723,19 @@ model PasswordReset {
// ('login') or to prove the channel works before 2FA is switched on ('enable').
// Only the HMAC of the code is stored (see backend/src/utils/twoFactor.js).
model TwoFactorChallenge {
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
purpose String // 'login' | 'enable'
method TwoFactorMethod
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
purpose String // 'login' | 'enable'
method TwoFactorMethod
// 2.3.0: an authenticator app being set up: its secret (encrypted) until the first code confirms it.
pendingSecret String?
codeHash String
attempts Int @default(0)
lastSentAt DateTime @default(now())
expiresAt DateTime
usedAt DateTime?
createdAt DateTime @default(now())
codeHash String
attempts Int @default(0)
lastSentAt DateTime @default(now())
expiresAt DateTime
usedAt DateTime?
createdAt DateTime @default(now())
@@index([userId])
}
@@ -851,6 +856,12 @@ enum AdminAuditAction {
product_link_disconnected
feed_publish_toggled
feed_show_toggled
sign_in_move_started
sign_in_move_finished
sign_in_move_failed
sign_in_move_undone
sign_in_secrets_cleared
account_changed_in_accounts
}
// Append-only audit trail for admin/supervisor-initiated actions with money or
@@ -970,7 +981,7 @@ model FormDraft {
model ProviderTransaction {
id String @id @default(uuid())
provider String @default("yoco") // payment provider id (src/payments)
externalId String // the provider's payment/event id
externalId String // the provider's payment/event id
amount Int?
currency String?
createdDate DateTime?
@@ -995,19 +1006,19 @@ model ProviderTransaction {
// can be checked against it. Its id is the payer's link (/pay/<id>) and, for PayFast, the
// m_payment_id. `provider` is null until the payer picks one (when several are enabled).
model ProviderCheckout {
id String @id @default(uuid())
id String @id @default(uuid())
provider String?
// The provider's own checkout id (Yoco) and where it sends the payer.
externalId String?
redirectUrl String?
amountCents Int
currency String @default("ZAR")
currency String @default("ZAR")
// Who/what the payment is for: registrationId, userId, eventId, type, donationAmount, …
metadata Json
// Everything needed to start the checkout with any provider: lineItems, return URLs, payer.
request Json
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([provider, externalId])
}
@@ -1461,16 +1472,16 @@ model FeedbackField {
/// Who was asked. tokenHash is the HMAC of the link token (the token itself isn't stored).
model FeedbackInvite {
id String @id @default(uuid())
formId String
userId String
tokenHash String @unique
sentAt DateTime @default(now())
remindedAt DateTime? // the last reminder (automatic or by hand)
reminderCount Int @default(0)
respondedAt DateTime?
form FeedbackForm @relation(fields: [formId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
id String @id @default(uuid())
formId String
userId String
tokenHash String @unique
sentAt DateTime @default(now())
remindedAt DateTime? // the last reminder (automatic or by hand)
reminderCount Int @default(0)
respondedAt DateTime?
form FeedbackForm @relation(fields: [formId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@unique([formId, userId])
@@index([userId])
@@ -1603,7 +1614,7 @@ model TicketTransfer {
}
model Attendee {
id String @id @default(uuid())
id String @id @default(uuid())
registrationId String
registrationOptionId String?
eventOptionId String
@@ -1617,12 +1628,12 @@ model Attendee {
parentName String?
parentEmail String?
parentPhone String?
order Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
registration Registration @relation(fields: [registrationId], references: [id], onDelete: Cascade)
registrationOption RegistrationOption? @relation(fields: [registrationOptionId], references: [id], onDelete: SetNull)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
order Int @default(0)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
registration Registration @relation(fields: [registrationId], references: [id], onDelete: Cascade)
registrationOption RegistrationOption? @relation(fields: [registrationOptionId], references: [id], onDelete: SetNull)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
ticket Ticket?
formResponses FormResponse[]
consentRequests ConsentRequest[]
@@ -1795,23 +1806,23 @@ enum CheckInWindow {
// One date/time of a multi-day event.
model EventSession {
id String @id @default(uuid())
eventId String
label String?
startsAt DateTime
endsAt DateTime
location String?
id String @id @default(uuid())
eventId String
label String?
startsAt DateTime
endsAt DateTime
location String?
// Cancelled sessions are kept (they may have check-ins) but hidden from the schedule
// and left out of attendance totals.
cancelledAt DateTime?
order Int @default(0)
cancelledAt DateTime?
order Int @default(0)
// Optional limit on people at this session (picked places + whole-course tickets).
capacity Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
usages TicketUsage[]
reminders SessionReminderLog[]
capacity Int?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
usages TicketUsage[]
reminders SessionReminderLog[]
registrationOptions RegistrationOption[]
waitlistEntries WaitlistEntry[]
servingRoles ServingRole[]
@@ -1834,24 +1845,24 @@ model SessionReminderLog {
// A completion certificate for one ticket (one person).
model Certificate {
id String @id @default(uuid())
eventId String
ticketId String
userId String?
name String
id String @id @default(uuid())
eventId String
ticketId String
userId String?
name String
// Short code printed on the certificate and checked on the public verify page.
code String @unique
sessionsAttended Int @default(0)
totalSessions Int @default(0)
manual Boolean @default(false)
issuedById String?
issuedAt DateTime @default(now())
emailedAt DateTime?
revokedAt DateTime?
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
issuedBy User? @relation("CertificateIssuedBy", fields: [issuedById], references: [id], onDelete: SetNull)
code String @unique
sessionsAttended Int @default(0)
totalSessions Int @default(0)
manual Boolean @default(false)
issuedById String?
issuedAt DateTime @default(now())
emailedAt DateTime?
revokedAt DateTime?
event Event @relation(fields: [eventId], references: [id], onDelete: Cascade)
ticket Ticket @relation(fields: [ticketId], references: [id], onDelete: Cascade)
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
issuedBy User? @relation("CertificateIssuedBy", fields: [issuedById], references: [id], onDelete: SetNull)
@@unique([eventId, ticketId])
@@index([userId])
@@ -2187,16 +2198,16 @@ model KidsAlert {
// A leader on duty in a kids room for an occasion ("I'm on duty"), for the ratio.
model KidsRoomDuty {
id String @id @default(uuid())
roomId String
occasion String
userId String
startedAt DateTime @default(now())
endedAt DateTime?
id String @id @default(uuid())
roomId String
occasion String
userId String
startedAt DateTime @default(now())
endedAt DateTime?
// Volunteer rosters (1.46.0): started by a rostered volunteer checking in, not "I'm on duty".
fromRoster Boolean @default(false)
room AllocationGroup @relation(fields: [roomId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
fromRoster Boolean @default(false)
room AllocationGroup @relation(fields: [roomId], references: [id], onDelete: Cascade)
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@index([roomId, occasion])
@@index([userId])
@@ -2288,21 +2299,21 @@ model VolunteerSwap {
/// Outbound webhooks (1.48.0): a URL that is sent what happens here (registrations, payments,
/// check-ins, new accounts, published events), signed with its own secret.
model WebhookEndpoint {
id String @id @default(uuid())
name String
url String
id String @id @default(uuid())
name String
url String
// HMAC secret, encrypted (utils/encryption.js); shown to the admin once, when made or rotated.
secret String
secret String
// Event types it gets, e.g. ["registration.paid", "ticket.checked_in"].
events String[]
isActive Boolean @default(true)
events String[]
isActive Boolean @default(true)
// The operator register entry made for it (POPIA), if any.
operatorId String?
operatorId String?
lastSuccessAt DateTime?
lastFailureAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deliveries WebhookDelivery[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
deliveries WebhookDelivery[]
}
/// One message to one endpoint, with its retries. Kept 30 days.
@@ -2442,3 +2453,23 @@ model ImportedEvent {
@@index([linkId])
@@index([endsAt])
}
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §3): one sign-in through the church's Accounts. The callback
// makes it with a one-time handoff code (hashed, 60 seconds) that the page swaps for Events' own
// token; the token carries this row's id (`asi`), so signing out can send Accounts the ID token.
model AccountsSignIn {
id String @id @default(uuid())
userId String
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
codeHash String? @unique
codeExpires DateTime?
codeUsedAt DateTime?
returnTo String
idToken String? // encrypted (utils/encryption)
sid String?
mfa Boolean @default(false)
createdAt DateTime @default(now())
@@index([userId])
@@index([createdAt])
}
+91
View File
@@ -0,0 +1,91 @@
/**
* Accounts' signed calls to Events (`crosscode.identity/1`, 3.0.0, docs/EVENTS-3.0-PLAN.md §7):
*
* - `user.updated`: keep Events' copy of the profile and news consent current.
* - `user.export`: Events' part of "Download my data", from the same export Events' own privacy
* page gives (utils/privacy.exportUserData), as sections.
* - `user.deleted`: Events' existing rules: anonymise, keeping financial records without the name;
* `deferred` while the person has a registration for an event that hasn't ended.
*
* A call for someone Events doesn't know is answered as done: there's nothing here to change.
*/
import { IDENTITY_SCHEMA, type AccountsCall, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
import { updateLocalCopy, endEventsSessions } from './signin';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const privacy = require('../utils/privacy') as {
exportUserData(userId: string): Promise<Record<string, unknown> | null>;
deletionBlockers(userId: string): Promise<{ eventTitle: string; endDate: Date }[]>;
anonymiseUser(userId: string): Promise<unknown>;
};
/* eslint-enable @typescript-eslint/no-require-imports */
const TITLES: Record<string, string> = {
account: 'Your Cross Events details',
registrations: 'Registrations',
payments: 'Payments',
tickets: 'Tickets and check-ins',
waitlist: 'Waiting lists',
certificates: 'Certificates',
feedback: 'Feedback you gave',
consents: 'Message preferences (history)',
accountActivity: 'Sign-ins to Cross Events before the move',
dataRequests: 'Privacy requests',
notices: 'Privacy notices accepted',
kidsFamily: 'Family and children',
volunteering: 'Volunteering',
seriesFollowed: 'Series you follow',
seasonPasses: 'Season passes',
};
const sectionKey = (k: string) => k.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/[^a-z0-9_]/g, '').replace(/^[^a-z]+/, '').slice(0, 50) || 'other';
const asRecords = (v: unknown): Record<string, unknown>[] =>
(Array.isArray(v) ? v : v && typeof v === 'object' ? [v] : []).map((x) => (x && typeof x === 'object' ? (JSON.parse(JSON.stringify(x)) as Record<string, unknown>) : { value: x }));
/** Events' export as `crosscode.identity/1` sections (at most 100). */
export function exportSections(data: Record<string, unknown>) {
return Object.entries(data)
.filter(([, v]) => v !== null && v !== undefined)
.map(([k, v]) => ({ key: sectionKey(k), title: TITLES[k] ?? k, records: asRecords(v) }))
.filter((s) => s.records.length > 0)
.slice(0, 100);
}
const DEFER_HOURS = 24;
export async function handleAccountsCall(call: AccountsCall): Promise<object> {
const user = await prisma.user.findUnique({ where: { accountId: call.sub }, select: { id: true } });
switch (call.type) {
case 'user.updated': {
if (user) await updateLocalCopy(user.id, call.profile);
return { schema: IDENTITY_SCHEMA, ok: true };
}
case 'user.export': {
const data = user ? await privacy.exportUserData(user.id) : null;
const reply: UserExportReply = {
schema: IDENTITY_SCHEMA, exportId: call.exportId, sub: call.sub, product: 'events', generatedAt: new Date().toISOString(),
sections: data ? exportSections(data) : [],
};
return reply;
}
case 'user.deleted': {
if (!user) return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
const blockers = await privacy.deletionBlockers(user.id);
if (blockers.length) {
const first = blockers[0]!;
const end = new Date(Math.max(new Date(first.endDate).getTime(), Date.now()) + DEFER_HOURS * 3600e3);
const more = blockers.length > 1 ? ` and ${blockers.length - 1} more` : '';
return {
schema: IDENTITY_SCHEMA, status: 'deferred',
reason: `Has a registration for ${first.eventTitle} (${new Date(first.endDate).toISOString().slice(0, 10)})${more}`.slice(0, 500),
retryAfter: end.toISOString(),
} satisfies UserDeletedReply;
}
await endEventsSessions(user.id);
await privacy.anonymiseUser(user.id);
await prisma.user.update({ where: { id: user.id }, data: { accountId: null } }).catch(() => {});
return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
}
}
}
@@ -0,0 +1,74 @@
/**
* The church's Accounts, as this site's OIDC client (3.0.0, docs/EVENTS-3.0-PLAN.md §1): built on
* `@crosscode/auth-client` from the Accounts link that Connect made (Settings → Linked products).
* Its address is the one the Hub listed; its client id is this site's Hub install id and its client
* secret comes from the link's secret, so there's no `.env` setting for any of it.
*
* `@crosscode/auth-client` and `openid-client` are ES modules and this backend is CommonJS, which
* compiles `import()` into `require()`. The loader below keeps a real dynamic import, so it works on
* every Node the servers run (20+), not only where `require()` of ES modules is allowed.
*/
import type { AccountsClient } from '@crosscode/auth-client';
import { hubInstallId, siteUrl } from '../feed/context';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
/* eslint-enable @typescript-eslint/no-require-imports */
export type AuthClientModule = typeof import('@crosscode/auth-client');
// eslint-disable-next-line @typescript-eslint/no-implied-eval -- a real import(), see above
const importEsm = new Function('specifier', 'return import(specifier)') as (s: string) => Promise<AuthClientModule>;
let loader: () => Promise<AuthClientModule> = () => importEsm('@crosscode/auth-client');
/** Tests: use another auth-client (a fake, or the real one loaded another way). */
export function setAuthClientLoader(next: () => Promise<AuthClientModule>): void {
loader = next;
cached = null;
}
export class AccountsUnavailable extends Error {
status = 503;
code = 'ACCOUNTS_UNAVAILABLE';
}
export type AccountsLink = { installId: string; url: string; secret: string; updatedAt: Date };
/** The Accounts link, or null when Accounts isn't connected. */
export async function accountsLink(): Promise<AccountsLink | null> {
return prisma.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
}
let cached: { key: string; client: Promise<AccountsClient> } | null = null;
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
export async function accounts(): Promise<AccountsClient> {
const link = await accountsLink();
if (!link) throw new AccountsUnavailable('Accounts isn\'t connected. Connect it under Settings → Linked products.');
const [clientId, productUrl] = await Promise.all([hubInstallId(), siteUrl()]);
if (!clientId) throw new AccountsUnavailable('This site isn\'t connected to the Hub yet.');
const key = `${link.installId}|${new Date(link.updatedAt).getTime()}|${clientId}|${productUrl}`;
if (!cached || cached.key !== key) {
const client = loader().then((m) => m.accountsClient({
accountsUrl: link.url,
productUrl,
clientId,
linkSecret: decrypt(link.secret),
allowInsecure: process.env.NODE_ENV !== 'production' && link.url.startsWith('http:'),
}));
// A failed discovery (Accounts down for a moment) is tried again next time.
client.catch(() => { if (cached?.key === key) cached = null; });
cached = { key, client };
}
try {
return await cached.client;
} catch (e) {
throw new AccountsUnavailable(`Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
}
}
/** The module itself (for its error classes). */
export function authClientModule(): Promise<AuthClientModule> {
return loader();
}
+106
View File
@@ -0,0 +1,106 @@
/**
* Cross Events' own sign-in, once sign-in goes through Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §6).
* Mounted after express.json, before the API:
*
* - Signing in, signing up, passwords, activation and 2FA here answer 409 `SIGN_IN_MOVED` with
* where to go instead (the frontend forwards there).
* - While a move runs, Events' own sign-in waits (503 `SIGN_IN_MOVING`).
* - Changing my name, email or phone is done in Accounts (`PATCH /me` keeps the rest).
* - An admin changing someone's name, email or phone (`PATCH /users/:id`) changes their account in
* Accounts first (`people.update`), then Events' copy; a password or 2FA change is refused.
*/
import type { NextFunction, Request, Response } from 'express';
import { accounts, AccountsUnavailable } from './client';
import { getSetting, viaAccounts } from './mode';
import { RUNNING_KEY } from './move';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
const MOVED = [
'POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/login/code/resend', 'POST /api/v2/auth/signup',
'POST /api/v2/auth/password/forgot', 'POST /api/v2/auth/password/reset', 'POST /api/v2/auth/activate',
'POST /api/v2/me/verify-password', 'POST /api/v2/me/close',
];
const MOVED_PREFIXES = ['POST /api/v2/me/two-factor/'];
const LOCAL_SIGN_IN = ['POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/signup', 'POST /api/v2/auth/activate'];
const movedAnswer = (res: Response) => res.status(409).json({
error: {
code: 'SIGN_IN_MOVED',
message: 'Signing in, passwords and two-step sign-in are now on your church account. Use "Sign in" to continue.',
signInUrl: '/api/auth/signin',
},
});
export async function signInGuard(req: Request, res: Response, next: NextFunction) {
const key = `${req.method} ${req.path.replace(/\/+$/, '')}`;
const isMoved = MOVED.includes(key) || MOVED_PREFIXES.some((p) => key.startsWith(p));
const isMe = key === 'PATCH /api/v2/me';
const isAdminEdit = /^PATCH \/api\/v2\/users\/[^/]+$/.test(key);
if (!isMoved && !isMe && !isAdminEdit) return next();
try {
if (!(await viaAccounts())) {
if (LOCAL_SIGN_IN.includes(key)) {
const running = await getSetting(RUNNING_KEY);
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) {
return res.status(503).json({ error: { code: 'SIGN_IN_MOVING', message: 'One moment, we\'re updating the sign-in. Please try again in a minute.' } });
}
}
return next();
}
if (isMoved) return movedAnswer(res);
const body = (req.body ?? {}) as Record<string, unknown>;
if (isMe) {
if (body.password !== undefined || body.currentPassword !== undefined) return movedAnswer(res);
delete body.name;
delete body.email;
delete body.phone;
return next();
}
// An admin's change to someone (the route itself checks they're an admin).
if (body.password !== undefined || body.twoFactorEnabled !== undefined) return movedAnswer(res);
const changes: { name?: string; email?: string; phone?: string | null } = {};
if (typeof body.name === 'string') changes.name = body.name.trim();
if (typeof body.email === 'string') changes.email = body.email.trim().toLowerCase();
if (body.phoneNumber !== undefined) changes.phone = body.phoneNumber ? String(body.phoneNumber) : null;
if (!Object.keys(changes).length) return next();
const target = await prisma.user.findUnique({ where: { id: String(req.params?.id ?? req.path.split('/').pop()) }, select: { id: true, accountId: true, name: true, email: true, phoneNumber: true } });
if (!target?.accountId) return next();
const differs = (changes.name !== undefined && changes.name !== target.name) || (changes.email !== undefined && changes.email !== target.email) || (changes.phone !== undefined && changes.phone !== target.phoneNumber);
if (!differs) return next();
// Only for a signed-in admin: anyone else is refused by the route itself, untouched here.
const admin = await signedInAdmin(req);
if (!admin) return next();
await (await accounts()).request({ type: 'people.update', actor: admin.accountId, sub: target.accountId, ...changes });
return next();
} catch (e) {
if (e instanceof AccountsUnavailable) return res.status(503).json({ error: { code: 'UNAVAILABLE', message: e.message } });
const err = e as { code?: string; message: string };
if (err.code === 'EMAIL_TAKEN') return res.status(409).json({ error: { code: 'CONFLICT', message: 'Another account has that email address.' } });
if (err.code) return res.status(502).json({ error: { code: 'UNAVAILABLE', message: `Accounts didn't accept the change: ${err.message}` } });
return next(e);
}
}
/**
* The request's user when it's a valid, current admin token (as `protect` + `admin` would accept,
* not viewing as someone else), or null. Their `accountId` goes to Accounts' audit log.
*/
async function signedInAdmin(req: Request): Promise<{ id: string; accountId: string | null } | null> {
try {
const header = String(req.headers.authorization || '');
if (!header.startsWith('Bearer ')) return null;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const jwt = require('jsonwebtoken');
const decoded = jwt.verify(header.slice(7), process.env.JWT_SECRET, { algorithms: ['HS256'] }) as { id?: string; tokenVersion?: number; imp?: string; asi?: string; mfa?: boolean };
// Viewing as someone, or an Accounts sign-in without the second step admins need.
if (!decoded.id || decoded.imp || (decoded.asi && decoded.mfa !== true)) return null;
const u = await prisma.user.findUnique({ where: { id: decoded.id }, select: { id: true, accountId: true, role: true, isActive: true, tokenVersion: true } });
if (!u || !u.isActive || u.role !== 'admin' || (decoded.tokenVersion ?? 0) !== u.tokenVersion) return null;
return { id: u.id, accountId: u.accountId };
} catch {
return null;
}
}
+49
View File
@@ -0,0 +1,49 @@
/**
* Where people sign in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): `local` (Cross Events' own sign-in, as
* 2.x, before the move or after Undo) or `accounts` (through the church's Accounts). Kept in
* AppSetting `auth_mode`; read with a short cache, so every PM2 process follows a move within
* seconds. A new install starts in `accounts` (§9); everyone else starts in `local`.
*
* Other keys: `auth_moved_at` (ISO, when the move finished: Undo is allowed for 14 days, then the
* old secrets are cleared), `auth_move_report` (JSON), `auth_secrets_cleared_at` (ISO).
*/
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
export type AuthMode = 'local' | 'accounts';
export const MODE_KEY = 'auth_mode';
export const MOVED_AT_KEY = 'auth_moved_at';
export const REPORT_KEY = 'auth_move_report';
export const CLEARED_KEY = 'auth_secrets_cleared_at';
export const UNDO_DAYS = 14;
const TTL_MS = 5000;
let cache: { mode: AuthMode; at: number } | null = null;
export async function authMode(): Promise<AuthMode> {
if (cache && Date.now() - cache.at < TTL_MS) return cache.mode;
const row = await prisma.appSetting.findUnique({ where: { key: MODE_KEY } }).catch(() => null);
const mode: AuthMode = row?.value === 'accounts' ? 'accounts' : 'local';
cache = { mode, at: Date.now() };
return mode;
}
export async function viaAccounts(): Promise<boolean> {
return (await authMode()) === 'accounts';
}
export async function setSetting(key: string, value: string | null): Promise<void> {
if (value === null) await prisma.appSetting.deleteMany({ where: { key } });
else await prisma.appSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
if (key === MODE_KEY) cache = null;
}
export async function getSetting(key: string): Promise<string | null> {
return (await prisma.appSetting.findUnique({ where: { key } }))?.value ?? null;
}
/** For tests. */
export function forgetMode(): void {
cache = null;
}
+327
View File
@@ -0,0 +1,327 @@
/**
* Moving sign-in to the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §4–§5), from
* Settings → Sign-in:
*
* check() a dry run: who would be moved, linked to an existing account, skipped or refused
* move() copies everyone into Accounts (crosscode.identity-request/1, batches of 200, secrets
* sealed with the link's secret), checks Accounts holds the same people, then switches
* `auth_mode` to `accounts`. Idempotent: a failed move can be run again
* undo() back to Cross Events' own sign-in, for 14 days (the old passwords are still here)
* clearOldSecrets() after those 14 days: Events' password hashes, authenticator secrets,
* recovery codes and trusted devices go (the `accounts-secrets` job)
*
* Who moves: everyone with a real email address who isn't linked yet. Guests (`@guest.local`) and
* 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 { 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';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
const { getSettingSync } = require('../utils/settingsCache') as { getSettingSync(k: string, f?: string): string };
/* eslint-enable @typescript-eslint/no-require-imports */
export class MoveError extends Error {
constructor(message: string, public code = 'MOVE_FAILED', public status = 409) {
super(message);
}
}
/** While a move runs, Cross Events' own sign-in waits (people already signed in stay signed in). */
export const RUNNING_KEY = 'auth_move_running';
const MIN_ACCOUNTS = [1, 1, 0];
const NOT_MOVED = /@(guest\.local|deleted\.invalid|deleted\.local)$/i;
const HASH = /^(\$argon2(id|i|d)\$|\$2[aby]\$)/;
const iso = (d: Date | string | null | undefined) => (d ? new Date(d).toISOString() : null);
type Row = {
id: string; name: string; email: string; phoneNumber: string | null; password: string; role: string; isActive: boolean; createdAt: Date;
failedAttempts: number; lockUntil: Date | null; twoFactorEnabled: boolean; twoFactorMethod: string | null; totpSecret: string | null; totpLastStep: number | null;
newsEmail: boolean; newsWhatsApp: boolean; newsAskedAt: Date | null; noticeVersionAccepted: number | null; lastLoginAt: Date | null;
};
const SELECT = {
id: true, name: true, email: true, phoneNumber: true, password: true, role: true, isActive: true, createdAt: true, failedAttempts: true, lockUntil: true,
twoFactorEnabled: true, twoFactorMethod: true, totpSecret: true, totpLastStep: true, newsEmail: true, newsWhatsApp: true, newsAskedAt: true,
noticeVersionAccepted: true, lastLoginAt: true,
} as const;
/** The people who move: a real email, not linked yet. */
async function peopleToMove(): Promise<Row[]> {
const rows: Row[] = await prisma.user.findMany({ where: { accountId: null }, select: SELECT, orderBy: { createdAt: 'asc' } });
return rows.filter((u) => !NOT_MOVED.test(u.email));
}
async function skippedCount(): Promise<number> {
const rows: { email: string }[] = await prisma.user.findMany({ where: { accountId: null }, select: { email: true } });
return rows.filter((u) => NOT_MOVED.test(u.email)).length;
}
/** Accounts' notice versions are Events' + 1: its built-in notice is 1, Events' is 0 (null: never accepted). */
const toAccountsVersion = (v: number | null) => (v === null || v === undefined ? 0 : v + 1);
/** Never activated (made by staff, the link not used yet): Accounts' "choose your password" instead. */
const pendingActivation = (u: Row) => !u.isActive && !u.lastLoginAt;
async function person(u: Row, opts: { admins: Set<string>; seal: (v: string) => string; keepAccountsNotices: boolean }): Promise<ImportPerson> {
const [acceptances, consents] = await Promise.all([
prisma.noticeAcceptance.findMany({ where: { userId: u.id }, select: { version: true, createdAt: true }, orderBy: { createdAt: 'asc' }, take: 100 }),
prisma.communicationConsent.findMany({ where: { userId: u.id }, select: { channel: true, granted: true, createdAt: true }, orderBy: { createdAt: 'asc' }, take: 500 }),
]);
const totp = u.twoFactorEnabled && u.twoFactorMethod === 'authenticator' && u.totpSecret ? (() => { try { return decrypt(u.totpSecret!); } catch { return null; } })() : null;
// An authenticator whose secret can't be read moves without 2FA rather than locking them out.
const twoFactor = !u.twoFactorEnabled ? null : u.twoFactorMethod === 'authenticator' ? (totp ? 'totp' as const : null) : u.twoFactorMethod === 'whatsapp' ? 'whatsapp' as const : 'email' as const;
const phone = u.phoneNumber && phoneSchema.safeParse(u.phoneNumber).success ? u.phoneNumber : null;
return {
id: u.id,
name: (u.name || '').trim().slice(0, 200) || u.email,
email: u.email.trim().toLowerCase(),
emailVerified: !!u.lastLoginAt,
phone,
passwordHash: !pendingActivation(u) && HASH.test(u.password) ? opts.seal(u.password) : null,
twoFactor: twoFactor === 'whatsapp' && !phone ? 'email' : twoFactor,
totpSecret: totp ? opts.seal(totp) : null,
totpLastStep: totp ? u.totpLastStep ?? null : null,
failedSignIns: Math.min(1000, Math.max(0, u.failedAttempts || 0)),
lockedUntil: iso(u.lockUntil),
news: { email: !!u.newsEmail, whatsapp: !!u.newsWhatsApp },
newsAskedAt: iso(u.newsAskedAt),
noticeVersionAccepted: opts.keepAccountsNotices ? 0 : toAccountsVersion(u.noticeVersionAccepted),
noticeAcceptances: opts.keepAccountsNotices ? [] : acceptances.map((a: { version: number; createdAt: Date }) => ({ version: a.version + 1, acceptedAt: iso(a.createdAt)! })),
consentChanges: consents.filter((c: { channel: string }) => c.channel === 'email' || c.channel === 'whatsapp').map((c: { channel: 'email' | 'whatsapp'; granted: boolean; createdAt: Date }) => ({ channel: c.channel, granted: c.granted, at: iso(c.createdAt)! })),
lastSignInAt: iso(u.lastLoginAt),
status: u.isActive || pendingActivation(u) ? 'active' : 'deactivated',
admin: opts.admins.has(u.id) && u.role === 'admin',
createdAt: iso(u.createdAt)!,
};
}
/** Events' published notice versions, as Accounts numbers them. */
async function notices() {
const rows: { version: number; sections: unknown; publishedAt: Date }[] = await prisma.privacyNotice.findMany({ orderBy: { version: 'asc' }, take: 100 });
return rows.map((n) => {
const sections = Array.isArray(n.sections) ? (n.sections as { title?: string; body?: string }[]) : [];
const body = sections.map((s) => [s.title ? `${s.title}` : '', s.body ?? ''].filter(Boolean).join('\n\n')).join('\n\n').slice(0, 200_000) || 'Privacy notice';
return { version: n.version + 1, title: 'Privacy notice', body, publishedAt: iso(n.publishedAt)! };
});
}
function versionAtLeast(v: string, min: number[]) {
const parts = String(v).split('.').map((x) => parseInt(x, 10) || 0);
for (let i = 0; i < min.length; i++) {
if ((parts[i] ?? 0) !== min[i]) return (parts[i] ?? 0) > min[i]!;
}
return true;
}
const chunk = <T,>(list: T[], n: number) => Array.from({ length: Math.ceil(list.length / n) }, (_, i) => list.slice(i * n, i * n + n));
export type MoveSummary = {
mode: 'local' | 'accounts';
accountsConnected: boolean;
accountsUrl: string | null;
movedAt: string | null;
undoUntil: string | null;
secretsCleared: boolean;
running: boolean;
report: unknown;
};
export async function status(): Promise<MoveSummary> {
const [mode, link, movedAt, cleared, report, running] = await Promise.all([authMode(), accountsLink(), getSetting(MOVED_AT_KEY), getSetting(CLEARED_KEY), getSetting(REPORT_KEY), getSetting(RUNNING_KEY)]);
const undoUntil = movedAt && !cleared ? new Date(new Date(movedAt).getTime() + UNDO_DAYS * 86400e3).toISOString() : null;
return {
mode, accountsConnected: !!link, accountsUrl: link?.url ?? null, movedAt, undoUntil, secretsCleared: !!cleared,
running: !!running && Date.now() - new Date(running).getTime() < 30 * 60e3,
report: report ? JSON.parse(report) : null,
};
}
function church() {
const name = getSettingSync('org_name', '') || getSettingSync('site_name', '') || null;
const colour = getSettingSync('primary_color', '') || getSettingSync('brand_color', '');
return { name: name ? name.slice(0, 200) : null, primaryColour: /^#[0-9a-fA-F]{6}$/.test(colour) ? colour : null };
}
export type CheckResult = {
accountsVersion: string;
toMove: number;
wouldCreate: number;
wouldLink: { name: string; email: string }[];
refused: { name: string; email: string; reason: string }[];
skipped: number;
admins: { id: string; name: string; email: string }[];
noticeConflict: { accountsVersions: number[]; eventsVersions: number[] } | null;
withTwoFactor: number;
};
async function connected() {
if ((await authMode()) === 'accounts') throw new MoveError('Sign-in already goes through Accounts.', 'ALREADY_MOVED');
try {
return await accounts();
} catch (e) {
if (e instanceof AccountsUnavailable) throw new MoveError(e.message, 'ACCOUNTS_UNAVAILABLE', 503);
throw e;
}
}
/** The dry run: nothing is written, here or in Accounts. */
export async function check(): Promise<CheckResult> {
const auth = await connected();
const begin = await auth.request<{ noticesTaken: boolean; accountsNoticeVersions: number[]; accountsVersion: string }>({ type: 'import.begin', actor: null, check: true, notices: [], church: church() });
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) {
throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later. Update Accounts first.`, 'ACCOUNTS_TOO_OLD');
}
const people = await peopleToMove();
const seal = (v: string) => auth.seal(v);
const byId = new Map(people.map((p) => [p.id, p]));
const results: ImportResult[] = [];
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
const built = await Promise.all(batch.map((u) => person(u, { admins: new Set(), seal, keepAccountsNotices: false })));
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor: null, check: true, people: built });
results.push(...r.results);
}
const eventsNotices = await notices();
const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' });
return {
accountsVersion: begin.accountsVersion,
toMove: people.length,
wouldCreate: results.filter((r) => r.outcome === 'created' || r.outcome === 'updated').length,
wouldLink: results.filter((r) => r.outcome === 'linked').map((r) => who(r.id)),
refused: results.filter((r) => r.outcome === 'refused').map((r) => ({ ...who(r.id), reason: r.reason ?? '' })),
skipped: await skippedCount(),
admins: people.filter((p) => p.role === 'admin').map((p) => ({ id: p.id, name: p.name, email: p.email })),
noticeConflict: !begin.noticesTaken && eventsNotices.length ? { accountsVersions: begin.accountsNoticeVersions, eventsVersions: eventsNotices.map((n) => n.version - 1) } : null,
withTwoFactor: people.filter((p) => p.twoFactorEnabled).length,
};
}
export type MoveReport = {
movedAt: string;
by: string;
created: number;
linked: { name: string; email: string }[];
refused: { name: string; email: string; reason: string }[];
skipped: number;
accountsAdmins: { name: string; email: string }[];
notices: 'events' | 'accounts';
};
/** 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();
const running = await getSetting(RUNNING_KEY);
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) throw new MoveError('A move is already running.', 'RUNNING');
await setSetting(RUNNING_KEY, new Date().toISOString());
const audit = (action: string, metadata: object) => logAdminAction({ actorId: opts.actor.id, actorRole: opts.actor.role, action, targetType: 'setting', targetId: MODE_KEY, metadata, ip: opts.ip ?? null });
await audit('sign_in_move_started', { adminIds: opts.adminIds });
let begun = false;
try {
const eventsNotices = await notices();
const begin = await auth.request<{ noticesTaken: boolean; accountsVersion: string }>({
type: 'import.begin', actor: opts.actor.id, check: false, notices: opts.keepAccountsNotices ? [] : eventsNotices, church: church(),
});
begun = true;
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later.`, 'ACCOUNTS_TOO_OLD');
if (!begin.noticesTaken && eventsNotices.length && !opts.keepAccountsNotices) {
throw new MoveError('Accounts already has its own privacy notice. Choose which notice to keep, then move again.', 'NOTICE_CONFLICT');
}
const people = await peopleToMove();
const byId = new Map(people.map((p) => [p.id, p]));
const admins = new Set(opts.adminIds);
const results: ImportResult[] = [];
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
const built = await Promise.all(batch.map((u) => person(u, { admins, seal: (v) => auth.seal(v), keepAccountsNotices: !!opts.keepAccountsNotices })));
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor: opts.actor.id, 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 } });
}
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');
const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' });
const report: MoveReport = {
movedAt: new Date().toISOString(),
by: opts.actor.name ?? opts.actor.id,
created: results.filter((r) => r.outcome === 'created' || r.outcome === 'updated').length,
linked: results.filter((r) => r.outcome === 'linked').map((r) => who(r.id)),
refused: results.filter((r) => r.outcome === 'refused').map((r) => ({ ...who(r.id), reason: r.reason ?? '' })),
skipped: await skippedCount(),
accountsAdmins: people.filter((p) => admins.has(p.id) && p.role === 'admin').map((p) => ({ name: p.name, email: p.email })),
notices: opts.keepAccountsNotices ? 'accounts' : 'events',
};
await setSetting(REPORT_KEY, JSON.stringify(report));
await setSetting(MOVED_AT_KEY, report.movedAt);
await setSetting(CLEARED_KEY, null);
await setSetting(MODE_KEY, 'accounts');
await audit('sign_in_move_finished', { created: report.created, linked: report.linked.length, refused: report.refused.length, skipped: report.skipped });
emailReport(opts.actor.id, report).catch(() => {});
return report;
} catch (e) {
if (begun) await auth.request({ type: 'import.abort', actor: opts.actor.id }).catch(() => {});
await audit('sign_in_move_failed', { message: (e as Error).message });
if (e instanceof MoveError) throw e;
throw new MoveError(`The move stopped: ${(e as Error).message}. Nothing was switched; you can run it again.`, (e as { code?: string }).code ?? 'MOVE_FAILED', 502);
} finally {
await setSetting(RUNNING_KEY, null);
}
}
async function emailReport(actorId: string, report: MoveReport) {
const admin = await prisma.user.findUnique({ where: { id: actorId }, select: { email: true, name: true } });
if (!admin?.email || NOT_MOVED.test(admin.email)) return;
const { sendMail } = require('../utils/email') as { sendMail(m: object): Promise<void> };
const lines = [
`Hello ${admin.name || 'there'},`,
'',
`Sign-in for ${await siteUrl()} now goes through your church's Accounts.`,
'',
`Moved: ${report.created}`,
`Linked to an account they already had: ${report.linked.length}${report.linked.length ? ` (${report.linked.map((l) => l.email).join(', ')})` : ''}`,
`Not moved: ${report.refused.length}${report.refused.length ? ` (${report.refused.map((r) => `${r.email}: ${r.reason}`).join('; ')})` : ''}`,
`Guests and deleted people (stay in Cross Events only): ${report.skipped}`,
`Also Accounts admins: ${report.accountsAdmins.map((a) => a.name).join(', ') || 'nobody'}`,
'',
`You can undo this under Settings → Sign-in for ${UNDO_DAYS} days.`,
];
await sendMail({ to: admin.email, subject: 'Sign-in has moved to your church\'s Accounts', text: lines.join('\n'), html: lines.map((l) => (l ? `<p>${l.replace(/</g, '&lt;')}</p>` : '')).join('') });
}
export async function undo(actor: { id: string; role: string }, ip: string | null = null) {
const s = await status();
if (s.mode !== 'accounts') throw new MoveError('Sign-in is already in Cross Events.', 'NOT_MOVED');
if (!s.undoUntil || new Date(s.undoUntil) < new Date()) throw new MoveError(`Undo was possible for ${UNDO_DAYS} days after the move; the old passwords have been removed since.`, 'TOO_LATE');
await setSetting(MODE_KEY, 'local');
await logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'sign_in_move_undone', targetType: 'setting', targetId: MODE_KEY, metadata: { movedAt: s.movedAt }, ip });
return status();
}
/** The `accounts-secrets` job: 14 days after the move, Events stops holding passwords and 2FA secrets. */
export async function clearOldSecrets(now = new Date()) {
const [mode, movedAt, cleared] = await Promise.all([authMode(), getSetting(MOVED_AT_KEY), getSetting(CLEARED_KEY)]);
if (mode !== 'accounts' || !movedAt || cleared) return { cleared: 0 };
if (now.getTime() - new Date(movedAt).getTime() < UNDO_DAYS * 86400e3) return { cleared: 0 };
const linked: { id: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { id: true } });
const ids = linked.map((u) => u.id);
for (const id of ids) {
await prisma.user.update({ where: { id }, data: { password: `!accounts:${crypto.randomBytes(12).toString('hex')}`, totpSecret: null, totpLastStep: null } });
}
await prisma.recoveryCode.deleteMany({ where: { userId: { in: ids } } });
await prisma.trustedDevice.deleteMany({ where: { userId: { in: ids } } });
await prisma.passwordReset.updateMany({ where: { userId: { in: ids }, used: false }, data: { used: true } });
await setSetting(CLEARED_KEY, now.toISOString());
await logAdminAction({ actorId: null, actorRole: 'system', action: 'sign_in_secrets_cleared', targetType: 'setting', targetId: MODE_KEY, metadata: { people: ids.length } });
return { cleared: ids.length };
}
+25
View File
@@ -0,0 +1,25 @@
/**
* News consent lives in the church's Accounts once sign-in goes through it (3.0.0,
* docs/EVENTS-3.0-PLAN.md decision 7). An unsubscribe link or a WhatsApp STOP here turns news off
* there too (`people.newsOff`), so it's off for every product, and Accounts' next `user.updated`
* doesn't turn it back on here. Never fails the unsubscribe itself.
*/
import { accounts } from './client';
import { viaAccounts } from './mode';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
export async function newsOffInAccounts(userId: string, channels: string[]): Promise<void> {
try {
if (!(await viaAccounts())) return;
const u = await prisma.user.findUnique({ where: { id: userId }, select: { accountId: true } });
if (!u?.accountId) return;
const both = channels.includes('email') && channels.includes('whatsapp');
const channel = both ? 'all' : channels.includes('whatsapp') ? 'whatsapp' : 'email';
await (await accounts()).request({ type: 'people.newsOff', actor: null, sub: u.accountId, channel });
} catch (e) {
console.warn('[accounts] news off not passed on:', (e as Error).message);
}
}
+280
View File
@@ -0,0 +1,280 @@
/**
* Signing in through the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §3), under /api:
*
* GET /auth/signin?returnTo=…[&signup=1][&mfa=1] start: PKCE + state, a pending cookie, off to Accounts
* GET /auth/callback back from Accounts: find or link the user, then
* /auth/complete#<one-time code>
* POST /auth/handoff { code } the page swaps the code for Events' own token
* POST /auth/signout ends Events' sessions; answers Accounts' sign-out address
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
*
* Events keeps its own session (the 30-day token with `tokenVersion`), so the rest of the API is
* unchanged; only how a token is obtained changes. The token carries `asi` (this sign-in's row) and
* `mfa` (whether Accounts asked for a second step), which `protect` checks for staff roles.
*/
import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import { ACCOUNTS_CALL_PATH, OIDC_CLIENT_PATHS, safeReturnPath, type IdentityClaims } from '@crosscode/contracts';
import { siteUrl } from '../feed/context';
import { accounts, AccountsUnavailable } from './client';
import { viaAccounts } from './mode';
import { handleAccountsCall } from './calls';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { generateToken } = require('../config/auth') as { generateToken(id: string, role: string, v: number, extra?: object): string };
const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: string): string; decrypt(v: string): string };
const { requiresTwoFactor } = require('../utils/twoFactor') as { requiresTwoFactor(u: { role: string }): boolean };
const { logSecurityEvent } = require('../utils/securityEvents') as { logSecurityEvent(e: object): Promise<void> };
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: unknown): string | null };
/* eslint-enable @typescript-eslint/no-require-imports */
const PENDING_COOKIE = 'ev_signin';
const MFA_COOKIE = 'ev_signin_mfa';
const COOKIE_PATH = '/api/auth';
const PENDING_MINUTES = 10;
const HANDOFF_SECONDS = 60;
const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
function cookies(req: Request): Record<string, string> {
const out: Record<string, string> = {};
for (const part of String(req.headers.cookie || '').split(';')) {
const i = part.indexOf('=');
if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
}
return out;
}
const cookieOptions = () => ({ httpOnly: true, sameSite: 'lax' as const, secure: process.env.NODE_ENV === 'production', path: COOKIE_PATH });
/** A page of this site (absolute: in development the API and the pages are on different ports). */
async function page(path: string): Promise<string> {
return `${(await siteUrl()).replace(/\/+$/, '')}${path}`;
}
/** Where a problem page sends people: a short reason and "Try again" with the same return path. */
const problem = async (res: Response, code: string, returnTo = '/') =>
res.redirect(303, await page(`/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
/** A placeholder for `User.password` (required by the schema): never a valid hash, so never a password. */
const NO_PASSWORD = () => `!accounts:${crypto.randomBytes(12).toString('hex')}`;
type EventsUser = { id: string; name: string; email: string; role: string; tokenVersion: number; isActive: boolean; accountId: string | null; phoneNumber: string | null };
const USER_SELECT = { id: true, name: true, email: true, role: true, tokenVersion: true, isActive: true, accountId: true, phoneNumber: true } as const;
const isGuestEmail = (e: string) => /@(guest\.local|deleted\.invalid|deleted\.local)$/.test(e);
/**
* The Events user for an Accounts sign-in (§2): by `accountId`; else a user (often a guest
* record from the door) with the same **verified** email that isn't linked yet; else a new `user`.
*/
export async function userForClaims(claims: IdentityClaims): Promise<{ user: EventsUser | null; problem?: string; linked?: boolean; created?: boolean }> {
const byAccount = await prisma.user.findUnique({ where: { accountId: claims.sub }, select: USER_SELECT });
if (byAccount) return { user: byAccount };
const email = claims.email.toLowerCase();
const byEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' } }, select: USER_SELECT });
if (byEmail) {
if (byEmail.accountId) return { user: null, problem: 'EMAIL_IN_USE' };
if (!claims.email_verified) return { user: null, problem: 'EMAIL_NOT_VERIFIED' };
const linked = await prisma.user.update({ where: { id: byEmail.id }, data: { accountId: claims.sub }, select: USER_SELECT });
return { user: linked, linked: true };
}
// New to Events. Its id is the sub when that's free, as for everyone moved in.
const taken = await prisma.user.findUnique({ where: { id: claims.sub }, select: { id: true } });
const created = await prisma.user.create({
data: {
...(taken ? {} : { id: claims.sub }),
accountId: claims.sub,
name: claims.name,
email,
password: NO_PASSWORD(),
role: 'user',
newsEmail: claims.news_consent.email,
newsWhatsApp: claims.news_consent.whatsapp,
newsAskedAt: new Date(),
// Accounts' notice versions are Events' + 1 (its built-in notice is 1, Events' is 0).
noticeVersionAccepted: Math.max(0, claims.privacy_notice_version - 1),
},
select: USER_SELECT,
});
return { user: created, created: true };
}
/** Keeps Events' copy of the profile (for lists and messages) as Accounts has it. */
export async function updateLocalCopy(userId: string, profile: Pick<IdentityClaims, 'name' | 'email' | 'phone_number' | 'news_consent'> & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor'] }) {
const data: Record<string, unknown> = {
name: profile.name,
// The 2FA method, for admins' list of staff (2.3.0); Accounts' `totp` is Events' `authenticator`.
...(profile.two_factor !== undefined ? { twoFactorEnabled: profile.two_factor !== null, twoFactorMethod: profile.two_factor === 'totp' ? 'authenticator' : profile.two_factor } : {}),
newsEmail: profile.news_consent.email,
newsWhatsApp: profile.news_consent.whatsapp,
...(profile.privacy_notice_version ? { noticeVersionAccepted: Math.max(0, profile.privacy_notice_version - 1) } : {}),
};
const email = profile.email.toLowerCase();
const sameEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' }, NOT: { id: userId } }, select: { id: true } });
if (!sameEmail && !isGuestEmail(email)) data.email = email;
if (profile.phone_number) {
const samePhone = await prisma.user.findFirst({ where: { phoneNumber: profile.phone_number, NOT: { id: userId } }, select: { id: true } });
if (!samePhone) data.phoneNumber = profile.phone_number;
} else {
data.phoneNumber = null;
}
await prisma.user.update({ where: { id: userId }, data });
}
async function startSignIn(req: Request, res: Response) {
const returnTo = safeReturnPath(req.query.returnTo);
if (!(await viaAccounts())) return res.redirect(303, await page(`/login?redirect=${encodeURIComponent(returnTo)}&local=1`));
try {
const auth = await accounts();
const requireTwoFactor = req.query.mfa === '1';
const { url, cookie } = await auth.startSignIn(returnTo, {
requireTwoFactor,
signUp: req.query.signup === '1',
...(typeof req.query.email === 'string' && req.query.email.length < 200 ? { loginHint: req.query.email } : {}),
});
res.cookie(PENDING_COOKIE, cookie, { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
else res.clearCookie(MFA_COOKIE, cookieOptions());
return res.redirect(303, url);
} catch (e) {
console.warn('[accounts] sign-in could not start:', (e as Error).message);
return problem(res, e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED', returnTo);
}
}
async function callback(req: Request, res: Response) {
const jar = cookies(req);
const askedMfa = jar[MFA_COOKIE] === '1';
res.clearCookie(PENDING_COOKIE, cookieOptions());
res.clearCookie(MFA_COOKIE, cookieOptions());
// Cancelled at Accounts: back to the home page, signed out.
if (req.query.error === 'access_denied') return res.redirect(303, await page('/'));
let auth;
try {
auth = await accounts();
} catch {
return problem(res, 'ACCOUNTS_UNAVAILABLE');
}
let signed;
try {
// The address Accounts sent the browser to, as it registered it (never the backend's own port).
signed = await auth.finishSignIn(`${(await siteUrl()).replace(/\/+$/, '')}${req.originalUrl}`, jar[PENDING_COOKIE]);
} catch (e) {
const code = (e as { code?: string }).code;
console.warn('[accounts] sign-in could not finish:', (e as Error).message);
return problem(res, code === 'NO_PENDING' ? 'EXPIRED' : 'FINISH_FAILED');
}
const { claims, returnTo, idToken } = signed;
const found = await userForClaims(claims);
if (!found.user) return problem(res, found.problem ?? 'NO_USER', returnTo);
const user = found.user;
if (!user.isActive) return problem(res, 'EVENTS_OFF', returnTo);
// Staff roles need a second step (§3): ask Accounts for it once; a second miss is a problem.
const mfa = claims.amr.includes('mfa');
if (requiresTwoFactor(user) && !mfa) {
if (askedMfa) return problem(res, 'MFA_REQUIRED', returnTo);
return res.redirect(303, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`);
}
await updateLocalCopy(user.id, claims).catch((e: Error) => console.warn('[accounts] profile copy:', e.message));
await prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date(), inactivityWarnedAt: null } }).catch(() => {});
logSecurityEvent({ userId: user.id, type: 'login', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
const code = crypto.randomBytes(32).toString('base64url');
const sid = (claims as unknown as { sid?: string }).sid ?? null;
await prisma.accountsSignIn.create({
data: { userId: user.id, codeHash: hash(code), codeUsedAt: null, codeExpires: new Date(Date.now() + HANDOFF_SECONDS * 1000), returnTo, idToken: encrypt(idToken), sid, mfa },
});
return res.redirect(303, await page(`/auth/complete#${code}`));
}
async function handoff(req: Request, res: Response) {
const code = typeof req.body?.code === 'string' ? req.body.code : '';
const row = code ? await prisma.accountsSignIn.findUnique({ where: { codeHash: hash(code) } }) : null;
if (!row || row.codeUsedAt || !row.codeExpires || row.codeExpires < new Date()) {
return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
}
// Single use, whatever happens next.
const used = await prisma.accountsSignIn.updateMany({ where: { id: row.id, codeUsedAt: null }, data: { codeUsedAt: new Date(), codeHash: null } });
if (!used.count) return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
const user = await prisma.user.findUnique({ where: { id: row.userId }, select: USER_SELECT });
if (!user || !user.isActive) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Please sign in again.' } });
return res.json({
data: {
status: 'signed_in',
token: generateToken(user.id, user.role, user.tokenVersion, { asi: row.id, mfa: row.mfa }),
user: { id: user.id, name: user.name, email: user.email, role: user.role },
newsPromptPending: false,
noticePromptPending: false,
returnTo: safeReturnPath(row.returnTo),
},
});
}
/** Ends this person's Events sessions (every token they hold stops working at the next request). */
export async function endEventsSessions(userId: string) {
await prisma.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
}
async function signOut(req: Request, res: Response) {
// `protect` ran: req.user is the person; the token's `asi` finds the ID token for Accounts.
const user = (req as unknown as { user?: { id: string } }).user;
const asi = (req as unknown as { tokenClaims?: { asi?: string } }).tokenClaims?.asi;
if (!user) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Not signed in.' } });
await endEventsSessions(user.id);
let url: string | null = null;
if (await viaAccounts()) {
try {
const row = asi ? await prisma.accountsSignIn.findUnique({ where: { id: asi } }) : null;
const idToken = row?.idToken ? (() => { try { return decrypt(row.idToken); } catch { return undefined; } })() : undefined;
url = (await accounts()).signOutUrl(idToken);
} catch (e) {
console.warn('[accounts] sign-out address:', (e as Error).message);
}
}
return res.json({ data: { signedOut: true, url } });
}
async function backchannelLogout(req: Request, res: Response) {
try {
const { sub } = await (await accounts()).verifyLogoutToken(String(req.body?.logout_token ?? ''));
const user = await prisma.user.findUnique({ where: { accountId: sub }, select: { id: true } });
if (user) await endEventsSessions(user.id);
return res.status(200).end();
} catch (e) {
console.warn('[accounts] back-channel logout refused:', (e as Error).message);
return res.status(400).json({ error: 'invalid_request' });
}
}
async function accountsCall(req: Request, res: Response) {
try {
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const call = (await accounts()).verifyAccountsCall(raw, req.headers as Record<string, string | string[] | undefined>);
return res.json(await handleAccountsCall(call));
} catch (e) {
const err = e as { code?: string; message: string; status?: number };
const status = err.code === 'BAD_SIGNATURE' || err.code === 'STALE_REQUEST' ? 401 : err.code === 'INVALID_REQUEST' ? 400 : err.status ?? 500;
if (status >= 500) console.warn('[accounts] call failed:', err.message);
return res.status(status).json({ message: err.message, code: err.code ?? 'SERVER_ERROR' });
}
}
/** Mounted at /api before express.json (the Accounts calls need the exact bytes). */
export function accountsRouter(protect: express.RequestHandler) {
const r = express.Router();
const strip = (p: string) => p.replace(/^\/api/, '');
r.get('/auth/signin', startSignIn);
r.get(strip(OIDC_CLIENT_PATHS.callback), callback);
r.post('/auth/handoff', express.json({ limit: '4kb' }), handoff);
r.post('/auth/signout', express.json({ limit: '4kb' }), protect, signOut);
r.post(strip(OIDC_CLIENT_PATHS.backchannelLogout), express.urlencoded({ extended: false, limit: '16kb' }), backchannelLogout);
r.post(strip(ACCOUNTS_CALL_PATH), express.raw({ type: () => true, limit: '256kb' }), accountsCall);
return r;
}
+6
View File
@@ -138,6 +138,9 @@ app.use('/api/v2/webhooks', webhooksRouter);
// The church's other products (2.4.0): the event feed, event.changed and Connect
// (/api/feed/v1, /api/links/v1; src/links/routes.ts). Its own parsers (raw for the webhook).
app.use('/api', require('./links/routes').crossProductRouter());
// 3.0.0: signing in through the church's Accounts (/api/auth/*, Accounts' calls at
// /api/accounts/v1/events; src/accounts/signin.ts). Its own parsers (raw for Accounts' calls).
app.use('/api', require('./accounts/signin').accountsRouter(require('./middleware/authMiddleware').protect));
// Apply JSON body parser for all non-webhook routes
app.use(express.json());
@@ -146,6 +149,9 @@ app.use((req, res, next) => {
if (req.body === undefined) req.body = {};
next();
});
// 3.0.0: once sign-in goes through Accounts, Events' own sign-in, password and 2FA endpoints say
// where to go instead, and profile changes go to Accounts (src/accounts/guard.ts).
app.use((req, res, next) => { require('./accounts/guard').signInGuard(req, res, next).catch(next); });
// Count server errors (any 5xx response) for the Hub heartbeat.
app.use((req, res, next) => {
+11
View File
@@ -95,6 +95,17 @@ const JOBS = [
name: 'backup', label: 'Database backup', cron: '0 2 * * *', env: 'BACKUP_ENABLED',
run: async () => ({ file: (await require('../utils/backupUtils').runBackup()).filename }),
},
{
// 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.
name: 'accounts-secrets', label: 'Accounts: clear old passwords 14 days after the move, and old sign-in records', cron: '45 3 * * *', env: null,
run: async () => {
const { clearOldSecrets } = require('../accounts/move');
const prisma = require('../config/db');
const old = await prisma.accountsSignIn.deleteMany({ where: { createdAt: { lt: new Date(Date.now() - 40 * 24 * 3600e3) } } });
return { ...(await clearOldSecrets(new Date())), signInsRemoved: old.count };
},
},
{
name: 'temp-cleanup', label: 'Delete temp files older than 7 days', cron: '0 3 * * *', env: null,
run: async () => require('../utils/cleanupTemp').cleanupTempFiles(),
@@ -2,7 +2,7 @@ const rateLimit = require("express-rate-limit");
const jwt = require('jsonwebtoken');
const prisma = require('../config/db');
const { mustEnrolTwoFactor } = require('../utils/twoFactor');
const { mustEnrolTwoFactor, requiresTwoFactor } = require('../utils/twoFactor');
// The setup wizard's token may finish setup without 2FA for this long.
const SETUP_TOKEN_GRACE_SECONDS = 2 * 60 * 60;
@@ -71,8 +71,14 @@ const protect = async (req, res, next) => {
// requirement (or the user's promotion) is sent back to log in, where they
// enrol. The setup wizard's own token gets a short grace period.
const inSetupGrace = decoded.setup === true && Date.now() / 1000 - (decoded.iat || 0) < SETUP_TOKEN_GRACE_SECONDS;
// 3.0.0: a token from a sign-in through Accounts (`asi`) says whether Accounts asked for the
// second step (`mfa`); Events' own 2FA settings don't apply to it. A token from Events' own
// sign-in (before the move) is checked as before, so nobody is signed out by the move.
const viaAccounts = typeof decoded.asi === 'string';
const needsTwoFactor = viaAccounts ? requiresTwoFactor(req.user) && decoded.mfa !== true : await mustEnrolTwoFactor(req.user);
req.tokenClaims = decoded;
// (An impersonating admin has already passed 2FA themselves.)
if (!inSetupGrace && !req.impersonation && (await mustEnrolTwoFactor(req.user))) {
if (!inSetupGrace && !req.impersonation && needsTwoFactor) {
return res.status(401).json({
message: 'Two-factor authentication is required for your role. Please log in again to set it up.',
code: 'TWO_FACTOR_REQUIRED',
+21
View File
@@ -48,6 +48,13 @@ const frontendUrl = () => (process.env.FRONTEND_URL || process.env.APP_BASE_URL
export async function sendActivationLink(user: { id: string; name?: string | null; email?: string | null; phoneNumber?: string | null }): Promise<void> {
const hasRealEmail = !!(user?.email && !user.email.endsWith('@guest.local'));
if (!hasRealEmail && !user?.phoneNumber) return;
// 3.0.0: once sign-in goes through the church's Accounts, Accounts makes (or finds) their account
// and emails them a link to choose a password; there's no Events activation any more.
if (hasRealEmail && (await (require('../accounts/mode') as typeof import('../accounts/mode')).viaAccounts())) {
ensureAccount(user as { id: string; name?: string | null; email: string; phoneNumber?: string | null })
.catch((e: any) => console.warn('[accounts] Could not make the account:', e?.message || e));
return;
}
try {
const token = uuidv4();
const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);
@@ -81,6 +88,20 @@ export async function sendActivationLink(user: { id: string; name?: string | nul
}
}
/** Asks Accounts for this person's account (people.ensure) and links it; they can then sign in. */
export async function ensureAccount(user: { id: string; name?: string | null; email: string; phoneNumber?: string | null }): Promise<string | null> {
const { accounts } = require('../accounts/client') as typeof import('../accounts/client');
const { siteUrl } = require('../feed/context') as typeof import('../feed/context');
const { phoneSchema } = require('@crosscode/contracts') as typeof import('@crosscode/contracts');
const phone = user.phoneNumber && phoneSchema.safeParse(user.phoneNumber).success ? user.phoneNumber : null;
const r = await (await accounts()).request<{ sub: string; created: boolean }>({
type: 'people.ensure', actor: null, name: (user.name || user.email).slice(0, 200), email: user.email.toLowerCase(), phone, returnUrl: `${(await siteUrl()).replace(/\/+$/, '')}/`,
});
const other = await prisma.user.findUnique({ where: { accountId: r.sub }, select: { id: true } });
if (!other) await prisma.user.update({ where: { id: user.id }, data: { accountId: r.sub, isActive: true } });
return r.sub;
}
// Fire-and-forget: a login notice with the approximate place it came from.
async function sendLoginNotification(user: any, info: RequestInfo): Promise<void> {
try {
+5 -1
View File
@@ -156,7 +156,10 @@ async function unsubscribe(token, { channels = CHANNELS, source = 'unsubscribe_l
if (target.userId) {
const prefs = {};
for (const c of channels) if (CHANNELS.includes(c)) prefs[c] = false;
return setNewsPreferences(target.userId, prefs, { source, ip });
const state = await setNewsPreferences(target.userId, prefs, { source, ip });
// 3.0.0: off in the church's Accounts too, when sign-in goes through it.
await require('../accounts/news').newsOffInAccounts(target.userId, Object.keys(prefs));
return state;
}
await optOutAddress(target.channel, target.address, { source, ip });
return { optedOut: true };
@@ -281,6 +284,7 @@ async function whatsAppStop(rawPhone) {
const user = await prisma.user.findFirst({ where: { phoneNumber: phone }, select: { id: true } });
if (user) {
await setNewsPreferences(user.id, { whatsapp: false }, { source: 'whatsapp_stop' });
await require('../accounts/news').newsOffInAccounts(user.id, ['whatsapp']);
return 'account';
}
await optOutAddress('whatsapp', phone, { source: 'whatsapp_stop' });
@@ -123,6 +123,9 @@ async function inactiveAccounts(before, { warned, warnedBefore, limit }, db = pr
FROM "User" u
WHERE u."role" = 'user'
AND u."email" NOT LIKE '%@deleted.invalid' AND u."email" NOT LIKE '%@deleted.local'
-- 3.0.0: people who sign in through the church's Accounts are kept or removed there
-- (EVENTS-3.0-PLAN §7); Events still cleans up guests and anyone not linked.
AND u."accountId" IS NULL
) x
WHERE last_active < $1
AND ${warned === false ? '(warned_at IS NULL OR warned_at < last_active)' : 'warned_at >= last_active AND warned_at <= $2'}
+1
View File
@@ -25,6 +25,7 @@ import './resources/auth';
import './resources/ai';
import './resources/feedback';
import './resources/linkedProducts';
import './resources/signIn';
const pkg = require('../../package.json') as { version: string };
@@ -0,0 +1,197 @@
import { z } from 'zod';
import { defineRoute } from '../route';
import { ApiError, notFound } from '../errors';
import { single } from '../paging';
import { authMode } from '../../accounts/mode';
import { check, move, MoveError, status, undo } from '../../accounts/move';
import { accounts, accountsLink, AccountsUnavailable } from '../../accounts/client';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../../config/db');
const { logAdminAction } = require('../../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string | null };
/* eslint-enable @typescript-eslint/no-require-imports */
/**
* Settings → Sign-in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): where people sign in, the move to the
* church's Accounts (check, move, undo), and what an admin can do to someone's account from here
* once sign-in goes through Accounts (§6). And, for every page, where to send someone to sign in.
*/
function asApiError(e: unknown): never {
if (e instanceof MoveError) {
const code = e.status === 503 || e.status === 502 ? 'UNAVAILABLE' : 'CONFLICT';
throw new ApiError(code, e.message);
}
if (e instanceof AccountsUnavailable) throw new ApiError('UNAVAILABLE', e.message);
const err = e as { code?: string; message?: string; status?: number };
if (err?.code && typeof err.status === 'number') {
if (err.code === 'UNKNOWN_PERSON') throw new ApiError('NOT_FOUND', 'Accounts doesn\'t know this person through Cross Events yet. They need to sign in once first.');
if (err.code === 'NOT_ALLOWED') throw new ApiError('FORBIDDEN', err.message ?? 'Accounts didn\'t allow that.');
throw new ApiError('UNAVAILABLE', `Accounts didn't accept that: ${err.message}`);
}
throw e;
}
const person = z.object({ name: z.string(), email: z.string() });
const statusSchema = z.object({
mode: z.enum(['local', 'accounts']).describe('local: Cross Events\' own sign-in; accounts: through the church\'s Accounts'),
accountsConnected: z.boolean(),
accountsUrl: z.string().nullable(),
movedAt: z.string().nullable(),
undoUntil: z.string().nullable().describe('Undo is possible until then (14 days after the move)'),
secretsCleared: z.boolean().describe('The old passwords have been removed (Undo is no longer possible)'),
running: z.boolean(),
report: z.unknown().nullable(),
});
export const signInMode = defineRoute({
method: 'get',
path: '/auth/mode',
tag: 'Accounts',
summary: 'Where people sign in',
description: '`accounts`: send people to `GET /api/auth/signin?returnTo=<this page>` (the church\'s Accounts). `local`: Cross Events\' own sign-in.',
access: 'public',
response: single(z.object({
mode: z.enum(['local', 'accounts']),
signInUrl: z.string(),
accountUrl: z.string().nullable().describe('With `accounts`: the church account page (profile, password, two-step sign-in, privacy)'),
})),
async handler() {
const mode = await authMode();
const link = mode === 'accounts' ? await accountsLink() : null;
return { data: { mode, signInUrl: '/api/auth/signin', accountUrl: link ? `${link.url.replace(/\/+$/, '')}/api/self/signin?returnTo=/account` : null } };
},
});
export const signInStatus = defineRoute({
method: 'get',
path: '/settings/sign-in',
tag: 'Accounts',
summary: 'Sign-in: where it is and the move to Accounts',
access: 'admin',
response: single(statusSchema),
async handler() {
return { data: await status() };
},
});
export const signInCheck = defineRoute({
method: 'post',
path: '/settings/sign-in/check',
tag: 'Accounts',
summary: 'Check the move to Accounts (nothing changes)',
description: 'Who would move, who already has an account (they\'re linked to it), who is skipped (guests, deleted) and anything that would stop the move.',
access: 'admin',
response: single(z.object({
accountsVersion: z.string(),
toMove: z.number().int(),
wouldCreate: z.number().int(),
wouldLink: z.array(person),
refused: z.array(person.extend({ reason: z.string() })),
skipped: z.number().int(),
admins: z.array(person.extend({ id: z.string() })),
noticeConflict: z.object({ accountsVersions: z.array(z.number()), eventsVersions: z.array(z.number()) }).nullable(),
withTwoFactor: z.number().int(),
})),
async handler() {
return { data: await check().catch(asApiError) };
},
});
export const signInMove = defineRoute({
method: 'post',
path: '/settings/sign-in/move',
tag: 'Accounts',
summary: 'Move sign-in to Accounts',
description: 'Copies everyone into the church\'s Accounts with their passwords and authenticator apps, checks the count, then switches. Nothing switches if anything fails, and it can be run again. Undo for 14 days.',
access: 'admin',
body: z.object({
adminIds: z.array(z.uuid()).max(500).describe('Events admins who also become Accounts admins'),
keepAccountsNotices: z.boolean().optional().describe('When Accounts has its own privacy notice: keep it (everyone accepts it at their next sign-in) instead of Events\''),
}),
response: single(statusSchema),
async handler({ body, user, req }) {
const me = await prisma.user.findUnique({ where: { id: user!.id }, select: { name: true } });
await move({ actor: { id: user!.id, role: user!.role, name: me?.name }, adminIds: body.adminIds, keepAccountsNotices: body.keepAccountsNotices, ip: getClientIp(req) }).catch(asApiError);
return { data: await status() };
},
});
export const signInUndo = defineRoute({
method: 'post',
path: '/settings/sign-in/undo',
tag: 'Accounts',
summary: 'Undo the move (back to Cross Events\' own sign-in)',
description: 'Within 14 days of the move. People sign in with the password they had at the move; changes made in Accounts since then don\'t come back here.',
access: 'admin',
response: single(statusSchema),
async handler({ user, req }) {
return { data: await undo({ id: user!.id, role: user!.role }, getClientIp(req)).catch(asApiError) };
},
});
// ─── An admin, for someone's account (sign-in through Accounts) ─────────────
const idParams = z.object({ id: z.uuid() });
async function targetFor(id: string) {
const u = await prisma.user.findUnique({ where: { id }, select: { id: true, accountId: true, name: true } });
if (!u) throw notFound('That person');
if (!u.accountId) throw new ApiError('CONFLICT', `${u.name} doesn't sign in through the church's account yet.`);
return u as { id: string; accountId: string; name: string };
}
async function forAccount(id: string, admin: { id: string; role: string }, req: unknown, what: 'people.resetTwoFactor' | 'people.unlock' | 'people.setActive', extra: object = {}) {
if ((await authMode()) !== 'accounts') throw new ApiError('CONFLICT', 'Sign-in is still in Cross Events: use the account\'s own settings here.');
const target = await targetFor(id);
const actor = (await prisma.user.findUnique({ where: { id: admin.id }, select: { accountId: true } }))?.accountId ?? null;
await (await accounts().catch(asApiError)).request({ type: what, actor, sub: target.accountId, ...extra } as never).catch(asApiError);
await logAdminAction({ actorId: admin.id, actorRole: admin.role, action: 'account_changed_in_accounts', targetType: 'user', targetId: target.id, metadata: { request: what, ...extra }, ip: getClientIp(req) });
return { data: { ok: true as const } };
}
const ok = single(z.object({ ok: z.literal(true) }));
export const accountResetTwoFactor = defineRoute({
method: 'post',
path: '/users/:id/account/reset-two-factor',
tag: 'Accounts',
summary: 'Reset someone\'s two-step sign-in (in Accounts)',
description: 'They set it up again at their next sign-in, and are signed out everywhere.',
access: 'admin',
params: idParams,
response: ok,
async handler({ params, user, req }) {
return forAccount(params.id, user!, req, 'people.resetTwoFactor');
},
});
export const accountUnlock = defineRoute({
method: 'post',
path: '/users/:id/account/unlock',
tag: 'Accounts',
summary: 'Unlock someone after too many wrong passwords (in Accounts)',
access: 'admin',
params: idParams,
response: ok,
async handler({ params, user, req }) {
return forAccount(params.id, user!, req, 'people.unlock');
},
});
export const accountSetActive = defineRoute({
method: 'post',
path: '/users/:id/account/active',
tag: 'Accounts',
summary: 'Turn someone\'s church account off or on everywhere (in Accounts)',
description: 'Off signs them out of every product of the church. To only stop them using Cross Events, deactivate them here instead.',
access: 'admin',
params: idParams,
body: z.object({ active: z.boolean() }),
response: ok,
async handler({ params, body, user, req }) {
return forAccount(params.id, user!, req, 'people.setActive', { active: body.active });
},
});
@@ -0,0 +1,241 @@
// Cross Events 3.0 against the real Accounts (docs/EVENTS-3.0-PLAN.md §12): Events' own code (the
// move, sign-in, sign-out, Accounts' calls) talking to the whole Accounts app on real ports, each with
// an in-memory database. Run with `npm run test:accounts` (node:test through tsx, not Jest: Accounts
// is ES modules).
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
import { createRequire } from 'node:module';
import { after, before, describe, test } from 'node:test';
import bcrypt from 'bcryptjs';
import express from 'express';
import jwt from 'jsonwebtoken';
import { ed25519PublicToPem, generateEd25519, newLinkSecret } from '@crosscode/contracts/signing';
import { Browser, startHarness, ACCOUNTS_ID, type Harness } from '../../../../accounts/backend/tests/support/harness.ts';
import { memoryDb } from '../../../../accounts/backend/tests/support/memoryDb.ts';
import { codeAt, generateSecret } from '../../../../accounts/backend/src/lib/totp.ts';
import { runDue } from '../../../../accounts/backend/src/links/deliveries.ts';
import { signOutEverywhere } from '../../../../accounts/backend/src/oidc/sessions.ts';
import { profileChanged } from '../../../../accounts/backend/src/accounts/service.ts';
const require = createRequire(import.meta.url);
process.env.NODE_ENV = 'test';
process.env.JWT_SECRET = 'an-events-test-secret-long-enough-for-the-encryption-key';
// Events' database: the in-memory stand-in, with Prisma's `{ increment }` for tokenVersion.
const raw = memoryDb();
const eventsDb = new Proxy(raw, {
get(target, prop: string) {
const model = (target as unknown as Record<string, Record<string, (...a: unknown[]) => Promise<unknown>>>)[prop];
if (prop !== 'user') return model;
return new Proxy(model, {
get(m, op: string) {
if (op !== 'update') return m[op];
return async (args: { where: Record<string, unknown>; data: Record<string, unknown>; select?: Record<string, boolean> }) => {
const inc = args.data.tokenVersion as { increment?: number } | undefined;
if (inc && typeof inc === 'object' && 'increment' in inc) {
const cur = (await m.findUnique!({ where: args.where })) as { tokenVersion: number };
args = { ...args, data: { ...args.data, tokenVersion: cur.tokenVersion + inc.increment! } };
}
return m.update!(args);
};
},
});
},
});
const dbPath = require.resolve('../../src/config/db.js');
require.cache[dbPath] = { id: dbPath, filename: dbPath, loaded: true, exports: eventsDb } as never;
const { encrypt } = require('../../src/utils/encryption.js');
const { accountsRouter } = require('../../src/accounts/signin.ts');
const { signInGuard } = require('../../src/accounts/guard.ts');
const { protect } = require('../../src/middleware/authMiddleware.js');
const move = require('../../src/accounts/move.ts');
const mode = require('../../src/accounts/mode.ts');
const { setAuthClientLoader } = require('../../src/accounts/client.ts');
const EVENTS_ID = '6d1f0b2c-8a3e-4c5d-9e7f-1a2b3c4d5e6f';
let h: Harness;
let eventsUrl: string;
let server: http.Server;
const totpSecret = generateSecret();
const ids = { thandi: crypto.randomUUID(), sam: crypto.randomUUID(), lerato: crypto.randomUUID(), guest: crypto.randomUUID(), sipho: crypto.randomUUID() };
async function eventsUser(data: Record<string, unknown>) {
return eventsDb.user.create({
data: {
accountId: null, role: 'user', isActive: true, tokenVersion: 0, phoneNumber: null, failedAttempts: 0, lockUntil: null, twoFactorEnabled: false, twoFactorMethod: null,
totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: new Date(), noticeVersionAccepted: 0, lastLoginAt: new Date('2026-10-01'),
notificationPreference: 'email', inactivityWarnedAt: null, ...data,
},
});
}
before(async () => {
h = await startHarness();
setAuthClientLoader(() => import('@crosscode/auth-client'));
// Events on a real port: the sign-in routes, the guard, and one page that needs signing in.
const app = express();
app.use('/api', accountsRouter(protect));
app.use(express.json());
app.use((req, res, next) => { signInGuard(req, res, next).catch(next); });
app.get('/api/v2/me', protect, (req, res) => res.json({ data: { id: (req as unknown as { user: { id: string } }).user.id } }));
app.post('/api/v2/auth/login', (_req, res) => res.json({ data: { status: 'local' } }));
server = http.createServer(app);
await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()));
eventsUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
process.env.FRONTEND_URL = eventsUrl;
// Connect (as Linked products would): the same secret on both sides.
const secret = newLinkSecret();
await h.db.productLink.create({ data: { installId: EVENTS_ID, product: 'events', url: eventsUrl, publicKey: ed25519PublicToPem(generateEd25519().publicKey), secret: h.ctx.secrets.encrypt(secret), connectedAt: new Date() } });
await eventsDb.productLink.create({ data: { installId: ACCOUNTS_ID, product: 'accounts', url: h.publicUrl, publicKey: 'x', secret: encrypt(secret), connectedAt: new Date(), updatedAt: new Date() } });
await eventsDb.appSetting.create({ data: { key: 'hub_install_id', value: EVENTS_ID } });
// Events' people before the move.
await eventsUser({ id: ids.thandi, name: 'Thandi Mokoena', email: 'thandi@hope.test', password: await bcrypt.hash('Old-events-pass1', 4), newsEmail: true });
await eventsUser({ id: ids.sam, name: 'Sam Admin', email: 'sam@hope.test', role: 'admin', password: await bcrypt.hash('Admin-pass-123', 4), twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: encrypt(totpSecret), totpLastStep: 1 });
await eventsUser({ id: ids.lerato, name: 'Lerato', email: 'lerato@hope.test', password: await bcrypt.hash('Events-pass-99', 4) });
await eventsUser({ id: ids.sipho, name: 'Sipho Supervisor', email: 'sipho@hope.test', role: 'supervisor', password: await bcrypt.hash('Sipho-pass-123', 4) });
await eventsUser({ id: ids.guest, name: 'Door Guest', email: 'guest+ab12cd34@guest.local', password: 'x' });
// Lerato already made a church account (e.g. on the website) with another password.
await h.makeAccount({ email: 'lerato@hope.test', password: 'Accounts-pass-1', name: 'Lerato M' });
});
after(async () => {
await new Promise((r) => server.close(r));
await h.close();
});
/** Signs in through Events: Events → Accounts → Events' callback → /auth/complete#code → handoff. */
async function signInThroughEvents(browser: Browser, email: string, password: string, returnTo: string, opts: { totp?: string } = {}) {
const start = `${eventsUrl}/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}`;
const toComplete = (u: URL) => u.host === new URL(eventsUrl).host && (u.pathname === '/auth/complete' || u.pathname === '/auth/problem');
let at = await browser.follow(start, (u) => u.pathname === '/signin' || toComplete(u));
const steps: Record<string, unknown>[] = [];
for (let i = 0; i < 4 && at.url.pathname === '/signin'; i++) {
const uid = at.url.searchParams.get('uid')!;
let step = await h.api(browser, 'GET', `/api/v2/interaction/${uid}/state`);
if (step.body.stage === 'password') step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email, password });
if (step.body.stage === 'two_factor') step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor`, { code: codeAt(opts.totp!, Math.floor(Date.now() / 30000)) });
steps.push(step.body);
assert.equal(step.body.stage, 'done', JSON.stringify(step.body));
at = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/signin' || toComplete(u));
}
if (at.url.pathname === '/auth/problem') return { problem: at.url.searchParams.get('code'), steps };
const code = at.url.hash.slice(1);
const res = await fetch(`${eventsUrl}/api/auth/handoff`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code }) });
const body = (await res.json()) as { data: { token: string; returnTo: string; user: { id: string } } };
return { ...body.data, code, steps };
}
const me = (token: string) => fetch(`${eventsUrl}/api/v2/me`, { headers: { authorization: `Bearer ${token}` } });
describe('moving Events\' sign-in to Accounts', () => {
test('the check counts people and writes nothing', async () => {
const r = await move.check();
assert.equal(r.toMove, 4, 'the guest stays');
assert.equal(r.skipped, 1);
assert.equal(r.wouldCreate, 3);
assert.deepEqual(r.wouldLink.map((l: { email: string }) => l.email), ['lerato@hope.test']);
assert.deepEqual(r.admins.map((a: { id: string }) => a.id), [ids.sam]);
assert.equal(await h.db.account.findUnique({ where: { id: ids.thandi } }), null);
assert.equal(await mode.authMode(), 'local');
});
test('the move copies everyone, links Lerato to her account, and switches', async () => {
const report = await move.move({ actor: { id: ids.sam, role: 'admin', name: 'Sam Admin' }, adminIds: [ids.sam] });
assert.equal(report.created, 3);
assert.equal(report.linked.length, 1);
mode.forgetMode();
assert.equal(await mode.authMode(), 'accounts');
const thandi = await eventsDb.user.findUnique({ where: { id: ids.thandi } }) as { accountId: string };
assert.equal(thandi.accountId, ids.thandi, 'sub = Events id');
const lerato = await eventsDb.user.findUnique({ where: { id: ids.lerato } }) as { accountId: string };
const account = await h.db.account.findUnique({ where: { email: 'lerato@hope.test' } }) as { id: string };
assert.equal(lerato.accountId, account.id, 'linked to the account she had');
assert.equal((await eventsDb.user.findUnique({ where: { id: ids.guest } }) as { accountId: string | null }).accountId, null);
assert.equal((await h.db.account.findUnique({ where: { id: ids.sam } }) as { role: string }).role, 'admin');
});
});
describe('signing in through Events after the move', () => {
test('Thandi signs in with her old Events password and lands on the page she started from', async () => {
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/events/youth-camp/register?ticket=adult');
assert.ok('token' in r && r.token, JSON.stringify(r));
assert.equal(r.returnTo, '/events/youth-camp/register?ticket=adult');
assert.equal(r.user.id, ids.thandi);
assert.equal((await me(r.token)).status, 200);
// The code is single use.
const again = await fetch(`${eventsUrl}/api/auth/handoff`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: r.code }) });
assert.equal(again.status, 400);
});
test('a foreign return address lands on the home page instead', async () => {
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '//evil.test/steal');
assert.ok('returnTo' in r);
assert.equal(r.returnTo, '/');
});
test('the admin signs in with the old authenticator app, gets new recovery codes, and the token says mfa', async () => {
const r = await signInThroughEvents(new Browser(), 'sam@hope.test', 'Admin-pass-123', '/dashboard/admin', { totp: totpSecret });
assert.ok('token' in r && r.token, JSON.stringify(r));
assert.equal((r.steps[0]!.recoveryCodes as string[]).length, 10);
assert.equal((jwt.decode(r.token) as { mfa: boolean }).mfa, true);
assert.equal((await me(r.token)).status, 200);
});
test('a supervisor without 2FA is sent back to Accounts to set it up', async () => {
const browser = new Browser();
const start = `${eventsUrl}/api/auth/signin?returnTo=/dashboard`;
let at = await browser.follow(start, (u) => u.pathname === '/signin');
const uid = at.url.searchParams.get('uid')!;
const step = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'sipho@hope.test', password: 'Sipho-pass-123' });
assert.equal(step.body.stage, 'done');
at = await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/signin' || u.pathname === '/auth/complete');
assert.equal(at.url.pathname, '/signin', 'back at Accounts for the second step');
const state = await h.api(browser, 'GET', `/api/v2/interaction/${at.url.searchParams.get('uid')}/state`);
assert.equal(state.body.stage, 'setup_two_factor');
});
test('Events\' own sign-in now says where to go', async () => {
const res = await fetch(`${eventsUrl}/api/v2/auth/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
assert.equal(res.status, 409);
assert.equal(((await res.json()) as { error: { code: string } }).error.code, 'SIGN_IN_MOVED');
});
});
describe('signing out, and Accounts\' calls', () => {
test('signing out of Events ends the session here and gives Accounts\' sign-out address', async () => {
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/');
assert.ok('token' in r);
const out = await fetch(`${eventsUrl}/api/auth/signout`, { method: 'POST', headers: { authorization: `Bearer ${r.token}`, 'content-type': 'application/json' }, body: '{}' });
const body = (await out.json()) as { data: { url: string } };
assert.match(body.data.url, new RegExp(`^${h.publicUrl}/api/oidc/session/end`));
assert.equal((await me(r.token)).status, 401);
});
test('signing out everywhere in Accounts ends the Events session (back-channel logout)', async () => {
const r = await signInThroughEvents(new Browser(), 'thandi@hope.test', 'Old-events-pass1', '/');
assert.ok('token' in r);
assert.equal((await me(r.token)).status, 200);
await signOutEverywhere(h.ctx, h.provider, ids.thandi);
assert.equal((await me(r.token)).status, 401);
});
test('a name changed in Accounts reaches Events (user.updated)', async () => {
await h.db.account.update({ where: { id: ids.thandi }, data: { name: 'Thandi M. Mokoena' } });
await profileChanged(h.ctx, ids.thandi);
await runDue(h.ctx);
assert.equal((await eventsDb.user.findUnique({ where: { id: ids.thandi } }) as { name: string }).name, 'Thandi M. Mokoena');
});
test('Undo goes back to Events\' own sign-in', async () => {
await move.undo({ id: ids.sam, role: 'admin' });
mode.forgetMode();
assert.equal(await mode.authMode(), 'local');
const res = await fetch(`${eventsUrl}/api/v2/auth/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });
assert.equal(res.status, 200);
});
});
@@ -0,0 +1,71 @@
// 3.0.0 (docs/EVENTS-3.0-PLAN.md §7): Accounts' user.export and user.deleted calls, answered with
// Events' existing export and deletion rules. The sign-in itself, the move and the other calls run
// against the real Accounts in tests/accounts-integration (npm run test:accounts).
const mockUsers = new Map<string, { id: string; accountId: string | null; tokenVersion: number }>();
const mockAnonymised: string[] = [];
let mockBlockers: { eventTitle: string; endDate: Date }[] = [];
jest.mock('../src/config/db', () => ({
user: {
findUnique: async ({ where }: { where: { accountId?: string; id?: string } }) =>
[...mockUsers.values()].find((u) => (where.accountId ? u.accountId === where.accountId : u.id === where.id)) ?? null,
update: async ({ where, data }: { where: { id: string }; data: Record<string, unknown> }) => {
const u = mockUsers.get(where.id)!;
if (data.tokenVersion && typeof data.tokenVersion === 'object') u.tokenVersion += 1;
if ('accountId' in data) u.accountId = data.accountId as string | null;
return u;
},
},
}));
jest.mock('../src/utils/privacy', () => ({
exportUserData: async (id: string) => ({ account: { id, name: 'Thandi' }, registrations: [{ event: 'Youth Camp' }], payments: [], seasonPasses: [] }),
deletionBlockers: async () => mockBlockers,
anonymiseUser: async (id: string) => { mockAnonymised.push(id); },
}));
import { IDENTITY_SCHEMA, userDeletedReplySchema, userExportReplySchema } from '@crosscode/contracts';
import { exportSections, handleAccountsCall } from '../src/accounts/calls';
const SUB = '5f0c7d2a-3b1e-4c8f-9a6d-2e4b1c7f8a90';
const base = { schema: IDENTITY_SCHEMA, callId: '0b6e1f2a-3c4d-4e5f-8a9b-0c1d2e3f4a5b', occurredAt: '2026-11-20T10:00:00.000Z', sub: SUB } as const;
beforeEach(() => {
mockUsers.clear();
mockUsers.set('u1', { id: 'u1', accountId: SUB, tokenVersion: 0 });
mockAnonymised.length = 0;
mockBlockers = [];
});
test('user.export answers with Events\' export as sections, empty ones left out', async () => {
const reply = await handleAccountsCall({ ...base, type: 'user.export', exportId: '1c7f2a3b-4d5e-4f6a-9b0c-1d2e3f4a5b6c' });
expect(userExportReplySchema.safeParse(reply).success).toBe(true);
const sections = (reply as { sections: { key: string; title: string }[] }).sections;
expect(sections.map((s) => s.key)).toEqual(['account', 'registrations']);
expect(sections[1]!.title).toBe('Registrations');
});
test('section keys fit the contract', () => {
expect(exportSections({ seasonPasses: [{}], kidsFamily: { a: 1 } }).map((s) => s.key)).toEqual(['season_passes', 'kids_family']);
});
test('user.deleted waits while there is a registration for an event that has not ended', async () => {
mockBlockers = [{ eventTitle: 'Youth Camp', endDate: new Date('2027-03-14T12:00:00Z') }];
const reply = await handleAccountsCall({ ...base, type: 'user.deleted', approvedAt: base.occurredAt });
expect(userDeletedReplySchema.parse(reply)).toMatchObject({ status: 'deferred', reason: 'Has a registration for Youth Camp (2027-03-14)' });
expect(new Date((reply as { retryAfter: string }).retryAfter).getTime()).toBeGreaterThan(new Date('2027-03-14T12:00:00Z').getTime());
expect(mockAnonymised).toEqual([]);
});
test('user.deleted anonymises, signs them out here and unlinks the account', async () => {
const reply = await handleAccountsCall({ ...base, type: 'user.deleted', approvedAt: base.occurredAt });
expect(reply).toEqual({ schema: IDENTITY_SCHEMA, status: 'deleted' });
expect(mockAnonymised).toEqual(['u1']);
expect(mockUsers.get('u1')).toMatchObject({ accountId: null, tokenVersion: 1 });
});
test('a call for someone Events doesn\'t know is answered as done', async () => {
const other = { ...base, sub: '8d2e4f6a-1b3c-4d5e-8f7a-9b0c1d2e3f4a' };
expect(await handleAccountsCall({ ...other, type: 'user.deleted', approvedAt: base.occurredAt })).toEqual({ schema: IDENTITY_SCHEMA, status: 'deleted' });
const exp = await handleAccountsCall({ ...other, type: 'user.export', exportId: '1c7f2a3b-4d5e-4f6a-9b0c-1d2e3f4a5b6c' });
expect((exp as { sections: unknown[] }).sections).toEqual([]);
});