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
Add password change flow
yoma2b1dd0d6b534
diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex 26cdd443..739e93b7 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -5,6 +5,7 @@ import {docToText,emptyDoc,ApiTokenCreateSchema,+ ChangePasswordSchema,DeleteMemosSchema,LoginSchema,markdownToDoc,@@ -445,6 +446,45 @@ app.post("/api/v1/auth/login", zValidator("json", LoginSchema), async (c) => {});});+app.post("/api/v1/auth/change-password", zValidator("json", ChangePasswordSchema), async (c) => {+ const auth = await authenticateSession(c, true);++ if (!auth || auth.kind !== "user" || !auth.actorId || !auth.sessionId) {+ return unauthorized(c, "An interactive user session is required.");+ }++ const input = c.req.valid("json");+ const user = await c.env.DB.prepare(+ `SELECT id, username, password_hash, display_name, is_disabled+ FROM users+ WHERE id = ? AND is_disabled = 0`+ )+ .bind(auth.actorId)+ .first<UserRow>();++ if (!user || !(await verifyPassword(input.currentPassword, user.password_hash))) {+ return apiError(c, "invalid_current_password", "Current password is incorrect.", 400);+ }++ const now = isoNow();+ const passwordHash = await hashPassword(input.newPassword);++ await c.env.DB.batch([+ c.env.DB.prepare(`UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?`).bind(+ passwordHash,+ now,+ user.id+ ),+ c.env.DB.prepare(+ `UPDATE sessions SET revoked_at = ?+ WHERE user_id = ? AND id != ? AND revoked_at IS NULL`+ ).bind(now, user.id, auth.sessionId),+ auditStatement(c.env.DB, "user", user.id, "auth.password_change", "user", user.id, {}),+ ]);++ return c.json({ ok: true });+});+app.post("/api/v1/auth/logout", async (c) => {const token = getCookie(c, SESSION_COOKIE) ?? getBearerToken(c);diff --git a/apps/web/src/components/SettingsPane.tsx b/apps/web/src/components/SettingsPane.tsxindex f0a14be8..29a5e5f5 100644--- a/apps/web/src/components/SettingsPane.tsx+++ b/apps/web/src/components/SettingsPane.tsx@@ -7,6 +7,7 @@ import { EvernoteImportGuideCard } from "./settings/EvernoteImportGuideCard";import { McpConfigCard } from "./settings/McpConfigCard";import { PreferenceCard } from "./settings/PreferenceCard";import { PwaInstallCard } from "./settings/PwaInstallCard";+import { PasswordCard } from "./settings/PasswordCard";import { SessionCard } from "./settings/SessionCard";import { SystemInfoCard } from "./settings/SystemInfoCard";@@ -67,6 +68,7 @@ export const SettingsPane = ({shortcutSettings={shortcutSettings}onShortcutSettingsChange={onShortcutSettingsChange}/>+ <PasswordCard authRequired={authRequired} /><PwaInstallCard /><AdvancedPlayCard /><EvernoteImportGuideCard onShowGuide={onShowGuide} />diff --git a/apps/web/src/components/settings/PasswordCard.tsx b/apps/web/src/components/settings/PasswordCard.tsxnew file mode 100644index 00000000..4d00b655--- /dev/null+++ b/apps/web/src/components/settings/PasswordCard.tsx@@ -0,0 +1,116 @@+import { useState, type FormEvent } from "react";+import { useTranslation } from "react-i18next";+import { KeyRound } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";+import { Input } from "@/components/ui/input";+import { ApiRequestError, api } from "@/lib/api";++interface PasswordCardProps {+ authRequired: boolean;+}++export const PasswordCard = ({ authRequired }: PasswordCardProps) => {+ const { t } = useTranslation();+ const [currentPassword, setCurrentPassword] = useState("");+ const [newPassword, setNewPassword] = useState("");+ const [confirmPassword, setConfirmPassword] = useState("");+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [feedback, setFeedback] = useState<{ type: "success" | "error"; message: string } | null>(null);++ if (!authRequired) {+ return null;+ }++ const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ setFeedback(null);++ if (newPassword.length < 8) {+ setFeedback({ type: "error", message: t("password.newPasswordTooShort") });+ return;+ }++ if (newPassword !== confirmPassword) {+ setFeedback({ type: "error", message: t("password.passwordMismatch") });+ return;+ }++ setIsSubmitting(true);++ try {+ await api.changePassword({ currentPassword, newPassword, confirmPassword });+ setCurrentPassword("");+ setNewPassword("");+ setConfirmPassword("");+ setFeedback({ type: "success", message: t("password.changed") });+ } catch (error) {+ const message =+ error instanceof ApiRequestError && error.code === "invalid_current_password"+ ? t("password.currentPasswordIncorrect")+ : t("password.changeFailed");+ setFeedback({ type: "error", message });+ } finally {+ setIsSubmitting(false);+ }+ };++ return (+ <Card className="w-full min-w-0 overflow-hidden shadow-none">+ <CardHeader className="p-4">+ <CardTitle className="flex items-center gap-2 text-sm">+ <KeyRound className="h-4 w-4 text-emerald-700" />+ {t("password.title")}+ </CardTitle>+ <CardDescription>{t("password.description")}</CardDescription>+ </CardHeader>+ <CardContent className="p-4 pt-0">+ <form className="grid gap-3" onSubmit={handleSubmit}>+ <label className="grid gap-1.5 text-sm font-medium text-slate-700">+ {t("password.currentPassword")}+ <Input+ type="password"+ autoComplete="current-password"+ value={currentPassword}+ onChange={(event) => setCurrentPassword(event.target.value)}+ required+ />+ </label>+ <label className="grid gap-1.5 text-sm font-medium text-slate-700">+ {t("password.newPassword")}+ <Input+ type="password"+ autoComplete="new-password"+ minLength={8}+ value={newPassword}+ onChange={(event) => setNewPassword(event.target.value)}+ required+ />+ </label>+ <label className="grid gap-1.5 text-sm font-medium text-slate-700">+ {t("password.confirmPassword")}+ <Input+ type="password"+ autoComplete="new-password"+ minLength={8}+ value={confirmPassword}+ onChange={(event) => setConfirmPassword(event.target.value)}+ required+ />+ </label>+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">+ <p+ className={feedback?.type === "error" ? "text-xs font-medium text-rose-600" : "text-xs font-medium text-emerald-700"}+ role={feedback ? "status" : undefined}+ >+ {feedback?.message}+ </p>+ <Button className="w-full bg-emerald-600 text-white hover:bg-emerald-700 sm:w-auto" type="submit" disabled={isSubmitting}>+ {isSubmitting ? t("password.changing") : t("password.change")}+ </Button>+ </div>+ </form>+ </CardContent>+ </Card>+ );+};diff --git a/apps/web/src/i18n/resources/en-US.ts b/apps/web/src/i18n/resources/en-US.tsindex 092fee36..0c00cf18 100644--- a/apps/web/src/i18n/resources/en-US.ts+++ b/apps/web/src/i18n/resources/en-US.ts@@ -498,6 +498,20 @@ export const enUS = {loggingOut: "Signing out...",logout: "Sign out",},+ password: {+ title: "Change password",+ description: "Your current device stays signed in; other sessions will be signed out.",+ currentPassword: "Current password",+ newPassword: "New password",+ confirmPassword: "Confirm new password",+ change: "Change password",+ changing: "Changing...",+ changed: "Password changed successfully.",+ currentPasswordIncorrect: "The current password is incorrect.",+ passwordMismatch: "The new passwords do not match.",+ newPasswordTooShort: "The new password must be at least 8 characters.",+ changeFailed: "Unable to change the password. Please try again.",+ },mcp: {createdTitle: "API Token created",copyToken: "Copy token",diff --git a/apps/web/src/i18n/resources/zh-CN.ts b/apps/web/src/i18n/resources/zh-CN.tsindex 88728097..33f07de0 100644--- a/apps/web/src/i18n/resources/zh-CN.ts+++ b/apps/web/src/i18n/resources/zh-CN.ts@@ -498,6 +498,20 @@ export const zhCN = {loggingOut: "安全退出中...",logout: "退出登录",},+ password: {+ title: "修改密码",+ description: "修改后会保留当前设备登录,并退出其他设备上的登录会话。",+ currentPassword: "当前密码",+ newPassword: "新密码",+ confirmPassword: "确认新密码",+ change: "修改密码",+ changing: "修改中...",+ changed: "密码已修改成功。",+ currentPasswordIncorrect: "当前密码不正确。",+ passwordMismatch: "两次输入的新密码不一致。",+ newPasswordTooShort: "新密码至少需要 8 个字符。",+ changeFailed: "密码修改失败,请稍后重试。",+ },mcp: {createdTitle: "API Token 已成功生成",copyToken: "复制 Token",diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.tsindex abefb7e5..e5f0e831 100644--- a/apps/web/src/lib/api.ts+++ b/apps/web/src/lib/api.ts@@ -107,6 +107,12 @@ export const api = {body: JSON.stringify(payload),}),+ changePassword: (payload: { currentPassword: string; newPassword: string; confirmPassword: string }) =>+ request<{ ok: true }>("/api/v1/auth/change-password", {+ method: "POST",+ body: JSON.stringify(payload),+ }),+logout: () =>request<{ ok: true }>("/api/v1/auth/logout", {method: "POST",diff --git a/docs/openapi.json b/docs/openapi.jsonindex c1e3a368..5908fa2d 100644--- a/docs/openapi.json+++ b/docs/openapi.json@@ -109,6 +109,39 @@}}},+ "/api/v1/auth/change-password": {+ "post": {+ "summary": "Change the current user's password",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChangePasswordInput"+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "Password changed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/Ok"+ }+ }+ }+ },+ "400": {+ "$ref": "#/components/responses/Error"+ },+ "401": {+ "$ref": "#/components/responses/Error"+ }+ }+ }+ },"/api/v1/auth/logout": {"post": {"summary": "Revoke interactive session",@@ -1091,6 +1124,27 @@},"required": ["username", "password"]},+ "ChangePasswordInput": {+ "type": "object",+ "properties": {+ "currentPassword": {+ "type": "string",+ "minLength": 1,+ "maxLength": 512+ },+ "newPassword": {+ "type": "string",+ "minLength": 8,+ "maxLength": 512+ },+ "confirmPassword": {+ "type": "string",+ "minLength": 8,+ "maxLength": 512+ }+ },+ "required": ["currentPassword", "newPassword", "confirmPassword"]+ },"Notebook": {"type": "object","properties": {diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.tsindex de599e15..6661fbe6 100644--- a/packages/shared/src/schemas.ts+++ b/packages/shared/src/schemas.ts@@ -56,6 +56,17 @@ export const LoginSchema = z.object({password: z.string().min(1).max(512),});+export const ChangePasswordSchema = z+ .object({+ currentPassword: z.string().min(1).max(512),+ newPassword: z.string().min(8).max(512),+ confirmPassword: z.string().min(8).max(512),+ })+ .refine((input) => input.newPassword === input.confirmPassword, {+ message: "New passwords do not match.",+ path: ["confirmPassword"],+ });+export const ApiTokenCreateSchema = z.object({name: z.string().trim().min(1).max(80),scopes: z.array(z.string().trim().min(1).max(80)).min(1).max(32),@@ -74,5 +85,6 @@ export type MoveMemosInput = z.infer<typeof MoveMemosSchema>;export type DeleteMemosInput = z.infer<typeof DeleteMemosSchema>;export type MergeMemosInput = z.infer<typeof MergeMemosSchema>;export type LoginInput = z.infer<typeof LoginSchema>;+export type ChangePasswordInput = z.infer<typeof ChangePasswordSchema>;export type ApiTokenCreateInput = z.infer<typeof ApiTokenCreateSchema>;export type TagRenameInput = z.infer<typeof TagRenameSchema>;