Enforce database concurrency invariants
This commit is contained in:
1 parent
145f13fee5
commit
924f9ffcc6
6 files changed
+114
-31
No files matched your search
@@ -86,6 +86,7 @@ psql -U forumlify -d forumlify -f schema.sql
|
||||
| `JWT_SECRET` | 本地开发使用内置值 | JWT 签名密钥;`NODE_ENV=production` 时必须显式设置 |
|
||||
| `ALLOWED_ORIGINS` | 空 | 允许跨域访问的来源,多个值用逗号分隔;为空时仅支持同源访问 |
|
||||
| `TRUST_PROXY` | `false` | 位于可信反向代理后时设为 `true`,用于正确识别限流 IP |
|
||||
| `ADMIN_BOOTSTRAP_TOKEN` | 空 | 首次部署时设置强随机值;注册页填写相同值可创建唯一初始管理员,初始化后应删除该变量 |
|
||||
|
||||
4. **启动**
|
||||
|
||||
|
||||
@@ -362,6 +362,7 @@
|
||||
<input type="text" id="regUsername" placeholder="用户名" />
|
||||
<input type="email" id="regEmail" placeholder="邮箱" />
|
||||
<input type="password" id="regPassword" placeholder="密码(至少6位)" />
|
||||
<input type="password" id="regBootstrapToken" placeholder="管理员初始化令牌(仅首次部署,可选)" autocomplete="off" />
|
||||
<div class="captcha-row">
|
||||
<span id="regCaptchaQuestion">3 + 5 = ?</span>
|
||||
<input type="text" id="regCaptchaInput" placeholder="答案" style="width:80px;" />
|
||||
|
||||
@@ -35,10 +35,10 @@ const API = {
|
||||
return data;
|
||||
},
|
||||
|
||||
async register(email, password, username) {
|
||||
async register(email, password, username, bootstrapToken = '') {
|
||||
const data = await apiFetch('/auth/register', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ email, password, username })
|
||||
body: JSON.stringify({ email, password, username, bootstrap_token: bootstrapToken || undefined })
|
||||
});
|
||||
if (data.error) throw new Error(data.error);
|
||||
return data;
|
||||
|
||||
+3
-1
@@ -42,13 +42,14 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
||||
const username = document.getElementById('regUsername').value.trim();
|
||||
const email = document.getElementById('regEmail').value.trim();
|
||||
const password = document.getElementById('regPassword').value;
|
||||
const bootstrapToken = document.getElementById('regBootstrapToken').value.trim();
|
||||
const captchaInput = document.getElementById('regCaptchaInput').value.trim();
|
||||
const captchaAnswer = parseInt(document.getElementById('regCaptchaInput').dataset.answer);
|
||||
if (!username || !email || !password) { alert('请填写完整信息'); return; }
|
||||
if (password.length < 6) { alert('密码至少6位'); return; }
|
||||
if (parseInt(captchaInput) !== captchaAnswer) { alert('验证码错误,请重新计算'); refreshCaptcha('reg'); return; }
|
||||
try {
|
||||
await API.register(email, password, username);
|
||||
await API.register(email, password, username, bootstrapToken);
|
||||
} catch (err) {
|
||||
alert('注册失败:' + err.message);
|
||||
return;
|
||||
@@ -58,6 +59,7 @@ document.getElementById('registerSubmit').addEventListener('click', async () =>
|
||||
document.getElementById('regUsername').value = '';
|
||||
document.getElementById('regEmail').value = '';
|
||||
document.getElementById('regPassword').value = '';
|
||||
document.getElementById('regBootstrapToken').value = '';
|
||||
document.getElementById('regCaptchaInput').value = '';
|
||||
|
||||
try {
|
||||
|
||||
+64
@@ -112,6 +112,7 @@ CREATE TABLE IF NOT EXISTS conversations (
|
||||
user2_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
last_message_at TIMESTAMPTZ DEFAULT now(),
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
CHECK (user1_id < user2_id),
|
||||
UNIQUE(user1_id, user2_id)
|
||||
);
|
||||
|
||||
@@ -202,6 +203,69 @@ CREATE INDEX IF NOT EXISTS idx_posts_is_pinned ON posts(is_pinned);
|
||||
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS signature TEXT DEFAULT '';
|
||||
|
||||
-- Canonicalize conversation pairs and merge any pre-existing reverse/duplicate
|
||||
-- conversations before enforcing one row per unordered user pair.
|
||||
ALTER TABLE conversations DROP CONSTRAINT IF EXISTS conversations_user1_id_user2_id_key;
|
||||
ALTER TABLE conversations DROP CONSTRAINT IF EXISTS conversations_canonical_pair;
|
||||
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
id,
|
||||
FIRST_VALUE(id) OVER (
|
||||
PARTITION BY LEAST(user1_id, user2_id), GREATEST(user1_id, user2_id)
|
||||
ORDER BY created_at, id
|
||||
) AS keep_id
|
||||
FROM conversations
|
||||
)
|
||||
UPDATE messages AS m
|
||||
SET conversation_id = ranked.keep_id
|
||||
FROM ranked
|
||||
WHERE m.conversation_id = ranked.id
|
||||
AND ranked.id <> ranked.keep_id;
|
||||
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY LEAST(user1_id, user2_id), GREATEST(user1_id, user2_id)
|
||||
ORDER BY created_at, id
|
||||
) AS row_number
|
||||
FROM conversations
|
||||
)
|
||||
DELETE FROM conversations AS c
|
||||
USING ranked
|
||||
WHERE c.id = ranked.id AND ranked.row_number > 1;
|
||||
|
||||
UPDATE conversations
|
||||
SET user1_id = LEAST(user1_id, user2_id),
|
||||
user2_id = GREATEST(user1_id, user2_id);
|
||||
|
||||
ALTER TABLE conversations
|
||||
ADD CONSTRAINT conversations_canonical_pair CHECK (user1_id < user2_id);
|
||||
ALTER TABLE conversations
|
||||
ADD CONSTRAINT conversations_user1_id_user2_id_key UNIQUE (user1_id, user2_id);
|
||||
|
||||
-- Keep one pending report per reporter/post at the database layer. Historical
|
||||
-- duplicates are rejected before creating the partial unique index.
|
||||
WITH duplicates AS (
|
||||
SELECT id, ROW_NUMBER() OVER (
|
||||
PARTITION BY post_id, reporter_id
|
||||
ORDER BY created_at, id
|
||||
) AS row_number
|
||||
FROM reports
|
||||
WHERE status = 'pending' AND post_id IS NOT NULL
|
||||
)
|
||||
UPDATE reports AS r
|
||||
SET status = 'rejected',
|
||||
handled_at = COALESCE(r.handled_at, NOW()),
|
||||
handler_note = COALESCE(r.handler_note, '重复举报已自动合并')
|
||||
FROM duplicates
|
||||
WHERE r.id = duplicates.id AND duplicates.row_number > 1;
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_reports_unique_pending
|
||||
ON reports(post_id, reporter_id)
|
||||
WHERE status = 'pending' AND post_id IS NOT NULL;
|
||||
|
||||
-- ============================================================
|
||||
-- 论坛默认设置
|
||||
-- ============================================================
|
||||
|
||||
@@ -13,6 +13,7 @@ const { Pool } = require('pg');
|
||||
const multer = require('multer');
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const app = express();
|
||||
|
||||
@@ -170,9 +171,17 @@ app.put('/api/settings', auth, admin, async (req, res) => {
|
||||
// 认证接口
|
||||
// ============================================================
|
||||
|
||||
// 注册 - 第一个用户自动成为管理员
|
||||
function secureTokenMatch(provided, expected) {
|
||||
if (!provided || !expected) return false;
|
||||
const providedBuffer = Buffer.from(String(provided));
|
||||
const expectedBuffer = Buffer.from(String(expected));
|
||||
return providedBuffer.length === expectedBuffer.length &&
|
||||
crypto.timingSafeEqual(providedBuffer, expectedBuffer);
|
||||
}
|
||||
|
||||
// 注册;管理员只能使用部署时配置的一次性引导令牌创建
|
||||
app.post('/api/auth/register', async (req, res) => {
|
||||
const { email, password, username } = req.body;
|
||||
const { email, password, username, bootstrap_token } = req.body;
|
||||
|
||||
if (!email || !password || !username) {
|
||||
return res.status(400).json({ error: '请填写完整信息' });
|
||||
@@ -181,31 +190,49 @@ app.post('/api/auth/register', async (req, res) => {
|
||||
return res.status(400).json({ error: '密码至少6位' });
|
||||
}
|
||||
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
|
||||
let client;
|
||||
try {
|
||||
const countResult = await pool.query('SELECT COUNT(*) FROM users');
|
||||
const isFirstUser = parseInt(countResult.rows[0].count) === 0;
|
||||
client = await pool.connect();
|
||||
await client.query('BEGIN');
|
||||
await client.query("SELECT pg_advisory_xact_lock(hashtext('forumlify-admin-bootstrap'))");
|
||||
const adminResult = await client.query("SELECT EXISTS(SELECT 1 FROM users WHERE role = 'admin') AS exists");
|
||||
const hasAdmin = adminResult.rows[0].exists;
|
||||
const requestedBootstrap = Boolean(bootstrap_token);
|
||||
const validBootstrap = secureTokenMatch(bootstrap_token, process.env.ADMIN_BOOTSTRAP_TOKEN);
|
||||
|
||||
const hash = await bcrypt.hash(password, 10);
|
||||
const avatar = 'https://ui-avatars.com/api/?name=' + encodeURIComponent(username) + '&background=6366f1&color=fff&size=64';
|
||||
const role = isFirstUser ? 'admin' : 'user';
|
||||
if (requestedBootstrap && !validBootstrap) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(403).json({ error: '管理员初始化令牌无效' });
|
||||
}
|
||||
if (validBootstrap && hasAdmin) {
|
||||
await client.query('ROLLBACK');
|
||||
return res.status(409).json({ error: '管理员已初始化' });
|
||||
}
|
||||
|
||||
const r = await pool.query(
|
||||
const role = validBootstrap && !hasAdmin ? 'admin' : 'user';
|
||||
const r = await client.query(
|
||||
`INSERT INTO users (email, password_hash, username, avatar_url, role, signature)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING id, username, avatar_url, role, signature, created_at`,
|
||||
[email, hash, username, avatar, role, '']
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
|
||||
res.json({
|
||||
user: r.rows[0],
|
||||
message: isFirstUser ? '🎉 你是第一个用户,已自动设为管理员!' : '注册成功'
|
||||
message: role === 'admin' ? '管理员初始化成功' : '注册成功'
|
||||
});
|
||||
} catch (err) {
|
||||
if (client) await client.query('ROLLBACK').catch(() => {});
|
||||
if (err.code === '23505') {
|
||||
res.status(400).json({ error: '邮箱或用户名已被注册' });
|
||||
} else {
|
||||
res.status(500).json({ error: '注册失败,请稍后重试' });
|
||||
}
|
||||
} finally {
|
||||
if (client) client.release();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -779,14 +806,6 @@ app.post('/api/reports', auth, async (req, res) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const existing = await pool.query(
|
||||
'SELECT id FROM reports WHERE post_id = $1 AND reporter_id = $2 AND status = $3',
|
||||
[post_id, req.user.id, 'pending']
|
||||
);
|
||||
if (existing.rows.length > 0) {
|
||||
return res.status(400).json({ error: '你已经举报过此帖子,请等待处理' });
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO reports (post_id, reporter_id, reason)
|
||||
VALUES ($1, $2, $3)`,
|
||||
@@ -794,6 +813,9 @@ app.post('/api/reports', auth, async (req, res) => {
|
||||
);
|
||||
res.json({ success: true });
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
return res.status(409).json({ error: '你已经举报过此帖子,请等待处理' });
|
||||
}
|
||||
res.status(500).json({ error: '举报失败,请稍后重试' });
|
||||
}
|
||||
});
|
||||
@@ -1108,7 +1130,7 @@ app.post('/api/conversations', auth, async (req, res) => {
|
||||
if (!other_user_id) {
|
||||
return res.status(400).json({ error: '缺少对方用户ID' });
|
||||
}
|
||||
if (other_user_id === req.user.id) {
|
||||
if (String(other_user_id).toLowerCase() === String(req.user.id).toLowerCase()) {
|
||||
return res.status(400).json({ error: '不能与自己私信' });
|
||||
}
|
||||
|
||||
@@ -1118,18 +1140,11 @@ app.post('/api/conversations', auth, async (req, res) => {
|
||||
return res.status(404).json({ error: '用户不存在' });
|
||||
}
|
||||
|
||||
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)
|
||||
`, [req.user.id, other_user_id]);
|
||||
|
||||
if (existing.rows.length > 0) {
|
||||
return res.json({ id: existing.rows[0].id });
|
||||
}
|
||||
|
||||
const r = await pool.query(`
|
||||
INSERT INTO conversations (user1_id, user2_id)
|
||||
VALUES ($1, $2)
|
||||
SELECT 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
|
||||
`, [req.user.id, other_user_id]);
|
||||
|
||||
|
||||
Reference in new issue
Block a user