From 1e4586794adeda748a9a559104040cf8d858fb73 Mon Sep 17 00:00:00 2001 From: Ignat Alexeyenko Date: Mon, 30 Nov 2026 14:34:58 +0100 Subject: [PATCH] fix(auth): change login code to one supported by Apple ecosystem These changes should enable code auto-fill in Safari for codes received in the Mail app on iPhone and macOS. - code is now numeric, 6 digits maching other apps - email format changed: labelled code on its own line, hidden preheader - magic link kept as an alternative - OTP input takes 6 digits - code expires after 10 minutes - stored tokens are scoped to the identifier so two user do not collide --- src/lib/verificationCode.ts | 16 +++ src/pages/auth/VerificationStep.tsx | 23 ++-- src/server/auth.ts | 10 +- src/server/mailer.ts | 51 +++++++- src/server/verificationCode.ts | 12 ++ src/server/verificationTokens.ts | 52 ++++++++ src/tests/authEmailProvider.test.ts | 89 +++++++++++++ src/tests/mailer.test.ts | 95 +++++++++++++- src/tests/verificationCode.test.ts | 42 +++++++ src/tests/verificationStep.test.tsx | 87 +++++++++++++ src/tests/verificationTokens.test.ts | 181 +++++++++++++++++++++++++++ 11 files changed, 639 insertions(+), 19 deletions(-) create mode 100644 src/lib/verificationCode.ts create mode 100644 src/server/verificationCode.ts create mode 100644 src/server/verificationTokens.ts create mode 100644 src/tests/authEmailProvider.test.ts create mode 100644 src/tests/verificationCode.test.ts create mode 100644 src/tests/verificationStep.test.tsx create mode 100644 src/tests/verificationTokens.test.ts diff --git a/src/lib/verificationCode.ts b/src/lib/verificationCode.ts new file mode 100644 index 00000000..f825cb7c --- /dev/null +++ b/src/lib/verificationCode.ts @@ -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; diff --git a/src/pages/auth/VerificationStep.tsx b/src/pages/auth/VerificationStep.tsx index cc5bb8ab..78d34495 100644 --- a/src/pages/auth/VerificationStep.tsx +++ b/src/pages/auth/VerificationStep.tsx @@ -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'; @@ -9,6 +9,10 @@ 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({ @@ -16,7 +20,7 @@ const otpSchema = (t: TFunction) => .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>; @@ -95,18 +99,17 @@ const OTPInput = ({ field }) => ( - - - - - + {OTP_SLOT_INDEXES.map((index) => ( + + ))} diff --git a/src/server/auth.ts b/src/server/auth.ts index f62ae420..684737c0 100644 --- a/src/server/auth.ts +++ b/src/server/auth.ts @@ -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'; @@ -53,7 +56,7 @@ declare module 'next-auth' { } const SplitProPrismaAdapter = (...args: Parameters): Adapter => { - const prismaAdapter = PrismaAdapter(...args); + const prismaAdapter = withScopedVerificationTokens(PrismaAdapter(...args), db); return { ...prismaAdapter, @@ -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, }), ); } diff --git a/src/server/mailer.ts b/src/server/mailer.ts index e5188b80..97c51b1b 100644 --- a/src/server/mailer.ts +++ b/src/server/mailer.ts @@ -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'; @@ -38,9 +39,53 @@ 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 = [ + `
Your login code: ${escapeHtml(token)}
`, + '

Hey,

', + '

Your SplitPro login code:

', + `

${escapeHtml(token)}

`, + `

This code expires in ${minutes} minutes or once it has been used.

`, + `

Prefer not to use the code? Sign in to ${escapeHtml(host)} instead.

`, + "

If you didn't request this email, you can safely ignore it.

", + '

Thanks,
SplitPro Team

', + ].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) { @@ -48,9 +93,7 @@ export async function sendSignUpEmail(email: string, url: string, token: string) 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 = `

Hey,

You can sign in to SplitPro by clicking the below URL:

Sign in to ${host}

You can also use this OTP: ${token}



Thanks,


SplitPro Team

`; + const { subject, text, html } = buildSignInEmail(url, token); return await sendMail(email, subject, text, html); } diff --git a/src/server/verificationCode.ts b/src/server/verificationCode.ts new file mode 100644 index 00000000..d9593152 --- /dev/null +++ b/src/server/verificationCode.ts @@ -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'); diff --git a/src/server/verificationTokens.ts b/src/server/verificationTokens.ts new file mode 100644 index 00000000..130b6df1 --- /dev/null +++ b/src/server/verificationTokens.ts @@ -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; + +/** + * 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) }), + }; +}; diff --git a/src/tests/authEmailProvider.test.ts b/src/tests/authEmailProvider.test.ts new file mode 100644 index 00000000..1039305a --- /dev/null +++ b/src/tests/authEmailProvider.test.ts @@ -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'), + }); + }); + }); +}); diff --git a/src/tests/mailer.test.ts b/src/tests/mailer.test.ts index ae1ecdd2..990fc3cf 100644 --- a/src/tests/mailer.test.ts +++ b/src/tests/mailer.test.ts @@ -3,7 +3,7 @@ import EmailProvider from 'next-auth/providers/email'; import { env } from '~/env'; import { sendToDiscord } from '~/server/service-notification'; -import { sendInviteEmail } from '~/server/mailer'; +import { buildSignInEmail, sendInviteEmail, sendSignUpEmail } from '~/server/mailer'; jest.mock('~/env', () => ({ env: { @@ -136,6 +136,99 @@ describe('sendInviteEmail', () => { }); }); +describe('buildSignInEmail', () => { + const code = '040046'; + const url = `https://splitpro.example.com/api/auth/callback/email?callbackUrl=https%3A%2F%2Fsplitpro.example.com&token=${code}&email=friend%40example.com`; + + // Apple does not document email code detection; this layout mirrors emails that get AutoFill. + describe('Apple AutoFill layout (heuristic)', () => { + it('labels the code as a "login code" in the subject', () => { + expect(buildSignInEmail(url, code).subject).toBe('Your SplitPro login code'); + }); + + it('puts the code alone on its own line in the plain-text part', () => { + const { text } = buildSignInEmail(url, code); + const lines = text.split('\n'); + + expect(lines).toContain(code); + expect(lines[lines.indexOf(code) - 2]).toBe('Your SplitPro login code:'); + }); + + it('puts the code alone in its own element in the HTML part', () => { + const { html } = buildSignInEmail(url, code); + + expect(html).toEqual( + expect.stringContaining(`

${code}

`), + ); + }); + + it('includes a hidden preheader repeating the labelled code', () => { + const { html } = buildSignInEmail(url, code); + + expect(html).toMatch(/^
Your login code: 040046<\/div>/); + }); + }); + + describe('content', () => { + it('states the expiry derived from the code lifetime', () => { + const { text, html } = buildSignInEmail(url, code); + + expect(text).toEqual(expect.stringContaining('expires in 10 minutes')); + expect(html).toEqual(expect.stringContaining('expires in 10 minutes')); + }); + + it('still offers the magic link in both parts', () => { + const { text, html } = buildSignInEmail(url, code); + + expect(text).toEqual(expect.stringContaining(`\n${url}\n`)); + expect(html).toEqual(expect.stringContaining('>Sign in to splitpro.example.com')); + }); + + it('escapes the URL in the HTML href so query separators stay valid', () => { + const { html } = buildSignInEmail(url, code); + + expect(html).toEqual( + expect.stringContaining( + 'callbackUrl=https%3A%2F%2Fsplitpro.example.com&token=040046&email=', + ), + ); + expect(html).not.toEqual(expect.stringContaining('&token=')); + }); + + it('escapes HTML special characters in the token', () => { + const { html } = buildSignInEmail(url, ''); + + expect(html).not.toEqual(expect.stringContaining('')); + expect(html).toEqual(expect.stringContaining('<b>')); + }); + }); +}); + +describe('sendSignUpEmail', () => { + const url = 'https://splitpro.example.com/api/auth/callback/email?token=123456'; + + beforeEach(() => { + jest.clearAllMocks(); + (env as { NODE_ENV: string }).NODE_ENV = 'production'; + }); + + it('sends the AutoFill-friendly content built by buildSignInEmail', async () => { + mockSendMail.mockResolvedValue(mockSentMessageInfo); + + await expect(sendSignUpEmail('friend@example.com', url, '123456')).resolves.toBe(true); + + expect(mockSendMail).toHaveBeenCalledWith( + expect.objectContaining({ + to: 'friend@example.com', + from: 'noreply@example.com', + subject: 'Your SplitPro login code', + text: expect.stringContaining('\n123456\n'), + html: expect.stringContaining('>123456

'), + }), + ); + }); +}); + describe('NextAuth email provider Nodemailer compatibility', () => { it('uses Nodemailer createTransport and sendMail for verification requests', async () => { const server = { diff --git a/src/tests/verificationCode.test.ts b/src/tests/verificationCode.test.ts new file mode 100644 index 00000000..b6c9a4e3 --- /dev/null +++ b/src/tests/verificationCode.test.ts @@ -0,0 +1,42 @@ +import { randomInt } from 'node:crypto'; + +import { VERIFICATION_CODE_LENGTH } from '~/lib/verificationCode'; +import { generateVerificationCode } from '~/server/verificationCode'; + +jest.mock('node:crypto', () => { + const actual = jest.requireActual<{ randomInt: (min: number, max: number) => number }>( + 'node:crypto', + ); + return { ...actual, randomInt: jest.fn(actual.randomInt) }; +}); + +// `randomInt` is overloaded (sync/callback); only the sync (min, max) form is used here. +const mockRandomInt = randomInt as unknown as jest.Mock; + +describe('generateVerificationCode', () => { + afterEach(() => { + mockRandomInt.mockClear(); + }); + + describe('format', () => { + it('produces exactly the configured number of digits', () => { + Array.from({ length: 500 }).forEach(() => { + expect(generateVerificationCode()).toMatch( + new RegExp(`^\\d{${VERIFICATION_CODE_LENGTH}}$`), + ); + }); + }); + + it.each([ + [0, '000000'], + [46, '000046'], + [40_046, '040046'], + [909_928, '909928'], + [999_999, '999999'], + ])('zero-pads %d to %s', (value, expected) => { + mockRandomInt.mockReturnValueOnce(value); + + expect(generateVerificationCode()).toBe(expected); + }); + }); +}); diff --git a/src/tests/verificationStep.test.tsx b/src/tests/verificationStep.test.tsx new file mode 100644 index 00000000..25149d4c --- /dev/null +++ b/src/tests/verificationStep.test.tsx @@ -0,0 +1,87 @@ +/** @jest-environment jsdom */ + +import { fireEvent, screen, waitFor } from '@testing-library/react'; + +import { VERIFICATION_CODE_LENGTH } from '~/lib/verificationCode'; +import VerificationStep from '~/pages/auth/VerificationStep'; +import { renderWithProviders } from '~/tests/helpers/render'; + +const getCodeInput = () => { + const input = document.querySelector('input[data-input-otp]'); + if (!input) { + throw new Error('OTP input not rendered'); + } + return input; +}; + +// JSDOM has no ResizeObserver, which `input-otp` uses to size its caret overlay. +class ResizeObserverStub { + observe = jest.fn(); + unobserve = jest.fn(); + disconnect = jest.fn(); +} + +describe('VerificationStep', () => { + beforeAll(() => { + window.ResizeObserver = ResizeObserverStub; + // Also used by `input-otp` to detect password manager badges. + document.elementFromPoint = jest.fn(() => null); + }); + + beforeEach(() => { + renderWithProviders(); + }); + + describe('code input attributes (needed for iOS/Safari AutoFill)', () => { + it('declares itself a one-time-code field', () => { + expect(getCodeInput()).toHaveAttribute('autocomplete', 'one-time-code'); + }); + + it('opens the numeric keypad', () => { + expect(getCodeInput()).toHaveAttribute('inputmode', 'numeric'); + }); + + it('limits the input to the configured number of digits', () => { + expect(getCodeInput()).toHaveAttribute('maxlength', String(VERIFICATION_CODE_LENGTH)); + }); + }); + + describe('typing', () => { + it('accepts a full numeric code, including leading zeros', () => { + const input = getCodeInput(); + + fireEvent.change(input, { target: { value: '040046' } }); + + expect(input).toHaveValue('040046'); + }); + + it('ignores letters', () => { + const input = getCodeInput(); + + fireEvent.change(input, { target: { value: 'abcdef' } }); + + expect(input).toHaveValue(''); + }); + + it('truncates input longer than the code', () => { + const input = getCodeInput(); + + fireEvent.change(input, { target: { value: '12345678' } }); + + expect(input).toHaveValue('123456'); + }); + }); + + describe('validation', () => { + it('rejects an incomplete code', async () => { + fireEvent.change(getCodeInput(), { target: { value: '12345' } }); + fireEvent.click(screen.getByRole('button', { name: 'Submit' })); + + await waitFor(() => expect(screen.getByText('Invalid OTP')).toBeInTheDocument()); + }); + + it('does not show an error before submitting', () => { + expect(screen.queryByText('Invalid OTP')).not.toBeInTheDocument(); + }); + }); +}); diff --git a/src/tests/verificationTokens.test.ts b/src/tests/verificationTokens.test.ts new file mode 100644 index 00000000..4396f56d --- /dev/null +++ b/src/tests/verificationTokens.test.ts @@ -0,0 +1,181 @@ +import { type PrismaClient } from '@prisma/client'; +import { type Adapter, type VerificationToken } from 'next-auth/adapters'; + +import { scopeVerificationToken, withScopedVerificationTokens } from '~/server/verificationTokens'; + +/** + * In-memory stand-in for the Prisma adapter and table: `token` is globally unique, a row is + * deleted when used, and an unknown token yields `null`, like the real `VerificationToken` model. + */ +const createFakeStore = () => { + const rows: VerificationToken[] = []; + + const adapter = { + createVerificationToken: (data: VerificationToken) => { + if (rows.some(({ token }) => token === data.token)) { + return Promise.reject(new Error('Unique constraint failed on the fields: (`token`)')); + } + rows.push(data); + return Promise.resolve(data); + }, + useVerificationToken: ({ identifier, token }: { identifier: string; token: string }) => { + const index = rows.findIndex((row) => row.identifier === identifier && row.token === token); + return Promise.resolve(-1 === index ? null : (rows.splice(index, 1)[0] ?? null)); + }, + } as unknown as Adapter; + + const prisma = { + verificationToken: { + deleteMany: ({ where }: { where: { identifier: string; token: string } }) => { + const kept = rows.filter( + (row) => row.identifier !== where.identifier || row.token !== where.token, + ); + const count = rows.length - kept.length; + rows.splice(0, rows.length, ...kept); + return Promise.resolve({ count }); + }, + }, + } as unknown as Pick; + + return { rows, adapter, prisma }; +}; + +const inOneHour = () => new Date(Date.now() + 60 * 60 * 1000); + +// What NextAuth passes to the adapter: sha256(code + secret), independent of the identifier. +const HASHED_CODE = 'a'.repeat(64); +const OTHER_HASHED_CODE = 'b'.repeat(64); + +const issue = (adapter: Adapter, identifier: string, token = HASHED_CODE) => + adapter.createVerificationToken?.({ identifier, token, expires: inOneHour() }); + +const redeem = (adapter: Adapter, identifier: string, token = HASHED_CODE) => + adapter.useVerificationToken?.({ identifier, token }); + +describe('scopeVerificationToken', () => { + it('is deterministic', () => { + expect(scopeVerificationToken('a@example.com', HASHED_CODE)).toBe( + scopeVerificationToken('a@example.com', HASHED_CODE), + ); + }); + + it('differs per identifier and per token', () => { + const base = scopeVerificationToken('a@example.com', HASHED_CODE); + + expect(scopeVerificationToken('b@example.com', HASHED_CODE)).not.toBe(base); + expect(scopeVerificationToken('a@example.com', OTHER_HASHED_CODE)).not.toBe(base); + }); +}); + +describe('withScopedVerificationTokens', () => { + it('throws when the adapter has no verification token support', () => { + const { prisma } = createFakeStore(); + + expect(() => withScopedVerificationTokens({}, prisma)).toThrow( + 'Adapter is missing verification token support.', + ); + }); + + describe('two users drawing the same code (10^6 codes repeat)', () => { + it('control: the unwrapped adapter rejects the second user', async () => { + const { adapter } = createFakeStore(); + await issue(adapter, 'a@example.com'); + + await expect(issue(adapter, 'b@example.com')).rejects.toThrow('Unique constraint'); + }); + + it('lets both hold the code at once and redeem it independently', async () => { + const { adapter, prisma } = createFakeStore(); + const wrapped = withScopedVerificationTokens(adapter, prisma); + + await issue(wrapped, 'a@example.com'); + await expect(issue(wrapped, 'b@example.com')).resolves.toBeDefined(); + + await expect(redeem(wrapped, 'a@example.com')).resolves.toMatchObject({ + identifier: 'a@example.com', + }); + await expect(redeem(wrapped, 'b@example.com')).resolves.toMatchObject({ + identifier: 'b@example.com', + }); + }); + }); + + describe('storage', () => { + it('stores the identifier-scoped token instead of the raw hash', async () => { + const { rows, adapter, prisma } = createFakeStore(); + + await issue(withScopedVerificationTokens(adapter, prisma), 'a@example.com'); + + expect(rows.map(({ identifier, token }) => ({ identifier, token }))).toEqual([ + { + identifier: 'a@example.com', + token: scopeVerificationToken('a@example.com', HASHED_CODE), + }, + ]); + }); + }); + + describe('redeeming', () => { + it('only works for the identifier the code was issued to', async () => { + const { adapter, prisma } = createFakeStore(); + const wrapped = withScopedVerificationTokens(adapter, prisma); + await issue(wrapped, 'a@example.com'); + + await expect(redeem(wrapped, 'b@example.com')).resolves.toBeNull(); + }); + + it('is single use', async () => { + const { adapter, prisma } = createFakeStore(); + const wrapped = withScopedVerificationTokens(adapter, prisma); + await issue(wrapped, 'a@example.com'); + + await expect(redeem(wrapped, 'a@example.com')).resolves.not.toBeNull(); + await expect(redeem(wrapped, 'a@example.com')).resolves.toBeNull(); + }); + + it('rejects a wrong code', async () => { + const { adapter, prisma } = createFakeStore(); + const wrapped = withScopedVerificationTokens(adapter, prisma); + await issue(wrapped, 'a@example.com'); + + await expect(redeem(wrapped, 'a@example.com', OTHER_HASHED_CODE)).resolves.toBeNull(); + }); + }); + + describe('issuing another code to the same identifier', () => { + it('keeps earlier codes valid, so others cannot invalidate a pending code by requesting more', async () => { + const { adapter, prisma } = createFakeStore(); + const wrapped = withScopedVerificationTokens(adapter, prisma); + + await issue(wrapped, 'a@example.com', HASHED_CODE); + await issue(wrapped, 'a@example.com', OTHER_HASHED_CODE); + + await expect(redeem(wrapped, 'a@example.com', HASHED_CODE)).resolves.not.toBeNull(); + await expect(redeem(wrapped, 'a@example.com', OTHER_HASHED_CODE)).resolves.not.toBeNull(); + }); + + it('survives drawing the very same code twice (replaces that row instead of failing)', async () => { + const { rows, adapter, prisma } = createFakeStore(); + const wrapped = withScopedVerificationTokens(adapter, prisma); + + await issue(wrapped, 'a@example.com'); + await expect(issue(wrapped, 'a@example.com')).resolves.toBeDefined(); + + expect(rows).toHaveLength(1); + }); + + it('does not touch other identifiers’ rows when replacing', async () => { + const { rows, adapter, prisma } = createFakeStore(); + const wrapped = withScopedVerificationTokens(adapter, prisma); + + await issue(wrapped, 'b@example.com'); + await issue(wrapped, 'a@example.com'); + await issue(wrapped, 'a@example.com'); + + expect(rows.map(({ identifier }) => identifier).sort()).toEqual([ + 'a@example.com', + 'b@example.com', + ]); + }); + }); +});