Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): add app review sign-in otp (#760)

Generc0fa913680a8
diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.ts
index 13132b294..698a129de 100644
--- a/src/web/src/env.d.ts
+++ b/src/web/src/env.d.ts
@@ -1,5 +1,7 @@
interface RuntimeEnv {
ENCRYPTION_KEY: string
+ APP_REVIEW_EMAIL?: string
+ APP_REVIEW_OTP?: string
AUTH_OTP_RATE_LIMIT_MAX?: string
AUTH_OTP_RATE_LIMIT_WINDOW_SEC?: string
DEVICE_CLIENT_IDS?: string
diff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.ts
index c9952ed10..65c7a621b 100644
--- a/src/web/src/lib/auth.test.ts
+++ b/src/web/src/lib/auth.test.ts
@@ -3,6 +3,22 @@ import { afterEach, describe, it, expect, vi, beforeEach } from "vitest"
const appleMocks = vi.hoisted(() => ({
generateClientSecret: vi.fn(async () => "signed-apple-client-secret"),
}))
+const authLogMocks = vi.hoisted(() => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+}))
+const cloudflareMocks = vi.hoisted(() => {
+ const waitUntil = vi.fn<(promise: Promise<unknown>) => void>()
+ return {
+ waitUntil,
+ getCloudflareContext: vi.fn(() => ({ ctx: { waitUntil } })),
+ }
+})
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: cloudflareMocks.getCloudflareContext,
+}))
vi.mock("better-auth", () => ({
betterAuth: vi.fn((opts: unknown) => ({ __options: opts })),
@@ -53,7 +69,7 @@ vi.mock("@alook/shared", async (importOriginal) => {
const actual = await importOriginal<typeof import("@alook/shared")>()
return {
...actual,
- createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
+ createLogger: () => authLogMocks,
DEV_EMAIL_WORKER_URL: "http://localhost:0",
}
})
@@ -110,7 +126,20 @@ type AuthOptions = {
__plugin?: string
id?: string
cfg?: Record<string, unknown> & {
- sendVerificationOTP?: (args: { email: string; otp: string; type: string }) => Promise<void>
+ expiresIn?: number
+ allowedAttempts?: number
+ storeOTP?: string
+ generateOTP?: (args: { email: string; type: EmailOtpType }) => string | undefined
+ sendVerificationOTP?: (
+ args: { email: string; otp: string; type: EmailOtpType },
+ ctx?: {
+ context: {
+ internalAdapter: {
+ deleteVerificationByIdentifier: (identifier: string) => Promise<void>
+ }
+ }
+ },
+ ) => Promise<void>
}
}>
session?: {
@@ -138,6 +167,8 @@ type AuthOptions = {
}
}
+type EmailOtpType = "sign-in" | "email-verification" | "forget-password" | "change-email"
+
async function loadCreateAuth() {
vi.resetModules()
const mod = await import("./auth")
@@ -153,6 +184,13 @@ function getSendOtp(opts: AuthOptions) {
return fn
}
+function getGenerateOtp(opts: AuthOptions) {
+ const otp = opts.plugins?.find((p) => p?.__plugin === "emailOTP")
+ const fn = otp?.cfg?.generateOTP
+ if (!fn) throw new Error("emailOTP generator not present")
+ return fn
+}
+
describe("createAuth rate limiting", () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -228,6 +266,220 @@ describe("createAuth rate limiting", () => {
})
})
+describe("createAuth App Review OTP", () => {
+ const reviewEmail = "[email protected]"
+ const reviewOtp = "246810"
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockCheckRateLimit.mockReset().mockResolvedValue({ allowed: true })
+ })
+
+ function createReviewAuth(overrides: Partial<Record<string, unknown>> = {}) {
+ return loadCreateAuth().then((createAuth) => {
+ const env = makeEnv({
+ NODE_ENV: "production",
+ APP_REVIEW_EMAIL: ` ${reviewEmail.toUpperCase()} `,
+ APP_REVIEW_OTP: reviewOtp,
+ ...overrides,
+ })
+ const opts = (createAuth(env as never) as { __options: AuthOptions }).__options
+ return { env, opts }
+ })
+ }
+
+ it("uses the fixed six-digit code only for the normalized exact sign-in email", async () => {
+ const { opts } = await createReviewAuth()
+ const generateOtp = getGenerateOtp(opts)
+
+ expect(generateOtp({ email: reviewEmail.toUpperCase(), type: "sign-in" })).toBe(reviewOtp)
+ expect(generateOtp({ email: `other-${reviewEmail}`, type: "sign-in" })).toBeUndefined()
+ expect(generateOtp({ email: `[email protected]`, type: "sign-in" })).toBeUndefined()
+ expect(generateOtp({ email: reviewEmail, type: "email-verification" })).toBeUndefined()
+ expect(generateOtp({ email: reviewEmail, type: "forget-password" })).toBeUndefined()
+ expect(generateOtp({ email: reviewEmail, type: "change-email" })).toBeUndefined()
+ })
+
+ it("keeps the DO limiter but skips email delivery for the review sign-in", async () => {
+ const { env, opts } = await createReviewAuth()
+
+ await getSendOtp(opts)({
+ email: reviewEmail.toUpperCase(),
+ otp: reviewOtp,
+ type: "sign-in",
+ })
+
+ expect(mockCheckRateLimit).toHaveBeenCalledWith(
+ env,
+ "auth:otpSend",
+ "app-review",
+ { windowMs: 60_000, max: 5 },
+ )
+ expect(env.EMAIL_WORKER.fetch).not.toHaveBeenCalled()
+ })
+
+ it("keeps email delivery for similar emails and other OTP types", async () => {
+ const { env, opts } = await createReviewAuth()
+ const sendOtp = getSendOtp(opts)
+
+ await sendOtp({ email: "[email protected]", otp: "135790", type: "sign-in" })
+ await sendOtp({ email: reviewEmail, otp: "975310", type: "email-verification" })
+
+ expect(env.EMAIL_WORKER.fetch).toHaveBeenCalledTimes(2)
+ expect(cloudflareMocks.waitUntil).toHaveBeenCalledTimes(2)
+ })
+
+ it("waits for the DO gate but not ordinary email delivery", async () => {
+ let allowRateLimit: ((result: { allowed: true }) => void) | undefined
+ mockCheckRateLimit.mockReturnValueOnce(new Promise((resolve) => {
+ allowRateLimit = resolve
+ }))
+ let finishEmail: ((response: Response) => void) | undefined
+ const emailFetch = vi.fn(() => new Promise<Response>((resolve) => {
+ finishEmail = resolve
+ }))
+ const { opts } = await createReviewAuth({
+ EMAIL_WORKER: { fetch: emailFetch },
+ })
+
+ const send = getSendOtp(opts)({
+ email: "[email protected]",
+ otp: "135790",
+ type: "sign-in",
+ })
+ await Promise.resolve()
+ expect(emailFetch).not.toHaveBeenCalled()
+ expect(cloudflareMocks.waitUntil).not.toHaveBeenCalled()
+
+ allowRateLimit?.({ allowed: true })
+ await expect(send).resolves.toBeUndefined()
+ expect(emailFetch).toHaveBeenCalledOnce()
+ expect(cloudflareMocks.waitUntil).toHaveBeenCalledOnce()
+
+ const backgroundSend = cloudflareMocks.waitUntil.mock.calls[0]?.[0]
+ if (!backgroundSend) throw new Error("email send was not registered")
+ let backgroundSettled = false
+ void backgroundSend.then(() => { backgroundSettled = true })
+ await Promise.resolve()
+ expect(backgroundSettled).toBe(false)
+
+ finishEmail?.(new Response("ok", { status: 200 }))
+ await expect(backgroundSend).resolves.toBeUndefined()
+ })
+
+ it("contains background email failures after returning from the send callback", async () => {
+ const { opts } = await createReviewAuth({
+ EMAIL_WORKER: {
+ fetch: vi.fn().mockResolvedValue(new Response("worker down", { status: 503 })),
+ },
+ })
+
+ await expect(getSendOtp(opts)({
+ email: "[email protected]",
+ otp: "135790",
+ type: "sign-in",
+ })).resolves.toBeUndefined()
+
+ const backgroundSend = cloudflareMocks.waitUntil.mock.calls[0]?.[0]
+ if (!backgroundSend) throw new Error("email send was not registered")
+ await expect(backgroundSend).resolves.toBeUndefined()
+ expect(authLogMocks.error).toHaveBeenCalledWith(
+ "OTP email failed",
+ expect.objectContaining({ to: "[email protected]", type: "sign-in" }),
+ )
+ })
+
+ it("awaits email delivery when Cloudflare background scheduling is unavailable", async () => {
+ cloudflareMocks.getCloudflareContext.mockImplementationOnce(() => {
+ throw new Error("context unavailable")
+ })
+ let finishEmail: ((response: Response) => void) | undefined
+ const emailFetch = vi.fn(() => new Promise<Response>((resolve) => {
+ finishEmail = resolve
+ }))
+ const { opts } = await createReviewAuth({
+ EMAIL_WORKER: { fetch: emailFetch },
+ })
+
+ let callbackSettled = false
+ const send = getSendOtp(opts)({
+ email: "[email protected]",
+ otp: "135790",
+ type: "sign-in",
+ }).then(() => { callbackSettled = true })
+ await vi.waitFor(() => expect(emailFetch).toHaveBeenCalledOnce())
+
+ expect(cloudflareMocks.waitUntil).not.toHaveBeenCalled()
+ expect(callbackSettled).toBe(false)
+ finishEmail?.(new Response("ok", { status: 200 }))
+ await expect(send).resolves.toBeUndefined()
+ expect(callbackSettled).toBe(true)
+ })
+
+ it.each([undefined, "", "12345", "12345a", "1234567"])(
+ "fails closed for a matching review email when the OTP secret is %j",
+ async (configuredOtp) => {
+ const { env, opts } = await createReviewAuth({ APP_REVIEW_OTP: configuredOtp })
+ const generateOtp = getGenerateOtp(opts)
+
+ expect(() => generateOtp({ email: reviewEmail, type: "sign-in" }))
+ .toThrow("Verification code unavailable")
+ expect(env.EMAIL_WORKER.fetch).not.toHaveBeenCalled()
+ },
+ )
+
+ it.each([undefined, "", "not-an-email"])(
+ "does not enable the fixed path when the review email secret is %j",
+ async (configuredEmail) => {
+ const { env, opts } = await createReviewAuth({ APP_REVIEW_EMAIL: configuredEmail })
+
+ expect(getGenerateOtp(opts)({ email: reviewEmail, type: "sign-in" })).toBeUndefined()
+ await getSendOtp(opts)({ email: reviewEmail, otp: "135790", type: "sign-in" })
+ expect(env.EMAIL_WORKER.fetch).toHaveBeenCalledOnce()
+ },
+ )
+
+ it("removes the staged review challenge when the DO limiter blocks", async () => {
+ mockCheckRateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSec: 42 })
+ const deleteVerificationByIdentifier = vi.fn(async () => undefined)
+ const { env, opts } = await createReviewAuth()
+
+ await expect(getSendOtp(opts)(
+ { email: reviewEmail, otp: reviewOtp, type: "sign-in" },
+ { context: { internalAdapter: { deleteVerificationByIdentifier } } },
+ )).rejects.toThrow("OTP rate limit; retry in 42s")
+
+ expect(deleteVerificationByIdentifier).toHaveBeenCalledWith(
+ `sign-in-otp-${reviewEmail}`,
+ )
+ expect(env.EMAIL_WORKER.fetch).not.toHaveBeenCalled()
+ expect(JSON.stringify(authLogMocks.warn.mock.calls)).not.toContain(reviewEmail)
+ expect(JSON.stringify(authLogMocks.warn.mock.calls)).not.toContain(reviewOtp)
+ })
+
+ it("fails closed if the send callback does not receive the configured review code", async () => {
+ const { env, opts } = await createReviewAuth()
+
+ await expect(getSendOtp(opts)({
+ email: reviewEmail,
+ otp: "135790",
+ type: "sign-in",
+ })).rejects.toThrow("Verification code unavailable")
+ expect(env.EMAIL_WORKER.fetch).not.toHaveBeenCalled()
+ })
+
+ it("pins the five-minute expiry, three-attempt budget, and encrypted storage", async () => {
+ const { opts } = await createReviewAuth()
+ const plugin = opts.plugins?.find((candidate) => candidate.__plugin === "emailOTP")
+
+ expect(plugin?.cfg).toMatchObject({
+ expiresIn: 5 * 60,
+ allowedAttempts: 3,
+ storeOTP: "encrypted",
+ })
+ })
+})
+
describe("sendOtpEmail", () => {
afterEach(() => vi.unstubAllGlobals())
diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.ts
index 08d11aec5..0a07bbe39 100644
--- a/src/web/src/lib/auth.ts
+++ b/src/web/src/lib/auth.ts
@@ -1,5 +1,6 @@
import { betterAuth } from "better-auth"
import { emailOTP, deviceAuthorization, bearer, oneTimeToken } from "better-auth/plugins"
+import { getCloudflareContext } from "@opennextjs/cloudflare"
import { nanoid } from "nanoid"
import {
createLogger,
@@ -8,6 +9,7 @@ import {
queries,
COMMUNITY_BOT_EMAIL_DOMAIN,
RATE_LIMITS,
+ isValidEmail,
sanitizeCommunityName,
} from "@alook/shared"
import { getDb, getPrimaryDb } from "@/lib/db"
@@ -27,6 +29,35 @@ const DEFAULT_OTP_RATE_LIMIT_MAX = RATE_LIMITS["auth:otpSend"].max
const DEFAULT_OTP_RATE_LIMIT_WINDOW_SEC = Math.round(
RATE_LIMITS["auth:otpSend"].windowMs / 1000,
)
+const APP_REVIEW_OTP_PATTERN = /^\d{6}$/u
+const APP_REVIEW_OTP_UNAVAILABLE = "Verification code unavailable"
+const APP_REVIEW_RATE_LIMIT_KEY = "app-review"
+
+type EmailOtpType = Exclude<OtpType, "account-deletion">
+
+function normalizeAuthEmail(email: string): string {
+ return email.trim().toLowerCase()
+}
+
+function resolveAppReviewSignInOtp(
+ env: Env,
+ input: { email: string; type: EmailOtpType },
+): string | undefined {
+ const reviewEmail = normalizeAuthEmail(env.APP_REVIEW_EMAIL ?? "")
+ if (
+ input.type !== "sign-in"
+ || !isValidEmail(reviewEmail)
+ || normalizeAuthEmail(input.email) !== reviewEmail
+ ) {
+ return undefined
+ }
+
+ const reviewOtp = env.APP_REVIEW_OTP
+ if (!reviewOtp || !APP_REVIEW_OTP_PATTERN.test(reviewOtp)) {
+ throw new Error(APP_REVIEW_OTP_UNAVAILABLE)
+ }
+ return reviewOtp
+}
function parsePositiveInt(raw: string | undefined, fallback: number): number {
if (!raw) return fallback
@@ -298,23 +329,56 @@ export function createAuth(env: Env) {
storeToken: "hashed",
}),
emailOTP({
- async sendVerificationOTP({ email, otp, type }) {
- // Rate-limit BEFORE minting/sending the OTP so abuse can't
- // burn a token slot or hit the email worker. Keyed by email
- // (the sender's target); anyone attempting to spam a
- // specific inbox gets throttled per inbox.
- const rate = await checkRateLimit(env, "auth:otpSend", email, {
- windowMs: otpPolicy.windowMs,
- max: otpPolicy.max,
+ expiresIn: 5 * 60,
+ allowedAttempts: 3,
+ storeOTP: "encrypted",
+ generateOTP({ email, type }) {
+ return resolveAppReviewSignInOtp(env, { email, type })
+ },
+ async sendVerificationOTP({ email, otp, type }, ctx) {
+ const normalizedEmail = normalizeAuthEmail(email)
+ const appReviewOtp = resolveAppReviewSignInOtp(env, {
+ email: normalizedEmail,
+ type,
})
+ const rate = await checkRateLimit(
+ env,
+ "auth:otpSend",
+ appReviewOtp ? APP_REVIEW_RATE_LIMIT_KEY : normalizedEmail,
+ {
+ windowMs: otpPolicy.windowMs,
+ max: otpPolicy.max,
+ },
+ )
if (!rate.allowed) {
- log.warn("OTP send rate-limited", {
- to: email,
- retryAfterSec: rate.retryAfterSec,
- })
+ if (appReviewOtp) {
+ await ctx?.context.internalAdapter.deleteVerificationByIdentifier(
+ `sign-in-otp-${normalizedEmail}`,
+ )
+ }
+ log.warn(
+ "OTP send rate-limited",
+ appReviewOtp
+ ? { retryAfterSec: rate.retryAfterSec }
+ : { to: normalizedEmail, retryAfterSec: rate.retryAfterSec },
+ )
throw new Error(`OTP rate limit; retry in ${rate.retryAfterSec}s`)
}
- await sendOtpEmail(env, { email, otp, type })
+ if (appReviewOtp) {
+ if (otp !== appReviewOtp) throw new Error(APP_REVIEW_OTP_UNAVAILABLE)
+ return
+ }
+ const emailSend = sendOtpEmail(env, {
+ email: normalizedEmail,
+ otp,
+ type,
+ }).catch(() => undefined)
+ try {
+ getCloudflareContext().ctx.waitUntil(emailSend)
+ } catch {
+ // Outside Cloudflare, keep the request alive until delivery settles.
+ await emailSend
+ }
},
}),
]