|
| 1 | +import type { ClientJSON, PhoneNumberJSON, UserJSON } from '@clerk/shared/types'; |
| 2 | +import { http, HttpResponse } from 'msw'; |
| 3 | + |
| 4 | +import { type FapiEnvironment, fapiPhoneNumber, fapiVerification } from '../fapi'; |
| 5 | + |
| 6 | +export interface FakeMfaState { |
| 7 | + totpCreations: number; |
| 8 | + totpAttempts: string[]; |
| 9 | + totpRemovals: number; |
| 10 | + backupCodeCreations: number; |
| 11 | + phoneCreations: string[]; |
| 12 | + phonePreparations: string[]; |
| 13 | + phoneAttempts: { id: string; code: string }[]; |
| 14 | + phoneUpdates: { id: string; reserved?: boolean; default?: boolean }[]; |
| 15 | + codes: string[]; |
| 16 | +} |
| 17 | + |
| 18 | +export function createMfaState(): FakeMfaState { |
| 19 | + return { |
| 20 | + totpCreations: 0, |
| 21 | + totpAttempts: [], |
| 22 | + totpRemovals: 0, |
| 23 | + backupCodeCreations: 0, |
| 24 | + phoneCreations: [], |
| 25 | + phonePreparations: [], |
| 26 | + phoneAttempts: [], |
| 27 | + phoneUpdates: [], |
| 28 | + codes: Array.from({ length: 10 }, (_, index) => `CODE00${String(index + 1).padStart(2, '0')}`), |
| 29 | + }; |
| 30 | +} |
| 31 | + |
| 32 | +export function mfaHandlers( |
| 33 | + state: { client: ClientJSON; environment: FapiEnvironment; mfa: FakeMfaState }, |
| 34 | + fapiUrl: (path: string) => string, |
| 35 | +) { |
| 36 | + const active = () => state.client.sessions.find(session => session.id === state.client.last_active_session_id); |
| 37 | + const backupEnabled = () => |
| 38 | + state.environment.user_settings.attributes.backup_code.enabled && |
| 39 | + state.environment.user_settings.attributes.backup_code.used_for_second_factor; |
| 40 | + const usableFactors = (user: UserJSON) => |
| 41 | + Number(user.totp_enabled) + |
| 42 | + user.phone_numbers.filter(phone => phone.reserved_for_second_factor && phone.verification.status === 'verified') |
| 43 | + .length; |
| 44 | + const error = (code: string, message: string, status = 400) => |
| 45 | + HttpResponse.json({ errors: [{ code, message, long_message: message }] }, { status }); |
| 46 | + const respond = (response: object) => HttpResponse.json({ response, client: state.client }); |
| 47 | + const missing = () => |
| 48 | + HttpResponse.json({ errors: [{ code: 'resource_not_found', message: 'not found' }] }, { status: 404 }); |
| 49 | + const updateUser = (transform: (user: UserJSON) => UserJSON) => { |
| 50 | + const session = active(); |
| 51 | + if (!session) { |
| 52 | + return undefined; |
| 53 | + } |
| 54 | + const user = transform(session.user); |
| 55 | + state.client = { |
| 56 | + ...state.client, |
| 57 | + sessions: state.client.sessions.map(item => (item.id === session.id ? { ...item, user } : item)), |
| 58 | + }; |
| 59 | + return user; |
| 60 | + }; |
| 61 | + const updatePhone = (id: string, transform: (phone: PhoneNumberJSON) => PhoneNumberJSON) => { |
| 62 | + let updated: PhoneNumberJSON | undefined; |
| 63 | + updateUser(user => ({ |
| 64 | + ...user, |
| 65 | + phone_numbers: user.phone_numbers.map(phone => { |
| 66 | + if (phone.id !== id) { |
| 67 | + return phone; |
| 68 | + } |
| 69 | + updated = transform(phone); |
| 70 | + return updated; |
| 71 | + }), |
| 72 | + })); |
| 73 | + return updated; |
| 74 | + }; |
| 75 | + |
| 76 | + return [ |
| 77 | + http.get(fapiUrl('/v1/me'), () => { |
| 78 | + const session = active(); |
| 79 | + return session ? respond(session.user) : missing(); |
| 80 | + }), |
| 81 | + http.post(fapiUrl('/v1/me/totp'), ({ request }) => { |
| 82 | + if (!active()) { |
| 83 | + return missing(); |
| 84 | + } |
| 85 | + if (new URL(request.url).searchParams.get('_method') === 'DELETE') { |
| 86 | + const currentUser = active()?.user; |
| 87 | + if ( |
| 88 | + !currentUser?.totp_enabled || |
| 89 | + (state.environment.user_settings.sign_up.mfa?.required && usableFactors(currentUser) <= 1) |
| 90 | + ) { |
| 91 | + return error('second_factor_deletion_not_allowed', 'This method cannot be removed.'); |
| 92 | + } |
| 93 | + state.mfa.totpRemovals += 1; |
| 94 | + const user = updateUser(current => ({ |
| 95 | + ...current, |
| 96 | + totp_enabled: false, |
| 97 | + two_factor_enabled: current.phone_numbers.some(phone => phone.reserved_for_second_factor), |
| 98 | + backup_code_enabled: |
| 99 | + current.phone_numbers.some(phone => phone.reserved_for_second_factor) && current.backup_code_enabled, |
| 100 | + })); |
| 101 | + return user ? respond({ object: 'deleted', id: 'totp_1' }) : missing(); |
| 102 | + } |
| 103 | + if ( |
| 104 | + active()?.user.totp_enabled || |
| 105 | + !state.environment.user_settings.attributes.authenticator_app.used_for_second_factor |
| 106 | + ) { |
| 107 | + return error('form_param_value_invalid', 'Authenticator is unavailable.', 422); |
| 108 | + } |
| 109 | + state.mfa.totpCreations += 1; |
| 110 | + return respond({ |
| 111 | + object: 'totp', |
| 112 | + id: 'totp_1', |
| 113 | + secret: `SECRET${state.mfa.totpCreations}`, |
| 114 | + uri: `otpauth://totp/Acme:user?secret=SECRET${state.mfa.totpCreations}`, |
| 115 | + verified: false, |
| 116 | + created_at: Date.now(), |
| 117 | + updated_at: Date.now(), |
| 118 | + }); |
| 119 | + }), |
| 120 | + http.post(fapiUrl('/v1/me/totp/attempt_verification'), async ({ request }) => { |
| 121 | + if (state.mfa.totpCreations === 0 || active()?.user.totp_enabled) { |
| 122 | + return error('form_param_value_invalid', 'No authenticator setup is pending.', 422); |
| 123 | + } |
| 124 | + const code = new URLSearchParams(await request.text()).get('code') ?? ''; |
| 125 | + state.mfa.totpAttempts.push(code); |
| 126 | + if (code !== '123456') { |
| 127 | + return HttpResponse.json( |
| 128 | + { errors: [{ code: 'form_code_incorrect', message: 'Incorrect code', long_message: 'Incorrect code' }] }, |
| 129 | + { status: 422 }, |
| 130 | + ); |
| 131 | + } |
| 132 | + const newCodes = backupEnabled() && !active()?.user.backup_code_enabled; |
| 133 | + const user = updateUser(current => ({ |
| 134 | + ...current, |
| 135 | + totp_enabled: true, |
| 136 | + two_factor_enabled: true, |
| 137 | + backup_code_enabled: current.backup_code_enabled || newCodes, |
| 138 | + })); |
| 139 | + if (!user) { |
| 140 | + return missing(); |
| 141 | + } |
| 142 | + return respond({ |
| 143 | + object: 'totp', |
| 144 | + id: 'totp_1', |
| 145 | + verified: true, |
| 146 | + ...(newCodes ? { backup_codes: state.mfa.codes } : {}), |
| 147 | + created_at: Date.now(), |
| 148 | + updated_at: Date.now(), |
| 149 | + }); |
| 150 | + }), |
| 151 | + http.post(fapiUrl('/v1/me/backup_codes/'), () => { |
| 152 | + const currentUser = active()?.user; |
| 153 | + if (!currentUser || usableFactors(currentUser) === 0 || !backupEnabled()) { |
| 154 | + return error('form_param_value_invalid', 'Set up a verification method first.', 422); |
| 155 | + } |
| 156 | + state.mfa.backupCodeCreations += 1; |
| 157 | + state.mfa.codes = Array.from( |
| 158 | + { length: 10 }, |
| 159 | + (_, index) => `CODE${String(state.mfa.backupCodeCreations).padStart(2, '0')}${String(index).padStart(2, '0')}`, |
| 160 | + ); |
| 161 | + const user = updateUser(current => ({ ...current, backup_code_enabled: true })); |
| 162 | + return user |
| 163 | + ? respond({ |
| 164 | + object: 'backup_code', |
| 165 | + id: 'backup_1', |
| 166 | + codes: state.mfa.codes, |
| 167 | + created_at: Date.now(), |
| 168 | + updated_at: Date.now(), |
| 169 | + }) |
| 170 | + : missing(); |
| 171 | + }), |
| 172 | + http.post(fapiUrl('/v1/me/phone_numbers/'), async ({ request }) => { |
| 173 | + const number = new URLSearchParams(await request.text()).get('phone_number') ?? ''; |
| 174 | + state.mfa.phoneCreations.push(number); |
| 175 | + const existingIds = new Set(active()?.user.phone_numbers.map(phone => phone.id)); |
| 176 | + let nextPhoneNumber = state.mfa.phoneCreations.length; |
| 177 | + while (existingIds.has(`phone_${nextPhoneNumber}`)) { |
| 178 | + nextPhoneNumber += 1; |
| 179 | + } |
| 180 | + const phone = fapiPhoneNumber({ |
| 181 | + id: `phone_${nextPhoneNumber}`, |
| 182 | + phone_number: number, |
| 183 | + verification: fapiVerification('phone_code'), |
| 184 | + }); |
| 185 | + const user = updateUser(current => ({ ...current, phone_numbers: [...current.phone_numbers, phone] })); |
| 186 | + return user ? respond(phone) : missing(); |
| 187 | + }), |
| 188 | + http.post(fapiUrl('/v1/me/phone_numbers/:id/prepare_verification'), ({ params }) => { |
| 189 | + const id = String(params.id); |
| 190 | + state.mfa.phonePreparations.push(id); |
| 191 | + const phone = updatePhone(id, current => ({ ...current, verification: fapiVerification('phone_code') })); |
| 192 | + return phone ? respond(phone) : missing(); |
| 193 | + }), |
| 194 | + http.post(fapiUrl('/v1/me/phone_numbers/:id/attempt_verification'), async ({ params, request }) => { |
| 195 | + const id = String(params.id); |
| 196 | + const code = new URLSearchParams(await request.text()).get('code') ?? ''; |
| 197 | + state.mfa.phoneAttempts.push({ id, code }); |
| 198 | + if (code !== '123456') { |
| 199 | + return HttpResponse.json( |
| 200 | + { errors: [{ code: 'form_code_incorrect', message: 'Incorrect code' }] }, |
| 201 | + { status: 422 }, |
| 202 | + ); |
| 203 | + } |
| 204 | + const phone = updatePhone(id, current => ({ |
| 205 | + ...current, |
| 206 | + verification: fapiVerification('phone_code', { status: 'verified' }), |
| 207 | + })); |
| 208 | + return phone ? respond(phone) : missing(); |
| 209 | + }), |
| 210 | + http.post(fapiUrl('/v1/me/phone_numbers/:id'), async ({ params, request }) => { |
| 211 | + if (new URL(request.url).searchParams.get('_method') !== 'PATCH') { |
| 212 | + return undefined; |
| 213 | + } |
| 214 | + const id = String(params.id); |
| 215 | + const body = new URLSearchParams(await request.text()); |
| 216 | + const reserved = body.has('reserved_for_second_factor') |
| 217 | + ? body.get('reserved_for_second_factor') === 'true' |
| 218 | + : undefined; |
| 219 | + const isDefault = body.has('default_second_factor') ? body.get('default_second_factor') === 'true' : undefined; |
| 220 | + state.mfa.phoneUpdates.push({ id, reserved, default: isDefault }); |
| 221 | + const previous = active()?.user; |
| 222 | + const existingPhone = previous?.phone_numbers.find(phone => phone.id === id); |
| 223 | + if (reserved === true && (!existingPhone || existingPhone.verification.status !== 'verified')) { |
| 224 | + return error( |
| 225 | + 'identification_update_second_factor_unverified', |
| 226 | + 'Cannot update second factor attributes for unverified identification', |
| 227 | + ); |
| 228 | + } |
| 229 | + if ( |
| 230 | + reserved === false && |
| 231 | + state.environment.user_settings.sign_up.mfa?.required && |
| 232 | + previous && |
| 233 | + usableFactors(previous) <= 1 |
| 234 | + ) { |
| 235 | + return error('second_factor_deletion_not_allowed', 'This method cannot be removed.'); |
| 236 | + } |
| 237 | + const firstReservedPhone = !previous?.phone_numbers.some(item => item.reserved_for_second_factor); |
| 238 | + const newCodes = reserved && backupEnabled() && !previous?.backup_code_enabled; |
| 239 | + const phone = updatePhone(id, current => ({ |
| 240 | + ...current, |
| 241 | + reserved_for_second_factor: reserved ?? current.reserved_for_second_factor, |
| 242 | + default_second_factor: |
| 243 | + isDefault ?? |
| 244 | + (reserved && firstReservedPhone ? true : reserved === false ? false : current.default_second_factor), |
| 245 | + backup_codes: newCodes ? state.mfa.codes : undefined, |
| 246 | + })); |
| 247 | + if (isDefault) { |
| 248 | + updateUser(user => ({ |
| 249 | + ...user, |
| 250 | + phone_numbers: user.phone_numbers.map(item => |
| 251 | + item.id === id ? item : { ...item, default_second_factor: false }, |
| 252 | + ), |
| 253 | + })); |
| 254 | + } |
| 255 | + if (reserved !== undefined) { |
| 256 | + updateUser(user => ({ |
| 257 | + ...user, |
| 258 | + two_factor_enabled: user.totp_enabled || user.phone_numbers.some(item => item.reserved_for_second_factor), |
| 259 | + backup_code_enabled: reserved |
| 260 | + ? user.backup_code_enabled || Boolean(newCodes) |
| 261 | + : user.totp_enabled || user.phone_numbers.some(item => item.reserved_for_second_factor) |
| 262 | + ? user.backup_code_enabled |
| 263 | + : false, |
| 264 | + })); |
| 265 | + if (reserved === false && previous?.phone_numbers.find(item => item.id === id)?.default_second_factor) { |
| 266 | + updateUser(user => { |
| 267 | + const next = user.phone_numbers.find(item => item.reserved_for_second_factor); |
| 268 | + return { |
| 269 | + ...user, |
| 270 | + phone_numbers: user.phone_numbers.map(item => |
| 271 | + item.id === next?.id ? { ...item, default_second_factor: true } : item, |
| 272 | + ), |
| 273 | + }; |
| 274 | + }); |
| 275 | + } |
| 276 | + } |
| 277 | + return phone ? respond(phone) : missing(); |
| 278 | + }), |
| 279 | + ]; |
| 280 | +} |
0 commit comments