Skip to content

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

fix: harden Cloudflare deployment

tianma-if50ad70129b0f
diff --git a/.github/workflows/deploy-tools.yml b/.github/workflows/deploy-tools.yml
new file mode 100644
index 00000000..722d783b
--- /dev/null
+++ b/.github/workflows/deploy-tools.yml
@@ -0,0 +1,58 @@
+name: Test deployment tools
+
+on:
+ pull_request:
+ paths:
+ - "scripts/cloudflare-deploy.mjs"
+ - "scripts/run-wrangler.mjs"
+ - "scripts/wrangler-runner.mjs"
+ - "scripts/verify-deployment.mjs"
+ - "tests/wrangler-runner.test.ts"
+ - "tests/deployment-verify.test.ts"
+ - "package.json"
+ - "bun.lock"
+ - ".github/workflows/deploy-tools.yml"
+ push:
+ branches:
+ - main
+ paths:
+ - "scripts/cloudflare-deploy.mjs"
+ - "scripts/run-wrangler.mjs"
+ - "scripts/wrangler-runner.mjs"
+ - "scripts/verify-deployment.mjs"
+ - "tests/wrangler-runner.test.ts"
+ - "tests/deployment-verify.test.ts"
+ - "package.json"
+ - "bun.lock"
+ - ".github/workflows/deploy-tools.yml"
+
+permissions:
+ contents: read
+
+jobs:
+ wrangler:
+ name: Wrangler runner (${{ matrix.os }})
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os:
+ - ubuntu-latest
+ - windows-latest
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v5
+
+ - name: Set up Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: latest
+
+ - name: Install dependencies
+ run: bun install --frozen-lockfile
+
+ - name: Launch project-local Wrangler
+ run: bun scripts/run-wrangler.mjs --version
+
+ - name: Test deployment tooling
+ run: bun test tests/wrangler-runner.test.ts tests/deployment-verify.test.ts
diff --git a/README.md b/README.md
index 0468d0d0..77e6bcd1 100644
--- a/README.md
+++ b/README.md
@@ -80,6 +80,8 @@ Please refer to the [Cloudflare Manual Deployment Guide](docs/manual-deploy.md)
The automated helper commands are recommended. The template uses `admin` / `admin123` for the initial login, and the password can be changed later in Personal Settings. If you create the Cloudflare resources manually, finish configuring `.env.local`—including the D1 ID, R2 bucket, and the 400-day session limit—before running `bun run deploy`.
+Production deployments fail closed: when D1 migrations or the login Secret are missing, the instance shows a diagnosable configuration error and denies access instead of falling back to an unauthenticated workspace. Never insert plaintext passwords into D1; use the recovery command documented in the manual deployment guide.
+
## Multi-Account Login
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 9ef9bf56..61db8efa 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -77,6 +77,8 @@ Agent 应优先按 [AI Agent Cloudflare Deployment](docs/agent-deploy-cloudflare
推荐优先使用自动化辅助命令。配置模板使用 `admin` / `admin123` 作为初始登录账号密码,之后可在个人设置中修改密码。如果选择完全手动创建 Cloudflare 资源,必须先在 `.env.local` 中完成 D1 ID、R2 bucket 和 400 天会话期限等配置,再执行 `bun run deploy`。
+生产部署采用安全关闭策略:D1 未迁移或登录 Secret 缺失时,实例会显示可诊断的配置错误并拒绝访问,不会自动退化成免登录模式。请勿直接向 D1 写入明文密码;故障恢复命令见手动部署指南。
+
## 多账号登录
diff --git a/apps/api/src/auth-bootstrap.ts b/apps/api/src/auth-bootstrap.ts
index 51bd075f..33d7910a 100644
--- a/apps/api/src/auth-bootstrap.ts
+++ b/apps/api/src/auth-bootstrap.ts
@@ -1,5 +1,20 @@
type PasswordHashVerifier = (password: string, passwordHash: string) => Promise<boolean>;
+const PASSWORD_HASH_PATTERN = /^pbkdf2-sha256\$(\d+)\$([^$]+)\$([^$]+)$/;
+
+export const isSupportedPasswordHash = (passwordHash: string) => {
+ const match = passwordHash.match(PASSWORD_HASH_PATTERN);
+ if (!match || Number(match[1]) < 100_000) {
+ return false;
+ }
+
+ try {
+ return decodeBase64Url(match[2]).byteLength === 16 && decodeBase64Url(match[3]).byteLength === 32;
+ } catch {
+ return false;
+ }
+};
+
export const hasBootstrapCredential = (password: string | undefined, passwordHash: string | undefined) =>
Boolean(password || passwordHash?.trim());
@@ -38,3 +53,9 @@ const timingSafeEqual = (left: Uint8Array, right: Uint8Array) => {
return diff === 0;
};
+
+const decodeBase64Url = (value: string) => {
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");
+ return Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
+};
diff --git a/apps/api/src/auth-state.ts b/apps/api/src/auth-state.ts
new file mode 100644
index 00000000..b7f89ef9
--- /dev/null
+++ b/apps/api/src/auth-state.ts
@@ -0,0 +1,31 @@
+export type InstanceAuthMode = "required" | "disabled" | "unconfigured";
+
+export const isUnauthenticatedAccessEnabled = (value: string | undefined) =>
+ value?.trim().toLowerCase() === "true";
+
+export const resolveInstanceAuthMode = ({
+ allowUnauthenticated,
+ hasBootstrapCredential,
+ hasEnabledUser,
+}: {
+ allowUnauthenticated: boolean;
+ hasBootstrapCredential: boolean;
+ hasEnabledUser: boolean;
+}): InstanceAuthMode => {
+ if (allowUnauthenticated) {
+ return "disabled";
+ }
+
+ if (hasBootstrapCredential || hasEnabledUser) {
+ return "required";
+ }
+
+ return "unconfigured";
+};
+
+export const isDatabaseNotReadyError = (error: unknown) => {
+ const message = error instanceof Error ? error.message : String(error);
+ return /D1_ERROR|no such table|no such column|DB\.prepare is not a function|Cannot read properties of undefined.*prepare/i.test(
+ message,
+ );
+};
diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts
index 24f9a8af..3f24aef5 100644
--- a/apps/api/src/index.ts
+++ b/apps/api/src/index.ts
@@ -50,7 +50,13 @@ import { Hono } from "hono";
import { deleteCookie, getCookie, setCookie } from "hono/cookie";
import { cors } from "hono/cors";
import openApiSpec from "../../../docs/openapi.json";
-import { hasBootstrapCredential, verifyBootstrapPassword } from "./auth-bootstrap";
+import { hasBootstrapCredential, isSupportedPasswordHash, verifyBootstrapPassword } from "./auth-bootstrap";
+import {
+ isDatabaseNotReadyError,
+ isUnauthenticatedAccessEnabled,
+ resolveInstanceAuthMode,
+ type InstanceAuthMode,
+} from "./auth-state";
import {
isDemoModeEnabled,
isProtectedDemoAccount,
@@ -68,6 +74,7 @@ type Bindings = {
EDGE_EVER_R2_BUCKET_NAME?: string;
EDGE_EVER_DEMO_MODE?: string;
EDGE_EVER_LOCAL_DEMO_SEED?: string;
+ EDGE_EVER_ALLOW_UNAUTHENTICATED?: string;
};
type AuthContext = {
@@ -427,20 +434,31 @@ app.use(
})
);
-app.get("/api/health", (c) =>
- c.json({
+app.get("/api/health", async (c) => {
+ const authMode = await getInstanceAuthMode(c.env);
+
+ if (authMode === "unconfigured") {
+ return authNotConfigured(c);
+ }
+
+ return c.json({
ok: true,
name: "edgeever",
runtime: "cloudflare-workers",
- })
-);
+ authMode,
+ });
+});
app.get("/api/openapi.json", (c) => c.json(openApiSpec));
app.get("/api/v1/auth/session", async (c) => {
- const authRequired = await isAuthRequired(c.env);
+ const authMode = await getInstanceAuthMode(c.env);
+
+ if (authMode === "unconfigured") {
+ return authNotConfigured(c);
+ }
- if (!authRequired) {
+ if (authMode === "disabled") {
return c.json({
authRequired: false,
authenticated: true,
@@ -473,6 +491,11 @@ app.get("/api/v1/auth/session", async (c) => {
});
app.post("/api/v1/auth/login", zValidator("json", LoginSchema), async (c) => {
+ const authMode = await getInstanceAuthMode(c.env);
+ if (authMode === "unconfigured") {
+ return authNotConfigured(c);
+ }
+
const input = c.req.valid("json");
const user = await verifyLogin(c.env, input.username, input.password);
@@ -678,9 +701,13 @@ app.use("/api/v1/*", async (c, next) => {
return;
}
- const authRequired = await isAuthRequired(c.env);
+ const authMode = await getInstanceAuthMode(c.env);
+
+ if (authMode === "unconfigured") {
+ return authNotConfigured(c);
+ }
- if (!authRequired) {
+ if (authMode === "disabled") {
c.set("auth", {
kind: "user",
actorType: "user",
@@ -2549,6 +2576,20 @@ app.notFound((c) =>
)
);
+app.onError((error, c) => {
+ if (error instanceof AppError) {
+ return apiError(c, error.code, error.message, error.status);
+ }
+
+ if (isDatabaseNotReadyError(error)) {
+ console.error("EdgeEver database readiness check failed", error);
+ return databaseNotReady(c);
+ }
+
+ console.error("Unhandled EdgeEver API error", error);
+ return apiError(c, "internal_error", "An unexpected server error occurred.", 500);
+});
+
export default worker;
type JsonRpcRequest = {
@@ -3462,13 +3503,37 @@ const decodeBase64Data = async (value: string) => {
const escapeMarkdownImageAlt = (value: string) => value.replace(/[\\[\]]/g, "\\$&");
const escapeMarkdownLinkLabel = (value: string) => value.replace(/[\\[\]]/g, "\\$&");
-const isAuthRequired = async (env: Bindings) => {
- if (hasBootstrapCredential(env.EDGE_EVER_AUTH_PASSWORD, env.EDGE_EVER_AUTH_PASSWORD_HASH)) {
- return true;
+const getInstanceAuthMode = async (env: Bindings): Promise<InstanceAuthMode> => {
+ if (!env.DB || typeof env.DB.prepare !== "function") {
+ throw new AppError(
+ "database_not_ready",
+ "Database is not ready. Bind the D1 database as DB and apply the remote migrations.",
+ 503,
+ );
}
- const user = await env.DB.prepare(`SELECT id FROM users WHERE is_disabled = 0 LIMIT 1`).first<{ id: string }>();
- return Boolean(user);
+ let user: { id: string } | null;
+ try {
+ user = await env.DB.prepare(`SELECT id FROM users WHERE is_disabled = 0 LIMIT 1`).first<{ id: string }>();
+ } catch (error) {
+ if (isDatabaseNotReadyError(error)) {
+ throw new AppError(
+ "database_not_ready",
+ "Database is not ready. Bind the D1 database as DB and apply the remote migrations.",
+ 503,
+ );
+ }
+ throw error;
+ }
+
+ return resolveInstanceAuthMode({
+ allowUnauthenticated: isUnauthenticatedAccessEnabled(env.EDGE_EVER_ALLOW_UNAUTHENTICATED),
+ hasBootstrapCredential: hasBootstrapCredential(
+ env.EDGE_EVER_AUTH_PASSWORD,
+ env.EDGE_EVER_AUTH_PASSWORD_HASH,
+ ),
+ hasEnabledUser: Boolean(user),
+ });
};
const verifyLogin = async (env: Bindings, username: string, password: string): Promise<UserRow | null> => {
@@ -3476,7 +3541,19 @@ const verifyLogin = async (env: Bindings, username: string, password: string): P
const existingUser = await getUserByUsername(env.DB, normalizedUsername);
if (existingUser) {
- return (await verifyPassword(password, existingUser.password_hash)) ? existingUser : null;
+ if (await verifyPassword(password, existingUser.password_hash)) {
+ return existingUser;
+ }
+
+ if (!isSupportedPasswordHash(existingUser.password_hash)) {
+ throw new AppError(
+ "password_hash_invalid",
+ "This account has an invalid password hash. Reset it with the EdgeEver password reset command.",
+ 503,
+ );
+ }
+
+ return null;
}
const configuredHash = env.EDGE_EVER_AUTH_PASSWORD_HASH?.trim();
@@ -6317,6 +6394,22 @@ const apiError = (c: Context, code: string, message: string, status: number) =>
status as 400
);
+const authNotConfigured = (c: Context) =>
+ apiError(
+ c,
+ "auth_not_configured",
+ "Authentication is not configured. Set EDGE_EVER_AUTH_PASSWORD as a Worker Secret and redeploy.",
+ 503,
+ );
+
+const databaseNotReady = (c: Context) =>
+ apiError(
+ c,
+ "database_not_ready",
+ "Database is not ready. Bind the D1 database as DB and apply the remote migrations.",
+ 503,
+ );
+
const conflict = (c: Context, code: string, message: string) =>
c.json(
{
diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsx
index 9a26cb31..b6ee05cc 100644
--- a/apps/web/src/app/App.tsx
+++ b/apps/web/src/app/App.tsx
@@ -1,10 +1,11 @@
import { lazy, Suspense, useEffect } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Navigate, Route, Routes, useNavigate } from "react-router";
+import { useTranslation } from "react-i18next";
import { PwaUpdateNotice } from "@/components/PwaUpdateNotice";
import { PwaInstallProvider } from "@/components/PwaInstallContext";
import { PwaIosPrompt } from "@/components/PwaIosPrompt";
-import { api } from "@/lib/api";
+import { api, ApiRequestError } from "@/lib/api";
import { EVERNOTE_MIGRATION_PATH } from "@/lib/routes";
import type { AuthSession } from "@edgeever/shared";
@@ -41,6 +42,7 @@ const EvernoteMigrationRoute = () => {
const AuthenticatedWorkspace = () => {
const queryClient = useQueryClient();
+ const { t } = useTranslation();
const sessionQuery = useQuery({
queryKey: ["auth", "session"],
@@ -90,12 +92,29 @@ const AuthenticatedWorkspace = () => {
}
const session = sessionQuery.data;
+ const configurationError =
+ sessionQuery.error instanceof ApiRequestError
+ ? sessionQuery.error.code === "auth_not_configured"
+ ? t("login.authNotConfigured")
+ : sessionQuery.error.code === "database_not_ready"
+ ? t("login.databaseNotReady")
+ : t("login.instanceUnavailable")
+ : sessionQuery.error
+ ? t("login.instanceUnavailable")
+ : null;
+ const loginError =
+ loginMutation.error instanceof ApiRequestError && loginMutation.error.code === "password_hash_invalid"
+ ? t("login.passwordHashInvalid")
+ : loginMutation.error instanceof Error
+ ? loginMutation.error.message
+ : null;
if (!session?.authenticated) {
return (
<Suspense fallback={<AuthLoadingScreen />}>
<LoginScreen
- error={loginMutation.error instanceof Error ? loginMutation.error.message : null}
+ configurationError={configurationError}
+ error={loginError}
isSubmitting={loginMutation.isPending}
onSubmit={(payload) => loginMutation.mutate(payload)}
/>
diff --git a/apps/web/src/components/LoginScreen.tsx b/apps/web/src/components/LoginScreen.tsx
index 09404cf0..254f31f3 100644
--- a/apps/web/src/components/LoginScreen.tsx
+++ b/apps/web/src/components/LoginScreen.tsx
@@ -6,6 +6,7 @@ import { GitHubRepositoryLink } from "@/components/GitHubRepositoryLink";
import { Input } from "@/components/ui/input";
interface LoginScreenProps {
+ configurationError: string | null;
error: string | null;
isSubmitting: boolean;
onSubmit: (payload: { username: string; password: string }) => void;
@@ -23,7 +24,7 @@ const getDefaultLoginCredentials = () => {
return isDemoHost ? DEMO_LOGIN_CREDENTIALS : { username: "admin", password: "" };
};
-export const LoginScreen = ({ error, isSubmitting, onSubmit }: LoginScreenProps) => {
+export const LoginScreen = ({ configurationError, error, isSubmitting, onSubmit }: LoginScreenProps) => {
const { t } = useTranslation();
const [username, setUsername] = useState(() => getDefaultLoginCredentials().username);
const [password, setPassword] = useState(() => getDefaultLoginCredentials().password);
@@ -55,7 +56,11 @@ export const LoginScreen = ({ error, isSubmitting, onSubmit }: LoginScreenProps)
</div>
</div>
- <form className="space-y-5" onSubmit={handleSubmit}>
+ {configurationError ? (
+ <div className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm font-medium leading-6 text-amber-900">
+ {configurationError}
+ </div>
+ ) : <form className="space-y-5" onSubmit={handleSubmit}>
<label className="block">
<span className="mb-2 block text-sm font-semibold text-slate-700">{t("login.username")}</span>
<Input
@@ -93,7 +98,7 @@ export const LoginScreen = ({ error, isSubmitting, onSubmit }: LoginScreenProps)
<LockKeyhole className="h-4 w-4 mr-1" />
{isSubmitting ? t("login.submitting") : t("login.submit")}
</Button>
- </form>
+ </form>}
</section>
</main>
);
diff --git a/docs/agent-deploy-cloudflare.md b/docs/agent-deploy-cloudflare.md
index 900d410c..a4aff185 100644
--- a/docs/agent-deploy-cloudflare.md
+++ b/docs/agent-deploy-cloudflare.md
@@ -24,7 +24,7 @@ If the user supplied a custom initial password, replace the first command with:
EDGE_EVER_PASSWORD='<first-login-password>' bun run deploy:setup
```
-Do not deploy until `deploy:doctor` passes. After deployment, verify the Worker URL, `/api/openapi.json`, and login. The default initial login is `admin` / `admin123`.
+Do not deploy until `deploy:doctor` passes. After deployment, verify that `/api/health` returns `200` with `"ok": true`, then verify `/api/openapi.json` and login. A `database_not_ready` or `auth_not_configured` response means deployment is incomplete and must not be handed off as successful. The default initial login is `admin` / `admin123`.
## Automatic Updates
diff --git a/docs/manual-deploy.md b/docs/manual-deploy.md
index 7d33244a..ab3b4031 100644
--- a/docs/manual-deploy.md
+++ b/docs/manual-deploy.md
@@ -35,6 +35,8 @@ If you are comfortable with Cloudflare and the command line, or prefer customize
To use a custom first-login password, run `EDGE_EVER_PASSWORD='<your password>' bun run deploy:setup` instead. You can also change the password later in Personal Settings.
+ `deploy:setup` always invokes the project-local Wrangler directly, so a global `wrangler` installation is not required and PowerShell, CMD, and Git Bash are supported. If Cloudflare is not authorized yet, the command starts `wrangler login` automatically. If the browser does not open, copy the authorization URL printed in the terminal into a browser and leave the command running until verification completes.
+
### Creating Cloudflare Resources Manually
If you prefer not to use the automated `deploy:setup` helper, you can create the resources manually using Cloudflare CLI (Wrangler):
@@ -65,8 +67,27 @@ Before running `bun run deploy`, copy the D1 `database_id` and R2 bucket name in
`bun run deploy` builds the web app, applies remote D1 migrations, deploys the Worker, and uploads `EDGE_EVER_AUTH_PASSWORD` as a Worker Secret. After the first successful login, EdgeEver stores a salted PBKDF2-SHA256 hash in D1. Existing installations may continue to use `EDGE_EVER_AUTH_PASSWORD_HASH`; when both Secrets are set, the hash takes precedence. Verify the deployment by signing in with `EDGE_EVER_AUTH_USERNAME` and the configured password.
+`.env.local` is read only by the local EdgeEver scripts. It is not automatically uploaded to Cloudflare as a file, and it must never be uploaded manually or committed to Git. A build started directly from Cloudflare Dashboard does not automatically receive the D1, R2, or password settings in this file. Use `bun run deploy` for the first deployment, then use `bun run deploy:builds:setup` to copy the required settings securely into Workers Builds.
+
+The deployment command now runs `deploy:doctor` first and stops when the D1 ID, R2 bucket, or login password is missing. After deployment, `deploy:verify` checks the remote D1 schema and the Worker's authentication Secret; a missing requirement makes deployment exit as failed. The Worker also fails closed: when a production instance has neither a password Secret nor an enabled user, it returns `auth_not_configured` instead of opening an unauthenticated workspace. `/api/health` checks D1 and authentication initialization; the instance is ready only when it returns `200` with `"ok": true`.
+
Existing installations do not need to migrate. If you intentionally switch from the hash setting to `EDGE_EVER_AUTH_PASSWORD`, remove the old `EDGE_EVER_AUTH_PASSWORD_HASH` from `.env.local`, Workers Builds, and the Worker's runtime Secrets; otherwise the legacy hash remains authoritative.
+### Recovering login or database initialization failures
+
+- If the login page says the database is not ready, or the API returns `database_not_ready`, verify that the D1 binding is named exactly `DB`, then run `bun run db:migrate:remote && bun run deploy`.
+- If the login page says the security setup is incomplete, or the API returns `auth_not_configured`, configure `EDGE_EVER_AUTH_PASSWORD` in `.env.local`, then run `bun run deploy`. Never clear the account settings to bypass login.
+- If credentials were inserted into the `users` table manually, do not put plaintext in `password_hash`. EdgeEver rejects invalid hashes and points to the safe recovery command on the login page. Run:
+
+ ```sh
+ EDGE_EVER_PASSWORD='<new password of at least 8 characters>' \
+ bun run auth:reset-password -- --remote --username admin
+ ```
+
+ This command creates a compatible PBKDF2-SHA256 hash and revokes the account's old sessions without deleting note data.
+
+Cloudflare binding names must be exactly `DB` for D1 and `RESOURCES` for R2. The plain variable `EDGE_EVER_AUTH_USERNAME` does not replace the encrypted `EDGE_EVER_AUTH_PASSWORD` Secret.
+
---
## Enable Automatic Updates
diff --git a/docs/manual-deploy.zh-CN.md b/docs/manual-deploy.zh-CN.md
index 9ae8fcb5..1a5b61e5 100644
--- a/docs/manual-deploy.zh-CN.md
+++ b/docs/manual-deploy.zh-CN.md
@@ -35,6 +35,8 @@
如果希望首次登录就使用自定义密码,可改为执行 `EDGE_EVER_PASSWORD='<你的密码>' bun run deploy:setup`。部署成功后也可以在个人中心修改密码。
+ `deploy:setup` 始终直接使用项目内安装的 Wrangler,不要求全局安装 `wrangler`,并兼容 PowerShell、CMD 与 Git Bash。若尚未授权 Cloudflare,该命令会自动启动 `wrangler login`;浏览器没有自动打开时,请复制终端显示的授权链接到浏览器完成登录,然后保持命令运行到验证结束。
+
### 完全手动创建 Cloudflare 资源
如果你不想使用 `deploy:setup` 自动化脚本,也可以完全手动使用 Cloudflare CLI (Wrangler) 创建资源:
@@ -65,8 +67,27 @@ bun run deploy
`bun run deploy` 会构建 Web 应用、执行远程 D1 migration、部署 Worker,并将 `EDGE_EVER_AUTH_PASSWORD` 作为 Worker Secret 上传。首次登录成功后,EdgeEver 会将加盐的 PBKDF2-SHA256 哈希写入 D1。已有实例可以继续使用 `EDGE_EVER_AUTH_PASSWORD_HASH`;两个 Secret 同时存在时优先使用哈希。部署完成后,请使用 `.env.local` 中的 `EDGE_EVER_AUTH_USERNAME` 和配置的密码登录验证。
+`.env.local` 只供本机 EdgeEver 脚本读取,不会作为文件自动上传到 Cloudflare,也不应手工上传或提交到 Git。若从 Cloudflare Dashboard 直接触发构建,该文件中的 D1、R2 和密码配置不会自动生效;请使用 `bun run deploy` 完成首次部署,再使用 `bun run deploy:builds:setup` 将必要配置安全地写入 Workers Builds。
+
+部署命令会先自动执行 `deploy:doctor`,缺少 D1 ID、R2 bucket 或登录密码时会直接停止。部署完成后还会执行 `deploy:verify`,检查远程 D1 的关键数据表和 Worker 鉴权 Secret;任一缺失都会让部署以失败退出。Worker 也采用安全关闭策略:生产实例既没有密码 Secret、又没有有效用户时,会返回 `auth_not_configured`,不会降级成免登录工作区。`/api/health` 会检查 D1 和鉴权初始化状态;只有返回 `200` 且包含 `"ok": true` 才表示实例真正可用。
+
已有实例无需迁移。如果确实要从哈希配置切换为 `EDGE_EVER_AUTH_PASSWORD`,需要同时从 `.env.local`、Workers Builds 和 Worker 运行时 Secrets 中移除旧的 `EDGE_EVER_AUTH_PASSWORD_HASH`,否则旧哈希仍会优先生效。
+### 登录或数据库初始化故障恢复
+
+- 登录页显示“数据库尚未就绪”或接口返回 `database_not_ready`:确认 D1 binding 名称严格为 `DB`,然后执行 `bun run db:migrate:remote && bun run deploy`。
+- 登录页显示“实例尚未完成安全配置”或接口返回 `auth_not_configured`:在 `.env.local` 配置 `EDGE_EVER_AUTH_PASSWORD`,然后执行 `bun run deploy`。不要通过清空账号配置绕过登录。
+- 已经手工向 `users` 表写入账号密码:不要向 `password_hash` 写明文。EdgeEver 会拒绝无效哈希并在登录页提示安全恢复命令,请执行:
+
+ ```sh
+ EDGE_EVER_PASSWORD='<至少 8 位的新密码>' \
+ bun run auth:reset-password -- --remote --username admin
+ ```
+
+ 该命令会生成兼容的 PBKDF2-SHA256 哈希并撤销该账号的旧会话,不会删除笔记数据。
+
+Cloudflare 控制台中的 binding 名称必须严格使用 `DB`(D1)和 `RESOURCES`(R2)。普通变量 `EDGE_EVER_AUTH_USERNAME` 不能代替加密 Secret `EDGE_EVER_AUTH_PASSWORD`。
+
---
## 开启自动更新
diff --git a/docs/openapi.json b/docs/openapi.json
index 7245b2a4..ab32a0ed 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -39,12 +39,19 @@
},
"runtime": {
"type": "string"
+ },
+ "authMode": {
+ "type": "string",
+ "enum": ["required", "disabled"]
}
},
- "required": ["ok", "name", "runtime"]
+ "required": ["ok", "name", "runtime", "authMode"]
}
}
}
+ },
+ "503": {
+ "$ref": "#/components/responses/Error"
}
}
}
@@ -74,6 +81,9 @@
}
}
}
+ },
+ "503": {
+ "$ref": "#/components/responses/Error"
}
}
}
@@ -105,6 +115,9 @@
},
"401": {
"$ref": "#/components/responses/Error"
+ },
+ "503": {
+ "$ref": "#/components/responses/Error"
}
}
}
diff --git a/package.json b/package.json
index 38b79756..06413960 100644
--- a/package.json
+++ b/package.json
@@ -43,9 +43,10 @@
"mcp:stdio": "bun scripts/edgeever-mcp-stdio.mjs",
"deploy:doctor": "bun scripts/cloudflare-deploy.mjs doctor",
"deploy:setup": "bun scripts/cloudflare-deploy.mjs setup",
- "deploy": "bun run build && bun run deploy:worker",
+ "deploy": "bun run deploy:doctor && bun run build && bun run deploy:worker",
"deploy:worker": "bun run deploy:cloudflare-builds",
- "deploy:cloudflare-builds": "bun run db:migrate:remote && bun scripts/run-wrangler.mjs deploy",
+ "deploy:cloudflare-builds": "bun run db:migrate:remote && bun scripts/run-wrangler.mjs deploy && bun run deploy:verify",
+ "deploy:verify": "bun scripts/verify-deployment.mjs",
"deploy:builds:setup": "bun scripts/cloudflare-workers-builds.mjs setup",
"deploy:site": "bun run build:site && wrangler pages deploy apps/site/dist --project-name=edgeever-official"
},
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index a6e33a03..4417c10d 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -43,6 +43,10 @@ export const enUS = {
password: "Password",
submitting: "Signing in...",
submit: "Open workspace",
+ authNotConfigured: "This instance has not completed its security setup. Set EDGE_EVER_AUTH_PASSWORD as a Worker Secret and redeploy. Unauthenticated access stays blocked until it is fixed.",
+ databaseNotReady: "The database is not ready. Verify that the D1 binding is named DB, apply the remote migrations, and redeploy.",
+ instanceUnavailable: "This instance is temporarily unavailable. Check the Worker logs and run bun run deploy:doctor to validate the deployment.",
+ passwordHashInvalid: "This account's password data is invalid; plaintext passwords are not supported. Follow the deployment guide and run auth:reset-password to reset it safely.",
},
nav: {
mobileMain: "Mobile primary navigation",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 3977bd5a..46c54541 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -43,6 +43,10 @@ export const zhCN = {
password: "密码",
submitting: "安全登录中...",
submit: "开启工作区",
+ authNotConfigured: "实例尚未完成安全配置。请在 Worker 中设置 EDGE_EVER_AUTH_PASSWORD Secret,然后重新部署;在修复前不会开放免登录访问。",
+ databaseNotReady: "数据库尚未就绪。请确认 D1 绑定名称为 DB,并执行远程数据库迁移后重新部署。",
+ instanceUnavailable: "实例暂时不可用。请查看 Worker 日志并运行 bun run deploy:doctor 检查部署配置。",
+ passwordHashInvalid: "该账号的密码数据格式无效,不能使用明文密码。请按照部署指南运行 auth:reset-password 安全重置。",
},
nav: {
mobileMain: "移动端主导航",
diff --git a/scripts/cloudflare-deploy.mjs b/scripts/cloudflare-deploy.mjs
index 8f7922e1..8dbd68f7 100644
--- a/scripts/cloudflare-deploy.mjs
+++ b/scripts/cloudflare-deploy.mjs
@@ -1,6 +1,7 @@
import { spawnSync } from "node:child_process";
import { copyFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
+import { runWranglerSync } from "./wrangler-runner.mjs";
const PLACEHOLDER_D1_ID = "00000000-0000-0000-0000-000000000000";
const UUID_PATTERN =
@@ -15,17 +16,6 @@ if (!["doctor", "setup"].includes(command)) {
const envPath = resolve(".env.local");
const envExamplePath = resolve(".env.local.example");
-const localWrangler = resolve(
- "node_modules",
- ".bin",
- process.platform === "win32" ? "wrangler.cmd" : "wrangler",
-);
-const wrangler = existsSync(localWrangler)
- ? localWrangler
- : process.platform === "win32"
- ? "wrangler.cmd"
- : "wrangler";
-
const parseEnv = (content) => {
const values = new Map();
@@ -105,11 +95,17 @@ const run = (executable, args, options = {}) =>
cwd: resolve("."),
encoding: "utf8",
env: process.env,
- shell: process.platform === "win32",
+ shell: false,
...options,
});
-const runWrangler = (args) => run(wrangler, args);
+const runWrangler = (args, options = {}) =>
+ runWranglerSync(args, {
+ cwd: resolve("."),
+ encoding: "utf8",
+ env: process.env,
+ ...options,
+ });
const check = (label, passed, detail = "") => {
const status = passed ? "ok" : "fail";
@@ -117,6 +113,33 @@ const check = (label, passed, detail = "") => {
return passed;
};
+const printCommandFailure = (result) => {
+ if (result.error?.message) console.error(result.error.message);
+ if (result.stdout) console.error(String(result.stdout).trim());
+ if (result.stderr) console.error(String(result.stderr).trim());
+};
+
+const ensureCloudflareAuth = () => {
+ let whoami = runWrangler(["whoami"]);
+ if (whoami.status === 0) {
+ return check("Cloudflare auth", true, "authenticated");
+ }
+
+ console.log("[info] Cloudflare authorization is required; starting Wrangler login...");
+ const login = runWrangler(["login"], { encoding: undefined, stdio: "inherit" });
+ if (login.status !== 0) {
+ check("Cloudflare auth", false, "Wrangler login did not complete");
+ if (login.error?.message) console.error(login.error.message);
+ return false;
+ }
+
+ whoami = runWrangler(["whoami"]);
+ const authenticated = whoami.status === 0;
+ check("Cloudflare auth", authenticated, authenticated ? "authenticated" : "login verification failed");
+ if (!authenticated) printCommandFailure(whoami);
+ return authenticated;
+};
+
const ensureEnvLocal = () => {
if (existsSync(envPath)) {
return;
@@ -230,12 +253,20 @@ const doctor = () => {
const values = readEnv();
let passed = true;
- passed = check("Bun", run("bun", ["--version"]).status === 0) && passed;
- passed = check("Wrangler", runWrangler(["--version"]).status === 0) && passed;
+ passed = check("Bun", run(process.execPath, ["--version"]).status === 0) && passed;
+ const wranglerVersion = runWrangler(["--version"]);
+ const wranglerAvailable = wranglerVersion.status === 0;
+ passed = check("Wrangler", wranglerAvailable) && passed;
+ if (!wranglerAvailable) printCommandFailure(wranglerVersion);
passed = check(".env.local", existsSync(envPath), existsSync(envPath) ? "present" : "missing") && passed;
- const whoami = runWrangler(["whoami"]);
- passed = check("Cloudflare auth", whoami.status === 0, whoami.status === 0 ? "authenticated" : "run wrangler login") && passed;
+ if (wranglerAvailable) {
+ const whoami = runWrangler(["whoami"]);
+ passed = check("Cloudflare auth", whoami.status === 0, whoami.status === 0 ? "authenticated" : "run bun scripts/run-wrangler.mjs login") && passed;
+ if (whoami.status !== 0) printCommandFailure(whoami);
+ } else {
+ passed = check("Cloudflare auth", false, "Wrangler is unavailable") && passed;
+ }
const databaseId = envValue("D1_DATABASE_ID", values);
passed =
@@ -276,6 +307,16 @@ const doctor = () => {
: "missing",
) && passed;
+ const allowUnauthenticated = envValue("ALLOW_UNAUTHENTICATED", values).toLowerCase();
+ passed =
+ check(
+ "production authentication policy",
+ allowUnauthenticated !== "true",
+ allowUnauthenticated === "true"
+ ? "EDGE_EVER_ALLOW_UNAUTHENTICATED is local-only and must not be enabled for deployment"
+ : "fail-closed",
+ ) && passed;
+
process.exit(passed ? 0 : 1);
};
@@ -284,9 +325,14 @@ const setup = () => {
const values = readEnv();
let passed = true;
- passed = check("Wrangler", runWrangler(["--version"]).status === 0) && passed;
- const whoami = runWrangler(["whoami"]);
- passed = check("Cloudflare auth", whoami.status === 0, whoami.status === 0 ? "authenticated" : "run wrangler login") && passed;
+ const wranglerVersion = runWrangler(["--version"]);
+ const wranglerAvailable = wranglerVersion.status === 0;
+ passed = check("Wrangler", wranglerAvailable) && passed;
+ if (!wranglerAvailable) printCommandFailure(wranglerVersion);
+
+ if (wranglerAvailable) {
+ passed = ensureCloudflareAuth() && passed;
+ }
if (!passed) {
process.exit(1);
diff --git a/scripts/run-wrangler.mjs b/scripts/run-wrangler.mjs
index cdfb17a3..fc729466 100644
--- a/scripts/run-wrangler.mjs
+++ b/scripts/run-wrangler.mjs
@@ -1,6 +1,6 @@
-import { spawnSync } from "node:child_process";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
+import { runWranglerSync } from "./wrangler-runner.mjs";
const PLACEHOLDER_D1_ID = "00000000-0000-0000-0000-000000000000";
const UUID_PATTERN =
@@ -95,6 +95,11 @@ const envValue = (name) => {
|| process.env[`EDGE_EVER_${name}`]?.trim();
};
+const isRemoteCommand =
+ wranglerArgs.includes("deploy") || wranglerArgs.includes("--remote");
+const isRemoteDevCommand = wranglerArgs.includes("dev") && wranglerArgs.includes("--remote");
+const isLocalDevCommand = wranglerArgs.includes("dev") && wranglerArgs.includes("--local");
+
const workerName = envValue("WORKER_NAME");
if (workerName) {
config = replaceTomlValue(config, "name", workerName);
@@ -139,6 +144,9 @@ const runtimeVars = {
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"),
+ // Auth-free access is a local-development capability. Remote deployments
+ // fail closed when credentials and users are both missing.
+ EDGE_EVER_ALLOW_UNAUTHENTICATED: isLocalDevCommand ? "true" : undefined,
};
const runtimeVarLines = Object.entries(runtimeVars)
.filter(([, value]) => Boolean(value))
@@ -185,11 +193,6 @@ custom_domain = ${customDomain ? "true" : "false"}
`;
}
-const isRemoteCommand =
- wranglerArgs.includes("deploy") || wranglerArgs.includes("--remote");
-const isRemoteDevCommand = wranglerArgs.includes("dev") && wranglerArgs.includes("--remote");
-const isLocalDevCommand = wranglerArgs.includes("dev") && wranglerArgs.includes("--local");
-
if (isRemoteDevCommand && !instance) {
console.error(
"Remote development requires an explicit instance. Run EDGE_EVER_INSTANCE=<name> bun run dev:remote.",
@@ -226,6 +229,13 @@ const authSecrets = {
};
const finalWranglerArgs = [...wranglerArgs];
+if (isDeployCommand && Object.keys(authSecrets).length === 0) {
+ console.error(
+ "Refusing to deploy without EDGE_EVER_AUTH_PASSWORD or EDGE_EVER_AUTH_PASSWORD_HASH. Run bun run deploy:setup first.",
+ );
+ process.exit(1);
+}
+
if (isLocalDevCommand && !hasEnvFileArg) {
writeFileSync(generatedLocalDevEnvPath, "# Intentionally empty: local development must not inherit remote instance secrets.\n");
finalWranglerArgs.push("--env-file", generatedLocalDevEnvPath);
@@ -236,32 +246,20 @@ if (isDeployCommand && Object.keys(authSecrets).length > 0 && !hasSecretsFileArg
finalWranglerArgs.push("--secrets-file", generatedSecretsPath);
}
-const localWrangler = resolve(
- "node_modules",
- ".bin",
- process.platform === "win32" ? "wrangler.cmd" : "wrangler",
-);
-const executable = existsSync(localWrangler)
- ? localWrangler
- : process.platform === "win32"
- ? "wrangler.cmd"
- : "wrangler";
-const result = spawnSync(executable, ["--config", configPath, ...finalWranglerArgs], {
+const result = runWranglerSync(["--config", configPath, ...finalWranglerArgs], {
+ cwd: resolve("."),
+ env: process.env,
stdio: "inherit",
- shell: process.platform === "win32",
});
if (result.status === 0 && isDeployCommand) {
for (const [secretName, secretValue] of Object.entries(authSecrets)) {
- const secretResult = spawnSync(
- executable,
- ["--config", configPath, "secret", "put", secretName],
- {
- input: secretValue,
- stdio: ["pipe", "inherit", "inherit"],
- shell: process.platform === "win32",
- },
- );
+ const secretResult = runWranglerSync(["--config", configPath, "secret", "put", secretName], {
+ cwd: resolve("."),
+ env: process.env,
+ input: secretValue,
+ stdio: ["pipe", "inherit", "inherit"],
+ });
if (secretResult.error) {
throw secretResult.error;
diff --git a/scripts/verify-deployment.mjs b/scripts/verify-deployment.mjs
new file mode 100644
index 00000000..90f10dd3
--- /dev/null
+++ b/scripts/verify-deployment.mjs
@@ -0,0 +1,76 @@
+import { spawnSync } from "node:child_process";
+import { resolve } from "node:path";
+
+export const REQUIRED_TABLES = [
+ "users",
+ "sessions",
+ "workspaces",
+ "workspace_members",
+ "notebooks",
+ "memos",
+ "mobile_sync_changes",
+];
+
+export const buildSchemaVerificationSql = () =>
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (${REQUIRED_TABLES.map((name) => `'${name}'`).join(", ")}) ORDER BY name`;
+
+export const parseD1Rows = (output) => {
+ const parsed = JSON.parse(output);
+ const results = Array.isArray(parsed) ? parsed : [parsed];
+ return results.flatMap((result) => result?.results ?? []);
+};
+
+export const parseSecretNames = (output) => {
+ const parsed = JSON.parse(output);
+ const secrets = Array.isArray(parsed) ? parsed : parsed?.secrets ?? parsed?.result ?? [];
+ return new Set(secrets.map((secret) => secret?.name).filter(Boolean));
+};
+
+const runWrangler = (args) => {
+ const result = spawnSync(
+ process.execPath,
+ [resolve("scripts/run-wrangler.mjs"), ...args],
+ { encoding: "utf8", env: process.env },
+ );
+
+ if (result.status !== 0) {
+ if (result.stdout) process.stdout.write(result.stdout);
+ if (result.stderr) process.stderr.write(result.stderr);
+ throw new Error(`Wrangler verification command exited with status ${result.status ?? 1}.`);
+ }
+
+ return result.stdout;
+};
+
+const main = () => {
+ const schemaOutput = runWrangler([
+ "d1",
+ "execute",
+ "DB",
+ "--remote",
+ "--command",
+ buildSchemaVerificationSql(),
+ "--json",
+ ]);
+ const tableNames = new Set(parseD1Rows(schemaOutput).map((row) => row.name));
+ const missingTables = REQUIRED_TABLES.filter((table) => !tableNames.has(table));
+ if (missingTables.length > 0) {
+ throw new Error(`Remote D1 migrations are incomplete; missing tables: ${missingTables.join(", ")}.`);
+ }
+ console.log(`[ok] remote D1 schema: ${REQUIRED_TABLES.length} required tables`);
+
+ const secretNames = parseSecretNames(runWrangler(["secret", "list", "--format", "json"]));
+ if (!secretNames.has("EDGE_EVER_AUTH_PASSWORD") && !secretNames.has("EDGE_EVER_AUTH_PASSWORD_HASH")) {
+ throw new Error("The deployed Worker has no EdgeEver authentication Secret.");
+ }
+ console.log("[ok] Worker authentication Secret is deployed");
+};
+
+if (import.meta.main) {
+ try {
+ main();
+ } catch (error) {
+ console.error(`[fail] ${error instanceof Error ? error.message : String(error)}`);
+ process.exit(1);
+ }
+}
diff --git a/scripts/wrangler-runner.mjs b/scripts/wrangler-runner.mjs
new file mode 100644
index 00000000..4331a9a9
--- /dev/null
+++ b/scripts/wrangler-runner.mjs
@@ -0,0 +1,32 @@
+import { spawnSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { resolve } from "node:path";
+
+export const resolveWranglerCliPath = (cwd = resolve(".")) =>
+ resolve(cwd, "node_modules", "wrangler", "bin", "wrangler.js");
+
+export const buildWranglerInvocation = (args, options = {}) => ({
+ executable: options.runtimeExecutable ?? process.execPath,
+ args: [resolveWranglerCliPath(options.cwd), ...args],
+});
+
+export const runWranglerSync = (args, options = {}) => {
+ const cwd = options.cwd ?? resolve(".");
+ const cliPath = resolveWranglerCliPath(cwd);
+ if (!existsSync(cliPath)) {
+ return {
+ status: 1,
+ signal: null,
+ stdout: "",
+ stderr: `Wrangler is not installed at ${cliPath}. Run bun install first.\n`,
+ error: new Error("Local Wrangler installation not found."),
+ };
+ }
+
+ const { runtimeExecutable, ...spawnOptions } = options;
+ return spawnSync(runtimeExecutable ?? process.execPath, [cliPath, ...args], {
+ cwd,
+ shell: false,
+ ...spawnOptions,
+ });
+};
diff --git a/tests/auth-bootstrap.test.ts b/tests/auth-bootstrap.test.ts
index 4a79d697..881b864f 100644
--- a/tests/auth-bootstrap.test.ts
+++ b/tests/auth-bootstrap.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, test } from "bun:test";
-import { hasBootstrapCredential, verifyBootstrapPassword } from "../apps/api/src/auth-bootstrap";
+import {
+ hasBootstrapCredential,
+ isSupportedPasswordHash,
+ verifyBootstrapPassword,
+} from "../apps/api/src/auth-bootstrap";
const rejectHash = async () => false;
@@ -35,4 +39,13 @@ describe("bootstrap password authentication", () => {
expect(hasBootstrapCredential(undefined, undefined)).toBe(false);
expect(await verifyBootstrapPassword("password", undefined, undefined, rejectHash)).toBe(false);
});
+
+ test("distinguishes valid password hashes from plaintext or damaged database values", () => {
+ const salt = "AAAAAAAAAAAAAAAAAAAAAA";
+ const hash = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
+
+ expect(isSupportedPasswordHash(`pbkdf2-sha256$100000$${salt}$${hash}`)).toBe(true);
+ expect(isSupportedPasswordHash("admin123")).toBe(false);
+ expect(isSupportedPasswordHash("pbkdf2-sha256$100000$broken$broken")).toBe(false);
+ });
});
diff --git a/tests/auth-fail-closed.test.ts b/tests/auth-fail-closed.test.ts
new file mode 100644
index 00000000..6c18f99f
--- /dev/null
+++ b/tests/auth-fail-closed.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, test } from "bun:test";
+import worker from "../apps/api/src/index";
+
+const executionContext = {
+ passThroughOnException() {},
+ waitUntil() {},
+ props: {},
+} as unknown as ExecutionContext;
+
+const createDatabase = (options: { userId?: string; error?: Error } = {}) =>
+ ({
+ prepare() {
+ return {
+ async first() {
+ if (options.error) throw options.error;
+ return options.userId ? { id: options.userId } : null;
+ },
+ };
+ },
+ }) as unknown as D1Database;
+
+const fetchApi = (path: string, env: Record<string, unknown>) =>
+ worker.fetch(
+ new Request(`https://edgeever.test${path}`),
+ env as never,
+ executionContext,
+ );
+
+describe("production authentication guard", () => {
+ test("returns a diagnosable 503 instead of opening an empty production instance", async () => {
+ const response = await fetchApi("/api/v1/auth/session", { DB: createDatabase() });
+
+ expect(response.status).toBe(503);
+ expect(await response.json()).toEqual({
+ error: {
+ code: "auth_not_configured",
+ message: "Authentication is not configured. Set EDGE_EVER_AUTH_PASSWORD as a Worker Secret and redeploy.",
+ },
+ });
+ });
+
+ test("reports unapplied D1 migrations as database_not_ready", async () => {
+ const response = await fetchApi("/api/health", {
+ DB: createDatabase({ error: new Error("D1_ERROR: no such table: users") }),
+ });
+
+ expect(response.status).toBe(503);
+ expect((await response.json()) as { error: { code: string } }).toMatchObject({
+ error: { code: "database_not_ready" },
+ });
+ });
+
+ test("keeps passwordless access behind the explicit local-only flag", async () => {
+ const response = await fetchApi("/api/v1/auth/session", {
+ DB: createDatabase(),
+ EDGE_EVER_ALLOW_UNAUTHENTICATED: "true",
+ });
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({
+ authRequired: false,
+ authenticated: true,
+ });
+ });
+
+ test("keeps first-login bootstrap protected when the users table is empty", async () => {
+ const response = await fetchApi("/api/v1/auth/session", {
+ DB: createDatabase(),
+ EDGE_EVER_AUTH_PASSWORD: "admin123",
+ });
+
+ expect(response.status).toBe(200);
+ expect(await response.json()).toMatchObject({
+ authRequired: true,
+ authenticated: false,
+ });
+ });
+
+ test("rejects a manually inserted plaintext password with an actionable error", async () => {
+ const database = {
+ prepare(sql: string) {
+ return {
+ bind() {
+ return this;
+ },
+ async first() {
+ if (sql.includes("password_hash")) {
+ return {
+ id: "usr_owner",
+ username: "admin",
+ password_hash: "admin123",
+ display_name: "Admin",
+ is_disabled: 0,
+ };
+ }
+ return { id: "usr_owner" };
+ },
+ };
+ },
+ } as unknown as D1Database;
+
+ const response = await worker.fetch(
+ new Request("https://edgeever.test/api/v1/auth/login", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ username: "admin", password: "admin123" }),
+ }),
+ { DB: database } as never,
+ executionContext,
+ );
+
+ expect(response.status).toBe(503);
+ expect((await response.json()) as { error: { code: string } }).toMatchObject({
+ error: { code: "password_hash_invalid" },
+ });
+ });
+});
diff --git a/tests/auth-state.test.ts b/tests/auth-state.test.ts
new file mode 100644
index 00000000..2ac621c4
--- /dev/null
+++ b/tests/auth-state.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, test } from "bun:test";
+import {
+ isDatabaseNotReadyError,
+ isUnauthenticatedAccessEnabled,
+ resolveInstanceAuthMode,
+} from "../apps/api/src/auth-state";
+
+describe("instance authentication state", () => {
+ test("fails closed when production has neither credentials nor users", () => {
+ expect(
+ resolveInstanceAuthMode({
+ allowUnauthenticated: false,
+ hasBootstrapCredential: false,
+ hasEnabledUser: false,
+ }),
+ ).toBe("unconfigured");
+ });
+
+ test("requires authentication when a bootstrap credential or enabled user exists", () => {
+ expect(
+ resolveInstanceAuthMode({
+ allowUnauthenticated: false,
+ hasBootstrapCredential: true,
+ hasEnabledUser: false,
+ }),
+ ).toBe("required");
+ expect(
+ resolveInstanceAuthMode({
+ allowUnauthenticated: false,
+ hasBootstrapCredential: false,
+ hasEnabledUser: true,
+ }),
+ ).toBe("required");
+ });
+
+ test("allows unauthenticated access only through an explicit opt-in", () => {
+ expect(isUnauthenticatedAccessEnabled("true")).toBe(true);
+ expect(isUnauthenticatedAccessEnabled(" TRUE ")).toBe(true);
+ expect(isUnauthenticatedAccessEnabled(undefined)).toBe(false);
+ expect(
+ resolveInstanceAuthMode({
+ allowUnauthenticated: true,
+ hasBootstrapCredential: false,
+ hasEnabledUser: false,
+ }),
+ ).toBe("disabled");
+ });
+
+ test("recognizes missing D1 bindings and unapplied migrations", () => {
+ expect(isDatabaseNotReadyError(new Error("D1_ERROR: no such table: users"))).toBe(true);
+ expect(isDatabaseNotReadyError(new TypeError("Cannot read properties of undefined (reading 'prepare')"))).toBe(true);
+ expect(isDatabaseNotReadyError(new Error("network timeout"))).toBe(false);
+ });
+});
diff --git a/tests/deployment-verify.test.ts b/tests/deployment-verify.test.ts
new file mode 100644
index 00000000..ee339cac
--- /dev/null
+++ b/tests/deployment-verify.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test } from "bun:test";
+import {
+ buildSchemaVerificationSql,
+ parseD1Rows,
+ parseSecretNames,
+ REQUIRED_TABLES,
+} from "../scripts/verify-deployment.mjs";
+
+describe("deployment verification", () => {
+ test("checks the remote schema tables required by current application code", () => {
+ const sql = buildSchemaVerificationSql();
+ for (const table of REQUIRED_TABLES) {
+ expect(sql).toContain(`'${table}'`);
+ }
+ });
+
+ test("parses Wrangler D1 JSON output", () => {
+ expect(parseD1Rows(JSON.stringify([{ results: [{ name: "users" }] }]))).toEqual([{ name: "users" }]);
+ });
+
+ test("parses current and wrapped Wrangler secret output", () => {
+ expect(parseSecretNames(JSON.stringify([{ name: "EDGE_EVER_AUTH_PASSWORD" }]))).toContain(
+ "EDGE_EVER_AUTH_PASSWORD",
+ );
+ expect(parseSecretNames(JSON.stringify({ result: [{ name: "EDGE_EVER_AUTH_PASSWORD_HASH" }] }))).toContain(
+ "EDGE_EVER_AUTH_PASSWORD_HASH",
+ );
+ });
+});
diff --git a/tests/wrangler-runner.test.ts b/tests/wrangler-runner.test.ts
new file mode 100644
index 00000000..6d3e92b7
--- /dev/null
+++ b/tests/wrangler-runner.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, test } from "bun:test";
+import {
+ buildWranglerInvocation,
+ resolveWranglerCliPath,
+ runWranglerSync,
+} from "../scripts/wrangler-runner.mjs";
+
+describe("cross-platform Wrangler runner", () => {
+ test("uses the installed JavaScript CLI instead of a platform shell shim", () => {
+ const invocation = buildWranglerInvocation(["--version"], {
+ cwd: process.cwd(),
+ runtimeExecutable: process.execPath,
+ });
+
+ expect(invocation.executable).toBe(process.execPath);
+ expect(invocation.args).toEqual([resolveWranglerCliPath(process.cwd()), "--version"]);
+ expect(invocation.args[0]).toEndWith("node_modules/wrangler/bin/wrangler.js");
+ expect(invocation.args[0]).not.toEndWith("wrangler.cmd");
+ });
+
+ test("runs the project-local Wrangler without a global installation", () => {
+ const result = runWranglerSync(["--version"], { cwd: process.cwd(), encoding: "utf8" });
+
+ expect(result.status).toBe(0);
+ expect(result.stdout).toMatch(/^\d+\.\d+\.\d+/);
+ });
+});