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 password login
tianmae2f9b6675c1d
diff --git a/.env.example b/.env.exampleindex 13741d4a..fe94f937 100644--- a/.env.example+++ b/.env.example@@ -3,5 +3,15 @@# Cloudflare Deploy Button 会读取 `.env.example` / `.dev.vars.example`,并把其中# 每一个变量当作需要用户在部署向导里填写的 Worker Secret。#-# 当前阶段 EdgeEver 不需要任何 Worker 运行时密钥,所以这里故意不声明变量。-# 本地 CLI / Wrangler 部署所需的账号、资源和 Token 模板请看 `.env.local.example`。+# 登录账号。未配置密码 hash 且 D1 中没有用户时,EdgeEver 会保持无登录保护,+# 避免一键部署后因为缺少密码变量而锁死实例。+EDGE_EVER_AUTH_USERNAME=admin++# 登录密码的 PBKDF2-SHA256 hash。+# 生成命令:`bun run auth:hash -- <你的密码>`+EDGE_EVER_AUTH_PASSWORD_HASH=++# Web session 有效期,单位:天。服务端会限制在 1-90 天。+EDGE_EVER_SESSION_TTL_DAYS=30++# 本地 CLI / Wrangler 部署所需的 Cloudflare 账号、资源和 Token 模板请看 `.env.local.example`。diff --git a/.env.local.example b/.env.local.exampleindex 92b6c26f..767c77fc 100644--- a/.env.local.example+++ b/.env.local.example@@ -32,6 +32,19 @@ EDGE_EVER_R2_BUCKET_NAME=edgeever-resources# 可选;用于 Wrangler preview/dev 场景隔离测试附件。EDGE_EVER_R2_PREVIEW_BUCKET_NAME=edgeever-resources-preview+# 登录账号。+EDGE_EVER_AUTH_USERNAME=admin++# 登录密码的 PBKDF2-SHA256 hash。+# 生成命令:`bun run auth:hash -- <你的密码>`+# 也可以用 `EDGE_EVER_TIANMA_AUTH_PASSWORD_HASH` / `EDGE_EVER_DEMO_AUTH_PASSWORD_HASH`+# 给多实例配置不同密码。+# 线上部署时建议把对应 hash 配成 Cloudflare Worker Secret。+EDGE_EVER_AUTH_PASSWORD_HASH=++# Web session 有效期,单位:天。服务端会限制在 1-90 天。+EDGE_EVER_SESSION_TTL_DAYS=30+# 前端访问 API 的基础地址。# 本地开发默认指向 Wrangler dev:`bun run dev:api`VITE_API_BASE_URL=http://127.0.0.1:8787diff --git a/README.md b/README.mdindex 12d99758..ed42763a 100644--- a/README.md+++ b/README.md@@ -53,6 +53,7 @@ EdgeEver 要做的就是这个版本:经典的信息架构,现代的边缘- **无限级嵌套笔记本**:通过 `parent_id` 支持多级目录树。- **Markdown 友好的富文本编辑**:TipTap/ProseMirror JSON 作为权威编辑器格式,Markdown 作为 Agent、CLI 和导出格式。- **PWA 响应式布局**:桌面端三栏,移动端自动折叠为单栏。+- **单用户账号密码登录**:自部署实例可通过 PBKDF2-SHA256 密码 hash 启用网页登录,session 存入 D1。- **多选合并笔记**:选中多条笔记后创建一条合并后的新笔记,用 Markdown 分割线连接内容,原笔记软删除,资源引用重新指向新笔记。- **Headless 能力**:REST、MCP 和 CLI 共享同一套核心服务。- **资源模型**:图片和附件存入 R2,D1 保存资源元数据和笔记关联关系。@@ -77,7 +78,7 @@ edgeever/- `/api/v1/*` 提供 REST API。- `/mcp` 提供远程 MCP Streamable HTTP 入口。- Workers Assets 从 `apps/web/dist` 托管构建后的 SPA。-- D1 存储笔记本、笔记元数据、正文记录、搜索索引、Token、修订记录和审计事件。+- D1 存储笔记本、笔记元数据、正文记录、搜索索引、用户、Session、Token、修订记录和审计事件。- R2 存储图片和附件。## 技术栈@@ -129,7 +130,7 @@ content_text 全文搜索、摘要、embedding 使用的纯文本公开仓库可以直接通过上方 **Deploy to Cloudflare** 按钮进入部署向导。Cloudflare 会读取 `wrangler.toml`,为 D1/R2 等绑定创建或配置所需资源,并使用 `package.json` 中的 `deploy` 脚本执行 D1 migration 与 Worker 部署。你仍需要登录 Cloudflare、授权 GitHub/GitLab 连接,并确认仓库名、Worker 名和资源名;如果你的账号里已经存在同名 Worker 或仓库,把项目名改成一个唯一名称即可。-`.env.example` 在 Deploy Button 语义下是 Worker Secret 模板。当前 EdgeEver 不需要运行时密钥,所以一键部署时不需要填写 `CLOUDFLARE_ACCOUNT_ID` 或 `CLOUDFLARE_API_TOKEN`。+`.env.example` 在 Deploy Button 语义下是 Worker Secret 模板。EdgeEver 的登录密码使用 PBKDF2-SHA256 hash,不要把明文密码放进仓库或 wrangler 配置。如果你更喜欢 CLI 部署,先创建本机环境文件:@@ -148,10 +149,26 @@ bunx wrangler r2 bucket create edgeever-resources把 D1 创建命令返回的 `database_id` 填入本机 `.env.local` 的 `EDGE_EVER_D1_DATABASE_ID`。部署脚本会在运行时生成临时 `.wrangler.generated.toml`,不需要把个人 D1 ID 提交到公开仓库。+生成登录密码 hash,并填入 `.env.local` 或 Cloudflare Build Variables:++```sh+bun run auth:hash -- <你的密码>+```++```text+EDGE_EVER_AUTH_USERNAME=admin+EDGE_EVER_AUTH_PASSWORD_HASH=<上一步生成的 hash>+EDGE_EVER_SESSION_TTL_DAYS=30+```++线上部署时,`EDGE_EVER_AUTH_PASSWORD_HASH` 应作为 Cloudflare Worker Secret 配置;`EDGE_EVER_AUTH_USERNAME` 和 `EDGE_EVER_SESSION_TTL_DAYS` 可以作为普通 Build Variables/vars。未配置 `EDGE_EVER_AUTH_PASSWORD_HASH` 且 D1 中没有用户时,EdgeEver 会保持无登录保护,避免一键部署后因为缺少密码变量而锁死实例。一旦配置密码 hash,首次成功登录会在 D1 中创建用户,之后浏览器通过 HttpOnly cookie session 访问 REST API。+如果你把 Worker 连接到 GitHub 并开启 Cloudflare 自动构建,需要在 Cloudflare 的 Build Variables 里设置:```textEDGE_EVER_D1_DATABASE_ID=<你的 D1 database_id>+EDGE_EVER_AUTH_USERNAME=admin+EDGE_EVER_AUTH_PASSWORD_HASH=<你的密码 hash,建议作为 Worker Secret>```## 多实例部署@@ -170,11 +187,13 @@ EDGE_EVER_TIANMA_WORKER_NAME=edgeever-tianmaEDGE_EVER_TIANMA_CUSTOM_DOMAIN=tianma.edgeever.orgEDGE_EVER_TIANMA_D1_DATABASE_ID=<tianma D1 database_id>EDGE_EVER_TIANMA_R2_BUCKET_NAME=edgeever-tianma-resources+EDGE_EVER_TIANMA_AUTH_USERNAME=<tianma 登录账号>EDGE_EVER_DEMO_WORKER_NAME=edgeever-demoEDGE_EVER_DEMO_ROUTE_PATTERN=demo.edgeever.org/*EDGE_EVER_DEMO_D1_DATABASE_ID=<demo D1 database_id>EDGE_EVER_DEMO_R2_BUCKET_NAME=edgeever-demo-resources+EDGE_EVER_DEMO_AUTH_USERNAME=<demo 登录账号>````EDGE_EVER_CUSTOM_DOMAIN` 会通过 Workers Custom Domain 绑定域名;`EDGE_EVER_ROUTE_PATTERN` 会生成 Worker Route,适合配合 DNS CNAME 使用。当前推荐 `tianma` 用 Custom Domain,`demo` 用 Route Pattern,两个实例彼此独立。@@ -201,6 +220,9 @@ EDGE_EVER_ROUTE_PATTERN=<实例 route,例如 demo.edgeever.org/*>EDGE_EVER_D1_DATABASE_ID=<实例 D1 database_id>EDGE_EVER_R2_BUCKET_NAME=<实例 R2 bucket>EDGE_EVER_R2_PREVIEW_BUCKET_NAME=<实例 R2 preview bucket>+EDGE_EVER_AUTH_USERNAME=admin+EDGE_EVER_AUTH_PASSWORD_HASH=<实例密码 hash,建议作为 Worker Secret>+EDGE_EVER_SESSION_TTL_DAYS=30```应用本地迁移:@@ -254,9 +276,9 @@ bun run build当前已经具备第一条可运行纵向切片:- Bun monorepo 基础工程。-- D1 初始 schema:支持嵌套笔记本、笔记正文拆表、FTS5 搜索、资源、修订、审计、软删除和合并字段。-- Hono REST API:笔记本列表/创建/更新/删除,笔记列表/创建/读取/更新/删除,搜索,多选合并。-- Vite React PWA:桌面三栏布局,移动端单栏切换,递归笔记本树,笔记卡片流,TipTap 编辑器,标签和本地草稿备份。+- D1 schema:支持嵌套笔记本、用户、Session、笔记正文拆表、FTS5 搜索、资源、修订、审计、软删除和合并字段。+- Hono REST API:账号密码登录、cookie session 鉴权、笔记本列表/创建/更新/删除,笔记列表/创建/读取/更新/删除,搜索,多选合并。+- Vite React PWA:登录页、桌面三栏布局,移动端单栏切换,递归笔记本树,笔记卡片流,TipTap 编辑器,标签和本地草稿备份。- 基础 `wrangler.toml`:配置 Workers Assets、D1、R2 和 `/api/*`、`/mcp` Worker-first 路由。后续阶段会继续补完整 MCP Server、CLI、资源上传、认证 Token、导入导出和更完整的 Markdown 双向转换。diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 1238a1b7..abee5ba9 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -3,6 +3,7 @@ import {docToMarkdown,docToText,emptyDoc,+ LoginSchema,markdownToDoc,MemoCreateSchema,MemoUpdateSchema,@@ -18,11 +19,25 @@ import {import { zValidator } from "@hono/zod-validator";import type { Context } from "hono";import { Hono } from "hono";+import { deleteCookie, getCookie, setCookie } from "hono/cookie";import { cors } from "hono/cors";type Bindings = {DB: D1Database;RESOURCES: R2Bucket;+ EDGE_EVER_AUTH_USERNAME?: string;+ EDGE_EVER_AUTH_PASSWORD_HASH?: string;+ EDGE_EVER_SESSION_TTL_DAYS?: string;+};++type AuthContext = {+ kind: "user" | "agent";+ actorType: "user" | "agent";+ actorId: string | null;+ username: string;+ displayName: string | null;+ sessionId?: string;+ tokenId?: string;};type NotebookRow = {@@ -60,7 +75,40 @@ type MemoDetailRow = MemoSummaryRow & {content_hash: string;};-const app = new Hono<{ Bindings: Bindings }>();+type UserRow = {+ id: string;+ username: string;+ password_hash: string;+ display_name: string | null;+ is_disabled: number;+};++type SessionRow = {+ id: string;+ user_id: string;+ username: string;+ display_name: string | null;+ expires_at: string;+};++type ApiTokenRow = {+ id: string;+ name: string;+ scopes_json: string;+ expires_at: string | null;+};++type AppContext = Context<{ Bindings: Bindings; Variables: { auth: AuthContext } }>;++const SESSION_COOKIE = "edgeever_session";+const PASSWORD_HASH_ALGORITHM = "pbkdf2-sha256";+const PASSWORD_HASH_ITERATIONS = 210_000;+const PASSWORD_HASH_BYTES = 32;+const PASSWORD_SALT_BYTES = 16;+const SESSION_TOKEN_BYTES = 32;+const DEFAULT_SESSION_TTL_DAYS = 30;++const app = new Hono<{ Bindings: Bindings; Variables: { auth: AuthContext } }>();app.use("/api/*",@@ -68,6 +116,7 @@ app.use(origin: ["http://127.0.0.1:5173", "http://localhost:5173"],allowHeaders: ["Content-Type", "Authorization"],allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],+ credentials: true,}));@@ -79,6 +128,111 @@ app.get("/api/health", (c) =>}));+app.get("/api/v1/auth/session", async (c) => {+ const authRequired = await isAuthRequired(c.env);++ if (!authRequired) {+ return c.json({+ authRequired: false,+ authenticated: true,+ user: {+ id: "local",+ username: "owner",+ displayName: "Owner",+ },+ });+ }++ const auth = await authenticateRequest(c, false);++ return c.json({+ authRequired: true,+ authenticated: Boolean(auth && auth.kind === "user"),+ user:+ auth && auth.kind === "user"+ ? {+ id: auth.actorId,+ username: auth.username,+ displayName: auth.displayName,+ }+ : null,+ });+});++app.post("/api/v1/auth/login", zValidator("json", LoginSchema), async (c) => {+ const input = c.req.valid("json");+ const user = await verifyLogin(c.env, input.username, input.password);++ if (!user) {+ return unauthorized(c, "Username or password is incorrect.");+ }++ const session = await createSession(c, user);+ setSessionCookie(c, session.token, session.maxAge);++ await c.env.DB.batch([+ c.env.DB.prepare(`UPDATE users SET last_login_at = ?, updated_at = ? WHERE id = ?`).bind(+ isoNow(),+ isoNow(),+ user.id+ ),+ auditStatement(c.env.DB, "user", user.id, "auth.login", "session", session.id, {+ username: user.username,+ }),+ ]);++ return c.json({+ authRequired: true,+ authenticated: true,+ user: {+ id: user.id,+ username: user.username,+ displayName: user.display_name,+ },+ });+});++app.post("/api/v1/auth/logout", async (c) => {+ const token = getCookie(c, SESSION_COOKIE);++ if (token) {+ await revokeSession(c.env.DB, token);+ }++ deleteCookie(c, SESSION_COOKIE, { path: "/" });+ return c.json({ ok: true });+});++app.use("/api/v1/*", async (c, next) => {+ if (c.req.path.startsWith("/api/v1/auth/")) {+ await next();+ return;+ }++ const authRequired = await isAuthRequired(c.env);++ if (!authRequired) {+ c.set("auth", {+ kind: "user",+ actorType: "user",+ actorId: null,+ username: "owner",+ displayName: "Owner",+ });+ await next();+ return;+ }++ const auth = await authenticateRequest(c, true);++ if (!auth) {+ return unauthorized(c, "Authentication required.");+ }++ c.set("auth", auth);+ await next();+});+app.get("/api/v1/notebooks", async (c) => {const rows = await c.env.DB.prepare(`SELECT id, parent_id, name, slug, icon, color, sort_order, created_at, updated_at@@ -92,6 +246,7 @@ app.get("/api/v1/notebooks", async (c) => {app.post("/api/v1/notebooks", zValidator("json", NotebookCreateSchema), async (c) => {const input = c.req.valid("json");+ const actor = getAuditActor(c);const id = createId("nb");const now = isoNow();@@ -103,7 +258,7 @@ app.post("/api/v1/notebooks", zValidator("json", NotebookCreateSchema), async (c.run();const notebook = await getNotebook(c.env.DB, id);- await audit(c.env.DB, "user", null, "notebook.create", "notebook", id, { name: input.name });+ await audit(c.env.DB, actor.actorType, actor.actorId, "notebook.create", "notebook", id, { name: input.name });return c.json({ notebook }, 201);});@@ -111,6 +266,7 @@ app.post("/api/v1/notebooks", zValidator("json", NotebookCreateSchema), async (capp.patch("/api/v1/notebooks/:id", zValidator("json", NotebookUpdateSchema), async (c) => {const id = c.req.param("id");const input = c.req.valid("json");+ const actor = getAuditActor(c);const current = await getNotebook(c.env.DB, id);if (!current) {@@ -130,12 +286,13 @@ app.patch("/api/v1/notebooks/:id", zValidator("json", NotebookUpdateSchema), asy.bind(nextName, slugify(nextName), nextParentId ?? null, nextSortOrder, now, id).run();- await audit(c.env.DB, "user", null, "notebook.update", "notebook", id, input);+ await audit(c.env.DB, actor.actorType, actor.actorId, "notebook.update", "notebook", id, input);return c.json({ notebook: await getNotebook(c.env.DB, id) });});app.delete("/api/v1/notebooks/:id", async (c) => {const id = c.req.param("id");+ const actor = getAuditActor(c);const now = isoNow();await c.env.DB.prepare(@@ -146,7 +303,7 @@ app.delete("/api/v1/notebooks/:id", async (c) => {.bind(now, now, id).run();- await audit(c.env.DB, "user", null, "notebook.delete", "notebook", id, {});+ await audit(c.env.DB, actor.actorType, actor.actorId, "notebook.delete", "notebook", id, {});return c.json({ ok: true });});@@ -196,6 +353,8 @@ app.get("/api/v1/memos", async (c) => {app.post("/api/v1/memos", zValidator("json", MemoCreateSchema), async (c) => {const input = c.req.valid("json");+ const actor = getAuditActor(c);+ const actorLabel = getActorLabel(c);const tags = normalizeTags(input.tags);const contentMarkdown = input.contentMarkdown ?? "";const contentJson = markdownToDoc(contentMarkdown);@@ -210,8 +369,8 @@ app.post("/api/v1/memos", zValidator("json", MemoCreateSchema), async (c) => {c.env.DB.prepare(`INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, created_by, updated_by, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, 'user', 'user', ?, ?)`- ).bind(id, input.notebookId, title, excerpt, JSON.stringify(tags), now, now),+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`+ ).bind(id, input.notebookId, title, excerpt, JSON.stringify(tags), actorLabel, actorLabel, now, now),c.env.DB.prepare(`INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_text, content_hash, revision, created_at, updated_at@@ -221,7 +380,9 @@ app.post("/api/v1/memos", zValidator("json", MemoCreateSchema), async (c) => {`INSERT INTO memos_fts (memo_id, title, content_text, tags)VALUES (?, ?, ?, ?)`).bind(id, title, contentText, tags.join(" ")),- auditStatement(c.env.DB, "user", null, "memo.create", "memo", id, { notebookId: input.notebookId }),+ auditStatement(c.env.DB, actor.actorType, actor.actorId, "memo.create", "memo", id, {+ notebookId: input.notebookId,+ }),]);return c.json({ memo: await getMemoDetail(c.env.DB, id) }, 201);@@ -240,6 +401,8 @@ app.get("/api/v1/memos/:id", async (c) => {app.patch("/api/v1/memos/:id", zValidator("json", MemoUpdateSchema), async (c) => {const id = c.req.param("id");const input = c.req.valid("json");+ const actor = getAuditActor(c);+ const actorLabel = getActorLabel(c);const current = await getMemoDetailRow(c.env.DB, id);if (!current) {@@ -283,7 +446,7 @@ app.patch("/api/v1/memos/:id", zValidator("json", MemoUpdateSchema), async (c) =c.env.DB.prepare(`INSERT INTO memo_revisions (id, memo_id, revision, title, content_json, content_markdown, content_hash, created_by, created_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, 'user', ?)`+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(createId("rev"),id,@@ -292,13 +455,14 @@ app.patch("/api/v1/memos/:id", zValidator("json", MemoUpdateSchema), async (c) =current.content_json,current.content_markdown,current.content_hash,+ actorLabel,now),c.env.DB.prepare(`UPDATE memos- SET notebook_id = ?, title = ?, excerpt = ?, tags_json = ?, updated_by = 'user', updated_at = ?+ SET notebook_id = ?, title = ?, excerpt = ?, tags_json = ?, updated_by = ?, updated_at = ?WHERE id = ? AND is_deleted = 0`- ).bind(notebookId, title, excerpt, JSON.stringify(tags), now, id),+ ).bind(notebookId, title, excerpt, JSON.stringify(tags), actorLabel, now, id),c.env.DB.prepare(`UPDATE memo_contentsSET content_json = ?, content_markdown = ?, content_text = ?, content_hash = ?,@@ -310,7 +474,9 @@ app.patch("/api/v1/memos/:id", zValidator("json", MemoUpdateSchema), async (c) =`INSERT INTO memos_fts (memo_id, title, content_text, tags)VALUES (?, ?, ?, ?)`).bind(id, title, contentText, tags.join(" ")),- auditStatement(c.env.DB, "user", null, "memo.update", "memo", id, { revision: nextRevision }),+ auditStatement(c.env.DB, actor.actorType, actor.actorId, "memo.update", "memo", id, {+ revision: nextRevision,+ }),]);return c.json({ memo: await getMemoDetail(c.env.DB, id) });@@ -318,6 +484,7 @@ app.patch("/api/v1/memos/:id", zValidator("json", MemoUpdateSchema), async (c) =app.delete("/api/v1/memos/:id", async (c) => {const id = c.req.param("id");+ const actor = getAuditActor(c);const now = isoNow();await c.env.DB.batch([@@ -326,7 +493,7 @@ app.delete("/api/v1/memos/:id", async (c) => {SET is_deleted = 1, deleted_at = ?, updated_at = ?WHERE id = ? AND is_deleted = 0`).bind(now, now, id),- auditStatement(c.env.DB, "user", null, "memo.delete", "memo", id, {}),+ auditStatement(c.env.DB, actor.actorType, actor.actorId, "memo.delete", "memo", id, {}),]);return c.json({ ok: true });@@ -334,6 +501,8 @@ app.delete("/api/v1/memos/:id", async (c) => {app.post("/api/v1/memos/merge", zValidator("json", MergeMemosSchema), async (c) => {const input = c.req.valid("json");+ const actor = getAuditActor(c);+ const actorLabel = getActorLabel(c);const uniqueMemoIds = Array.from(new Set(input.memoIds));const placeholders = uniqueMemoIds.map(() => "?").join(", ");const rows = await c.env.DB.prepare(@@ -379,7 +548,7 @@ app.post("/api/v1/memos/merge", zValidator("json", MergeMemosSchema), async (c)`INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, source_memo_ids, merge_source_count,created_by, updated_by, created_at, updated_at- ) VALUES (?, ?, ?, ?, ?, ?, ?, 'user', 'user', ?, ?)`+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).bind(newMemoId,notebookId,@@ -388,6 +557,8 @@ app.post("/api/v1/memos/merge", zValidator("json", MergeMemosSchema), async (c)JSON.stringify(tags),JSON.stringify(uniqueMemoIds),uniqueMemoIds.length,+ actorLabel,+ actorLabel,now,now),@@ -412,7 +583,7 @@ app.post("/api/v1/memos/merge", zValidator("json", MergeMemosSchema), async (c)updated_at = ?WHERE memo_id IN (${placeholders})`).bind(newMemoId, now, ...uniqueMemoIds),- auditStatement(c.env.DB, "user", null, "memo.merge", "memo", newMemoId, {+ auditStatement(c.env.DB, actor.actorType, actor.actorId, "memo.merge", "memo", newMemoId, {sourceMemoIds: uniqueMemoIds,}),]);@@ -443,6 +614,312 @@ app.notFound((c) =>export default app;+const isAuthRequired = async (env: Bindings) => {+ if (env.EDGE_EVER_AUTH_PASSWORD_HASH?.trim()) {+ return true;+ }++ const user = await env.DB.prepare(`SELECT id FROM users WHERE is_disabled = 0 LIMIT 1`).first<{ id: string }>();+ return Boolean(user);+};++const verifyLogin = async (env: Bindings, username: string, password: string): Promise<UserRow | null> => {+ const normalizedUsername = username.trim();+ const existingUser = await getUserByUsername(env.DB, normalizedUsername);++ if (existingUser) {+ return (await verifyPassword(password, existingUser.password_hash)) ? existingUser : null;+ }++ const configuredHash = env.EDGE_EVER_AUTH_PASSWORD_HASH?.trim();++ if (!configuredHash) {+ return null;+ }++ const configuredUsername = env.EDGE_EVER_AUTH_USERNAME?.trim() || "admin";++ if (normalizedUsername !== configuredUsername || !(await verifyPassword(password, configuredHash))) {+ return null;+ }++ const now = isoNow();+ const userId = createId("usr");+ const passwordHash = await hashPassword(password);++ await env.DB.prepare(+ `INSERT OR IGNORE INTO users (id, username, password_hash, display_name, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?)`+ )+ .bind(userId, normalizedUsername, passwordHash, normalizedUsername, now, now)+ .run();++ return getUserByUsername(env.DB, normalizedUsername);+};++const getUserByUsername = async (db: D1Database, username: string) =>+ db+ .prepare(+ `SELECT id, username, password_hash, display_name, is_disabled+ FROM users+ WHERE username = ? AND is_disabled = 0`+ )+ .bind(username)+ .first<UserRow>();++const createSession = async (c: AppContext, user: UserRow) => {+ const token = randomToken(SESSION_TOKEN_BYTES);+ const id = createId("sess");+ const now = isoNow();+ const maxAge = getSessionMaxAge(c.env);+ const expiresAt = new Date(Date.now() + maxAge * 1000).toISOString();+ const ip = c.req.header("CF-Connecting-IP");+ const ipHash = ip ? await sha256(ip) : null;++ await c.env.DB.prepare(+ `INSERT INTO sessions (+ id, user_id, token_hash, user_agent, ip_hash, expires_at, created_at, last_seen_at+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`+ )+ .bind(+ id,+ user.id,+ await sha256(token),+ c.req.header("User-Agent") ?? null,+ ipHash,+ expiresAt,+ now,+ now+ )+ .run();++ return { id, token, maxAge };+};++const setSessionCookie = (c: AppContext, token: string, maxAge: number) => {+ setCookie(c, SESSION_COOKIE, token, {+ httpOnly: true,+ secure: new URL(c.req.url).protocol === "https:",+ sameSite: "Lax",+ path: "/",+ maxAge,+ });+};++const revokeSession = async (db: D1Database, token: string) => {+ await db+ .prepare(`UPDATE sessions SET revoked_at = ? WHERE token_hash = ? AND revoked_at IS NULL`)+ .bind(isoNow(), await sha256(token))+ .run();+};++const authenticateRequest = async (c: AppContext, touch: boolean): Promise<AuthContext | null> => {+ const bearerAuth = await authenticateBearerToken(c, touch);++ if (bearerAuth) {+ return bearerAuth;+ }++ return authenticateSession(c, touch);+};++const authenticateBearerToken = async (c: AppContext, touch: boolean): Promise<AuthContext | null> => {+ const token = getBearerToken(c);++ if (!token) {+ return null;+ }++ const row = await c.env.DB.prepare(+ `SELECT id, name, scopes_json, expires_at+ FROM api_tokens+ WHERE token_hash = ?+ AND is_revoked = 0+ AND (expires_at IS NULL OR expires_at > ?)`+ )+ .bind(await sha256(token), isoNow())+ .first<ApiTokenRow>();++ if (!row) {+ return null;+ }++ if (touch) {+ await c.env.DB.prepare(`UPDATE api_tokens SET last_used_at = ? WHERE id = ?`).bind(isoNow(), row.id).run();+ }++ return {+ kind: "agent",+ actorType: "agent",+ actorId: row.id,+ username: row.name,+ displayName: row.name,+ tokenId: row.id,+ };+};++const authenticateSession = async (c: AppContext, touch: boolean): Promise<AuthContext | null> => {+ const token = getCookie(c, SESSION_COOKIE);++ if (!token) {+ return null;+ }++ const row = await c.env.DB.prepare(+ `SELECT s.id, s.user_id, u.username, u.display_name, s.expires_at+ FROM sessions s+ INNER JOIN users u ON u.id = s.user_id+ WHERE s.token_hash = ?+ AND s.revoked_at IS NULL+ AND s.expires_at > ?+ AND u.is_disabled = 0`+ )+ .bind(await sha256(token), isoNow())+ .first<SessionRow>();++ if (!row) {+ return null;+ }++ if (touch) {+ await c.env.DB.prepare(`UPDATE sessions SET last_seen_at = ? WHERE id = ?`).bind(isoNow(), row.id).run();+ }++ return {+ kind: "user",+ actorType: "user",+ actorId: row.user_id,+ username: row.username,+ displayName: row.display_name,+ sessionId: row.id,+ };+};++const getBearerToken = (c: AppContext) => {+ const authorization = c.req.header("Authorization");++ if (!authorization) {+ return null;+ }++ const [scheme, token] = authorization.split(/\s+/, 2);+ return scheme.toLowerCase() === "bearer" && token ? token : null;+};++const getAuditActor = (c: AppContext) => {+ const auth = c.get("auth");++ return {+ actorType: auth?.actorType ?? "user",+ actorId: auth?.actorId ?? null,+ };+};++const getActorLabel = (c: AppContext) => {+ const auth = c.get("auth");+ return auth?.actorId ? `${auth.actorType}:${auth.actorId}` : auth?.username ?? "user";+};++const getSessionMaxAge = (env: Bindings) => {+ const days = clampNumber(Number(env.EDGE_EVER_SESSION_TTL_DAYS ?? DEFAULT_SESSION_TTL_DAYS), 1, 90);+ return days * 24 * 60 * 60;+};++const hashPassword = async (password: string) => {+ const salt = crypto.getRandomValues(new Uint8Array(PASSWORD_SALT_BYTES));+ const hash = await derivePasswordHash(password, salt, PASSWORD_HASH_ITERATIONS);++ return [+ PASSWORD_HASH_ALGORITHM,+ PASSWORD_HASH_ITERATIONS,+ base64UrlEncode(salt),+ base64UrlEncode(hash),+ ].join("$");+};++const verifyPassword = async (password: string, passwordHash: string) => {+ const [algorithm, iterationsRaw, saltRaw, hashRaw] = passwordHash.split("$");+ const iterations = Number(iterationsRaw);++ if (+ algorithm !== PASSWORD_HASH_ALGORITHM ||+ !Number.isInteger(iterations) ||+ iterations < 100_000 ||+ !saltRaw ||+ !hashRaw+ ) {+ return false;+ }++ try {+ const expected = base64UrlDecode(hashRaw);+ const salt = base64UrlDecode(saltRaw);+ const actual = await derivePasswordHash(password, salt, iterations);++ return timingSafeEqual(actual, expected);+ } catch {+ return false;+ }+};++const derivePasswordHash = async (password: string, salt: Uint8Array, iterations: number) => {+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(password), "PBKDF2", false, [+ "deriveBits",+ ]);+ const saltBuffer = salt.buffer.slice(salt.byteOffset, salt.byteOffset + salt.byteLength) as ArrayBuffer;+ const bits = await crypto.subtle.deriveBits(+ {+ name: "PBKDF2",+ hash: "SHA-256",+ salt: saltBuffer,+ iterations,+ },+ key,+ PASSWORD_HASH_BYTES * 8+ );++ return new Uint8Array(bits);+};++const randomToken = (bytes: number) => {+ const token = crypto.getRandomValues(new Uint8Array(bytes));+ return base64UrlEncode(token);+};++const base64UrlEncode = (bytes: Uint8Array) => {+ let binary = "";++ for (const byte of bytes) {+ binary += String.fromCharCode(byte);+ }++ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");+};++const base64UrlDecode = (value: string) => {+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");+ const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=");+ const binary = atob(padded);+ const bytes = new Uint8Array(binary.length);++ for (let index = 0; index < binary.length; index += 1) {+ bytes[index] = binary.charCodeAt(index);+ }++ return bytes;+};++const timingSafeEqual = (left: Uint8Array, right: Uint8Array) => {+ const length = Math.max(left.length, right.length);+ let diff = left.length ^ right.length;++ for (let index = 0; index < length; index += 1) {+ diff |= (left[index % left.length] ?? 0) ^ (right[index % right.length] ?? 0);+ }++ return diff === 0;+};+const mapNotebook = (row: NotebookRow): Notebook => ({id: row.id,parentId: row.parent_id,@@ -602,3 +1079,14 @@ const notFound = (c: Context, message: string) =>},404);++const unauthorized = (c: Context, message: string) =>+ c.json(+ {+ error: {+ code: "unauthorized",+ message,+ },+ },+ 401+ );diff --git a/apps/web/src/app/App.tsx b/apps/web/src/app/App.tsxindex 37182904..0f28d451 100644--- a/apps/web/src/app/App.tsx+++ b/apps/web/src/app/App.tsx@@ -1,4 +1,4 @@-import type { MemoDetail, MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";+import type { AuthSession, AuthUser, MemoDetail, MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";import Placeholder from "@tiptap/extension-placeholder";import { EditorContent, useEditor } from "@tiptap/react";import StarterKit from "@tiptap/starter-kit";@@ -12,6 +12,8 @@ import {Folder,Inbox,LayoutList,+ LockKeyhole,+ LogOut,Merge,MoreHorizontal,PanelLeft,@@ -22,7 +24,7 @@ import {Tags,Trash2,} from "lucide-react";-import { useEffect, useMemo, useRef, useState, type MouseEvent } from "react";+import { useEffect, useMemo, useRef, useState, type FormEvent, type MouseEvent } from "react";import { api } from "@/lib/api";import { localDb } from "@/lib/local-db";import { buildNotebookTree, cn, formatDateTime, parseTagsText, type NotebookNode } from "@/lib/utils";@@ -31,6 +33,83 @@ import { Button } from "@/components/ui/button";type Pane = "notebooks" | "memos" | "editor";export const App = () => {+ const queryClient = useQueryClient();+ const sessionQuery = useQuery({+ queryKey: ["auth", "session"],+ queryFn: () => api.getSession(),+ retry: false,+ });+ const loginMutation = useMutation({+ mutationFn: api.login,+ onSuccess: (session) => {+ queryClient.clear();+ queryClient.setQueryData(["auth", "session"], session);+ },+ });+ const logoutMutation = useMutation({+ mutationFn: api.logout,+ onSuccess: () => {+ queryClient.clear();+ queryClient.setQueryData<AuthSession>(["auth", "session"], {+ authRequired: true,+ authenticated: false,+ user: null,+ });+ },+ });++ useEffect(() => {+ const handleUnauthorized = () => {+ const current = queryClient.getQueryData<AuthSession>(["auth", "session"]);+ queryClient.clear();+ queryClient.setQueryData<AuthSession>(["auth", "session"], {+ authRequired: current?.authRequired ?? true,+ authenticated: false,+ user: null,+ });+ };++ window.addEventListener("edgeever:unauthorized", handleUnauthorized);+ return () => window.removeEventListener("edgeever:unauthorized", handleUnauthorized);+ }, [queryClient]);++ if (sessionQuery.isLoading) {+ return <AuthLoadingScreen />;+ }++ const session = sessionQuery.data;++ if (!session?.authenticated) {+ return (+ <LoginScreen+ error={loginMutation.error instanceof Error ? loginMutation.error.message : null}+ isSubmitting={loginMutation.isPending}+ onSubmit={(payload) => loginMutation.mutate(payload)}+ />+ );+ }++ return (+ <WorkspaceApp+ authRequired={session.authRequired}+ isLoggingOut={logoutMutation.isPending}+ user={session.user}+ onLogout={() => logoutMutation.mutate()}+ />+ );+};++const WorkspaceApp = ({+ authRequired,+ user,+ isLoggingOut,+ onLogout,+}: {+ authRequired: boolean;+ user: AuthUser | null;+ isLoggingOut: boolean;+ onLogout: () => void;+}) => {const queryClient = useQueryClient();const [activePane, setActivePane] = useState<Pane>("memos");const [selectedNotebookId, setSelectedNotebookId] = useState<string | null>(null);@@ -186,6 +265,8 @@ export const App = () => {)}><NotebookPane+ authRequired={authRequired}+ user={user}notebooks={notebooks}selectedNotebookId={selectedNotebookId}isLoading={notebooksQuery.isLoading}@@ -196,6 +277,8 @@ export const App = () => {}}onCreateNotebook={handleCreateNotebook}onBackToList={() => setActivePane("memos")}+ onLogout={onLogout}+ isLoggingOut={isLoggingOut}/></aside>@@ -252,6 +335,83 @@ export const App = () => {);};+const AuthLoadingScreen = () => (+ <div className="flex h-[100dvh] items-center justify-center bg-emerald-50 text-sm font-medium text-emerald-900">+ EdgeEver+ </div>+);++const LoginScreen = ({+ error,+ isSubmitting,+ onSubmit,+}: {+ error: string | null;+ isSubmitting: boolean;+ onSubmit: (payload: { username: string; password: string }) => void;+}) => {+ const [username, setUsername] = useState("admin");+ const [password, setPassword] = useState("");++ const handleSubmit = (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();++ if (!username.trim() || !password) {+ return;+ }++ onSubmit({ username: username.trim(), password });+ };++ return (+ <main className="flex h-[100dvh] items-center justify-center bg-emerald-50 px-4 py-8 text-slate-950">+ <section className="w-full max-w-[380px] rounded-md border border-emerald-100 bg-white p-5 shadow-panel">+ <div className="mb-5 flex items-center gap-3">+ <div className="flex h-10 w-10 items-center justify-center rounded-md border border-emerald-200 bg-emerald-100 text-emerald-900">+ <LockKeyhole className="h-5 w-5" />+ </div>+ <div className="min-w-0">+ <h1 className="text-lg font-semibold leading-tight tracking-normal">登录 EdgeEver</h1>+ <p className="mt-1 text-sm text-slate-500">自托管笔记工作区</p>+ </div>+ </div>++ <form className="space-y-4" onSubmit={handleSubmit}>+ <label className="block">+ <span className="mb-1.5 block text-sm font-medium text-slate-700">账号</span>+ <input+ autoComplete="username"+ className="h-10 w-full rounded-md border border-emerald-100 bg-emerald-50/50 px-3 text-sm outline-none transition focus:border-emerald-300 focus:bg-white"+ value={username}+ onChange={(event) => setUsername(event.target.value)}+ />+ </label>++ <label className="block">+ <span className="mb-1.5 block text-sm font-medium text-slate-700">密码</span>+ <input+ autoComplete="current-password"+ className="h-10 w-full rounded-md border border-emerald-100 bg-emerald-50/50 px-3 text-sm outline-none transition focus:border-emerald-300 focus:bg-white"+ type="password"+ value={password}+ onChange={(event) => setPassword(event.target.value)}+ />+ </label>++ {error ? (+ <div className="rounded-md border border-rose-100 bg-rose-50 px-3 py-2 text-sm text-rose-700">{error}</div>+ ) : null}++ <Button className="w-full justify-center" size="md" type="submit" variant="solid" disabled={isSubmitting}>+ <LockKeyhole className="h-4 w-4" />+ {isSubmitting ? "登录中" : "登录"}+ </Button>+ </form>+ </section>+ </main>+ );+};+const toggleMemoSelection = (current: Set<string>, memoId: string) => {const next = new Set(current);@@ -265,19 +425,27 @@ const toggleMemoSelection = (current: Set<string>, memoId: string) => {};const NotebookPane = ({+ authRequired,+ user,notebooks,selectedNotebookId,isLoading,onSelect,onCreateNotebook,onBackToList,+ onLogout,+ isLoggingOut,}: {+ authRequired: boolean;+ user: AuthUser | null;notebooks: Notebook[];selectedNotebookId: string | null;isLoading: boolean;onSelect: (notebookId: string) => void;onCreateNotebook: (parentId?: string | null) => void;onBackToList: () => void;+ onLogout: () => void;+ isLoggingOut: boolean;}) => {const tree = useMemo(() => buildNotebookTree(notebooks), [notebooks]);@@ -287,7 +455,7 @@ const NotebookPane = ({<div><div className="text-base font-semibold tracking-normal lg:hidden">笔记本</div><div className="hidden text-base font-semibold tracking-normal lg:block">EdgeEver</div>- <div className="text-xs text-slate-500">Cloudflare-native notes</div>+ <div className="text-xs text-slate-500">{user?.username ?? "Cloudflare-native notes"}</div></div><div className="flex items-center gap-1"><Button className="lg:hidden" size="icon" variant="ghost" title="返回笔记列表" onClick={onBackToList}>@@ -324,7 +492,7 @@ const NotebookPane = ({</div><footer className="border-t border-emerald-100 px-4 pb-[max(0.75rem,env(safe-area-inset-bottom))] pt-3">- <div className="grid grid-cols-3 gap-2">+ <div className={cn("grid gap-2", authRequired ? "grid-cols-4" : "grid-cols-3")}><Button size="icon" variant="ghost" title="标签"><Tags className="h-4 w-4" /></Button>@@ -334,6 +502,11 @@ const NotebookPane = ({<Button size="icon" variant="ghost" title="设置"><MoreHorizontal className="h-4 w-4" /></Button>+ {authRequired ? (+ <Button size="icon" variant="ghost" title="退出登录" onClick={onLogout} disabled={isLoggingOut}>+ <LogOut className="h-4 w-4" />+ </Button>+ ) : null}</div></footer></div>diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex cf79dba1..a9aa0e8a 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -1,4 +1,4 @@-import type { MemoDetail, MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";+import type { AuthSession, MemoDetail, MemoSummary, Notebook, TiptapDoc } from "@edgeever/shared";type ListNotebooksResponse = {notebooks: Notebook[];@@ -16,8 +16,21 @@ type NotebookResponse = {notebook: Notebook;};+export class ApiRequestError extends Error {+ status: number;+ code?: string;++ constructor(message: string, status: number, code?: string) {+ super(message);+ this.name = "ApiRequestError";+ this.status = status;+ this.code = code;+ }+}+const request = async <T>(path: string, init?: RequestInit): Promise<T> => {const response = await fetch(path, {+ credentials: "include",...init,headers: {"Content-Type": "application/json",@@ -27,18 +40,37 @@ const request = async <T>(path: string, init?: RequestInit): Promise<T> => {if (!response.ok) {const body = await response.json().catch(() => null);+ const error = body && typeof body === "object" && "error" in body ? (body as { error?: { code?: string; message?: string } }).error : undefined;const message =body && typeof body === "object" && "error" in body- ? (body as { error?: { message?: string } }).error?.message+ ? error?.message: response.statusText;- throw new Error(message || "Request failed");+ if (response.status === 401) {+ window.dispatchEvent(new CustomEvent("edgeever:unauthorized"));+ }++ throw new ApiRequestError(message || "Request failed", response.status, error?.code);}return response.json() as Promise<T>;};export const api = {+ getSession: () => request<AuthSession>("/api/v1/auth/session"),++ login: (payload: { username: string; password: string }) =>+ request<AuthSession>("/api/v1/auth/login", {+ method: "POST",+ body: JSON.stringify(payload),+ }),++ logout: () =>+ request<{ ok: true }>("/api/v1/auth/logout", {+ method: "POST",+ body: JSON.stringify({}),+ }),+listNotebooks: () => request<ListNotebooksResponse>("/api/v1/notebooks"),createNotebook: (payload: { name: string; parentId?: string | null }) =>diff --git a/migrations/0002_auth.sql b/migrations/0002_auth.sqlnew file mode 100644index 00000000..0a0c6255--- /dev/null+++ b/migrations/0002_auth.sql@@ -0,0 +1,34 @@+CREATE TABLE users (+ id TEXT PRIMARY KEY,+ username TEXT NOT NULL UNIQUE,+ password_hash TEXT NOT NULL,+ display_name TEXT,+ is_disabled INTEGER NOT NULL DEFAULT 0 CHECK (is_disabled IN (0, 1)),+ last_login_at TEXT,+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),+ updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))+);++CREATE INDEX idx_users_username+ ON users(username, is_disabled);++CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ user_id TEXT NOT NULL,+ token_hash TEXT NOT NULL UNIQUE,+ user_agent TEXT,+ ip_hash TEXT,+ expires_at TEXT NOT NULL,+ revoked_at TEXT,+ created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),+ last_seen_at TEXT,+ FOREIGN KEY (user_id) REFERENCES users(id)+ ON UPDATE CASCADE+ ON DELETE CASCADE+);++CREATE INDEX idx_sessions_token_hash+ ON sessions(token_hash, revoked_at, expires_at);++CREATE INDEX idx_sessions_user+ ON sessions(user_id, expires_at DESC);diff --git a/package.json b/package.jsonindex 4eea4cac..3993899c 100644--- a/package.json+++ b/package.json@@ -9,7 +9,7 @@],"scripts": {"dev": "concurrently -k -n api,web -c cyan,magenta \"bun run dev:api\" \"bun run dev:web\"",- "dev:api": "wrangler dev --local --port 8787",+ "dev:api": "bun scripts/run-wrangler.mjs dev --local --port 8787","dev:web": "vite --config apps/web/vite.config.ts --host 127.0.0.1 --port 5173","build": "bun run build:web","build:web": "vite build --config apps/web/vite.config.ts",@@ -17,6 +17,7 @@"typecheck": "tsc -p tsconfig.json --noEmit","db:migrate:local": "bun scripts/run-wrangler.mjs d1 migrations apply DB --local","db:migrate:remote": "bun scripts/run-wrangler.mjs d1 migrations apply DB --remote",+ "auth:hash": "bun scripts/hash-password.mjs","deploy": "bun run build && bun run db:migrate:remote && bun scripts/run-wrangler.mjs deploy","deploy:tianma": "EDGE_EVER_INSTANCE=tianma bun run deploy","deploy:demo": "EDGE_EVER_INSTANCE=demo bun run deploy",diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.tsindex 1db557b1..be432be3 100644--- a/packages/shared/src/schemas.ts+++ b/packages/shared/src/schemas.ts@@ -33,8 +33,14 @@ export const MergeMemosSchema = z.object({title: z.string().trim().max(160).optional(),});+export const LoginSchema = z.object({+ username: z.string().trim().min(1).max(80),+ password: z.string().min(1).max(512),+});+export type NotebookCreateInput = z.infer<typeof NotebookCreateSchema>;export type NotebookUpdateInput = z.infer<typeof NotebookUpdateSchema>;export type MemoCreateInput = z.infer<typeof MemoCreateSchema>;export type MemoUpdateInput = z.infer<typeof MemoUpdateSchema>;export type MergeMemosInput = z.infer<typeof MergeMemosSchema>;+export type LoginInput = z.infer<typeof LoginSchema>;diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex 4cdbd90b..fbbb84c2 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -34,6 +34,18 @@ export type MemoDetail = MemoSummary & {mergedIntoMemoId: string | null;};+export type AuthUser = {+ id: string;+ username: string;+ displayName: string | null;+};++export type AuthSession = {+ authRequired: boolean;+ authenticated: boolean;+ user: AuthUser | null;+};+export type ApiError = {error: {code: string;diff --git a/scripts/hash-password.mjs b/scripts/hash-password.mjsnew file mode 100644index 00000000..3aa7035c--- /dev/null+++ b/scripts/hash-password.mjs@@ -0,0 +1,24 @@+import { pbkdf2Sync, randomBytes } from "node:crypto";++const PASSWORD_HASH_ALGORITHM = "pbkdf2-sha256";+const PASSWORD_HASH_ITERATIONS = 210_000;+const PASSWORD_HASH_BYTES = 32;+const PASSWORD_SALT_BYTES = 16;++const password = process.argv.slice(2).join(" ") || process.env.EDGE_EVER_PASSWORD;++if (!password) {+ console.error("Usage: bun run auth:hash -- <password>");+ console.error("Or: EDGE_EVER_PASSWORD=<password> bun run auth:hash");+ process.exit(1);+}++const base64UrlEncode = (buffer) =>+ buffer.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");++const salt = randomBytes(PASSWORD_SALT_BYTES);+const hash = pbkdf2Sync(password, salt, PASSWORD_HASH_ITERATIONS, PASSWORD_HASH_BYTES, "sha256");++console.log(+ [PASSWORD_HASH_ALGORITHM, PASSWORD_HASH_ITERATIONS, base64UrlEncode(salt), base64UrlEncode(hash)].join("$")+);diff --git a/scripts/run-wrangler.mjs b/scripts/run-wrangler.mjsindex 7068c429..65089fa5 100644--- a/scripts/run-wrangler.mjs+++ b/scripts/run-wrangler.mjs@@ -68,6 +68,8 @@ const replaceTomlValue = (source, key, value) => {return source.replace(pattern, `$1${value}$2`);};+const tomlString = (value) => JSON.stringify(value);+const envValue = (name) => {const scopedName = instanceKey ? `EDGE_EVER_${instanceKey}_${name}` : undefined;return (scopedName ? process.env[scopedName] : undefined)?.trim()@@ -112,6 +114,23 @@ config = replaceTomlValue(envValue("R2_PREVIEW_BUCKET_NAME"),);+const runtimeVars = {+ EDGE_EVER_AUTH_USERNAME: envValue("AUTH_USERNAME"),+ EDGE_EVER_SESSION_TTL_DAYS: envValue("SESSION_TTL_DAYS"),+};+const runtimeVarLines = Object.entries(runtimeVars)+ .filter(([, value]) => Boolean(value))+ .map(([key, value]) => `${key} = ${tomlString(value)}`);++if (runtimeVarLines.length > 0) {+ changed = true;+ config = `${config.trimEnd()}++[vars]+${runtimeVarLines.join("\n")}+`;+}+const customDomain = envValue("CUSTOM_DOMAIN");const routePattern = envValue("ROUTE_PATTERN") || customDomain;if (routePattern) {