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
+16
View File
@@ -2,6 +2,22 @@
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
## events@3.0.0, accounts@1.1.0, contracts@1.8.0 - unreleased
Cross Events signs in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md).
Built on `feat/events-3.0`; not tagged until the VM test and a run on real Postgres.
- **Contracts 1.8.0:** `crosscode.identity-request/1` (product → Accounts at
`/api/accounts/v1/requests`): `import.begin` / `batch` / `finish` / `abort` and `people.*`;
`sealLinkValue` / `openLinkValue` and `importIdsHash` in `/signing`.
- **Accounts 1.1.0:** takes the requests: moves Events' users in with their password hashes and
authenticator secrets, new recovery codes after the first 2FA sign-in, `people.*` for people a
product knows, `screen=signup`. Details in `apps/accounts/CHANGELOG.md`.
- **`@crosscode/auth-client` 1.1.0:** `request()`, `seal()`, `startSignIn(…, { signUp })`.
- **Events 3.0.0:** Settings → Sign-in (check, move, undo), sign-in and sign-out through Accounts,
Accounts' calls, admin actions through Accounts. Details in `apps/events/CHANGELOG.md` and
`apps/events/MIGRATING-TO-3.md`.
## events@2.4.1, contracts@1.7.0, agent@1.2.0, crosscode script - 2026-11-19
Demo data from the Hub, for installs marked as demo sites (Hub 2.4.0).
+51
View File
@@ -5,6 +5,57 @@ All notable changes to this project are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project follows [Semantic Versioning](https://semver.org/).
## [3.0.0] - unreleased
Sign-in through the church's Accounts (ROADMAP-v3 phase 4, docs/EVENTS-3.0-PLAN.md). Requires
Accounts 1.1.0 (`— requires accounts 1.1.0` in WHATS-NEW.md) and contracts 1.8.0. Nothing changes
for people until an admin moves sign-in; see MIGRATING-TO-3.md.
### Added
- **Settings → Sign-in** (`/api/v2/settings/sign-in`, `…/check`, `…/move`, `…/undo`): Check (a dry
run in Accounts: who moves, who is linked to an account they already have, who is refused or
skipped), Move and Undo (14 days). The move sends everyone with a real email address to Accounts
(`crosscode.identity-request/1`, batches of 200, password hashes and authenticator secrets sealed
with the link's secret), checks Accounts holds the same people (count and hash of the subs), and
only then switches `auth_mode` to `accounts`. A move that fails switches nothing and can be run
again. The admin who ran it gets the report by email; it's in the audit log.
- **Signing in through Accounts** (`src/accounts/`): `GET /api/auth/signin?returnTo=` (PKCE, the
state carries the page), `GET /api/auth/callback` (finds the user by `accountId`, links a guest or
unlinked user with the same verified email, or makes a new `user`; keeps Events' copy of the
profile, news consent and 2FA method), then `/auth/complete#<one-time code>`, which the page swaps
for Events' own token at `POST /api/auth/handoff` (60 seconds, single use). Staff roles that need
2FA are sent straight back with `acr_values=mfa` when Accounts didn't ask for it. The token carries
`asi` (the sign-in) and `mfa`, which `protect` checks for staff roles; tokens from before the move
keep working under the old rules.
- **Signing out** (`POST /api/auth/signout`) ends Events' sessions and sends the browser to Accounts'
sign-out, which signs out of every product; **back-channel logout** from Accounts
(`/api/auth/backchannel-logout`) ends that person's Events sessions.
- **Accounts' calls** at `/api/accounts/v1/events`: `user.updated` (the local copy), `user.export`
(Events' export as sections), `user.deleted` (anonymise, or `deferred` while there's a registration
for an event that hasn't ended).
- **Admin, through Accounts:** `/api/v2/users/:id/account/reset-two-factor`, `…/unlock`, `…/active`;
changing someone's name, email or phone (`PATCH /users/:id`) changes their account first. People
staff add (ticket transfers, registrations at the door) get their account from Accounts
(`people.ensure`, a "choose your password" email) instead of an Events activation link.
- `GET /api/v2/auth/mode` (public): `local` or `accounts`, and the church account page.
- `User.accountId` (decision 1), `AccountsSignIn`, six audit actions; the `accounts-secrets` job
clears Events' passwords, authenticator secrets, recovery codes and trusted devices 14 days after
the move, and sign-in records after 40 days.
- `npm run test:accounts` (backend): Events' sign-in and move against the real Accounts app.
### Changed
- With sign-in through Accounts: `/login`, `/register` and `/forgot-password` forward there (every
`/login?redirect=` link keeps working); old reset and activation links say sign-in has moved; Events'
own sign-in, password, 2FA and close-account endpoints answer `409 SIGN_IN_MOVED`; Profile shows the
details read-only and links to the church account for password, 2FA and closing the account; the
privacy centre links there for news, "download my data" and deletion. An unsubscribe link or a
WhatsApp STOP turns news off in Accounts too (`people.newsOff`).
- `useRequireAuth` sends people to `/login?redirect=<this page>`, so they come back to it.
- The inactive-account retention rule skips people linked to Accounts (Accounts keeps or removes
them).
## [2.4.1] - 2026-11-19
### Fixed
+59
View File
@@ -0,0 +1,59 @@
# Moving to Cross Events 3.0
Cross Events 3.0 can sign people in with the **church's account** (Accounts), the one they'll use
for the church website and app too. It's a major version because it needs Accounts 1.1.0 or later
next to it. **Updating to 3.0 changes nothing for anyone**: people keep signing in with their Cross
Events password until an admin moves sign-in (step 4). The plan behind it is
[docs/EVENTS-3.0-PLAN.md](../../docs/EVENTS-3.0-PLAN.md).
## For whoever runs the server
1. **Accounts first.** The church needs Accounts 1.1.0 or later on the same server: in the Hub,
New install → Accounts for this church (an `add-product` job), or update its Accounts. The Hub
won't offer the Events 3.0 update before that (`requires accounts 1.1.0`), and `crosscode deploy`
refuses it too.
2. **Connect them.** In Cross Events, Site settings → Linked products → Accounts → **Connect**. This
also registers Events as a sign-in client of Accounts; nothing else is typed in.
3. **Update Events to 3.0** as usual (scheduled update from the Hub). There's one migration
(`User.accountId`, `AccountsSignIn`, six audit actions) and no new `.env` variable.
4. **Move sign-in** when the church is ready (below).
## For the church's admin: moving sign-in
Site settings → **Sign-in**:
1. **Check the move.** Nothing changes. It lists how many people move, who already has a church
account (they're linked to it and keep that account's password), anyone who can't move and why,
and the guests and deleted people who stay in Cross Events only.
2. Tick which Cross Events admins should also be **Accounts admins** (they can manage everyone's
sign-in). By default every admin is ticked.
3. **Move sign-in to Accounts** at a quiet time (not the evening before a big event's registration
closes). It takes about a minute. People already signed in stay signed in.
What people notice afterwards:
- "Sign in" opens the church's sign-in page (with the church's name and colours) and comes back to
the page they were on.
- **Same password, same authenticator app.** People with two-step sign-in get 10 new recovery codes
after their first sign-in (the old ones can't move); they should save them.
- Supervisors and admins still need two-step sign-in; Accounts asks them to set it up if they don't
have it.
- Password, two-step sign-in, news choices, "download my data" and deleting an account are on the
church account (Profile and Privacy link there).
**Undo** (same page) goes back to Cross Events' own sign-in for 14 days. People then sign in with
the password they had at the move; anything changed in Accounts since (a new password, two-step
sign-in set up) doesn't come back. After 14 days Cross Events removes the old passwords and Undo
goes away.
## For integrations
- `POST /api/v2/auth/login`, `…/login/code`, `…/signup`, `…/password/forgot`, `…/password/reset`,
`…/activate`, `/me/two-factor/*`, `/me/verify-password` and `/me/close` answer **`409`** with
`{ "error": { "code": "SIGN_IN_MOVED", "signInUrl": "/api/auth/signin" } }` once sign-in has moved.
A script that signed in with a password needs another way in (ask Cross Code).
- `GET /api/v2/auth/mode` says `local` or `accounts`.
- Tokens are the same as before (`Authorization: Bearer …`, 30 days, ended by signing out). A token
from a sign-in through Accounts also carries `asi` and `mfa`.
- `PATCH /api/v2/me` ignores `name`, `email` and `phone` (they're changed in Accounts) and refuses a
password.
+14
View File
@@ -12,6 +12,20 @@ Write for church admins, not developers: no environment variables, endpoints or
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
-->
## 3.0.0 — requires accounts 1.1.0
- **One sign-in for all your church's sites and apps.** People can now sign in to Cross Events with
their church account, the same one they'll use for the church website and app. Nothing changes
until an admin chooses **Move sign-in to Accounts** under Site settings → Sign-in.
- **Nobody has to reset anything.** Everyone keeps their password and their authenticator app.
People who use two-step sign-in get new recovery codes the first time they sign in.
- After signing in, people come back to exactly the page they were on, such as an event's
registration form.
- Passwords, two-step sign-in, news choices, "download my data" and deleting an account are on the
church account from then on, for all the church's sites at once.
- Admins can still reset someone's two-step sign-in or unlock them from the People page.
- Changed your mind? **Undo** goes back to Cross Events' own sign-in for 14 days after the move.
## 2.4.1
- Until you upload your own logo (Site settings → Branding), the site now shows the Cross Code
+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([]);
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events-frontend",
"version": "2.4.1",
"version": "3.0.0",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,4 +1,5 @@
"use client";
import { AccountsGate } from "@/components/auth/AccountsGate";
import { useState } from "react";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
@@ -6,7 +7,7 @@ import { KeyRound } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { apiV2Data } from "@/lib/apiV2";
export default function ForgotPasswordPage() {
function ForgotPasswordPageLocal() {
const [email, setEmail] = useState("");
const [status, setStatus] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
@@ -59,3 +60,8 @@ export default function ForgotPasswordPage() {
</div>
);
}
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
export default function ForgotPasswordPage() {
return <AccountsGate kind="forgot"><ForgotPasswordPageLocal /></AccountsGate>;
}
@@ -1,11 +1,12 @@
"use client";
import { AccountsGate } from "@/components/auth/AccountsGate";
import React, { Suspense } from "react";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { LoginForm } from "@/components/auth/LoginForm";
import { LogIn } from "lucide-react";
export default function LoginPage() {
function LoginPageLocal() {
return (
<div className="min-h-screen flex flex-col">
<Navbar />
@@ -29,3 +30,8 @@ export default function LoginPage() {
</div>
);
}
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
export default function LoginPage() {
return <AccountsGate kind="login"><LoginPageLocal /></AccountsGate>;
}
@@ -1,11 +1,12 @@
"use client";
import { AccountsGate } from "@/components/auth/AccountsGate";
import React, { Suspense } from "react";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { RegisterForm } from "@/components/auth/RegisterForm";
import { UserPlus } from "lucide-react";
export default function RegisterPage() {
function RegisterPageLocal() {
return (
<div className="min-h-screen flex flex-col">
<Navbar />
@@ -29,3 +30,8 @@ export default function RegisterPage() {
</div>
);
}
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
export default function RegisterPage() {
return <AccountsGate kind="register"><RegisterPageLocal /></AccountsGate>;
}
@@ -1,4 +1,5 @@
"use client";
import { AccountsGate } from "@/components/auth/AccountsGate";
import React, { Suspense, useMemo, useState } from "react";
import Link from "next/link";
import { Navbar } from "@/components/layout/Navbar";
@@ -89,10 +90,14 @@ function ActivateAccountContent() {
);
}
export default function ActivateAccountPage() {
function ActivateAccountPageLocal() {
return (
<Suspense fallback={<div className="p-6">Loading...</div>}>
<ActivateAccountContent />
</Suspense>
);
}
}
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
export default function ActivateAccountPage() {
return <AccountsGate kind="activate"><ActivateAccountPageLocal /></AccountsGate>;
}
@@ -0,0 +1,46 @@
"use client";
import React, { useEffect, useState } from "react";
import { API_BASE } from "@/lib/api";
import { saveToken } from "@/lib/auth";
import { safePath, signInHref } from "@/lib/signIn";
/**
* Back from the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §3): the one-time code in the
* address's fragment (never sent to a server or in a Referer) is swapped for Events' own token,
* then on to the page the person started on.
*/
export default function SignInCompletePage() {
const [failed, setFailed] = useState<string | null>(null);
useEffect(() => {
const code = window.location.hash.slice(1);
// Out of the address bar and the history straight away.
window.history.replaceState(null, "", "/auth/complete");
if (!code) {
setFailed("This sign-in link has already been used.");
return;
}
fetch(`${API_BASE}/api/auth/handoff`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code }) })
.then(async (r) => {
const j = await r.json().catch(() => null);
if (!r.ok || !j?.data?.token) throw new Error(j?.error?.message || "This sign-in has expired. Please sign in again.");
saveToken(j.data.token);
// A full page load, so the whole app starts signed in.
window.location.replace(safePath(j.data.returnTo));
})
.catch((e: Error) => setFailed(e.message));
}, []);
return (
<div className="min-h-screen flex items-center justify-center p-6">
{failed ? (
<div className="w-full max-w-md border rounded-2xl p-8 bg-white shadow-sm">
<h1 className="text-xl font-semibold text-gray-900 mb-2">We couldn&apos;t sign you in</h1>
<p className="text-sm text-gray-600 mb-6">{failed}</p>
<a href={signInHref("/dashboard")} className="inline-block w-full text-center px-4 py-2.5 rounded-lg bg-brand-600 text-white text-sm font-medium">Sign in again</a>
</div>
) : (
<p className="text-sm text-gray-500" role="status">Signing you in…</p>
)}
</div>
);
}
@@ -0,0 +1,44 @@
"use client";
import React, { Suspense } from "react";
import { useSearchParams } from "next/navigation";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
import { safePath, signInHref } from "@/lib/signIn";
/** When signing in through the church's Accounts didn't work (3.0.0): what happened, and Try again. */
const MESSAGES: Record<string, { title: string; text: string; retry?: boolean }> = {
EXPIRED: { title: "That sign-in expired", text: "It took too long, or it was opened in another browser. Please try again.", retry: true },
ACCOUNTS_UNAVAILABLE: { title: "Sign-in isn’t available right now", text: "We couldn’t reach the church’s sign-in. Please try again in a minute.", retry: true },
START_FAILED: { title: "Sign-in isn’t available right now", text: "Please try again in a minute.", retry: true },
FINISH_FAILED: { title: "We couldn’t finish signing you in", text: "Please try again.", retry: true },
EVENTS_OFF: { title: "Your access to events is turned off", text: "Your church account is fine, but you can’t use this site at the moment. Please ask the church office." },
MFA_REQUIRED: { title: "Two-step sign-in is needed", text: "Your role here needs a second step when you sign in. Please try again and set it up when asked.", retry: true },
EMAIL_IN_USE: { title: "That email address belongs to someone else here", text: "Please ask the church office to sort it out." },
EMAIL_NOT_VERIFIED: { title: "Please confirm your email address", text: "Confirm the email address on your church account, then sign in again.", retry: true },
};
function Problem() {
const search = useSearchParams();
const m = MESSAGES[search.get("code") || ""] ?? { title: "Something went wrong signing in", text: "Please try again.", retry: true };
return (
<div className="w-full max-w-md border rounded-2xl p-8 bg-white shadow-sm">
<h1 className="text-xl font-semibold text-gray-900 mb-2">{m.title}</h1>
<p className="text-sm text-gray-600 mb-6">{m.text}</p>
{m.retry && <a href={signInHref(safePath(search.get("returnTo"), "/"))} className="inline-block w-full text-center px-4 py-2.5 rounded-lg bg-brand-600 text-white text-sm font-medium">Try again</a>}
<a href="/" className="block mt-3 text-center text-sm text-gray-500 underline">Home page</a>
</div>
);
}
export default function SignInProblemPage() {
return (
<div className="min-h-screen flex flex-col">
<Navbar />
<main className="flex-1 flex items-center justify-center p-6">
<Suspense fallback={<div />}><Problem /></Suspense>
</main>
<Footer />
</div>
);
}
@@ -8,7 +8,7 @@ import { ApiError, resolveToApiOrigin } from "@/lib/api";
import { apiV2Raw, apiV2Data } from "@/lib/apiV2";
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
import { useDismissingState } from "@/hooks/useDismissingState";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles, Link2 } from "lucide-react";
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles, Link2, LogIn } from "lucide-react";
import { ColorPickerField } from "@/components/admin/ColorPickerField";
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
import { BackupsTab } from "@/components/admin/BackupsTab";
@@ -18,6 +18,7 @@ import { LicenceTab } from "@/components/admin/LicenceTab";
import { WebhooksTab } from "@/components/admin/WebhooksTab";
import { AiTab } from "@/components/admin/AiTab";
import { LinkedProductsTab } from "@/components/admin/LinkedProductsTab";
import { SignInTab } from "@/components/admin/SignInTab";
import { CampusesTab } from "@/components/admin/CampusesTab";
import { extractDominantColors } from "@/lib/extractColors";
import { mapsSearchUrl } from "@/lib/maps";
@@ -26,7 +27,7 @@ import { BackLink } from "@/components/shared/BackLink";
import { uploadImage } from "@/lib/eventSetup";
import { useExternalEffect } from "@/lib/hooks";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "backups" | "jobs" | "licence" | "ai";
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "signin" | "backups" | "jobs" | "licence" | "ai";
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "organisation", label: "Organisation", icon: Building2 },
@@ -39,6 +40,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
{ id: "payments", label: "Payments", icon: CreditCard },
{ id: "webhooks", label: "Webhooks", icon: Webhook },
{ id: "linked", label: "Linked products", icon: Link2 },
{ id: "signin", label: "Sign-in", icon: LogIn },
{ id: "backups", label: "Backups", icon: DatabaseBackup },
{ id: "jobs", label: "Background jobs", icon: Timer },
{ id: "licence", label: "Licence", icon: KeyRound },
@@ -721,6 +723,7 @@ function SiteSettingsPageInner() {
{activeTab === "backups" && <BackupsTab active={activeTab === "backups"} />}
{activeTab === "webhooks" && <WebhooksTab active={activeTab === "webhooks"} />}
{activeTab === "linked" && <LinkedProductsTab active={activeTab === "linked"} />}
{activeTab === "signin" && <SignInTab active={activeTab === "signin"} />}
{activeTab === "jobs" && <JobsTab active={activeTab === "jobs"} />}
{activeTab === "licence" && <LicenceTab active={activeTab === "licence"} />}
{activeTab === "ai" && <AiTab active={activeTab === "ai"} />}
@@ -1,4 +1,5 @@
"use client";
import { useAuthInfo } from "@/components/auth/ChurchAccountNotice";
import React, { useCallback, useEffect, useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
@@ -39,6 +40,9 @@ const TWO_FACTOR_LABEL: Record<"email" | "whatsapp" | "authenticator", string> =
export default function AdminUsersPage() {
const { user, loading, token } = useAuth();
// 3.0.0: signed in through the church's Accounts, 2FA and lockouts are reset there.
const authInfo = useAuthInfo();
const viaAccounts = authInfo?.mode === "accounts";
const router = useRouter();
const isAdmin = useMemo(() => user?.role === "admin", [user]);
@@ -234,15 +238,25 @@ export default function AdminUsersPage() {
const message = role === "admin" || role === "supervisor"
? `Reset two-factor authentication for ${name}? Their sessions end, and they'll set it up again with a new code at their next login.`
: `Turn off two-factor authentication for ${name}? They will be able to log in with just their password until they turn it back on.`;
if (!confirm(message)) return;
if (!confirm(viaAccounts ? `Reset two-step sign-in for ${name} on their church account? They're signed out everywhere and set it up again at their next sign-in.` : message)) return;
try {
await apiV2Data("patch", "/users/{id}", { params: { id: id }, authToken: token, body: { twoFactorEnabled: false } });
if (viaAccounts) await apiV2Data("post", "/users/{id}/account/reset-two-factor", { params: { id }, authToken: token });
else await apiV2Data("patch", "/users/{id}", { params: { id: id }, authToken: token, body: { twoFactorEnabled: false } });
await loadUsers(page);
} catch (e) {
setError(errorMessage(e) || "Failed to reset two-factor authentication");
}
};
const unlockAccount = async (id: string, name: string) => {
try {
await apiV2Data("post", "/users/{id}/account/unlock", { params: { id }, authToken: token });
alert(`${name} can sign in again.`);
} catch (e) {
setError(errorMessage(e) || "Failed to unlock the account");
}
};
const deactivate = async (id: string) => {
if (!confirm("Deactivate this user? Their account will be disabled.")) return;
try {
@@ -447,7 +461,10 @@ export default function AdminUsersPage() {
{u.twoFactorEnabled && (
<button className="px-2 py-1 text-xs rounded bg-amber-500 text-white hover:bg-amber-600" onClick={() => resetTwoFactor(u.id, u.name, u.role)} title={u.role === "admin" || u.role === "supervisor" ? "Reset two-factor authentication — they set it up again at their next login" : "Turn off two-factor authentication for a user who can no longer receive their codes"}>Reset 2FA</button>
)}
<button className="px-2 py-1 text-xs rounded bg-orange-500 text-white hover:bg-orange-600" onClick={() => deactivate(u.id)} title="Deactivate account">Deactivate</button>
{viaAccounts && (
<button className="px-2 py-1 text-xs rounded bg-gray-100 hover:bg-gray-200" onClick={() => unlockAccount(u.id, u.name)} title="After too many wrong passwords: let them try again now">Unlock</button>
)}
<button className="px-2 py-1 text-xs rounded bg-orange-500 text-white hover:bg-orange-600" onClick={() => deactivate(u.id)} title={viaAccounts ? "Stop them using Cross Events (their church account stays)" : "Deactivate account"}>Deactivate</button>
<button className="px-2 py-1 text-xs rounded bg-red-700 text-white hover:bg-red-800" onClick={() => deleteUserData(u.id, u.name)} title="Erase personal data">Delete data</button>
</div>
</td>
@@ -1,4 +1,5 @@
"use client";
import { ChurchAccountNotice, useAuthInfo } from "@/components/auth/ChurchAccountNotice";
import React, { useCallback, useState } from "react";
import Link from "next/link";
@@ -77,6 +78,10 @@ function Toggle({ label, hint, checked, disabled, onChange }: { label: string; h
export default function PrivacyCentrePage() {
const { token, logout } = useAuth();
// 3.0.0: signed in through the church's Accounts, news choices, "download my data" (with this
// site's part in it) and deleting the account are on the church account.
const authInfo = useAuthInfo();
const viaAccounts = authInfo?.mode === "accounts";
const [info, setInfo] = useState<PrivacyInfo | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
@@ -202,7 +207,14 @@ export default function PrivacyCentrePage() {
<div className="grid lg:grid-cols-2 gap-6 items-start">
<div className="space-y-6">
{viaAccounts && (
<ChurchAccountNotice
accountUrl={authInfo?.accountUrl ?? null}
what="Your news choices, downloading everything the church holds about you (including your events, tickets and payments here), and deleting your account are on your church account, for all the church's sites and apps at once."
/>
)}
{/* ── News & announcements ───────────────────────────────────────── */}
{!viaAccounts && (<>
<section className="border rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={Megaphone} title="News & announcements" />
<p className="text-sm text-gray-500 mb-4">
@@ -255,6 +267,7 @@ export default function PrivacyCentrePage() {
{downloadMsg && <Alert msg={downloadMsg} />}
</section>
</>)}
{/* ── My requests ────────────────────────────────────────────────── */}
{info && info.requests.length > 0 && (
<section className="border rounded-xl p-5 bg-white shadow-sm">
@@ -300,6 +313,7 @@ export default function PrivacyCentrePage() {
</section>
{/* ── Delete my account ──────────────────────────────────────────── */}
{!viaAccounts && (
<section className="border border-red-200 rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={Trash2} title="Delete my account" tone="red" />
<p className="text-sm text-gray-500 mb-4">
@@ -337,6 +351,7 @@ export default function PrivacyCentrePage() {
)}
{deleteMsg && <Alert msg={deleteMsg} />}
</section>
)}
</div>
</div>
</div>
@@ -1,4 +1,5 @@
"use client";
import { ChurchAccountNotice, useAuthInfo } from "@/components/auth/ChurchAccountNotice";
import React, { useCallback, useEffect, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
@@ -50,6 +51,10 @@ const SectionHeader = ({ icon: Icon, title, tone = "brand" }: { icon: typeof Use
export default function UserProfilePage() {
const { user, token, logout, updateToken } = useAuth();
const router = useRouter();
// 3.0.0: signed in through the church's Accounts, the details, password, two-step sign-in and
// closing the account are on the church account.
const authInfo = useAuthInfo();
const viaAccounts = authInfo?.mode === "accounts";
useEffect(() => {
if (!user && !token) router.replace("/login");
@@ -372,16 +377,21 @@ export default function UserProfilePage() {
<form onSubmit={saveProfile} className="space-y-4">
<div>
<label htmlFor="profile-full-name" className="block text-sm font-medium text-gray-700 mb-1">Full name</label>
<input id="profile-full-name" className={inputCls} value={name} onChange={e => setName(e.target.value)} required />
<input id="profile-full-name" className={inputCls} value={name} onChange={e => setName(e.target.value)} required readOnly={viaAccounts} />
</div>
<div>
<label htmlFor="profile-email-address" className="block text-sm font-medium text-gray-700 mb-1">Email address</label>
<input id="profile-email-address" type="email" className={inputCls} value={email} onChange={e => setEmail(e.target.value)} required />
<input id="profile-email-address" type="email" className={inputCls} value={email} onChange={e => setEmail(e.target.value)} required readOnly={viaAccounts} />
</div>
<div>
<label htmlFor="profile-phone-number" className="block text-sm font-medium text-gray-700 mb-1">Phone number</label>
<input id="profile-phone-number" type="tel" className={inputCls} value={phone} onChange={e => setPhone(e.target.value)} placeholder="e.g. 082 123 4567" />
<input id="profile-phone-number" type="tel" className={inputCls} value={phone} onChange={e => setPhone(e.target.value)} placeholder="e.g. 082 123 4567" readOnly={viaAccounts} />
</div>
{viaAccounts && (
<p className="text-xs text-gray-500">
Your name, email and phone are on your church account{authInfo?.accountUrl ? <>: <a href={authInfo.accountUrl} className="text-brand-600 hover:underline">change them there</a></> : null}. Changes show here the next time you sign in.
</p>
)}
{campusInfo.enabled && campusInfo.campuses.length > 0 && (
<div>
@@ -443,6 +453,13 @@ export default function UserProfilePage() {
</div>
<div className="space-y-6">
{viaAccounts && (
<ChurchAccountNotice
accountUrl={authInfo?.accountUrl ?? null}
what="Your password, two-step sign-in, recovery codes, recent sign-ins and closing your account are on your church account, the same one you use for the church's other sites and apps."
/>
)}
{!viaAccounts && (<>
{/* ── Password ─────────────────────────────────────────────────── */}
<section className="border rounded-xl p-5 bg-white shadow-sm">
<SectionHeader icon={Lock} title="Change password" />
@@ -706,6 +723,7 @@ export default function UserProfilePage() {
</form>
)}
</section>
</>)}
</div>
</div>
</div>
@@ -1,4 +1,5 @@
"use client";
import { AccountsGate } from "@/components/auth/AccountsGate";
import React, { Suspense, useMemo, useState } from "react";
import { Navbar } from "@/components/layout/Navbar";
import { Footer } from "@/components/layout/Footer";
@@ -68,10 +69,15 @@ function ResetPasswordContent() {
);
}
export default function ResetPasswordPage() {
function ResetPasswordPageLocal() {
return (
<Suspense fallback={<div className="p-6">Loading...</div>}>
<ResetPasswordContent />
</Suspense>
);
}
// 3.0.0: forwards to the church's Accounts once sign-in has moved there (components/auth/AccountsGate).
export default function ResetPasswordPage() {
return <AccountsGate kind="reset"><ResetPasswordPageLocal /></AccountsGate>;
}
@@ -0,0 +1,171 @@
"use client";
import React, { useEffect, useState } from "react";
import { LogIn } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { apiV2, type V2Result } from "@/lib/apiV2";
import { errorMessage } from "@/lib/utils";
type Status = V2Result<"/settings/sign-in", "get">["data"];
type Check = V2Result<"/settings/sign-in/check", "post">["data"];
type Report = { created: number; linked: { name: string; email: string }[]; refused: { name: string; email: string; reason: string }[]; skipped: number; accountsAdmins: { name: string }[]; by: string; movedAt: string };
const when = (iso: string | null | undefined) =>
iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "long", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "";
/**
* Site settings → Sign-in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): where people sign in, and moving
* sign-in to the church's Accounts: Check (nothing changes), Move (with which admins also manage
* Accounts), and Undo for 14 days.
*/
export function SignInTab({ active }: { active: boolean }) {
const { token } = useAuth();
const [status, setStatus] = useState<Status | null>(null);
const [checked, setChecked] = useState<Check | null>(null);
const [admins, setAdmins] = useState<Set<string>>(new Set());
const [keepAccountsNotices, setKeepAccountsNotices] = useState(false);
const [busy, setBusy] = useState<string | null>(null);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
useEffect(() => {
if (!active || !token) return;
let alive = true;
apiV2("get", "/settings/sign-in", { authToken: token })
.then(({ data }) => { if (alive) setStatus(data); })
.catch((e) => { if (alive) setMsg({ ok: false, text: errorMessage(e) || "Could not load the sign-in settings." }); });
return () => { alive = false; };
}, [active, token]);
if (!token) return null;
if (!status) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
const auth = { authToken: token };
const runCheck = async () => {
setBusy("check");
setMsg(null);
try {
const { data } = await apiV2("post", "/settings/sign-in/check", auth);
setChecked(data);
setAdmins(new Set(data.admins.map((a) => a.id)));
} catch (e) {
setMsg({ ok: false, text: errorMessage(e) || "The check didn't work." });
}
setBusy(null);
};
const runMove = async () => {
if (!checked) return;
if (!window.confirm(`Move sign-in to your church's Accounts now? ${checked.toMove} people will sign in there from now on, with the passwords they have today.`)) return;
setBusy("move");
setMsg(null);
try {
const { data } = await apiV2("post", "/settings/sign-in/move", { ...auth, body: { adminIds: [...admins], ...(checked.noticeConflict ? { keepAccountsNotices } : {}) } });
setStatus(data);
setChecked(null);
setMsg({ ok: true, text: "Sign-in now goes through your church's Accounts. People already signed in stay signed in." });
} catch (e) {
setMsg({ ok: false, text: errorMessage(e) || "The move didn't finish. Nothing was switched; you can try again." });
}
setBusy(null);
};
const runUndo = async () => {
if (!window.confirm("Go back to Cross Events' own sign-in? People sign in with the password they had at the move. Changes made in Accounts since then (a new password, two-step sign-in) don't come back here.")) return;
setBusy("undo");
setMsg(null);
try {
const { data } = await apiV2("post", "/settings/sign-in/undo", auth);
setStatus(data);
setMsg({ ok: true, text: "Sign-in is back in Cross Events." });
} catch (e) {
setMsg({ ok: false, text: errorMessage(e) || "Undo didn't work." });
}
setBusy(null);
};
const report = status.report as Report | null;
return (
<div className="space-y-6">
<div>
<h2 className="flex items-center gap-2 text-lg font-semibold"><LogIn className="h-5 w-5 text-brand-600" aria-hidden /> Sign-in</h2>
<p className="text-sm text-gray-600 mt-1">
{status.mode === "accounts"
? "People sign in with their church account, the same one they use for the church's other sites and apps. Passwords and two-step sign-in are managed there."
: "People sign in with a Cross Events password. You can move sign-in to your church's Accounts, so one account works for all the church's sites and apps."}
</p>
</div>
{msg && <p className={`text-sm rounded-lg px-3 py-2 ${msg.ok ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`} role="status">{msg.text}</p>}
{status.mode === "accounts" ? (
<section className="border rounded-xl p-4 space-y-3">
<p className="text-sm"><span className="font-medium">Through Accounts</span>{status.accountsUrl ? <> at <a className="underline" href={status.accountsUrl} target="_blank" rel="noreferrer">{status.accountsUrl.replace(/^https?:\/\//, "")}</a></> : null}{status.movedAt ? `, since ${when(status.movedAt)}` : ""}.</p>
{report && (
<ul className="text-sm text-gray-700 list-disc pl-5 space-y-1">
<li>{report.created} people moved{report.by ? ` (by ${report.by})` : ""}.</li>
{report.linked.length > 0 && <li>{report.linked.length} already had an account and were linked to it: {report.linked.map((l) => l.email).join(", ")}.</li>}
{report.refused.length > 0 && <li>{report.refused.length} couldn&apos;t move: {report.refused.map((r) => `${r.email} (${r.reason})`).join("; ")}.</li>}
<li>{report.skipped} guests and deleted people stay in Cross Events only.</li>
<li>Also Accounts admins: {report.accountsAdmins.map((a) => a.name).join(", ") || "nobody"}.</li>
</ul>
)}
{status.undoUntil && !status.secretsCleared ? (
<div className="flex flex-wrap items-center gap-3">
<button type="button" onClick={runUndo} disabled={!!busy} className="px-3 py-2 rounded-lg border text-sm">{busy === "undo" ? "Going back…" : "Undo the move"}</button>
<span className="text-xs text-gray-500">Possible until {when(status.undoUntil)}. After that, Cross Events removes the old passwords.</span>
</div>
) : <p className="text-xs text-gray-500">Cross Events no longer holds anyone&apos;s password.</p>}
</section>
) : !status.accountsConnected ? (
<section className="border rounded-xl p-4">
<p className="text-sm text-gray-700">Connect your church&apos;s Accounts first, under <span className="font-medium">Linked products</span>. Ask Cross Code to install Accounts if it isn&apos;t listed there.</p>
</section>
) : (
<section className="border rounded-xl p-4 space-y-4">
<div className="flex flex-wrap items-center gap-3">
<button type="button" onClick={runCheck} disabled={!!busy || status.running} className="px-3 py-2 rounded-lg border text-sm">{busy === "check" ? "Checking…" : checked ? "Check again" : "Check the move"}</button>
<span className="text-xs text-gray-500">Nothing changes until you press Move.</span>
</div>
{checked && (
<div className="space-y-4">
<ul className="text-sm text-gray-700 list-disc pl-5 space-y-1">
<li>{checked.wouldCreate} people move with their current password{checked.withTwoFactor ? `; ${checked.withTwoFactor} use two-step sign-in and keep their method (they get new recovery codes the first time)` : ""}.</li>
{checked.wouldLink.length > 0 && <li>{checked.wouldLink.length} already have a church account and will be linked to it (they keep that account&apos;s password): {checked.wouldLink.map((l) => l.email).join(", ")}.</li>}
{checked.refused.length > 0 && <li className="text-red-700">{checked.refused.length} can&apos;t move: {checked.refused.map((r) => `${r.email} (${r.reason})`).join("; ")}. Fix these first, or they won&apos;t be able to sign in.</li>}
<li>{checked.skipped} guests and deleted people stay in Cross Events only.</li>
<li>Accounts {checked.accountsVersion}.</li>
</ul>
{checked.admins.length > 0 && (
<fieldset>
<legend className="text-sm font-medium mb-1">Also make these admins Accounts admins (they can manage everyone&apos;s sign-in)</legend>
{checked.admins.map((a) => (
<label key={a.id} className="flex items-center gap-2 text-sm py-0.5">
<input type="checkbox" checked={admins.has(a.id)} onChange={(e) => {
const next = new Set(admins);
if (e.target.checked) next.add(a.id); else next.delete(a.id);
setAdmins(next);
}} />
{a.name} <span className="text-gray-500">({a.email})</span>
</label>
))}
</fieldset>
)}
{checked.noticeConflict && (
<fieldset>
<legend className="text-sm font-medium mb-1">Accounts already has its own privacy notice. Which one should people see?</legend>
<label className="flex items-center gap-2 text-sm py-0.5"><input type="radio" name="notice" checked={keepAccountsNotices} onChange={() => setKeepAccountsNotices(true)} /> Keep Accounts&apos; notice (everyone accepts it at their next sign-in)</label>
<label className="flex items-center gap-2 text-sm py-0.5 text-gray-400"><input type="radio" name="notice" disabled checked={!keepAccountsNotices} readOnly /> Use Cross Events&apos; notice (remove Accounts&apos; notice in Accounts first)</label>
</fieldset>
)}
<button type="button" onClick={runMove} disabled={!!busy || (!!checked.noticeConflict && !keepAccountsNotices)} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium disabled:opacity-50">
{busy === "move" ? "Moving… (don't close this page)" : "Move sign-in to Accounts"}
</button>
<p className="text-xs text-gray-500">Pick a quiet time. It takes about a minute; people already signed in stay signed in. You can undo it for 14 days.</p>
</div>
)}
</section>
)}
</div>
);
}
@@ -0,0 +1,54 @@
"use client";
import React, { useEffect, useState } from "react";
import { fetchAuthMode, safePath, signInHref, type AuthMode } from "@/lib/signIn";
type Kind = "login" | "register" | "forgot" | "reset" | "activate";
/**
* Cross Events' own sign-in pages (3.0.0). With sign-in through Accounts, the sign-in, sign-up and
* forgot-password pages forward there (keeping where to come back to), and old reset and activation
* links say sign-in has moved. Otherwise (`local`, or `?local=1` from the backend) the page as before.
*/
export function AccountsGate({ kind, children }: { kind: Kind; children: React.ReactNode }) {
const [mode, setMode] = useState<AuthMode | null>(null);
useEffect(() => {
let alive = true;
const params = new URLSearchParams(window.location.search);
if (params.get("local") === "1") {
setMode("local");
return;
}
fetchAuthMode().then((m) => {
if (!alive) return;
if (m === "accounts" && (kind === "login" || kind === "register" || kind === "forgot")) {
window.location.replace(signInHref(safePath(params.get("redirect")), { signUp: kind === "register" }));
return;
}
setMode(m);
});
return () => { alive = false; };
}, [kind]);
if (mode === null) {
return <div className="min-h-[50vh] flex items-center justify-center text-sm text-gray-500" role="status">Loading…</div>;
}
if (mode === "accounts") return <SignInMoved kind={kind} />;
return <>{children}</>;
}
function SignInMoved({ kind }: { kind: Kind }) {
return (
<div className="min-h-[60vh] flex items-center justify-center p-6">
<div className="w-full max-w-md border rounded-2xl p-8 bg-white shadow-sm">
<h1 className="text-xl font-semibold text-gray-900 mb-2">Sign-in has moved</h1>
<p className="text-sm text-gray-600 mb-6">
{kind === "activate"
? "You now sign in with your church account. To get started, use “Forgot your password?” there with your email address to choose a password."
: "You now sign in with your church account, so this link no longer works. Use “Forgot your password?” there to choose a new one."}
</p>
<a href={signInHref("/dashboard")} className="inline-block w-full text-center px-4 py-2.5 rounded-lg bg-brand-600 text-white text-sm font-medium">Sign in</a>
</div>
</div>
);
}
@@ -0,0 +1,28 @@
"use client";
import React, { useEffect, useState } from "react";
import { fetchAuthInfo, type AuthInfo } from "@/lib/signIn";
/** Whether sign-in goes through the church's Accounts (3.0.0), and its account page; null while loading. */
export function useAuthInfo(): AuthInfo | null {
const [info, setInfo] = useState<AuthInfo | null>(null);
useEffect(() => {
let alive = true;
fetchAuthInfo().then((i) => { if (alive) setInfo(i); });
return () => { alive = false; };
}, []);
return info;
}
/** "Your sign-in and security are on your church account", with a link to it. */
export function ChurchAccountNotice({ accountUrl, what }: { accountUrl: string | null; what: string }) {
return (
<section className="border rounded-xl p-5 bg-white shadow-sm">
<h2 className="text-lg font-semibold text-gray-900 mb-2">On your church account</h2>
<p className="text-sm text-gray-600 mb-4">{what}</p>
{accountUrl && (
<a href={accountUrl} className="inline-block px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700">Open my church account</a>
)}
</section>
);
}
@@ -4,6 +4,8 @@ import React, { createContext, useCallback, useContext, useEffect, useMemo, useS
import { ApiError } from "@/lib/api";
import { AuthResponse, AuthUser, TwoFactorChallenge, clearToken, getDeviceToken, getToken, saveDeviceToken, saveToken } from "@/lib/auth";
import { apiV2, type V2Result, apiV2Data } from "@/lib/apiV2";
import { API_BASE } from "@/lib/api";
import { fetchAuthMode } from "@/lib/signIn";
// A v2 "signed_in" answer as the session the app keeps (the user's fields plus the token).
type V2Session = Extract<V2Result<"/auth/login", "post">["data"], { status: "signed_in" }>;
@@ -142,10 +144,21 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
}, []);
const logout = useCallback(() => {
const t = getToken();
clearToken();
cacheUser(null);
setToken(null);
setUser(null);
// 3.0.0: signed in through the church's Accounts, signing out here signs out there too (and of
// the church's other products), then comes back to this site's home page.
if (t) {
fetchAuthMode()
.then((m) => (m === "accounts"
? fetch(`${API_BASE}/api/auth/signout`, { method: "POST", headers: { Authorization: `Bearer ${t}`, "Content-Type": "application/json" }, body: "{}" }).then((r) => r.json())
: null))
.then((j: { data?: { url?: string | null } } | null) => { if (j?.data?.url) window.location.assign(j.data.url); })
.catch(() => { /* signed out here either way */ });
}
}, []);
// Some endpoints (profile update, password change, session revocation) issue a
@@ -3,6 +3,7 @@
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/useAuth";
import { currentPage } from "@/lib/signIn";
/**
* Use inside any client component that requires authentication.
@@ -19,7 +20,9 @@ export function useRequireAuth(redirectTo = "/login") {
useEffect(() => {
if (loading) return;
if (!user) router.replace(redirectTo);
// Back to this exact page after signing in (3.0.0: through the church's Accounts, which
// `/login` forwards to).
if (!user) router.replace(redirectTo === "/login" ? `/login?redirect=${encodeURIComponent(currentPage())}` : redirectTo);
}, [user, loading, router, redirectTo]);
const ready = !loading && !!user;
@@ -72240,6 +72240,950 @@
}
}
}
},
"/auth/mode": {
"get": {
"tags": [
"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.\n\n**Who:** Anyone.",
"operationId": "getAuthMode",
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": [
"local",
"accounts"
]
},
"signInUrl": {
"type": "string"
},
"accountUrl": {
"description": "With `accounts`: the church account page (profile, password, two-step sign-in, privacy)",
"type": [
"string",
"null"
]
}
},
"required": [
"mode",
"signInUrl",
"accountUrl"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
}
}
}
},
"/settings/sign-in": {
"get": {
"tags": [
"Accounts"
],
"summary": "Sign-in: where it is and the move to Accounts",
"description": "**Who:** Admins only.",
"operationId": "getSettingsSign-in",
"security": [
{
"bearerAuth": []
}
],
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": [
"local",
"accounts"
],
"description": "local: Cross Events' own sign-in; accounts: through the church's Accounts"
},
"accountsConnected": {
"type": "boolean"
},
"accountsUrl": {
"type": [
"string",
"null"
]
},
"movedAt": {
"type": [
"string",
"null"
]
},
"undoUntil": {
"description": "Undo is possible until then (14 days after the move)",
"type": [
"string",
"null"
]
},
"secretsCleared": {
"type": "boolean",
"description": "The old passwords have been removed (Undo is no longer possible)"
},
"running": {
"type": "boolean"
},
"report": {
"anyOf": [
{},
{
"type": "null"
}
]
}
},
"required": [
"mode",
"accountsConnected",
"accountsUrl",
"movedAt",
"undoUntil",
"secretsCleared",
"running",
"report"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/settings/sign-in/check": {
"post": {
"tags": [
"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.\n\n**Who:** Admins only.",
"operationId": "postSettingsSign-inCheck",
"security": [
{
"bearerAuth": []
}
],
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"accountsVersion": {
"type": "string"
},
"toMove": {
"type": "integer",
"minimum": -9007199254740991,
"maximum": 9007199254740991
},
"wouldCreate": {
"type": "integer",
"minimum": -9007199254740991,
"maximum": 9007199254740991
},
"wouldLink": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"email": {
"type": "string"
}
},
"required": [
"name",
"email"
],
"additionalProperties": false
}
},
"refused": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"email": {
"type": "string"
},
"reason": {
"type": "string"
}
},
"required": [
"name",
"email",
"reason"
],
"additionalProperties": false
}
},
"skipped": {
"type": "integer",
"minimum": -9007199254740991,
"maximum": 9007199254740991
},
"admins": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"email": {
"type": "string"
},
"id": {
"type": "string"
}
},
"required": [
"name",
"email",
"id"
],
"additionalProperties": false
}
},
"noticeConflict": {
"anyOf": [
{
"type": "object",
"properties": {
"accountsVersions": {
"type": "array",
"items": {
"type": "number"
}
},
"eventsVersions": {
"type": "array",
"items": {
"type": "number"
}
}
},
"required": [
"accountsVersions",
"eventsVersions"
],
"additionalProperties": false
},
{
"type": "null"
}
]
},
"withTwoFactor": {
"type": "integer",
"minimum": -9007199254740991,
"maximum": 9007199254740991
}
},
"required": [
"accountsVersion",
"toMove",
"wouldCreate",
"wouldLink",
"refused",
"skipped",
"admins",
"noticeConflict",
"withTwoFactor"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/settings/sign-in/move": {
"post": {
"tags": [
"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.\n\n**Who:** Admins only.",
"operationId": "postSettingsSign-inMove",
"security": [
{
"bearerAuth": []
}
],
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"adminIds": {
"maxItems": 500,
"type": "array",
"items": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
},
"description": "Events admins who also become Accounts admins"
},
"keepAccountsNotices": {
"description": "When Accounts has its own privacy notice: keep it (everyone accepts it at their next sign-in) instead of Events'",
"type": "boolean"
}
},
"required": [
"adminIds"
]
}
}
}
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": [
"local",
"accounts"
],
"description": "local: Cross Events' own sign-in; accounts: through the church's Accounts"
},
"accountsConnected": {
"type": "boolean"
},
"accountsUrl": {
"type": [
"string",
"null"
]
},
"movedAt": {
"type": [
"string",
"null"
]
},
"undoUntil": {
"description": "Undo is possible until then (14 days after the move)",
"type": [
"string",
"null"
]
},
"secretsCleared": {
"type": "boolean",
"description": "The old passwords have been removed (Undo is no longer possible)"
},
"running": {
"type": "boolean"
},
"report": {
"anyOf": [
{},
{
"type": "null"
}
]
}
},
"required": [
"mode",
"accountsConnected",
"accountsUrl",
"movedAt",
"undoUntil",
"secretsCleared",
"running",
"report"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"400": {
"description": "Validation failed (VALIDATION_FAILED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/settings/sign-in/undo": {
"post": {
"tags": [
"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.\n\n**Who:** Admins only.",
"operationId": "postSettingsSign-inUndo",
"security": [
{
"bearerAuth": []
}
],
"parameters": [],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"mode": {
"type": "string",
"enum": [
"local",
"accounts"
],
"description": "local: Cross Events' own sign-in; accounts: through the church's Accounts"
},
"accountsConnected": {
"type": "boolean"
},
"accountsUrl": {
"type": [
"string",
"null"
]
},
"movedAt": {
"type": [
"string",
"null"
]
},
"undoUntil": {
"description": "Undo is possible until then (14 days after the move)",
"type": [
"string",
"null"
]
},
"secretsCleared": {
"type": "boolean",
"description": "The old passwords have been removed (Undo is no longer possible)"
},
"running": {
"type": "boolean"
},
"report": {
"anyOf": [
{},
{
"type": "null"
}
]
}
},
"required": [
"mode",
"accountsConnected",
"accountsUrl",
"movedAt",
"undoUntil",
"secretsCleared",
"running",
"report"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/users/{id}/account/reset-two-factor": {
"post": {
"tags": [
"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.\n\n**Who:** Admins only.",
"operationId": "postUsersIdAccountReset-two-factor",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "The id",
"schema": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"ok": {
"type": "boolean",
"const": true
}
},
"required": [
"ok"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"400": {
"description": "Validation failed (VALIDATION_FAILED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "Not found (NOT_FOUND)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/users/{id}/account/unlock": {
"post": {
"tags": [
"Accounts"
],
"summary": "Unlock someone after too many wrong passwords (in Accounts)",
"description": "**Who:** Admins only.",
"operationId": "postUsersIdAccountUnlock",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "The id",
"schema": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"ok": {
"type": "boolean",
"const": true
}
},
"required": [
"ok"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"400": {
"description": "Validation failed (VALIDATION_FAILED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "Not found (NOT_FOUND)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
},
"/users/{id}/account/active": {
"post": {
"tags": [
"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.\n\n**Who:** Admins only.",
"operationId": "postUsersIdAccountActive",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "The id",
"schema": {
"type": "string",
"format": "uuid",
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
}
}
],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"active": {
"type": "boolean"
}
},
"required": [
"active"
]
}
}
}
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {
"ok": {
"type": "boolean",
"const": true
}
},
"required": [
"ok"
],
"additionalProperties": false
}
},
"required": [
"data"
],
"additionalProperties": false
}
}
}
},
"400": {
"description": "Validation failed (VALIDATION_FAILED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"401": {
"description": "Not signed in (UNAUTHENTICATED)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"403": {
"description": "Not allowed for this role (FORBIDDEN)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
},
"404": {
"description": "Not found (NOT_FOUND)",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Error"
}
}
}
}
}
}
}
},
"components": {
+645
View File
@@ -7498,6 +7498,178 @@ export interface paths {
patch?: never;
trace?: never;
};
"/auth/mode": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* 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.
*
* **Who:** Anyone.
*/
get: operations["getAuthMode"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/settings/sign-in": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Sign-in: where it is and the move to Accounts
* @description **Who:** Admins only.
*/
get: operations["getSettingsSign-in"];
put?: never;
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/settings/sign-in/check": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postSettingsSign-inCheck"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/settings/sign-in/move": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postSettingsSign-inMove"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/settings/sign-in/undo": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postSettingsSign-inUndo"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/users/{id}/account/reset-two-factor": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postUsersIdAccountReset-two-factor"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/users/{id}/account/unlock": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Unlock someone after too many wrong passwords (in Accounts)
* @description **Who:** Admins only.
*/
post: operations["postUsersIdAccountUnlock"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/users/{id}/account/active": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Admins only.
*/
post: operations["postUsersIdAccountActive"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@@ -39597,4 +39769,477 @@ export interface operations {
};
};
};
getAuthMode: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @enum {string} */
mode: "local" | "accounts";
signInUrl: string;
/** @description With `accounts`: the church account page (profile, password, two-step sign-in, privacy) */
accountUrl: string | null;
};
};
};
};
};
};
"getSettingsSign-in": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/**
* @description local: Cross Events' own sign-in; accounts: through the church's Accounts
* @enum {string}
*/
mode: "local" | "accounts";
accountsConnected: boolean;
accountsUrl: string | null;
movedAt: string | null;
/** @description Undo is possible until then (14 days after the move) */
undoUntil: string | null;
/** @description The old passwords have been removed (Undo is no longer possible) */
secretsCleared: boolean;
running: boolean;
report: unknown | null;
};
};
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postSettingsSign-inCheck": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
accountsVersion: string;
toMove: number;
wouldCreate: number;
wouldLink: {
name: string;
email: string;
}[];
refused: {
name: string;
email: string;
reason: string;
}[];
skipped: number;
admins: {
name: string;
email: string;
id: string;
}[];
noticeConflict: {
accountsVersions: number[];
eventsVersions: number[];
} | null;
withTwoFactor: number;
};
};
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postSettingsSign-inMove": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description Events admins who also become Accounts admins */
adminIds: string[];
/** @description When Accounts has its own privacy notice: keep it (everyone accepts it at their next sign-in) instead of Events' */
keepAccountsNotices?: boolean;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/**
* @description local: Cross Events' own sign-in; accounts: through the church's Accounts
* @enum {string}
*/
mode: "local" | "accounts";
accountsConnected: boolean;
accountsUrl: string | null;
movedAt: string | null;
/** @description Undo is possible until then (14 days after the move) */
undoUntil: string | null;
/** @description The old passwords have been removed (Undo is no longer possible) */
secretsCleared: boolean;
running: boolean;
report: unknown | null;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postSettingsSign-inUndo": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/**
* @description local: Cross Events' own sign-in; accounts: through the church's Accounts
* @enum {string}
*/
mode: "local" | "accounts";
accountsConnected: boolean;
accountsUrl: string | null;
movedAt: string | null;
/** @description Undo is possible until then (14 days after the move) */
undoUntil: string | null;
/** @description The old passwords have been removed (Undo is no longer possible) */
secretsCleared: boolean;
running: boolean;
report: unknown | null;
};
};
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
"postUsersIdAccountReset-two-factor": {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id */
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @constant */
ok: true;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postUsersIdAccountUnlock: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id */
id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @constant */
ok: true;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postUsersIdAccountActive: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The id */
id: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
active: boolean;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @constant */
ok: true;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
}
+57
View File
@@ -0,0 +1,57 @@
/**
* Signing in through the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §3). Once an admin has
* moved sign-in (Settings → Sign-in), `/login`, `/register` and `/forgot-password` forward to
* `GET /api/auth/signin?returnTo=…`, which sends the browser to Accounts and back to the same page.
* Every existing `/login?redirect=…` link keeps working that way.
*/
import { API_BASE } from "@/lib/api";
export type AuthMode = "local" | "accounts";
export type AuthInfo = { mode: AuthMode; accountUrl: string | null };
let infoPromise: Promise<AuthInfo> | null = null;
/**
* Where people sign in, and (through Accounts) the church account page, asked once per page load
* (it only changes when an admin moves sign-in).
*/
export function fetchAuthInfo(): Promise<AuthInfo> {
if (!infoPromise) {
infoPromise = fetch(`${API_BASE}/api/v2/auth/mode`, { headers: { Accept: "application/json" } })
.then((r) => (r.ok ? r.json() : null))
.then((j: { data?: { mode?: AuthMode; accountUrl?: string | null } } | null): AuthInfo => ({
mode: j?.data?.mode === "accounts" ? "accounts" : "local",
accountUrl: j?.data?.accountUrl ?? null,
}))
.catch(() => {
infoPromise = null;
return { mode: "local" as const, accountUrl: null };
});
}
return infoPromise;
}
export function fetchAuthMode(): Promise<AuthMode> {
return fetchAuthInfo().then((i) => i.mode);
}
/** A relative path on this site, or the fallback: never another site (the backend checks too). */
export function safePath(raw: string | null | undefined, fallback = "/dashboard"): string {
const s = String(raw ?? "");
return s.startsWith("/") && !s.startsWith("//") && !s.startsWith("/\\") ? s : fallback;
}
/** The address that signs someone in through Accounts and brings them back to `returnTo`. */
export function signInHref(returnTo: string, opts: { signUp?: boolean; email?: string } = {}): string {
const q = new URLSearchParams({ returnTo: safePath(returnTo) });
if (opts.signUp) q.set("signup", "1");
if (opts.email) q.set("email", opts.email);
return `${API_BASE}/api/auth/signin?${q.toString()}`;
}
/** The page someone is on now (path and query), to come back to after signing in. */
export function currentPage(): string {
if (typeof window === "undefined") return "/";
return `${window.location.pathname}${window.location.search}`;
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/events",
"version": "2.4.1",
"version": "3.0.0",
"main": "index.js",
"scripts": {
"dev:backend": "cd backend && npm run dev",
+36 -2
View File
@@ -52,8 +52,9 @@ connected before its Events can move.
12. [What changes in each repo](#11-what-changes-in-each-repo)
13. [Testing](#12-testing)
14. [Releasing and rolling it out](#13-releasing-and-rolling-it-out)
15. [Decisions](#decisions)
16. [Still open](#still-open)
15. [Changes while building](#changes-while-building)
16. [Decisions](#decisions)
17. [Still open](#still-open)
---
@@ -418,6 +419,39 @@ only for a connected product:
login events, Events' audit log) → after 14 days the Undo window closes and the old secrets are
cleared. **The demo site first, then Hope Family Church**, then the rest.
## Changes while building
1. **One request schema for product → Accounts:** `crosscode.identity-request/1` at
`POST /api/accounts/v1/requests` carries both `import.*` and `people.*` (contracts 1.8.0), so
`crosscode.identity/1` (Accounts → product) is unchanged. The `people.*` names: `ensure`,
`update`, `resetTwoFactor`, `unlock`, `setActive`, `newsOff`. A request id seen before gets its
first answer.
2. **`import.finish` hashes the subs Accounts gave back**, not the Events ids, so people linked to an
account they already had count too. Accounts compares it with the people it holds as moved from
that product (`ProductPerson`).
3. **Notice versions are shifted by one:** Accounts' built-in notice is version 1, Events' is 0, so
Events' version *n* is Accounts' *n + 1* (acceptances too). "Use Cross Events' notice" when
Accounts already has its own isn't offered yet: the admin keeps Accounts' notice, or removes it
in Accounts first.
4. **The setup wizard still makes a local first admin** (§9 is not built): a new install starts in
`local`, and its admin moves sign-in once Accounts is connected (a one-person move takes seconds).
That avoids a setup that depends on Accounts being connected first. Signing in through Accounts
from the wizard can come with Hub 2.5.0's automatic Connect.
5. **People who never activated** (`isActive` false and never signed in) move as active accounts
without a password: Accounts' "Forgot your password?" sets one. Everyone else who is deactivated
moves as deactivated.
6. **`/login` forwards instead of a new `signInHref` in every link:** every existing
`/login?redirect=` link (and `useRequireAuth`, which now passes the current page) goes through it,
so the 49 files that link to `/login` didn't change.
7. **Events' own sign-in endpoints answer 409 `SIGN_IN_MOVED`** from one guard
(`src/accounts/guard.ts`) rather than in each controller. The guard only passes an admin's change
of someone's name, email or phone to Accounts for a valid, current admin token with its second step.
8. **The `auth-client` loader** uses a real dynamic `import()` (`src/accounts/client.ts`), since the
backend compiles to CommonJS and deploys still allow Node 20.
9. **Tests:** `npm run test:accounts` runs Events' own code (move, sign-in, sign-out, back-channel
logout, `user.updated`, Undo) against the whole Accounts app on real ports, each with an in-memory
database (11 tests). `user.export` and `user.deleted` are Jest tests (`tests/accountsCalls.test.ts`).
## Decisions
Confirmed by Joshua on 2026-11-19, all as proposed.
+1 -1
View File
@@ -32,7 +32,7 @@ every release).
| 1d | Agent 1.0.x + Hub 2.1.x (+ contracts 1.3.0) | **Released** 2026-11-17 (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`). **VM tested** end to end (AGENT-1.0-PLAN §13: joins, installs behind frp, scheduled / batch / missed updates, uninstall with export and purge, forged and replayed jobs). 2026-11-18: **`agent@1.0.1`** (the agent answers status on the central server itself) and Hub **`v2.1.1`** (adopt passes the church's address; Link takes the short name as a name). **Not rolled out**: use agent 1.0.1 and Hub 2.1.1 |
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` (+ contracts 1.4.0, Hub 2.2.0) | **Released** 2026-11-18 (`events@2.4.0`, `contracts@1.4.0`, Hub `v2.2.0`, crosscode-site `v1.4.0`; [EVENTS-2.4-PLAN.md](./EVENTS-2.4-PLAN.md)). **Before any church gets it:** the Events e2e run on Postgres and the VM test (EVENTS-2.4-PLAN §8) |
| 3 | Accounts 1.0.0 (+ contracts 1.5.0, agent 1.1.0, Hub 2.3.0) | **Released** 2026-11-18 (`accounts@1.0.0`, `contracts@1.5.0`, `agent@1.1.0`, Hub `v2.3.0`, crosscode-site `v1.5.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)). 37 backend and 8 Playwright tests pass without Postgres. **Before installing it for a church:** the VM test and a run on real Postgres; a Hub release source for `accounts@` tags |
| 4 | Cross Events 3.0.0: sign-in through Accounts, users migrated with their password hashes and 2FA | **Next.** Moved before the Website on 2026-11-19 (ROADMAP decision 38). Planned: [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md) (with contracts 1.8.0, Accounts 1.1.0, Hub 2.5.0); decisions confirmed 2026-11-19; being built on `feat/events-3.0` |
| 4 | Cross Events 3.0.0: sign-in through Accounts, users migrated with their password hashes and 2FA | **Next.** Moved before the Website on 2026-11-19 (ROADMAP decision 38). **Built** on `feat/events-3.0` (2026-11-19, not tagged): contracts 1.8.0, Accounts 1.1.0, Events 3.0.0 ([EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md), "Changes while building"). `npm run check` passes; `npm run test:accounts` (Events against the real Accounts) 11/11. **Still to do:** Hub 2.5.0 (New install of Events 3.x adds Accounts first and connects), the Events Playwright run with Accounts, the VM test and real Postgres, crosscode-site 1.6.0 |
| 5–7 | Website 1.0.0 → App 1.0.0 → App 1.x | Not started |
## Next up
+7 -6
View File
@@ -46,7 +46,7 @@
},
"apps/accounts/backend": {
"name": "@crosscode/accounts-backend",
"version": "1.0.1",
"version": "1.1.0",
"hasInstallScript": true,
"dependencies": {
"@crosscode/contracts": "*",
@@ -82,7 +82,7 @@
},
"apps/accounts/frontend": {
"name": "@crosscode/accounts-frontend",
"version": "1.0.1",
"version": "1.1.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/ui": "*",
@@ -127,10 +127,11 @@
},
"apps/events/backend": {
"name": "@crosscode/events-backend",
"version": "2.4.1",
"version": "3.0.0",
"hasInstallScript": true,
"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",
@@ -176,7 +177,7 @@
},
"apps/events/frontend": {
"name": "@crosscode/events-frontend",
"version": "2.4.1",
"version": "3.0.0",
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
@@ -21266,7 +21267,7 @@
},
"packages/auth-client": {
"name": "@crosscode/auth-client",
"version": "1.0.0",
"version": "1.1.0",
"dependencies": {
"@crosscode/contracts": "*",
"openid-client": "6.8.9"
@@ -21274,7 +21275,7 @@
},
"packages/contracts": {
"name": "@crosscode/contracts",
"version": "1.7.0",
"version": "1.8.0",
"license": "UNLICENSED",
"dependencies": {
"zod": "^4.6.7"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@crosscode/auth-client",
"version": "1.0.0",
"version": "1.1.0",
"private": true,
"description": "The product side of signing in through the church's Accounts (docs/ACCOUNTS-1.0-PLAN.md §5): start a sign-in with the return path, finish it, back-channel logout and Accounts' signed calls",
"type": "module",