Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(mobile): surface actionable login diagnostics

tianma-if69ee9c3823d3
diff --git a/apps/mobile/src/lib/login-error.test.mjs b/apps/mobile/src/lib/login-error.test.mjs
new file mode 100644
index 00000000..1d9bf5fe
--- /dev/null
+++ b/apps/mobile/src/lib/login-error.test.mjs
@@ -0,0 +1,43 @@
+import { describe, expect, test } from "bun:test";
+import { ApiRequestError } from "@edgeever/client";
+import { formatMobileLoginError } from "./login-error.ts";
+
+describe("mobile login error messages", () => {
+ test("explains a Cloudflare challenge and preserves its Ray ID", () => {
+ const error = new ApiRequestError("Request failed", 403, undefined, undefined, {
+ cloudflareMitigated: true,
+ isEdgeEverApiError: false,
+ rayId: "abc123-NRT",
+ });
+
+ expect(formatMobileLoginError(error, "zh-CN")).toContain("Cloudflare 人机验证拦截了登录接口");
+ expect(formatMobileLoginError(error, "zh-CN")).toContain("cloudflare_challenge · Ray ID: abc123-NRT");
+ expect(formatMobileLoginError(error, "en-US")).toContain("A Cloudflare browser challenge intercepted the login API");
+ });
+
+ test("distinguishes credentials, edge security blocks, and EdgeEver 403 responses", () => {
+ expect(formatMobileLoginError(new ApiRequestError("Unauthorized", 401), "zh-CN"))
+ .toContain("用户名或密码不正确");
+
+ const blocked = new ApiRequestError("Forbidden", 403, undefined, undefined, {
+ cloudflareMitigated: false,
+ isEdgeEverApiError: false,
+ rayId: "def456-SJC",
+ });
+ expect(formatMobileLoginError(blocked, "zh-CN")).toContain("安全策略拦截");
+ expect(formatMobileLoginError(blocked, "zh-CN")).toContain("security_policy_blocked");
+
+ const forbidden = new ApiRequestError("Forbidden", 403, "forbidden", undefined, {
+ cloudflareMitigated: false,
+ isEdgeEverApiError: true,
+ });
+ expect(formatMobileLoginError(forbidden, "en-US")).toContain("The instance rejected the login request");
+ });
+
+ test("provides actionable network and server messages", () => {
+ expect(formatMobileLoginError(new TypeError("Failed to fetch"), "en-US"))
+ .toContain("Unable to reach the instance");
+ expect(formatMobileLoginError(new ApiRequestError("Unavailable", 503), "zh-CN"))
+ .toContain("实例服务异常(HTTP 503)");
+ });
+});
diff --git a/apps/mobile/src/lib/login-error.ts b/apps/mobile/src/lib/login-error.ts
new file mode 100644
index 00000000..7ba6e278
--- /dev/null
+++ b/apps/mobile/src/lib/login-error.ts
@@ -0,0 +1,122 @@
+import { ApiRequestError } from "@edgeever/client";
+
+export type MobileLoginLocale = "zh-CN" | "en-US";
+
+const appendDiagnostics = (
+ message: string,
+ diagnosticCode: string,
+ rayId?: string,
+) => `${message}\n${diagnosticCode}${rayId ? ` · Ray ID: ${rayId}` : ""}`;
+
+export const formatMobileLoginError = (error: unknown, locale: MobileLoginLocale) => {
+ const english = locale === "en-US";
+
+ if (error instanceof ApiRequestError) {
+ const rayId = error.responseDiagnostics?.rayId;
+
+ if (error.responseDiagnostics?.cloudflareMitigated) {
+ return appendDiagnostics(
+ english
+ ? "A Cloudflare browser challenge intercepted the login API. Ask the instance administrator to adjust the WAF Challenge rule for the API."
+ : "Cloudflare 人机验证拦截了登录接口。请实例管理员调整针对 API 的 WAF Challenge 规则。",
+ "cloudflare_challenge",
+ rayId,
+ );
+ }
+ if (error.code === "auth_not_configured") {
+ return appendDiagnostics(
+ english ? "Sign-in is not configured for this instance." : "这个实例还没有配置登录功能。",
+ "auth_not_configured",
+ rayId,
+ );
+ }
+ if (error.code === "database_not_ready") {
+ return appendDiagnostics(
+ english ? "The instance database is not ready." : "实例数据库尚未就绪。",
+ "database_not_ready",
+ rayId,
+ );
+ }
+ if (error.code === "password_hash_invalid") {
+ return appendDiagnostics(
+ english ? "The instance password configuration is invalid." : "实例的密码配置无效。",
+ "password_hash_invalid",
+ rayId,
+ );
+ }
+ if (error.code === "login_rate_limited" || error.status === 429) {
+ return appendDiagnostics(
+ english ? "Too many sign-in attempts. Try again later." : "登录尝试次数过多,请稍后再试。",
+ "login_rate_limited",
+ rayId,
+ );
+ }
+ if (error.code === "unauthorized" || error.status === 401) {
+ return appendDiagnostics(
+ english ? "The username or password is incorrect." : "用户名或密码不正确。",
+ "invalid_credentials",
+ rayId,
+ );
+ }
+ if (error.status === 404) {
+ return appendDiagnostics(
+ english
+ ? "No EdgeEver API was found at this instance address."
+ : "该实例地址没有找到 EdgeEver API,请检查地址。",
+ "edgeever_api_not_found",
+ rayId,
+ );
+ }
+ if (error.status === 403) {
+ const isEdgeEverApiError = error.responseDiagnostics?.isEdgeEverApiError;
+ return appendDiagnostics(
+ isEdgeEverApiError
+ ? (english ? "The instance rejected the login request." : "实例拒绝了登录请求。")
+ : (english
+ ? "A security policy blocked the request before it reached EdgeEver. Check Cloudflare Security Events, Access, WAF, or reverse-proxy rules."
+ : "登录请求在到达 EdgeEver 前被安全策略拦截。请检查 Cloudflare Security Events、Access、WAF 或反向代理规则。"),
+ isEdgeEverApiError ? error.code || "http_403" : "security_policy_blocked",
+ rayId,
+ );
+ }
+ if (error.status >= 500) {
+ return appendDiagnostics(
+ english
+ ? `The instance returned a server error (HTTP ${error.status}).`
+ : `实例服务异常(HTTP ${error.status})。`,
+ `http_${error.status}`,
+ rayId,
+ );
+ }
+ return appendDiagnostics(
+ english
+ ? `The instance rejected the request (HTTP ${error.status}).`
+ : `实例拒绝了请求(HTTP ${error.status})。`,
+ error.code || `http_${error.status}`,
+ rayId,
+ );
+ }
+
+ if (error instanceof TypeError) {
+ return appendDiagnostics(
+ english
+ ? "Unable to reach the instance. Check its address and your network connection."
+ : "无法连接实例,请检查实例地址和网络连接。",
+ "network_unreachable",
+ );
+ }
+
+ if (error instanceof SyntaxError) {
+ return appendDiagnostics(
+ english
+ ? "The server response is not a valid EdgeEver response."
+ : "服务端返回的内容不是有效的 EdgeEver 响应。",
+ "invalid_instance_response",
+ );
+ }
+
+ return appendDiagnostics(
+ english ? "Sign-in failed. Try again later." : "登录失败,请稍后再试。",
+ "unexpected_login_error",
+ );
+};
diff --git a/apps/mobile/src/lib/session.tsx b/apps/mobile/src/lib/session.tsx
index f1f7ee54..b8c9ecd1 100644
--- a/apps/mobile/src/lib/session.tsx
+++ b/apps/mobile/src/lib/session.tsx
@@ -81,7 +81,7 @@ export const SessionProvider = ({ children }: { children: ReactNode }) => {
const signIn = useCallback(async (input: { baseUrl: string; username: string; password: string }) => {
const baseUrl = normalizeInstanceUrl(resolveInstanceUrlInput(input.baseUrl));
const deviceId = await getOrCreateDeviceId();
- const loginClient = createEdgeEverClient({ baseUrl });
+ const loginClient = createEdgeEverClient({ baseUrl, fetch: expoFetch as typeof fetch });
const authSession = await loginClient.login({
username: input.username,
password: input.password,
diff --git a/apps/mobile/src/screens/LoginScreen.tsx b/apps/mobile/src/screens/LoginScreen.tsx
index a23f6703..5448edb2 100644
--- a/apps/mobile/src/screens/LoginScreen.tsx
+++ b/apps/mobile/src/screens/LoginScreen.tsx
@@ -11,6 +11,8 @@ import { PUBLIC_DEMO_INSTANCE_URL } from "@edgeever/shared";
import { SafeAreaView } from "react-native-safe-area-context";
import { ActivityIndicator, GitHub, LockKeyhole } from "../components/icons";
import { Pressable, Text, TextInput } from "../components/LocalizedText";
+import { formatMobileLoginError } from "../lib/login-error";
+import { useMobileLocale } from "../lib/mobile-locale";
import { resolveMobileThemeStyles, useMobileTheme, type MobileResolvedTheme } from "../lib/mobile-theme";
import { useSession } from "../lib/session";
@@ -18,6 +20,7 @@ const GITHUB_REPOSITORY_URL = "https://github.com/tianma-if/edgeever";
export const LoginScreen = () => {
const { resolvedTheme } = useMobileTheme();
+ const { resolvedLocale } = useMobileLocale();
refreshLoginThemeStyles(resolvedTheme);
const { signIn } = useSession();
const [baseUrl, setBaseUrl] = useState("");
@@ -39,7 +42,7 @@ export const LoginScreen = () => {
try {
await signIn({ baseUrl, username, password });
} catch (signInError) {
- setError(signInError instanceof Error ? signInError.message : "登录失败");
+ setError(formatMobileLoginError(signInError, resolvedLocale));
} finally {
setSubmitting(false);
}
diff --git a/docs/deploy-cloudflare-button.md b/docs/deploy-cloudflare-button.md
index fcd2a2ef..f767a485 100644
--- a/docs/deploy-cloudflare-button.md
+++ b/docs/deploy-cloudflare-button.md
@@ -125,4 +125,9 @@ Passwords and other credentials remain Worker runtime Secrets and must never be
4. Prefer this workflow over GitHub **Sync fork** for day-to-day upgrades.
5. If an old updater fails with `without workflows permission`, use **Sync fork** once as the repository owner, then re-run **Update deployed EdgeEver**. The current updater preserves `.github/workflows/**`, so later product updates do not hit this permission boundary.
- **Push succeeded but site unchanged**: Confirm Workers Builds ran for the new `main` SHA. Optionally add repository secret `EDGE_EVER_CLOUDFLARE_DEPLOY_HOOK_URL` so the workflow can call a Deploy Hook after publish.
+- **The Android or iOS app reports that Cloudflare or a security policy blocked sign-in**:
+ 1. Retry once and record the diagnostic code, Ray ID, and approximate time shown by the app. In Cloudflare, open **Security → Analytics → Events**, find the matching request, and check its **Service**, **Action**, and rule ID before changing any protection.
+ 2. Native apps call `/api/*` directly and cannot complete an interactive browser challenge. Do not try to solve this by embedding the challenge in the app. Keep EdgeEver authentication and its application-level login rate limits enabled, but make sure legitimate API traffic receives a machine-readable response instead of a Managed or Interactive Challenge.
+ 3. If a custom WAF rule issued the challenge, narrow that rule so it does not challenge the required `/api/*` requests. For Managed Rules or Super Bot Fight Mode false positives, create the smallest applicable [Skip rule or exception](https://developers.cloudflare.com/waf/custom-rules/skip/). Do not broadly disable unrelated security controls.
+ 4. Cloudflare's free Bot Fight Mode cannot be bypassed by a WAF Skip rule. If Security Events identifies Bot Fight Mode, follow Cloudflare's [false-positive guidance](https://developers.cloudflare.com/bots/troubleshooting/false-positives/) and either disable it or use a protection mode that supports scoped exceptions.
- **Reset or Manual Recovery**: See the [Cloudflare Manual Deployment Guide](manual-deploy.md).
diff --git a/docs/deploy-cloudflare-button.zh-CN.md b/docs/deploy-cloudflare-button.zh-CN.md
index d8392476..3a5e472a 100644
--- a/docs/deploy-cloudflare-button.zh-CN.md
+++ b/docs/deploy-cloudflare-button.zh-CN.md
@@ -125,4 +125,9 @@ EDGE_EVER_UPDATE_CHANNEL=edge
4. 日常升级请优先用本工作流,而不是 GitHub **Sync fork**。
5. 若旧版更新器报错 `without workflows permission`,请使用仓库所有者身份执行一次 **Sync fork**,然后重新运行 **Update deployed EdgeEver**。新版更新器会保留 `.github/workflows/**`,后续产品更新不会再触发这项权限限制。
- **Git 已 push 但网站没变**:确认 Workers Builds 是否针对新的 `main` SHA 构建。可选:添加仓库 Secret `EDGE_EVER_CLOUDFLARE_DEPLOY_HOOK_URL`,让工作流在 publish 后调用 Deploy Hook。
+- **Android 或 iOS App 提示登录被 Cloudflare 或安全策略拦截**:
+ 1. 重试一次并记录 App 显示的诊断代码、Ray ID 和大致时间。在 Cloudflare 中打开 **Security → Analytics → Events**,找到对应请求并确认其 **Service**、**Action** 和规则 ID,再决定调整哪项防护。
+ 2. 原生 App 会直接调用 `/api/*`,无法完成交互式浏览器验证。不要尝试在 App 中嵌入该验证。请继续启用 EdgeEver 身份认证及应用层登录限流,但要确保合法 API 流量收到机器可解析的响应,而不是 Managed Challenge 或 Interactive Challenge。
+ 3. 如果是自定义 WAF 规则发起验证,请缩小规则范围,不要验证 App 所需的 `/api/*` 请求。如果是 Managed Rules 或 Super Bot Fight Mode 误判,请创建范围尽可能小的 [Skip 规则或例外](https://developers.cloudflare.com/waf/custom-rules/skip/),不要笼统关闭无关的安全防护。
+ 4. Cloudflare 免费版 Bot Fight Mode 无法通过 WAF Skip 规则绕过。如果 Security Events 显示由 Bot Fight Mode 拦截,请按 Cloudflare 的[误报处理指引](https://developers.cloudflare.com/bots/troubleshooting/false-positives/)关闭该功能,或改用支持精确例外的防护模式。
- **需要重置或手动恢复部署**:请参阅 [手动部署指南](manual-deploy.zh-CN.md)。
diff --git a/packages/client/src/index.test.mjs b/packages/client/src/index.test.mjs
index 232c44a8..41655dcf 100644
--- a/packages/client/src/index.test.mjs
+++ b/packages/client/src/index.test.mjs
@@ -127,4 +127,53 @@ describe("EdgeEver client HTTP contract", () => {
}
expect(unauthorized).toBe(1);
});
+
+ test("preserves Cloudflare diagnostics when an HTML challenge intercepts the API", async () => {
+ const client = createEdgeEverClient({
+ fetch: async () => new Response("<html>challenge</html>", {
+ status: 403,
+ headers: {
+ "CF-Mitigated": "challenge",
+ "CF-Ray": "abc123-NRT",
+ "Content-Type": "text/html",
+ },
+ }),
+ });
+
+ try {
+ await client.login({ username: "admin", password: "secret" });
+ throw new Error("expected request to fail");
+ } catch (error) {
+ expect(error).toBeInstanceOf(ApiRequestError);
+ expect(error).toMatchObject({
+ status: 403,
+ message: "Request failed",
+ responseDiagnostics: {
+ cloudflareMitigated: true,
+ isEdgeEverApiError: false,
+ rayId: "abc123-NRT",
+ },
+ });
+ }
+ });
+
+ test("distinguishes EdgeEver API errors from edge security responses", async () => {
+ const client = createEdgeEverClient({
+ fetch: async () => jsonResponse(
+ { error: { code: "forbidden", message: "Forbidden", details: { reason: "policy" } } },
+ { status: 403, headers: { "CF-Ray": "def456-SJC", "Content-Type": "application/json" } },
+ ),
+ });
+
+ await expect(client.login({ username: "admin", password: "secret" })).rejects.toMatchObject({
+ status: 403,
+ code: "forbidden",
+ details: { reason: "policy" },
+ responseDiagnostics: {
+ cloudflareMitigated: false,
+ isEdgeEverApiError: true,
+ rayId: "def456-SJC",
+ },
+ });
+ });
});
diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts
index 563bd7d5..28c29d1a 100644
--- a/packages/client/src/index.ts
+++ b/packages/client/src/index.ts
@@ -170,15 +170,31 @@ export type MobileSyncChangesPage = {
export class ApiRequestError extends Error {
status: number;
code?: string;
-
- constructor(message: string, status: number, code?: string) {
+ details?: unknown;
+ responseDiagnostics?: ApiResponseDiagnostics;
+
+ constructor(
+ message: string,
+ status: number,
+ code?: string,
+ details?: unknown,
+ responseDiagnostics?: ApiResponseDiagnostics,
+ ) {
super(message);
this.name = "ApiRequestError";
this.status = status;
this.code = code;
+ this.details = details;
+ this.responseDiagnostics = responseDiagnostics;
}
}
+export type ApiResponseDiagnostics = {
+ cloudflareMitigated: boolean;
+ isEdgeEverApiError: boolean;
+ rayId?: string;
+};
+
export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
const fetchImpl = options.fetch ?? fetch;
const baseUrl = normalizeBaseUrl(options.baseUrl);
@@ -202,17 +218,29 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {
if (!response.ok) {
const body = await response.json().catch(() => null);
+ const rayId = response.headers.get("cf-ray")?.trim();
const error =
body && typeof body === "object" && "error" in body
- ? (body as { error?: { code?: string; message?: string } }).error
+ ? (body as { error?: { code?: string; message?: string; details?: unknown } }).error
: undefined;
const message = error?.message ?? response.statusText;
+ const responseDiagnostics: ApiResponseDiagnostics = {
+ cloudflareMitigated: response.headers.get("cf-mitigated") === "challenge",
+ isEdgeEverApiError: Boolean(error && typeof error === "object"),
+ ...(rayId ? { rayId } : {}),
+ };
if (response.status === 401) {
options.onUnauthorized?.();
}
- throw new ApiRequestError(message || "Request failed", response.status, error?.code);
+ throw new ApiRequestError(
+ message || "Request failed",
+ response.status,
+ error?.code,
+ error?.details,
+ responseDiagnostics,
+ );
}
return response.json() as Promise<T>;