Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix(auth): invalidate email OTP on a failed guess, not just a match

addyCooks2562bc18c517
diff --git a/apps/web/__tests__/unit/verification-token.test.ts b/apps/web/__tests__/unit/verification-token.test.ts
new file mode 100644
index 000000000..54822e448
--- /dev/null
+++ b/apps/web/__tests__/unit/verification-token.test.ts
@@ -0,0 +1,98 @@
+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";
+import { describe, expect, it } from "vitest";
+import { DrizzleAdapter } from "../../../../packages/database/auth/drizzle-adapter";
+
+type TokenRow = { identifier: string; token: string; expires: Date };
+
+function parsePredicate(condition: SQL) {
+ 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,
+ };
+}
+
+function fakeDatabase(initialRow: TokenRow) {
+ 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] : [];
+ },
+ }),
+ }),
+ }),
+ delete: () => ({
+ where: async (condition: SQL) => {
+ if (!row) return;
+ const { column, value } = parsePredicate(condition);
+ if (row[column] === value) row = undefined;
+ },
+ }),
+ };
+ return { db: db as unknown as MySql2Database, getRow: () => row };
+}
+
+describe("useVerificationToken", () => {
+ const identifier = "[email protected]";
+ const validRow: TokenRow = {
+ identifier,
+ token: "111111",
+ expires: new Date(Date.now() + 60_000),
+ };
+
+ it("burns the code on a wrong guess instead of leaving it guessable", async () => {
+ const { db, getRow } = fakeDatabase({ ...validRow });
+ const adapter = DrizzleAdapter(db);
+
+ const wrongGuess = await adapter.useVerificationToken?.({
+ identifier,
+ token: "000000",
+ });
+
+ expect(wrongGuess).toBeNull();
+ expect(getRow()).toBeUndefined();
+
+ const correctGuessAfterward = await adapter.useVerificationToken?.({
+ identifier,
+ token: "111111",
+ });
+ expect(correctGuessAfterward).toBeNull();
+ });
+
+ it("returns the row and deletes it on a correct guess", async () => {
+ const { db, getRow } = fakeDatabase({ ...validRow });
+ const adapter = DrizzleAdapter(db);
+
+ const result = await adapter.useVerificationToken?.({
+ identifier,
+ token: "111111",
+ });
+
+ expect(result).toMatchObject({ identifier, token: "111111" });
+ expect(getRow()).toBeUndefined();
+ });
+
+ it("returns null when no code was ever requested for the identifier", async () => {
+ const { db } = fakeDatabase({ ...validRow });
+ const adapter = DrizzleAdapter(db);
+
+ const result = await adapter.useVerificationToken?.({
+ identifier: "[email protected]",
+ token: "111111",
+ });
+
+ expect(result).toBeNull();
+ });
+});
diff --git a/packages/database/auth/drizzle-adapter.ts b/packages/database/auth/drizzle-adapter.ts
index 16f7e1045..57e663f2c 100644
--- a/packages/database/auth/drizzle-adapter.ts
+++ b/packages/database/auth/drizzle-adapter.ts
@@ -510,31 +510,28 @@ export function DrizzleAdapter(
return row;
},
async useVerificationToken({ identifier, token }) {
+ const normalizedIdentifier = identifier?.toLowerCase() ?? "";
const rows = await db
.select()
.from(verificationTokens)
- .where(eq(verificationTokens.token, token))
+ .where(eq(verificationTokens.identifier, normalizedIdentifier))
.limit(1);
const row = rows[0];
if (!row) {
console.warn("[useVerificationToken] No token found");
return null;
}
- const normalizedIdentifier = identifier?.toLowerCase() ?? "";
- const storedIdentifier = row.identifier?.toLowerCase() ?? "";
- if (normalizedIdentifier !== storedIdentifier) {
- console.warn("[useVerificationToken] Identifier mismatch");
- 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
.delete(verificationTokens)
- .where(
- and(
- eq(verificationTokens.token, token),
- eq(verificationTokens.identifier, row.identifier),
- ),
- );
- return { ...row, identifier: storedIdentifier };
+ .where(eq(verificationTokens.identifier, row.identifier));
+
+ if (row.token !== token) {
+ console.warn("[useVerificationToken] Token mismatch");
+ return null;
+ }
+ return { ...row, identifier: normalizedIdentifier };
},
};
}