|
| 1 | +import { Empty, RuntimeError, ScriptContext } from "../module.gen.ts"; |
| 2 | +import { verifyCode } from "../utils/code_management.ts"; |
| 3 | +import { IDENTITY_INFO_PASSWORD } from "../utils/provider.ts"; |
| 4 | +import { ensureNotAssociatedAll } from "../utils/link_assertions.ts"; |
| 5 | + |
| 6 | +export interface Request { |
| 7 | + userToken: string; |
| 8 | + |
| 9 | + email: string; |
| 10 | + password: string; |
| 11 | + oldPassword: string | null; |
| 12 | + |
| 13 | + verificationToken: string; |
| 14 | + code: string; |
| 15 | +} |
| 16 | + |
| 17 | +export type Response = Empty; |
| 18 | + |
| 19 | +export async function run( |
| 20 | + ctx: ScriptContext, |
| 21 | + req: Request, |
| 22 | +): Promise<Response> { |
| 23 | + await ctx.modules.rateLimit.throttlePublic({}); |
| 24 | + |
| 25 | + // Check the verification code. If it is valid, but for the wrong email, say |
| 26 | + // the verification failed. |
| 27 | + const { email } = await verifyCode(ctx, req.verificationToken, req.code); |
| 28 | + if (!compareConstantTime(req.email, email)) { |
| 29 | + throw new RuntimeError("verification_failed"); |
| 30 | + } |
| 31 | + |
| 32 | + // Ensure that the email is not associated with ANY accounts in ANY way. |
| 33 | + const providedUser = await ctx.modules.users.authenticateToken({ |
| 34 | + userToken: req.userToken, |
| 35 | + }); |
| 36 | + await ensureNotAssociatedAll(ctx, email, new Set([providedUser.userId])); |
| 37 | + |
| 38 | + // If an old password was provided, ensure it was correct and update it. |
| 39 | + // If one was not, register the user with the `userPasswords` module. |
| 40 | + if (req.oldPassword) { |
| 41 | + await ctx.modules.userPasswords.verify({ |
| 42 | + userId: providedUser.userId, |
| 43 | + password: req.oldPassword, |
| 44 | + }); |
| 45 | + await ctx.modules.userPasswords.update({ |
| 46 | + userId: providedUser.userId, |
| 47 | + newPassword: req.password, |
| 48 | + }); |
| 49 | + } else { |
| 50 | + await ctx.modules.userPasswords.add({ |
| 51 | + userId: providedUser.userId, |
| 52 | + password: req.password, |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + // Sign up the user with the passwordless email identity |
| 57 | + await ctx.modules.identities.link({ |
| 58 | + userToken: req.userToken, |
| 59 | + info: IDENTITY_INFO_PASSWORD, |
| 60 | + uniqueData: { |
| 61 | + identifier: email, |
| 62 | + }, |
| 63 | + additionalData: {}, |
| 64 | + }); |
| 65 | + |
| 66 | + return {}; |
| 67 | +} |
| 68 | + |
| 69 | +function compareConstantTime(aConstant: string, b: string) { |
| 70 | + let isEq = 1; |
| 71 | + for (let i = 0; i < aConstant.length; i++) { |
| 72 | + isEq &= Number(aConstant[i] === b[i]); |
| 73 | + } |
| 74 | + isEq &= Number(aConstant.length === b.length); |
| 75 | + |
| 76 | + return Boolean(isEq); |
| 77 | +} |
0 commit comments