@insapp-dev/inslog 0.0.0-stage → 0.1.1

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 +70 -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,35 @@
1
+ // 申请绑定新 Passkey:不立刻给挑战,先发确认邮件
2
+ import { NextResponse } from "next/server";
3
+ import { isLoggedIn } from "@/lib/auth";
4
+ import { passkeyAddAllowed } from "@/lib/credentials";
5
+ import { clientKey } from "@/lib/rate-limit";
6
+ import { mailReady, requestPasskeyChange } from "@/lib/change-request";
7
+ import { getT } from "@/lib/i18n";
8
+ import { getEnvValue } from "@/lib/env-config";
9
+
10
+ export async function POST(req: Request) {
11
+ const t = await getT();
12
+ if (!(await isLoggedIn())) {
13
+ return NextResponse.json({ error: t("请先登录") }, { status: 401 });
14
+ }
15
+ if (await passkeyAddAllowed()) {
16
+ return NextResponse.json({ ok: true, alreadyAuthorized: true });
17
+ }
18
+ if (!(await mailReady())) {
19
+ return NextResponse.json(
20
+ { error: t("还没配好邮件确认,暂时不能新增 Passkey") },
21
+ { status: 503 }
22
+ );
23
+ }
24
+
25
+ const result = await requestPasskeyChange({
26
+ action: "add",
27
+ linkOrigin: getEnvValue("ORIGIN") || new URL(req.url).origin,
28
+ ip: clientKey(req),
29
+ ua: req.headers.get("user-agent") ?? "",
30
+ });
31
+ if ("error" in result) {
32
+ return NextResponse.json({ error: result.error }, { status: 400 });
33
+ }
34
+ return NextResponse.json({ ok: true, pending: true });
35
+ }
@@ -0,0 +1,40 @@
1
+ // Passkey 登录第一步:给出挑战
2
+ import { NextResponse } from "next/server";
3
+ import { cookies } from "next/headers";
4
+ import { generateAuthenticationOptions } from "@simplewebauthn/server";
5
+ import type { AuthenticatorTransportFuture } from "@simplewebauthn/server";
6
+ import { listPasskeys, rpConfig } from "@/lib/passkey";
7
+ import { CHALLENGE_COOKIE, COOKIE_OPTIONS } from "@/lib/session";
8
+ import { getT } from "@/lib/i18n";
9
+
10
+ export async function GET(req: Request) {
11
+ const t = await getT();
12
+ const { rpID } = rpConfig(req);
13
+ const passkeys = await listPasskeys();
14
+
15
+ if (passkeys.length === 0) {
16
+ return NextResponse.json(
17
+ { error: t("还没有绑定 Passkey,请先用验证器登录并在设置里添加") },
18
+ { status: 400 }
19
+ );
20
+ }
21
+
22
+ const options = await generateAuthenticationOptions({
23
+ rpID,
24
+ allowCredentials: passkeys.map((p) => ({
25
+ id: p.credentialId,
26
+ transports: p.transports as AuthenticatorTransportFuture[] | undefined,
27
+ })),
28
+ userVerification: "preferred",
29
+ // 默认 60 秒对「找一下钥匙串 / 拿手机碰一下」偏紧,放宽到 2 分钟
30
+ timeout: 120000,
31
+ });
32
+
33
+ // 挑战 5 分钟内有效,存在 httpOnly cookie 里
34
+ (await cookies()).set(CHALLENGE_COOKIE, options.challenge, {
35
+ ...COOKIE_OPTIONS,
36
+ maxAge: 300,
37
+ });
38
+
39
+ return NextResponse.json(options);
40
+ }
@@ -0,0 +1,58 @@
1
+ // Passkey 登录第二步:校验签名
2
+ import { NextResponse } from "next/server";
3
+ import { cookies } from "next/headers";
4
+ import { verifyAuthenticationResponse } from "@simplewebauthn/server";
5
+ import type { AuthenticationResponseJSON, AuthenticatorTransportFuture } from "@simplewebauthn/server";
6
+ import { findPasskey, fromBase64Url, rpConfig, touchPasskey } from "@/lib/passkey";
7
+ import { startSession } from "@/lib/auth";
8
+ import { CHALLENGE_COOKIE } from "@/lib/session";
9
+ import { getT } from "@/lib/i18n";
10
+
11
+ export async function POST(req: Request) {
12
+ const t = await getT();
13
+ const jar = await cookies();
14
+ const expectedChallenge = jar.get(CHALLENGE_COOKIE)?.value;
15
+ if (!expectedChallenge) {
16
+ return NextResponse.json({ error: t("验证已过期,请重新登录") }, { status: 400 });
17
+ }
18
+
19
+ const body = (await req.json().catch(() => ({}))) as {
20
+ response?: AuthenticationResponseJSON;
21
+ };
22
+ if (!body.response) {
23
+ return NextResponse.json({ error: t("缺少认证数据") }, { status: 400 });
24
+ }
25
+
26
+ const passkey = await findPasskey(body.response.id);
27
+ if (!passkey) {
28
+ return NextResponse.json({ error: t("没有找到这把 Passkey") }, { status: 404 });
29
+ }
30
+
31
+ const { rpID, origin } = rpConfig(req);
32
+
33
+ try {
34
+ const verification = await verifyAuthenticationResponse({
35
+ response: body.response,
36
+ expectedChallenge,
37
+ expectedOrigin: origin,
38
+ expectedRPID: rpID,
39
+ credential: {
40
+ id: passkey.credentialId,
41
+ publicKey: fromBase64Url(passkey.publicKey),
42
+ counter: passkey.counter,
43
+ transports: passkey.transports as AuthenticatorTransportFuture[] | undefined,
44
+ },
45
+ });
46
+
47
+ if (!verification.verified) {
48
+ return NextResponse.json({ error: t("验证失败") }, { status: 401 });
49
+ }
50
+
51
+ await touchPasskey(passkey.credentialId, verification.authenticationInfo.newCounter);
52
+ jar.delete(CHALLENGE_COOKIE);
53
+ await startSession();
54
+ return NextResponse.json({ ok: true });
55
+ } catch {
56
+ return NextResponse.json({ error: t("验证失败,请重试") }, { status: 400 });
57
+ }
58
+ }
@@ -0,0 +1,46 @@
1
+ // 注册新的 Passkey(需先登录):给出注册挑战
2
+ import { NextResponse } from "next/server";
3
+ import { cookies } from "next/headers";
4
+ import { generateRegistrationOptions } from "@simplewebauthn/server";
5
+ import { listPasskeys, rpConfig } from "@/lib/passkey";
6
+ import { isLoggedIn } from "@/lib/auth";
7
+ import { passkeyAddAllowed } from "@/lib/credentials";
8
+ import { CHALLENGE_COOKIE, COOKIE_OPTIONS } from "@/lib/session";
9
+ import { getT } from "@/lib/i18n";
10
+
11
+ export async function POST(req: Request) {
12
+ const t = await getT();
13
+ if (!(await isLoggedIn())) {
14
+ return NextResponse.json({ error: t("请先登录") }, { status: 401 });
15
+ }
16
+ // 新增 Passkey 要过邮件确认:确认页开一个 10 分钟窗口,这里检查它
17
+ if (!(await passkeyAddAllowed())) {
18
+ return NextResponse.json(
19
+ { error: t("请先到设置页申请绑定,点确认邮件里的链接后再回来完成") },
20
+ { status: 403 }
21
+ );
22
+ }
23
+
24
+ const { rpID } = rpConfig(req);
25
+ const passkeys = await listPasskeys();
26
+
27
+ const options = await generateRegistrationOptions({
28
+ rpName: "inslog",
29
+ rpID,
30
+ userName: "owner",
31
+ userDisplayName: t("站长"),
32
+ attestationType: "none",
33
+ excludeCredentials: passkeys.map((p) => ({ id: p.credentialId })),
34
+ authenticatorSelection: {
35
+ residentKey: "preferred",
36
+ userVerification: "preferred",
37
+ },
38
+ });
39
+
40
+ (await cookies()).set(CHALLENGE_COOKIE, options.challenge, {
41
+ ...COOKIE_OPTIONS,
42
+ maxAge: 300,
43
+ });
44
+
45
+ return NextResponse.json(options);
46
+ }
@@ -0,0 +1,63 @@
1
+ // 注册新的 Passkey:校验注册结果并入库
2
+ import { NextResponse } from "next/server";
3
+ import { cookies } from "next/headers";
4
+ import { verifyRegistrationResponse } from "@simplewebauthn/server";
5
+ import type { AuthenticatorTransportFuture, RegistrationResponseJSON } from "@simplewebauthn/server";
6
+ import { addPasskey, listPasskeys, rpConfig, toBase64Url } from "@/lib/passkey";
7
+ import { isLoggedIn } from "@/lib/auth";
8
+ import { clearPasskeyAddAuthorization, passkeyAddAllowed } from "@/lib/credentials";
9
+ import { CHALLENGE_COOKIE } from "@/lib/session";
10
+ import { getT } from "@/lib/i18n";
11
+
12
+ export async function POST(req: Request) {
13
+ const t = await getT();
14
+ if (!(await isLoggedIn())) {
15
+ return NextResponse.json({ error: t("请先登录") }, { status: 401 });
16
+ }
17
+ if (!(await passkeyAddAllowed())) {
18
+ return NextResponse.json({ error: t("授权已过期,请重新申请") }, { status: 403 });
19
+ }
20
+
21
+ const jar = await cookies();
22
+ const expectedChallenge = jar.get(CHALLENGE_COOKIE)?.value;
23
+ if (!expectedChallenge) {
24
+ return NextResponse.json({ error: t("验证已过期,请重试") }, { status: 400 });
25
+ }
26
+
27
+ const body = (await req.json().catch(() => ({}))) as {
28
+ response?: RegistrationResponseJSON;
29
+ name?: string;
30
+ };
31
+ if (!body.response) {
32
+ return NextResponse.json({ error: t("缺少注册数据") }, { status: 400 });
33
+ }
34
+
35
+ const { rpID, origin } = rpConfig(req);
36
+
37
+ try {
38
+ const verification = await verifyRegistrationResponse({
39
+ response: body.response,
40
+ expectedChallenge,
41
+ expectedOrigin: origin,
42
+ expectedRPID: rpID,
43
+ });
44
+
45
+ if (!verification.verified || !verification.registrationInfo) {
46
+ return NextResponse.json({ error: t("注册失败") }, { status: 400 });
47
+ }
48
+
49
+ const { credential } = verification.registrationInfo;
50
+ await addPasskey({
51
+ credentialId: credential.id,
52
+ publicKey: toBase64Url(credential.publicKey),
53
+ counter: credential.counter,
54
+ transports: credential.transports as AuthenticatorTransportFuture[] | undefined,
55
+ });
56
+
57
+ jar.delete(CHALLENGE_COOKIE);
58
+ await clearPasskeyAddAuthorization();
59
+ return NextResponse.json({ ok: true, count: (await listPasskeys()).length });
60
+ } catch {
61
+ return NextResponse.json({ error: t("注册失败,请重试") }, { status: 400 });
62
+ }
63
+ }
@@ -0,0 +1,44 @@
1
+ // 申请删除一把 Passkey:发确认邮件,确认页里才会真的删
2
+ import { NextResponse } from "next/server";
3
+ import { isLoggedIn } from "@/lib/auth";
4
+ import { listPasskeys } from "@/lib/passkey";
5
+ import { clientKey } from "@/lib/rate-limit";
6
+ import { mailReady, requestPasskeyChange } from "@/lib/change-request";
7
+ import { getT } from "@/lib/i18n";
8
+ import { getEnvValue } from "@/lib/env-config";
9
+
10
+ export async function POST(req: Request) {
11
+ const t = await getT();
12
+ if (!(await isLoggedIn())) {
13
+ return NextResponse.json({ error: t("请先登录") }, { status: 401 });
14
+ }
15
+
16
+ const body = (await req.json().catch(() => ({}))) as { credentialId?: string };
17
+ const credentialId = String(body.credentialId ?? "");
18
+ if (!credentialId) {
19
+ return NextResponse.json({ error: t("缺少凭据编号") }, { status: 400 });
20
+ }
21
+
22
+ const all = await listPasskeys();
23
+ if (!all.some((key) => key.credentialId === credentialId)) {
24
+ return NextResponse.json({ error: t("没有找到这把 Passkey") }, { status: 404 });
25
+ }
26
+ if (!(await mailReady())) {
27
+ return NextResponse.json(
28
+ { error: t("还没配好邮件确认,暂时不能删除 Passkey") },
29
+ { status: 503 }
30
+ );
31
+ }
32
+
33
+ const result = await requestPasskeyChange({
34
+ action: "remove",
35
+ credentialId,
36
+ linkOrigin: getEnvValue("ORIGIN") || new URL(req.url).origin,
37
+ ip: clientKey(req),
38
+ ua: req.headers.get("user-agent") ?? "",
39
+ });
40
+ if ("error" in result) {
41
+ return NextResponse.json({ error: result.error }, { status: 400 });
42
+ }
43
+ return NextResponse.json({ ok: true, pending: true });
44
+ }
@@ -0,0 +1,45 @@
1
+ // 紧急入口:两把钥匙都丢了的时候,用环境变量里的一把临时密钥把门打开
2
+ import { NextResponse } from "next/server";
3
+ import { timingSafeEqual } from "node:crypto";
4
+ import { startSession } from "@/lib/auth";
5
+ import { clientKey, rateLimit, resetRateLimit } from "@/lib/rate-limit";
6
+ import { getEnvValue } from "@/lib/env-config";
7
+ import { getT } from "@/lib/i18n";
8
+
9
+ function same(a: string, b: string): boolean {
10
+ const left = Buffer.from(a);
11
+ const right = Buffer.from(b);
12
+ if (left.length !== right.length) return false;
13
+ return timingSafeEqual(left, right);
14
+ }
15
+
16
+ export async function POST(req: Request) {
17
+ const t = await getT();
18
+ const expected = getEnvValue("RECOVERY_TOKEN");
19
+ // 没设、或者设得太短:不是错误,前端只提示去服务器 / 平台后台设置。
20
+ if (!expected || expected.length < 16) {
21
+ return NextResponse.json({ ok: false, code: "NOT_CONFIGURED" });
22
+ }
23
+
24
+ const key = `recovery:${clientKey(req)}`;
25
+ const gate = await rateLimit(key, 3);
26
+ if (!gate.allowed) {
27
+ return NextResponse.json(
28
+ { error: t("尝试次数过多,请 {minutes} 分钟后再试", { minutes: String(gate.minutes) }) },
29
+ { status: 429 }
30
+ );
31
+ }
32
+
33
+ const body = (await req.json().catch(() => ({}))) as { key?: string };
34
+ if (!body.key || !same(body.key.trim(), expected)) {
35
+ return NextResponse.json({ error: t("密钥不对") }, { status: 401 });
36
+ }
37
+
38
+ await resetRateLimit(key);
39
+ try {
40
+ await startSession();
41
+ } catch {
42
+ return NextResponse.json({ error: t("数据库暂时不可用,稍后再试") }, { status: 503 });
43
+ }
44
+ return NextResponse.json({ ok: true });
45
+ }
@@ -0,0 +1,42 @@
1
+ // 解绑验证器:必须过邮件确认(这一步会让账号少一把钥匙)
2
+ import { NextResponse } from "next/server";
3
+ import { isLoggedIn } from "@/lib/auth";
4
+ import { getAuth } from "@/lib/credentials";
5
+ import { clientKey } from "@/lib/rate-limit";
6
+ import { mailReady, requestTotpChange } from "@/lib/change-request";
7
+ import { getT } from "@/lib/i18n";
8
+ import { getEnvValue } from "@/lib/env-config";
9
+
10
+ export async function POST(req: Request) {
11
+ const t = await getT();
12
+ if (!(await isLoggedIn())) {
13
+ return NextResponse.json({ error: t("请先登录") }, { status: 401 });
14
+ }
15
+
16
+ let auth;
17
+ try {
18
+ auth = await getAuth();
19
+ } catch {
20
+ return NextResponse.json({ error: t("数据库暂时不可用,稍后再试") }, { status: 503 });
21
+ }
22
+ if (!auth.totpBound) {
23
+ return NextResponse.json({ error: t("现在没有绑定验证器") }, { status: 400 });
24
+ }
25
+ if (!(await mailReady())) {
26
+ return NextResponse.json(
27
+ { error: t("还没配好邮件确认,暂时不能解绑") },
28
+ { status: 503 }
29
+ );
30
+ }
31
+
32
+ const result = await requestTotpChange({
33
+ action: "disable",
34
+ linkOrigin: getEnvValue("ORIGIN") || new URL(req.url).origin,
35
+ ip: clientKey(req),
36
+ ua: req.headers.get("user-agent") ?? "",
37
+ });
38
+ if ("error" in result) {
39
+ return NextResponse.json({ error: result.error }, { status: 400 });
40
+ }
41
+ return NextResponse.json({ ok: true, pending: true });
42
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * 绑定验证器。
3
+ *
4
+ * 验过 6 位码后**一律发确认邮件**,点邮件里的链接才真正生效。
5
+ * 首次绑定和换绑走同一条路:
6
+ * - 换绑:旧验证器会立刻失效,多一道确认是必须的
7
+ * - 首次绑定:同样是给账号加一把钥匙,走一样的流程更一致,
8
+ * 也免得「码验过了就生效」——万一这个码是被别人看到的
9
+ * (比如你把手机屏幕亮给别人看),对方就能直接绑一把自己的验证器
10
+ */
11
+ import { NextResponse } from "next/server";
12
+ import { isLoggedIn } from "@/lib/auth";
13
+ import { getAuth } from "@/lib/credentials";
14
+ import { sealValue } from "@/lib/secret-box";
15
+ import { verifyCode } from "@/lib/totp";
16
+ import { clientKey } from "@/lib/rate-limit";
17
+ import { mailReady, requestTotpChange } from "@/lib/change-request";
18
+ import { getT } from "@/lib/i18n";
19
+ import { getEnvValue } from "@/lib/env-config";
20
+
21
+ export async function POST(req: Request) {
22
+ const t = await getT();
23
+ if (!(await isLoggedIn())) {
24
+ return NextResponse.json({ error: t("请先登录") }, { status: 401 });
25
+ }
26
+
27
+ const body = (await req.json().catch(() => ({}))) as {
28
+ secret?: string;
29
+ code?: string;
30
+ };
31
+ const secret = typeof body.secret === "string" ? body.secret.trim().toUpperCase() : "";
32
+ const code = typeof body.code === "string" ? body.code : "";
33
+
34
+ // secret 是 base32,长度太短说明不是我们发出去的
35
+ if (!/^[A-Z2-7]{16,64}$/.test(secret)) {
36
+ return NextResponse.json({ error: t("密钥格式不对,请重新生成") }, { status: 400 });
37
+ }
38
+
39
+ if (!verifyCode(secret, code, null).ok) {
40
+ return NextResponse.json(
41
+ { error: t("验证码不对。手机上的那条必须对应本页显示的密钥,重新扫一次二维码。") },
42
+ { status: 401 }
43
+ );
44
+ }
45
+
46
+ let auth;
47
+ try {
48
+ auth = await getAuth();
49
+ } catch {
50
+ return NextResponse.json({ error: t("数据库暂时不可用,稍后再试") }, { status: 503 });
51
+ }
52
+
53
+ const sealed = sealValue(secret);
54
+
55
+ // 没配好邮件通道就动不了手:绑定必须能被邮件确认
56
+ if (!(await mailReady())) {
57
+ return NextResponse.json(
58
+ { error: t("还没配好邮件确认,暂时不能绑定验证器") },
59
+ { status: 503 }
60
+ );
61
+ }
62
+
63
+ // 首次绑定和换绑都发确认信,确认页才真正写库
64
+ const result = await requestTotpChange({
65
+ action: "set",
66
+ sealedSecret: sealed,
67
+ linkOrigin: getEnvValue("ORIGIN") || new URL(req.url).origin,
68
+ ip: clientKey(req),
69
+ ua: req.headers.get("user-agent") ?? "",
70
+ });
71
+ if ("error" in result) {
72
+ return NextResponse.json({ error: result.error }, { status: 400 });
73
+ }
74
+ return NextResponse.json({ ok: true, pending: true });
75
+ }
@@ -0,0 +1,47 @@
1
+ // 验证码登录:用手机验证器里的 6 位码换会话
2
+ import { NextResponse } from "next/server";
3
+ import { getAuth, recordTotpStep } from "@/lib/credentials";
4
+ import { startSession } from "@/lib/auth";
5
+ import { verifyCode } from "@/lib/totp";
6
+ import { clientKey, rateLimit, resetRateLimit } from "@/lib/rate-limit";
7
+ import { getT } from "@/lib/i18n";
8
+
9
+ export async function POST(req: Request) {
10
+ const t = await getT();
11
+ const key = `totp-login:${clientKey(req)}`;
12
+ const gate = await rateLimit(key, 5);
13
+ if (!gate.allowed) {
14
+ return NextResponse.json(
15
+ { error: `尝试次数过多,请 ${gate.minutes} 分钟后再试` },
16
+ { status: 429 }
17
+ );
18
+ }
19
+
20
+ const body = (await req.json().catch(() => ({}))) as { code?: string };
21
+ const code = typeof body.code === "string" ? body.code : "";
22
+
23
+ let auth;
24
+ try {
25
+ auth = await getAuth();
26
+ } catch {
27
+ return NextResponse.json({ error: t("数据库暂时不可用,稍后再试") }, { status: 503 });
28
+ }
29
+
30
+ if (!auth.totpSecret) {
31
+ return NextResponse.json(
32
+ { error: t("还没有绑定验证器。请用 Passkey 登录后到设置页绑定。") },
33
+ { status: 400 }
34
+ );
35
+ }
36
+
37
+ const result = verifyCode(auth.totpSecret, code, auth.totpLastStep);
38
+ if (!result.ok) {
39
+ return NextResponse.json({ error: t("验证码不对,或已经用过") }, { status: 401 });
40
+ }
41
+
42
+ // 先记时间步再发会话:万一写库失败,宁可让用户重试,也不要留下可复用的码
43
+ await recordTotpStep(result.step);
44
+ await resetRateLimit(key);
45
+ await startSession();
46
+ return NextResponse.json({ ok: true });
47
+ }
@@ -0,0 +1,20 @@
1
+ // 生成一把新的验证器 secret,只返回给已登录的浏览器,不落库
2
+ // 落库发生在 /api/auth/totp/enable,且必须先验过一次 6 位码
3
+ import { NextResponse } from "next/server";
4
+ import { isLoggedIn } from "@/lib/auth";
5
+ import { groupSecret, newSecret, otpauthUri, qrSvg } from "@/lib/totp";
6
+ import { getT } from "@/lib/i18n";
7
+
8
+ export async function POST() {
9
+ const t = await getT();
10
+ if (!(await isLoggedIn())) {
11
+ return NextResponse.json({ error: t("请先登录") }, { status: 401 });
12
+ }
13
+ const secret = newSecret();
14
+ const qrSvgString = await qrSvg(otpauthUri(secret));
15
+ return NextResponse.json({
16
+ secret,
17
+ grouped: groupSecret(secret),
18
+ qrSvg: qrSvgString,
19
+ });
20
+ }
@@ -0,0 +1,27 @@
1
+ // 首次安装:环境变量配齐后标记初始化完成。
2
+ // 不自动登录——接下来跳到登录页,让站长用 RECOVERY_TOKEN 进门,
3
+ // 再去设置页配邮箱和身份验证。
4
+ import { NextResponse } from "next/server";
5
+ import { isLoggedIn } from "@/lib/auth";
6
+ import { saveSettings } from "@/lib/settings";
7
+ import { getT } from "@/lib/i18n";
8
+ import { hasCredentials } from "@/app/setup/config-actions";
9
+
10
+ export const dynamic = "force-dynamic";
11
+
12
+ export async function POST() {
13
+ const t = await getT();
14
+
15
+ // 站点已有凭据 yet 未登录时,不能让陌生人把状态改成「已完成」。
16
+ if (!(await isLoggedIn()) && (await hasCredentials())) {
17
+ return NextResponse.json({ error: t("请先登录") }, { status: 401 });
18
+ }
19
+
20
+ try {
21
+ await saveSettings({ setupCompleted: true });
22
+ } catch {
23
+ return NextResponse.json({ error: t("保存失败:数据库异常") }, { status: 503 });
24
+ }
25
+
26
+ return NextResponse.json({ ok: true });
27
+ }
@@ -0,0 +1,41 @@
1
+ // 安装第一步:填邮箱 → 发确认信。点信里的链接才把邮箱写进设置。
2
+ import { NextResponse } from "next/server";
3
+ import { isLoggedIn } from "@/lib/auth";
4
+ import { requestSetupEmail } from "@/lib/change-request";
5
+ import { clientKey } from "@/lib/rate-limit";
6
+ import { getEnvValue } from "@/lib/env-config";
7
+ import { getT } from "@/lib/i18n";
8
+
9
+ export const dynamic = "force-dynamic";
10
+
11
+ export async function POST(req: Request) {
12
+ const t = await getT();
13
+
14
+ // 安装还没走完时可能还没登录,但这一步要能走——
15
+ // 免登录放行只在「站点上还没有任何凭据」时成立,
16
+ // 这里跟着同样的判断,不给别的人口子。
17
+ if (!(await isLoggedIn())) {
18
+ const { hasCredentials } = await import("@/app/setup/config-actions");
19
+ if (await hasCredentials()) {
20
+ return NextResponse.json({ error: t("请先登录") }, { status: 401 });
21
+ }
22
+ }
23
+
24
+ const body = (await req.json().catch(() => ({}))) as { email?: string };
25
+ const email = typeof body.email === "string" ? body.email.trim() : "";
26
+ if (!email) {
27
+ return NextResponse.json({ error: t("先填个邮箱") }, { status: 400 });
28
+ }
29
+
30
+ const result = await requestSetupEmail({
31
+ email,
32
+ linkOrigin: getEnvValue("ORIGIN") || new URL(req.url).origin,
33
+ ip: clientKey(req),
34
+ ua: req.headers.get("user-agent") ?? "",
35
+ });
36
+
37
+ if ("error" in result) {
38
+ return NextResponse.json({ error: result.error }, { status: 400 });
39
+ }
40
+ return NextResponse.json({ ok: true });
41
+ }
@@ -0,0 +1,73 @@
1
+ // 本地磁盘存储:文件由服务器写入 uploads 目录
2
+ import { NextResponse } from "next/server";
3
+ import { isLoggedIn } from "@/lib/auth";
4
+ import { getT } from "@/lib/i18n";
5
+ import {
6
+ MAX_ATTACHMENT_SIZE,
7
+ MAX_IMAGE_SIZE,
8
+ isAllowedImageType,
9
+ saveLocalFile,
10
+ } from "@/lib/storage";
11
+
12
+ export const dynamic = "force-dynamic";
13
+
14
+ export async function POST(req: Request) {
15
+ const t = await getT();
16
+
17
+ if (!(await isLoggedIn())) {
18
+ return NextResponse.json(
19
+ { error: `${t("登录后才能上传文件")} [UNAUTHORIZED]` },
20
+ { status: 401 }
21
+ );
22
+ }
23
+
24
+ let file: File | null = null;
25
+ let kind = "image";
26
+ try {
27
+ const form = await req.formData();
28
+ const entry = form.get("file");
29
+ if (entry instanceof File) file = entry;
30
+ const kindEntry = form.get("kind");
31
+ if (typeof kindEntry === "string") kind = kindEntry;
32
+ } catch {
33
+ file = null;
34
+ }
35
+
36
+ if (!file) {
37
+ return NextResponse.json(
38
+ { error: `${t("请求格式不正确")} [BAD_REQUEST]` },
39
+ { status: 400 }
40
+ );
41
+ }
42
+
43
+ // 附件不限类型,只卡大小;图片仍然只收图片类型
44
+ const isAttachment = kind === "attachment";
45
+ if (!isAttachment && !isAllowedImageType(file.type)) {
46
+ return NextResponse.json(
47
+ { error: `${t("只支持图片文件")} [BAD_TYPE]` },
48
+ { status: 400 }
49
+ );
50
+ }
51
+ const maxSize = isAttachment ? MAX_ATTACHMENT_SIZE : MAX_IMAGE_SIZE;
52
+ if (file.size > maxSize) {
53
+ return NextResponse.json(
54
+ {
55
+ error: isAttachment
56
+ ? `${t("附件太大,单个不能超过 50MB")} [TOO_LARGE]`
57
+ : `${t("图片过大,请压缩后再传")} [TOO_LARGE]`,
58
+ },
59
+ { status: 400 }
60
+ );
61
+ }
62
+
63
+ try {
64
+ const saved = await saveLocalFile(file);
65
+ return NextResponse.json(saved);
66
+ } catch (err) {
67
+ const message = err instanceof Error ? err.message : t("上传失败");
68
+ return NextResponse.json(
69
+ { error: `${message} [UPLOAD_FAILED]` },
70
+ { status: 400 }
71
+ );
72
+ }
73
+ }