Merge branch 'feat/totp'
This commit is contained in:
+14
-2
@@ -2,9 +2,17 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## Unreleased
|
||||
## events@2.3.0, contracts@1.3.0, agent@1.0.0 - 2026-11-17
|
||||
|
||||
Phase 1d (docs/AGENT-1.0-PLAN.md), built on `feat/agent-1.0`, not released yet:
|
||||
Phase 1c (authenticator-app sign-in) and phase 1d (docs/AGENT-1.0-PLAN.md): installs, updates and
|
||||
uninstalls from the Hub (Hub 2.1.0) through the agent. Tested end to end on a VM (church server +
|
||||
central server + Hub, AGENT-1.0-PLAN §13 and EVENTS-2.2-PLAN §6).
|
||||
|
||||
### Events (2.3.0)
|
||||
|
||||
- Two-factor with an authenticator app, and recovery codes. The env template, the church export
|
||||
and registering by itself from `HUB_LICENCE_KEY` for installs from the Hub. Details in
|
||||
`apps/events/CHANGELOG.md`.
|
||||
|
||||
### Contracts (1.3.0)
|
||||
|
||||
@@ -25,6 +33,10 @@ Phase 1d (docs/AGENT-1.0-PLAN.md), built on `feat/agent-1.0`, not released yet:
|
||||
- `--json` reports and `--config` on every command; `.env` files from each release's env template
|
||||
(appended to, never rewritten, on deploy); `install --frp` with Hub-given ports, a database on
|
||||
another server, and clean-up on failure; frpc.ini blocks; `restart`, `export`, `uninstall`, `purge`.
|
||||
- Fixed in the VM test: `adopt` applies a release's new migrations in the switch-over; a failed
|
||||
migration is marked rolled back so later deploys aren't blocked; frpc is restarted once when its
|
||||
admin lines are first added; a site's PM2 always runs under its own systemd unit (`pm2-<user>`),
|
||||
so restarting or updating the agent never stops a site; tags are fetched with `--force`.
|
||||
|
||||
## events@2.2.0, contracts@1.2.0 - 2026-11-17
|
||||
|
||||
|
||||
@@ -5,10 +5,27 @@ 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/).
|
||||
|
||||
## [Unreleased]
|
||||
## [2.3.0] - 2026-11-17
|
||||
|
||||
Authenticator-app sign-in and recovery codes (ROADMAP-v3 phase 1c), and what installs and
|
||||
updates from the Hub need (crosscode agent 1.0, Hub 2.1.0).
|
||||
|
||||
### Added
|
||||
|
||||
- **Two-factor with an authenticator app** (TOTP, RFC 6238) next to email and WhatsApp: Profile &
|
||||
Security → Two-factor → "An authenticator app" shows a QR code (drawn in the browser) and the key;
|
||||
the app's first code confirms it. Codes can't be used twice; nothing is sent, so there's no resend.
|
||||
The secret is stored encrypted (`User.totpSecret`).
|
||||
- **Recovery codes**: 10 single-use codes each time two-factor is turned on (any method), shown
|
||||
once with Download and Copy; one works at sign-in in place of any code ("Use a recovery code").
|
||||
A new set from Profile & Security (password needed). Using one, and making a new set, show in
|
||||
the account's activity.
|
||||
- **Admins see each account's method** in Users ("2FA: app / email / WhatsApp"); Reset 2FA also
|
||||
removes the app's secret and the recovery codes.
|
||||
- API (v2): `authenticator` in `/me/two-factor/enable` (answers with `secret` and `otpauthUrl`),
|
||||
`recoveryCodes` from `/me/two-factor/confirm`, `POST /me/two-factor/recovery-codes`;
|
||||
`twoFactorMethod` and `recoveryCodesLeft` on `/me`, `twoFactorMethod` on users.
|
||||
- Migration `20261118150000_authenticator_app`.
|
||||
- `env.template.json`: every `.env` variable with its layer, for installs and updates from the Hub.
|
||||
- `scripts/export-church.ts`: the church's data as `crosscode.church-export/1` (for `crosscode export`).
|
||||
- A site installed from the Hub registers by itself on first start when `HUB_LICENCE_KEY` is set
|
||||
|
||||
@@ -12,6 +12,17 @@ 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".
|
||||
-->
|
||||
|
||||
## 2.3.0
|
||||
|
||||
- **Sign in with an authenticator app.** Two-factor sign-in can now use an app on your phone
|
||||
(Google Authenticator, Microsoft Authenticator, 1Password and others) instead of a code by email
|
||||
or WhatsApp. It's the most secure option and works without signal. Set it up under Profile &
|
||||
Security.
|
||||
- **Recovery codes.** When you turn on two-factor you get 10 single-use recovery codes to keep
|
||||
somewhere safe: if you lose your phone, one of them lets you sign in.
|
||||
- **Admins can see how each person signs in**: the Users page shows whether each account uses an
|
||||
app, email or WhatsApp for its codes.
|
||||
|
||||
## 2.2.0
|
||||
|
||||
- **AI use is now shown in tokens.** Site settings → AI shows how much of this month's AI allowance
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "2.2.0",
|
||||
"version": "2.3.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
-- 2.3.0: two-factor with an authenticator app (TOTP), and recovery codes.
|
||||
ALTER TYPE "TwoFactorMethod" ADD VALUE 'authenticator';
|
||||
ALTER TABLE "User" ADD COLUMN "totpSecret" TEXT;
|
||||
ALTER TABLE "User" ADD COLUMN "totpLastStep" INTEGER;
|
||||
ALTER TABLE "TwoFactorChallenge" ADD COLUMN "pendingSecret" TEXT;
|
||||
CREATE TABLE "RecoveryCode" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"codeHash" TEXT NOT NULL,
|
||||
"usedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "RecoveryCode_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
CREATE UNIQUE INDEX "RecoveryCode_codeHash_key" ON "RecoveryCode"("codeHash");
|
||||
CREATE INDEX "RecoveryCode_userId_idx" ON "RecoveryCode"("userId");
|
||||
ALTER TABLE "RecoveryCode" ADD CONSTRAINT "RecoveryCode_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TYPE "SecurityEventType" ADD VALUE 'recovery_code_used';
|
||||
ALTER TYPE "SecurityEventType" ADD VALUE 'recovery_codes_replaced';
|
||||
@@ -52,11 +52,16 @@ enum SecurityEventType {
|
||||
password_reset
|
||||
two_factor_enabled
|
||||
two_factor_disabled
|
||||
// 2.3.0: a recovery code signed in (the app or phone may be lost); a new set was made.
|
||||
recovery_code_used
|
||||
recovery_codes_replaced
|
||||
}
|
||||
|
||||
enum TwoFactorMethod {
|
||||
email
|
||||
whatsapp
|
||||
// 2.3.0: codes from an authenticator app (TOTP); nothing is sent.
|
||||
authenticator
|
||||
}
|
||||
|
||||
model User {
|
||||
@@ -75,6 +80,11 @@ model User {
|
||||
notificationPreference NotificationPreference @default(email)
|
||||
twoFactorEnabled Boolean @default(false)
|
||||
twoFactorMethod TwoFactorMethod?
|
||||
// 2.3.0: the authenticator app's secret (encrypted, utils/encryption.js) and the last 30-second
|
||||
// step a code was used for, so a code can't be used twice.
|
||||
totpSecret String?
|
||||
totpLastStep Int?
|
||||
recoveryCodes RecoveryCode[]
|
||||
// POPIA: opted in to "News & announcements" (marketing) bulk messages, per channel.
|
||||
// Event updates to registrants don't depend on these. History in CommunicationConsent.
|
||||
newsEmail Boolean @default(false)
|
||||
@@ -713,6 +723,8 @@ model TwoFactorChallenge {
|
||||
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())
|
||||
@@ -2353,3 +2365,15 @@ model AiCall {
|
||||
@@index([createdAt])
|
||||
@@index([userId, createdAt])
|
||||
}
|
||||
|
||||
// 2.3.0: single-use codes for when the authenticator app (or phone) is lost. Only an HMAC is kept.
|
||||
model RecoveryCode {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
codeHash String @unique
|
||||
usedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
@@ -11,6 +11,9 @@ const {
|
||||
resendChallenge,
|
||||
clearTrustedDevices,
|
||||
requiresTwoFactor,
|
||||
replaceRecoveryCodes,
|
||||
recoveryCodesLeft,
|
||||
clearTwoFactor,
|
||||
} = require('../utils/twoFactor');
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
@@ -99,7 +102,7 @@ const startEnableTwoFactor = async (req, res) => {
|
||||
}
|
||||
if (!TWO_FACTOR_METHODS.includes(method)) {
|
||||
res.status(400);
|
||||
throw new Error('Choose email or WhatsApp for your verification codes');
|
||||
throw new Error('Choose email, WhatsApp or an authenticator app for your verification codes');
|
||||
}
|
||||
if (!(await availableMethods(user)).includes(method)) {
|
||||
res.status(400);
|
||||
@@ -109,7 +112,8 @@ const startEnableTwoFactor = async (req, res) => {
|
||||
}
|
||||
|
||||
// Unlike login, don't fall back to email here — the point of this step is to
|
||||
// prove the channel the user picked actually reaches them.
|
||||
// prove the channel the user picked actually reaches them. For an authenticator app the
|
||||
// answer carries the secret and its otpauth:// link (shown as a QR code) until confirmed.
|
||||
res.json(await createChallenge(user, 'enable', method, { allowFallback: false }));
|
||||
} catch (error) {
|
||||
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
|
||||
@@ -124,13 +128,20 @@ const confirmEnableTwoFactor = async (req, res) => {
|
||||
const { challengeId, code } = req.body || {};
|
||||
const challenge = await verifyChallenge(challengeId, code, 'enable', req.user.id);
|
||||
|
||||
// An authenticator app: the confirmed secret is kept (encrypted). Another method: any app is
|
||||
// forgotten. Either way a fresh set of recovery codes, shown once (2.3.0).
|
||||
await prisma.user.update({
|
||||
where: { id: req.user.id },
|
||||
data: { twoFactorEnabled: true, twoFactorMethod: challenge.method, updatedAt: new Date() },
|
||||
data: {
|
||||
twoFactorEnabled: true, twoFactorMethod: challenge.method, updatedAt: new Date(),
|
||||
...(challenge.method === 'authenticator' ? { totpSecret: challenge.pendingSecret } : { totpSecret: null, totpLastStep: null }),
|
||||
},
|
||||
});
|
||||
await prisma.twoFactorChallenge.update({ where: { id: challenge.id }, data: { pendingSecret: null } }).catch(() => {});
|
||||
const recoveryCodes = await replaceRecoveryCodes(req.user.id);
|
||||
logSecurityEvent({ userId: req.user.id, type: 'two_factor_enabled', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
|
||||
|
||||
res.json({ twoFactorEnabled: true, twoFactorMethod: challenge.method });
|
||||
res.json({ twoFactorEnabled: true, twoFactorMethod: challenge.method, recoveryCodes });
|
||||
} catch (error) {
|
||||
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
@@ -157,7 +168,7 @@ const disableTwoFactor = async (req, res) => {
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { twoFactorEnabled: false, twoFactorMethod: null, updatedAt: new Date() },
|
||||
data: { ...(await clearTwoFactor(user.id)), updatedAt: new Date() },
|
||||
});
|
||||
await clearTrustedDevices(user.id);
|
||||
if (user.twoFactorEnabled) {
|
||||
@@ -170,6 +181,27 @@ const disableTwoFactor = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
// @desc A new set of recovery codes (the old ones stop working), shown once (2.3.0)
|
||||
// @route POST /api/v2/me/two-factor/recovery-codes
|
||||
// @access Private
|
||||
const replaceMyRecoveryCodes = async (req, res) => {
|
||||
try {
|
||||
const { password } = req.body || {};
|
||||
const user = await prisma.user.findUnique({ where: { id: req.user.id } });
|
||||
if (!user) { res.status(404); throw new Error('User not found'); }
|
||||
if (!user.twoFactorEnabled) { res.status(400); throw new Error('Turn on two-factor authentication first.'); }
|
||||
if (typeof password !== 'string' || !(await comparePassword(password, user.password))) {
|
||||
res.status(400);
|
||||
throw new Error('Incorrect password');
|
||||
}
|
||||
const recoveryCodes = await replaceRecoveryCodes(user.id);
|
||||
logSecurityEvent({ userId: user.id, type: 'recovery_codes_replaced', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
|
||||
res.json({ recoveryCodes });
|
||||
} catch (error) {
|
||||
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Re-confirm the logged-in user's password without starting a new session
|
||||
// (the self-service kiosk uses this before letting the event be changed)
|
||||
// @route POST /api/users/verify-password
|
||||
@@ -220,7 +252,7 @@ const getUserProfile = async (req, res) => {
|
||||
const noticePromptPending = !req.impersonation && await require('../utils/privacyNotice').noticePromptPending({ noticeVersionAccepted });
|
||||
// Campus-scoped staff: the campuses they're limited to (null = every campus).
|
||||
const campusScope = (await require('../utils/campusScope').scopeFor(req))?.campusIds || null;
|
||||
res.json({ ...rest, twoFactorRequired: requiresTwoFactor(user), newsPromptPending: !newsAskedAt && !req.impersonation, noticePromptPending, campusScope });
|
||||
res.json({ ...rest, twoFactorRequired: requiresTwoFactor(user), recoveryCodesLeft: user.twoFactorEnabled ? await recoveryCodesLeft(user.id) : 0, newsPromptPending: !newsAskedAt && !req.impersonation, noticePromptPending, campusScope });
|
||||
} else {
|
||||
res.status(404);
|
||||
throw new Error('User not found');
|
||||
@@ -253,7 +285,7 @@ const getUsers = async (req, res) => {
|
||||
|
||||
const select = {
|
||||
id: true, name: true, email: true, role: true,
|
||||
phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, createdAt: true, updatedAt: true, isActive: true
|
||||
phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, twoFactorMethod: true, createdAt: true, updatedAt: true, isActive: true
|
||||
};
|
||||
|
||||
// Build filters
|
||||
@@ -406,8 +438,8 @@ const updateUser = async (req, res) => {
|
||||
// but never on — enabling requires the user to prove the channel themselves.
|
||||
const resetTwoFactor = twoFactorEnabled === false && user.twoFactorEnabled;
|
||||
if (resetTwoFactor) {
|
||||
data.twoFactorEnabled = false;
|
||||
data.twoFactorMethod = null;
|
||||
// The app's secret and the recovery codes go too (2.3.0).
|
||||
Object.assign(data, await clearTwoFactor(user.id));
|
||||
}
|
||||
|
||||
// Promoted to a role that requires 2FA without having it: end their sessions
|
||||
@@ -443,6 +475,7 @@ const updateUser = async (req, res) => {
|
||||
phoneNumber: true,
|
||||
notificationPreference: true,
|
||||
twoFactorEnabled: true,
|
||||
twoFactorMethod: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
isActive: true,
|
||||
@@ -820,6 +853,7 @@ module.exports = {
|
||||
startEnableTwoFactor,
|
||||
confirmEnableTwoFactor,
|
||||
disableTwoFactor,
|
||||
replaceMyRecoveryCodes,
|
||||
verifyPassword,
|
||||
getUserProfile,
|
||||
updateUserProfile,
|
||||
|
||||
@@ -16,7 +16,8 @@ const auth = require('../config/auth') as {
|
||||
};
|
||||
const twoFactor = require('../utils/twoFactor') as {
|
||||
createChallenge(user: any, purpose: string, method: string): Promise<{ challengeId: string; method: string; destination: string | null }>;
|
||||
verifyChallenge(challengeId: string, code: string, purpose: string): Promise<{ userId: string; method: string }>;
|
||||
verifyChallenge(challengeId: string, code: string, purpose: string): Promise<{ userId: string; method: string; usedRecoveryCode?: boolean }>;
|
||||
recoveryCodesLeft(userId: string): Promise<number>;
|
||||
issueTrustedDevice(userId: string, userAgent?: string): Promise<string>;
|
||||
isTrustedDevice(userId: string, deviceToken?: string): Promise<boolean>;
|
||||
clearTrustedDevices(userId: string): Promise<unknown>;
|
||||
@@ -279,6 +280,10 @@ export async function verifyLoginCode(input: { challengeId: string; code: string
|
||||
user = await prisma.user.update({ where: { id: user.id }, data: { twoFactorEnabled: true, twoFactorMethod: challenge.method as 'email' | 'whatsapp', updatedAt: new Date() }, select: LOGIN_USER_SELECT });
|
||||
logSecurityEvent({ userId: user.id, type: 'two_factor_enabled', ip: info.ip, userAgent: info.userAgent }).catch(() => {});
|
||||
}
|
||||
// 2.3.0: a recovery code was used instead (the app or phone may be lost): it's in the activity log.
|
||||
if (challenge.usedRecoveryCode) {
|
||||
logSecurityEvent({ userId: user.id, type: 'recovery_code_used', ip: info.ip, userAgent: info.userAgent }).catch(() => {});
|
||||
}
|
||||
const extra = input.rememberDevice === true ? { deviceToken: await twoFactor.issueTrustedDevice(user.id, info.userAgent) } : {};
|
||||
return completeLogin(user, info, extra);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Codes from an authenticator app (2.3.0; RFC 6238 TOTP: SHA-1, 6 digits, 30 seconds), the same
|
||||
* as Cross Code Hub's. `matchStep` says which 30-second step a code belongs to, so a code that was
|
||||
* used once is refused the second time (utils/twoFactor.js keeps the last step used).
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
const STEP = 30;
|
||||
|
||||
function base32Encode(buf) {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
let out = '';
|
||||
for (const byte of buf) {
|
||||
value = (value << 8) | byte;
|
||||
bits += 8;
|
||||
while (bits >= 5) {
|
||||
out += BASE32[(value >>> (bits - 5)) & 31];
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
if (bits > 0) out += BASE32[(value << (5 - bits)) & 31];
|
||||
return out;
|
||||
}
|
||||
|
||||
function base32Decode(str) {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
const out = [];
|
||||
for (const ch of String(str).toUpperCase().replace(/=+$/, '')) {
|
||||
const idx = BASE32.indexOf(ch);
|
||||
if (idx === -1) continue;
|
||||
value = (value << 5) | idx;
|
||||
bits += 5;
|
||||
if (bits >= 8) {
|
||||
out.push((value >>> (bits - 8)) & 255);
|
||||
bits -= 8;
|
||||
}
|
||||
}
|
||||
return Buffer.from(out);
|
||||
}
|
||||
|
||||
/** A new secret: 20 random bytes, base32 (what the app stores). */
|
||||
function generateSecret() {
|
||||
return base32Encode(crypto.randomBytes(20));
|
||||
}
|
||||
|
||||
function codeAt(secret, counter) {
|
||||
const buf = Buffer.alloc(8);
|
||||
buf.writeBigUInt64BE(BigInt(counter));
|
||||
const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest();
|
||||
const offset = hmac[hmac.length - 1] & 0xf;
|
||||
const num = ((hmac[offset] & 0x7f) << 24) | (hmac[offset + 1] << 16) | (hmac[offset + 2] << 8) | hmac[offset + 3];
|
||||
return String(num % 1_000_000).padStart(6, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* The step `code` is right for (now, or one step either side for clock drift), or null. Steps at
|
||||
* or before `afterStep` don't count: that code was already used.
|
||||
*/
|
||||
function matchStep(secret, code, { now = Date.now(), afterStep = -1 } = {}) {
|
||||
const clean = String(code || '').replace(/\D/g, '');
|
||||
if (clean.length !== 6) return null;
|
||||
const counter = Math.floor(now / 1000 / STEP);
|
||||
for (const c of [counter - 1, counter, counter + 1]) {
|
||||
if (c <= afterStep) continue;
|
||||
if (crypto.timingSafeEqual(Buffer.from(codeAt(secret, c)), Buffer.from(clean))) return c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The otpauth:// link an authenticator app scans (as a QR code). */
|
||||
function otpauthUrl(secret, account, issuer) {
|
||||
const label = `${issuer}:${account}`;
|
||||
return `otpauth://totp/${encodeURIComponent(label)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
|
||||
}
|
||||
|
||||
module.exports = { STEP, generateSecret, codeAt, matchStep, otpauthUrl, base32Encode, base32Decode };
|
||||
@@ -16,7 +16,9 @@ const RESEND_COOLDOWN_MS = 60 * 1000; // minimum gap between sends
|
||||
const CHALLENGE_MAX_AGE_MS = 30 * 60 * 1000; // after this, log in again rather than resend
|
||||
const TRUSTED_DEVICE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
const METHODS = ['email', 'whatsapp'];
|
||||
// 2.3.0: 'authenticator' — codes from an app (TOTP, utils/totp.js); nothing is sent.
|
||||
const METHODS = ['email', 'whatsapp', 'authenticator'];
|
||||
const RECOVERY_CODE_COUNT = 10;
|
||||
|
||||
// Roles that must use two-factor authentication.
|
||||
const REQUIRED_ROLES = ['admin', 'supervisor'];
|
||||
@@ -67,9 +69,75 @@ async function availableMethods(user) {
|
||||
const methods = [];
|
||||
if (hasRealEmail(user)) methods.push('email');
|
||||
if (isValidZAPhone(user?.phoneNumber) && (await isConfigured())) methods.push('whatsapp');
|
||||
// An authenticator app needs nothing from the site, so it's always possible.
|
||||
methods.push('authenticator');
|
||||
return methods;
|
||||
}
|
||||
|
||||
// ─── Authenticator app (2.3.0) ───────────────────────────────────────────────
|
||||
|
||||
const totp = require('./totp');
|
||||
const { encrypt, decrypt } = require('./encryption');
|
||||
|
||||
/** A new secret for setting up an app, with the link and text to show (not saved yet). */
|
||||
function newAuthenticatorSecret(user) {
|
||||
const { getSettingSync } = require('./settingsCache');
|
||||
const issuer = getSettingSync('org_name', process.env.ORG_NAME || 'Cross Events');
|
||||
const secret = totp.generateSecret();
|
||||
return { secret, otpauthUrl: totp.otpauthUrl(secret, user.email, issuer) };
|
||||
}
|
||||
|
||||
// Recovery codes: xxxxx-xxxxx from an alphabet without look-alikes; stored as an HMAC.
|
||||
const RECOVERY_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';
|
||||
const normaliseRecovery = (code) => String(code || '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
const hashRecovery = (code) => hmac(`2fa-recovery:${normaliseRecovery(code)}`);
|
||||
const looksLikeRecoveryCode = (code) => normaliseRecovery(code).length === 10;
|
||||
|
||||
function randomRecoveryCode() {
|
||||
let s = '';
|
||||
for (let i = 0; i < 10; i++) s += RECOVERY_ALPHABET[crypto.randomInt(0, RECOVERY_ALPHABET.length)];
|
||||
return `${s.slice(0, 5)}-${s.slice(5)}`;
|
||||
}
|
||||
|
||||
/** A new set of recovery codes (the old ones stop working). Returns the codes to show once. */
|
||||
async function replaceRecoveryCodes(userId, db = prisma) {
|
||||
const codes = Array.from({ length: RECOVERY_CODE_COUNT }, randomRecoveryCode);
|
||||
await db.recoveryCode.deleteMany({ where: { userId } });
|
||||
await db.recoveryCode.createMany({ data: codes.map(c => ({ userId, codeHash: hashRecovery(c) })) });
|
||||
return codes;
|
||||
}
|
||||
|
||||
async function recoveryCodesLeft(userId) {
|
||||
return prisma.recoveryCode.count({ where: { userId, usedAt: null } });
|
||||
}
|
||||
|
||||
/** Uses a recovery code if it's one of this user's unused ones (single use, race-safe). */
|
||||
async function useRecoveryCode(userId, code) {
|
||||
if (!looksLikeRecoveryCode(code)) return false;
|
||||
const used = await prisma.recoveryCode.updateMany({ where: { userId, codeHash: hashRecovery(code), usedAt: null }, data: { usedAt: new Date() } });
|
||||
return used.count === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks an app code against `secret` and records its step, so the same code can't be used again
|
||||
* (the update only succeeds if no later step was recorded meanwhile).
|
||||
*/
|
||||
async function useAuthenticatorCode(user, secret, code) {
|
||||
const step = totp.matchStep(secret, code, { afterStep: user.totpLastStep ?? -1 });
|
||||
if (step === null) return false;
|
||||
const saved = await prisma.user.updateMany({
|
||||
where: { id: user.id, OR: [{ totpLastStep: null }, { totpLastStep: { lt: step } }] },
|
||||
data: { totpLastStep: step },
|
||||
});
|
||||
return saved.count === 1;
|
||||
}
|
||||
|
||||
/** Turns 2FA off completely: the app's secret and the recovery codes go too. */
|
||||
async function clearTwoFactor(userId, db = prisma) {
|
||||
await db.recoveryCode.deleteMany({ where: { userId } });
|
||||
return { twoFactorEnabled: false, twoFactorMethod: null, totpSecret: null, totpLastStep: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* True when this user's role must use two-factor authentication.
|
||||
* TWO_FACTOR_REQUIRED_ROLES=false turns the requirement off (break-glass).
|
||||
@@ -143,6 +211,20 @@ async function deliverCode(user, method, code, { allowFallback = true } = {}) {
|
||||
* purpose for this user is discarded, so only the newest code works.
|
||||
*/
|
||||
async function createChallenge(user, purpose, method, options) {
|
||||
if (method === 'authenticator') {
|
||||
// Nothing is sent: the code comes from the app. Setting it up carries the new secret,
|
||||
// encrypted, until the first code proves the app has it.
|
||||
const setup = purpose === 'enable' ? newAuthenticatorSecret(user) : null;
|
||||
// (Looked up here: the user passed in may be a selection that leaves the secret out.)
|
||||
if (purpose !== 'enable' && !(await prisma.user.findUnique({ where: { id: user.id }, select: { totpSecret: true } }))?.totpSecret) {
|
||||
throw fail('No authenticator app is set up for this account.', 400);
|
||||
}
|
||||
await prisma.twoFactorChallenge.deleteMany({ where: { userId: user.id, purpose } });
|
||||
const challenge = await prisma.twoFactorChallenge.create({
|
||||
data: { userId: user.id, purpose, method: 'authenticator', codeHash: '', pendingSecret: setup ? encrypt(setup.secret) : null, expiresAt: new Date(Date.now() + CODE_TTL_MS) },
|
||||
});
|
||||
return { challengeId: challenge.id, method: 'authenticator', destination: 'your authenticator app', ...(setup ? { secret: setup.secret, otpauthUrl: setup.otpauthUrl } : {}) };
|
||||
}
|
||||
const code = generateCode();
|
||||
const sent = await deliverCode(user, method, code, options);
|
||||
|
||||
@@ -185,9 +267,23 @@ async function verifyChallenge(challengeId, code, purpose, userId) {
|
||||
if (counted.count !== 1) throw invalid();
|
||||
|
||||
const challenge = await prisma.twoFactorChallenge.findUnique({ where: { id: challengeId }, include: { user: true } });
|
||||
if (!challenge || !safeEqual(challenge.codeHash, hashCode(submitted))) {
|
||||
let ok = false;
|
||||
let usedRecoveryCode = false;
|
||||
if (challenge?.method === 'authenticator') {
|
||||
const stored = purpose === 'enable' ? challenge.pendingSecret : challenge.user?.totpSecret;
|
||||
ok = !!stored && (await useAuthenticatorCode(challenge.user, decrypt(stored), submitted));
|
||||
} else if (challenge) {
|
||||
ok = safeEqual(challenge.codeHash, hashCode(submitted));
|
||||
}
|
||||
// At sign-in, a recovery code works in place of any code (2.3.0).
|
||||
if (!ok && challenge && purpose === 'login' && challenge.user?.twoFactorEnabled && (await useRecoveryCode(challenge.userId, code))) {
|
||||
ok = true;
|
||||
usedRecoveryCode = true;
|
||||
}
|
||||
if (!ok) {
|
||||
const left = challenge ? MAX_ATTEMPTS - challenge.attempts : 0;
|
||||
throw fail(left > 0 ? `Incorrect code. ${left} attempt${left === 1 ? '' : 's'} left.` : 'Too many incorrect attempts. Please request a new code.');
|
||||
const again = challenge?.method === 'authenticator' ? 'Please log in again.' : 'Please request a new code.';
|
||||
throw fail(left > 0 ? `Incorrect code. ${left} attempt${left === 1 ? '' : 's'} left.` : `Too many incorrect attempts. ${again}`);
|
||||
}
|
||||
|
||||
// Single use — if two requests race with the right code, only one wins.
|
||||
@@ -197,7 +293,7 @@ async function verifyChallenge(challengeId, code, purpose, userId) {
|
||||
});
|
||||
if (used.count !== 1) throw invalid();
|
||||
|
||||
return challenge;
|
||||
return { ...challenge, usedRecoveryCode };
|
||||
}
|
||||
|
||||
/** Replaces the code on an existing challenge and sends it again. */
|
||||
@@ -208,6 +304,7 @@ async function resendChallenge(challengeId, purpose, userId) {
|
||||
const challenge = await prisma.twoFactorChallenge.findUnique({ where: { id: challengeId }, include: { user: true } });
|
||||
if (!challenge || challenge.purpose !== purpose || challenge.usedAt || (userId && challenge.userId !== userId)) throw expired();
|
||||
if (Date.now() - challenge.createdAt.getTime() > CHALLENGE_MAX_AGE_MS) throw expired();
|
||||
if (challenge.method === 'authenticator') throw fail('Nothing is sent for an authenticator app: open the app for the current code, or use one of your recovery codes.');
|
||||
|
||||
const wait = RESEND_COOLDOWN_MS - (Date.now() - challenge.lastSentAt.getTime());
|
||||
if (wait > 0) throw fail(`Please wait ${Math.ceil(wait / 1000)} seconds before requesting another code.`, 429);
|
||||
@@ -264,6 +361,13 @@ async function clearTrustedDevices(userId) {
|
||||
|
||||
module.exports = {
|
||||
METHODS,
|
||||
RECOVERY_CODE_COUNT,
|
||||
replaceRecoveryCodes,
|
||||
recoveryCodesLeft,
|
||||
useRecoveryCode,
|
||||
useAuthenticatorCode,
|
||||
clearTwoFactor,
|
||||
newAuthenticatorSecret,
|
||||
REQUIRED_ROLES,
|
||||
requiresTwoFactor,
|
||||
enforcementMethod,
|
||||
|
||||
@@ -51,6 +51,8 @@ export const user = obj({
|
||||
role: z.enum(['admin', 'supervisor', 'staff', 'user']),
|
||||
isActive: optBool,
|
||||
notificationPreference: z.enum(['email', 'whatsapp', 'both']).nullish(),
|
||||
twoFactorEnabled: optBool,
|
||||
twoFactorMethod: z.enum(['email', 'whatsapp', 'authenticator']).nullish().describe('How their sign-in codes come (2.3.0: authenticator = an app)'),
|
||||
homeCampusId: optStr,
|
||||
createdAt: optDate,
|
||||
});
|
||||
|
||||
@@ -26,7 +26,7 @@ const toMe = (u: MeRow): z.input<typeof me> => ({
|
||||
});
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */
|
||||
const { requiresTwoFactor } = require('../../utils/twoFactor') as { requiresTwoFactor(user: object): boolean };
|
||||
const { requiresTwoFactor, recoveryCodesLeft } = require('../../utils/twoFactor') as { requiresTwoFactor(user: object): boolean; recoveryCodesLeft(userId: string): Promise<number> };
|
||||
const privacyNotice = require('../../utils/privacyNotice') as { noticePromptPending(u: { noticeVersionAccepted: unknown }): Promise<false | 'first' | 'updated'> };
|
||||
const campusScope = require('../../utils/campusScope') as { scopeFor(req: unknown): Promise<{ campusIds: string[] | null } | null> };
|
||||
|
||||
@@ -39,6 +39,8 @@ export const getMe = defineRoute({
|
||||
access: 'user',
|
||||
response: single(me.extend({
|
||||
twoFactorRequired: z.boolean().describe('Their role must use two-step sign-in'),
|
||||
twoFactorMethod: z.enum(['email', 'whatsapp', 'authenticator']).nullable().describe('How their codes come (2.3.0: authenticator = an app)'),
|
||||
recoveryCodesLeft: z.number().int().describe('Unused recovery codes (0 with two-step sign-in off)'),
|
||||
newsPromptPending: z.boolean(),
|
||||
noticePromptPending: z.union([z.literal(false), z.enum(['first', 'updated'])]),
|
||||
campusScope: z.array(id).nullable(),
|
||||
@@ -54,6 +56,8 @@ export const getMe = defineRoute({
|
||||
data: {
|
||||
...toMe(u),
|
||||
twoFactorRequired: requiresTwoFactor(u),
|
||||
twoFactorMethod: u.twoFactorEnabled ? (u.twoFactorMethod ?? null) : null,
|
||||
recoveryCodesLeft: u.twoFactorEnabled ? await recoveryCodesLeft(u.id) : 0,
|
||||
newsPromptPending: !u.newsAskedAt && !impersonating,
|
||||
noticePromptPending: impersonating ? false as const : await privacyNotice.noticePromptPending({ noticeVersionAccepted: u.noticeVersionAccepted }),
|
||||
campusScope: (await campusScope.scopeFor(req))?.campusIds ?? null,
|
||||
|
||||
@@ -42,7 +42,7 @@ const SCOPE_LIST = 'scopeList (the handler filters by listWhere)';
|
||||
|
||||
// ─── Documented shapes (docs.ts) ─────────────────────────────────────────────
|
||||
|
||||
const challenge = D.obj({ challengeId: D.str, method: z.enum(['email', 'whatsapp']), destination: D.str.describe('Where the code went, partly hidden') });
|
||||
const challenge = D.obj({ challengeId: D.str, method: z.enum(['email', 'whatsapp', 'authenticator']), destination: D.str.describe('Where the code went, partly hidden') });
|
||||
const signedIn = D.obj({ message: D.optStr, id: D.str, name: D.str, email: D.str, role: D.str, token: D.str.describe('A new sign-in token') });
|
||||
const kind = z.enum(['update', 'news']).describe('update: about something they booked (always sent). news: needs their news consent');
|
||||
const attendeeFilter = D.obj({
|
||||
@@ -90,8 +90,9 @@ v1Route({ method: 'post', path: '/me/sessions/revoke', tag: 'Me', summary: 'Sign
|
||||
v1Route({ method: 'post', path: '/me/close', tag: 'Me', summary: 'Close my account', description: 'Needs the password. Personal details are removed; payment records stay, anonymised.', access: 'user', body: loose, documented: { body: D.obj({ password: D.str, deleteData: D.optBool.describe('Also ask for my personal information to be deleted') }), response: D.message }, v1: users.closeAccount });
|
||||
v1Route({ method: 'get', path: '/me/activity', tag: 'Me', summary: 'Recent sign-ins and changes to my account', access: 'user', documented: { response: z.array(D.obj({ id: D.str, type: D.str.describe('login, password_changed, two_factor_enabled…'), device: D.optStr, createdAt: D.date })) }, v1: users.getMyActivity });
|
||||
v1Route({ method: 'post', path: '/me/verify-password', tag: 'Me', summary: 'Check my password (before a sensitive change)', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.ok }, v1: users.verifyPassword });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/enable', tag: 'Me', summary: 'Start turning on two-step sign-in', description: 'Sends a code to confirm with.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ method: z.enum(['email', 'whatsapp']), password: D.str }), response: challenge }, v1: users.startEnableTwoFactor });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/confirm', tag: 'Me', summary: 'Confirm two-step sign-in with the code', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ challengeId: D.str, code: D.str }), response: D.obj({ twoFactorEnabled: z.literal(true), twoFactorMethod: D.str }) }, v1: users.confirmEnableTwoFactor });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/enable', tag: 'Me', summary: 'Start turning on two-step sign-in', description: 'Sends a code to confirm with, or for `authenticator` (2.3.0) answers with `secret` and `otpauthUrl` to show as a QR code; the app\x27s first code confirms it.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ method: z.enum(['email', 'whatsapp', 'authenticator']), password: D.str }), response: challenge.extend({ secret: D.optStr.describe('authenticator: the key to type in by hand'), otpauthUrl: D.optStr.describe('authenticator: show as a QR code') }) }, v1: users.startEnableTwoFactor });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/confirm', tag: 'Me', summary: 'Confirm two-step sign-in with the code', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ challengeId: D.str, code: D.str }), response: D.obj({ twoFactorEnabled: z.literal(true), twoFactorMethod: D.str, recoveryCodes: z.array(D.str).describe('Shown once: single-use codes for when the app or phone is lost') }) }, v1: users.confirmEnableTwoFactor });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/recovery-codes', tag: 'Me', summary: 'A new set of recovery codes', description: 'Needs the password. The old codes stop working; the new ones are shown once.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.obj({ recoveryCodes: z.array(D.str) }) }, v1: users.replaceMyRecoveryCodes });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/disable', tag: 'Me', summary: 'Turn off two-step sign-in', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.obj({ twoFactorEnabled: z.literal(false), twoFactorMethod: z.null() }) }, v1: users.disableTwoFactor });
|
||||
v1Route({
|
||||
method: 'get', path: '/users/exists', tag: 'Accounts', summary: 'Is there an account with this email or phone?',
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
// Two-factor with an authenticator app and recovery codes (2.3.0): setting it up, signing in with
|
||||
// the app's code (once only), recovery codes (single use), and turning it off.
|
||||
process.env.JWT_SECRET = 'test-secret';
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
function matches(row, where = {}) {
|
||||
return Object.entries(where).every(([key, cond]) => {
|
||||
if (key === 'OR') return cond.some(c => matches(row, c));
|
||||
const value = row[key];
|
||||
if (cond === null) return value == null;
|
||||
if (cond && typeof cond === 'object' && !(cond instanceof Date)) {
|
||||
if ('gt' in cond && !(value > cond.gt)) return false;
|
||||
if ('lt' in cond && !(value != null && value < cond.lt)) return false;
|
||||
return true;
|
||||
}
|
||||
return value === cond;
|
||||
});
|
||||
}
|
||||
|
||||
function model(defaults = () => ({})) {
|
||||
let rows = [];
|
||||
let seq = 0;
|
||||
const apply = (row, data) => { for (const [k, v] of Object.entries(data)) row[k] = v && typeof v === 'object' && 'increment' in v ? row[k] + v.increment : v; };
|
||||
return {
|
||||
rows: () => rows,
|
||||
reset: () => { rows = []; },
|
||||
create: async ({ data }) => { const r = { id: `id-${++seq}`, ...defaults(), ...data }; rows.push(r); return { ...r }; },
|
||||
createMany: async ({ data }) => { for (const d of data) rows.push({ id: `id-${++seq}`, ...defaults(), ...d }); return { count: data.length }; },
|
||||
findUnique: async ({ where, include, select }) => {
|
||||
const r = rows.find(x => matches(x, where));
|
||||
if (!r) return null;
|
||||
const out = { ...r };
|
||||
if (include?.user) out.user = { ...mockDb.user.rows().find(u => u.id === r.userId) };
|
||||
if (select) return Object.fromEntries(Object.keys(select).map(k => [k, r[k]]));
|
||||
return out;
|
||||
},
|
||||
update: async ({ where, data }) => { const r = rows.find(x => matches(x, where)); apply(r, data); return { ...r }; },
|
||||
updateMany: async ({ where, data }) => { const hit = rows.filter(x => matches(x, where)); hit.forEach(r => apply(r, data)); return { count: hit.length }; },
|
||||
deleteMany: async ({ where }) => { const before = rows.length; rows = rows.filter(x => !matches(x, where)); return { count: before - rows.length }; },
|
||||
count: async ({ where }) => rows.filter(x => matches(x, where)).length,
|
||||
};
|
||||
}
|
||||
|
||||
const mockDb = {
|
||||
user: model(),
|
||||
twoFactorChallenge: model(() => ({ attempts: 0, usedAt: null, lastSentAt: new Date(), createdAt: new Date(), pendingSecret: null })),
|
||||
recoveryCode: model(() => ({ usedAt: null, createdAt: new Date() })),
|
||||
trustedDevice: model(),
|
||||
};
|
||||
jest.mock('../src/config/db', () => mockDb);
|
||||
jest.mock('../src/utils/settingsCache', () => ({ getSettingSync: (_key, fallback) => fallback }));
|
||||
|
||||
const twoFactor = require('../src/utils/twoFactor');
|
||||
const totp = require('../src/utils/totp');
|
||||
const { decrypt } = require('../src/utils/encryption');
|
||||
|
||||
const STEP_MS = totp.STEP * 1000;
|
||||
const codeNow = (secret, offsetSteps = 0) => totp.codeAt(secret, Math.floor(Date.now() / STEP_MS) + offsetSteps);
|
||||
|
||||
beforeEach(() => {
|
||||
for (const m of Object.values(mockDb)) m.reset();
|
||||
mockDb.user.rows().push({ id: 'u1', name: 'Jane', email: 'jane@example.com', role: 'admin', twoFactorEnabled: false, totpSecret: null, totpLastStep: null });
|
||||
});
|
||||
|
||||
async function setUpApp() {
|
||||
const user = mockDb.user.rows()[0];
|
||||
const ch = await twoFactor.createChallenge(user, 'enable', 'authenticator');
|
||||
return { ch, user };
|
||||
}
|
||||
|
||||
describe('setting up an authenticator app', () => {
|
||||
test('gives a secret and an otpauth link, keeps it only encrypted, and sends nothing', async () => {
|
||||
const { ch } = await setUpApp();
|
||||
expect(ch).toMatchObject({ method: 'authenticator', destination: 'your authenticator app' });
|
||||
expect(ch.secret).toMatch(/^[A-Z2-7]{32}$/);
|
||||
expect(ch.otpauthUrl).toMatch(/^otpauth:\/\/totp\/.+secret=[A-Z2-7]{32}&issuer=/);
|
||||
const row = mockDb.twoFactorChallenge.rows()[0];
|
||||
expect(row.pendingSecret).not.toContain(ch.secret);
|
||||
expect(decrypt(row.pendingSecret)).toBe(ch.secret);
|
||||
});
|
||||
|
||||
test('the app\'s current code confirms it; a wrong code doesn\'t', async () => {
|
||||
const { ch } = await setUpApp();
|
||||
await expect(twoFactor.verifyChallenge(ch.challengeId, '000000', 'enable', 'u1')).rejects.toThrow(/Incorrect code/);
|
||||
const ok = await twoFactor.verifyChallenge(ch.challengeId, codeNow(ch.secret), 'enable', 'u1');
|
||||
expect(ok.method).toBe('authenticator');
|
||||
expect(decrypt(ok.pendingSecret)).toBe(ch.secret);
|
||||
});
|
||||
|
||||
test('resend is refused: nothing is sent for an app', async () => {
|
||||
const { ch } = await setUpApp();
|
||||
await expect(twoFactor.resendChallenge(ch.challengeId, 'enable', 'u1')).rejects.toThrow(/authenticator app/);
|
||||
});
|
||||
|
||||
test('it\'s always among the available methods', async () => {
|
||||
expect(await twoFactor.availableMethods({ email: 'x@guest.local', phoneNumber: null })).toEqual(['authenticator']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('signing in with the app', () => {
|
||||
let secret;
|
||||
beforeEach(async () => {
|
||||
const { ch } = await setUpApp();
|
||||
secret = ch.secret;
|
||||
Object.assign(mockDb.user.rows()[0], { twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: mockDb.twoFactorChallenge.rows()[0].pendingSecret });
|
||||
});
|
||||
|
||||
test('the current code works once; the same code again is refused', async () => {
|
||||
const user = mockDb.user.rows()[0];
|
||||
const a = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
expect(a.secret).toBeUndefined();
|
||||
const code = codeNow(secret);
|
||||
await expect(twoFactor.verifyChallenge(a.challengeId, code, 'login')).resolves.toMatchObject({ usedRecoveryCode: false });
|
||||
const b = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
await expect(twoFactor.verifyChallenge(b.challengeId, code, 'login')).rejects.toThrow(/Incorrect code/);
|
||||
});
|
||||
|
||||
test('a code from the step before still works (clock drift); one from two steps back doesn\'t', async () => {
|
||||
const user = mockDb.user.rows()[0];
|
||||
const a = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
await expect(twoFactor.verifyChallenge(a.challengeId, codeNow(secret, -2), 'login')).rejects.toThrow(/Incorrect/);
|
||||
await expect(twoFactor.verifyChallenge(a.challengeId, codeNow(secret, -1), 'login')).resolves.toBeTruthy();
|
||||
});
|
||||
|
||||
test('no app set up: signing in with it is refused', async () => {
|
||||
mockDb.user.rows()[0].totpSecret = null;
|
||||
await expect(twoFactor.createChallenge(mockDb.user.rows()[0], 'login', 'authenticator')).rejects.toThrow(/No authenticator app/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recovery codes', () => {
|
||||
test('ten codes, single use, accepted at sign-in in place of the app\'s code', async () => {
|
||||
const { ch } = await setUpApp();
|
||||
Object.assign(mockDb.user.rows()[0], { twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: mockDb.twoFactorChallenge.rows()[0].pendingSecret });
|
||||
const codes = await twoFactor.replaceRecoveryCodes('u1', mockDb);
|
||||
expect(codes).toHaveLength(10);
|
||||
expect(new Set(codes).size).toBe(10);
|
||||
codes.forEach(c => expect(c).toMatch(/^[a-z2-9]{5}-[a-z2-9]{5}$/));
|
||||
expect(JSON.stringify(mockDb.recoveryCode.rows())).not.toContain(codes[0]);
|
||||
|
||||
const user = mockDb.user.rows()[0];
|
||||
const a = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
await expect(twoFactor.verifyChallenge(a.challengeId, codes[3].toUpperCase().replace('-', ' '), 'login')).resolves.toMatchObject({ usedRecoveryCode: true });
|
||||
expect(await twoFactor.recoveryCodesLeft('u1')).toBe(9);
|
||||
const b = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
await expect(twoFactor.verifyChallenge(b.challengeId, codes[3], 'login')).rejects.toThrow(/Incorrect/);
|
||||
expect(ch).toBeTruthy();
|
||||
});
|
||||
|
||||
test('a new set replaces the old one', async () => {
|
||||
const first = await twoFactor.replaceRecoveryCodes('u1', mockDb);
|
||||
await twoFactor.replaceRecoveryCodes('u1', mockDb);
|
||||
expect(await twoFactor.useRecoveryCode('u1', first[0])).toBe(false);
|
||||
expect(await twoFactor.recoveryCodesLeft('u1')).toBe(10);
|
||||
});
|
||||
|
||||
test('turning 2FA off removes them and the app\'s secret', async () => {
|
||||
await twoFactor.replaceRecoveryCodes('u1', mockDb);
|
||||
const data = await twoFactor.clearTwoFactor('u1', mockDb);
|
||||
expect(data).toEqual({ twoFactorEnabled: false, twoFactorMethod: null, totpSecret: null, totpLastStep: null });
|
||||
expect(await twoFactor.recoveryCodesLeft('u1')).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -117,15 +117,15 @@ afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
describe('availableMethods', () => {
|
||||
test('offers WhatsApp only with a valid phone and a configured gateway', async () => {
|
||||
expect(await availableMethods(USER)).toEqual(['email', 'whatsapp']);
|
||||
expect(await availableMethods(USER)).toEqual(['email', 'whatsapp', 'authenticator']);
|
||||
mockWhatsApp.configured = false;
|
||||
expect(await availableMethods(USER)).toEqual(['email']);
|
||||
expect(await availableMethods(USER)).toEqual(['email', 'authenticator']);
|
||||
mockWhatsApp.configured = true;
|
||||
expect(await availableMethods({ ...USER, phoneNumber: null })).toEqual(['email']);
|
||||
expect(await availableMethods({ ...USER, phoneNumber: null })).toEqual(['email', 'authenticator']);
|
||||
});
|
||||
|
||||
test('offers nothing by email for a guest placeholder address', async () => {
|
||||
expect(await availableMethods({ ...USER, email: 'x@guest.local' })).toEqual(['whatsapp']);
|
||||
expect(await availableMethods({ ...USER, email: 'x@guest.local' })).toEqual(['whatsapp', 'authenticator']);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "2.2.0",
|
||||
"version": "2.3.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -23,6 +23,7 @@ interface UserItem {
|
||||
phoneNumber?: string | null;
|
||||
notificationPreference?: string;
|
||||
twoFactorEnabled?: boolean;
|
||||
twoFactorMethod?: "email" | "whatsapp" | "authenticator" | null;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -34,6 +35,8 @@ type Role = typeof roleOptions[number];
|
||||
const notificationPreferenceOptions = ["email", "whatsapp", "both"] as const;
|
||||
|
||||
|
||||
const TWO_FACTOR_LABEL: Record<"email" | "whatsapp" | "authenticator", string> = { email: "email", whatsapp: "WhatsApp", authenticator: "app" };
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
const { user, loading, token } = useAuth();
|
||||
const router = useRouter();
|
||||
@@ -418,6 +421,9 @@ export default function AdminUsersPage() {
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<RoleBadge role={u.role as RoleBadgeRole} />
|
||||
<div className="mt-1 text-xs text-gray-500" title="How their sign-in codes come">
|
||||
{u.twoFactorEnabled ? `2FA: ${TWO_FACTOR_LABEL[u.twoFactorMethod || "email"]}` : "No 2FA"}
|
||||
</div>
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<span>{u.phoneNumber || ""}</span>
|
||||
|
||||
@@ -14,17 +14,19 @@ import { useCampuses } from "@/hooks/useCampuses";
|
||||
import { apiV2, apiV2Data } from "@/lib/apiV2";
|
||||
import { useStateSync } from "@/lib/hooks";
|
||||
|
||||
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string };
|
||||
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled" | "recovery_code_used" | "recovery_codes_replaced"; device: string | null; createdAt: string };
|
||||
|
||||
const ACTIVITY_META: Record<ActivityEvent["type"], { label: (device: string | null) => string; icon: typeof LogIn }> = {
|
||||
login: { label: d => `Logged in${d ? ` from ${d}` : ""}`, icon: LogIn },
|
||||
password_changed: { label: () => "Password changed", icon: KeyRound },
|
||||
password_reset: { label: () => "Password reset via email link", icon: RotateCcw },
|
||||
two_factor_enabled: { label: () => "Two-factor authentication turned on", icon: ShieldCheck },
|
||||
recovery_code_used: { label: () => "Logged in with a recovery code", icon: ShieldAlert },
|
||||
recovery_codes_replaced: { label: () => "New recovery codes made", icon: ShieldCheck },
|
||||
two_factor_disabled: { label: () => "Two-factor authentication turned off", icon: ShieldOff },
|
||||
};
|
||||
|
||||
const TWO_FACTOR_METHOD_LABEL: Record<TwoFactorMethod, string> = { email: "email", whatsapp: "WhatsApp" };
|
||||
const TWO_FACTOR_METHOD_LABEL: Record<TwoFactorMethod, string> = { email: "email", whatsapp: "WhatsApp", authenticator: "an authenticator app" };
|
||||
|
||||
// Shared bits of the page (outside the component, so they aren't new components each render).
|
||||
const Alert = ({ msg }: { msg: { type: "ok" | "err"; text: string } }) => (
|
||||
@@ -185,12 +187,16 @@ export default function UserProfilePage() {
|
||||
// loaded once per page load, so it wouldn't reflect a change made here.
|
||||
const [tfEnabled, setTfEnabled] = useState(false);
|
||||
const [tfMethod, setTfMethod] = useState<TwoFactorMethod>("email");
|
||||
const [tfStep, setTfStep] = useState<"idle" | "code" | "disable" | "change">("idle");
|
||||
const [tfStep, setTfStep] = useState<"idle" | "code" | "disable" | "change" | "recovery">("idle");
|
||||
const [tfPassword, setTfPassword] = useState("");
|
||||
const [tfCode, setTfCode] = useState("");
|
||||
const [tfChallenge, setTfChallenge] = useState<TwoFactorChallenge | null>(null);
|
||||
const [tfMsg, setTfMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
|
||||
const [tfBusy, setTfBusy] = useState(false);
|
||||
// 2.3.0: recovery codes just made (shown once), how many are left, and the setup QR code.
|
||||
const [tfRecovery, setTfRecovery] = useState<string[] | null>(null);
|
||||
const [tfRecoveryLeft, setTfRecoveryLeft] = useState(0);
|
||||
const [tfQr, setTfQr] = useState<{ url: string; image: string } | null>(null);
|
||||
|
||||
// WhatsApp codes need the number that's actually saved, not one still being typed.
|
||||
const canWhatsAppCodes = isValidZAPhone(user?.phoneNumber || "");
|
||||
@@ -201,9 +207,19 @@ export default function UserProfilePage() {
|
||||
if (user) {
|
||||
setTfEnabled(!!user.twoFactorEnabled);
|
||||
setTfMethod(user.twoFactorMethod || "email");
|
||||
setTfRecoveryLeft((user as { recoveryCodesLeft?: number }).recoveryCodesLeft ?? 0);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// The setup QR code, drawn here from the otpauth:// link (the key never leaves the browser).
|
||||
useEffect(() => {
|
||||
const url = tfChallenge?.otpauthUrl;
|
||||
if (!url) return;
|
||||
let alive = true;
|
||||
import("qrcode").then(q => q.toDataURL(url, { margin: 1, width: 200 })).then(image => { if (alive) setTfQr({ url, image }); }).catch(() => {});
|
||||
return () => { alive = false; };
|
||||
}, [tfChallenge]);
|
||||
|
||||
const resetTwoFactorForm = () => {
|
||||
setTfStep("idle");
|
||||
setTfPassword("");
|
||||
@@ -241,12 +257,14 @@ export default function UserProfilePage() {
|
||||
const res = await (apiV2Data("post", "/me/two-factor/confirm", {
|
||||
authToken: token,
|
||||
body: { challengeId: tfChallenge.challengeId, code: tfCode },
|
||||
}) as Promise<{ twoFactorMethod: TwoFactorMethod }>);
|
||||
}) as Promise<{ twoFactorMethod: TwoFactorMethod; recoveryCodes?: string[] }>);
|
||||
const wasEnabled = tfEnabled;
|
||||
setTfEnabled(true);
|
||||
setTfMethod(res.twoFactorMethod);
|
||||
resetTwoFactorForm();
|
||||
setTfMsg({ type: "ok", text: wasEnabled ? `Codes will now be sent by ${TWO_FACTOR_METHOD_LABEL[res.twoFactorMethod]}.` : "Two-factor authentication is on." });
|
||||
setTfRecovery(res.recoveryCodes ?? null);
|
||||
setTfRecoveryLeft(res.recoveryCodes?.length ?? 0);
|
||||
setTfMsg({ type: "ok", text: wasEnabled ? `Your codes now come from ${TWO_FACTOR_METHOD_LABEL[res.twoFactorMethod]}.` : "Two-factor authentication is on." });
|
||||
loadActivity();
|
||||
} catch (e) {
|
||||
setTfMsg({ type: "err", text: errorMessage(e) || "Failed to verify the code." });
|
||||
@@ -255,6 +273,35 @@ export default function UserProfilePage() {
|
||||
}
|
||||
};
|
||||
|
||||
const newRecoveryCodes = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!token) return;
|
||||
setTfBusy(true);
|
||||
setTfMsg(null);
|
||||
try {
|
||||
const res = await (apiV2Data("post", "/me/two-factor/recovery-codes", { authToken: token, body: { password: tfPassword } }) as Promise<{ recoveryCodes: string[] }>);
|
||||
resetTwoFactorForm();
|
||||
setTfRecovery(res.recoveryCodes);
|
||||
setTfRecoveryLeft(res.recoveryCodes.length);
|
||||
loadActivity();
|
||||
} catch (e) {
|
||||
setTfMsg({ type: "err", text: errorMessage(e) || "Couldn't make new recovery codes." });
|
||||
} finally {
|
||||
setTfBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const downloadRecovery = () => {
|
||||
if (!tfRecovery) return;
|
||||
const text = `Recovery codes for ${user?.email || "your account"} (${window.location.host})\nEach works once, in place of a code, if you lose your phone or app.\n\n${tfRecovery.join("\n")}\n`;
|
||||
const url = URL.createObjectURL(new Blob([text], { type: "text/plain" }));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "recovery-codes.txt";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const disableTwoFactor = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!token) return;
|
||||
@@ -266,6 +313,7 @@ export default function UserProfilePage() {
|
||||
body: { password: tfPassword },
|
||||
});
|
||||
setTfEnabled(false);
|
||||
setTfRecoveryLeft(0);
|
||||
resetTwoFactorForm();
|
||||
setTfMsg({ type: "ok", text: "Two-factor authentication is off." });
|
||||
loadActivity();
|
||||
@@ -424,9 +472,20 @@ export default function UserProfilePage() {
|
||||
|
||||
{tfStep === "code" && tfChallenge ? (
|
||||
<form onSubmit={confirmEnableTwoFactor} className="space-y-4">
|
||||
<p className="text-sm text-gray-500">
|
||||
We sent a 6-digit code to {tfChallenge.destination} by {TWO_FACTOR_METHOD_LABEL[tfChallenge.method]}. {tfEnabled ? "Enter it to switch your codes to this channel." : "Enter it to finish turning on two-factor authentication."}
|
||||
</p>
|
||||
{tfChallenge.method === "authenticator" ? (
|
||||
<div className="space-y-3 text-sm text-gray-600">
|
||||
<p>Scan this with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password, Authy…), then enter the 6-digit code it shows.</p>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- a data: URL drawn in the browser */}
|
||||
{tfQr && tfQr.url === tfChallenge.otpauthUrl && <img src={tfQr.image} alt="QR code to add this account to an authenticator app" width={200} height={200} className="rounded border" />}
|
||||
{tfChallenge.secret && (
|
||||
<p className="text-xs">Can't scan it? Type this key into the app: <code className="select-all break-all rounded bg-gray-100 px-1 py-0.5 font-mono">{tfChallenge.secret.replace(/(.{4})/g, "$1 ").trim()}</code></p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">
|
||||
We sent a 6-digit code to {tfChallenge.destination} by {TWO_FACTOR_METHOD_LABEL[tfChallenge.method]}. {tfEnabled ? "Enter it to switch your codes to this channel." : "Enter it to finish turning on two-factor authentication."}
|
||||
</p>
|
||||
)}
|
||||
<div>
|
||||
<label htmlFor="profile-verification-code" className="block text-sm font-medium text-gray-700 mb-1">Verification code</label>
|
||||
<input
|
||||
@@ -446,16 +505,32 @@ export default function UserProfilePage() {
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" disabled={tfBusy || tfCode.length !== 6} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
|
||||
{tfBusy ? "Verifying…" : "Turn on two-factor"}
|
||||
{tfBusy ? "Verifying…" : tfEnabled ? "Switch" : "Turn on two-factor"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : tfEnabled && tfStep !== "change" ? (
|
||||
<>
|
||||
<p className="text-sm text-gray-500 mb-4">
|
||||
<span className="font-medium text-green-700">On.</span> When you log in we send a 6-digit code by{" "}
|
||||
{TWO_FACTOR_METHOD_LABEL[tfMethod]}. Devices you've chosen to trust skip the code for 30 days.
|
||||
<span className="font-medium text-green-700">On.</span>{" "}
|
||||
{tfMethod === "authenticator" ? "When you log in, enter the 6-digit code from your authenticator app." : <>When you log in we send a 6-digit code by {TWO_FACTOR_METHOD_LABEL[tfMethod]}.</>}{" "}
|
||||
Devices you've chosen to trust skip the code for 30 days.
|
||||
</p>
|
||||
<div className="mb-4 rounded-lg border border-gray-200 bg-gray-50 p-3 text-sm">
|
||||
<p className="text-gray-700"><span className="font-medium">Recovery codes:</span> {tfRecoveryLeft} of 10 left. Each works once in place of a code if you lose your phone or app.</p>
|
||||
{tfStep === "recovery" ? (
|
||||
<form onSubmit={newRecoveryCodes} className="mt-3 flex flex-wrap items-end gap-2">
|
||||
<div className="flex-1 min-w-[12rem]">
|
||||
<label htmlFor="profile-recovery-password" className="block text-xs font-medium text-gray-700 mb-1">Confirm with your password</label>
|
||||
<input id="profile-recovery-password" type="password" className={inputCls} value={tfPassword} onChange={e => setTfPassword(e.target.value)} required autoComplete="current-password" />
|
||||
</div>
|
||||
<button type="button" onClick={resetTwoFactorForm} className="px-3 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">Cancel</button>
|
||||
<button type="submit" disabled={tfBusy || !tfPassword} className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">{tfBusy ? "Making…" : "Make new codes"}</button>
|
||||
</form>
|
||||
) : (
|
||||
<button onClick={() => { setTfStep("recovery"); setTfPassword(""); setTfMsg(null); }} className="mt-2 text-sm text-brand-700 hover:underline">New recovery codes…</button>
|
||||
)}
|
||||
</div>
|
||||
{tfRequired ? (
|
||||
<>
|
||||
<p className="text-xs text-gray-500 mb-3">Required for your role, so it can't be turned off.</p>
|
||||
@@ -495,11 +570,12 @@ export default function UserProfilePage() {
|
||||
<p className="text-sm text-gray-500">
|
||||
{tfEnabled
|
||||
? "Choose where your login codes go. We'll send a code there first to check it reaches you."
|
||||
: "Add a second step to logging in: after your password, we send a 6-digit code that you need to enter."}
|
||||
: "Add a second step to logging in: after your password, a 6-digit code from an authenticator app, or one we send you."}
|
||||
</p>
|
||||
<div>
|
||||
<label htmlFor="profile-send-my-codes-by" className="block text-sm font-medium text-gray-700 mb-1">Send my codes by</label>
|
||||
<select id="profile-send-my-codes-by" className={inputCls} value={tfMethod} onChange={e => setTfMethod(e.target.value as TwoFactorMethod)}>
|
||||
<option value="authenticator">An authenticator app (most secure)</option>
|
||||
<option value="email">Email</option>
|
||||
{canWhatsAppCodes && <option value="whatsapp">WhatsApp</option>}
|
||||
</select>
|
||||
@@ -518,11 +594,23 @@ export default function UserProfilePage() {
|
||||
</button>
|
||||
)}
|
||||
<button type="submit" disabled={tfBusy || !tfPassword} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
|
||||
{tfBusy ? "Sending code…" : "Send verification code"}
|
||||
{tfBusy ? (tfMethod === "authenticator" ? "Preparing…" : "Sending code…") : tfMethod === "authenticator" ? "Set up the app" : "Send verification code"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{tfRecovery && (
|
||||
<div className="mt-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-sm" role="region" aria-label="Your recovery codes">
|
||||
<p className="font-medium text-amber-900">Save your recovery codes now</p>
|
||||
<p className="mt-1 text-amber-900">Each works once, in place of a code, if you lose your phone or app. They won't be shown again.</p>
|
||||
<ul className="mt-3 grid grid-cols-2 gap-x-6 gap-y-1 font-mono text-sm sm:grid-cols-3">{tfRecovery.map(c => <li key={c}>{c}</li>)}</ul>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" onClick={downloadRecovery} className="px-3 py-2 rounded-lg bg-white border border-amber-300 text-sm font-medium hover:bg-amber-100">Download</button>
|
||||
<button type="button" onClick={() => navigator.clipboard?.writeText(tfRecovery.join("\n"))} className="px-3 py-2 rounded-lg bg-white border border-amber-300 text-sm font-medium hover:bg-amber-100">Copy</button>
|
||||
<button type="button" onClick={() => setTfRecovery(null)} className="px-3 py-2 rounded-lg bg-amber-600 text-white text-sm font-medium hover:bg-amber-700">I've saved them</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tfMsg && <Alert msg={tfMsg} />}
|
||||
</section>
|
||||
|
||||
|
||||
@@ -27,6 +27,8 @@ export function LoginForm() {
|
||||
// Two-factor step — set once the password is accepted for an account with 2FA on.
|
||||
const [challenge, setChallenge] = useState<TwoFactorChallenge | null>(null);
|
||||
const [code, setCode] = useState("");
|
||||
// 2.3.0: a recovery code instead of the 6-digit code (xxxxx-xxxxx, single use).
|
||||
const [useRecovery, setUseRecovery] = useState(false);
|
||||
const [rememberDevice, setRememberDevice] = useState(false);
|
||||
const [resendIn, setResendIn] = useState(0);
|
||||
|
||||
@@ -109,6 +111,7 @@ export function LoginForm() {
|
||||
const backToPassword = () => {
|
||||
setChallenge(null);
|
||||
setCode("");
|
||||
setUseRecovery(false);
|
||||
setPassword("");
|
||||
setError(null);
|
||||
};
|
||||
@@ -124,20 +127,24 @@ export function LoginForm() {
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
We sent a 6-digit code to {challenge.destination} by {challenge.method === "whatsapp" ? "WhatsApp" : "email"}. It expires in 10 minutes.
|
||||
{useRecovery
|
||||
? "Enter one of the recovery codes you saved when you turned on two-factor. Each works once."
|
||||
: challenge.method === "authenticator"
|
||||
? "Open your authenticator app and enter the 6-digit code it shows for this site."
|
||||
: <>We sent a 6-digit code to {challenge.destination} by {challenge.method === "whatsapp" ? "WhatsApp" : "email"}. It expires in 10 minutes.</>}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="login-code" className="block text-sm font-medium mb-1">Verification code</label>
|
||||
<label htmlFor="login-code" className="block text-sm font-medium mb-1">{useRecovery ? "Recovery code" : "Verification code"}</label>
|
||||
<input
|
||||
id="login-code"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
inputMode={useRecovery ? "text" : "numeric"}
|
||||
autoComplete={useRecovery ? "off" : "one-time-code"}
|
||||
maxLength={useRecovery ? 11 : 6}
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
|
||||
onChange={(e) => setCode(useRecovery ? e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "") : e.target.value.replace(/\D/g, ""))}
|
||||
className="w-full border rounded px-3 py-2 text-lg tracking-widest"
|
||||
autoFocus
|
||||
required
|
||||
@@ -158,7 +165,7 @@ export function LoginForm() {
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || code.length !== 6}
|
||||
disabled={loading || (useRecovery ? code.replace(/-/g, "").length !== 10 : code.length !== 6)}
|
||||
className="w-full bg-brand-600 hover:bg-brand-700 text-white rounded py-2 disabled:opacity-60"
|
||||
>
|
||||
{loading ? "Verifying..." : "Verify and log in"}
|
||||
@@ -168,14 +175,21 @@ export function LoginForm() {
|
||||
<button type="button" onClick={backToPassword} className="text-brand-600 hover:underline">
|
||||
Back to login
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onResend}
|
||||
disabled={resendIn > 0}
|
||||
className="text-brand-600 hover:underline disabled:text-gray-400 disabled:no-underline"
|
||||
>
|
||||
{resendIn > 0 ? `Resend code in ${resendIn}s` : "Resend code"}
|
||||
</button>
|
||||
{!challenge.enrolling && (
|
||||
<button type="button" onClick={() => { setUseRecovery(!useRecovery); setCode(""); setError(null); }} className="text-brand-600 hover:underline">
|
||||
{useRecovery ? "Use a code instead" : "Use a recovery code"}
|
||||
</button>
|
||||
)}
|
||||
{challenge.method !== "authenticator" && !useRecovery && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onResend}
|
||||
disabled={resendIn > 0}
|
||||
className="text-brand-600 hover:underline disabled:text-gray-400 disabled:no-underline"
|
||||
>
|
||||
{resendIn > 0 ? `Resend code in ${resendIn}s` : "Resend code"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -12950,6 +12950,28 @@
|
||||
"type": "boolean",
|
||||
"description": "Their role must use two-step sign-in"
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "How their codes come (2.3.0: authenticator = an app)"
|
||||
},
|
||||
"recoveryCodesLeft": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991,
|
||||
"description": "Unused recovery codes (0 with two-step sign-in off)"
|
||||
},
|
||||
"newsPromptPending": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -12995,6 +13017,8 @@
|
||||
"homeCampusId",
|
||||
"createdAt",
|
||||
"twoFactorRequired",
|
||||
"twoFactorMethod",
|
||||
"recoveryCodesLeft",
|
||||
"newsPromptPending",
|
||||
"noticePromptPending",
|
||||
"campusScope"
|
||||
@@ -47764,7 +47788,8 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
"destination": {
|
||||
@@ -48395,7 +48420,7 @@
|
||||
"Me"
|
||||
],
|
||||
"summary": "Start turning on two-step sign-in",
|
||||
"description": "Sends a code to confirm with.\n\n**Who:** Any signed-in person.",
|
||||
"description": "Sends a code to confirm with, or for `authenticator` (2.3.0) answers with `secret` and `otpauthUrl` to show as a QR code; the app's first code confirms it.\n\n**Who:** Any signed-in person.",
|
||||
"operationId": "postMeTwo-factorEnable",
|
||||
"security": [
|
||||
{
|
||||
@@ -48414,7 +48439,8 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
"password": {
|
||||
@@ -48448,12 +48474,27 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
"destination": {
|
||||
"type": "string",
|
||||
"description": "Where the code went, partly hidden"
|
||||
},
|
||||
"secret": {
|
||||
"description": "authenticator: the key to type in by hand",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"otpauthUrl": {
|
||||
"description": "authenticator: show as a QR code",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -48549,11 +48590,107 @@
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"type": "string"
|
||||
},
|
||||
"recoveryCodes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Shown once: single-use codes for when the app or phone is lost"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"twoFactorEnabled",
|
||||
"twoFactorMethod"
|
||||
"twoFactorMethod",
|
||||
"recoveryCodes"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
}
|
||||
},
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/me/two-factor/recovery-codes": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Me"
|
||||
],
|
||||
"summary": "A new set of recovery codes",
|
||||
"description": "Needs the password. The old codes stop working; the new ones are shown once.\n\n**Who:** Any signed-in person.",
|
||||
"operationId": "postMeTwo-factorRecovery-codes",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"password": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"password"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"recoveryCodes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"recoveryCodes"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
}
|
||||
@@ -48975,6 +49112,28 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"twoFactorEnabled": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"description": "How their sign-in codes come (2.3.0: authenticator = an app)",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"homeCampusId": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -49148,6 +49307,28 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"twoFactorEnabled": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"description": "How their sign-in codes come (2.3.0: authenticator = an app)",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"homeCampusId": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -49385,6 +49566,28 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"twoFactorEnabled": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"description": "How their sign-in codes come (2.3.0: authenticator = an app)",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"homeCampusId": {
|
||||
"type": [
|
||||
"string",
|
||||
|
||||
+97
-4
@@ -4787,7 +4787,7 @@ export interface paths {
|
||||
put?: never;
|
||||
/**
|
||||
* Start turning on two-step sign-in
|
||||
* @description Sends a code to confirm with.
|
||||
* @description Sends a code to confirm with, or for `authenticator` (2.3.0) answers with `secret` and `otpauthUrl` to show as a QR code; the app's first code confirms it.
|
||||
*
|
||||
* **Who:** Any signed-in person.
|
||||
*/
|
||||
@@ -4818,6 +4818,28 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/me/two-factor/recovery-codes": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* A new set of recovery codes
|
||||
* @description Needs the password. The old codes stop working; the new ones are shown once.
|
||||
*
|
||||
* **Who:** Any signed-in person.
|
||||
*/
|
||||
post: operations["postMeTwo-factorRecovery-codes"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/me/two-factor/disable": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -12787,6 +12809,10 @@ export interface operations {
|
||||
createdAt: string;
|
||||
/** @description Their role must use two-step sign-in */
|
||||
twoFactorRequired: boolean;
|
||||
/** @description How their codes come (2.3.0: authenticator = an app) */
|
||||
twoFactorMethod: ("email" | "whatsapp" | "authenticator") | null;
|
||||
/** @description Unused recovery codes (0 with two-step sign-in off) */
|
||||
recoveryCodesLeft: number;
|
||||
newsPromptPending: boolean;
|
||||
noticePromptPending: false | ("first" | "updated");
|
||||
campusScope: string[] | null;
|
||||
@@ -28100,7 +28126,7 @@ export interface operations {
|
||||
data: {
|
||||
challengeId: string;
|
||||
/** @enum {string} */
|
||||
method: "email" | "whatsapp";
|
||||
method: "email" | "whatsapp" | "authenticator";
|
||||
/** @description Where the code went, partly hidden */
|
||||
destination: string;
|
||||
} & {
|
||||
@@ -28472,7 +28498,7 @@ export interface operations {
|
||||
content: {
|
||||
"application/json": {
|
||||
/** @enum {string} */
|
||||
method: "email" | "whatsapp";
|
||||
method: "email" | "whatsapp" | "authenticator";
|
||||
password: string;
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
@@ -28490,9 +28516,13 @@ export interface operations {
|
||||
data: {
|
||||
challengeId: string;
|
||||
/** @enum {string} */
|
||||
method: "email" | "whatsapp";
|
||||
method: "email" | "whatsapp" | "authenticator";
|
||||
/** @description Where the code went, partly hidden */
|
||||
destination: string;
|
||||
/** @description authenticator: the key to type in by hand */
|
||||
secret?: string | null;
|
||||
/** @description authenticator: show as a QR code */
|
||||
otpauthUrl?: string | null;
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
@@ -28548,6 +28578,60 @@ export interface operations {
|
||||
/** @constant */
|
||||
twoFactorEnabled: true;
|
||||
twoFactorMethod: string;
|
||||
/** @description Shown once: single-use codes for when the app or phone is lost */
|
||||
recoveryCodes: string[];
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @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"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postMeTwo-factorRecovery-codes": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
password: string;
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
recoveryCodes: string[];
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
@@ -28738,6 +28822,9 @@ export interface operations {
|
||||
role: "admin" | "supervisor" | "staff" | "user";
|
||||
isActive?: boolean | null;
|
||||
notificationPreference?: ("email" | "whatsapp" | "both") | null;
|
||||
twoFactorEnabled?: boolean | null;
|
||||
/** @description How their sign-in codes come (2.3.0: authenticator = an app) */
|
||||
twoFactorMethod?: ("email" | "whatsapp" | "authenticator") | null;
|
||||
homeCampusId?: string | null;
|
||||
createdAt?: string | null;
|
||||
} & {
|
||||
@@ -28810,6 +28897,9 @@ export interface operations {
|
||||
role: "admin" | "supervisor" | "staff" | "user";
|
||||
isActive?: boolean | null;
|
||||
notificationPreference?: ("email" | "whatsapp" | "both") | null;
|
||||
twoFactorEnabled?: boolean | null;
|
||||
/** @description How their sign-in codes come (2.3.0: authenticator = an app) */
|
||||
twoFactorMethod?: ("email" | "whatsapp" | "authenticator") | null;
|
||||
homeCampusId?: string | null;
|
||||
createdAt?: string | null;
|
||||
/** @description Campuses they're limited to */
|
||||
@@ -28972,6 +29062,9 @@ export interface operations {
|
||||
role: "admin" | "supervisor" | "staff" | "user";
|
||||
isActive?: boolean | null;
|
||||
notificationPreference?: ("email" | "whatsapp" | "both") | null;
|
||||
twoFactorEnabled?: boolean | null;
|
||||
/** @description How their sign-in codes come (2.3.0: authenticator = an app) */
|
||||
twoFactorMethod?: ("email" | "whatsapp" | "authenticator") | null;
|
||||
homeCampusId?: string | null;
|
||||
createdAt?: string | null;
|
||||
} & {
|
||||
|
||||
@@ -26,7 +26,7 @@ export type AuthResponse = AuthUser & {
|
||||
deviceToken?: string;
|
||||
};
|
||||
|
||||
export type TwoFactorMethod = "email" | "whatsapp";
|
||||
export type TwoFactorMethod = "email" | "whatsapp" | "authenticator";
|
||||
|
||||
// What the login endpoint returns instead of a token when the account has 2FA on:
|
||||
// a code was sent to `destination` (masked) and must be exchanged for the token.
|
||||
@@ -37,6 +37,9 @@ export type TwoFactorChallenge = {
|
||||
destination: string;
|
||||
// The role requires 2FA and it wasn't on yet: verifying this code turns it on.
|
||||
enrolling?: boolean;
|
||||
// 2.3.0, setting up an authenticator app: the key and its otpauth:// link (shown as a QR code).
|
||||
secret?: string;
|
||||
otpauthUrl?: string;
|
||||
};
|
||||
|
||||
export function isTwoFactorChallenge(res: unknown): res is TwoFactorChallenge {
|
||||
|
||||
Generated
+2
-2
@@ -59,7 +59,7 @@
|
||||
},
|
||||
"apps/events/backend": {
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "2.2.0",
|
||||
"version": "2.3.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
@@ -106,7 +106,7 @@
|
||||
},
|
||||
"apps/events/frontend": {
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "2.2.0",
|
||||
"version": "2.3.0",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@hookform/resolvers": "^5.2.1",
|
||||
|
||||
Reference in New Issue
Block a user