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

+160 -3
View File
@@ -8,8 +8,10 @@
"name": "perler-lab-server",
"version": "1.0.0",
"dependencies": {
"@types/pg": "^8.23.1",
"better-sqlite3": "^11.7.0",
"express": "^4.21.0"
"express": "^4.21.0",
"pg": "^8.23.0"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.12",
@@ -990,12 +992,22 @@
"version": "26.2.0",
"resolved": "https://registry.npmmirror.com/@types/node/-/node-26.2.0.tgz",
"integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.3.0"
}
},
"node_modules/@types/pg": {
"version": "8.23.1",
"resolved": "https://registry.npmmirror.com/@types/pg/-/pg-8.23.1.tgz",
"integrity": "sha512-fKVHpikPdg4GKks3JuLEhvwSyvwzF23hnabPy6DD8ljVbC7+6J5dQzdv4arV6jqq57djnMgs1HKBxX4P8aBI3A==",
"license": "MIT",
"dependencies": {
"@types/node": "*",
"pg-protocol": "*",
"pg-types": "^2.2.0"
}
},
"node_modules/@types/qs": {
"version": "6.15.1",
"resolved": "https://registry.npmmirror.com/@types/qs/-/qs-6.15.1.tgz",
@@ -2284,6 +2296,95 @@
"node": ">= 14.16"
}
},
"node_modules/pg": {
"version": "8.23.0",
"resolved": "https://registry.npmmirror.com/pg/-/pg-8.23.0.tgz",
"integrity": "sha512-Ip2EQCngowJLGOfCwkFhPXU7/ljlhn6Rxlmy4XYfL2Y+vyRM59+8uR2xqRWKdYmbXmxCFOAmKxBuSUCdF34qLg==",
"license": "MIT",
"dependencies": {
"pg-connection-string": "^2.14.0",
"pg-pool": "^3.14.0",
"pg-protocol": "^1.16.0",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.4.0"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-cloudflare": {
"version": "1.4.0",
"resolved": "https://registry.npmmirror.com/pg-cloudflare/-/pg-cloudflare-1.4.0.tgz",
"integrity": "sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
"version": "2.14.0",
"resolved": "https://registry.npmmirror.com/pg-connection-string/-/pg-connection-string-2.14.0.tgz",
"integrity": "sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==",
"license": "MIT"
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/pg-pool": {
"version": "3.14.0",
"resolved": "https://registry.npmmirror.com/pg-pool/-/pg-pool-3.14.0.tgz",
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.16.0",
"resolved": "https://registry.npmmirror.com/pg-protocol/-/pg-protocol-1.16.0.tgz",
"integrity": "sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmmirror.com/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmmirror.com/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.1.1.tgz",
@@ -2320,6 +2421,45 @@
"node": "^10 || ^12 || >=14"
}
},
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmmirror.com/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmmirror.com/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/prebuild-install": {
"version": "7.1.2",
"resolved": "https://registry.npmmirror.com/prebuild-install/-/prebuild-install-7.1.2.tgz",
@@ -2707,6 +2847,15 @@
"node": ">=0.10.0"
}
},
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmmirror.com/split2/-/split2-4.2.0.tgz",
"integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==",
"license": "ISC",
"engines": {
"node": ">= 10.x"
}
},
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmmirror.com/stackback/-/stackback-0.0.2.tgz",
@@ -2975,7 +3124,6 @@
"version": "8.3.0",
"resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
"dev": true,
"license": "MIT"
},
"node_modules/unpipe": {
@@ -3662,6 +3810,15 @@
"resolved": "https://registry.npmmirror.com/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmmirror.com/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
}
}
}
+3 -1
View File
@@ -12,8 +12,10 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@types/pg": "^8.23.1",
"better-sqlite3": "^11.7.0",
"express": "^4.21.0"
"express": "^4.21.0",
"pg": "^8.23.0"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.12",
+20 -36
View File
@@ -5,7 +5,7 @@
* 组装提示词 -> 调用 OpenAI 兼容图像接口 (AI_IMAGE_API_URL /
* AI_IMAGE_API_KEY),未配置接口地址时使用内置 mock 模式生成占位图。
*/
import type Database from "better-sqlite3";
import type { Db } from "../db/index.js";
import { deflateSync } from "node:zlib";
import type { AccessInfo } from "../types/index.js";
import { consumeCode, CodeError, createDownloadGrant } from "../codes/service.js";
@@ -52,7 +52,7 @@ export class ChibiError extends Error {
}
// ---------------------------------------------------------------------------
// Mock 占位图 (纯函数实现的最小合法 PNG: 纯色 RGB + gridSize 尺寸)
// Mock 占位图
// ---------------------------------------------------------------------------
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
@@ -89,14 +89,13 @@ function pngChunk(type: string, data: Buffer): Buffer {
/** 生成 size×size 纯色 PNG,返回 base64 dataURL。 */
function makePlaceholderPng(size: number, rgb: readonly [number, number, number]): string {
const ihdr = Buffer.alloc(13);
ihdr.writeUInt32BE(size, 0); // width
ihdr.writeUInt32BE(size, 4); // height
ihdr.writeUInt8(8, 8); // bit depth
ihdr.writeUInt8(2, 9); // color type: truecolor RGB
// bytes 10/11/12: compression / filter / interlace,默认 0
ihdr.writeUInt32BE(size, 0);
ihdr.writeUInt32BE(size, 4);
ihdr.writeUInt8(8, 8);
ihdr.writeUInt8(2, 9);
const row = Buffer.alloc(1 + size * 3);
row.writeUInt8(0, 0); // filter: none
row.writeUInt8(0, 0);
for (let x = 0; x < size; x++) {
row.writeUInt8(rgb[0], 1 + x * 3);
row.writeUInt8(rgb[1], 2 + x * 3);
@@ -112,25 +111,18 @@ function makePlaceholderPng(size: number, rgb: readonly [number, number, number]
return `data:image/png;base64,${png.toString("base64")}`;
}
/** 每类一个主题色,mock 模式下占位图随分类变色,便于肉眼区分。 */
const CATEGORY_COLORS: Record<ChibiCategory, readonly [number, number, number]> = {
landscape: [96, 165, 250], // 天空蓝
person: [251, 146, 60], // 活力橙
pet: [167, 139, 250], // 香芋紫
object: [52, 211, 153], // 抹茶绿
food: [251, 113, 133], // 蜜桃粉
landscape: [96, 165, 250],
person: [251, 146, 60],
pet: [167, 139, 250],
object: [52, 211, 153],
food: [251, 113, 133],
};
// ---------------------------------------------------------------------------
// AI 接口调用 (OpenAI 兼容)
// AI 接口调用
// ---------------------------------------------------------------------------
/**
* 从 OpenAI 兼容响应中提取 base64 (或图像 url)。
* 支持两种形态:
* /v1/images/generations -> { data: [{ b64_json | url }] }
* /v1/chat/completions -> { choices: [{ message: { images: [{ b64_json | url }] } }] }
*/
function extractImageBase64(payload: unknown): string | null {
if (!payload || typeof payload !== "object") return null;
const root = payload as Record<string, unknown>;
@@ -161,7 +153,6 @@ async function requestAiImage(prompt: string, req: GenerateRequest): Promise<str
const headers: Record<string, string> = { "Content-Type": "application/json" };
if (apiKey) headers["Authorization"] = `Bearer ${apiKey}`;
// chat/completions 走多模态消息 (携带原图/参考图),images/generations 走纯提示词
const isChat = (apiUrl ?? "").includes("/chat/completions");
let payload: unknown;
if (isChat) {
@@ -205,7 +196,6 @@ async function requestAiImage(prompt: string, req: GenerateRequest): Promise<str
throw new ChibiError("AI 图像生成失败,请稍后重试", 502);
}
if (b64OrUrl.startsWith("http://") || b64OrUrl.startsWith("https://")) {
// 接口返回 url 时下载并转为 base64 dataURL
let imgRes: Awaited<ReturnType<typeof fetch>>;
try {
imgRes = await fetch(b64OrUrl, { signal: AbortSignal.timeout(60_000) });
@@ -223,10 +213,6 @@ async function requestAiImage(prompt: string, req: GenerateRequest): Promise<str
return b64OrUrl.startsWith("data:") ? b64OrUrl : `data:image/png;base64,${b64OrUrl}`;
}
/**
* 生成图像。未配置 AI_IMAGE_API_URL 时进入 mock 模式,返回 gridSize
* 尺寸的纯色占位 PNG (dataURL)。
*/
async function generateImage(prompt: string, req: GenerateRequest): Promise<string> {
const apiUrl = process.env["AI_IMAGE_API_URL"];
if (!apiUrl) {
@@ -240,11 +226,10 @@ async function generateImage(prompt: string, req: GenerateRequest): Promise<stri
// ---------------------------------------------------------------------------
/**
* 生成 chibi 拼豆图。先原子消耗一次兑换码次数(无剩余次数时抛出
* ChibiError "生成次数不足", 402),再调用 AI 接口。
* 生成 chibi 拼豆图。先原子消耗一次兑换码次数,再调用 AI 接口。
*/
export async function generateChibiImage(
db: Database.Database,
db: Db,
req: GenerateRequest,
): Promise<GenerateOutcome> {
// 1. 组装提示词
@@ -259,13 +244,12 @@ export async function generateChibiImage(
hasReferenceImage: req.referenceImage !== undefined && req.referenceImage !== "",
});
// 2. 消耗一次次数 (原子校验 + 扣减)
// 2. 消耗一次次数
let access: AccessInfo;
try {
access = consumeCode(db, req.code);
access = await consumeCode(db, req.code);
} catch (err) {
if (err instanceof CodeError) {
// 未找到 / 禁用 / 过期 / 用尽 统一视为无法生成
throw new ChibiError("生成次数不足", 402);
}
throw err;
@@ -274,8 +258,8 @@ export async function generateChibiImage(
// 3. 生成图片
const image = await generateImage(prompt, req);
// 4. 写入一次性下载授权凭证(下载时必须携带,防止绕过生成直接消耗次数)
const downloadGrant = createDownloadGrant(db, req.code);
// 4. 写入一次性下载授权凭证
const downloadGrant = await createDownloadGrant(db, req.code);
return { image, downloadGrant, access };
}
}
+7 -14
View File
@@ -1,6 +1,6 @@
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import type { Db } from "../db/index.js";
import { getDb } from "../db/index.js";
import { generateChibiImage, ChibiError, type GenerateRequest } from "./generate.js";
import { findTemplate, type ChibiCategory, type Composition } from "./prompts.js";
@@ -9,8 +9,8 @@ import { createRateLimiter, RATE_LIMITS } from "../security/rate-limit.js";
const CATEGORIES: readonly ChibiCategory[] = ["landscape", "person", "pet", "object", "food"];
const COMPOSITIONS: readonly Composition[] = ["主体特写", "半幅构图", "完整构图"];
/** Resolve the database instance: injected DB for tests, else global singleton. */
function resolveDb(injected?: Database.Database): Database.Database {
/** Resolve the database instance. */
function resolveDb(injected?: Db): Db {
return injected ?? getDb();
}
@@ -21,22 +21,18 @@ function resolveDb(injected?: Database.Database): Database.Database {
* Request: { code, image, referenceImage?, category, subtype, gridSize,
* colorCount, composition, detailTags, customPrompt? }
* Response: 200 { image, access, downloadGrant }
* 400 参数错误 (中文提示)
* 402 { error: "生成次数不足" }
* 500 服务器内部错误
* 502 AI 图像生成失败
* 400 / 402 / 500 / 502
*/
export function createChibiRouter(injectedDb?: Database.Database): Router {
export function createChibiRouter(injectedDb?: Db): Router {
const router = Router();
// 防刷限流:AI 生成 10 次/小时/IP(每路由实例独立计数,测试互不干扰)
// 防刷限流
const chibiLimiter = createRateLimiter(RATE_LIMITS.chibiGenerate)("chibi_generate");
router.post("/generate", chibiLimiter, async (req: Request, res: Response): Promise<void> => {
try {
const body = (req.body ?? {}) as Record<string, unknown>;
// ---- 基础字段校验 ----
const code = typeof body.code === "string" ? body.code : "";
if (!code) {
res.status(400).json({ error: "请输入兑换码" });
@@ -52,7 +48,6 @@ export function createChibiRouter(injectedDb?: Database.Database): Router {
? body.referenceImage
: undefined;
// ---- 分类 / 细分模板 ----
const category = body.category as ChibiCategory;
if (!CATEGORIES.includes(category)) {
res.status(400).json({ error: "未知的分类" });
@@ -66,7 +61,6 @@ export function createChibiRouter(injectedDb?: Database.Database): Router {
return;
}
// ---- 构图 / 网格 / 颜色 ----
const composition = body.composition as Composition;
if (!COMPOSITIONS.includes(composition)) {
res.status(400).json({ error: "未知的构图方式" });
@@ -83,7 +77,6 @@ export function createChibiRouter(injectedDb?: Database.Database): Router {
return;
}
// ---- 细节标签 / 自定义提示词 ----
const detailTags = Array.isArray(body.detailTags)
? body.detailTags.filter((t): t is string => typeof t === "string")
: [];
@@ -122,4 +115,4 @@ export function createChibiRouter(injectedDb?: Database.Database): Router {
});
return router;
}
}
+19 -41
View File
@@ -1,6 +1,6 @@
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import type { Db } from "../db/index.js";
import { getDb } from "../db/index.js";
import { consumeCodeWithGrant, redeemCode, getCodeStatus, CodeError, ERRORS, normalizeCode } from "./service.js";
import { createRateLimiter, RATE_LIMITS } from "../security/rate-limit.js";
@@ -17,14 +17,14 @@ function handleCodeError(res: Response, err: CodeError): void {
* Resolve the database instance: use injected DB if provided, otherwise
* fall back to the global singleton.
*/
function resolveDb(injected?: Database.Database): Database.Database {
function resolveDb(injected?: Db): Db {
return injected ?? getDb();
}
/**
* Create the codes router. Accepts an optional injected database for testing.
*/
export function createCodesRouter(injectedDb?: Database.Database): Router {
export function createCodesRouter(injectedDb?: Db): Router {
const router = Router();
// 防刷限流(每路由实例独立计数,测试互不干扰)
@@ -35,17 +35,9 @@ export function createCodesRouter(injectedDb?: Database.Database): Router {
* POST /api/codes/redeem
*
* Redeem a code: validate it is active, has remaining uses, and log the
* redemption event. Returns the access info (code, packageType,
* remainingUses, totalUses).
*
* Request: { code: string }
* Response: 200 { access: AccessInfo }
* 404 { error: "兑换码不存在,请检查后重试" }
* 400 { error: "兑换码已用尽" }
* 403 { error: "检测到异常操作,请联系客服" } (防刷)
* 429 { error: "操作过于频繁,请稍后再试" } (限流)
* redemption event. Returns the access info.
*/
router.post("/redeem", redeemLimiter, (req: Request, res: Response): void => {
router.post("/redeem", redeemLimiter, async (req: Request, res: Response): Promise<void> => {
try {
const { code } = req.body as { code?: string };
if (!code || typeof code !== "string") {
@@ -53,18 +45,18 @@ export function createCodesRouter(injectedDb?: Database.Database): Router {
return;
}
const db = resolveDb(injectedDb);
const access = redeemCode(db, normalizeCode(code));
// 记录兑换成功事件(携带来源 IP,用于多 IP 共享码检测)
logSecurityEvent(db, req.ip ?? null, access.code, "redeem", "redeem_ok");
if (detectAbuse(db, access.code, req.ip)) {
markSuspicious(db, access.code);
const access = await redeemCode(db, normalizeCode(code));
// 记录兑换成功事件
await logSecurityEvent(db, req.ip ?? null, access.code, "redeem", "redeem_ok");
if (await detectAbuse(db, access.code, req.ip)) {
await markSuspicious(db, access.code);
res.status(403).json({ error: ABUSE_MESSAGE });
return;
}
res.status(200).json({ access });
} catch (err) {
if (err instanceof CodeError) {
// 无效兑换码(不存在/格式错误)→ 记录安全事件并检测刷码
// 无效兑换码 → 记录安全事件并检测刷码
const { code } = req.body as { code?: string };
if (
typeof code === "string" &&
@@ -72,9 +64,9 @@ export function createCodesRouter(injectedDb?: Database.Database): Router {
) {
const db = resolveDb(injectedDb);
const attempted = normalizeCode(code);
logSecurityEvent(db, req.ip ?? null, attempted, "redeem", "redeem_fail");
if (detectAbuse(db, attempted, req.ip)) {
markSuspicious(db, attempted);
await logSecurityEvent(db, req.ip ?? null, attempted, "redeem", "redeem_fail");
if (await detectAbuse(db, attempted, req.ip)) {
await markSuspicious(db, attempted);
res.status(403).json({ error: ABUSE_MESSAGE });
return;
}
@@ -92,16 +84,9 @@ export function createCodesRouter(injectedDb?: Database.Database): Router {
*
* Consume one use of a code. Atomically decrements used_uses in a
* transaction. If downloadGrant is provided it must be an unused grant
* belonging to this code (created by chibi generate); it is marked used in
* the same transaction. Returns the updated access info + freeDownload flag.
*
* Request: { code: string, fileName: string, downloadGrant?: string }
* Response: 200 { access: AccessInfo, freeDownload: boolean }
* 400 { error: "兑换码已用尽" }
* 403 { error: "下载授权无效或已使用" }
* 429 { error: "操作过于频繁,请稍后再试" } (限流)
* belonging to this code; it is marked used in the same transaction.
*/
router.post("/consume", consumeLimiter, (req: Request, res: Response): void => {
router.post("/consume", consumeLimiter, async (req: Request, res: Response): Promise<void> => {
try {
const { code, downloadGrant } = req.body as {
code?: string;
@@ -112,11 +97,8 @@ export function createCodesRouter(injectedDb?: Database.Database): Router {
res.status(400).json({ error: "请输入兑换码" });
return;
}
// 空 grant 向后兼容:仅携带 downloadGrant 时做一次性授权校验
const grant = typeof downloadGrant === "string" && downloadGrant !== "" ? downloadGrant : undefined;
const access = consumeCodeWithGrant(resolveDb(injectedDb), normalizeCode(code), grant);
// freeDownload is true when the code still has remaining uses after
// this consumption (i.e. the user can still download)
const access = await consumeCodeWithGrant(resolveDb(injectedDb), normalizeCode(code), grant);
res.status(200).json({ access, freeDownload: access.remainingUses > 0 });
} catch (err) {
if (err instanceof CodeError) {
@@ -132,19 +114,15 @@ export function createCodesRouter(injectedDb?: Database.Database): Router {
* GET /api/codes/status?code=XXX
*
* Get the current status of a code without mutating anything.
*
* Query: code=string
* Response: 200 { access: AccessInfo }
* 404 { error: "兑换码不存在,请检查后重试" }
*/
router.get("/status", (req: Request, res: Response): void => {
router.get("/status", async (req: Request, res: Response): Promise<void> => {
try {
const codeParam = req.query.code;
if (!codeParam || typeof codeParam !== "string") {
res.status(400).json({ error: "请输入兑换码" });
return;
}
const access = getCodeStatus(resolveDb(injectedDb), normalizeCode(codeParam));
const access = await getCodeStatus(resolveDb(injectedDb), normalizeCode(codeParam));
res.status(200).json({ access });
} catch (err) {
if (err instanceof CodeError) {
+204
View File
@@ -0,0 +1,204 @@
/**
* PostgreSQL 异步实现:兑换码 + 下载授权相关数据操作。
* 与同步的 SQLite 实现(codes/service.ts 内部)一一对应。
*/
import { randomBytes } from "node:crypto";
import type { PoolClient } from "pg";
import type { PgDb } from "../db/index.js";
import type { AccessInfo, RedemptionAction } from "../types/index.js";
import {
validateFormat,
toAccess,
assertRedeemable,
type CodeRow,
type DownloadGrantRow,
ERRORS,
} from "./service.js";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** 可查询对象:Pool 或事务中的 Client 都可执行 query。 */
type Queryable = PgDb | PoolClient;
// ---------------------------------------------------------------------------
// 事务辅助
// ---------------------------------------------------------------------------
async function withTransaction<T>(
pool: PgDb,
fn: (client: PoolClient) => Promise<T>,
): Promise<T> {
const client = await pool.connect();
try {
await client.query("BEGIN");
const result = await fn(client);
await client.query("COMMIT");
return result;
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
}
// ---------------------------------------------------------------------------
// 核心操作(共享给 consumeCodePg / consumeCodeWithGrantPg)
// ---------------------------------------------------------------------------
async function consumeCorePg(db: Queryable, code: string): Promise<AccessInfo> {
const { rows } = await db.query<CodeRow>(
"SELECT * FROM codes WHERE code = $1",
[code],
);
const row = rows[0] as CodeRow | undefined;
assertRedeemable(row);
const newUsed = row!.used_uses + 1;
const newStatus = newUsed >= row!.total_uses ? "used" : row!.status;
await db.query(
"UPDATE codes SET used_uses = $1, status = $2 WHERE code = $3",
[newUsed, newStatus, code],
);
await db.query(
"INSERT INTO redemption_logs (code, action, used_delta) VALUES ($1, 'consume', 1)",
[code],
);
return toAccess({ ...row!, used_uses: newUsed, status: newStatus });
}
// ---------------------------------------------------------------------------
// 公共 API(供 service.ts 的 dispatcher 调用)
// ---------------------------------------------------------------------------
export async function insertCodesPg(
pool: PgDb,
codes: string[],
packageType: string,
totalUses: number,
): Promise<number> {
if (codes.length === 0) return 0;
const placeholders: string[] = [];
const params: unknown[] = [];
let n = 1;
for (const code of codes) {
placeholders.push(`($${n}, $${n + 1}, $${n + 2}, 0, 'active')`);
params.push(code, packageType, totalUses);
n += 3;
}
const sql = `INSERT INTO codes (code, package_type, total_uses, used_uses, status)
VALUES ${placeholders.join(", ")}
ON CONFLICT (code) DO NOTHING`;
const res = await pool.query(sql, params);
return res.rowCount ?? 0;
}
export async function checkRedeemablePg(
pool: PgDb,
rawCode: string,
): Promise<AccessInfo> {
const code = validateFormat(rawCode);
const { rows } = await pool.query<CodeRow>(
"SELECT * FROM codes WHERE code = $1",
[code],
);
return assertRedeemable(rows[0] as CodeRow | undefined);
}
export async function redeemCodePg(
pool: PgDb,
rawCode: string,
): Promise<AccessInfo> {
const access = await checkRedeemablePg(pool, rawCode);
await pool.query(
"INSERT INTO redemption_logs (code, action, used_delta) VALUES ($1, 'redeem', 0)",
[access.code],
);
return access;
}
export async function consumeCodePg(
pool: PgDb,
rawCode: string,
): Promise<AccessInfo> {
const code = validateFormat(rawCode);
return withTransaction(pool, (client) => consumeCorePg(client, code));
}
export async function consumeCodeWithGrantPg(
pool: PgDb,
rawCode: string,
grant?: string,
): Promise<AccessInfo> {
const code = validateFormat(rawCode);
const grantParam = grant !== undefined && grant !== "" ? grant : undefined;
return withTransaction(pool, async (client) => {
if (grantParam !== undefined) {
const { rows } = await client.query<DownloadGrantRow>(
'SELECT * FROM download_grants WHERE "grant" = $1',
[grantParam],
);
const row = rows[0] as DownloadGrantRow | undefined;
if (!row || row.used !== 0 || row.code !== code) {
throw ERRORS.GRANT_INVALID;
}
}
const access = await consumeCorePg(client, code);
if (grantParam !== undefined) {
await client.query(
'UPDATE download_grants SET used = 1 WHERE "grant" = $1',
[grantParam],
);
}
return access;
});
}
export async function createDownloadGrantPg(
pool: PgDb,
rawCode: string,
orderNo?: string,
): Promise<string> {
const code = validateFormat(rawCode);
const grant = randomBytes(16).toString("hex");
await pool.query(
'INSERT INTO download_grants ("grant", code, order_no) VALUES ($1, $2, $3)',
[grant, code, orderNo ?? null],
);
return grant;
}
export async function getCodeStatusPg(
pool: PgDb,
rawCode: string,
): Promise<AccessInfo> {
const code = validateFormat(rawCode);
const { rows } = await pool.query<CodeRow>(
"SELECT * FROM codes WHERE code = $1",
[code],
);
const row = rows[0] as CodeRow | undefined;
if (!row) throw ERRORS.NOT_FOUND;
return toAccess(row);
}
export async function logActionPg(
pool: PgDb,
code: string,
action: RedemptionAction,
usedDelta: number,
): Promise<void> {
await pool.query(
"INSERT INTO redemption_logs (code, action, used_delta) VALUES ($1, $2, $3)",
[code, action, usedDelta],
);
}
+256 -165
View File
@@ -1,16 +1,30 @@
import type Database from "better-sqlite3";
import { randomBytes } from "node:crypto";
import type { AccessInfo, PackageDefinition } from "../types/index.js";
import type { RedemptionAction } from "../types/index.js";
import type { AccessInfo, PackageDefinition, RedemptionAction } from "../types/index.js";
import { PACKAGE_DEFINITIONS } from "../types/index.js";
import type { Db, PgDb, SqliteDb } from "../db/index.js";
import { isPgDb } from "../db/index.js";
import {
insertCodesPg,
checkRedeemablePg,
redeemCodePg,
consumeCodePg,
consumeCodeWithGrantPg,
createDownloadGrantPg,
getCodeStatusPg,
logActionPg,
} from "./service.pg.js";
// Re-export for convenience
export { PACKAGE_DEFINITIONS } from "../types/index.js";
// ---------------------------------------------------------------------------
// 公共类型 & 常量
// ---------------------------------------------------------------------------
/** Regex for code format validation: 16 chars uppercase A-Z0-9. */
export const CODE_FORMAT = /^[A-Z0-9]{16}$/;
/** Package definition map: 体验包 3次, 常用包 10次, 进阶包 30次, 代理 200/500/1000次. */
/** Package definition map. */
export type PackageType = keyof typeof PACKAGE_DEFINITIONS;
export interface CodeRow {
@@ -44,7 +58,7 @@ export class CodeError extends Error {
}
// ---------------------------------------------------------------------------
// Errors (Chinese messages matching competitor UX)
// Errors
// ---------------------------------------------------------------------------
export const ERRORS = {
@@ -57,21 +71,17 @@ export const ERRORS = {
} as const;
// ---------------------------------------------------------------------------
// Code generation
// 纯函数(无 DB)
// ---------------------------------------------------------------------------
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
function randomChar(): string {
// crypto.getRandomValues is cryptographically secure
const buf = new Uint32Array(1);
crypto.getRandomValues(buf);
return ALPHABET[buf[0]! % ALPHABET.length]!;
}
/**
* Generate a single random code of the given length using chars A-Z0-9.
*/
export function generateCode(length = 16): string {
let out = "";
for (let i = 0; i < length; i++) {
@@ -80,11 +90,10 @@ export function generateCode(length = 16): string {
return out;
}
/**
* Batch-generate `count` unique codes with an optional prefix.
* Codes are 16 chars total (A-Z0-9), uppercase. Prefix is body chars.
*/
export function generateCodes(count: number, options?: { prefix?: string; length?: number }): string[] {
export function generateCodes(
count: number,
options?: { prefix?: string; length?: number },
): string[] {
if (count <= 0 || !Number.isInteger(count)) {
throw new CodeError("生成数量必须为正整数", 400, "GEN_COUNT");
}
@@ -106,20 +115,10 @@ export function generateCodes(count: number, options?: { prefix?: string; length
return Array.from(codes);
}
// ---------------------------------------------------------------------------
// DB helpers
// ---------------------------------------------------------------------------
function getCodeByRaw(db: Database.Database, rawCode: string): CodeRow | undefined {
return db.prepare("SELECT * FROM codes WHERE code = ?").get(rawCode) as CodeRow | undefined;
}
/** Normalize a redemption code input: trim + uppercase. */
export function normalizeCode(raw: string): string {
return raw.trim().toUpperCase();
}
/** Validate that a code is well-formed (16 chars A-Z0-9) and return normalized. */
export function validateFormat(raw: string): string {
const code = normalizeCode(raw);
if (!CODE_FORMAT.test(code)) {
@@ -128,15 +127,79 @@ export function validateFormat(raw: string): string {
return code;
}
/** 将行转换为 AccessInfo。 */
export function toAccess(code: CodeRow): AccessInfo {
return {
code: code.code,
packageType: code.package_type,
remainingUses: code.total_uses - code.used_uses,
totalUses: code.total_uses,
};
}
/** 校验行是否可兑换;不可用则抛出对应的 CodeError。 */
export function assertRedeemable(row: CodeRow | undefined): AccessInfo {
if (!row) throw ERRORS.NOT_FOUND;
if (row.status === "disabled") throw ERRORS.DISABLED;
if (row.expired_at && row.expired_at !== "" && Date.parse(row.expired_at) < Date.now()) {
throw ERRORS.EXPIRED;
}
if (row.used_uses >= row.total_uses) throw ERRORS.EXHAUSTED;
return toAccess(row);
}
// ---------------------------------------------------------------------------
// Insert / redeem / consume
// SQLite 内部帮助函数(同步,测试用)
// ---------------------------------------------------------------------------
/**
* Insert generated codes into the database.
* Returns number of codes actually inserted.
*/
export function insertCodes(db: Database.Database, codes: string[], packageType: string, totalUses: number): number {
function getCodeByRawSqlite(db: SqliteDb, rawCode: string): CodeRow | undefined {
return db.prepare("SELECT * FROM codes WHERE code = ?").get(rawCode) as CodeRow | undefined;
}
function getGrantByRawSqlite(db: SqliteDb, grant: string): DownloadGrantRow | undefined {
return db.prepare("SELECT * FROM download_grants WHERE grant = ?").get(grant) as
| DownloadGrantRow
| undefined;
}
function logActionSqlite(
db: SqliteDb,
code: string,
action: RedemptionAction,
usedDelta: number,
): void {
db.prepare("INSERT INTO redemption_logs (code, action, used_delta) VALUES (?, ?, ?)").run(
code,
action,
usedDelta,
);
}
function consumeCoreSqlite(db: SqliteDb, code: string): AccessInfo {
const row = getCodeByRawSqlite(db, code);
assertRedeemable(row);
const newUsed = row!.used_uses + 1;
const newStatus = newUsed >= row!.total_uses ? "used" : row!.status;
db.prepare("UPDATE codes SET used_uses = ?, status = ? WHERE code = ?").run(
newUsed,
newStatus,
code,
);
logActionSqlite(db, code, "consume", 1);
return toAccess({ ...row!, used_uses: newUsed, status: newStatus });
}
// ---------------------------------------------------------------------------
// SQLite 实现(同步,被 dispatcher 调用 — 测试路径)
// ---------------------------------------------------------------------------
function insertCodesSqlite(
db: SqliteDb,
codes: string[],
packageType: string,
totalUses: number,
): number {
const stmt = db.prepare(
"INSERT OR IGNORE INTO codes (code, package_type, total_uses, used_uses, status) VALUES (?, ?, ?, 0, 'active')",
);
@@ -150,107 +213,46 @@ export function insertCodes(db: Database.Database, codes: string[], packageType:
return inserted;
}
function toAccess(code: CodeRow): AccessInfo {
return {
code: code.code,
packageType: code.package_type,
remainingUses: code.total_uses - code.used_uses,
totalUses: code.total_uses,
};
}
/**
* Check whether a code is redeemable. Throws CodeError with the proper
* Chinese message + HTTP status if it is not. Returns the access info.
*/
export function checkRedeemable(db: Database.Database, rawCode: string): AccessInfo {
function checkRedeemableSqlite(db: SqliteDb, rawCode: string): AccessInfo {
const code = validateFormat(rawCode);
const row = getCodeByRaw(db, code);
if (!row) {
throw ERRORS.NOT_FOUND;
}
if (row.status === "disabled") {
throw ERRORS.DISABLED;
}
if (row.expired_at && row.expired_at !== "" && Date.parse(row.expired_at) < Date.now()) {
throw ERRORS.EXPIRED;
}
if (row.used_uses >= row.total_uses) {
throw ERRORS.EXHAUSTED;
}
return toAccess(row);
return assertRedeemable(getCodeByRawSqlite(db, code));
}
/**
* Redeem a code: validates it and records a redeem action in the log.
* NOTE: redemption only verifies the code is valid — actual consumption is
* tracked per-use via consume(). Marking a code as "used" happens only when
* its uses are fully exhausted by consume().
*/
export function redeemCode(db: Database.Database, rawCode: string): AccessInfo {
const access = checkRedeemable(db, rawCode);
logAction(db, access.code, "redeem", 0);
function redeemCodeSqlite(db: SqliteDb, rawCode: string): AccessInfo {
const access = checkRedeemableSqlite(db, rawCode);
logActionSqlite(db, access.code, "redeem", 0);
return access;
}
/**
* Core consume logic: re-checks the code inside the caller's transaction so
* concurrent requests cannot double-decrement past zero. Expects `code`
* already normalized + format-validated.
*/
function consumeCore(db: Database.Database, code: string): AccessInfo {
const row = getCodeByRaw(db, code);
if (!row) {
throw ERRORS.NOT_FOUND;
}
if (row.status === "disabled") {
throw ERRORS.DISABLED;
}
if (row.expired_at && row.expired_at !== "" && Date.parse(row.expired_at) < Date.now()) {
throw ERRORS.EXPIRED;
}
if (row.used_uses >= row.total_uses) {
throw ERRORS.EXHAUSTED;
}
const newUsed = row.used_uses + 1;
const newStatus = newUsed >= row.total_uses ? "used" : row.status;
db.prepare("UPDATE codes SET used_uses = ?, status = ? WHERE code = ?").run(newUsed, newStatus, code);
logAction(db, code, "consume", 1);
return toAccess({ ...row, used_uses: newUsed, status: newStatus });
}
/**
* Consume one use of a code ATOMICALLY.
* Uses a transaction that re-checks remaining uses inside the same write
* transaction so concurrent requests cannot double-decrement past zero.
*/
export function consumeCode(db: Database.Database, rawCode: string): AccessInfo {
function consumeCodeSqlite(db: SqliteDb, rawCode: string): AccessInfo {
const code = validateFormat(rawCode);
return db.transaction(() => consumeCore(db, code))();
return db.transaction(() => consumeCoreSqlite(db, code))();
}
// ---------------------------------------------------------------------------
// 下载授权 (download_grants)
// ---------------------------------------------------------------------------
function getGrantByRaw(db: Database.Database, grant: string): DownloadGrantRow | undefined {
return db.prepare("SELECT * FROM download_grants WHERE grant = ?").get(grant) as
| DownloadGrantRow
| undefined;
}
/**
* Generate a cryptographically random 32-hex download grant and persist it
* (one-time use, tied to the given code). Returns the grant string.
*/
export function createDownloadGrant(
db: Database.Database,
function consumeCodeWithGrantSqlite(
db: SqliteDb,
rawCode: string,
orderNo?: string,
): string {
grant?: string,
): AccessInfo {
const code = validateFormat(rawCode);
const grantParam = grant !== undefined && grant !== "" ? grant : undefined;
return db.transaction((): AccessInfo => {
if (grantParam !== undefined) {
const row = getGrantByRawSqlite(db, grantParam);
if (!row || row.used !== 0 || row.code !== code) {
throw ERRORS.GRANT_INVALID;
}
}
const access = consumeCoreSqlite(db, code);
if (grantParam !== undefined) {
db.prepare("UPDATE download_grants SET used = 1 WHERE grant = ?").run(grantParam);
}
return access;
})();
}
function createDownloadGrantSqlite(db: SqliteDb, rawCode: string, orderNo?: string): string {
const code = validateFormat(rawCode);
const grant = randomBytes(16).toString("hex");
db.prepare("INSERT INTO download_grants (grant, code, order_no) VALUES (?, ?, ?)").run(
@@ -261,56 +263,145 @@ export function createDownloadGrant(
return grant;
}
/**
* Consume one use of a code ATOMICALLY with optional one-time download grant.
*
* When `grant` is provided (non-empty): validates it exists, is unused, and
* belongs to `code` BEFORE decrementing — invalid/used/mismatched grant throws
* ERRORS.GRANT_INVALID (403) and nothing is decremented. On success the grant
* is marked used=1 inside the same transaction as the decrement.
*
* When `grant` is empty/omitted: behaves exactly like consumeCode (backward
* compat for direct consumption).
*/
export function consumeCodeWithGrant(
db: Database.Database,
rawCode: string,
grant?: string,
): AccessInfo {
function getCodeStatusSqlite(db: SqliteDb, rawCode: string): AccessInfo {
const code = validateFormat(rawCode);
const grantParam = grant !== undefined && grant !== "" ? grant : undefined;
return db.transaction((): AccessInfo => {
if (grantParam !== undefined) {
const row = getGrantByRaw(db, grantParam);
if (!row || row.used !== 0 || row.code !== code) {
throw ERRORS.GRANT_INVALID;
}
}
const access = consumeCore(db, code);
if (grantParam !== undefined) {
db.prepare("UPDATE download_grants SET used = 1 WHERE grant = ?").run(grantParam);
}
return access;
})();
}
/** Get current access status without mutating anything. */
export function getCodeStatus(db: Database.Database, rawCode: string): AccessInfo {
const code = validateFormat(rawCode);
const row = getCodeByRaw(db, code);
if (!row) {
throw ERRORS.NOT_FOUND;
}
const row = getCodeByRawSqlite(db, code);
if (!row) throw ERRORS.NOT_FOUND;
return toAccess(row);
}
// ---------------------------------------------------------------------------
// Logging
// 公共 Dispatcher(根据 db 类型路由到 SQLite 或 PostgreSQL)
// ---------------------------------------------------------------------------
export function logAction(db: Database.Database, code: string, action: RedemptionAction, usedDelta: number): void {
db.prepare("INSERT INTO redemption_logs (code, action, used_delta) VALUES (?, ?, ?)").run(code, action, usedDelta);
type MaybePromise<T> = T | Promise<T>;
export function insertCodes(
db: SqliteDb,
codes: string[],
packageType: string,
totalUses: number,
): number;
export function insertCodes(
db: PgDb,
codes: string[],
packageType: string,
totalUses: number,
): Promise<number>;
export function insertCodes(
db: Db,
codes: string[],
packageType: string,
totalUses: number,
): MaybePromise<number>;
export function insertCodes(
db: Db,
codes: string[],
packageType: string,
totalUses: number,
): MaybePromise<number> {
return isPgDb(db) ? insertCodesPg(db, codes, packageType, totalUses) : insertCodesSqlite(db, codes, packageType, totalUses);
}
export function checkRedeemable(db: SqliteDb, rawCode: string): AccessInfo;
export function checkRedeemable(db: PgDb, rawCode: string): Promise<AccessInfo>;
export function checkRedeemable(db: Db, rawCode: string): MaybePromise<AccessInfo>;
export function checkRedeemable(db: Db, rawCode: string): MaybePromise<AccessInfo> {
return isPgDb(db) ? checkRedeemablePg(db, rawCode) : checkRedeemableSqlite(db, rawCode);
}
export function redeemCode(db: SqliteDb, rawCode: string): AccessInfo;
export function redeemCode(db: PgDb, rawCode: string): Promise<AccessInfo>;
export function redeemCode(db: Db, rawCode: string): MaybePromise<AccessInfo>;
export function redeemCode(db: Db, rawCode: string): MaybePromise<AccessInfo> {
return isPgDb(db) ? redeemCodePg(db, rawCode) : redeemCodeSqlite(db, rawCode);
}
export function consumeCode(db: SqliteDb, rawCode: string): AccessInfo;
export function consumeCode(db: PgDb, rawCode: string): Promise<AccessInfo>;
export function consumeCode(db: Db, rawCode: string): MaybePromise<AccessInfo>;
export function consumeCode(db: Db, rawCode: string): MaybePromise<AccessInfo> {
return isPgDb(db) ? consumeCodePg(db, rawCode) : consumeCodeSqlite(db, rawCode);
}
export function consumeCodeWithGrant(
db: SqliteDb,
rawCode: string,
grant?: string,
): AccessInfo;
export function consumeCodeWithGrant(
db: PgDb,
rawCode: string,
grant?: string,
): Promise<AccessInfo>;
export function consumeCodeWithGrant(
db: Db,
rawCode: string,
grant?: string,
): MaybePromise<AccessInfo>;
export function consumeCodeWithGrant(
db: Db,
rawCode: string,
grant?: string,
): MaybePromise<AccessInfo> {
return isPgDb(db) ? consumeCodeWithGrantPg(db, rawCode, grant) : consumeCodeWithGrantSqlite(db, rawCode, grant);
}
export function createDownloadGrant(
db: SqliteDb,
rawCode: string,
orderNo?: string,
): string;
export function createDownloadGrant(
db: PgDb,
rawCode: string,
orderNo?: string,
): Promise<string>;
export function createDownloadGrant(
db: Db,
rawCode: string,
orderNo?: string,
): MaybePromise<string>;
export function createDownloadGrant(
db: Db,
rawCode: string,
orderNo?: string,
): MaybePromise<string> {
return isPgDb(db) ? createDownloadGrantPg(db, rawCode, orderNo) : createDownloadGrantSqlite(db, rawCode, orderNo);
}
export function getCodeStatus(db: SqliteDb, rawCode: string): AccessInfo;
export function getCodeStatus(db: PgDb, rawCode: string): Promise<AccessInfo>;
export function getCodeStatus(db: Db, rawCode: string): MaybePromise<AccessInfo>;
export function getCodeStatus(db: Db, rawCode: string): MaybePromise<AccessInfo> {
return isPgDb(db) ? getCodeStatusPg(db, rawCode) : getCodeStatusSqlite(db, rawCode);
}
export function logAction(
db: SqliteDb,
code: string,
action: RedemptionAction,
usedDelta: number,
): void;
export function logAction(
db: PgDb,
code: string,
action: RedemptionAction,
usedDelta: number,
): Promise<void>;
export function logAction(
db: Db,
code: string,
action: RedemptionAction,
usedDelta: number,
): MaybePromise<void>;
export function logAction(
db: Db,
code: string,
action: RedemptionAction,
usedDelta: number,
): MaybePromise<void> {
return isPgDb(db) ? logActionPg(db, code, action, usedDelta) : logActionSqlite(db, code, action, usedDelta);
}
/** List package definitions (read-only mirror of PACKAGE_DEFINITIONS). */
+191 -33
View File
@@ -1,29 +1,73 @@
import Database from "better-sqlite3";
import { Pool } from "pg";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { SCHEMA_SQL } from "./schema.js";
import { SCHEMA_SQL_SQLITE, SCHEMA_SQL_PG } from "./schema.js";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
let _db: Database.Database | null = null;
/**
* 默认 PostgreSQL 连接串:test2 环境,库名 perler_lab。
* 可用 DATABASE_URL 环境变量覆盖。
*/
export const DEFAULT_DATABASE_URL =
"postgres://pgsql:XGYnJPysCNJsLeea@172.16.0.11:54322/perler_lab";
export interface DbConfig {
// ---------------------------------------------------------------------------
// DB 类型联合:业务代码同时支持 SQLite(测试/本地)与 PostgreSQL(生产)。
// tests 继续用 better-sqlite3 内存库(同步 API);生产链路走 pg Pool(异步)。
// ---------------------------------------------------------------------------
export type SqliteDb = Database.Database;
export type PgDb = Pool;
export type Db = SqliteDb | PgDb;
/** 类型守卫:pg Pool 拥有 query 方法,better-sqlite3 没有。 */
export function isPgDb(db: Db): db is PgDb {
return typeof (db as Readonly<{ query?: unknown }>).query === "function";
}
/** SQLite 连接配置(createTestDatabase 之外的本地文件/迁移模式)。 */
export interface SqliteConfig {
/** Path to the SQLite database file. Default: <project-root>/data/perler-lab.db */
dbPath?: string;
/** Enable WAL mode for better concurrent read performance. Default: true */
wal?: boolean;
}
/** PostgreSQL 连接配置。connectionString 缺省取 DATABASE_URL,再回退 DEFAULT_DATABASE_URL。 */
export interface PgConfig {
connectionString?: string;
}
export type DbConfig = SqliteConfig | PgConfig;
let _pool: PgDb | null = null;
let _sqlite: SqliteDb | null = null;
/**
* Initialize the database: open connection, run migrations, set pragmas.
* Idempotent — safe to call multiple times.
* Initialize the database — idempotent, safe to call multiple times.
*
* - 传入 dbPath / 不传 connectionString 的纯 SqliteConfig → 打开 SQLite 文件库(同步返回 Database),
* 供迁移测试与本地回退使用。
* - 否则(默认 / 传 connectionString)→ 创建 PostgreSQL 连接池并跑迁移(异步返回 Pool)。
*/
export function initDatabase(config?: DbConfig): Database.Database {
if (_db) return _db;
export function initDatabase(config?: SqliteConfig): SqliteDb;
export function initDatabase(config?: PgConfig): Promise<PgDb>;
export function initDatabase(config?: DbConfig): SqliteDb | Promise<PgDb> {
if (config === undefined || "connectionString" in config) {
return initPg(config as PgConfig | undefined);
}
return initSqlite(config as SqliteConfig);
}
/** 打开并迁移 SQLite 文件库(保留此路径供 showcase 迁移测试与本地开发)。 */
function initSqlite(config: SqliteConfig): SqliteDb {
if (_sqlite) return _sqlite;
const dbPath =
config?.dbPath ??
config.dbPath ??
process.env["DB_PATH"] ??
path.resolve(__dirname, "..", "..", "data", "perler-lab.db");
@@ -34,31 +78,63 @@ export function initDatabase(config?: DbConfig): Database.Database {
const db = new Database(dbPath);
// Performance & safety pragmas
db.pragma("journal_mode = WAL");
if (config.wal !== false) db.pragma("journal_mode = WAL");
db.pragma("foreign_keys = ON");
db.pragma("busy_timeout = 5000");
db.pragma("synchronous = NORMAL");
// Run migrations
runMigrations(db);
runSqliteMigrations(db);
_db = db;
_sqlite = db;
return db;
}
/**
* Run all pending migrations. Currently just applies the schema DDL.
*/
function runMigrations(db: Database.Database): void {
db.exec(SCHEMA_SQL);
migrateShowcaseSpec(db);
/** 创建 PostgreSQL 连接池并跑迁移。 */
async function initPg(config?: PgConfig): Promise<PgDb> {
if (_pool) return _pool;
const connectionString =
config?.connectionString ?? process.env["DATABASE_URL"] ?? DEFAULT_DATABASE_URL;
const pool = new Pool({
connectionString,
max: 10,
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 5_000,
});
pool.on("error", (err) => {
console.error("PostgreSQL pool error:", err);
});
await runPgMigrations(pool);
_pool = pool;
return pool;
}
/** SQLite 迁移:整段 DDL + showcase_works 规格列补齐(幂等)。 */
function runSqliteMigrations(db: SqliteDb): void {
db.exec(SCHEMA_SQL_SQLITE);
migrateShowcaseSpecSqlite(db);
}
/** PostgreSQL 迁移:逐条执行 DDL + showcase_works 规格列补齐(information_schema)。 */
async function runPgMigrations(pool: PgDb): Promise<void> {
// 单条 query 不能同时执行多条语句,逐条拆分执行;DDL 无参数,简单协议即安全。
const statements = SCHEMA_SQL_PG.split(";")
.map((s) => s.trim())
.filter((s) => s.length > 0);
for (const stmt of statements) {
await pool.query(stmt);
}
await migrateShowcaseSpecPg(pool);
}
/**
* 为 T-099~T-102 期间创建的旧 showcase_works 表补齐规格列。
* 为 T-099~T-102 期间创建的旧 showcase_works 表补齐规格列(SQLite 版)。
* 新库由 SCHEMA_SQL 一次性建全列;旧库逐列 ALTER TABLE ADD COLUMN(幂等)。
*/
function migrateShowcaseSpec(db: Database.Database): void {
function migrateShowcaseSpecSqlite(db: SqliteDb): void {
const columns = new Set(
(db.prepare("PRAGMA table_info(showcase_works)").all() as Array<{ name: string }>).map(
(col) => col.name,
@@ -78,34 +154,116 @@ function migrateShowcaseSpec(db: Database.Database): void {
}
}
/** PostgreSQL 版规格列补齐:information_schema 查询列,缺列逐列 ALTER(幂等)。 */
async function migrateShowcaseSpecPg(pool: PgDb): Promise<void> {
const reg = await pool.query("SELECT to_regclass('public.showcase_works') AS reg");
if (reg.rows[0]?.reg === null) return; // 表不存在:新库将由 SCHEMA_SQL_PG 建全列
const cols = await pool.query(
"SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'showcase_works'",
);
const columns = new Set(
(cols.rows as ReadonlyArray<{ column_name: string }>).map((c) => c.column_name),
);
const additions: ReadonlyArray<[name: string, declaration: string]> = [
["width", "INTEGER"],
["height", "INTEGER"],
["brand", "TEXT"],
["materials", "TEXT"],
];
for (const [name, declaration] of additions) {
if (!columns.has(name)) {
await pool.query(`ALTER TABLE showcase_works ADD COLUMN ${name} ${declaration}`);
}
}
}
/**
* Get the active database instance. Throws if not initialized.
* 生产返回 pg Pool;sqlite 文件模式返回 Database。
*/
export function getDb(): Database.Database {
if (!_db) {
throw new Error("Database not initialized. Call initDatabase() first.");
}
return _db;
export function getDb(): Db {
if (_pool) return _pool;
if (_sqlite) return _sqlite;
throw new Error("Database not initialized. Call initDatabase() first.");
}
/**
* Close the database connection gracefully.
* 同时关闭 pg 连接池与 sqlite 文件句柄(幂等)。
*/
export function closeDatabase(): void {
if (_db) {
_db.close();
_db = null;
export async function closeDatabase(): Promise<void> {
if (_pool) {
await _pool.end();
_pool = null;
}
if (_sqlite) {
_sqlite.close();
_sqlite = null;
}
}
/**
* Create an in-memory database for testing. Returns the db instance.
* Does NOT affect the global _db singleton.
* Create an in-memory SQLite database for testing. Returns the db instance.
* Does NOT affect the global singleton.
*/
export function createTestDatabase(): Database.Database {
export function createTestDatabase(): SqliteDb {
const db = new Database(":memory:");
db.pragma("journal_mode = WAL");
db.pragma("foreign_keys = ON");
db.exec(SCHEMA_SQL);
db.exec(SCHEMA_SQL_SQLITE);
return db;
}
// ---------------------------------------------------------------------------
// 统一查询辅助:路由层同一查询同时给出 sqlite(? 占位符)与 pg($n 占位符)
// 两个版本,仅方言不同;始终异步返回,调用方统一 await。
// ---------------------------------------------------------------------------
export interface DualSql {
sqlite: string;
pg: string;
}
/** 查询单行(可能为空)。pg 版把 COUNT(*) 等 bigint 列按调用方类型返回。 */
export async function dbGet<T>(
db: Db,
sql: DualSql,
params?: readonly unknown[],
): Promise<T | undefined> {
if (isPgDb(db)) {
const res = await db.query(sql.pg, params as unknown[]);
return res.rows[0] as T | undefined;
}
return (params === undefined ? db.prepare(sql.sqlite).get() : db.prepare(sql.sqlite).get(...params)) as
| T
| undefined;
}
/** 查询多行。 */
export async function dbAll<T>(
db: Db,
sql: DualSql,
params?: readonly unknown[],
): Promise<T[]> {
if (isPgDb(db)) {
const res = await db.query(sql.pg, params as unknown[]);
return res.rows as T[];
}
return (params === undefined
? db.prepare(sql.sqlite).all()
: db.prepare(sql.sqlite).all(...params)) as T[];
}
/** 执行写入。 */
export async function dbRun(db: Db, sql: DualSql, params?: readonly unknown[]): Promise<void> {
if (isPgDb(db)) {
await db.query(sql.pg, params as unknown[]);
return;
}
if (params === undefined) {
db.prepare(sql.sqlite).run();
} else {
db.prepare(sql.sqlite).run(...params);
}
}
+122 -13
View File
@@ -1,15 +1,13 @@
/**
* SQLite database schema for PERLER LAB.
* Database schema for PERLER LAB.
*
* DB choice: better-sqlite3
* - Synchronous API (no async overhead for SQLite): simpler code, faster local operations.
* - Well-typed TypeScript bindings via @types/better-sqlite3.
* - Mature, widely used, zero-dependency native bindings.
* - No external server process needed — database is a single file.
* Two DDL exports:
* SCHEMA_SQL_SQLITE — SQLite DDL (used by tests + legacy sqlite file mode)
* SCHEMA_SQL_PG — PostgreSQL DDL (used by production initDatabase)
*/
/** All DDL statements for creating tables. */
export const SCHEMA_SQL = `
/** All DDL statements for creating tables on SQLite. */
export const SCHEMA_SQL_SQLITE = `
-- 兑换码表
CREATE TABLE IF NOT EXISTS codes (
code TEXT PRIMARY KEY,
@@ -108,10 +106,6 @@ CREATE TABLE IF NOT EXISTS download_grants (
CREATE INDEX IF NOT EXISTS idx_download_grants_code ON download_grants(code);
-- chibi Showcase 作品表
-- title: 作品标题;image_data: base64 dataURL 或 http(s) URL;
-- tags: 标签数组 JSON 文本(如 '["宠物","猫"]');source: 作品来源(如 chibi/manual)
-- 规格列(T-131 详情页需要):width/height 图纸宽高(格);brand 材料品牌(如 MARD);
-- materials 用料清单 JSON 文本(如 '[{"code":"A7","count":980}]',name 可选),缺省为 NULL
CREATE TABLE IF NOT EXISTS showcase_works (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
@@ -127,4 +121,119 @@ CREATE TABLE IF NOT EXISTS showcase_works (
-- 索引:按创建时间倒序查询作品列表(Showcase 展示页主路径)
CREATE INDEX IF NOT EXISTS idx_showcase_works_created_at ON showcase_works(created_at DESC, id DESC);
`;
`;
/** All DDL statements for creating tables on PostgreSQL. */
export const SCHEMA_SQL_PG = `
-- 兑换码表
CREATE TABLE IF NOT EXISTS codes (
code TEXT PRIMARY KEY,
package_type TEXT NOT NULL,
total_uses INTEGER NOT NULL CHECK(total_uses > 0),
used_uses INTEGER NOT NULL DEFAULT 0 CHECK(used_uses >= 0),
status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active', 'used', 'disabled')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expired_at TEXT
);
-- 订单表
CREATE TABLE IF NOT EXISTS orders (
order_no TEXT PRIMARY KEY,
package_name TEXT NOT NULL,
amount_cents INTEGER NOT NULL CHECK(amount_cents > 0),
payment_method TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending', 'paid', 'failed')),
access_code TEXT REFERENCES codes(code),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
paid_at TIMESTAMPTZ
);
-- 核销日志表
CREATE TABLE IF NOT EXISTS redemption_logs (
id SERIAL PRIMARY KEY,
code TEXT NOT NULL REFERENCES codes(code),
action TEXT NOT NULL CHECK(action IN ('redeem', 'consume')),
used_delta INTEGER NOT NULL DEFAULT 0 CHECK(used_delta >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- AI 生成记录表
CREATE TABLE IF NOT EXISTS chibi_generations (
id SERIAL PRIMARY KEY,
code TEXT NOT NULL REFERENCES codes(code),
category TEXT NOT NULL,
subtype TEXT NOT NULL,
grid_size INTEGER NOT NULL,
color_count INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- 索引:按 code 查询日志
CREATE INDEX IF NOT EXISTS idx_redemption_logs_code ON redemption_logs(code);
-- 索引:按状态查询兑换码
CREATE INDEX IF NOT EXISTS idx_codes_status ON codes(status);
-- 索引:按 order_no 查询订单
CREATE INDEX IF NOT EXISTS idx_orders_order_no ON orders(order_no);
-- 设备绑定表(云端同步权益)
CREATE TABLE IF NOT EXISTS device_bindings (
device_id TEXT NOT NULL,
code TEXT NOT NULL REFERENCES codes(code),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (device_id, code)
);
-- 索引:按 code 反查绑定设备
CREATE INDEX IF NOT EXISTS idx_device_bindings_code ON device_bindings(code);
-- 安全事件表
CREATE TABLE IF NOT EXISTS security_events (
id SERIAL PRIMARY KEY,
ip TEXT,
code TEXT NOT NULL,
action TEXT NOT NULL,
event_type TEXT NOT NULL CHECK(event_type IN ('redeem_ok', 'redeem_fail', 'code_disabled')),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- 索引:按兑换码查询安全事件
CREATE INDEX IF NOT EXISTS idx_security_events_code ON security_events(code, event_type, created_at);
-- 索引:按 IP 查询安全事件
CREATE INDEX IF NOT EXISTS idx_security_events_ip ON security_events(ip, event_type, created_at);
-- 下载授权表
CREATE TABLE IF NOT EXISTS download_grants (
"grant" TEXT PRIMARY KEY,
code TEXT NOT NULL REFERENCES codes(code),
order_no TEXT,
used INTEGER NOT NULL DEFAULT 0 CHECK(used IN (0, 1)),
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- 索引:按兑换码查询下载授权
CREATE INDEX IF NOT EXISTS idx_download_grants_code ON download_grants(code);
-- chibi Showcase 作品表
CREATE TABLE IF NOT EXISTS showcase_works (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
image_data TEXT NOT NULL,
tags TEXT NOT NULL DEFAULT '[]',
source TEXT NOT NULL DEFAULT 'manual',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
width INTEGER,
height INTEGER,
brand TEXT,
materials TEXT
);
-- 索引:按创建时间倒序查询作品列表
CREATE INDEX IF NOT EXISTS idx_showcase_works_created_at ON showcase_works(created_at DESC, id DESC);
`;
/** 保留旧名以便渐进切换(SQLite DDL,用于 createTestDatabase)。 */
export const SCHEMA_SQL = SCHEMA_SQL_SQLITE;
+50 -47
View File
@@ -1,7 +1,7 @@
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import { getDb } from "../db/index.js";
import type { Db } from "../db/index.js";
import { getDb, dbGet, dbRun } from "../db/index.js";
import { getPaymentProvider, isWechatPayEnabled } from "./index.js";
import type { PaymentMethod } from "./types.js";
import { generateCode, insertCodes } from "../codes/service.js";
@@ -14,7 +14,7 @@ const PACKAGES: Record<string, { name: string; cents: number; uses: number }> =
"进阶包": { name: "进阶包", cents: 2990, uses: 30 },
};
function resolveDb(injected?: Database.Database): Database.Database {
function resolveDb(injected?: Db): Db {
return injected ?? getDb();
}
@@ -28,16 +28,37 @@ function genOrderNo(): string {
return `PL${ts}${rand}`;
}
// 双方言 SQL 常量
const INSERT_ORDER_SQL = {
sqlite: `INSERT INTO orders (order_no, package_name, amount_cents, payment_method, status, created_at)
VALUES (?, ?, ?, ?, 'pending', ?)`,
pg: `INSERT INTO orders (order_no, package_name, amount_cents, payment_method, status, created_at)
VALUES ($1, $2, $3, $4, 'pending', $5)`,
} as const;
const SELECT_ORDER_SQL = {
sqlite: "SELECT * FROM orders WHERE order_no = ?",
pg: "SELECT * FROM orders WHERE order_no = $1",
} as const;
const SELECT_ORDER_STATUS_SQL = {
sqlite: "SELECT status, package_name FROM orders WHERE order_no = ?",
pg: "SELECT status, package_name FROM orders WHERE order_no = $1",
} as const;
const UPDATE_ORDER_PAID_SQL = {
sqlite: "UPDATE orders SET status = 'paid', paid_at = ?, access_code = ? WHERE order_no = ?",
pg: "UPDATE orders SET status = 'paid', paid_at = $1, access_code = $2 WHERE order_no = $3",
} as const;
/**
* 标记订单为已支付并生成权益兑换码(幂等调用方需先判断状态)。
*/
function markOrderPaid(db: Database.Database, orderNo: string, packageName: string): string {
async function markOrderPaid(db: Db, orderNo: string, packageName: string): Promise<string> {
const pkg = PACKAGES[packageName] ?? PACKAGES["常用包"]!;
const code = generateCode();
insertCodes(db, [code], pkg.name, pkg.uses);
db.prepare(
`UPDATE orders SET status = 'paid', paid_at = ?, access_code = ? WHERE order_no = ?`,
).run(new Date().toISOString(), code, orderNo);
await insertCodes(db, [code], pkg.name, pkg.uses);
await dbRun(db, UPDATE_ORDER_PAID_SQL, [new Date().toISOString(), code, orderNo]);
return code;
}
@@ -45,16 +66,14 @@ function markOrderPaid(db: Database.Database, orderNo: string, packageName: stri
* 创建支付订单路由。
* 注入 DB 便于测试(与 codes 模块一致)。
*/
export function createPaymentRouter(injectedDb?: Database.Database): Router {
export function createPaymentRouter(injectedDb?: Db): Router {
const router = Router();
// 防刷限流:创建订单 5 次/小时/IP(每路由实例独立计数,测试互不干扰)
// 防刷限流
const ordersLimiter = createRateLimiter(RATE_LIMITS.orders)("orders");
/**
* POST /api/orders
* 请求: { packageName: string, paymentMethod: "wechat" | "alipay" }
* 响应: 200 { order, payment } / 400 { error } / 429 限流
*/
router.post("/", ordersLimiter, async (req: Request, res: Response): Promise<void> => {
try {
@@ -74,10 +93,7 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
}
const orderNo = genOrderNo();
const createdAt = new Date().toISOString();
db.prepare(
`INSERT INTO orders (order_no, package_name, amount_cents, payment_method, status, created_at)
VALUES (?, ?, ?, ?, 'pending', ?)`,
).run(orderNo, pkg.name, pkg.cents, paymentMethod, createdAt);
await dbRun(db, INSERT_ORDER_SQL, [orderNo, pkg.name, pkg.cents, paymentMethod, createdAt]);
const order = {
orderNo,
@@ -102,9 +118,8 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
/**
* GET /api/orders?orderNo=XXX
* 响应: 200 { order } / 404 { error }
*/
router.get("/", (req: Request, res: Response): void => {
router.get("/", async (req: Request, res: Response): Promise<void> => {
try {
const db = resolveDb(injectedDb);
const orderNo = typeof req.query.orderNo === "string" ? req.query.orderNo : "";
@@ -112,9 +127,7 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
res.status(400).json({ error: "缺少 orderNo 参数" });
return;
}
const row = db.prepare("SELECT * FROM orders WHERE order_no = ?").get(orderNo) as
| Record<string, unknown>
| undefined;
const row = await dbGet<Record<string, unknown>>(db, SELECT_ORDER_SQL, [orderNo]);
if (!row) {
res.status(404).json({ error: "订单不存在" });
return;
@@ -128,21 +141,13 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
/**
* 支付回调处理(真实微信支付与 mock 共用)。
*
* 关键差异说明:
* - 真实微信支付(isWechatPayEnabled() 为 true):回调必须经过验签 + 解密
* (verifyCallback),验证通过后才允许标记订单为 paid,绝不能在未验证
* 的情况下直接改单。订单号以回调解密后的 out_trade_no 为准(微信回调
* 通知地址是固定的,路径中的订单号参数在真实模式下无意义)。
* - mock 模式:保持原有简化流程(路径参数 orderNo,直接标记 paid),
* 供本地开发与前端联调使用。
*/
async function handlePayCallback(req: Request, res: Response): Promise<void> {
const db = resolveDb(injectedDb);
const pathOrderNo = (req.params["orderNo"] as string | undefined) ?? "";
if (isWechatPayEnabled()) {
// ---- 真实微信支付回调:先验签,后标记支付 ----
// ---- 真实微信支付回调 ----
const rawBody = (req as Request & { rawBody?: Buffer }).rawBody;
if (rawBody === undefined) {
res.status(400).json({ code: "FAIL", message: "缺少原始请求体" });
@@ -164,32 +169,34 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
return;
}
if (pathOrderNo !== "" && pathOrderNo !== verified.orderNo) {
// 路径订单号仅作参考(通知地址固定),不一致时以解密结果为准
console.warn(`支付回调路径订单号 ${pathOrderNo} 与解密订单号 ${verified.orderNo} 不一致`);
}
const row = db.prepare("SELECT status, package_name FROM orders WHERE order_no = ?").get(
verified.orderNo,
) as { status: string; package_name: string } | undefined;
const row = await dbGet<{ status: string; package_name: string }>(
db,
SELECT_ORDER_STATUS_SQL,
[verified.orderNo],
);
if (!row) {
res.status(400).json({ code: "FAIL", message: "订单不存在" });
return;
}
if (row.status !== "paid") {
// 已支付订单不再重复生成兑换码(微信可能重试回调,保持幂等)
markOrderPaid(db, verified.orderNo, row.package_name);
await markOrderPaid(db, verified.orderNo, row.package_name);
}
res.status(200).json({ code: "SUCCESS", message: "成功" });
return;
}
// ---- mock 模式:简化流程,直接标记 paid(本地开发/前端联调) ----
// ---- mock 模式 ----
if (!pathOrderNo) {
res.status(400).json({ error: "缺少订单号" });
return;
}
const row = db.prepare("SELECT * FROM orders WHERE order_no = ?").get(pathOrderNo) as
| { order_no: string; status: string; package_name: string }
| undefined;
const row = await dbGet<{ order_no: string; status: string; package_name: string }>(
db,
SELECT_ORDER_SQL,
[pathOrderNo],
);
if (!row) {
res.status(404).json({ error: "订单不存在" });
return;
@@ -198,15 +205,13 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
res.status(200).json({ ok: true, order: row });
return;
}
const accessCode = markOrderPaid(db, pathOrderNo, row.package_name);
const updated = db.prepare("SELECT * FROM orders WHERE order_no = ?").get(pathOrderNo);
const accessCode = await markOrderPaid(db, pathOrderNo, row.package_name);
const updated = await dbGet<Record<string, unknown>>(db, SELECT_ORDER_SQL, [pathOrderNo]);
res.status(200).json({ ok: true, order: updated, accessCode });
}
/**
* POST /api/orders/:orderNo/pay-callback
* mock 模式:模拟支付回调(路径携带订单号,直接标记 paid)。
* 真实模式:同 /notify,验签通过后才标记 paid(订单号以回调体为准)。
*/
router.post("/:orderNo/pay-callback", (req: Request, res: Response): void => {
handlePayCallback(req, res).catch((err: unknown) => {
@@ -217,8 +222,6 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
/**
* POST /api/orders/notify
* 真实微信支付回调入口(WECHAT_NOTIFY_URL 指向此地址)。
* mock 模式下不存在真实回调,返回 400。
*/
router.post("/notify", (req: Request, res: Response): void => {
if (!isWechatPayEnabled()) {
@@ -232,4 +235,4 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
});
return router;
}
}
+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);
}
+8 -12
View File
@@ -1,6 +1,6 @@
import express from "express";
import type { Express, Request } from "express";
import type Database from "better-sqlite3";
import type { Db } from "./db/index.js";
import { initDatabase } from "./db/index.js";
import { createCodesRouter } from "./codes/routes.js";
import { createPaymentRouter } from "./payment/routes.js";
@@ -17,13 +17,10 @@ const PORT = parseInt(process.env["PORT"] ?? "8788", 10);
* Create the Express app. Accepts an optional injected database so tests can
* use an in-memory DB; production uses the singleton from initDatabase().
*/
export function createApp(db?: Database.Database): Express {
export function createApp(db?: Db): Express {
const app = express();
// ---- CORS middleware ----
// Manual middleware instead of the `cors` package: the only browser client
// is the Vite dev server on http://localhost:5173, so an explicit allowlist
// (no wildcard) is simpler and safer than a new dependency.
const ALLOWED_ORIGINS: readonly string[] = ["http://localhost:5173", "http://127.0.0.1:5173"];
app.use((req, res, next) => {
const origin = req.headers.origin;
@@ -42,9 +39,6 @@ export function createApp(db?: Database.Database): Express {
});
// ---- Middleware ----
// 通过 verify 捕获原始请求体:微信支付回调验签必须基于未经解析的原始
// body 字节(Wechatpay-Signature 是对原始报文的签名)。
// limit 放宽到 20mb:图案导出需要承载 512×512 的大网格 JSON(约 8MB)。
app.use(
express.json({
limit: "20mb",
@@ -80,10 +74,12 @@ export function createApp(db?: Database.Database): Express {
// Only auto-start when run directly (not when imported by tests)
const isMain = process.argv[1] !== undefined && process.argv[1]!.endsWith("server.ts");
if (isMain) {
initDatabase();
createApp().listen(PORT, () => {
console.log(`PERLER LAB server running on http://localhost:${PORT}`);
});
void (async (): Promise<void> => {
await initDatabase();
createApp().listen(PORT, () => {
console.log(`PERLER LAB server running on http://localhost:${PORT}`);
});
})();
}
export default createApp;
+99 -75
View File
@@ -5,26 +5,15 @@
* Request: { title: string, imageData: string, tags?: string[], source?: string,
* width?: number, height?: number, brand?: string, materials?: MaterialLine[] }
* Response: 201 { id: number }
* 400 { error: "请输入作品标题" } 标题为空
* 400 { error: "作品标题过长" } 标题超过 100 字符
* 400 { error: "图片格式无效" } imageData 非 base64 dataURL 也非 http(s) URL
* 400 { error: "标签格式无效" } tags 不是数组
* 400 { error: "尺寸参数无效" } width/height 非 1..512 整数
* 400 { error: "品牌格式无效" } brand 非字符串/超长
* 400 { error: "用料清单格式无效" } materials 非法
* 500 服务器内部错误
* 400 参数错误
*
* GET /api/showcase/works(T-100 展示页列表)
* Query: page=1&limit=12&tag=卡通动漫&source=chibi
* Response: 200 { items: [{ id, title, imageUrl, tags, source, createdAt }],
* total, page, limit }(items 按 created_at DESC, id DESC)
* 400 { error: "分页参数无效" } page/limit 非正整数
* Response: 200 { items, total, page, limit }
*
* GET /api/showcase/works/:id(T-131 作品详情)
* Response: 200 { id, title, imageUrl, tags, source, createdAt,
* spec: { width, height, brand, materials } }
* 400 { error: "作品 ID 无效" } id 非正整数
* 404 { error: "作品不存在" } id 无对应记录
* Response: 200 { id, title, imageUrl, tags, source, createdAt, spec }
* 400 / 404
*
* GET /api/showcase/meta(T-101 展示页 SEO 元数据)
* Query: lang=zh|en(缺省 zh)
@@ -33,8 +22,8 @@
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import { getDb } from "../db/index.js";
import type { Db, PgDb, SqliteDb } from "../db/index.js";
import { getDb, isPgDb } from "../db/index.js";
import {
insertWork,
getWorkById,
@@ -51,10 +40,10 @@ const MAX_TAGS = 20;
/** 单个标签最大长度。 */
const MAX_TAG_LENGTH = 30;
/** 图纸单边最大格数(与服务端导出能力 512×512 对齐)。 */
/** 图纸单边最大格数。 */
const MAX_GRID_SIZE = 512;
/** 用料清单最大条目数(与前端分享码 256 色上限对齐)。 */
/** 用料清单最大条目数。 */
const MAX_MATERIALS = 256;
/** 品牌名最大长度。 */
@@ -66,20 +55,18 @@ const MAX_MATERIAL_CODE_LENGTH = 20;
/** 用料清单单行名称最大长度。 */
const MAX_MATERIAL_NAME_LENGTH = 30;
/** base64 dataURL:data:image/<type>;base64,<data>(data 可含 +/ 与 = 填充)。 */
/** base64 dataURL。 */
const DATA_URL_RE = /^data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/=]+$/;
/** http(s) 绝对 URL(图片外链)。 */
/** http(s) 绝对 URL。 */
const HTTP_URL_RE = /^https?:\/\/[^\s]+$/i;
/** Resolve the database instance: injected DB for tests, else global singleton. */
function resolveDb(injected?: Database.Database): Database.Database {
/** Resolve the database instance. */
function resolveDb(injected?: Db): Db {
return injected ?? getDb();
}
/**
* 校验图片字段:必须是 base64 dataURL 或 http(s) URL。
*/
/** 校验图片字段。 */
function isValidImageData(value: string): boolean {
return DATA_URL_RE.test(value) || HTTP_URL_RE.test(value);
}
@@ -87,14 +74,14 @@ function isValidImageData(value: string): boolean {
/**
* 创建 Showcase 路由。接受可选注入数据库以便测试。
*/
export function createShowcaseRouter(injectedDb?: Database.Database): Router {
export function createShowcaseRouter(injectedDb?: Db): Router {
const router = Router();
router.post("/works", (req: Request, res: Response): void => {
router.post("/works", async (req: Request, res: Response): Promise<void> => {
try {
const body = (req.body ?? {}) as Record<string, unknown>;
// ---- title:非空字符串,长度限制 ----
// ---- title ----
const title = typeof body.title === "string" ? body.title.trim() : "";
if (!title) {
res.status(400).json({ error: "请输入作品标题" });
@@ -105,14 +92,14 @@ export function createShowcaseRouter(injectedDb?: Database.Database): Router {
return;
}
// ---- imageData:base64 dataURL 或 http(s) URL ----
// ---- imageData ----
const imageData = typeof body.imageData === "string" ? body.imageData : "";
if (!imageData || !isValidImageData(imageData)) {
res.status(400).json({ error: "图片格式无效" });
return;
}
// ---- tags:必须是数组,元素过滤为合法字符串 ----
// ---- tags ----
const rawTags = body.tags;
if (rawTags !== undefined && !Array.isArray(rawTags)) {
res.status(400).json({ error: "标签格式无效" });
@@ -130,13 +117,13 @@ export function createShowcaseRouter(injectedDb?: Database.Database): Router {
return;
}
// ---- source:可选字符串,默认 manual ----
// ---- source ----
const source =
typeof body.source === "string" && body.source.trim() !== ""
? body.source.trim().slice(0, 50)
: "manual";
// ---- 规格字段(T-131:详情页需要的尺寸/品牌/用料信息,均可选)----
// ---- 规格字段 ----
const width = validateOptionalGridSize(body.width);
if (width.error !== null) {
res.status(400).json({ error: width.error });
@@ -158,7 +145,8 @@ export function createShowcaseRouter(injectedDb?: Database.Database): Router {
return;
}
const id = insertWork(resolveDb(injectedDb), {
const db = resolveDb(injectedDb);
const id = await insertWork(db, {
title,
imageData,
tags,
@@ -177,9 +165,8 @@ export function createShowcaseRouter(injectedDb?: Database.Database): Router {
/**
* GET /api/showcase/works — 展示页列表(分页 + 标签筛选 + 来源筛选)。
* 按 created_at DESC, id DESC 排序,返回契约字段 items/total/page/limit。
*/
router.get("/works", (req: Request, res: Response): void => {
router.get("/works", async (req: Request, res: Response): Promise<void> => {
const page = parsePositiveInt(req.query["page"], DEFAULT_PAGE);
const limitRaw = parsePositiveInt(req.query["limit"], DEFAULT_LIMIT);
if (page === null || limitRaw === null) {
@@ -192,33 +179,54 @@ export function createShowcaseRouter(injectedDb?: Database.Database): Router {
const source = parseQueryString(req.query["source"]);
const db = resolveDb(injectedDb);
const { where, params } = buildFilter(tag, source);
const totalRow = db
.prepare(`SELECT COUNT(*) AS total FROM showcase_works w ${where}`)
.get(...params) as { total: number };
const isPg = isPgDb(db);
const { where, params, limitPh, offsetPh } = buildFilter(tag, source, isPg);
const offset = (page - 1) * limit;
const rows = db
.prepare(
let total: number;
let rows: ShowcaseWorkRow[];
if (isPg) {
const pg = db as PgDb;
const totalRes = await pg.query<{ total: number }>(
`SELECT COUNT(*)::int AS total FROM showcase_works w ${where}`,
params,
);
total = totalRes.rows[0]!.total;
const listRes = await pg.query<ShowcaseWorkRow>(
`SELECT w.id, w.title, w.image_data, w.tags, w.source, w.created_at
FROM showcase_works w
${where}
ORDER BY w.created_at DESC, w.id DESC
LIMIT ? OFFSET ?`,
)
.all(...params, limit, offset) as ShowcaseWorkRow[];
LIMIT ${limitPh} OFFSET ${offsetPh}`,
[...params, limit, offset],
);
rows = listRes.rows as ShowcaseWorkRow[];
} else {
const sql = db as SqliteDb;
const totalRow = sql
.prepare(`SELECT COUNT(*) AS total FROM showcase_works w ${where}`)
.get(...params) as { total: number };
total = totalRow.total;
rows = sql
.prepare(
`SELECT w.id, w.title, w.image_data, w.tags, w.source, w.created_at
FROM showcase_works w
${where}
ORDER BY w.created_at DESC, w.id DESC
LIMIT ${limitPh} OFFSET ${offsetPh}`,
)
.all(...params, limit, offset) as ShowcaseWorkRow[];
}
const items = rows.map(toShowcaseWork);
res.status(200).json({ items, total: totalRow.total, page, limit });
res.status(200).json({ items, total, page, limit });
});
/**
* GET /api/showcase/works/:id — 作品详情(T-131)。
* 按 id 查询单作品:返回基础字段 + spec 规格块(尺寸/品牌/用料清单,缺省可空)。
* id 非正整数 → 400;记录不存在 → 404。
*/
router.get("/works/:id", (req: Request, res: Response): void => {
router.get("/works/:id", async (req: Request, res: Response): Promise<void> => {
try {
const id = parsePositiveId(req.params["id"]);
if (id === null) {
@@ -226,7 +234,7 @@ export function createShowcaseRouter(injectedDb?: Database.Database): Router {
return;
}
const db = resolveDb(injectedDb);
const row = getWorkById(db, id);
const row = await getWorkById(db, id);
if (row === undefined) {
res.status(404).json({ error: "作品不存在" });
return;
@@ -240,8 +248,6 @@ export function createShowcaseRouter(injectedDb?: Database.Database): Router {
/**
* GET /api/showcase/meta — 展示页 SEO 元数据(多语言)。
* 供前端注入 og:title / og:description / og:image,并附带 JSON-LD
* CollectionPage 结构化数据(可整段写入 <script type="application/ld+json">)。
*/
router.get("/meta", (req: Request, res: Response): void => {
const lang = normalizeLang(req.query["lang"]);
@@ -268,7 +274,7 @@ const DEFAULT_PAGE = 1;
const DEFAULT_LIMIT = 12;
const MAX_LIMIT = 100;
/** 解析正整数查询参数;缺失回退默认值,非法(非整数 / <1)返回 null。 */
/** 解析正整数查询参数。 */
function parsePositiveInt(raw: unknown, fallback: number): number | null {
if (raw === undefined) return fallback;
if (typeof raw !== "string" || raw.trim() === "") return fallback;
@@ -277,36 +283,54 @@ function parsePositiveInt(raw: unknown, fallback: number): number | null {
return n;
}
/** 解析可选查询字符串参数;空值 / 非字符串返回 null。 */
/** 解析可选查询字符串参数。 */
function parseQueryString(raw: unknown): string | null {
if (typeof raw !== "string") return null;
const trimmed = raw.trim();
return trimmed === "" ? null : trimmed;
}
/** 构建标签 / 来源筛选的 WHERE 子句与参数(标签用 json_each 精确匹配)。 */
function buildFilter(tag: string | null, source: string | null): {
/**
* 构建标签 / 来源筛选的 WHERE 子句与参数。
* 占位符编号统一:tag → $1, source → $2, LIMIT → $M, OFFSET → $M+1(pg 风格);
* sqlite 用 ? 占位符,通过 ph() 生成。
*/
function buildFilter(
tag: string | null,
source: string | null,
pg: boolean,
): {
where: string;
params: unknown[];
limitPh: string;
offsetPh: string;
} {
const clauses: string[] = [];
const params: unknown[] = [];
let n = 1;
const ph = (): string => (pg ? `$${n++}` : "?");
if (tag !== null) {
clauses.push("EXISTS (SELECT 1 FROM json_each(w.tags) je WHERE je.value = ?)");
const p = ph();
clauses.push(
pg
? `EXISTS (SELECT 1 FROM jsonb_array_elements_text(w.tags::jsonb) je WHERE je = ${p})`
: `EXISTS (SELECT 1 FROM json_each(w.tags) je WHERE je.value = ${p})`,
);
params.push(tag);
}
if (source !== null) {
clauses.push("w.source = ?");
clauses.push(`w.source = ${ph()}`);
params.push(source);
}
return {
where: clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "",
params,
};
const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
const limitPh = ph();
const offsetPh = ph();
return { where, params, limitPh, offsetPh };
}
/** 解析 tags JSON 文本为字符串数组;非法 JSON / 非数组回退空数组。 */
/** 解析 tags JSON 文本为字符串数组。 */
function toShowcaseWork(row: ShowcaseWorkRow): {
id: number;
title: string;
@@ -334,7 +358,7 @@ function toShowcaseWork(row: ShowcaseWorkRow): {
};
}
/** 解析路径参数 :id 为合法正整数(AUTOINCREMENT id ≥ 1);非法返回 null。 */
/** 解析路径参数 :id 为合法正整数。 */
function parsePositiveId(raw: unknown): number | null {
if (typeof raw !== "string" || raw.trim() === "") return null;
if (!/^[1-9]\d*$/.test(raw.trim())) return null;
@@ -343,7 +367,7 @@ function parsePositiveId(raw: unknown): number | null {
return n;
}
/** 校验可选规格整数(1..MAX_GRID_SIZE);缺省/空返回 null,非法返回错误信息。 */
/** 校验可选规格整数(1..MAX_GRID_SIZE)。 */
function validateOptionalGridSize(raw: unknown): { value: number | null; error: string | null } {
if (raw === undefined || raw === null) return { value: null, error: null };
if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 1 || raw > MAX_GRID_SIZE) {
@@ -352,7 +376,7 @@ function validateOptionalGridSize(raw: unknown): { value: number | null; error:
return { value: raw, error: null };
}
/** 校验可选品牌名(非空字符串,≤50 字符);非法返回错误信息。 */
/** 校验可选品牌名。 */
function validateBrand(raw: unknown): { value: string | null; error: string | null } {
if (raw === undefined || raw === null) return { value: null, error: null };
if (typeof raw !== "string") return { value: null, error: "品牌格式无效" };
@@ -363,7 +387,7 @@ function validateBrand(raw: unknown): { value: string | null; error: string | nu
return { value: trimmed, error: null };
}
/** 校验可选用料清单({code, count, name?}[],≤256 行);非法返回错误信息。 */
/** 校验可选用料清单。 */
function validateMaterials(raw: unknown): { value: MaterialLine[] | null; error: string | null } {
if (raw === undefined || raw === null) return { value: null, error: null };
if (!Array.isArray(raw) || raw.length > MAX_MATERIALS) {
@@ -401,7 +425,7 @@ function validateMaterials(raw: unknown): { value: MaterialLine[] | null; error:
return { value: lines, error: null };
}
/** 解析 materials JSON 文本为用料清单;缺省/脏数据返回 null。 */
/** 解析 materials JSON 文本为用料清单。 */
function parseMaterials(raw: string | null): MaterialLine[] | null {
if (raw === null || raw === "") return null;
try {
@@ -419,7 +443,7 @@ function parseMaterials(raw: string | null): MaterialLine[] | null {
}
}
/** 详情接口响应结构:基础字段 + spec 规格块(尺寸/品牌/用料,缺省可空)。 */
/** 详情接口响应结构。 */
function toWorkDetail(row: ShowcaseWorkRow): {
id: number;
title: string;
@@ -446,7 +470,7 @@ function toWorkDetail(row: ShowcaseWorkRow): {
};
}
/** 规范化 lang 参数:zh/zh-CN/zh-TW → zh;en/en-US/en-GB → en;其余 → zh。 */
/** 规范化 lang 参数。 */
export function normalizeLang(raw: unknown): "zh" | "en" {
if (typeof raw !== "string") return "zh";
const lower = raw.trim().toLowerCase();
@@ -454,7 +478,7 @@ export function normalizeLang(raw: unknown): "zh" | "en" {
return "zh";
}
/** 展示页 SEO 文案(zh / en)。 */
/** 展示页 SEO 文案。 */
export const SHOWCASE_META: Readonly<Record<"zh" | "en", { title: string; description: string }>> = {
zh: {
title: "拼豆艺术作品展示 | PERLER LAB 拼豆图纸生成器",
@@ -467,8 +491,8 @@ export const SHOWCASE_META: Readonly<Record<"zh" | "en", { title: string; descri
},
};
/** og:image 默认路径;可用环境变量 SHOWCASE_OG_IMAGE 覆盖为完整 URL。 */
/** og:image 默认路径。 */
function resolveOgImage(): string {
const custom = process.env["SHOWCASE_OG_IMAGE"];
return custom !== undefined && custom.trim() !== "" ? custom.trim() : "/og-showcase.png";
}
}
+60 -14
View File
@@ -1,5 +1,5 @@
/**
* chibi Showcase 作品数据层:showcase_works 表的插入操作。
* chibi Showcase 作品数据层:showcase_works 表的插入/查询操作。
*
* 作品信息:
* - title: 作品标题(非空)
@@ -8,7 +8,8 @@
* - source: 作品来源(如 chibi / manual)
*/
import type Database from "better-sqlite3";
import type { Db, PgDb, SqliteDb } from "../db/index.js";
import { isPgDb } from "../db/index.js";
/** showcase_works 表行结构。 */
export interface ShowcaseWorkRow {
@@ -43,11 +44,12 @@ export interface InsertWorkInput {
materials?: MaterialLine[] | null;
}
/**
* 插入一条作品记录,返回自增主键 id。
* 规格字段可选(T-131):缺省时写入 NULL,详情接口返回可空规格。
*/
export function insertWork(db: Database.Database, input: InsertWorkInput): number {
// ---------------------------------------------------------------------------
// SQLite 实现(同步,测试路径)
// ---------------------------------------------------------------------------
/** 插入一条作品记录,返回自增主键 id(SQLite,同步)。 */
function insertWorkSqlite(db: SqliteDb, input: InsertWorkInput): number {
const info = db
.prepare(
`INSERT INTO showcase_works (title, image_data, tags, source, width, height, brand, materials)
@@ -68,14 +70,58 @@ export function insertWork(db: Database.Database, input: InsertWorkInput): numbe
return Number(info.lastInsertRowid);
}
/**
* 按 id 查询单条作品记录;不存在返回 undefined(详情接口主查询)。
*/
export function getWorkById(
db: Database.Database,
id: number,
): ShowcaseWorkRow | undefined {
function getWorkByIdSqlite(db: SqliteDb, id: number): ShowcaseWorkRow | undefined {
return db.prepare(`SELECT * FROM showcase_works WHERE id = ?`).get(id) as
| ShowcaseWorkRow
| undefined;
}
// ---------------------------------------------------------------------------
// PostgreSQL 实现(异步,生产路径)
// ---------------------------------------------------------------------------
async function insertWorkPg(db: PgDb, input: InsertWorkInput): Promise<number> {
const res = await db.query<{ id: number }>(
`INSERT INTO showcase_works (title, image_data, tags, source, width, height, brand, materials)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id`,
[
input.title,
input.imageData,
JSON.stringify(input.tags),
input.source,
input.width ?? null,
input.height ?? null,
input.brand ?? null,
input.materials === undefined || input.materials === null
? null
: JSON.stringify(input.materials),
],
);
return res.rows[0]!.id;
}
async function getWorkByIdPg(db: PgDb, id: number): Promise<ShowcaseWorkRow | undefined> {
const res = await db.query<ShowcaseWorkRow>(`SELECT * FROM showcase_works WHERE id = $1`, [id]);
return res.rows[0] as ShowcaseWorkRow | undefined;
}
// ---------------------------------------------------------------------------
// 公共 Dispatcher
// ---------------------------------------------------------------------------
type MaybePromise<T> = T | Promise<T>;
export function insertWork(db: SqliteDb, input: InsertWorkInput): number;
export function insertWork(db: PgDb, input: InsertWorkInput): Promise<number>;
export function insertWork(db: Db, input: InsertWorkInput): MaybePromise<number>;
export function insertWork(db: Db, input: InsertWorkInput): MaybePromise<number> {
return isPgDb(db) ? insertWorkPg(db, input) : insertWorkSqlite(db, input);
}
export function getWorkById(db: SqliteDb, id: number): ShowcaseWorkRow | undefined;
export function getWorkById(db: PgDb, id: number): Promise<ShowcaseWorkRow | undefined>;
export function getWorkById(db: Db, id: number): MaybePromise<ShowcaseWorkRow | undefined>;
export function getWorkById(db: Db, id: number): MaybePromise<ShowcaseWorkRow | undefined> {
return isPgDb(db) ? getWorkByIdPg(db, id) : getWorkByIdSqlite(db, id);
}
+40 -37
View File
@@ -1,7 +1,7 @@
import { Router } from "express";
import type { Request, Response } from "express";
import type Database from "better-sqlite3";
import { getDb } from "../db/index.js";
import type { Db } from "../db/index.js";
import { getDb, dbAll, dbRun } from "../db/index.js";
import { checkRedeemable, validateFormat, CodeError } from "../codes/service.js";
import type { AccessInfo } from "../types/index.js";
@@ -36,16 +36,14 @@ function handleCodeError(res: Response, err: CodeError): void {
}
/**
* Resolve the database instance: use injected DB if provided, otherwise
* fall back to the global singleton.
* Resolve the database instance.
*/
function resolveDb(injected?: Database.Database): Database.Database {
function resolveDb(injected?: Db): Db {
return injected ?? getDb();
}
/**
* Normalize a device id: trim; reject anything not matching the format.
* Throws a CodeError (400, "设备标识无效") on invalid input.
*/
function parseDeviceId(raw: string): string {
const deviceId = raw.trim();
@@ -55,6 +53,30 @@ function parseDeviceId(raw: string): string {
return deviceId;
}
// 双方言 SQL
const BIND_SQL = {
sqlite: "INSERT OR IGNORE INTO device_bindings (device_id, code) VALUES (?, ?)",
pg: "INSERT INTO device_bindings (device_id, code) VALUES ($1, $2) ON CONFLICT (device_id, code) DO NOTHING",
} as const;
const UNBIND_SQL = {
sqlite: "DELETE FROM device_bindings WHERE device_id = ? AND code = ?",
pg: "DELETE FROM device_bindings WHERE device_id = $1 AND code = $2",
} as const;
const BINDINGS_SQL = {
sqlite: `SELECT c.code, c.package_type, c.total_uses, c.used_uses, c.status
FROM device_bindings b
JOIN codes c ON c.code = b.code
WHERE b.device_id = ?
ORDER BY b.created_at, c.code`,
pg: `SELECT c.code, c.package_type, c.total_uses, c.used_uses, c.status
FROM device_bindings b
JOIN codes c ON c.code = b.code
WHERE b.device_id = $1
ORDER BY b.created_at, c.code`,
} as const;
/**
* Create the sync router (cloud-sync of redeemed code benefits).
* Accepts an optional injected database for testing.
@@ -62,40 +84,22 @@ function parseDeviceId(raw: string): string {
* POST /api/sync/bind
* Request: { deviceId: string, code: string }
* Response: 200 { ok: true, access: AccessInfo }
* 400 { error: "设备标识无效" / "兑换码格式不正确" / ... }
* 404 { error: "兑换码不存在,请检查后重试" }
* Idempotent: binding an already-bound code is a no-op success.
*
* GET /api/sync/restore?deviceId=XXX
* Response: 200 { codes: BoundCode[] } (empty array when none)
* 400 { error: "设备标识无效" }
* Response: 200 { codes: BoundCode[] }
*
* POST /api/sync/unbind
* Request: { deviceId: string, code: string }
* Response: 200 { ok: true }
* Idempotent: unbinding a non-existent binding still succeeds.
*/
export function createSyncRouter(injectedDb?: Database.Database): Router {
export function createSyncRouter(injectedDb?: Db): Router {
const router = Router();
const bindStmt = (db: Database.Database) =>
db.prepare("INSERT OR IGNORE INTO device_bindings (device_id, code) VALUES (?, ?)");
const unbindStmt = (db: Database.Database) =>
db.prepare("DELETE FROM device_bindings WHERE device_id = ? AND code = ?");
const bindingsStmt = (db: Database.Database) =>
db.prepare(
`SELECT c.code, c.package_type, c.total_uses, c.used_uses, c.status
FROM device_bindings b
JOIN codes c ON c.code = b.code
WHERE b.device_id = ?
ORDER BY b.created_at, c.code`,
);
/**
* POST /api/sync/bind
* Bind a redeemed code to a device so it can be restored later.
*/
router.post("/bind", (req: Request, res: Response): void => {
router.post("/bind", async (req: Request, res: Response): Promise<void> => {
try {
const { deviceId, code } = req.body as { deviceId?: string; code?: string };
if (!deviceId || typeof deviceId !== "string") {
@@ -109,10 +113,9 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
const db = resolveDb(injectedDb);
const id = parseDeviceId(deviceId);
const normalized = validateFormat(code);
// Verifies the code exists & is still redeemable (active, not expired,
// not exhausted). Throws CodeError with Chinese message + status.
const access: AccessInfo = checkRedeemable(db, normalized);
bindStmt(db).run(id, access.code);
// Verifies the code exists & is still redeemable
const access: AccessInfo = await checkRedeemable(db, normalized);
await dbRun(db, BIND_SQL, [id, access.code]);
res.status(200).json({ ok: true, access });
} catch (err) {
if (err instanceof CodeError) {
@@ -128,7 +131,7 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
* GET /api/sync/restore?deviceId=XXX
* Return all codes bound to this device with their access info.
*/
router.get("/restore", (req: Request, res: Response): void => {
router.get("/restore", async (req: Request, res: Response): Promise<void> => {
try {
const deviceIdParam = req.query.deviceId;
if (!deviceIdParam || typeof deviceIdParam !== "string") {
@@ -137,7 +140,7 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
}
const db = resolveDb(injectedDb);
const id = parseDeviceId(deviceIdParam);
const rows = bindingsStmt(db).all(id) as BindingRow[];
const rows = await dbAll<BindingRow>(db, BINDINGS_SQL, [id]);
const codes: BoundCode[] = rows.map((row) => ({
code: row.code,
packageType: row.package_type,
@@ -158,9 +161,9 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
/**
* POST /api/sync/unbind
* Remove a binding. Idempotent: succeeds even if the binding never existed.
* Remove a binding. Idempotent.
*/
router.post("/unbind", (req: Request, res: Response): void => {
router.post("/unbind", async (req: Request, res: Response): Promise<void> => {
try {
const { deviceId, code } = req.body as { deviceId?: string; code?: string };
if (!deviceId || typeof deviceId !== "string") {
@@ -174,7 +177,7 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
const db = resolveDb(injectedDb);
const id = parseDeviceId(deviceId);
const normalized = validateFormat(code);
unbindStmt(db).run(id, normalized);
await dbRun(db, UNBIND_SQL, [id, normalized]);
res.status(200).json({ ok: true });
} catch (err) {
if (err instanceof CodeError) {
@@ -187,4 +190,4 @@ export function createSyncRouter(injectedDb?: Database.Database): Router {
});
return router;
}
}
+97 -1659
View File
File diff suppressed because it is too large. Load diff
+26 -8
View File
@@ -1,13 +1,32 @@
# PERLER LAB 任务看板
> 生成时间: 2026-08-15T07:12:46.985Z · 任务总数: **137** · 未关闭 Bug: **0**
> 生成时间: 2026-08-15T15:15:25.485+08:00 · 任务总数: **137** · 未关闭 Bug: **0**
## 🤖 Agent 火力面板
| Agent | 状态 | 在办 | 完成 | 累计 | 当前任务 | 活跃时间 |
|---|---|---|---|---|---|---|
| Oracle-Architect-Agent | 🔥在职 | 0 | 10 | 10 | - | 08-14T12:09 |
| PM-Agent | 🔥在职 | 0 | 17 | 17 | - | 08-15T14:39 |
| UI-Designer-Agent | 🔥在职 | 0 | 16 | 16 | - | 08-15T14:39 |
| Frontend-Dev-Agent | 🔥在职 | 0 | 28 | 28 | - | 08-15T14:39 |
| Backend-Dev-Agent | 🔥在职 | 0 | 13 | 13 | - | 08-15T14:39 |
| QA-Tester-Agent | 🔥在职 | 0 | 4 | 4 | - | 08-14T00:39 |
| Backend-Engineer-2 | 🔥在职 | 0 | 9 | 9 | - | 08-14T10:52 |
| Spider-Agent | 🔥在职 | 0 | 22 | 22 | - | 08-14T12:09 |
| 主代理(顶岗) | 🔥在职 | 0 | 3 | 3 | - | 08-13T20:18 |
| GitOps-Engineer | 🔥在职 | 0 | 7 | 7 | - | 08-15T15:12 |
| Release-Manager | 🔥在职 | 0 | 2 | 2 | - | 08-14T10:52 |
| DevOps-Engineer | 🔥在职 | 0 | 2 | 2 | - | 08-14T10:52 |
---
| 状态 | 数量 |
|---|---|
| 待处理 | 0 |
| 开发中 | 1 |
| 开发中 | 0 |
| 待验收 | 0 |
| 验收通过 | 117 |
| 验收通过 | 118 |
| 不合格 | 0 |
| 已关闭 | 19 |
@@ -17,17 +36,15 @@
_空_
## 📋 开发中 (1)
## 📋 开发中 (0)
| ID | 优先级 | 标题 | 实施 | 创建时间 | 认领/提交/测试 | 备注 |
|---|---|---|---|---|---|---|
| **T-137** | 中 | 工程化:V1.2 P0 批次成果入库推送 | GitOps-Engineer | 08-15T15:12 | 认领 08-15T15:12 | |
_空_
## 📋 待验收 (0)
_空_
## 📋 验收通过 (117)
## 📋 验收通过 (118)
| ID | 优先级 | 标题 | 实施 | 创建时间 | 认领/提交/测试 | 备注 |
|---|---|---|---|---|---|---|
@@ -144,6 +161,7 @@ _空_
| **T-134** | 中 | 前端:Showcase与图纸库到详情页链接 | UI-Designer-Agent | 08-15T14:38 | 认领 08-15T14:39<br>提交 08-15T15:02<br>测试 08-15T15:07 | QA验收: WorkCard.tsx缩略图/标题/底部查看详情均链接/work/:id(3处href), onTagCl |
| **T-135** | 中 | 前端:详情页 CreativeWork JSON-LD 注入 | UI-Designer-Agent | 08-15T14:38 | 认领 08-15T14:39<br>提交 08-15T15:02<br>测试 08-15T15:07 | QA验收: script type=application/ld+json @graph三件套-CreativeWork |
| **T-136** | 中 | 工程化:V1.1 验收成果批量入库推送 | GitOps-Engineer | 08-15T14:38 | 认领 08-15T14:39<br>提交 08-15T14:41<br>测试 08-15T15:10 | QA验证通过:git log -1=f53f0a2;ls-remote origin master=f53f0a2b25 |
| **T-137** | 中 | 工程化:V1.2 P0 批次成果入库推送 | GitOps-Engineer | 08-15T15:12 | 认领 08-15T15:12<br>提交 08-15T15:14<br>测试 08-15T15:15 | 346f41d 入库验证通过,23文件,远程一致 |
| **T-016** | 低 | P13 爬虫监控:竞品版本变更检测脚本 | Spider-Agent | 08-13T17:38 | 认领 08-13T17:39<br>提交 08-13T17:54<br>测试 08-13T18:59 | QA实测:指纹记录+无变更+零依赖,PASS | 监控脚本验收通过 |
| **T-017** | 低 | P14 素材库:示例图/演示图案资源整理 | Spider-Agent | 08-13T17:38 | 认领 08-13T17:39<br>提交 08-13T17:54<br>测试 08-13T18:59 | QA实测:demo-cat gridSize=32/palette=8/grid=1024,10张对比图齐全,PASS |
| **T-033** | 低 | 运营:代理合作话术与流程 | PM-Agent | 08-13T18:05 | 认领 08-13T19:34<br>提交 08-13T21:04<br>测试 08-13T21:18 | QA实测:AGENT.md话术/流程/FAQ10条/价目表确认 |