Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(auth): make OTP consumption atomic to close concurrent-guess race
addyCooks1dd7b68300a1
diff --git a/apps/web/__tests__/unit/verification-token.test.ts b/apps/web/__tests__/unit/verification-token.test.tsindex 54822e448..ea7c96357 100644--- a/apps/web/__tests__/unit/verification-token.test.ts+++ b/apps/web/__tests__/unit/verification-token.test.ts@@ -1,4 +1,3 @@-import { verificationTokens } from "@cap/database/schema";import type { SQL } from "drizzle-orm";import { MySqlDialect } from "drizzle-orm/mysql-core";import type { MySql2Database } from "drizzle-orm/mysql2";@@ -7,41 +6,53 @@ import { DrizzleAdapter } from "../../../../packages/database/auth/drizzle-adapttype TokenRow = { identifier: string; token: string; expires: Date };-function parsePredicate(condition: SQL) {+function matchesPredicate(condition: SQL, row: TokenRow) {const query = new MySqlDialect().sqlToQuery(condition);- const match = /^`verification_tokens`\.`(identifier|token)` = \?$/.exec(- query.sql,- );- if (!match?.[1]) throw new Error(`Unexpected predicate: ${query.sql}`);- return {- column: match[1] as "identifier" | "token",- value: query.params[0] as string,- };+ const columns = [+ ...query.sql.matchAll(+ /`verification_tokens`\.`(identifier|token)`\s*=\s*\?/g,+ ),+ ].map((match) => match[1] as "identifier" | "token");+ if (columns.length === 0) {+ throw new Error(`Unexpected predicate: ${query.sql}`);+ }+ return columns.every((column, i) => row[column] === query.params[i]);}-function fakeDatabase(initialRow: TokenRow) {+function fakeDatabase(+ initialRow: TokenRow,+ options?: { afterSelect?: () => void },+) {let row: TokenRow | undefined = initialRow;const db = {select: () => ({from: () => ({where: (condition: SQL) => ({limit: async () => {- if (!row) return [];- const { column, value } = parsePredicate(condition);- return row[column] === value ? [row] : [];+ const result = row && matchesPredicate(condition, row) ? [row] : [];+ options?.afterSelect?.();+ return result;},}),}),}),delete: () => ({where: async (condition: SQL) => {- if (!row) return;- const { column, value } = parsePredicate(condition);- if (row[column] === value) row = undefined;+ if (row && matchesPredicate(condition, row)) {+ row = undefined;+ return [{ affectedRows: 1 }];+ }+ return [{ affectedRows: 0 }];},}),};- return { db: db as unknown as MySql2Database, getRow: () => row };+ return {+ db: db as unknown as MySql2Database,+ getRow: () => row,+ setRow: (next: TokenRow) => {+ row = next;+ },+ };}describe("useVerificationToken", () => {@@ -95,4 +106,41 @@ describe("useVerificationToken", () => {expect(result).toBeNull();});++ it("lets only one of two concurrent correct guesses succeed", async () => {+ const { db, getRow } = fakeDatabase({ ...validRow });+ const adapter = DrizzleAdapter(db);++ const [first, second] = await Promise.all([+ adapter.useVerificationToken?.({ identifier, token: "111111" }),+ adapter.useVerificationToken?.({ identifier, token: "111111" }),+ ]);++ const successes = [first, second].filter((result) => result !== null);+ expect(successes).toHaveLength(1);+ expect(getRow()).toBeUndefined();+ });++ it("does not delete a resent code that replaced the row a guess read", async () => {+ const resentRow: TokenRow = {+ identifier,+ token: "222222",+ expires: new Date(Date.now() + 60_000),+ };+ const { db, getRow, setRow } = fakeDatabase(+ { ...validRow },+ {+ afterSelect: () => setRow({ ...resentRow }),+ },+ );+ const adapter = DrizzleAdapter(db);++ const wrongGuessAgainstStaleCode = await adapter.useVerificationToken?.({+ identifier,+ token: "000000",+ });++ expect(wrongGuessAgainstStaleCode).toBeNull();+ expect(getRow()).toEqual(resentRow);+ });});diff --git a/packages/database/auth/drizzle-adapter.ts b/packages/database/auth/drizzle-adapter.tsindex 57e663f2c..882fd950b 100644--- a/packages/database/auth/drizzle-adapter.ts+++ b/packages/database/auth/drizzle-adapter.ts@@ -17,6 +17,15 @@ import {} from "../schema.ts";import type { ValidatedSsoIdentity } from "./sso.ts";+const getAffectedRows = (result: unknown) => {+ if (Array.isArray(result)) {+ return (+ (result[0] as { affectedRows?: number } | undefined)?.affectedRows ?? 0+ );+ }+ return (result as { affectedRows?: number } | undefined)?.affectedRows ?? 0;+};+type CreateUserData = Parameters<NonNullable<Adapter["createUser"]>>[0];type LinkAccountData = Parameters<NonNullable<Adapter["linkAccount"]>>[0];type UnlinkAccountData = Parameters<NonNullable<Adapter["unlinkAccount"]>>[0];@@ -521,12 +530,24 @@ export function DrizzleAdapter(console.warn("[useVerificationToken] No token found");return null;}- // Delete on every attempt (not just a match) so a wrong guess burns the- // code instead of leaving it guessable for the rest of its TTL.- await db+ // Claim the exact row we just read (identifier + token) with a single+ // delete, and only proceed if we actually removed it. This makes+ // consumption atomic: concurrent requests race on the same delete, so+ // at most one of them can claim the row, whether the guess is right or+ // wrong. Scoping by token too (not identifier alone) means the delete+ // can't clobber a resend that replaced this row after we read it.+ const result = await db.delete(verificationTokens)- .where(eq(verificationTokens.identifier, row.identifier));-+ .where(+ and(+ eq(verificationTokens.identifier, row.identifier),+ eq(verificationTokens.token, row.token),+ ),+ );+ if (getAffectedRows(result) !== 1) {+ console.warn("[useVerificationToken] Token already consumed");+ return null;+ }if (row.token !== token) {console.warn("[useVerificationToken] Token mismatch");return null;