fix(login): suggest the fix for a mistyped email domain and never send a code to one (BUG-2395)
Independent Staging Quality Gate / validate-python (push) Successful in 7m59s
Independent Staging Quality Gate / validate-frontend (push) Successful in 7m10s
Independent Staging Quality Gate / publish (push) Successful in 3m59s

Codes sent to addresses like x@qq.con bounced; the bounce rate rose to 21%,
far above the provider's risk line. The email field now offers the corrected
address inline, and the server refuses the four code-sending endpoints for
suffixes no mail domain uses, before a code is made.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DbBXp3RzgZVEpT1PXxkwHj
This commit is contained in:
2026-11-25 22:25:16 +08:00
co-authored by Claude Opus 5.5
parent 969cfb9e48
commit a56bfc6e60
7 changed files with 416 additions and 22 deletions
+16
View File
@@ -32551,3 +32551,19 @@
- 相关记录:BUG-1507(新疆部分由本条关闭)、BUG-1971(自己选流程;平票两按钮由本条取代)、BUG-2192、BUG-2256(随缘版记录)、BUG-2272。
- 复发自:无
- 修复版本:分支 `claude/rect-tie-tz-2355`(待父会话推送)。
## BUG-2395 | 邮箱后缀打错(如 qq.con)时照样发验证码,退信率升到 21%
- **状态**:resolved(staging 待推)
- **现象**:负责人转来发信服务后台截图:近一天退信率 21.43%,远高于服务商 4% 的风险线;被退回的全是后缀打错的地址(`@qq.con`),同一个错地址连点几次发送。用户收不到验证码,页面只说「暂时无法发送」或什么都不说。
- **触发条件**:登录、注册或重设密码时邮箱后缀打错,例如 `.con`、`.cmo`、`gmial.com`。
- **根因**:登录页只有浏览器自带的邮箱格式检查,`x@qq.con` 格式合法;服务端收到就生成验证码并调用发信接口。发信量小时几封退信就把退信率推过风险线,长期如此服务商会限制整个账号发信。
- **修复**:
- `frontend/src/lib/email-typo.ts`:`emailDomainTypo`(最后一段是任何邮箱都不会用的后缀,如 con/cmo/comm)与 `suggestEmailFix`(和常见邮箱服务商域名只差一个字,且只匹配一个时给出改正后的地址)。
- `frontend/src/modules/identity/auth-factory.ts`:Better Auth `hooks.before` 在四个发验证码接口上拒绝 `emailDomainTypo` 的地址(400,code `EMAIL_DOMAIN_TYPO`),在生成验证码和调用发信之前。
- `frontend/src/modules/identity/client.ts`:发送与重设密码遇到这个 code 时提示「这个邮箱地址的后缀好像不完整,请检查一下再发送」,不再说「请稍后再试」。
- `frontend/src/components/email-otp-login.tsx`:两个邮箱输入框改为 `EmailField`(负责人 11-25 追加「后缀放进输入框右边下拉,选了自动替换」):输入框右侧「@后缀 ▾」菜单列 16 个常用后缀(qq、163、gmail、126、icloud、outlook 等);选中后框里只填 @ 前面的部分,后缀自动接上,换一个就直接替换;自己打出「@」或浏览器自动填入完整地址就回到整址输入;菜单末项「其他邮箱(自己输入完整地址)」;打了「@y」时菜单只列 y 开头的后缀。整址输入时一打出「@」,框下自动展开后缀列表(负责人 11-25「@之后自动展开」),随后续字母收窄(`@y` → yahoo.com、yeah.net),点一项补全,焦点留在输入框,↑↓/回车可选,Esc、离开输入框或后缀已完整时收起;列表浮在下方,不推动页面。整址输入时域名差一个字,框下显示「是不是 …@qq.com?」,点地址即改正。只是帮助,不拦发送,不用 toast。
- **验证**:新测 `frontend/tests/email-typo-2395.test.ts` 6 条;登录/身份相关前端测试 104 条中 103 过,1 条 `identity-auth-integration` 需要本机 docker 启 Postgres(本机无 docker,CI 跑);tsc 无错;`npx eslint .` 0 错。
- **防复发**:测试钉住纠错与拒发规则、拦截挂在四个发码路径、客户端提示文字、两个输入框都有内联提示。
- **关联记录**:BUG-2348(发信重试与失败信号)、BUG-2346、BUG-2056(结果用 toast,内联提示除外)。
- **修复版本**:1.5(待发)。
+14
View File
@@ -3035,6 +3035,20 @@ input:not([type="radio"]):not([type="checkbox"]):not([class^="ant-"]):not([class
.auth-center { min-width: 0; width: 100%; display: grid; grid-template-columns: minmax(0, 1fr); justify-items: center; align-content: center; gap: var(--space-6); padding: var(--space-8) 0 var(--space-12); text-align: center; }
.auth-body { width: min(340px, 100%); display: grid; gap: var(--space-4); text-align: left; }
.auth-heading { width: 100%; min-width: 0; display: grid; grid-template-columns: minmax(0, 1fr); justify-items: center; gap: var(--space-3); }
/* BUG-2395: the ending menu sits inside the email field on the right. */
.auth-email-field { position: relative; min-width: 0; }
.auth-email-field input { padding-right: 164px; }
.auth-email-domain-trigger { position: absolute; top: 4px; right: 4px; bottom: 4px; display: inline-flex; align-items: center; gap: 4px; max-width: 156px; height: auto; min-height: 0; padding: 0 10px; border: 0; border-radius: calc(var(--radius-md, 8px) - 2px); background: var(--color-surface-muted, transparent); color: var(--color-ink-secondary); font-size: var(--type-body-sm); white-space: nowrap; cursor: pointer; }
.auth-email-domain-trigger span { overflow: hidden; text-overflow: ellipsis; }
.auth-email-domain-trigger svg { flex: none; width: 14px; height: 14px; }
.auth-email-domain-menu { max-height: min(360px, 60vh); overflow-y: auto; }
.auth-email-domain-item { min-height: 40px; }
.auth-email-suggest { position: absolute; z-index: 20; top: calc(100% + 6px); left: 0; right: 0; max-height: min(264px, 45vh); overflow-y: auto; padding: 6px; border: 1px solid var(--color-border); border-radius: var(--radius-lg); background: var(--color-canvas); box-shadow: var(--shadow-elevated); }
.auth-email-suggest-item { display: flex; gap: 0; width: 100%; justify-content: flex-start; height: 44px; padding: 0 12px; overflow: hidden; color: var(--color-ink-secondary); font-weight: 400; text-overflow: ellipsis; white-space: nowrap; }
.auth-email-suggest-item strong { color: var(--color-ink); font-weight: 500; }
.auth-email-suggest-item[data-active] { background: var(--sidebar-accent); }
.auth-email-hint { margin: 0; color: var(--color-ink-secondary); font-size: var(--type-body-sm); line-height: 1.5; }
.auth-email-hint-fix { display: inline; height: auto; min-height: 0; padding: 0; color: var(--color-ink); font: inherit; text-decoration: underline; text-underline-offset: 3px; vertical-align: baseline; }
.auth-intro { max-width: 340px; margin: 0; color: var(--color-ink-secondary); font-size: var(--type-body-sm); line-height: 1.6; text-wrap: pretty; }
/* The headline is in the server HTML. With motion allowed it waits hidden (at its final
size) for up to 2 s while the script loads, then types out; past 2 s it simply shows. */
+144 -22
View File
@@ -8,6 +8,10 @@ import { LoginConsentNotice, LoginLegalFooter } from "@/components/legal/login-c
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ChevronDown } from "lucide-react";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/dropdown-menu-lazy";
import { autoEmailDomains, menuEmailDomains, suggestEmailFix } from "@/lib/email-typo";
import { recordLegalConsent } from "@/lib/legal-consent-client";
import { findEarlyLoginForm, LOGIN_EMAIL_FORM_ID, LOGIN_EMAIL_INPUT_ID, takeEarlyLoginInput } from "@/lib/login-early-input";
import { dismissNotice, notifyError, notifyInfo, notifySuccess, NOTICE_DURATION_MS } from "@/lib/notify";
@@ -84,6 +88,130 @@ function authMessage(caught: unknown) {
return message;
}
// BUG-2395 (owner 11-25: endings in a menu at the right of the field, replaced on pick).
// With an ending picked, the field holds only the part before 「@」 and the ending is added; typing 「@」
// (or an autofilled full address) goes back to the whole address. A domain one slip from a common provider
// (`qq.con`) gets 「是不是 …?」 under the field. A typed 「@y」 narrows the menu to the endings starting with y.
// Typing 「@」 opens the endings under the field by themselves (the field keeps the focus; ↑↓ and Enter work);
// they narrow as letters follow and close on a pick, Esc, leaving the field, or a complete known ending. Only help: nothing is blocked here, nothing is a toast.
type EmailFieldProps = {
id: string;
name?: string;
email: string;
picked: string | null;
placeholder: string;
onChange: (email: string, picked: string | null) => void;
};
function EmailField({ id, name, email, picked, placeholder, onChange }: EmailFieldProps) {
const local = picked && email.endsWith(`@${picked}`) ? email.slice(0, -picked.length - 1) : picked ? "" : email;
const shown = picked ? local : email;
const [focused, setFocused] = useState(false);
const [dismissed, setDismissed] = useState<string | null>(null);
const [active, setActive] = useState(0);
const suggestions = picked || !focused || dismissed === email ? [] : autoEmailDomains(email);
const listId = `${id}-domains`;
const fixed = picked || suggestions.length ? null : suggestEmailFix(email);
const complete = (domain: string) => {
const before = email.slice(0, email.indexOf("@")).trim();
onChange(`${before}@${domain}`, null);
setActive(0);
};
const pick = (domain: string | null) => {
if (domain === null) {
onChange(email, null);
} else {
const before = (picked ? local : email.split("@")[0]).trim();
onChange(before ? `${before}@${domain}` : "", domain);
}
document.getElementById(id)?.focus();
};
return (
<>
<div className="auth-email-field">
<Input
id={id}
name={name}
className="h-11"
// The part before 「@」 alone is not an email address; the browser check applies to whole addresses.
type={picked ? "text" : "email"}
autoComplete="email"
inputMode="email"
autoCapitalize="none"
spellCheck={false}
required
autoFocus
value={shown}
onChange={(event) => {
const typed = event.target.value;
setActive(0);
if (picked && !typed.includes("@")) onChange(typed.trim() ? `${typed}@${picked}` : "", picked);
else onChange(typed, null);
}}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
onKeyDown={(event) => {
if (!suggestions.length) return;
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
const step = event.key === "ArrowDown" ? 1 : -1;
setActive((current) => (current + step + suggestions.length) % suggestions.length);
} else if (event.key === "Enter") {
event.preventDefault();
complete(suggestions[Math.min(active, suggestions.length - 1)]);
} else if (event.key === "Escape") {
setDismissed(email);
}
}}
placeholder={picked ? "邮箱 @ 前面的部分" : placeholder}
/>
{suggestions.length ? (
<div className="auth-email-suggest" id={listId} role="group" aria-label="邮箱后缀">
{suggestions.map((domain, index) => (
<Button
key={domain}
type="button"
variant="ghost"
data-active={index === Math.min(active, suggestions.length - 1) ? "" : undefined}
className="auth-email-suggest-item"
// Keep the focus in the field so typing goes on; the pick happens on click.
onMouseDown={(event) => event.preventDefault()}
onClick={() => complete(domain)}
>
{email.slice(0, email.indexOf("@"))}<strong>@{domain}</strong>
</Button>
))}
</div>
) : null}
<DropdownMenu>
<DropdownMenuTrigger className="auth-email-domain-trigger" type="button" aria-label="选择邮箱后缀">
<span>{picked ? `@${picked}` : "@后缀"}</span>
<ChevronDown aria-hidden="true" />
</DropdownMenuTrigger>
<DropdownMenuContent className="account-menu-popup auth-email-domain-menu w-auto" aria-label="邮箱后缀" side="bottom" align="end" sideOffset={6}>
{(picked ? menuEmailDomains("") : menuEmailDomains(email)).map((domain) => (
<DropdownMenuItem key={domain} className="auth-email-domain-item" onClick={() => pick(domain)}>
@{domain}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem className="auth-email-domain-item" onClick={() => pick(null)}>其他邮箱(自己输入完整地址)</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{fixed ? (
<p className="auth-email-hint" aria-live="polite">
是不是{" "}
<Button type="button" variant="link" className="auth-email-hint-fix" onClick={() => onChange(fixed, null)}>
{fixed}
</Button>
?
</p>
) : null}
</>
);
}
function passwordError(password: string, confirmation: string): string {
if (password.length < 8 || password.length > 128) {
return "密码长度须为 8–128 位";
@@ -108,6 +236,8 @@ export function EmailOtpLogin({
const [mode, setMode] = useState<AuthMode>(passwordOnly ? "password" : "otp");
const [step, setStep] = useState<AuthStep>("email");
const [email, setEmail] = useState("");
// BUG-2395: the ending picked from the menu at the right of the email field, or null for a typed address.
const [pickedDomain, setPickedDomain] = useState<string | null>(null);
const [token, setToken] = useState("");
const [password, setPassword] = useState("");
const [confirmation, setConfirmation] = useState("");
@@ -440,20 +570,16 @@ export function EmailOtpLogin({
onSubmit={signInWithPassword}
>
<Label htmlFor="password-email">邮箱</Label>
<Input
<EmailField
id="password-email"
className="h-11"
type="email"
autoComplete="email"
inputMode="email"
required
autoFocus
value={email}
onChange={(event) => {
setEmail(event.target.value);
email={email}
picked={pickedDomain}
placeholder="you@example.com"
onChange={(next, picked) => {
setEmail(next);
setPickedDomain(picked);
dismissNotice(AUTH_ERROR);
}}
placeholder="you@example.com"
/>
<Label htmlFor="current-password">密码</Label>
<Input
@@ -488,21 +614,17 @@ export function EmailOtpLogin({
onSubmit={sendOtp}
>
<Label htmlFor={LOGIN_EMAIL_INPUT_ID} className={mode === "otp" ? "sr-only" : undefined}>邮箱</Label>
<Input
<EmailField
id={LOGIN_EMAIL_INPUT_ID}
name="email"
className="h-11"
type="email"
autoComplete="email"
inputMode="email"
required
autoFocus
value={email}
onChange={(event) => {
setEmail(event.target.value);
email={email}
picked={pickedDomain}
placeholder={mode === "otp" ? "输入邮箱" : "you@example.com"}
onChange={(next, picked) => {
setEmail(next);
setPickedDomain(picked);
clearAuthNotices();
}}
placeholder={mode === "otp" ? "输入邮箱" : "you@example.com"}
/>
<Button
className="button-primary"
+106
View File
@@ -0,0 +1,106 @@
/**
* BUG-2395: login codes sent to mistyped addresses (`…@qq.con`) bounced, so the person never got a code
* and the sending account's bounce rate rose far above the provider's risk line.
*
* Two checks, both on the domain only:
* - `emailDomainTypo`: the domain ends in a suffix no mail domain has (`.con`, `.cmo` …). The server
* refuses to send to it; nothing could be delivered there.
* - `suggestEmailFix`: the domain is one keystroke away from a common mail provider (`qq.co`,
* `gmial.com`, `163.con`). The login form offers the corrected address; the person decides.
*/
export const COMMON_EMAIL_DOMAINS = [
"qq.com", "foxmail.com", "163.com", "126.com", "yeah.net", "sina.com", "sina.cn", "sohu.com",
"139.com", "189.cn", "aliyun.com", "vip.qq.com", "vip.163.com",
"gmail.com", "outlook.com", "hotmail.com", "live.com", "icloud.com", "me.com", "yahoo.com",
"msn.com", "proton.me", "protonmail.com",
] as const;
// Suffixes that are not top-level domains and are one slip from `.com` / `.cn` / `.net`.
const TYPO_SUFFIXES = new Set([
"con", "cmo", "ocm", "comm", "coom", "cpm", "vom", "xom", "cim", "conm", "ccom", "coml", "comn",
"cnn", "nte", "ent", "met",
]);
const COMMON = new Set<string>(COMMON_EMAIL_DOMAINS);
function splitEmail(email: string): { local: string; domain: string } | null {
const value = email.trim().toLowerCase();
const at = value.lastIndexOf("@");
if (at <= 0 || at === value.length - 1) return null;
return { local: value.slice(0, at), domain: value.slice(at + 1) };
}
/** True when the domain's last label is a known slip that no mail domain uses. */
export function emailDomainTypo(email: string): boolean {
const parts = splitEmail(email);
if (!parts) return false;
const suffix = parts.domain.slice(parts.domain.lastIndexOf(".") + 1);
return TYPO_SUFFIXES.has(suffix);
}
function withinOneEdit(a: string, b: string): boolean {
if (a === b) return true;
if (Math.abs(a.length - b.length) > 1) return false;
if (a.length === b.length) {
const diffs: number[] = [];
for (let index = 0; index < a.length; index += 1) {
if (a[index] !== b[index]) diffs.push(index);
if (diffs.length > 2) return false;
}
if (diffs.length === 1) return true;
// Two neighbouring letters swapped (gmial / gmail).
const [first, second] = diffs;
return second === first + 1 && a[first] === b[second] && a[second] === b[first];
}
const [longer, shorter] = a.length > b.length ? [a, b] : [b, a];
for (let index = 0; index < longer.length; index += 1) {
if (longer.slice(0, index) + longer.slice(index + 1) === shorter) return true;
}
return false;
}
/** The corrected address when the domain is one slip from a common provider; otherwise null. */
export function suggestEmailFix(email: string): string | null {
const parts = splitEmail(email);
if (!parts || COMMON.has(parts.domain)) return null;
const matches = COMMON_EMAIL_DOMAINS.filter((domain) => withinOneEdit(parts.domain, domain));
// Only a single clear match; `16.com` is as close to 163.com as to 126.com.
if (matches.length !== 1) return null;
return `${parts.local}@${matches[0]}`;
}
// The endings in the menu at the right of the email field, most used first.
export const PICK_EMAIL_DOMAINS = [
"qq.com", "163.com", "gmail.com", "126.com", "icloud.com", "outlook.com", "foxmail.com", "hotmail.com",
"sina.com", "139.com", "yahoo.com", "sohu.com", "yeah.net", "aliyun.com", "live.com", "189.cn",
] as const;
/**
* The endings the menu lists for what is in the field: after 「@」, those that start with the typed part
* (`@y` → yeah.net, yahoo.com); otherwise, or when nothing matches, all of them.
*/
export function menuEmailDomains(email: string): string[] {
const value = email.trim().toLowerCase();
const at = value.lastIndexOf("@");
const typed = at < 0 ? "" : value.slice(at + 1);
if (!typed || COMMON.has(typed)) return [...PICK_EMAIL_DOMAINS];
const matches = PICK_EMAIL_DOMAINS.filter((domain) => domain.startsWith(typed));
return matches.length ? matches : [...PICK_EMAIL_DOMAINS];
}
/**
* The endings that open by themselves under the field once 「@」 is typed: all of them right after 「@」,
* then those starting with the typed part. Empty when nothing matches or the ending is already a known one.
*/
export function autoEmailDomains(email: string): string[] {
const value = email.trim().toLowerCase();
const at = value.indexOf("@");
if (at <= 0 || value.indexOf("@", at + 1) >= 0) return [];
const typed = value.slice(at + 1);
if (COMMON.has(typed)) return [];
return PICK_EMAIL_DOMAINS.filter((domain) => domain.startsWith(typed));
}
export const EMAIL_DOMAIN_TYPO_CODE = "EMAIL_DOMAIN_TYPO";
export const EMAIL_DOMAIN_TYPO_MESSAGE = "这个邮箱地址的后缀好像不完整,请检查一下再发送";
@@ -1,7 +1,10 @@
import { createHmac } from "node:crypto";
import type { BetterAuthOptions } from "better-auth";
import { APIError, createAuthMiddleware } from "better-auth/api";
import { admin, emailOTP, twoFactor, type EmailOTPOptions } from "better-auth/plugins";
import { EMAIL_DOMAIN_TYPO_CODE, EMAIL_DOMAIN_TYPO_MESSAGE, emailDomainTypo } from "../../lib/email-typo.ts";
import type { SelfHostedIdentityConfig } from "./config.ts";
import type { EmailOtpSender } from "./contracts.ts";
import { identityModelMapping } from "./model.ts";
@@ -80,6 +83,24 @@ export function createEmailOtpOptions(
};
}
// BUG-2395: endpoints that email a code. A domain ending in a known slip (`qq.con`) cannot receive mail;
// sending there only bounces and raises the account's bounce rate, so the request is refused before a code is made.
export const OTP_SENDING_PATHS = new Set([
"/email-otp/send-verification-otp",
"/email-otp/request-password-reset",
"/forget-password/email-otp",
"/email-otp/request-email-change",
]);
export const refuseMistypedEmailDomain = createAuthMiddleware(async (ctx) => {
if (!OTP_SENDING_PATHS.has(ctx.path)) return;
const body = ctx.body as { email?: unknown; newEmail?: unknown } | undefined;
const email = typeof body?.newEmail === "string" ? body.newEmail : body?.email;
if (typeof email === "string" && emailDomainTypo(email)) {
throw new APIError("BAD_REQUEST", { code: EMAIL_DOMAIN_TYPO_CODE, message: EMAIL_DOMAIN_TYPO_MESSAGE });
}
});
export function buildAuthOptions({
config,
database,
@@ -128,6 +149,7 @@ export function buildAuthOptions({
maxPasswordLength: 128,
revokeSessionsOnPasswordReset: true,
},
hooks: { before: refuseMistypedEmailDomain },
plugins: [
emailOTP(createEmailOtpOptions(emailSender, config.userSecret, false, config.testOtp)),
twoFactor({
+9
View File
@@ -1,6 +1,12 @@
import { createAuthClient } from "better-auth/react";
import { emailOTPClient, twoFactorClient } from "better-auth/client/plugins";
import { EMAIL_DOMAIN_TYPO_CODE, EMAIL_DOMAIN_TYPO_MESSAGE } from "../../lib/email-typo.ts";
function isEmailDomainTypoError(error: unknown): boolean {
return typeof error === "object" && error !== null && (error as { code?: unknown }).code === EMAIL_DOMAIN_TYPO_CODE;
}
interface AuthClientResult {
data: unknown;
error: unknown;
@@ -107,6 +113,8 @@ export function createSelfHostedAuthActions(
type: "sign-in",
});
if (result.error) {
// BUG-2395: the server refused a mistyped domain; say so instead of "try later".
if (isEmailDomainTypoError(result.error)) throw new Error(EMAIL_DOMAIN_TYPO_MESSAGE);
throw new Error("暂时无法发送验证码,请稍后再试");
}
},
@@ -145,6 +153,7 @@ export function createSelfHostedAuthActions(
email: normalizeEmail(email),
});
if (result.error) {
if (isEmailDomainTypoError(result.error)) throw new Error(EMAIL_DOMAIN_TYPO_MESSAGE);
throw new Error("暂时无法发送验证码,请稍后再试");
}
},
+105
View File
@@ -0,0 +1,105 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
import { refuseMistypedEmailDomain, OTP_SENDING_PATHS, buildAuthOptions } from "../src/modules/identity/auth-factory.ts";
import { createSelfHostedAuthActions, type SelfHostedAuthClient } from "../src/modules/identity/client.ts";
import { FakeEmailOtpSender } from "../src/modules/identity/email/fake-email-otp-sender.ts";
import { EMAIL_DOMAIN_TYPO_CODE, EMAIL_DOMAIN_TYPO_MESSAGE, PICK_EMAIL_DOMAINS, emailDomainTypo, menuEmailDomains, autoEmailDomains, suggestEmailFix } from "../src/lib/email-typo.ts";
// BUG-2395: codes sent to mistyped domains bounced (bounce rate far above the provider's risk line).
test("a domain one slip from a common provider gets one suggestion", () => {
assert.equal(suggestEmailFix("someone@qq.con"), "someone@qq.com");
assert.equal(suggestEmailFix("someone@qq.co"), "someone@qq.com");
assert.equal(suggestEmailFix("Someone@GMIAL.com "), "someone@gmail.com");
assert.equal(suggestEmailFix("someone@hotmial.com"), "someone@hotmail.com");
assert.equal(suggestEmailFix("someone@163.con"), "someone@163.com");
assert.equal(suggestEmailFix("someone@qq.com"), null);
assert.equal(suggestEmailFix("someone@example.org"), null);
assert.equal(suggestEmailFix("someone@company.cn"), null);
// Ambiguous between 163.com and 126.com: no guess.
assert.equal(suggestEmailFix("someone@16.com"), null);
assert.equal(suggestEmailFix("no-at-sign"), null);
});
test("only suffixes no mail domain uses are refused", () => {
for (const email of ["a@qq.con", "a@163.cmo", "a@gmail.comm", "a@x.y.con"]) assert.equal(emailDomainTypo(email), true, email);
for (const email of ["a@qq.com", "a@qq.co", "a@company.cn", "a@example.net", "a@x.me", "bad"]) assert.equal(emailDomainTypo(email), false, email);
});
test("the server refuses to send a code to a mistyped domain, before any code is made", async () => {
const options = buildAuthOptions({
config: { provider: "self-hosted", databaseUrl: "postgresql://u:p@h:5432/d", userOrigin: "https://u.example", adminOrigin: "https://a.example", userSecret: "user-secret-that-is-at-least-32-bytes-long", resendApiKey: "re_test", resendFrom: "x <x@u.example>", testOtp: null },
database: {} as never,
emailSender: new FakeEmailOtpSender(),
});
assert.equal(options.hooks?.before, refuseMistypedEmailDomain);
assert.ok(OTP_SENDING_PATHS.has("/email-otp/send-verification-otp"));
assert.ok(OTP_SENDING_PATHS.has("/email-otp/request-password-reset"));
const run = (path: string, body: unknown) =>
(refuseMistypedEmailDomain as unknown as (ctx: unknown) => Promise<unknown>)({ path, body, context: {}, headers: new Headers() });
await assert.rejects(run("/email-otp/send-verification-otp", { email: "a@qq.con", type: "sign-in" }), (error: { body?: { code?: string; message?: string } }) => {
assert.equal(error.body?.code, EMAIL_DOMAIN_TYPO_CODE);
assert.equal(error.body?.message, EMAIL_DOMAIN_TYPO_MESSAGE);
return true;
});
await run("/email-otp/send-verification-otp", { email: "a@qq.com", type: "sign-in" });
await run("/sign-in/email-otp", { email: "a@qq.con", otp: "123456" });
});
test("the login form says what to check instead of 'try later'", async () => {
const client = {
emailOtp: {
sendVerificationOtp: async () => ({ data: null, error: { code: EMAIL_DOMAIN_TYPO_CODE, status: 400 } }),
requestPasswordReset: async () => ({ data: null, error: { code: EMAIL_DOMAIN_TYPO_CODE, status: 400 } }),
},
signIn: { emailOtp: async () => ({ data: null, error: null }) },
} as unknown as SelfHostedAuthClient;
const actions = createSelfHostedAuthActions(client);
await assert.rejects(actions.send("a@qq.con"), new Error(EMAIL_DOMAIN_TYPO_MESSAGE));
await assert.rejects(actions.requestPasswordReset("a@qq.con"), new Error(EMAIL_DOMAIN_TYPO_MESSAGE));
assert.doesNotMatch(EMAIL_DOMAIN_TYPO_MESSAGE, /错误|你输错/);
});
test("both email fields show the inline hint, not a toast", () => {
const source = readFileSync(new URL("../src/components/email-otp-login.tsx", import.meta.url), "utf8");
assert.equal(source.match(/<EmailField\n/g)?.length, 2);
const field = source.slice(source.indexOf("function EmailField"), source.indexOf("function passwordError"));
assert.match(field, /className="auth-email-hint"/);
// The ending menu sits in the field; with an ending picked the field holds only the part before 「@」.
assert.match(field, /className="auth-email-domain-trigger"/);
assert.match(field, /type=\{picked \? "text" : "email"\}/);
assert.match(field, /其他邮箱(自己输入完整地址)/);
assert.doesNotMatch(field, /notify/);
});
test("the ending menu lists the common providers, Gmail among the first", () => {
assert.equal(PICK_EMAIL_DOMAINS.length, 16);
assert.deepEqual(PICK_EMAIL_DOMAINS.slice(0, 5), ["qq.com", "163.com", "gmail.com", "126.com", "icloud.com"]);
});
test("a typed 「@y」 narrows the ending menu", () => {
assert.deepEqual(menuEmailDomains("ganxianting@y"), ["yahoo.com", "yeah.net"]);
assert.deepEqual(menuEmailDomains("ganxianting@ye"), ["yeah.net"]);
assert.deepEqual(menuEmailDomains("lily@1"), ["163.com", "126.com", "139.com", "189.cn"]);
// Nothing typed after 「@」, a complete known ending, or no match: the whole list.
for (const email of ["lily", "lily@", "lily@qq.com", "lily@company.cn", ""]) {
assert.equal(menuEmailDomains(email).length, PICK_EMAIL_DOMAINS.length, email);
}
});
test("typing 「@」 opens the endings by themselves and narrows them", () => {
assert.equal(autoEmailDomains("ganxianting@").length, PICK_EMAIL_DOMAINS.length);
assert.deepEqual(autoEmailDomains("ganxianting@y"), ["yahoo.com", "yeah.net"]);
assert.deepEqual(autoEmailDomains("ganxianting@yeah.n"), ["yeah.net"]);
for (const email of ["ganxianting", "ganxianting@yeah.net", "ganxianting@company.cn", "@qq", "a@b@c"]) {
assert.deepEqual(autoEmailDomains(email), [], email);
}
const source = readFileSync(new URL("../src/components/email-otp-login.tsx", import.meta.url), "utf8");
const field = source.slice(source.indexOf("function EmailField"), source.indexOf("function passwordError"));
// The list keeps the focus in the field and the typo line waits while the list is open.
assert.match(field, /className="auth-email-suggest"/);
assert.match(field, /onMouseDown=\{\(event\) => event\.preventDefault\(\)\}/);
assert.match(field, /const fixed = picked \|\| suggestions\.length \? null/);
});