Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/lib/verificationCode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* Sign-in verification code settings, shared by the server (token generation, email) and the
* client (OTP input).
*
* The code is purely numeric on purpose. Apple does not document how Mail detects codes in emails,
* but numeric codes of roughly 4-8 digits are the ones that get offered for AutoFill in practice;
* alphanumeric codes are not.
*/
export const VERIFICATION_CODE_LENGTH = 6;

/**
* The same token powers the magic link and the typed code. NextAuth's default is 24 hours; a
* 10^6 keyspace warrants less. Note this only shortens the window: failed guesses are not
* throttled or counted, so this is not a substitute for rate limiting.
*/
export const VERIFICATION_CODE_MAX_AGE_SECONDS = 10 * 60;
23 changes: 13 additions & 10 deletions src/pages/auth/VerificationStep.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// oxlint-disable no-html-link-for-pages
import { zodResolver } from '@hookform/resolvers/zod';
import { REGEXP_ONLY_DIGITS_AND_CHARS } from 'input-otp';
import { REGEXP_ONLY_DIGITS } from 'input-otp';
import { type TFunction, useTranslation } from 'next-i18next';
import { type FC, useCallback, useMemo } from 'react';
import { useForm } from 'react-hook-form';
Expand All @@ -9,14 +9,18 @@ import { z } from 'zod';
import { Button } from '~/components/ui/button';
import { Form, FormControl, FormField, FormItem, FormMessage } from '~/components/ui/form';
import { InputOTP, InputOTPGroup, InputOTPSlot } from '~/components/ui/input-otp';
import { VERIFICATION_CODE_LENGTH } from '~/lib/verificationCode';

const VERIFICATION_CODE_PATTERN = new RegExp(`^\\d{${VERIFICATION_CODE_LENGTH}}$`);
const OTP_SLOT_INDEXES = Array.from({ length: VERIFICATION_CODE_LENGTH }, (_, index) => index);

const otpSchema = (t: TFunction) =>
z.object({
otp: z
.string({
error: (issue) => (undefined === issue.input ? t('errors.otp_required') : undefined),
})
.length(5, { message: t('errors.otp_invalid') }),
.regex(VERIFICATION_CODE_PATTERN, { message: t('errors.otp_invalid') }),
});

type OTPFormValues = z.infer<ReturnType<typeof otpSchema>>;
Expand Down Expand Up @@ -95,18 +99,17 @@ const OTPInput = ({ field }) => (
<FormControl>
<InputOTP
className="w-[300px]"
maxLength={5}
pattern={REGEXP_ONLY_DIGITS_AND_CHARS}
inputMode="text"
maxLength={VERIFICATION_CODE_LENGTH}
pattern={REGEXP_ONLY_DIGITS}
inputMode="numeric"
autoComplete="one-time-code"
autoFocus
{...field}
>
<InputOTPGroup>
<InputOTPSlot className="w-[60px]" index={0} />
<InputOTPSlot className="w-[60px]" index={1} />
<InputOTPSlot className="w-[60px]" index={2} />
<InputOTPSlot className="w-[60px]" index={3} />
<InputOTPSlot className="w-[60px]" index={4} />
{OTP_SLOT_INDEXES.map((index) => (
<InputOTPSlot key={index} className="w-[50px]" index={index} />
))}
</InputOTPGroup>
</InputOTP>
</FormControl>
Expand Down
10 changes: 6 additions & 4 deletions src/server/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ import GoogleProvider from 'next-auth/providers/google';
import KeycloakProvider from 'next-auth/providers/keycloak';

import { env } from '~/env';
import { VERIFICATION_CODE_MAX_AGE_SECONDS } from '~/lib/verificationCode';
import { db } from '~/server/db';
import { sanitiseAdapterAccount } from '~/server/authAccount';
import { generateVerificationCode } from '~/server/verificationCode';
import { withScopedVerificationTokens } from '~/server/verificationTokens';
import { parseEnvBoolean } from '~/utils/env';

import { mailServerConfig, sendSignUpEmail } from './mailer';
Expand Down Expand Up @@ -53,7 +56,7 @@ declare module 'next-auth' {
}

const SplitProPrismaAdapter = (...args: Parameters<typeof PrismaAdapter>): Adapter => {
const prismaAdapter = PrismaAdapter(...args);
const prismaAdapter = withScopedVerificationTokens(PrismaAdapter(...args), db);

return {
...prismaAdapter,
Expand Down Expand Up @@ -227,9 +230,8 @@ function getProviders() {
throw new Error('Failed to send email');
}
},
generateVerificationToken() {
return Math.random().toString(36).substring(2, 7).toLowerCase();
},
maxAge: VERIFICATION_CODE_MAX_AGE_SECONDS,
generateVerificationToken: generateVerificationCode,
}),
);
}
Expand Down
51 changes: 47 additions & 4 deletions src/server/mailer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { type Transporter, createTransport } from 'nodemailer';

import { env } from '~/env';
import { escapeHtml } from '~/lib/utils';
import { VERIFICATION_CODE_MAX_AGE_SECONDS } from '~/lib/verificationCode';

import { sendToDiscord } from './service-notification';

Expand Down Expand Up @@ -38,19 +39,61 @@ const getTransporter = () => {
return transporter;
};

export async function sendSignUpEmail(email: string, url: string, token: string) {
/**
* Builds the sign-in email. Apple does not document how Mail detects codes, so the layout is a
* best-effort heuristic that mirrors emails that are offered for AutoFill (for example Cloudflare
* Access and JetBrains Account login emails):
* - a numeric code, introduced by the words "login code",
* - the code alone on its own line (text part) / in its own element (HTML part),
* - a hidden preheader repeating "Your login code: 123456" (HTML part).
*/
export const buildSignInEmail = (url: string, token: string) => {
const { host } = new URL(url);
const minutes = Math.round(VERIFICATION_CODE_MAX_AGE_SECONDS / 60);

const subject = 'Your SplitPro login code';

const text = [
'Hey,',
'',
'Your SplitPro login code:',
'',
token,
'',
`This code expires in ${minutes} minutes or once it has been used.`,
'',
'Prefer not to use the code? Sign in with the link below instead:',
url,
'',
"If you didn't request this email, you can safely ignore it.",
'',
'Thanks,',
'SplitPro Team',
].join('\n');

const html = [
`<div style="display:none;max-height:0;overflow:hidden;opacity:0;">Your login code: ${escapeHtml(token)}</div>`,
'<p>Hey,</p>',
'<p>Your SplitPro login code:</p>',
`<p style="font-size:26px;font-weight:bold;">${escapeHtml(token)}</p>`,
`<p>This code expires in ${minutes} minutes or once it has been used.</p>`,
`<p>Prefer not to use the code? <a href="${escapeHtml(url)}">Sign in to ${escapeHtml(host)}</a> instead.</p>`,
"<p>If you didn't request this email, you can safely ignore it.</p>",
'<p>Thanks,<br/>SplitPro Team</p>',
].join('');

return { subject, text, html };
};

export async function sendSignUpEmail(email: string, url: string, token: string) {
console.log(env.NODE_ENV);

if ('development' === env.NODE_ENV) {
console.log('Sign in link : ', email, url, token);
return true;
}

const subject = 'Sign in to SplitPro';
const text = `Hey,\n\nYou can sign in to SplitPro by clicking the below URL:\n${url}\n\nYou can also use this OTP: ${token}\n\nThanks,\nSplitPro Team`;
const html = `<p>Hey,</p> <p>You can sign in to SplitPro by clicking the below URL:</p><p><a href="${url}">Sign in to ${host}</a></p><p>You can also use this OTP: <b>${token}</b></p><br /><br /><p>Thanks,</p><br/>SplitPro Team</p>`;
const { subject, text, html } = buildSignInEmail(url, token);

return await sendMail(email, subject, text, html);
}
Expand Down
12 changes: 12 additions & 0 deletions src/server/verificationCode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { randomInt } from 'node:crypto';

import { VERIFICATION_CODE_LENGTH } from '~/lib/verificationCode';

/**
* Generates a zero-padded numeric sign-in code (e.g. `040046`) using a CSPRNG. `randomInt` is
* uniformly distributed, so there is no modulo bias.
*/
export const generateVerificationCode = (): string =>
randomInt(0, 10 ** VERIFICATION_CODE_LENGTH)
.toString()
.padStart(VERIFICATION_CODE_LENGTH, '0');
52 changes: 52 additions & 0 deletions src/server/verificationTokens.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { type PrismaClient } from '@prisma/client';
import { createHash } from 'node:crypto';
import { type Adapter } from 'next-auth/adapters';

/**
* NextAuth stores `sha256(token + secret)` in `VerificationToken.token`, which has a global
* unique constraint and does not include the identifier. With random 36^5 tokens a clash was very
* unlikely, but 6-digit codes (10^6 values) can clash between different users, and the failed
* insert would happen after the email was already sent.
*
* Scoping the stored value to the identifier removes cross-user clashes without a schema
* migration.
*/
export const scopeVerificationToken = (identifier: string, hashedToken: string) =>
createHash('sha256').update(`${identifier}:${hashedToken}`).digest('hex');

type VerificationTokenClient = Pick<PrismaClient, 'verificationToken'>;

/**
* Wraps the adapter's verification token methods so that stored tokens are scoped to the
* identifier (see {@link scopeVerificationToken}).
*
* Other codes issued to the same identifier stay valid. Only a row holding the very same code is
* replaced, because the same identifier drawing the same 6-digit code twice would otherwise violate
* the unique constraint.
*
* Rows created before this wrapper was introduced were stored unscoped and can no longer be
* redeemed; those users simply request a new code.
*/
export const withScopedVerificationTokens = (
adapter: Adapter,
{ verificationToken }: VerificationTokenClient,
): Adapter => {
const { createVerificationToken, useVerificationToken } = adapter;

if (!createVerificationToken || !useVerificationToken) {
throw new Error('Adapter is missing verification token support.');
}

return {
...adapter,
createVerificationToken: async ({ identifier, token, expires }) => {
const scopedToken = scopeVerificationToken(identifier, token);

await verificationToken.deleteMany({ where: { identifier, token: scopedToken } });

return createVerificationToken({ identifier, token: scopedToken, expires });
},
useVerificationToken: ({ identifier, token }) =>
useVerificationToken({ identifier, token: scopeVerificationToken(identifier, token) }),
};
};
89 changes: 89 additions & 0 deletions src/tests/authEmailProvider.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import {
VERIFICATION_CODE_LENGTH,
VERIFICATION_CODE_MAX_AGE_SECONDS,
} from '~/lib/verificationCode';
import { authOptions } from '~/server/auth';
import { scopeVerificationToken } from '~/server/verificationTokens';

jest.mock('~/env', () => ({
env: {
NODE_ENV: 'test',
EMAIL_SERVER_HOST: 'smtp.example.com',
FROM_EMAIL: 'noreply@example.com',
NEXTAUTH_URL: 'https://splitpro.example.com',
},
}));

jest.mock('~/server/db', () => ({ db: { verificationToken: { deleteMany: jest.fn() } } }));

jest.mock('~/server/mailer', () => ({ mailServerConfig: {}, sendSignUpEmail: jest.fn() }));

jest.mock('~/utils/api', () => ({ getBaseUrl: () => 'https://splitpro.example.com' }));

jest.mock('@next-auth/prisma-adapter', () => {
const createVerificationToken = jest.fn();
const useVerificationToken = jest.fn();
return {
mockCreateVerificationToken: createVerificationToken,
mockUseVerificationToken: useVerificationToken,
PrismaAdapter: () => ({ createVerificationToken, useVerificationToken }),
};
});

const { mockCreateVerificationToken, mockUseVerificationToken } = jest.requireMock<{
mockCreateVerificationToken: jest.Mock;
mockUseVerificationToken: jest.Mock;
}>('@next-auth/prisma-adapter');

const getEmailProviderOptions = () => {
const provider = authOptions.providers.find(({ id }) => 'email' === id);
const options = provider?.options as
| { maxAge?: number; generateVerificationToken?: () => string }
| undefined;
if (!options) {
throw new Error('Email provider is not registered');
}
return options;
};

describe('NextAuth email provider wiring', () => {
it('limits the lifetime of the token', () => {
expect(getEmailProviderOptions().maxAge).toBe(VERIFICATION_CODE_MAX_AGE_SECONDS);
});

it('issues numeric codes of the configured length', () => {
const { generateVerificationToken } = getEmailProviderOptions();

expect(generateVerificationToken?.()).toMatch(new RegExp(`^\\d{${VERIFICATION_CODE_LENGTH}}$`));
});

describe('adapter', () => {
const expires = new Date('2030-01-01T00:00:00.000Z');

it('stores verification tokens scoped to the identifier', async () => {
await authOptions.adapter?.createVerificationToken?.({
identifier: 'a@example.com',
token: 'hashed',
expires,
});

expect(mockCreateVerificationToken).toHaveBeenCalledWith({
identifier: 'a@example.com',
token: scopeVerificationToken('a@example.com', 'hashed'),
expires,
});
});

it('looks verification tokens up by the scoped value', async () => {
await authOptions.adapter?.useVerificationToken?.({
identifier: 'a@example.com',
token: 'hashed',
});

expect(mockUseVerificationToken).toHaveBeenCalledWith({
identifier: 'a@example.com',
token: scopeVerificationToken('a@example.com', 'hashed'),
});
});
});
});
Loading