feat: 后端 SQLite→PostgreSQL 迁移(双驱动)——codes/showcase/sync/chibi/payment/security 全链路支持 pg,修复 grant 保留字,schema 双 DDL 导出

This commit is contained in:
Sisyphus committed 2026-08-19 19:12:26 +08:00
1 parent 346f41d391
commit 605af4cdd3
17 files changed
+1516 -2202

No files matched your search

+154 -44
View File
@@ -1,4 +1,5 @@
import type Database from "better-sqlite3";
import type { Db, PgDb, SqliteDb } from "../db/index.js";
import { isPgDb } from "../db/index.js";
/**
* 兑换码防刷检测(防滥用)。
@@ -30,13 +31,42 @@ const DISTINCT_IP_WINDOW_HOURS = 24;
/** 无效尝试统计窗口(分钟) */
const FAIL_WINDOW_MINUTES = 10;
/**
* 记录一条安全事件(IP 追踪)。
* @param ip 来源 IP,可空(如禁用事件无来源)
* @param code 涉及/尝试的兑换码(未规范化的原值由调用方负责 normalize)
*/
export function logSecurityEvent(
db: Database.Database,
/** 时间窗口的两种方言表达。 */
const DISTINCT_IP_SQL = {
sqlite: `SELECT COUNT(DISTINCT ip) AS c FROM security_events
WHERE code = ? AND event_type = 'redeem_ok'
AND created_at >= datetime('now', ?)`,
pg: `SELECT COUNT(DISTINCT ip)::int AS c FROM security_events
WHERE code = $1 AND event_type = 'redeem_ok'
AND created_at >= now() - ($2)::interval`,
};
const FAIL_IP_SQL = {
sqlite: `SELECT COUNT(*) AS c FROM security_events
WHERE ip = ? AND event_type = 'redeem_fail'
AND created_at >= datetime('now', ?)`,
pg: `SELECT COUNT(*)::int AS c FROM security_events
WHERE ip = $1 AND event_type = 'redeem_fail'
AND created_at >= now() - ($2)::interval`,
};
const FAIL_GROUP_SQL = {
sqlite: `SELECT ip FROM security_events
WHERE code = ? AND event_type = 'redeem_fail'
AND created_at >= datetime('now', ?)
GROUP BY ip HAVING COUNT(*) > ? LIMIT 1`,
pg: `SELECT ip FROM security_events
WHERE code = $1 AND event_type = 'redeem_fail'
AND created_at >= now() - ($2)::interval
GROUP BY ip HAVING COUNT(*) > $3 LIMIT 1`,
};
type MaybePromise<T> = T | Promise<T>;
// ---------------------------------------------------------------------------
// SQLite 实现(同步,测试路径)
// ---------------------------------------------------------------------------
function logSecurityEventSqlite(
db: SqliteDb,
ip: string | null,
code: string,
action: SecurityAction,
@@ -50,24 +80,11 @@ export function logSecurityEvent(
);
}
/**
* 检测兑换码是否存在滥用行为。
*
* @param db 数据库实例
* @param code 兑换码(已规范化)
* @param ip 当前请求来源 IP(可选)。提供时同时校验"同一 IP 无效尝试"规则;
* 不提供时退化为按该兑换码分组统计。
* @returns 判定为滥用返回 true
*/
export function detectAbuse(db: Database.Database, code: string, ip?: string): boolean {
function detectAbuseSqlite(db: SqliteDb, code: string, ip?: string): boolean {
// 规则 1:同一兑换码 24h 内被超过 5 个不同 IP 兑换
const distinct = db
.prepare(
`SELECT COUNT(DISTINCT ip) AS c FROM security_events
WHERE code = ? AND event_type = 'redeem_ok'
AND created_at >= datetime('now', ?)`,
)
.get(code, `-${DISTINCT_IP_WINDOW_HOURS} hours`) as { c: number };
const distinct = db.prepare(DISTINCT_IP_SQL.sqlite).get(code, `-${DISTINCT_IP_WINDOW_HOURS} hours`) as {
c: number;
};
if (distinct.c > MAX_DISTINCT_IPS_PER_CODE) {
return true;
}
@@ -75,11 +92,7 @@ export function detectAbuse(db: Database.Database, code: string, ip?: string): b
// 规则 2:同一 IP 10 分钟内无效兑换码尝试超过 50 次
if (ip !== undefined && ip !== "") {
const failed = db
.prepare(
`SELECT COUNT(*) AS c FROM security_events
WHERE ip = ? AND event_type = 'redeem_fail'
AND created_at >= datetime('now', ?)`,
)
.prepare(FAIL_IP_SQL.sqlite)
.get(ip, `-${FAIL_WINDOW_MINUTES} minutes`) as { c: number };
if (failed.c > MAX_FAILED_ATTEMPTS_PER_IP) {
return true;
@@ -89,26 +102,123 @@ export function detectAbuse(db: Database.Database, code: string, ip?: string): b
// 未提供 IP 时:按该兑换码分组的失败尝试是否有人超限
const badIp = db
.prepare(
`SELECT ip FROM security_events
WHERE code = ? AND event_type = 'redeem_fail'
AND created_at >= datetime('now', ?)
GROUP BY ip HAVING COUNT(*) > ? LIMIT 1`,
)
.prepare(FAIL_GROUP_SQL.sqlite)
.get(code, `-${FAIL_WINDOW_MINUTES} minutes`, MAX_FAILED_ATTEMPTS_PER_IP);
return badIp !== undefined;
}
/**
* 确认滥用后将兑换码禁用并记录安全事件。
*
* @param code 兑换码(已规范化);不存在时静默(UPDATE 影响 0 行)
* @returns 是否实际更新了兑换码状态(false 表示兑换码不存在或已禁用)
*/
export function markSuspicious(db: Database.Database, code: string): boolean {
function markSuspiciousSqlite(db: SqliteDb, code: string): boolean {
const result = db
.prepare("UPDATE codes SET status = 'disabled' WHERE code = ? AND status != 'disabled'")
.run(code);
logSecurityEvent(db, null, code, "disable", "code_disabled");
logSecurityEventSqlite(db, null, code, "disable", "code_disabled");
return result.changes > 0;
}
// ---------------------------------------------------------------------------
// PostgreSQL 实现(异步,生产路径)
// ---------------------------------------------------------------------------
async function logSecurityEventPg(
db: PgDb,
ip: string | null,
code: string,
action: SecurityAction,
eventType: SecurityEventType,
): Promise<void> {
await db.query(
"INSERT INTO security_events (ip, code, action, event_type) VALUES ($1, $2, $3, $4)",
[ip, code, action, eventType],
);
}
async function detectAbusePg(db: PgDb, code: string, ip?: string): Promise<boolean> {
// 规则 1
const distinct = await db.query<{ c: number }>(DISTINCT_IP_SQL.pg, [
code,
`${DISTINCT_IP_WINDOW_HOURS} hours`,
]);
if ((distinct.rows[0]?.c ?? 0) > MAX_DISTINCT_IPS_PER_CODE) {
return true;
}
// 规则 2
if (ip !== undefined && ip !== "") {
const failed = await db.query<{ c: number }>(FAIL_IP_SQL.pg, [
ip,
`${FAIL_WINDOW_MINUTES} minutes`,
]);
if ((failed.rows[0]?.c ?? 0) > MAX_FAILED_ATTEMPTS_PER_IP) {
return true;
}
return false;
}
// 未提供 IP 时按兑换码分组
const badIp = await db.query<{ ip: string | null }>(FAIL_GROUP_SQL.pg, [
code,
`${FAIL_WINDOW_MINUTES} minutes`,
MAX_FAILED_ATTEMPTS_PER_IP,
]);
return badIp.rows[0] !== undefined;
}
async function markSuspiciousPg(db: PgDb, code: string): Promise<boolean> {
const result = await db.query(
"UPDATE codes SET status = 'disabled' WHERE code = $1 AND status != 'disabled'",
[code],
);
await logSecurityEventPg(db, null, code, "disable", "code_disabled");
return (result.rowCount ?? 0) > 0;
}
// ---------------------------------------------------------------------------
// 公共 Dispatcher
// ---------------------------------------------------------------------------
export function logSecurityEvent(
db: SqliteDb,
ip: string | null,
code: string,
action: SecurityAction,
eventType: SecurityEventType,
): void;
export function logSecurityEvent(
db: PgDb,
ip: string | null,
code: string,
action: SecurityAction,
eventType: SecurityEventType,
): Promise<void>;
export function logSecurityEvent(
db: Db,
ip: string | null,
code: string,
action: SecurityAction,
eventType: SecurityEventType,
): MaybePromise<void>;
export function logSecurityEvent(
db: Db,
ip: string | null,
code: string,
action: SecurityAction,
eventType: SecurityEventType,
): MaybePromise<void> {
return isPgDb(db)
? logSecurityEventPg(db, ip, code, action, eventType)
: logSecurityEventSqlite(db, ip, code, action, eventType);
}
export function detectAbuse(db: SqliteDb, code: string, ip?: string): boolean;
export function detectAbuse(db: PgDb, code: string, ip?: string): Promise<boolean>;
export function detectAbuse(db: Db, code: string, ip?: string): MaybePromise<boolean>;
export function detectAbuse(db: Db, code: string, ip?: string): MaybePromise<boolean> {
return isPgDb(db) ? detectAbusePg(db, code, ip) : detectAbuseSqlite(db, code, ip);
}
export function markSuspicious(db: SqliteDb, code: string): boolean;
export function markSuspicious(db: PgDb, code: string): Promise<boolean>;
export function markSuspicious(db: Db, code: string): MaybePromise<boolean>;
export function markSuspicious(db: Db, code: string): MaybePromise<boolean> {
return isPgDb(db) ? markSuspiciousPg(db, code) : markSuspiciousSqlite(db, code);
}