diff --git a/app/api/admin/email-verify/route.js b/app/api/admin/email-verify/route.js
new file mode 100644
index 0000000..4e11b5f
--- /dev/null
+++ b/app/api/admin/email-verify/route.js
@@ -0,0 +1,20 @@
+import pool from '@/lib/db';
+import { getUser, requireAdmin } from '@/lib/auth';
+import { loadSmtpConfig, isConfigComplete } from '@/lib/mailer';
+
+export async function PUT(req) {
+ const forbidden = await requireAdmin(getUser(req));
+ if (forbidden) return forbidden;
+ const body = await req.json().catch(() => ({}));
+ if (typeof body.required !== 'boolean') return Response.json({ error: '参数无效' }, { status: 400 });
+ try {
+ if (body.required && !isConfigComplete(await loadSmtpConfig())) {
+ return Response.json({ error: '请先完成 SMTP 配置' }, { status: 400 });
+ }
+ await pool.query(`INSERT INTO settings (key, value) VALUES ('email_verify_required', $1)
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, [String(body.required)]);
+ return Response.json({ success: true, email_verify_required: body.required });
+ } catch {
+ return Response.json({ error: '保存失败,请稍后重试' }, { status: 500 });
+ }
+}
diff --git a/app/api/admin/smtp/password/route.js b/app/api/admin/smtp/password/route.js
new file mode 100644
index 0000000..15324c6
--- /dev/null
+++ b/app/api/admin/smtp/password/route.js
@@ -0,0 +1,14 @@
+import pool from '@/lib/db';
+import { getUser, requireAdmin } from '@/lib/auth';
+
+export async function DELETE(req) {
+ const forbidden = await requireAdmin(getUser(req));
+ if (forbidden) return forbidden;
+ try {
+ await pool.query(`INSERT INTO settings (key, value) VALUES ('smtp_password', '')
+ ON CONFLICT (key) DO UPDATE SET value = '', updated_at = now()`);
+ return Response.json({ success: true });
+ } catch {
+ return Response.json({ error: '清除失败,请稍后重试' }, { status: 500 });
+ }
+}
diff --git a/app/api/admin/smtp/route.js b/app/api/admin/smtp/route.js
new file mode 100644
index 0000000..5094aad
--- /dev/null
+++ b/app/api/admin/smtp/route.js
@@ -0,0 +1,75 @@
+import pool from '@/lib/db';
+import { getUser, requireAdmin } from '@/lib/auth';
+import { loadSmtpConfig, isConfigComplete } from '@/lib/mailer';
+import { normalizeEmail } from '@/lib/email-verification';
+
+export const dynamic = 'force-dynamic';
+
+export async function GET(req) {
+ const forbidden = await requireAdmin(getUser(req));
+ if (forbidden) return forbidden;
+ try {
+ const config = await loadSmtpConfig();
+ return Response.json({
+ enabled: config.enabled,
+ host: config.host,
+ port: config.port,
+ secure: config.secure,
+ user: config.user,
+ from_name: config.fromName,
+ from_email: config.fromEmail,
+ allow_self_signed: config.allowSelfSigned,
+ password_set: Boolean(config.password),
+ configured: isConfigComplete(config),
+ }, { headers: { 'Cache-Control': 'private, no-store' } });
+ } catch {
+ return Response.json({ error: '服务器错误' }, { status: 500 });
+ }
+}
+
+export async function PUT(req) {
+ const forbidden = await requireAdmin(getUser(req));
+ if (forbidden) return forbidden;
+ const body = await req.json().catch(() => ({}));
+ const port = Number(body.port);
+ const host = typeof body.host === 'string' ? body.host.trim() : '';
+ const user = typeof body.user === 'string' ? body.user.trim() : '';
+ const fromName = typeof body.from_name === 'string' ? body.from_name.trim() : '';
+ const fromEmail = typeof body.from_email === 'string' ? body.from_email.trim() : '';
+ if (typeof body.enabled !== 'boolean' || typeof body.secure !== 'boolean' ||
+ !Number.isInteger(port) || port < 1 || port > 65535 ||
+ host.length > 255 || user.length > 255 || fromName.length > 100 ||
+ (fromEmail && !normalizeEmail(fromEmail)) ||
+ (body.password !== undefined && (typeof body.password !== 'string' || body.password.length > 255))) {
+ return Response.json({ error: 'SMTP 配置无效' }, { status: 400 });
+ }
+ const previous = await loadSmtpConfig();
+ if (body.enabled && (!host || !fromEmail || (user && !body.password && !previous.password))) {
+ return Response.json({ error: '启用 SMTP 前请填写服务器、发件邮箱和认证信息' }, { status: 400 });
+ }
+ const entries = [
+ ['smtp_enabled', String(body.enabled)], ['smtp_host', host], ['smtp_port', String(port)],
+ ['smtp_secure', String(body.secure)], ['smtp_user', user], ['smtp_from_name', fromName],
+ ['smtp_from_email', fromEmail], ['smtp_allow_self_signed', String(body.allow_self_signed === true)],
+ ];
+ if (body.password) entries.push(['smtp_password', body.password]);
+ const client = await pool.connect();
+ try {
+ await client.query('BEGIN');
+ for (const [key, value] of entries) {
+ await client.query(`INSERT INTO settings (key, value) VALUES ($1, $2)
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, [key, value]);
+ }
+ if (!body.enabled) {
+ await client.query(`INSERT INTO settings (key, value) VALUES ('email_verify_required', 'false')
+ ON CONFLICT (key) DO UPDATE SET value = 'false', updated_at = now()`);
+ }
+ await client.query('COMMIT');
+ return Response.json({ success: true });
+ } catch {
+ await client.query('ROLLBACK').catch(() => {});
+ return Response.json({ error: '保存失败,请稍后重试' }, { status: 500 });
+ } finally {
+ client.release();
+ }
+}
diff --git a/app/api/admin/smtp/test/route.js b/app/api/admin/smtp/test/route.js
new file mode 100644
index 0000000..6bafb99
--- /dev/null
+++ b/app/api/admin/smtp/test/route.js
@@ -0,0 +1,27 @@
+import pool from '@/lib/db';
+import { getUser, requireAdmin } from '@/lib/auth';
+import { loadSmtpConfig, isConfigComplete, sendMail, describeSmtpError } from '@/lib/mailer';
+import { normalizeEmail } from '@/lib/email-verification';
+
+export async function POST(req) {
+ const user = getUser(req);
+ const forbidden = await requireAdmin(user);
+ if (forbidden) return forbidden;
+ const body = await req.json().catch(() => ({}));
+ if (body.to && !normalizeEmail(body.to)) return Response.json({ error: '收件人邮箱格式无效' }, { status: 400 });
+ try {
+ const config = await loadSmtpConfig();
+ if (!isConfigComplete(config)) return Response.json({ error: 'SMTP 尚未配置完成' }, { status: 400 });
+ const me = await pool.query('SELECT email FROM users WHERE id = $1', [user.id]);
+ const to = body.to ? normalizeEmail(body.to) : me.rows[0]?.email;
+ if (!to) return Response.json({ error: '请指定收件人邮箱' }, { status: 400 });
+ await sendMail(config, {
+ to,
+ subject: 'Forumlify SMTP 测试邮件',
+ text: `这是一封来自 Forumlify 的测试邮件。\n\n发送时间:${new Date().toISOString()}`,
+ });
+ return Response.json({ success: true, to });
+ } catch (error) {
+ return Response.json({ error: describeSmtpError(error) }, { status: 400 });
+ }
+}
diff --git a/app/api/auth/forgot-password/route.js b/app/api/auth/forgot-password/route.js
new file mode 100644
index 0000000..94f6562
--- /dev/null
+++ b/app/api/auth/forgot-password/route.js
@@ -0,0 +1,31 @@
+import pool from '@/lib/db';
+import { loadSmtpConfig, isConfigComplete, sendMail, describeSmtpError } from '@/lib/mailer';
+import { normalizeEmail, saveEmailCode, invalidateEmailCode } from '@/lib/email-verification';
+
+export async function POST(req) {
+ const body = await req.json().catch(() => ({}));
+ const email = normalizeEmail(body.email);
+ if (!email) return Response.json({ error: '请输入有效邮箱' }, { status: 400 });
+ try {
+ const config = await loadSmtpConfig();
+ if (!isConfigComplete(config)) return Response.json({ error: '站点尚未配置邮件服务' }, { status: 503 });
+ const user = await pool.query('SELECT id FROM users WHERE LOWER(email) = $1', [email]);
+ if (user.rowCount) {
+ const code = await saveEmailCode(email, 'reset');
+ if (!code) return Response.json({ error: '请 60 秒后再获取验证码' }, { status: 429 });
+ try {
+ await sendMail(config, {
+ to: email,
+ subject: 'Forumlify 密码重置验证码',
+ text: `你的密码重置验证码是:${code}\n\n有效期 10 分钟。如果这不是你本人的操作,请忽略本邮件。`,
+ });
+ } catch (error) {
+ await invalidateEmailCode(email, 'reset');
+ throw error;
+ }
+ }
+ return Response.json({ success: true, message: '如果该邮箱已注册,重置码已发送' });
+ } catch (error) {
+ return Response.json({ error: describeSmtpError(error) }, { status: 400 });
+ }
+}
diff --git a/app/api/auth/register/route.js b/app/api/auth/register/route.js
index 6f4e9d8..6eefd41 100644
--- a/app/api/auth/register/route.js
+++ b/app/api/auth/register/route.js
@@ -3,20 +3,27 @@ import bcrypt from 'bcryptjs';
import pool from '@/lib/db';
import { verifyCaptcha } from '@/lib/captcha';
import { logAudit } from '@/lib/audit';
+import { normalizeEmail, isEmailVerificationRequired, withEmailCode, CODE_ERRORS, ensureEmailVerificationSchema } from '@/lib/email-verification';
export async function POST(req) {
- const { email, password, username, captcha_id, captcha_answer, captcha_sig } = await req.json();
- if (!email || !password || !username) {
+ const { email, password, username, email_code, captcha_id, captcha_answer, captcha_sig } = await req.json();
+ const normalizedEmail = normalizeEmail(email);
+ if (!normalizedEmail || !password || !username) {
return Response.json({ error: '请填写完整信息' }, { status: 400 });
}
- if (password.length < 6) {
- return Response.json({ error: '密码至少6位' }, { status: 400 });
+ if (typeof password !== 'string' || password.length < 6 || password.length > 128 ||
+ typeof username !== 'string' || !username.trim() || username.length > 50) {
+ return Response.json({ error: '用户名或密码长度无效' }, { status: 400 });
}
// 服务端验证码校验(ENABLE_CAPTCHA 关闭时跳过)
if (process.env.ENABLE_CAPTCHA !== 'false' && !verifyCaptcha(captcha_id, captcha_answer, captcha_sig)) {
return Response.json({ error: '验证码错误,请重新计算' }, { status: 400 });
}
try {
+ const verificationRequired = await isEmailVerificationRequired();
+ if (verificationRequired && !/^\d{6}$/.test(email_code || '')) {
+ return Response.json({ error: '请输入邮箱验证码' }, { status: 400 });
+ }
const countResult = await pool.query('SELECT COUNT(*) FROM users');
const isFirstUser = parseInt(countResult.rows[0].count) === 0;
@@ -24,12 +31,21 @@ export async function POST(req) {
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
const role = isFirstUser ? 'admin' : 'user';
- const r = await pool.query(
- `INSERT INTO users (email, password_hash, username, avatar_url, role)
- VALUES ($1, $2, $3, $4, $5)
+ const insert = (client) => client.query(
+ `INSERT INTO users (email, password_hash, username, avatar_url, role, email_verified)
+ VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id, username, avatar_url, role, created_at`,
- [email, hash, username, avatar, role]
+ [normalizedEmail, hash, username.trim(), avatar, role, verificationRequired]
);
+ let r;
+ if (verificationRequired) {
+ const result = await withEmailCode(normalizedEmail, 'register', email_code, insert);
+ if (result.failure) return Response.json({ error: CODE_ERRORS[result.failure] }, { status: 400 });
+ r = result.value;
+ } else {
+ await ensureEmailVerificationSchema();
+ r = await insert(pool);
+ }
// 服务端审计:注册成功
await logAudit(req, 'register', r.rows[0].id);
diff --git a/app/api/auth/reset-password-by-email/route.js b/app/api/auth/reset-password-by-email/route.js
new file mode 100644
index 0000000..c2b2348
--- /dev/null
+++ b/app/api/auth/reset-password-by-email/route.js
@@ -0,0 +1,23 @@
+import bcrypt from 'bcryptjs';
+import { normalizeEmail, withEmailCode, CODE_ERRORS } from '@/lib/email-verification';
+
+export async function POST(req) {
+ const body = await req.json().catch(() => ({}));
+ const email = normalizeEmail(body.email);
+ if (!email || !/^\d{6}$/.test(body.code || '') ||
+ typeof body.newPassword !== 'string' || body.newPassword.length < 6 || body.newPassword.length > 128) {
+ return Response.json({ error: '请填写有效的邮箱、验证码和新密码' }, { status: 400 });
+ }
+ try {
+ const hash = await bcrypt.hash(body.newPassword, 10);
+ const result = await withEmailCode(email, 'reset', body.code, async (client) => {
+ const updated = await client.query('UPDATE users SET password_hash = $1 WHERE LOWER(email) = $2 RETURNING id', [hash, email]);
+ if (!updated.rowCount) throw new Error('账号不存在');
+ return updated.rows[0];
+ });
+ if (result.failure) return Response.json({ error: CODE_ERRORS[result.failure] }, { status: 400 });
+ return Response.json({ success: true });
+ } catch {
+ return Response.json({ error: '重置失败,请稍后重试' }, { status: 500 });
+ }
+}
diff --git a/app/api/auth/send-code/route.js b/app/api/auth/send-code/route.js
new file mode 100644
index 0000000..0ae9df9
--- /dev/null
+++ b/app/api/auth/send-code/route.js
@@ -0,0 +1,33 @@
+import pool from '@/lib/db';
+import { loadSmtpConfig, isConfigComplete, sendMail, describeSmtpError } from '@/lib/mailer';
+import { normalizeEmail, isEmailVerificationRequired, saveEmailCode, invalidateEmailCode } from '@/lib/email-verification';
+
+export async function POST(req) {
+ const body = await req.json().catch(() => ({}));
+ const email = normalizeEmail(body.email);
+ if (!email) return Response.json({ error: '请输入有效邮箱' }, { status: 400 });
+ try {
+ if (!await isEmailVerificationRequired()) {
+ return Response.json({ error: '本站未开启邮箱验证' }, { status: 400 });
+ }
+ const config = await loadSmtpConfig();
+ if (!isConfigComplete(config)) return Response.json({ error: '站点尚未配置邮件服务' }, { status: 503 });
+ const existing = await pool.query('SELECT 1 FROM users WHERE LOWER(email) = $1', [email]);
+ if (existing.rowCount) return Response.json({ error: '该邮箱已被注册' }, { status: 409 });
+ const code = await saveEmailCode(email, 'register');
+ if (!code) return Response.json({ error: '请 60 秒后再获取验证码' }, { status: 429 });
+ try {
+ await sendMail(config, {
+ to: email,
+ subject: 'Forumlify 注册验证码',
+ text: `你的注册验证码是:${code}\n\n有效期 10 分钟,请勿转发给他人。`,
+ });
+ } catch (error) {
+ await invalidateEmailCode(email, 'register');
+ throw error;
+ }
+ return Response.json({ success: true });
+ } catch (error) {
+ return Response.json({ error: describeSmtpError(error) }, { status: 400 });
+ }
+}
diff --git a/app/api/blocks/route.js b/app/api/blocks/route.js
new file mode 100644
index 0000000..6f4dcc1
--- /dev/null
+++ b/app/api/blocks/route.js
@@ -0,0 +1,19 @@
+import pool from '@/lib/db';
+import { getUser } from '@/lib/auth';
+import { ensureUserBlocksSchema } from '@/lib/user-blocks';
+
+export async function GET(req) {
+ const user = getUser(req);
+ if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
+ try {
+ await ensureUserBlocksSchema();
+ const result = await pool.query(`
+ SELECT u.id, u.username, u.avatar_url, b.created_at
+ FROM user_blocks b JOIN users u ON u.id = b.blocked_id
+ WHERE b.blocker_id = $1 ORDER BY b.created_at DESC
+ `, [user.id]);
+ return Response.json({ data: result.rows }, { headers: { 'Cache-Control': 'private, no-store' } });
+ } catch {
+ return Response.json({ error: '服务器错误' }, { status: 500 });
+ }
+}
diff --git a/app/api/conversations/[id]/messages/route.js b/app/api/conversations/[id]/messages/route.js
index 56b49c1..49c7d5e 100644
--- a/app/api/conversations/[id]/messages/route.js
+++ b/app/api/conversations/[id]/messages/route.js
@@ -1,6 +1,7 @@
// GET /api/conversations/[id]/messages, POST /api/conversations/[id]/messages
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
+import { ensureUserBlocksSchema } from '@/lib/user-blocks';
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -49,30 +50,60 @@ export async function POST(req, { params }) {
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
}
const { content } = await req.json();
- if (!content || content.trim().length === 0) {
- return Response.json({ error: '请填写消息内容' }, { status: 400 });
+ if (typeof content !== 'string' || !content.trim() || content.length > 10000) {
+ return Response.json({ error: '消息长度应为1到10000个字符' }, { status: 400 });
}
+ const client = await pool.connect();
try {
- const check = await pool.query(`
- SELECT id FROM conversations
+ await ensureUserBlocksSchema();
+ await client.query('BEGIN');
+ const check = await client.query(`
+ SELECT id, user1_id, user2_id FROM conversations
WHERE id = $1 AND (user1_id = $2 OR user2_id = $2)
+ FOR UPDATE
`, [(await params).id, user.id]);
if (check.rows.length === 0) {
+ await client.query('ROLLBACK');
return Response.json({ error: '无权限访问此会话' }, { status: 403 });
}
- const r = await pool.query(`
+ const conversation = check.rows[0];
+ const otherId = conversation.user1_id === user.id ? conversation.user2_id : conversation.user1_id;
+ const blocked = await client.query(`
+ SELECT 1 FROM user_blocks
+ WHERE (blocker_id = $1 AND blocked_id = $2)
+ OR (blocker_id = $2 AND blocked_id = $1)
+ LIMIT 1
+ `, [otherId, user.id]);
+ if (blocked.rowCount) {
+ await client.query('ROLLBACK');
+ return Response.json({ error: '无法向该用户发送消息' }, { status: 403 });
+ }
+ const stats = await client.query(`
+ SELECT COUNT(*) FILTER (WHERE sender_id = $2) AS mine,
+ COUNT(*) FILTER (WHERE sender_id = $3) AS theirs
+ FROM messages WHERE conversation_id = $1
+ `, [(await params).id, user.id, otherId]);
+ if (Number(stats.rows[0].theirs) === 0 && Number(stats.rows[0].mine) >= 3) {
+ await client.query('ROLLBACK');
+ return Response.json({ error: '对方回复前最多发送 3 条消息,请等待对方回复', limit_reached: true, limit: 3 }, { status: 429 });
+ }
+ const r = await client.query(`
INSERT INTO messages (conversation_id, sender_id, content)
VALUES ($1, $2, $3)
RETURNING *
- `, [(await params).id, user.id, content]);
- await pool.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [(await params).id]);
- const userInfo = await pool.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
+ `, [(await params).id, user.id, content.trim()]);
+ await client.query('UPDATE conversations SET last_message_at = NOW() WHERE id = $1', [(await params).id]);
+ const userInfo = await client.query('SELECT username, avatar_url FROM users WHERE id = $1', [user.id]);
+ await client.query('COMMIT');
return Response.json({
...r.rows[0],
sender_username: userInfo.rows[0].username,
sender_avatar_url: userInfo.rows[0].avatar_url,
});
} catch {
+ await client.query('ROLLBACK').catch(() => {});
return Response.json({ error: '发送失败,请稍后重试' }, { status: 500 });
+ } finally {
+ client.release();
}
}
diff --git a/app/api/conversations/route.js b/app/api/conversations/route.js
index 96def92..3149d00 100644
--- a/app/api/conversations/route.js
+++ b/app/api/conversations/route.js
@@ -1,6 +1,7 @@
// GET /api/conversations, POST /api/conversations
import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
+import { ensureUserBlocksSchema, hasBlocked, UUID_RE } from '@/lib/user-blocks';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
@@ -42,17 +43,21 @@ export async function POST(req) {
return Response.json({ error: '请先登录' }, { status: 401 });
}
const { other_user_id } = await req.json();
- if (!other_user_id) {
- return Response.json({ error: '缺少对方用户ID' }, { status: 400 });
+ if (!UUID_RE.test(other_user_id || '')) {
+ return Response.json({ error: '对方用户ID无效' }, { status: 400 });
}
if (other_user_id === user.id) {
return Response.json({ error: '不能与自己私信' }, { status: 400 });
}
try {
+ await ensureUserBlocksSchema();
const userCheck = await pool.query('SELECT id FROM users WHERE id = $1', [other_user_id]);
if (userCheck.rows.length === 0) {
return Response.json({ error: '用户不存在' }, { status: 404 });
}
+ if (await hasBlocked(other_user_id, user.id) || await hasBlocked(user.id, other_user_id)) {
+ return Response.json({ error: '无法向该用户发起私信' }, { status: 403 });
+ }
const existing = await pool.query(`
SELECT id FROM conversations
WHERE (user1_id = $1 AND user2_id = $2) OR (user1_id = $2 AND user2_id = $1)
@@ -62,7 +67,9 @@ export async function POST(req) {
}
const r = await pool.query(`
INSERT INTO conversations (user1_id, user2_id)
- VALUES ($1, $2)
+ VALUES (LEAST($1::uuid, $2::uuid), GREATEST($1::uuid, $2::uuid))
+ ON CONFLICT (user1_id, user2_id)
+ DO UPDATE SET user1_id = EXCLUDED.user1_id
RETURNING id
`, [user.id, other_user_id]);
return Response.json({ id: r.rows[0].id });
diff --git a/app/api/posts/[id]/replies/route.js b/app/api/posts/[id]/replies/route.js
index 93b9cf4..ce59c16 100644
--- a/app/api/posts/[id]/replies/route.js
+++ b/app/api/posts/[id]/replies/route.js
@@ -6,8 +6,12 @@ import { verifyCaptcha } from '@/lib/captcha';
import { logAudit } from '@/lib/audit';
import { getReplySchemaCapabilities } from '@/lib/reply-schema';
import { resolvePostReference } from '@/lib/post-reference';
+import { ensureUserBlocksSchema } from '@/lib/user-blocks';
-function repliesSelectSql(capabilities) {
+function repliesSelectSql(capabilities, viewer) {
+ const visible = viewer ? ` AND NOT EXISTS (
+ SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = r.user_id
+ )` : '';
if (capabilities.replyToId) {
return `SELECT r.id, r.post_id, r.user_id, r.content, r.created_at,
r.reply_to_id, u.username, u.avatar_url,
@@ -16,7 +20,7 @@ function repliesSelectSql(capabilities) {
JOIN users u ON r.user_id = u.id
LEFT JOIN replies rt ON r.reply_to_id = rt.id
LEFT JOIN users ru ON rt.user_id = ru.id
- WHERE r.post_id = $1
+ WHERE r.post_id = $1${visible}
ORDER BY r.created_at ASC`;
}
@@ -27,7 +31,7 @@ function repliesSelectSql(capabilities) {
r.reply_to_username
FROM replies r
JOIN users u ON r.user_id = u.id
- WHERE r.post_id = $1
+ WHERE r.post_id = $1${visible}
ORDER BY r.created_at ASC`;
}
@@ -37,7 +41,7 @@ function repliesSelectSql(capabilities) {
u.username, u.avatar_url
FROM replies r
JOIN users u ON r.user_id = u.id
- WHERE r.post_id = $1
+ WHERE r.post_id = $1${visible}
ORDER BY r.created_at ASC`;
}
@@ -45,9 +49,13 @@ export async function GET(req, { params }) {
try {
const reference = await resolvePostReference((await params).id);
if (!reference) return Response.json({ error: '帖子不存在' }, { status: 404 });
+ const viewer = getUser(req);
+ if (viewer) await ensureUserBlocksSchema();
const capabilities = await getReplySchemaCapabilities();
- const r = await pool.query(repliesSelectSql(capabilities), [reference.id]);
- return jsonWithEtag(req, r.rows);
+ const r = await pool.query(repliesSelectSql(capabilities, viewer), viewer ? [reference.id, viewer.id] : [reference.id]);
+ return viewer
+ ? Response.json(r.rows, { headers: { 'Cache-Control': 'private, no-store' } })
+ : jsonWithEtag(req, r.rows);
} catch (error) {
console.error('[replies] list failed:', error?.code || error?.message);
return Response.json({ error: '服务器错误' }, { status: 500 });
diff --git a/app/api/posts/[id]/route.js b/app/api/posts/[id]/route.js
index b048e43..752a5a0 100644
--- a/app/api/posts/[id]/route.js
+++ b/app/api/posts/[id]/route.js
@@ -3,6 +3,7 @@ import pool from '@/lib/db';
import { getUser } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
import { resolvePostReference } from '@/lib/post-reference';
+import { ensureUserBlocksSchema } from '@/lib/user-blocks';
function invalidId() {
return Response.json({ error: '帖子不存在' }, { status: 404 });
@@ -10,19 +11,25 @@ function invalidId() {
export async function GET(req, { params }) {
try {
+ const viewer = getUser(req);
const reference = await resolvePostReference((await params).id);
if (!reference) return invalidId();
+ if (viewer) await ensureUserBlocksSchema();
const r = await pool.query(
`SELECT p.*, u.username, u.avatar_url, u.signature
FROM posts p
JOIN users u ON p.user_id = u.id
- WHERE p.id = $1`,
- [reference.id]
+ WHERE p.id = $1${viewer ? ` AND NOT EXISTS (
+ SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = p.user_id
+ )` : ''}`,
+ viewer ? [reference.id, viewer.id] : [reference.id]
);
if (r.rows.length === 0) {
return invalidId();
}
- return jsonWithEtag(req, r.rows[0]);
+ return viewer
+ ? Response.json(r.rows[0], { headers: { 'Cache-Control': 'private, no-store' } })
+ : jsonWithEtag(req, r.rows[0]);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
diff --git a/app/api/posts/route.js b/app/api/posts/route.js
index 391bfec..71870f2 100644
--- a/app/api/posts/route.js
+++ b/app/api/posts/route.js
@@ -5,6 +5,7 @@ import { jsonWithEtag } from '@/lib/http-cache';
import { verifyCaptcha } from '@/lib/captcha';
import { logAudit } from '@/lib/audit';
import { ensurePostNumberSchema } from '@/lib/post-reference';
+import { ensureUserBlocksSchema } from '@/lib/user-blocks';
// 避免 GET 被静态优化导致写方法 405(动态接口,不能缓存)
export const dynamic = 'force-dynamic';
@@ -14,6 +15,7 @@ export async function GET(req) {
const url = new URL(req.url);
const sort = url.searchParams.get('sort') === 'hot' ? 'updated_at' : 'created_at';
const userId = url.searchParams.get('user_id');
+ const viewer = getUser(req);
const page = Math.max(1, parseInt(url.searchParams.get('page')) || 1);
// 分页边界:limit 封顶 50,page 封顶 10000(防深分页 DoS)
const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit')) || 20));
@@ -24,11 +26,19 @@ export async function GET(req) {
try {
await ensurePostNumberSchema();
const params = [];
- let where = '';
+ const conditions = [];
if (userId) {
- where = ' WHERE p.user_id = $1';
- (await params).push(userId);
+ params.push(userId);
+ conditions.push(`p.user_id = $${params.length}`);
}
+ if (viewer) {
+ await ensureUserBlocksSchema();
+ params.push(viewer.id);
+ conditions.push(`NOT EXISTS (
+ SELECT 1 FROM user_blocks b WHERE b.blocker_id = $${params.length} AND b.blocked_id = p.user_id
+ )`);
+ }
+ const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
const countResult = await pool.query(`SELECT COUNT(*) as total FROM posts p${where}`, params);
const total = parseInt(countResult.rows[0]?.total || 0);
@@ -44,13 +54,16 @@ export async function GET(req) {
JOIN users u ON p.user_id = u.id
${where}
ORDER BY is_pinned DESC, pinned_at DESC NULLS LAST, ${sort} DESC
- LIMIT $${(await params).length + 1} OFFSET $${(await params).length + 2}
+ LIMIT $${params.length + 1} OFFSET $${params.length + 2}
`, [...params, limit, offset]);
- return jsonWithEtag(req, {
+ const payload = {
data: r.rows,
pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
- });
+ };
+ return viewer
+ ? Response.json(payload, { headers: { 'Cache-Control': 'private, no-store' } })
+ : jsonWithEtag(req, payload);
} catch {
return Response.json({ error: '服务器错误' }, { status: 500 });
}
diff --git a/app/api/posts/search/route.js b/app/api/posts/search/route.js
new file mode 100644
index 0000000..703e45a
--- /dev/null
+++ b/app/api/posts/search/route.js
@@ -0,0 +1,51 @@
+import pool from '@/lib/db';
+import { getUser } from '@/lib/auth';
+import { ensurePostNumberSchema } from '@/lib/post-reference';
+import { ensureUserBlocksSchema } from '@/lib/user-blocks';
+
+export const dynamic = 'force-dynamic';
+
+function escapeLike(value) {
+ return value.replace(/[\\%_]/g, (character) => `\\${character}`);
+}
+
+export async function GET(req) {
+ const url = new URL(req.url);
+ const keyword = (url.searchParams.get('q') || '').trim();
+ if (!keyword) return Response.json({ error: '请输入搜索关键词' }, { status: 400 });
+ if (keyword.length > 100) return Response.json({ error: '搜索关键词过长(最多 100 字)' }, { status: 400 });
+
+ const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get('limit'), 10) || 20));
+ const page = Math.min(10000, Math.max(1, parseInt(url.searchParams.get('page'), 10) || 1));
+ const user = getUser(req);
+ const values = [`%${escapeLike(keyword)}%`];
+ let where = '(p.title ILIKE $1 OR p.content ILIKE $1)';
+
+ try {
+ if (user) {
+ await ensureUserBlocksSchema();
+ values.push(user.id);
+ where += ` AND NOT EXISTS (
+ SELECT 1 FROM user_blocks b WHERE b.blocker_id = $2 AND b.blocked_id = p.user_id
+ )`;
+ }
+ await ensurePostNumberSchema();
+ const count = await pool.query(`SELECT COUNT(*) AS total FROM posts p WHERE ${where}`, values);
+ const total = Number(count.rows[0].total);
+ const rows = await pool.query(`
+ SELECT p.*, u.username, u.avatar_url, u.signature,
+ (SELECT COUNT(*) FROM replies WHERE post_id = p.id) AS reply_count
+ FROM posts p JOIN users u ON u.id = p.user_id
+ WHERE ${where}
+ ORDER BY p.created_at DESC
+ LIMIT $${values.length + 1} OFFSET $${values.length + 2}
+ `, [...values, limit, (page - 1) * limit]);
+ return Response.json({
+ data: rows.rows,
+ query: keyword,
+ pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
+ }, { headers: { 'Cache-Control': 'private, no-store' } });
+ } catch {
+ return Response.json({ error: '服务器错误' }, { status: 500 });
+ }
+}
diff --git a/app/api/settings/route.js b/app/api/settings/route.js
index 0e4aa4a..80b327b 100644
--- a/app/api/settings/route.js
+++ b/app/api/settings/route.js
@@ -2,6 +2,7 @@
import pool from '@/lib/db';
import { getUser, requireAdmin } from '@/lib/auth';
import { jsonWithEtag } from '@/lib/http-cache';
+import { loadSmtpConfig, isConfigComplete } from '@/lib/mailer';
const VERSION_COMMIT = (process.env.FORUMLIFY_COMMIT || 'unknown').slice(0, 7);
@@ -15,10 +16,14 @@ export async function GET(req) {
`INSERT INTO settings (key, value) VALUES ('forum_name', 'Forumlify')
ON CONFLICT (key) DO NOTHING`
);
- const r = await pool.query('SELECT key, value FROM settings ORDER BY key');
+ const r = await pool.query(`SELECT key, value FROM settings
+ WHERE key = ANY($1::text[]) ORDER BY key`,
+ [['forum_name', 'favicon_url', 'favicon_version', 'custom_css_enabled', 'email_verify_required']]);
const settings = {};
r.rows.forEach((row) => { settings[row.key] = row.value; });
- delete settings.favicon_object;
+ const config = await loadSmtpConfig();
+ settings.smtp_ready = isConfigComplete(config);
+ settings.email_verify_required = settings.email_verify_required === 'true' && settings.smtp_ready;
// 兜底:即使插入失败也保证返回 forum_name
if (!settings.forum_name) settings.forum_name = 'Forumlify';
settings.version_commit = VERSION_COMMIT;
diff --git a/app/api/users/[id]/block-status/route.js b/app/api/users/[id]/block-status/route.js
new file mode 100644
index 0000000..9e4a0d4
--- /dev/null
+++ b/app/api/users/[id]/block-status/route.js
@@ -0,0 +1,22 @@
+import pool from '@/lib/db';
+import { getUser } from '@/lib/auth';
+import { ensureUserBlocksSchema, UUID_RE } from '@/lib/user-blocks';
+
+export async function GET(req, { params }) {
+ const user = getUser(req);
+ if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
+ const targetId = (await params).id;
+ if (!UUID_RE.test(targetId)) return Response.json({ error: '用户不存在' }, { status: 404 });
+ if (targetId === user.id) return Response.json({ blocked_by_me: false, blocked_me: false, self: true });
+ try {
+ await ensureUserBlocksSchema();
+ const result = await pool.query(`
+ SELECT
+ EXISTS(SELECT 1 FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2) AS blocked_by_me,
+ EXISTS(SELECT 1 FROM user_blocks WHERE blocker_id = $2 AND blocked_id = $1) AS blocked_me
+ `, [user.id, targetId]);
+ return Response.json(result.rows[0], { headers: { 'Cache-Control': 'private, no-store' } });
+ } catch {
+ return Response.json({ error: '服务器错误' }, { status: 500 });
+ }
+}
diff --git a/app/api/users/[id]/block/route.js b/app/api/users/[id]/block/route.js
new file mode 100644
index 0000000..c5ccac2
--- /dev/null
+++ b/app/api/users/[id]/block/route.js
@@ -0,0 +1,41 @@
+import pool from '@/lib/db';
+import { getUser } from '@/lib/auth';
+import { ensureUserBlocksSchema, UUID_RE } from '@/lib/user-blocks';
+
+export async function POST(req, { params }) {
+ const user = getUser(req);
+ if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
+ const targetId = (await params).id;
+ if (!UUID_RE.test(targetId) || targetId === user.id) {
+ return Response.json({ error: '不能屏蔽该用户' }, { status: 400 });
+ }
+ try {
+ await ensureUserBlocksSchema();
+ const result = await pool.query(`
+ INSERT INTO user_blocks (blocker_id, blocked_id)
+ SELECT $1, id FROM users WHERE id = $2
+ ON CONFLICT (blocker_id, blocked_id) DO NOTHING RETURNING id
+ `, [user.id, targetId]);
+ if (!result.rowCount) {
+ const target = await pool.query('SELECT id FROM users WHERE id = $1', [targetId]);
+ if (!target.rowCount) return Response.json({ error: '用户不存在' }, { status: 404 });
+ }
+ return Response.json({ success: true, blocked: true });
+ } catch {
+ return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
+ }
+}
+
+export async function DELETE(req, { params }) {
+ const user = getUser(req);
+ if (!user) return Response.json({ error: '请先登录' }, { status: 401 });
+ const targetId = (await params).id;
+ if (!UUID_RE.test(targetId)) return Response.json({ error: '用户不存在' }, { status: 404 });
+ try {
+ await ensureUserBlocksSchema();
+ await pool.query('DELETE FROM user_blocks WHERE blocker_id = $1 AND blocked_id = $2', [user.id, targetId]);
+ return Response.json({ success: true, blocked: false });
+ } catch {
+ return Response.json({ error: '操作失败,请稍后重试' }, { status: 500 });
+ }
+}
diff --git a/app/api/users/search/route.js b/app/api/users/search/route.js
new file mode 100644
index 0000000..281bef8
--- /dev/null
+++ b/app/api/users/search/route.js
@@ -0,0 +1,38 @@
+import pool from '@/lib/db';
+import { getUser } from '@/lib/auth';
+import { ensureUserBlocksSchema } from '@/lib/user-blocks';
+
+export const dynamic = 'force-dynamic';
+
+export async function GET(req) {
+ const url = new URL(req.url);
+ const keyword = (url.searchParams.get('q') || '').trim();
+ if (!keyword) return Response.json({ error: '请输入搜索关键词' }, { status: 400 });
+ if (keyword.length > 50) return Response.json({ error: '搜索关键词过长(最多 50 字)' }, { status: 400 });
+
+ const limit = Math.min(20, Math.max(1, parseInt(url.searchParams.get('limit'), 10) || 10));
+ const user = getUser(req);
+ try {
+ const values = [`%${keyword.replace(/[\\%_]/g, (character) => `\\${character}`)}%`,
+ `${keyword.replace(/[\\%_]/g, (character) => `\\${character}`)}%`];
+ let filter = '';
+ if (user) {
+ await ensureUserBlocksSchema();
+ values.push(user.id);
+ filter = ` AND u.id <> $3 AND NOT EXISTS (
+ SELECT 1 FROM user_blocks b WHERE b.blocker_id = $3 AND b.blocked_id = u.id
+ )`;
+ }
+ values.push(limit);
+ const result = await pool.query(`
+ SELECT u.id, u.username, u.avatar_url, u.role, u.signature
+ FROM users u WHERE u.username ILIKE $1${filter}
+ ORDER BY CASE WHEN u.username ILIKE $2 THEN 0 ELSE 1 END,
+ LENGTH(u.username), u.username
+ LIMIT $${values.length}
+ `, values);
+ return Response.json({ data: result.rows, query: keyword }, { headers: { 'Cache-Control': 'private, no-store' } });
+ } catch {
+ return Response.json({ error: '服务器错误' }, { status: 500 });
+ }
+}
diff --git a/app/globals.css b/app/globals.css
index 67b16af..5eba9c3 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -514,6 +514,119 @@ svg {
margin-right: 6px;
}
+.feed-search {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ min-height: 44px;
+ padding: 0 14px;
+ margin: 0 0 18px;
+ border: 1px solid var(--glass-border);
+ border-radius: var(--radius-sm);
+ background: var(--glass-bg);
+ color: var(--glass-text-secondary);
+ backdrop-filter: blur(12px);
+ -webkit-backdrop-filter: blur(12px);
+}
+.feed-search:focus-within { border-color: var(--primary); }
+.feed-search input {
+ flex: 1;
+ min-width: 0;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: var(--glass-text);
+ font: inherit;
+ font-size: 14px;
+}
+.feed-search input::-webkit-search-cancel-button { display: none; }
+.feed-search button {
+ border: 0;
+ background: transparent;
+ color: inherit;
+ cursor: pointer;
+}
+.search-empty {
+ padding: 60px 16px;
+ text-align: center;
+ color: var(--glass-text-secondary);
+ overflow-wrap: anywhere;
+}
+.chat-user-search {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 16px;
+ border-bottom: 1px solid var(--border);
+ color: var(--text-secondary);
+}
+.chat-user-search input {
+ flex: 1;
+ min-width: 0;
+ border: 0;
+ outline: 0;
+ background: transparent;
+ color: var(--text);
+ font: inherit;
+}
+.chat-user-result {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 10px 16px;
+ border: 0;
+ border-bottom: 1px solid var(--border);
+ background: transparent;
+ color: var(--text);
+ text-align: left;
+ cursor: pointer;
+}
+.chat-user-result:hover { background: var(--glass-bg); }
+.chat-user-result img { width: 36px; height: 36px; border-radius: 50%; object-fit: cover; }
+.chat-search-state { padding: 32px 16px; text-align: center; color: var(--text-secondary); }
+.user-profile-actions { display: flex; justify-content: center; gap: 10px; flex-wrap: wrap; margin-top: 12px; }
+.user-profile-actions button { padding: 8px 20px; }
+.blocked-user-hint { margin-top: 10px; font-size: 12px; color: var(--text-secondary); }
+.chat-limit-hint { padding: 8px 16px; font-size: 12px; color: var(--text-secondary); text-align: center; }
+.smtp-settings { max-width: 860px; overflow-wrap: anywhere; }
+.smtp-settings h3 { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
+.smtp-settings label { display: block; font-size: 14px; font-weight: 600; color: var(--text); }
+.smtp-settings input:not([type="checkbox"]) {
+ display: block;
+ width: 100%;
+ min-width: 0;
+ margin: 6px 0 14px;
+ padding: 9px 12px;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--bg);
+ color: var(--text);
+ font: inherit;
+}
+.smtp-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 16px; }
+.smtp-settings .smtp-check { display: flex; align-items: center; gap: 8px; margin: 10px 0; font-weight: 500; }
+.smtp-actions { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 14px; }
+.smtp-actions button { padding: 9px 18px; }
+@media (max-width: 600px) { .smtp-grid { grid-template-columns: minmax(0, 1fr); } }
+.auth-email-code-row { display: flex; align-items: stretch; gap: 8px; }
+.auth-email-code-row input { min-width: 0; flex: 1; }
+.auth-email-code-row button, .auth-send-code {
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ background: var(--surface);
+ color: var(--text);
+ cursor: pointer;
+ padding: 8px 12px;
+ white-space: nowrap;
+}
+.auth-email-code-row button { align-self: flex-start; }
+.auth-send-code { margin-bottom: 10px; }
+.auth-reset-methods { display: flex; gap: 8px; margin-bottom: 12px; }
+.auth-reset-methods button { flex: 1; padding: 8px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--text-secondary); cursor: pointer; }
+.auth-reset-methods button.active { border-color: var(--primary); color: var(--primary); }
+
.new-post-launch-label,
.new-post-title-label {
display: inline-block;
@@ -1644,6 +1757,7 @@ html.post-view-transition::view-transition-group(post-expand),
html.home-view-transition.returning-home::view-transition-group(post-expand) {
animation-duration: 1.1s;
animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1);
+ background: var(--glass-bg);
border-radius: var(--radius);
overflow: clip;
}
@@ -1804,17 +1918,25 @@ html.post-view-transition::view-transition-old(post-feed-actions) {
}
html.post-view-transition::view-transition-old(post-body) {
- animation: none;
- opacity: 0;
+ animation: postBodyPreviewOut 0.96s linear both;
}
html.post-view-transition::view-transition-new(post-body) {
- animation: none;
- opacity: 1;
+ animation: postBodyDetailIn 0.96s linear both;
object-fit: none;
object-position: left top;
}
+@keyframes postBodyPreviewOut {
+ 0%, 62% { opacity: 1; }
+ 78%, 100% { opacity: 0; }
+}
+
+@keyframes postBodyDetailIn {
+ 0%, 62% { opacity: 0; }
+ 78%, 100% { opacity: 1; }
+}
+
html.post-view-transition::view-transition-new(post-detail-controls),
html.post-view-transition::view-transition-new(post-detail-signature) {
animation: detailOnlyPartIn 0.22s 0.62s ease-out both;
diff --git a/components/AdminPage.js b/components/AdminPage.js
index 465b779..65a7753 100644
--- a/components/AdminPage.js
+++ b/components/AdminPage.js
@@ -11,6 +11,7 @@ import AdminLinks from './admin/AdminLinks';
import AdminForumSettings from './admin/AdminForumSettings';
import AdminCustomPages from './admin/AdminCustomPages';
import AdminCustomCss from './admin/AdminCustomCss';
+import AdminMailSettings from './admin/AdminMailSettings';
const NAV = [
{ key: 'reports', labelKey: 'admin.reports', icon: 'shieldAlert' },
@@ -18,6 +19,7 @@ const NAV = [
{ key: 'logs', labelKey: 'admin.logs', icon: 'file' },
{ key: 'links', labelKey: 'admin.links', icon: 'link' },
{ key: 'settings', labelKey: 'admin.forumSettings', icon: 'settings' },
+ { key: 'mail', labelKey: 'admin.mail', icon: 'message' },
{ key: 'custom', labelKey: 'admin.customPages', icon: 'file' },
{ key: 'css', labelKey: 'admin.customCss', icon: 'file' },
];
@@ -123,6 +125,7 @@ export default function AdminPage() {
if (tab === 'links') return