AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: add portable login brute-force protection
tianma-ifea0f516ab73f
diff --git a/.env.local.example b/.env.local.exampleindex ff777b05..abc08973 100644--- a/.env.local.example+++ b/.env.local.example@@ -27,6 +27,13 @@ EDGE_EVER_AUTH_USERNAME=adminEDGE_EVER_AUTH_PASSWORD=admin123# Allowed range: 1-400 days.EDGE_EVER_SESSION_TTL_DAYS=400+# Portable application-level login protection. These values work in both D1 and SQLite.+# The defaults are 5 attempts per username / 15 minutes and 30 attempts per IP / 5 minutes.+EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS=900+EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS=5+EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS=900+EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS=30+EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS=300# Demo mode# Seeds sample content and periodically resets it; intended for public demos only.diff --git a/apps/api/src/auth-login-limiter.ts b/apps/api/src/auth-login-limiter.tsnew file mode 100644index 00000000..f406968f--- /dev/null+++ b/apps/api/src/auth-login-limiter.ts@@ -0,0 +1,172 @@+import type { DatabaseAdapter } from "./storage-contract";++export type LoginAttemptScope = "username" | "ip";++export type LoginAttemptKey = {+ scope: LoginAttemptScope;+ key: string;+};++export type LoginRateLimitConfig = {+ windowSeconds: number;+ usernameMaxAttempts: number;+ usernameCooldownSeconds: number;+ ipMaxAttempts: number;+ ipCooldownSeconds: number;+};++export type LoginRateLimitEnv = {+ EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS?: string;+ EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS?: string;+ EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS?: string;+ EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS?: string;+ EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS?: string;+};++export type LoginRateLimitResult = {+ blockedUntil: string | null;+ retryAfterSeconds: number;+};++export const DEFAULT_LOGIN_RATE_LIMIT_CONFIG: LoginRateLimitConfig = {+ windowSeconds: 15 * 60,+ usernameMaxAttempts: 5,+ usernameCooldownSeconds: 15 * 60,+ ipMaxAttempts: 30,+ ipCooldownSeconds: 5 * 60,+};++type LoginAttemptRow = {+ scope: LoginAttemptScope;+ blocked_until: string | null;+};++const parsePositiveInteger = (value: string | undefined, fallback: number, max: number) => {+ const parsed = Number(value);+ return Number.isInteger(parsed) && parsed > 0 ? Math.min(parsed, max) : fallback;+};++export const resolveLoginRateLimitConfig = (+ env: LoginRateLimitEnv,+): LoginRateLimitConfig => ({+ windowSeconds: parsePositiveInteger(+ env.EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS,+ DEFAULT_LOGIN_RATE_LIMIT_CONFIG.windowSeconds,+ 24 * 60 * 60,+ ),+ usernameMaxAttempts: parsePositiveInteger(+ env.EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS,+ DEFAULT_LOGIN_RATE_LIMIT_CONFIG.usernameMaxAttempts,+ 100,+ ),+ usernameCooldownSeconds: parsePositiveInteger(+ env.EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS,+ DEFAULT_LOGIN_RATE_LIMIT_CONFIG.usernameCooldownSeconds,+ 24 * 60 * 60,+ ),+ ipMaxAttempts: parsePositiveInteger(+ env.EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS,+ DEFAULT_LOGIN_RATE_LIMIT_CONFIG.ipMaxAttempts,+ 1_000,+ ),+ ipCooldownSeconds: parsePositiveInteger(+ env.EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS,+ DEFAULT_LOGIN_RATE_LIMIT_CONFIG.ipCooldownSeconds,+ 24 * 60 * 60,+ ),+});++const getScopeConfig = (scope: LoginAttemptScope, config: LoginRateLimitConfig) =>+ scope === "username"+ ? { maxAttempts: config.usernameMaxAttempts, cooldownSeconds: config.usernameCooldownSeconds }+ : { maxAttempts: config.ipMaxAttempts, cooldownSeconds: config.ipCooldownSeconds };++const toIso = (timestampMs: number) => new Date(timestampMs).toISOString();++const retryAfterSeconds = (blockedUntil: string | null, nowMs: number) => {+ if (!blockedUntil) return 0;+ return Math.max(0, Math.ceil((Date.parse(blockedUntil) - nowMs) / 1000));+};++const buildKeyFilter = (keys: LoginAttemptKey[]) =>+ keys.map(() => "(scope = ? AND attempt_key = ?)").join(" OR ");++const bindKeys = (keys: LoginAttemptKey[]) => keys.flatMap(({ scope, key }) => [scope, key]);++export const checkLoginRateLimit = async (+ db: DatabaseAdapter,+ keys: LoginAttemptKey[],+ config: LoginRateLimitConfig,+ nowMs = Date.now(),+): Promise<LoginRateLimitResult> => {+ if (keys.length === 0) return { blockedUntil: null, retryAfterSeconds: 0 };++ const now = toIso(nowMs);+ const retentionBoundary = toIso(nowMs - Math.max(config.windowSeconds, config.usernameCooldownSeconds, config.ipCooldownSeconds) * 2 * 1000);+ await db.prepare(`DELETE FROM auth_login_attempts WHERE updated_at <= ?`).bind(retentionBoundary).run();++ const rows = await db.prepare(+ `SELECT scope, blocked_until+ FROM auth_login_attempts+ WHERE ${buildKeyFilter(keys)}`,+ ).bind(...bindKeys(keys)).all<LoginAttemptRow>();++ const blockedUntil = rows.results+ .map((row) => row.blocked_until)+ .filter((value): value is string => Boolean(value && value > now))+ .sort()+ .at(-1) ?? null;++ return {+ blockedUntil,+ retryAfterSeconds: retryAfterSeconds(blockedUntil, nowMs),+ };+};++export const recordLoginFailure = async (+ db: DatabaseAdapter,+ keys: LoginAttemptKey[],+ config: LoginRateLimitConfig,+ nowMs = Date.now(),+): Promise<LoginRateLimitResult> => {+ if (keys.length === 0) return { blockedUntil: null, retryAfterSeconds: 0 };++ const now = toIso(nowMs);+ const windowBoundary = toIso(nowMs - config.windowSeconds * 1000);+ const statements = keys.map(({ scope, key }) => {+ const scopeConfig = getScopeConfig(scope, config);+ const blockedUntil = toIso(nowMs + scopeConfig.cooldownSeconds * 1000);+ return db.prepare(+ `INSERT INTO auth_login_attempts (+ scope, attempt_key, failure_count, window_started_at, blocked_until, updated_at+ ) VALUES (?, ?, 1, ?, NULL, ?)+ ON CONFLICT(scope, attempt_key) DO UPDATE SET+ failure_count = CASE+ WHEN auth_login_attempts.window_started_at <= ? THEN 1+ ELSE auth_login_attempts.failure_count + 1+ END,+ window_started_at = CASE+ WHEN auth_login_attempts.window_started_at <= ? THEN excluded.window_started_at+ ELSE auth_login_attempts.window_started_at+ END,+ blocked_until = CASE+ WHEN (+ CASE+ WHEN auth_login_attempts.window_started_at <= ? THEN 1+ ELSE auth_login_attempts.failure_count + 1+ END+ ) >= ? THEN ?+ ELSE NULL+ END,+ updated_at = excluded.updated_at`,+ ).bind(scope, key, now, now, windowBoundary, windowBoundary, windowBoundary, scopeConfig.maxAttempts, blockedUntil);+ });++ await db.batch(statements);+ return checkLoginRateLimit(db, keys, config, nowMs);+};++export const clearLoginAttempts = async (db: DatabaseAdapter, keys: LoginAttemptKey[]) => {+ if (keys.length === 0) return;+ await db.prepare(`DELETE FROM auth_login_attempts WHERE ${buildKeyFilter(keys)}`).bind(...bindKeys(keys)).run();+};diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex faa59910..fc9e9de2 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -74,6 +74,13 @@ import {resolveSessionDeviceId,type LoginDeviceSessionRow,} from "./auth-session-devices";+import {+ checkLoginRateLimit,+ clearLoginAttempts,+ recordLoginFailure,+ resolveLoginRateLimitConfig,+ type LoginAttemptKey,+} from "./auth-login-limiter";import {decodeDemoAttachment,DEMO_ATTACHMENT_MARKDOWN_EN,@@ -104,6 +111,11 @@ type Bindings = CloudflareStorageBindings & {EDGE_EVER_AUTH_PASSWORD?: string;EDGE_EVER_AUTH_PASSWORD_HASH?: string;EDGE_EVER_SESSION_TTL_DAYS?: string;+ EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS?: string;+ EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS?: string;+ EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS?: string;+ EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS?: string;+ EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS?: string;EDGE_EVER_R2_BUCKET_NAME?: string;EDGE_EVER_DEMO_MODE?: string;EDGE_EVER_LOCAL_DEMO_SEED?: string;@@ -631,12 +643,41 @@ app.post("/api/v1/auth/login", zValidator("json", LoginSchema), async (c) => {}const input = c.req.valid("json");+ const loginAttemptKeys = await getLoginAttemptKeys(c, input.username);+ const loginRateLimitConfig = resolveLoginRateLimitConfig(c.env);+ const currentRateLimit = await checkLoginRateLimit(c.env.storage.db, loginAttemptKeys, loginRateLimitConfig);++ if (currentRateLimit.retryAfterSeconds > 0) {+ return tooManyLoginAttempts(c, currentRateLimit.retryAfterSeconds);+ }+const user = await verifyLogin(c.env, input.username, input.password);if (!user) {+ const updatedRateLimit = await recordLoginFailure(+ c.env.storage.db,+ loginAttemptKeys,+ loginRateLimitConfig,+ );++ if (updatedRateLimit.retryAfterSeconds > 0) {+ await audit(+ c.env.storage.db,+ "system",+ null,+ "auth.login_rate_limited",+ "auth",+ loginAttemptKeys[0]?.key ?? "unknown",+ { retryAfterSeconds: updatedRateLimit.retryAfterSeconds },+ );+ return tooManyLoginAttempts(c, updatedRateLimit.retryAfterSeconds);+ }+return unauthorized(c, "Username or password is incorrect.");}+ await clearLoginAttempts(c.env.storage.db, loginAttemptKeys);+const workspace = await ensureUserWorkspace(c.env.storage.db, user.id, user.username);const session = await createSession(c, user, input.deviceId);setSessionCookie(c, session.token, session.maxAge);@@ -3824,6 +3865,33 @@ const getInstanceAuthMode = async (env: Bindings): Promise<InstanceAuthMode> =>});};+const getLoginAttemptKeys = async (c: AppContext, username: string): Promise<LoginAttemptKey[]> => {+ const keys: LoginAttemptKey[] = [{ scope: "username", key: await sha256(username.trim()) }];+ const clientIp = getClientIp(c);++ if (clientIp) {+ keys.push({ scope: "ip", key: await sha256(clientIp) });+ }++ return keys;+};++const getClientIp = (c: Context) => {+ const cloudflareIp = c.req.header("CF-Connecting-IP")?.trim();+ if (cloudflareIp) return cloudflareIp;++ const realIp = c.req.header("X-Real-IP")?.trim();+ if (realIp) return realIp;++ const forwardedIp = c.req.header("X-Forwarded-For")?.split(",", 1)[0]?.trim();+ return forwardedIp || null;+};++const tooManyLoginAttempts = (c: Context, retryAfterSeconds: number) => {+ c.header("Retry-After", String(retryAfterSeconds));+ return apiError(c, "login_rate_limited", "Too many login attempts. Try again later.", 429);+};+const verifyLogin = async (env: Bindings, username: string, password: string): Promise<UserRow | null> => {const normalizedUsername = username.trim();const existingUser = await getUserByUsername(env.storage.db, normalizedUsername);diff --git a/docs/manual-deploy.md b/docs/manual-deploy.mdindex 4e0737f9..9eb51e9c 100644--- a/docs/manual-deploy.md+++ b/docs/manual-deploy.md@@ -41,6 +41,12 @@ EDGE_EVER_R2_BUCKET_NAME=edgeever-resourcesEDGE_EVER_AUTH_USERNAME=adminEDGE_EVER_AUTH_PASSWORD=<strong password>EDGE_EVER_SESSION_TTL_DAYS=400+# Optional portable application-level login protection. These also work with Docker + SQLite.+EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS=900+EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS=5+EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS=900+EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS=30+EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS=300```Then run:diff --git a/docs/manual-deploy.zh-CN.md b/docs/manual-deploy.zh-CN.mdindex f62498fe..5fbcec03 100644--- a/docs/manual-deploy.zh-CN.md+++ b/docs/manual-deploy.zh-CN.md@@ -41,6 +41,12 @@ EDGE_EVER_R2_BUCKET_NAME=edgeever-resourcesEDGE_EVER_AUTH_USERNAME=adminEDGE_EVER_AUTH_PASSWORD=<强密码>EDGE_EVER_SESSION_TTL_DAYS=400+# 可选的应用层登录防护参数;同样适用于 Docker + SQLite。+EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS=900+EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS=5+EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS=900+EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS=30+EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS=300```然后运行:diff --git a/docs/openapi.json b/docs/openapi.jsonindex 7e2015e2..4ec6d08d 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -222,6 +222,9 @@"401": {"$ref": "#/components/responses/Error"},+ "429": {+ "$ref": "#/components/responses/Error"+ },"503": {"$ref": "#/components/responses/Error"}diff --git a/docs/self-hosting-architecture.md b/docs/self-hosting-architecture.mdindex 4dca0650..a605183b 100644--- a/docs/self-hosting-architecture.md+++ b/docs/self-hosting-architecture.md@@ -60,6 +60,9 @@ ambiguous.- Support `EDGE_EVER_AUTH_USERNAME`, `EDGE_EVER_AUTH_PASSWORD`, and sessionsettings without Cloudflare-specific naming assumptions in the containerentrypoint.+- Keep login brute-force protection in the application layer with SQLite/D1-+ compatible storage; Cloudflare Rate Limiting and WAF may be optional+ deployment-level enhancements, but must not be required.- Expose a health check that distinguishes process availability from databasereadiness and attachment-store readiness.diff --git a/docs/self-hosting-architecture.zh-CN.md b/docs/self-hosting-architecture.zh-CN.mdindex 1b505a70..3e29e253 100644--- a/docs/self-hosting-architecture.zh-CN.md+++ b/docs/self-hosting-architecture.zh-CN.md@@ -49,6 +49,8 @@ EdgeEver 容器- 将 `/data` 作为唯一必需的应用持久化路径,方便 NAS 用户备份一个卷。- 容器入口需要支持 `EDGE_EVER_AUTH_USERNAME`、`EDGE_EVER_AUTH_PASSWORD` 和会话配置,同时不能把 Cloudflare 专有配置当作前置条件。+- 登录暴力破解防护必须使用应用层的 SQLite/D1 兼容存储实现;Cloudflare+ Rate Limiting 和 WAF 只能作为部署层的可选增强,不能作为运行前提。- 健康检查应区分进程可用、数据库就绪和附件存储就绪。本文档用于预留架构边界,不是 Docker 部署指南。在自托管适配器以及备份、diff --git a/migrations/0020_auth_login_attempts.sql b/migrations/0020_auth_login_attempts.sqlnew file mode 100644index 00000000..29af5cb6--- /dev/null+++ b/migrations/0020_auth_login_attempts.sql@@ -0,0 +1,12 @@+CREATE TABLE auth_login_attempts (+ scope TEXT NOT NULL CHECK (scope IN ('username', 'ip')),+ attempt_key TEXT NOT NULL,+ failure_count INTEGER NOT NULL DEFAULT 0 CHECK (failure_count >= 0),+ window_started_at TEXT NOT NULL,+ blocked_until TEXT,+ updated_at TEXT NOT NULL,+ PRIMARY KEY (scope, attempt_key)+);++CREATE INDEX idx_auth_login_attempts_updated+ ON auth_login_attempts(updated_at);diff --git a/scripts/run-wrangler.mjs b/scripts/run-wrangler.mjsindex fbcaac63..9a104205 100644--- a/scripts/run-wrangler.mjs+++ b/scripts/run-wrangler.mjs@@ -187,6 +187,11 @@ config = replaceTomlValue(const runtimeVars = {EDGE_EVER_AUTH_USERNAME: envValue("AUTH_USERNAME"),EDGE_EVER_SESSION_TTL_DAYS: envValue("SESSION_TTL_DAYS"),+ EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS: envValue("AUTH_LOGIN_WINDOW_SECONDS"),+ EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS: envValue("AUTH_LOGIN_USERNAME_MAX_ATTEMPTS"),+ EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS: envValue("AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS"),+ EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS: envValue("AUTH_LOGIN_IP_MAX_ATTEMPTS"),+ EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS: envValue("AUTH_LOGIN_IP_COOLDOWN_SECONDS"),EDGE_EVER_R2_BUCKET_NAME: envValue("R2_BUCKET_NAME"),EDGE_EVER_DEMO_MODE: envValue("DEMO_MODE"),EDGE_EVER_LOCAL_DEMO_SEED: envValue("LOCAL_DEMO_SEED"),diff --git a/scripts/self-hosted-server.mjs b/scripts/self-hosted-server.mjsindex df79728d..1867a69a 100644--- a/scripts/self-hosted-server.mjs+++ b/scripts/self-hosted-server.mjs@@ -71,6 +71,11 @@ const env = {EDGE_EVER_AUTH_PASSWORD: process.env.EDGE_EVER_AUTH_PASSWORD,EDGE_EVER_AUTH_PASSWORD_HASH: process.env.EDGE_EVER_AUTH_PASSWORD_HASH,EDGE_EVER_SESSION_TTL_DAYS: process.env.EDGE_EVER_SESSION_TTL_DAYS ?? "400",+ EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS: process.env.EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS,+ EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS: process.env.EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS,+ EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS: process.env.EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS,+ EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS: process.env.EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS,+ EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS: process.env.EDGE_EVER_AUTH_LOGIN_IP_COOLDOWN_SECONDS,EDGE_EVER_DEMO_MODE: process.env.EDGE_EVER_DEMO_MODE,EDGE_EVER_ALLOW_UNAUTHENTICATED: process.env.EDGE_EVER_ALLOW_UNAUTHENTICATED,};diff --git a/scripts/verify-deployment.mjs b/scripts/verify-deployment.mjsindex 50eebff6..a51f7628 100644--- a/scripts/verify-deployment.mjs+++ b/scripts/verify-deployment.mjs@@ -4,6 +4,7 @@ import { resolve } from "node:path";export const REQUIRED_TABLES = ["users","sessions",+ "auth_login_attempts","workspaces","workspace_members","notebooks",diff --git a/tests/auth-fail-closed.test.ts b/tests/auth-fail-closed.test.tsindex 6c18f99f..a8b30987 100644--- a/tests/auth-fail-closed.test.ts+++ b/tests/auth-fail-closed.test.ts@@ -95,6 +95,12 @@ describe("production authentication guard", () => {}return { id: "usr_owner" };},+ async all() {+ return { results: [] };+ },+ async run() {+ return { success: true };+ },};},} as unknown as D1Database;diff --git a/tests/auth-login-limiter.test.ts b/tests/auth-login-limiter.test.tsnew file mode 100644index 00000000..66d45a9f--- /dev/null+++ b/tests/auth-login-limiter.test.ts@@ -0,0 +1,83 @@+import { Database } from "bun:sqlite";+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import {+ checkLoginRateLimit,+ clearLoginAttempts,+ recordLoginFailure,+ resolveLoginRateLimitConfig,+} from "../apps/api/src/auth-login-limiter";+import { createSelfHostedStorageAdapter } from "../apps/api/src/self-hosted-storage-adapter";++const createDatabase = () => {+ const sqlite = new Database(":memory:");+ sqlite.exec(readFileSync("migrations/0020_auth_login_attempts.sql", "utf8"));+ return {+ sqlite,+ db: createSelfHostedStorageAdapter(sqlite, ".edgeever-test-resources").db,+ };+};++describe("login attempt limiter", () => {+ test("uses portable defaults and clamps invalid configuration", () => {+ expect(resolveLoginRateLimitConfig({})).toMatchObject({+ windowSeconds: 900,+ usernameMaxAttempts: 5,+ usernameCooldownSeconds: 900,+ ipMaxAttempts: 30,+ ipCooldownSeconds: 300,+ });+ expect(resolveLoginRateLimitConfig({+ EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS: "0",+ EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS: "6.5",+ EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS: "2000",+ })).toMatchObject({+ windowSeconds: 900,+ usernameMaxAttempts: 5,+ ipMaxAttempts: 1_000,+ });+ });++ test("blocks repeated failures and reports a retry duration", async () => {+ const { sqlite, db } = createDatabase();+ const config = resolveLoginRateLimitConfig({+ EDGE_EVER_AUTH_LOGIN_WINDOW_SECONDS: "60",+ EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS: "2",+ EDGE_EVER_AUTH_LOGIN_USERNAME_COOLDOWN_SECONDS: "30",+ EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS: "10",+ });+ const keys = [{ scope: "username" as const, key: "user-hash" }];+ const start = Date.parse("2026-07-26T00:00:00.000Z");++ try {+ expect((await checkLoginRateLimit(db, keys, config, start)).retryAfterSeconds).toBe(0);+ expect((await recordLoginFailure(db, keys, config, start)).retryAfterSeconds).toBe(0);+ expect((await recordLoginFailure(db, keys, config, start + 1_000)).retryAfterSeconds).toBe(30);+ expect((await checkLoginRateLimit(db, keys, config, start + 2_000)).retryAfterSeconds).toBe(29);+ expect((await checkLoginRateLimit(db, keys, config, start + 31_000)).retryAfterSeconds).toBe(0);+ } finally {+ sqlite.close();+ }+ });++ test("clears username and IP buckets after a successful login", async () => {+ const { sqlite, db } = createDatabase();+ const config = resolveLoginRateLimitConfig({+ EDGE_EVER_AUTH_LOGIN_USERNAME_MAX_ATTEMPTS: "1",+ EDGE_EVER_AUTH_LOGIN_IP_MAX_ATTEMPTS: "1",+ });+ const keys = [+ { scope: "username" as const, key: "user-hash" },+ { scope: "ip" as const, key: "ip-hash" },+ ];++ try {+ await recordLoginFailure(db, keys, config);+ await clearLoginAttempts(db, keys);+ expect((await checkLoginRateLimit(db, keys, config)).retryAfterSeconds).toBe(0);+ expect(sqlite.query("SELECT COUNT(*) AS count FROM auth_login_attempts").get()).toEqual({ count: 0 });+ } finally {+ sqlite.close();+ }+ });+});