@insapp-dev/inslog 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +26 -0
  2. package/README.md +66 -2
  3. package/config/database.example.json +5 -0
  4. package/config/locale.example.json +3 -0
  5. package/locales/en.json +476 -0
  6. package/locales/zh-CN.json +1 -0
  7. package/next-env.d.ts +7 -0
  8. package/next.config.ts +10 -0
  9. package/package.json +62 -4
  10. package/public/apple-touch-icon.png +0 -0
  11. package/public/favicon.ico +0 -0
  12. package/public/icon-color.png +0 -0
  13. package/public/icon-color.svg +5 -0
  14. package/public/icon-dark.svg +5 -0
  15. package/public/icon.svg +5 -0
  16. package/scripts/_db.mjs +67 -0
  17. package/scripts/export-backup.mjs +104 -0
  18. package/scripts/release.sh +70 -0
  19. package/scripts/seed-demo.mjs +184 -0
  20. package/scripts/test-connection.mjs +26 -0
  21. package/src/app/api/auth/logout/route.ts +9 -0
  22. package/src/app/api/auth/passkey/add-request/route.ts +35 -0
  23. package/src/app/api/auth/passkey/login/options/route.ts +40 -0
  24. package/src/app/api/auth/passkey/login/verify/route.ts +58 -0
  25. package/src/app/api/auth/passkey/register/options/route.ts +46 -0
  26. package/src/app/api/auth/passkey/register/verify/route.ts +63 -0
  27. package/src/app/api/auth/passkey/remove-request/route.ts +44 -0
  28. package/src/app/api/auth/recovery/route.ts +45 -0
  29. package/src/app/api/auth/totp/disable/route.ts +42 -0
  30. package/src/app/api/auth/totp/enable/route.ts +75 -0
  31. package/src/app/api/auth/totp/login/route.ts +47 -0
  32. package/src/app/api/auth/totp/setup/route.ts +20 -0
  33. package/src/app/api/setup/complete/route.ts +27 -0
  34. package/src/app/api/setup/email/route.ts +41 -0
  35. package/src/app/api/upload/local/route.ts +73 -0
  36. package/src/app/api/upload/route.ts +73 -0
  37. package/src/app/api/upload/s3/route.ts +73 -0
  38. package/src/app/confirm/[token]/page.tsx +181 -0
  39. package/src/app/globals.css +952 -0
  40. package/src/app/layout.tsx +107 -0
  41. package/src/app/login/login-form.tsx +325 -0
  42. package/src/app/login/page.tsx +76 -0
  43. package/src/app/not-found.tsx +26 -0
  44. package/src/app/page.tsx +179 -0
  45. package/src/app/posts/[slug]/page.tsx +100 -0
  46. package/src/app/robots.txt/route.ts +25 -0
  47. package/src/app/rss.xml/route.ts +60 -0
  48. package/src/app/search/page.tsx +94 -0
  49. package/src/app/settings/actions.ts +92 -0
  50. package/src/app/settings/image-field.tsx +143 -0
  51. package/src/app/settings/language-actions.ts +28 -0
  52. package/src/app/settings/language-select.tsx +56 -0
  53. package/src/app/settings/page.tsx +97 -0
  54. package/src/app/settings/passkey-manager.tsx +194 -0
  55. package/src/app/settings/site-form.tsx +323 -0
  56. package/src/app/settings/theme-toggle.tsx +51 -0
  57. package/src/app/settings/totp-manager.tsx +239 -0
  58. package/src/app/setup/auth-config-panel.tsx +132 -0
  59. package/src/app/setup/config-actions.ts +90 -0
  60. package/src/app/setup/page.tsx +80 -0
  61. package/src/app/setup/secrets-actions.ts +49 -0
  62. package/src/app/setup/setup-data.ts +133 -0
  63. package/src/app/setup/setup-wizard.tsx +338 -0
  64. package/src/app/sitemap.xml/route.ts +46 -0
  65. package/src/app/uploads/[...path]/route.ts +64 -0
  66. package/src/app/write/actions.ts +85 -0
  67. package/src/app/write/page.tsx +48 -0
  68. package/src/app/write/write-client.tsx +254 -0
  69. package/src/components/BlockEditor.tsx +102 -0
  70. package/src/components/PostBody.tsx +51 -0
  71. package/src/components/SiteFooter.tsx +41 -0
  72. package/src/components/WriteFab.tsx +38 -0
  73. package/src/components/i18n-provider.tsx +22 -0
  74. package/src/components/install-hint.tsx +31 -0
  75. package/src/components/service-config-fields.tsx +110 -0
  76. package/src/lib/auth.ts +41 -0
  77. package/src/lib/change-request.ts +184 -0
  78. package/src/lib/config-keys.ts +300 -0
  79. package/src/lib/credentials.ts +171 -0
  80. package/src/lib/env-config.ts +39 -0
  81. package/src/lib/env-store.ts +72 -0
  82. package/src/lib/i18n-core.ts +27 -0
  83. package/src/lib/i18n.ts +72 -0
  84. package/src/lib/image-compress.ts +59 -0
  85. package/src/lib/mail.ts +121 -0
  86. package/src/lib/mongodb.ts +236 -0
  87. package/src/lib/passkey.ts +73 -0
  88. package/src/lib/pending.ts +142 -0
  89. package/src/lib/post-utils.ts +56 -0
  90. package/src/lib/posts.ts +283 -0
  91. package/src/lib/rate-limit.ts +91 -0
  92. package/src/lib/recovery-hints.ts +16 -0
  93. package/src/lib/safe-path.ts +0 -0
  94. package/src/lib/secret-box.ts +46 -0
  95. package/src/lib/service-config.ts +25 -0
  96. package/src/lib/service-features.ts +72 -0
  97. package/src/lib/session-constants.ts +5 -0
  98. package/src/lib/session.ts +51 -0
  99. package/src/lib/settings-file.ts +120 -0
  100. package/src/lib/settings.ts +199 -0
  101. package/src/lib/site-url.ts +15 -0
  102. package/src/lib/slug.ts +53 -0
  103. package/src/lib/storage.ts +226 -0
  104. package/src/lib/time.ts +15 -0
  105. package/src/lib/totp.ts +88 -0
  106. package/src/lib/types.ts +72 -0
  107. package/src/lib/upload-client.ts +83 -0
  108. package/src/lib/xml.ts +12 -0
  109. package/src/proxy.ts +24 -0
  110. package/tsconfig.json +41 -0
@@ -0,0 +1,323 @@
1
+ "use client";
2
+
3
+ // 站点设置:四组平铺,一个保存按钮,只提交改过的字段
4
+ import { useActionState, useEffect, useState, type ReactNode } from "react";
5
+ import type { SettingsDoc, SocialLink } from "@/lib/types";
6
+ import { saveSiteSettings, type SettingsState } from "./actions";
7
+ import ImageField from "./image-field";
8
+ import type { ClientStorageProvider } from "@/lib/upload-client";
9
+ import { useT } from "@/components/i18n-provider";
10
+
11
+ const initialState: SettingsState = { status: "idle", message: "" };
12
+
13
+ /**
14
+ * 社交链接在表单里的样子。
15
+ *
16
+ * 多一个 id 只为渲染用,不进数据库——存的是 title / url 两个字段。
17
+ * 用它做 React 的 key,删掉中间一条时节点不会错位、焦点不会跳到别的链接上。
18
+ */
19
+ type SocialRow = SocialLink & { id: string };
20
+
21
+ type Values = {
22
+ siteName: string;
23
+ description: string;
24
+ author: string;
25
+ seoTitle: string;
26
+ seoDescription: string;
27
+ seoKeywords: string;
28
+ postsPerPage: number;
29
+ footerText: string;
30
+ notifyEmail: string;
31
+ favicon: string;
32
+ ogImage: string;
33
+ social: SocialRow[];
34
+ };
35
+
36
+ let socialSeq = 0;
37
+ const nextSocialId = () => `social-${++socialSeq}`;
38
+
39
+ /**
40
+ * 把设置转成表单的值。
41
+ *
42
+ * prev 用来沿用已有的 id:位置和内容都对得上就复用,
43
+ * 否则每次渲染都换新 key,输入框会失焦。
44
+ */
45
+ function toValues(settings: SettingsDoc, prev?: Values): Values {
46
+ const social: SocialRow[] = settings.social.map((link, index) => {
47
+ const old = prev?.social[index];
48
+ if (old && old.title === link.title && old.url === link.url) return old;
49
+ return { ...link, id: nextSocialId() };
50
+ });
51
+ return {
52
+ siteName: settings.siteName,
53
+ description: settings.description,
54
+ author: settings.author,
55
+ seoTitle: settings.seoTitle,
56
+ seoDescription: settings.seoDescription,
57
+ seoKeywords: settings.seoKeywords,
58
+ postsPerPage: settings.postsPerPage,
59
+ footerText: settings.footerText,
60
+ notifyEmail: settings.notifyEmail ?? "",
61
+ favicon: settings.favicon,
62
+ ogImage: settings.ogImage,
63
+ social,
64
+ };
65
+ }
66
+
67
+ type Props = {
68
+ settings: SettingsDoc;
69
+ /** 外观组里的主题 / 界面语言控件(独立保存,不进表单) */
70
+ appearanceExtras?: ReactNode;
71
+ /** 安全组里的 Passkey / 验证器管理(各自的操作,不进表单) */
72
+ securityExtras?: ReactNode;
73
+ /** 当前图片存储方案,决定上传走哪条路 */
74
+ storageProvider: ClientStorageProvider;
75
+ };
76
+
77
+ export default function SettingsForm({
78
+ settings,
79
+ appearanceExtras,
80
+ securityExtras,
81
+ storageProvider,
82
+ }: Props) {
83
+ const t = useT();
84
+ const [state, action, pending] = useActionState(saveSiteSettings, initialState);
85
+ const initial = toValues(settings);
86
+ const [values, setValues] = useState<Values>(initial);
87
+
88
+ // 保存成功后服务端会把新的 settings 传回来(router.refresh)。
89
+ // 不同步的话 values 还是旧值,表单会一直显示「有未保存的改动」,
90
+ // 保存按钮也一直亮着,用户能反复点。
91
+ useEffect(() => {
92
+ setValues((prev) => toValues(settings, prev));
93
+ }, [settings]);
94
+
95
+ const changed = (key: keyof Values) =>
96
+ key === "social"
97
+ ? JSON.stringify(values.social.map(({ title, url }) => ({ title, url }))) !==
98
+ JSON.stringify(initial.social.map(({ title, url }) => ({ title, url })))
99
+ : values[key] !== initial[key];
100
+ const dirtyKeys = (Object.keys(initial) as (keyof Values)[]).filter(changed);
101
+ const dirty = dirtyKeys.length > 0;
102
+
103
+ const set = <K extends keyof Values>(key: K, value: Values[K]) =>
104
+ setValues((prev) => ({ ...prev, [key]: value }));
105
+
106
+ const updateLink = (index: number, key: keyof SocialLink, value: string) =>
107
+ set(
108
+ "social",
109
+ values.social.map((link, i) => (i === index ? { ...link, [key]: value } : link))
110
+ );
111
+ const addLink = () =>
112
+ set("social", [
113
+ ...values.social,
114
+ { id: nextSocialId(), title: "", url: "" },
115
+ ]);
116
+ const removeLink = (index: number) =>
117
+ set("social", values.social.filter((_, i) => i !== index));
118
+
119
+ // 这些是可编辑字段的展示名;可见控件用 _ 前缀命名,避免和下面提交的隐藏字段同名
120
+ return (
121
+ <form action={action}>
122
+ {dirtyKeys.map((key) => (
123
+ <input
124
+ key={key}
125
+ type="hidden"
126
+ name={key}
127
+ value={
128
+ key === "social"
129
+ ? JSON.stringify(
130
+ values.social.map(({ title, url }) => ({ title, url }))
131
+ )
132
+ : String(values[key])
133
+ }
134
+ />
135
+ ))}
136
+
137
+ <section className="section">
138
+ <h2 className="section-title">{t("站点信息")}</h2>
139
+ <div className="site-form">
140
+ <label className="field row gx-0 align-items-start">
141
+ <span className="field-label col-12 col-sm-2">{t("站点名")}</span>
142
+ <input
143
+ className="col-12 col-sm-10"
144
+ name="_siteName"
145
+ value={values.siteName}
146
+ onChange={(e) => set("siteName", e.target.value)}
147
+ required
148
+ />
149
+ </label>
150
+ <label className="field row gx-0 align-items-start">
151
+ <span className="field-label col-12 col-sm-2">{t("简介")}</span>
152
+ <textarea
153
+ className="col-12 col-sm-10"
154
+ name="_description"
155
+ value={values.description}
156
+ onChange={(e) => set("description", e.target.value)}
157
+ rows={2}
158
+ />
159
+ </label>
160
+ <label className="field row gx-0 align-items-start">
161
+ <span className="field-label col-12 col-sm-2">{t("作者")}</span>
162
+ <input
163
+ className="col-12 col-sm-10"
164
+ name="_author"
165
+ value={values.author}
166
+ onChange={(e) => set("author", e.target.value)}
167
+ />
168
+ </label>
169
+ <label className="field row gx-0 align-items-start">
170
+ <span className="field-label col-12 col-sm-2">{t("标题")}</span>
171
+ <input
172
+ className="col-12 col-sm-10"
173
+ name="_seoTitle"
174
+ value={values.seoTitle}
175
+ onChange={(e) => set("seoTitle", e.target.value)}
176
+ placeholder={t("留空用站点名")}
177
+ />
178
+ </label>
179
+ <label className="field row gx-0 align-items-start">
180
+ <span className="field-label col-12 col-sm-2">{t("描述")}</span>
181
+ <textarea
182
+ className="col-12 col-sm-10"
183
+ name="_seoDescription"
184
+ value={values.seoDescription}
185
+ onChange={(e) => set("seoDescription", e.target.value)}
186
+ rows={2}
187
+ placeholder={t("留空用简介")}
188
+ />
189
+ </label>
190
+ <label className="field row gx-0 align-items-start">
191
+ <span className="field-label col-12 col-sm-2">{t("关键词")}</span>
192
+ <input
193
+ className="col-12 col-sm-10"
194
+ name="_seoKeywords"
195
+ value={values.seoKeywords}
196
+ onChange={(e) => set("seoKeywords", e.target.value)}
197
+ placeholder={t("用逗号分隔")}
198
+ />
199
+ </label>
200
+ </div>
201
+ </section>
202
+
203
+ <section className="section">
204
+ <h2 className="section-title">{t("外观")}</h2>
205
+ <div className="site-form">
206
+ <ImageField
207
+ name="_favicon"
208
+ label={t("网站图标")}
209
+ value={values.favicon}
210
+ provider={storageProvider}
211
+ ratio="square"
212
+ onChange={(v) => set("favicon", v)}
213
+ placeholder={t("图片地址,留空用默认")}
214
+ />
215
+ <ImageField
216
+ name="_ogImage"
217
+ label={t("分享图")}
218
+ value={values.ogImage}
219
+ provider={storageProvider}
220
+ ratio="wide"
221
+ onChange={(v) => set("ogImage", v)}
222
+ placeholder={t("图片地址,留空用默认渐变图标")}
223
+ />
224
+ <label className="field row gx-0 align-items-start">
225
+ <span className="field-label col-12 col-sm-2">{t("每页文章数")}</span>
226
+ <input
227
+ className="col-12 col-sm-10"
228
+ name="_postsPerPage"
229
+ type="number"
230
+ min={1}
231
+ max={50}
232
+ value={values.postsPerPage}
233
+ onChange={(e) => set("postsPerPage", Number(e.target.value))}
234
+ />
235
+ </label>
236
+ <label className="field row gx-0 align-items-start">
237
+ <span className="field-label col-12 col-sm-2">{t("页脚文字")}</span>
238
+ <input
239
+ className="col-12 col-sm-10"
240
+ name="_footerText"
241
+ value={values.footerText}
242
+ onChange={(e) => set("footerText", e.target.value)}
243
+ placeholder={t("留空则显示 © 2026。填了就整段替换它。")}
244
+ />
245
+ </label>
246
+ </div>
247
+ {appearanceExtras && <div className="settings-extras">{appearanceExtras}</div>}
248
+ </section>
249
+
250
+ <section className="section">
251
+ <h2 className="section-title">{t("社交链接")}</h2>
252
+ <div className="site-form">
253
+ {values.social.map((link, index) => (
254
+ // key 用稳定的 id,不用下标:
255
+ // 下标作 key 时,删掉中间一条,React 会复用错误的 DOM 节点,
256
+ // 焦点会跳到不相干的那一条链接上。
257
+ <div className="social-row d-flex flex-wrap" key={link.id}>
258
+ <input
259
+ className="search-input"
260
+ value={link.title}
261
+ onChange={(e) => updateLink(index, "title", e.target.value)}
262
+ placeholder={t("标题")}
263
+ aria-label={t("第 {n} 条社交链接的标题", { n: index + 1 })}
264
+ />
265
+ <input
266
+ className="search-input"
267
+ value={link.url}
268
+ onChange={(e) => updateLink(index, "url", e.target.value)}
269
+ placeholder="https://..."
270
+ aria-label={t("第 {n} 条社交链接的地址", { n: index + 1 })}
271
+ />
272
+ <button
273
+ className="btn btn-outline-light btn-plain"
274
+ type="button"
275
+ onClick={() => removeLink(index)}
276
+ >
277
+ {t("删除")}
278
+ </button>
279
+ </div>
280
+ ))}
281
+ <button className="btn btn-outline-light btn-plain" type="button" onClick={addLink}>
282
+ {t("添加")}
283
+ </button>
284
+ </div>
285
+ </section>
286
+
287
+ <section className="section">
288
+ <h2 className="section-title">{t("安全")}</h2>
289
+ <div className="site-form">
290
+ <label className="field row gx-0 align-items-start">
291
+ <span className="field-label col-12 col-sm-2">{t("通知邮箱")}</span>
292
+ <input
293
+ className="col-12 col-sm-10"
294
+ name="_notifyEmail"
295
+ type="email"
296
+ value={values.notifyEmail}
297
+ onChange={(e) => set("notifyEmail", e.target.value)}
298
+ />
299
+ </label>
300
+ </div>
301
+ {securityExtras && <div className="settings-extras">{securityExtras}</div>}
302
+ </section>
303
+
304
+ <div className="form-actions d-flex align-items-center">
305
+ <button
306
+ className="btn btn-outline-light btn-plain"
307
+ type="submit"
308
+ disabled={pending || !dirty}
309
+ >
310
+ {pending ? t("保存中…") : t("保存")}
311
+ </button>
312
+ {state.message && (
313
+ <span
314
+ className={state.status === "error" ? "form-error form-msg" : "form-msg"}
315
+ role={state.status === "error" ? "alert" : "status"}
316
+ >
317
+ {state.message}
318
+ </span>
319
+ )}
320
+ </div>
321
+ </form>
322
+ );
323
+ }
@@ -0,0 +1,51 @@
1
+ "use client";
2
+
3
+ /** 外观:跟随系统 / 浅色 / 深色。选择存在 localStorage,刷新时由 layout 的内联脚本提前应用。 */
4
+ import { useEffect, useState } from "react";
5
+ import { useT } from "@/components/i18n-provider";
6
+
7
+ export default function ThemeToggle() {
8
+ const t = useT();
9
+ const OPTIONS = [
10
+ { value: "auto", label: t("跟随系统") },
11
+ { value: "light", label: t("浅色") },
12
+ { value: "dark", label: t("深色") },
13
+ ];
14
+ const [value, setValue] = useState("auto");
15
+
16
+ useEffect(() => {
17
+ try {
18
+ setValue(localStorage.getItem("inslog-theme") ?? "auto");
19
+ } catch {
20
+ setValue("auto");
21
+ }
22
+ }, []);
23
+
24
+ const choose = (next: string) => {
25
+ setValue(next);
26
+ try {
27
+ if (next === "auto") localStorage.removeItem("inslog-theme");
28
+ else localStorage.setItem("inslog-theme", next);
29
+ } catch {
30
+ // 隐私模式下 localStorage 不可用,只影响本次页面
31
+ }
32
+ if (next === "auto") delete document.documentElement.dataset.theme;
33
+ else document.documentElement.dataset.theme = next;
34
+ };
35
+
36
+ return (
37
+ <div className="tag-list d-flex flex-wrap">
38
+ {OPTIONS.map((option) => (
39
+ <button
40
+ key={option.value}
41
+ className={`visibility-option ${value === option.value ? "selected" : ""}`}
42
+ type="button"
43
+ aria-pressed={value === option.value}
44
+ onClick={() => choose(option.value)}
45
+ >
46
+ {option.label}
47
+ </button>
48
+ ))}
49
+ </div>
50
+ );
51
+ }
@@ -0,0 +1,239 @@
1
+ "use client";
2
+
3
+ /**
4
+ * 手机验证器的绑定 / 更换 / 解绑。
5
+ *
6
+ * 首次绑定:扫码 → 填一次 6 位码 → 直接生效(此时账号只有 Passkey,多一把钥匙不损失什么)
7
+ * 更换 / 解绑:验过新码后还要过邮件确认,因为这两件事会让已有的钥匙失效
8
+ */
9
+ import { useState } from "react";
10
+ import { useRouter } from "next/navigation";
11
+ import { useT } from "@/components/i18n-provider";
12
+
13
+ type Setup = { secret: string; grouped: string; qrSvg: string };
14
+
15
+ export default function TotpManager({
16
+ bound,
17
+ mailReady,
18
+ onBound,
19
+ }: {
20
+ bound: boolean;
21
+ mailReady: boolean;
22
+ onBound?: () => void;
23
+ }) {
24
+ const t = useT();
25
+ const router = useRouter();
26
+ const [setup, setSetup] = useState<Setup | null>(null);
27
+ const [code, setCode] = useState("");
28
+ const [busy, setBusy] = useState(false);
29
+ const [status, setStatus] = useState("");
30
+ const [error, setError] = useState("");
31
+
32
+ const reset = () => {
33
+ setSetup(null);
34
+ setCode("");
35
+ };
36
+
37
+ const begin = async () => {
38
+ setBusy(true);
39
+ setError("");
40
+ setStatus(t("正在生成密钥…"));
41
+ try {
42
+ const res = await fetch("/api/auth/totp/setup", { method: "POST" });
43
+ const data = await res.json();
44
+ if (!res.ok) throw new Error(data.error ?? t("无法生成密钥"));
45
+ setSetup(data as Setup);
46
+ setStatus("");
47
+ } catch (e) {
48
+ setStatus("");
49
+ setError(e instanceof Error ? e.message : t("无法生成密钥"));
50
+ } finally {
51
+ setBusy(false);
52
+ }
53
+ };
54
+
55
+ const confirmBind = async () => {
56
+ if (!setup) return;
57
+ // 位数不对就当场说清楚。以前按钮直接置灰,点了跟没点一样,
58
+ // 用户根本不知道是哪里不对。
59
+ if (code.length !== 6) {
60
+ setError(t("验证码是 6 位数字,现在只输入了 {n} 位。", { n: code.length }));
61
+ return;
62
+ }
63
+ setBusy(true);
64
+ setError("");
65
+ setStatus("");
66
+ try {
67
+ const res = await fetch("/api/auth/totp/enable", {
68
+ method: "POST",
69
+ headers: { "content-type": "application/json" },
70
+ body: JSON.stringify({ secret: setup.secret, code }),
71
+ // 请求挂住时给个说法,不然页面看起来就是没反应
72
+ signal: AbortSignal.timeout(20000),
73
+ });
74
+ const data = await res.json();
75
+ if (!res.ok) throw new Error(data.error ?? t("绑定失败"));
76
+
77
+ if (data.pending) {
78
+ reset();
79
+ setStatus(t("确认信已发出:点邮件里的链接、点一下确认,更换才会生效。"));
80
+ } else {
81
+ setStatus(t("已绑定。以后可以用这个验证器的 6 位码登录。"));
82
+ reset();
83
+ if (onBound) {
84
+ onBound();
85
+ }
86
+ // 让服务端重读绑定状态即可。整页 reload 会把下面的成功提示
87
+ // 和二维码 state 一起冲掉,看起来像「绑了又没绑」。
88
+ // 会话版本变化由 verify 接口签名的新 cookie 处理,不需要 reload。
89
+ router.refresh();
90
+ }
91
+ } catch (e) {
92
+ if (e instanceof DOMException && e.name === "TimeoutError") {
93
+ setError(t("请求超时了,服务器没在 20 秒内回应。稍后再试一次。"));
94
+ } else {
95
+ setError(e instanceof Error ? e.message : t("绑定失败"));
96
+ }
97
+ } finally {
98
+ setBusy(false);
99
+ }
100
+ };
101
+
102
+ const disable = async () => {
103
+ setBusy(true);
104
+ setError("");
105
+ setStatus("");
106
+ try {
107
+ const res = await fetch("/api/auth/totp/disable", { method: "POST" });
108
+ const data = await res.json();
109
+ if (!res.ok) throw new Error(data.error ?? t("请求失败"));
110
+ setStatus(t("确认信已发出:点邮件里的链接、点一下确认,解绑才会生效。"));
111
+ } catch (e) {
112
+ setError(e instanceof Error ? e.message : t("请求失败"));
113
+ } finally {
114
+ setBusy(false);
115
+ }
116
+ };
117
+
118
+ // 扫码绑定中
119
+ if (setup) {
120
+ return (
121
+ <div className="totp-manager">
122
+ <p className="notice">
123
+
124
+ {t("用手机上的验证器(1Password、Google Authenticator、iOS 密码 App 都行)扫这个码:")}
125
+ </p>
126
+ <div className="totp-qr" dangerouslySetInnerHTML={{ __html: setup.qrSvg }} />
127
+ <p className="notice">
128
+
129
+ {t("扫不了就把这串密钥手输进去:")}<code className="totp-secret">{setup.grouped}</code>
130
+ </p>
131
+ <p className="notice">
132
+ {t("手机上要留的必须是这一条。重新生成密钥后,旧的条目就作废了,验证码要对上这一串。")}
133
+ </p>
134
+
135
+ {/*
136
+ 这里不能用 <form>:本组件被塞进设置页的 <form action={saveSiteSettings}> 里,
137
+ 内层 form 会被浏览器丢弃,里面的 submit 按钮和回车都去提交外层表单,
138
+ 于是输验证码 / 粘贴到一半就把整页刷掉了。改用普通 div + 点击绑定。
139
+ */}
140
+ <div className="login-form totp-form d-flex flex-wrap">
141
+ <input
142
+ className="search-input"
143
+ type="text"
144
+ inputMode="numeric"
145
+ value={code}
146
+ onChange={(e) =>
147
+ // 只留数字;粘贴带空格的码也能用
148
+ setCode(e.target.value.replace(/\D/g, "").slice(0, 6))
149
+ }
150
+ onKeyDown={(e) => {
151
+ if (e.key === "Enter") {
152
+ e.preventDefault();
153
+ void confirmBind();
154
+ }
155
+ }}
156
+ placeholder={t("验证器上显示的 6 位码")}
157
+ aria-label={t("6 位验证码")}
158
+ />
159
+ <button
160
+ className="btn btn-outline-light btn-plain"
161
+ type="button"
162
+ onClick={confirmBind}
163
+ disabled={busy}
164
+ >
165
+ {bound ? t("验证并请求更换") : t("验证并绑定")}
166
+ </button>
167
+ <button
168
+ className="btn btn-outline-light btn-plain"
169
+ type="button"
170
+ onClick={reset}
171
+ disabled={busy}
172
+ >
173
+
174
+ {t("取消")}
175
+ </button>
176
+ </div>
177
+
178
+ {error && <p className="form-error">{error}</p>}
179
+ </div>
180
+ );
181
+ }
182
+
183
+ return (
184
+ <div className="totp-manager">
185
+ {bound ? (
186
+ <>
187
+ <p className="notice">{t("已经绑了一把验证器。")}</p>
188
+ <div className="tag-list d-flex flex-wrap">
189
+ <button
190
+ className="btn btn-outline-light btn-plain"
191
+ type="button"
192
+ onClick={begin}
193
+ disabled={busy || !mailReady}
194
+ >
195
+
196
+ {t("换一把")}
197
+ </button>
198
+ <button
199
+ className="btn btn-outline-light btn-plain"
200
+ type="button"
201
+ onClick={disable}
202
+ disabled={busy || !mailReady}
203
+ >
204
+
205
+ {t("解绑")}
206
+ </button>
207
+ </div>
208
+ {!mailReady && (
209
+ <p className="notice">
210
+
211
+ {t("换绑 / 解绑需邮件确认。请先配置服务端发信,并在站点设置里填好通知邮箱。")}
212
+ </p>
213
+ )}
214
+ </>
215
+ ) : (
216
+ <>
217
+ <p className="notice">{t("还没有绑定验证器。")}</p>
218
+ <button
219
+ className="btn btn-outline-light btn-plain"
220
+ type="button"
221
+ onClick={begin}
222
+ disabled={busy || !mailReady}
223
+ >
224
+
225
+ {t("绑定验证器")}
226
+ </button>
227
+ {!mailReady && (
228
+ <p className="notice">
229
+ {t("绑定验证器需要邮件确认。请先配置服务端发信,并在站点设置里填好通知邮箱。")}
230
+ </p>
231
+ )}
232
+ </>
233
+ )}
234
+
235
+ {status && <p className="notice">{status}</p>}
236
+ {error && <p className="form-error">{error}</p>}
237
+ </div>
238
+ );
239
+ }