feat: 增强功能批量入库 - 双色彩引擎/抖动/杂色清理/品牌色板/PDF导出/编辑工具/分享/i18n 等验收代码
This commit is contained in:
1 parent
02762400fb
commit
f846fabfc6
77 files changed
+11372
-226
No files matched your search
@@ -6,10 +6,9 @@
|
||||
* AI_IMAGE_API_KEY),未配置接口地址时使用内置 mock 模式生成占位图。
|
||||
*/
|
||||
import type Database from "better-sqlite3";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { deflateSync } from "node:zlib";
|
||||
import type { AccessInfo } from "../types/index.js";
|
||||
import { consumeCode, CodeError } from "../codes/service.js";
|
||||
import { consumeCode, CodeError, createDownloadGrant } from "../codes/service.js";
|
||||
import { buildPrompt, type ChibiCategory, type Composition } from "./prompts.js";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -275,5 +274,8 @@ export async function generateChibiImage(
|
||||
// 3. 生成图片
|
||||
const image = await generateImage(prompt, req);
|
||||
|
||||
return { image, downloadGrant: randomUUID(), access };
|
||||
// 4. 写入一次性下载授权凭证(下载时必须携带,防止绕过生成直接消耗次数)
|
||||
const downloadGrant = createDownloadGrant(db, req.code);
|
||||
|
||||
return { image, downloadGrant, access };
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import type Database from "better-sqlite3";
|
||||
import { getDb } from "../db/index.js";
|
||||
import { generateChibiImage, ChibiError, type GenerateRequest } from "./generate.js";
|
||||
import { findTemplate, type ChibiCategory, type Composition } from "./prompts.js";
|
||||
import { createRateLimiter, RATE_LIMITS } from "../security/rate-limit.js";
|
||||
|
||||
const CATEGORIES: readonly ChibiCategory[] = ["landscape", "person", "pet", "object", "food"];
|
||||
const COMPOSITIONS: readonly Composition[] = ["主体特写", "半幅构图", "完整构图"];
|
||||
@@ -28,7 +29,10 @@ function resolveDb(injected?: Database.Database): Database.Database {
|
||||
export function createChibiRouter(injectedDb?: Database.Database): Router {
|
||||
const router = Router();
|
||||
|
||||
router.post("/generate", async (req: Request, res: Response): Promise<void> => {
|
||||
// 防刷限流: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>;
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@ import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
import type Database from "better-sqlite3";
|
||||
import { getDb } from "../db/index.js";
|
||||
import { consumeCode, redeemCode, getCodeStatus, CodeError, normalizeCode } from "./service.js";
|
||||
import { consumeCodeWithGrant, redeemCode, getCodeStatus, CodeError, ERRORS, normalizeCode } from "./service.js";
|
||||
import { createRateLimiter, RATE_LIMITS } from "../security/rate-limit.js";
|
||||
import { ABUSE_MESSAGE, detectAbuse, logSecurityEvent, markSuspicious } from "../security/abuse.js";
|
||||
|
||||
/**
|
||||
* Format a CodeError into an Express response.
|
||||
@@ -25,6 +27,10 @@ function resolveDb(injected?: Database.Database): Database.Database {
|
||||
export function createCodesRouter(injectedDb?: Database.Database): Router {
|
||||
const router = Router();
|
||||
|
||||
// 防刷限流(每路由实例独立计数,测试互不干扰)
|
||||
const redeemLimiter = createRateLimiter(RATE_LIMITS.redeem)("redeem");
|
||||
const consumeLimiter = createRateLimiter(RATE_LIMITS.consume)("consume");
|
||||
|
||||
/**
|
||||
* POST /api/codes/redeem
|
||||
*
|
||||
@@ -36,18 +42,43 @@ export function createCodesRouter(injectedDb?: Database.Database): Router {
|
||||
* Response: 200 { access: AccessInfo }
|
||||
* 404 { error: "兑换码不存在,请检查后重试" }
|
||||
* 400 { error: "兑换码已用尽" }
|
||||
* 403 { error: "检测到异常操作,请联系客服" } (防刷)
|
||||
* 429 { error: "操作过于频繁,请稍后再试" } (限流)
|
||||
*/
|
||||
router.post("/redeem", (req: Request, res: Response): void => {
|
||||
router.post("/redeem", redeemLimiter, (req: Request, res: Response): void => {
|
||||
try {
|
||||
const { code } = req.body as { code?: string };
|
||||
if (!code || typeof code !== "string") {
|
||||
res.status(400).json({ error: "请输入兑换码" });
|
||||
return;
|
||||
}
|
||||
const access = redeemCode(resolveDb(injectedDb), normalizeCode(code));
|
||||
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);
|
||||
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" &&
|
||||
(err === ERRORS.NOT_FOUND || err === ERRORS.INVALID_FORMAT)
|
||||
) {
|
||||
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);
|
||||
res.status(403).json({ error: ABUSE_MESSAGE });
|
||||
return;
|
||||
}
|
||||
}
|
||||
handleCodeError(res, err);
|
||||
} else {
|
||||
console.error("POST /api/codes/redeem error:", err);
|
||||
@@ -60,20 +91,30 @@ export function createCodesRouter(injectedDb?: Database.Database): Router {
|
||||
* POST /api/codes/consume
|
||||
*
|
||||
* Consume one use of a code. Atomically decrements used_uses in a
|
||||
* transaction. Returns the updated access info + freeDownload flag.
|
||||
* 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 }
|
||||
* Request: { code: string, fileName: string, downloadGrant?: string }
|
||||
* Response: 200 { access: AccessInfo, freeDownload: boolean }
|
||||
* 400 { error: "兑换码已用尽" }
|
||||
* 403 { error: "下载授权无效或已使用" }
|
||||
* 429 { error: "操作过于频繁,请稍后再试" } (限流)
|
||||
*/
|
||||
router.post("/consume", (req: Request, res: Response): void => {
|
||||
router.post("/consume", consumeLimiter, (req: Request, res: Response): void => {
|
||||
try {
|
||||
const { code } = req.body as { code?: string; fileName?: string; downloadGrant?: string };
|
||||
const { code, downloadGrant } = req.body as {
|
||||
code?: string;
|
||||
fileName?: string;
|
||||
downloadGrant?: string;
|
||||
};
|
||||
if (!code || typeof code !== "string") {
|
||||
res.status(400).json({ error: "请输入兑换码" });
|
||||
return;
|
||||
}
|
||||
const access = consumeCode(resolveDb(injectedDb), normalizeCode(code));
|
||||
// 空 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)
|
||||
res.status(200).json({ access, freeDownload: access.remainingUses > 0 });
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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 { PACKAGE_DEFINITIONS } from "../types/index.js";
|
||||
@@ -22,6 +23,14 @@ export interface CodeRow {
|
||||
expired_at: string | null;
|
||||
}
|
||||
|
||||
export interface DownloadGrantRow {
|
||||
grant: string;
|
||||
code: string;
|
||||
order_no: string | null;
|
||||
used: 0 | 1;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export class CodeError extends Error {
|
||||
readonly status: number;
|
||||
readonly code: string;
|
||||
@@ -44,6 +53,7 @@ export const ERRORS = {
|
||||
EXPIRED: new CodeError("兑换码已过期,请联系客服", 400, "CODE_EXPIRED"),
|
||||
EXHAUSTED: new CodeError("兑换码已用尽", 400, "CODE_EXHAUSTED"),
|
||||
INVALID_FORMAT: new CodeError("兑换码格式不正确", 400, "CODE_INVALID_FORMAT"),
|
||||
GRANT_INVALID: new CodeError("下载授权无效或已使用", 403, "GRANT_INVALID"),
|
||||
} as const;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -183,6 +193,35 @@ export function redeemCode(db: Database.Database, rawCode: string): AccessInfo {
|
||||
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
|
||||
@@ -190,32 +229,70 @@ export function redeemCode(db: Database.Database, rawCode: string): AccessInfo {
|
||||
*/
|
||||
export function consumeCode(db: Database.Database, rawCode: string): AccessInfo {
|
||||
const code = validateFormat(rawCode);
|
||||
return db.transaction(() => consumeCore(db, code))();
|
||||
}
|
||||
|
||||
const consumeTx = db.transaction((): AccessInfo => {
|
||||
const row = getCodeByRaw(db, code);
|
||||
if (!row) {
|
||||
throw ERRORS.NOT_FOUND;
|
||||
// ---------------------------------------------------------------------------
|
||||
// 下载授权 (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,
|
||||
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(
|
||||
grant,
|
||||
code,
|
||||
orderNo ?? null,
|
||||
);
|
||||
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 {
|
||||
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;
|
||||
}
|
||||
}
|
||||
if (row.status === "disabled") {
|
||||
throw ERRORS.DISABLED;
|
||||
const access = consumeCore(db, code);
|
||||
if (grantParam !== undefined) {
|
||||
db.prepare("UPDATE download_grants SET used = 1 WHERE grant = ?").run(grantParam);
|
||||
}
|
||||
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 });
|
||||
});
|
||||
|
||||
return consumeTx();
|
||||
return access;
|
||||
})();
|
||||
}
|
||||
|
||||
/** Get current access status without mutating anything. */
|
||||
|
||||
@@ -75,4 +75,35 @@ CREATE TABLE IF NOT EXISTS device_bindings (
|
||||
|
||||
-- 索引:按 code 反查绑定设备
|
||||
CREATE INDEX IF NOT EXISTS idx_device_bindings_code ON device_bindings(code);
|
||||
|
||||
-- 安全事件表(防刷:IP 追踪 + 滥用检测)
|
||||
-- ip 可空:兑换成功/失败等带来源 IP 的事件写入,禁用事件(code_disabled)无来源
|
||||
CREATE TABLE IF NOT EXISTS security_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
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 TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
-- 索引:按兑换码查询安全事件(防刷检测主路径)
|
||||
CREATE INDEX IF NOT EXISTS idx_security_events_code ON security_events(code, event_type, created_at);
|
||||
|
||||
-- 索引:按 IP 查询安全事件(同一 IP 刷码检测)
|
||||
CREATE INDEX IF NOT EXISTS idx_security_events_ip ON security_events(ip, event_type, created_at);
|
||||
|
||||
-- 下载授权表(一次性下载凭证)
|
||||
-- AI 生成成功后写入一行:consume 时必须携带未使用的 grant 且归属同一兑换码,
|
||||
-- 核销时置 used=1,防止绕过生成流程直接消耗次数下载。
|
||||
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 TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
-- 索引:按兑换码查询下载授权
|
||||
CREATE INDEX IF NOT EXISTS idx_download_grants_code ON download_grants(code);
|
||||
`;
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* 品牌导出适配器:为导出文件名附加品牌信息,与前端命名保持一致。
|
||||
*
|
||||
* 前端命名(perler-lab/src/App.tsx handleDownload):
|
||||
* `${baseName}-${gridSize}x${gridSize}-MARD拼豆图纸.png`,如「宠物-64x64-MARD拼豆图纸.png」
|
||||
* 本模块的品牌化命名(在 baseName 与网格尺寸之间插入品牌 id,尾部标签随品牌):
|
||||
* `${baseName}-${brandId}-${gridSize}x${gridSize}-${label}拼豆图纸.png`
|
||||
* 例:宠物-MARD-64x64-MARD拼豆图纸.png、宠物-COCO-64x64-COCO拼豆图纸.png
|
||||
*/
|
||||
|
||||
/** 品牌引用:id 用于文件名中间段;label 用于尾部「xx拼豆图纸」标签,缺省即 id。 */
|
||||
export interface BrandRef {
|
||||
id: string;
|
||||
/** 尾部品牌标签,默认与 id 相同(如 "MARD"、"COCO"、"漫漫")。 */
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export interface ExportFileNameOptions {
|
||||
/** 图纸基础名(不含扩展名),如 "宠物";空/空白时回退为 "拼豆图纸"。 */
|
||||
baseName: string;
|
||||
brand: BrandRef;
|
||||
/** 网格尺寸(边长格数),如 64。 */
|
||||
gridSize: number;
|
||||
}
|
||||
|
||||
/** 生成品牌化导出文件名。 */
|
||||
export function formatExportFileName(options: ExportFileNameOptions): string {
|
||||
const { brand, gridSize } = options;
|
||||
if (!Number.isInteger(gridSize) || gridSize <= 0) {
|
||||
throw new Error(`网格尺寸不合法:${gridSize}`);
|
||||
}
|
||||
const base = options.baseName.trim() || "拼豆图纸";
|
||||
const label = brand.label?.trim() || brand.id;
|
||||
return `${base}-${brand.id}-${gridSize}x${gridSize}-${label}拼豆图纸.png`;
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
/**
|
||||
* 零依赖 PDF 生成器(T-077)。
|
||||
*
|
||||
* 仅使用 Node 内置模块(node:zlib 的 deflate)手写最小但合法的 PDF:
|
||||
* - 对象 1: Catalog / 对象 2: Pages / 对象 3: Page / 对象 4: 内容流(FlateDecode 压缩)
|
||||
* - 对象 5-6: Helvetica / Helvetica-Bold 基础 14 字体(无需嵌入)
|
||||
* - 标准 xref 表 + trailer + startxref
|
||||
*
|
||||
* 已知限制:基础 14 字体只支持 Latin-1 字符集,中文标题无法渲染,
|
||||
* 因此标题会做 Latin-1 兜底(非 Latin-1 字符替换为 ?,为空时使用
|
||||
* 英文默认标题)——竞品 pixel-beads 的 PDF 同样只使用英文/ASCII。
|
||||
*/
|
||||
import { deflateSync } from "node:zlib";
|
||||
import type { UsageStats } from "./usage-stats.js";
|
||||
|
||||
/** 图案 PDF 生成输入 */
|
||||
export interface PatternPdfInput {
|
||||
title: string;
|
||||
gridSize: number;
|
||||
/** 扁平的一维网格,长度为 gridSize × gridSize;单元格 color 可为十六进制或色板编码 */
|
||||
grid: { color: string }[];
|
||||
stats: UsageStats;
|
||||
}
|
||||
|
||||
// ---- A4 页面常量(pt,1pt = 1/72 英寸) ----
|
||||
const PAGE_W = 595.28;
|
||||
const PAGE_H = 841.89;
|
||||
const MARGIN = 36;
|
||||
const CONTENT_W = PAGE_W - MARGIN * 2;
|
||||
|
||||
// ---- 表格列位置 ----
|
||||
const SWATCH_X = MARGIN; // 色块左边缘
|
||||
const SWATCH_W = 24; // 色块宽度
|
||||
const CODE_X = 72; // 编码列
|
||||
const HEX_X = 210; // 十六进制列
|
||||
const COUNT_X = 330; // 数量列
|
||||
const PERCENT_RIGHT = PAGE_W - MARGIN; // 百分比右对齐边缘
|
||||
|
||||
/** 数字转字符串:保留至多 2 位小数并去掉末尾 0 */
|
||||
function fmt(v: number): string {
|
||||
return String(Math.round(v * 100) / 100);
|
||||
}
|
||||
|
||||
/** 规范化颜色为 #rrggbb(小写),支持 #rgb / #rrggbb / rrggbb;非法返回 null */
|
||||
function normalizeHex(raw: string): string | null {
|
||||
let hex = raw.trim().replace(/^#/, "");
|
||||
if (hex.length === 3) {
|
||||
hex = hex
|
||||
.split("")
|
||||
.map((ch) => ch + ch)
|
||||
.join("");
|
||||
}
|
||||
if (!/^[0-9a-fA-F]{6}$/.test(hex)) return null;
|
||||
return "#" + hex.toLowerCase();
|
||||
}
|
||||
|
||||
/** 解析十六进制颜色为 0-1 的 RGB 分量;失败返回 null */
|
||||
function parseHexColor(raw: string): { r: number; g: number; b: number } | null {
|
||||
const norm = normalizeHex(raw);
|
||||
if (norm === null) return null;
|
||||
const n = parseInt(norm.slice(1), 16);
|
||||
return { r: ((n >> 16) & 255) / 255, g: ((n >> 8) & 255) / 255, b: (n & 255) / 255 };
|
||||
}
|
||||
|
||||
/** 单元格颜色 → 规范化 #rrggbb:支持直接十六进制或色板编码(经 stats 映射) */
|
||||
function cellColor(raw: string, codeToHex: ReadonlyMap<string, string>): string {
|
||||
const c = raw.trim();
|
||||
if (c === "") return "";
|
||||
const hex = normalizeHex(c);
|
||||
if (hex !== null) return hex;
|
||||
return codeToHex.get(c) ?? "";
|
||||
}
|
||||
|
||||
/** 转义 PDF 字符串字面量;非 Latin-1 字符替换为 ?(基础 14 字体限制) */
|
||||
function escText(s: string): string {
|
||||
let out = "";
|
||||
for (const ch of s) {
|
||||
const cp = ch.codePointAt(0);
|
||||
if (cp === undefined) continue;
|
||||
if (cp === 40) out += "\\(";
|
||||
else if (cp === 41) out += "\\)";
|
||||
else if (cp === 92) out += "\\\\";
|
||||
else if (cp >= 32 && cp <= 126) out += ch;
|
||||
else if (cp >= 160 && cp <= 255) out += ch;
|
||||
else out += "?";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成图案图纸 PDF(A4 单页):
|
||||
* - 标题(Helvetica-Bold,Latin-1 兜底)
|
||||
* - 珠子网格:按单元格颜色绘制填充矩形,同行同色自动合并为长矩形
|
||||
* (单元格足够大时再画格线,大网格省略格线以免内容流过大)
|
||||
* - 颜色用量表:色块 + 编码 + 十六进制 + 数量 + 百分比
|
||||
* - 汇总行:总珠数 + 10% 额外建议
|
||||
*/
|
||||
export function generatePatternPdf(input: PatternPdfInput): Buffer {
|
||||
const { title, gridSize, grid, stats } = input;
|
||||
|
||||
// 标题 Latin-1 兜底:空标题使用英文默认名
|
||||
const safeTitle = (() => {
|
||||
const t = escText(title);
|
||||
return t.trim() === "" ? "Perler Pattern" : t;
|
||||
})();
|
||||
|
||||
// 色板编码 → 十六进制映射(用于以编码填色的单元格)
|
||||
const codeToHex = new Map<string, string>();
|
||||
for (const c of stats.perColor) {
|
||||
codeToHex.set(c.code, c.hex);
|
||||
const norm = normalizeHex(c.hex);
|
||||
if (norm !== null) codeToHex.set(norm, c.hex);
|
||||
}
|
||||
|
||||
// ---- 布局计算:网格与表格共享一页,表格优先保证完整 ----
|
||||
const colorCount = stats.perColor.length;
|
||||
const titleBaseline = PAGE_H - MARGIN - 14; // 标题基线 y
|
||||
const gridTop = titleBaseline - 22; // 网格顶部 y
|
||||
const gapGridTable = 16; // 网格与表格间距
|
||||
const tableHeaderH = 22; // 表头行高
|
||||
const totalRowH = 26; // 汇总行高
|
||||
const drawableH = gridTop - MARGIN; // 网格 + 表格可用高度
|
||||
const minGridH = Math.min(60, drawableH); // 网格最小高度
|
||||
const maxTableH = drawableH - minGridH; // 表格可用高度
|
||||
// 行高自适应:颜色很多时压缩行高,保证表格完整落在页面内
|
||||
const rowH =
|
||||
colorCount === 0
|
||||
? 18
|
||||
: Math.max(8, Math.min(18, Math.floor((maxTableH - tableHeaderH - totalRowH - 14) / colorCount)));
|
||||
const tableH = tableHeaderH + totalRowH + 14 + colorCount * rowH;
|
||||
const gridH = Math.min(Math.max(drawableH - tableH, minGridH), CONTENT_W, gridSize * 16);
|
||||
const cell = gridH / gridSize;
|
||||
const gridLeft = (PAGE_W - gridH) / 2; // 网格水平居中
|
||||
const gridBottom = gridTop - gridH;
|
||||
const tableTop = gridBottom - gapGridTable;
|
||||
const rowFont = Math.min(10, rowH - 1); // 行文本字号
|
||||
const strokeCells = cell >= 4; // 单元格足够大才绘制格线
|
||||
|
||||
const ops: string[] = [];
|
||||
|
||||
// ---- 标题 ----
|
||||
ops.push(`BT /F2 16 Tf ${fmt(MARGIN)} ${fmt(titleBaseline)} Td (${safeTitle}) Tj ET`);
|
||||
|
||||
// ---- 珠子网格 ----
|
||||
ops.push(`1 1 1 rg ${fmt(gridLeft)} ${fmt(gridBottom)} ${fmt(gridH)} ${fmt(gridH)} re f`);
|
||||
for (let row = 0; row < gridSize; row++) {
|
||||
const y = gridTop - (row + 1) * cell; // 本行矩形底边 y
|
||||
let runStart = 0; // 当前同色连续段起点
|
||||
let runColor = ""; // 当前段颜色
|
||||
for (let col = 0; col <= gridSize; col++) {
|
||||
const hex =
|
||||
col < gridSize ? cellColor(grid[row * gridSize + col]?.color ?? "", codeToHex) : "";
|
||||
if (col === gridSize || hex !== runColor) {
|
||||
// 结束一段连续同色,绘制为单个填充矩形
|
||||
if (runColor !== "" && col > runStart) {
|
||||
const x = gridLeft + runStart * cell;
|
||||
const w = (col - runStart) * cell;
|
||||
const rgb = parseHexColor(runColor);
|
||||
if (rgb !== null) {
|
||||
ops.push(
|
||||
`${fmt(rgb.r)} ${fmt(rgb.g)} ${fmt(rgb.b)} rg ${fmt(x)} ${fmt(y)} ${fmt(w)} ${fmt(cell)} re f`,
|
||||
);
|
||||
if (strokeCells) {
|
||||
ops.push(`0.85 0.85 0.85 RG 0.2 w ${fmt(x)} ${fmt(y)} ${fmt(w)} ${fmt(cell)} re S`);
|
||||
}
|
||||
}
|
||||
}
|
||||
runStart = col;
|
||||
runColor = hex;
|
||||
}
|
||||
}
|
||||
}
|
||||
// 网格外边框
|
||||
ops.push(`0.25 0.25 0.25 RG 1 w ${fmt(gridLeft)} ${fmt(gridBottom)} ${fmt(gridH)} ${fmt(gridH)} re S`);
|
||||
|
||||
// ---- 颜色用量表 ----
|
||||
ops.push("0 0 0 rg 0.6 0.6 0.6 RG 0.5 w");
|
||||
const headerY = tableTop - 9; // 表头文本基线
|
||||
ops.push(`BT /F2 11 Tf ${fmt(SWATCH_X)} ${fmt(headerY)} Td (Color) Tj ET`);
|
||||
ops.push(`BT /F2 11 Tf ${fmt(CODE_X)} ${fmt(headerY)} Td (Code) Tj ET`);
|
||||
ops.push(`BT /F2 11 Tf ${fmt(HEX_X)} ${fmt(headerY)} Td (Hex) Tj ET`);
|
||||
ops.push(`BT /F2 11 Tf ${fmt(COUNT_X)} ${fmt(headerY)} Td (Count) Tj ET`);
|
||||
ops.push(`BT /F2 11 Tf ${fmt(PERCENT_RIGHT - 7 * 11 * 0.5)} ${fmt(headerY)} Td (Percent) Tj ET`);
|
||||
// 表头分隔线
|
||||
const headerLineY = tableTop - tableHeaderH;
|
||||
ops.push(`${fmt(MARGIN)} ${fmt(headerLineY)} m ${fmt(MARGIN + CONTENT_W)} ${fmt(headerLineY)} l S`);
|
||||
|
||||
for (let i = 0; i < colorCount; i++) {
|
||||
const c = stats.perColor[i]!;
|
||||
const rowTop = headerLineY - i * rowH;
|
||||
const swatchY = rowTop - rowH + 3;
|
||||
const swatchH = rowH - 6;
|
||||
const rgb = parseHexColor(c.hex);
|
||||
// 色块:合法十六进制填充颜色,否则白底
|
||||
ops.push(
|
||||
`${rgb === null ? "1 1 1" : `${fmt(rgb.r)} ${fmt(rgb.g)} ${fmt(rgb.b)}`} rg ${fmt(SWATCH_X)} ${fmt(swatchY)} ${fmt(SWATCH_W)} ${fmt(swatchH)} re f`,
|
||||
);
|
||||
ops.push(`0 0 0 RG 0.5 w ${fmt(SWATCH_X)} ${fmt(swatchY)} ${fmt(SWATCH_W)} ${fmt(swatchH)} re S`);
|
||||
const baseline = rowTop - Math.ceil((rowH - rowFont) / 2) - 2;
|
||||
ops.push(`BT /F1 ${rowFont} Tf ${fmt(CODE_X)} ${fmt(baseline)} Td (${escText(c.code)}) Tj ET`);
|
||||
ops.push(`BT /F1 ${rowFont} Tf ${fmt(HEX_X)} ${fmt(baseline)} Td (${escText(c.hex)}) Tj ET`);
|
||||
ops.push(`BT /F1 ${rowFont} Tf ${fmt(COUNT_X)} ${fmt(baseline)} Td (${String(c.count)}) Tj ET`);
|
||||
const pct = `${c.percent.toFixed(1)}%`;
|
||||
// 百分比右对齐(按 Helvetica 平均字宽估算)
|
||||
ops.push(
|
||||
`BT /F1 ${rowFont} Tf ${fmt(PERCENT_RIGHT - pct.length * rowFont * 0.5)} ${fmt(baseline)} Td (${pct}) Tj ET`,
|
||||
);
|
||||
}
|
||||
|
||||
// ---- 汇总行:总珠数 + 10% 额外建议 ----
|
||||
const totalTop = headerLineY - colorCount * rowH;
|
||||
ops.push(`${fmt(MARGIN)} ${fmt(totalTop)} m ${fmt(MARGIN + CONTENT_W)} ${fmt(totalTop)} l S`);
|
||||
ops.push(
|
||||
`BT /F2 12 Tf ${fmt(MARGIN)} ${fmt(totalTop - 15)} Td (Total beads: ${String(stats.totalBeads)} | +10% extra recommended: ${String(stats.extra10Percent)}) Tj ET`,
|
||||
);
|
||||
|
||||
// ---- 组装 PDF 文件 ----
|
||||
// 内容流使用 FlateDecode(zlib deflate)压缩
|
||||
const content = Buffer.from(ops.join("\n") + "\n", "utf8");
|
||||
const compressed = deflateSync(content);
|
||||
|
||||
const obj1 = Buffer.from("1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n", "ascii");
|
||||
const obj2 = Buffer.from("2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n", "ascii");
|
||||
const obj3 = Buffer.from(
|
||||
`3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${fmt(PAGE_W)} ${fmt(PAGE_H)}] /Resources << /Font << /F1 5 0 R /F2 6 0 R >> >> /Contents 4 0 R >>\nendobj\n`,
|
||||
"ascii",
|
||||
);
|
||||
const obj4 = Buffer.concat([
|
||||
Buffer.from(`4 0 obj\n<< /Length ${compressed.length} /Filter /FlateDecode >>\nstream\n`, "ascii"),
|
||||
compressed,
|
||||
Buffer.from("\nendstream\nendobj\n", "ascii"),
|
||||
]);
|
||||
const obj5 = Buffer.from(
|
||||
"5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n",
|
||||
"ascii",
|
||||
);
|
||||
const obj6 = Buffer.from(
|
||||
"6 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>\nendobj\n",
|
||||
"ascii",
|
||||
);
|
||||
const objects: Buffer[] = [obj1, obj2, obj3, obj4, obj5, obj6];
|
||||
|
||||
// 二进制注释行让查看器把文件当二进制处理(避免破坏流数据)
|
||||
const header = Buffer.from("%PDF-1.4\n%\xe2\xe3\xcf\xd3\n", "latin1");
|
||||
const parts: Buffer[] = [header];
|
||||
const offsets: number[] = new Array(objects.length + 1).fill(0);
|
||||
let pos = header.length;
|
||||
for (let i = 0; i < objects.length; i++) {
|
||||
offsets[i + 1] = pos;
|
||||
parts.push(objects[i]!);
|
||||
pos += objects[i]!.length;
|
||||
}
|
||||
const xrefStart = pos;
|
||||
|
||||
// xref 条目必须恰好 20 字节(含行尾)
|
||||
const xrefLines: string[] = [`xref\n0 ${objects.length + 1}\n`];
|
||||
xrefLines.push("0000000000 65535 f \n");
|
||||
for (let i = 1; i <= objects.length; i++) {
|
||||
xrefLines.push(`${String(offsets[i]!).padStart(10, "0")} 00000 n \n`);
|
||||
}
|
||||
xrefLines.push(
|
||||
`trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xrefStart}\n%%EOF\n`,
|
||||
);
|
||||
const tail = Buffer.from(xrefLines.join(""), "ascii");
|
||||
|
||||
return Buffer.concat([...parts, tail]);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* 图案导出路由(T-076 + T-077):PDF 图纸生成 + 珠子用量统计。
|
||||
* 纯计算模块,不依赖数据库。
|
||||
*
|
||||
* POST /api/export/pdf { title?, gridSize, grid, palette } → application/pdf(附件下载)
|
||||
* POST /api/export/stats { palette, totalBeads } → 200 { stats }
|
||||
*/
|
||||
import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
import { computeUsageStats } from "./usage-stats.js";
|
||||
import { generatePatternPdf } from "./pdf.js";
|
||||
|
||||
const MAX_GRID_SIZE = 512;
|
||||
|
||||
/**
|
||||
* 校验并标准化色板为 { code, hex, count } 列表;
|
||||
* 任一元素缺 code/hex(非字符串)视为整体非法,count 缺失时按 0 处理。
|
||||
*/
|
||||
function parsePalette(raw: unknown): { code: string; hex: string; count: number }[] | null {
|
||||
if (!Array.isArray(raw)) return null;
|
||||
const out: { code: string; hex: string; count: number }[] = [];
|
||||
for (const item of raw) {
|
||||
if (typeof item !== "object" || item === null) return null;
|
||||
const rec = item as Record<string, unknown>;
|
||||
if (typeof rec.code !== "string" || typeof rec.hex !== "string") return null;
|
||||
const count =
|
||||
typeof rec.count === "number" && Number.isFinite(rec.count)
|
||||
? Math.max(0, Math.floor(rec.count))
|
||||
: 0;
|
||||
out.push({ code: rec.code, hex: rec.hex, count });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 创建图案导出路由(无状态,无需注入数据库) */
|
||||
export function createExportRouter(): Router {
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* POST /api/export/pdf
|
||||
* 请求: { title?, gridSize, grid: { color }[], palette: { code, hex, count }[] }
|
||||
* 响应: 200 application/pdf(Content-Disposition: attachment)
|
||||
* 400 中文参数提示 / 500 服务器内部错误
|
||||
*/
|
||||
router.post("/pdf", (req: Request, res: Response): void => {
|
||||
try {
|
||||
const body = (req.body ?? {}) as Record<string, unknown>;
|
||||
const title = typeof body.title === "string" ? body.title : "";
|
||||
const gridSize = Number(body.gridSize);
|
||||
if (!Number.isInteger(gridSize) || gridSize < 1 || gridSize > MAX_GRID_SIZE) {
|
||||
res.status(400).json({ error: "网格尺寸无效" });
|
||||
return;
|
||||
}
|
||||
const grid = body.grid;
|
||||
if (!Array.isArray(grid) || grid.length !== gridSize * gridSize) {
|
||||
res.status(400).json({ error: "网格数据与尺寸不匹配" });
|
||||
return;
|
||||
}
|
||||
const cells: { color: string }[] = grid.map((item) => {
|
||||
if (typeof item !== "object" || item === null) return { color: "" };
|
||||
const rec = item as Record<string, unknown>;
|
||||
return { color: typeof rec.color === "string" ? rec.color : "" };
|
||||
});
|
||||
const palette = parsePalette(body.palette);
|
||||
if (palette === null) {
|
||||
res.status(400).json({ error: "色板数据无效" });
|
||||
return;
|
||||
}
|
||||
// 珠子总数 = 网格中实际填色的格子数
|
||||
const totalBeads = cells.filter((c) => c.color.trim() !== "").length;
|
||||
const stats = computeUsageStats(palette, totalBeads);
|
||||
const pdf = generatePatternPdf({ title, gridSize, grid: cells, stats });
|
||||
res
|
||||
.status(200)
|
||||
.setHeader("Content-Type", "application/pdf")
|
||||
.setHeader("Content-Disposition", 'attachment; filename="perler-pattern.pdf"')
|
||||
.send(pdf);
|
||||
} catch (err) {
|
||||
console.error("POST /api/export/pdf error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/export/stats
|
||||
* 请求: { palette: { code, hex, count }[], totalBeads: number }
|
||||
* 响应: 200 { stats } / 400 中文参数提示 / 500 服务器内部错误
|
||||
*/
|
||||
router.post("/stats", (req: Request, res: Response): void => {
|
||||
try {
|
||||
const body = (req.body ?? {}) as Record<string, unknown>;
|
||||
const palette = parsePalette(body.palette);
|
||||
if (palette === null) {
|
||||
res.status(400).json({ error: "色板数据无效" });
|
||||
return;
|
||||
}
|
||||
const totalBeads = Number(body.totalBeads);
|
||||
if (!Number.isInteger(totalBeads) || totalBeads < 0) {
|
||||
res.status(400).json({ error: "珠子总数无效" });
|
||||
return;
|
||||
}
|
||||
res.status(200).json({ stats: computeUsageStats(palette, totalBeads) });
|
||||
} catch (err) {
|
||||
console.error("POST /api/export/stats error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 珠子用量统计(T-076)。
|
||||
*
|
||||
* 由前端算法产出的色板(每个颜色一个编码 + 十六进制 + 用量)计算
|
||||
* 每个颜色的百分比,以及「多买 10% 备用」的建议数量。
|
||||
*/
|
||||
|
||||
/** 单个颜色的用量统计 */
|
||||
export interface PerColorUsage {
|
||||
code: string;
|
||||
hex: string;
|
||||
count: number;
|
||||
/** 占总珠数的百分比(保留 1 位小数) */
|
||||
percent: number;
|
||||
}
|
||||
|
||||
/** 整张图案的用量统计 */
|
||||
export interface UsageStats {
|
||||
/** 图案总珠数 */
|
||||
totalBeads: number;
|
||||
/** 实际使用到的颜色数量(count > 0 的颜色) */
|
||||
colorCount: number;
|
||||
/** 各颜色用量明细 */
|
||||
perColor: PerColorUsage[];
|
||||
/** 建议额外备用的珠数:总珠数的 10%,向上取整 */
|
||||
extra10Percent: number;
|
||||
}
|
||||
|
||||
/** 百分比保留 1 位小数 */
|
||||
function round1(v: number): number {
|
||||
return Math.round(v * 10) / 10;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算用量统计。
|
||||
*
|
||||
* @param palette 色板:{ code, hex, count },count 为 0 的颜色会被过滤
|
||||
* @param totalBeads 图案总珠数(由调用方提供,作为百分比的基数)
|
||||
*/
|
||||
export function computeUsageStats(
|
||||
palette: { code: string; hex: string; count: number }[],
|
||||
totalBeads: number,
|
||||
): UsageStats {
|
||||
const perColor: PerColorUsage[] = palette
|
||||
.filter((p) => p.count > 0)
|
||||
.map((p) => ({
|
||||
code: p.code,
|
||||
hex: p.hex,
|
||||
count: p.count,
|
||||
percent: totalBeads > 0 ? round1((p.count / totalBeads) * 100) : 0,
|
||||
}));
|
||||
|
||||
return {
|
||||
totalBeads,
|
||||
colorCount: perColor.length,
|
||||
perColor,
|
||||
// 10% 额外建议,向上取整(如 60 颗 → 66)
|
||||
extra10Percent: Math.ceil(totalBeads * 1.1),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* 品牌色板元数据 API(palette API)。
|
||||
*
|
||||
* 设计说明:
|
||||
* 1. 后端只嵌入「最小品牌注册表」(品牌 id / 名称 / 色号条数),
|
||||
* 不复制 291 标准色的完整映射数据 —— 完整数据(hex/rgb/lab + 各品牌色号)
|
||||
* 在前端 perler-lab/src/lib/brand-palettes.ts。需要全量数据时请同步该前端模块。
|
||||
* 2. 色号列表在模块加载时从参考 CSV 读取一次(非每请求读取),按品牌列
|
||||
* 派生出去重、排序的色号数组;列头(品牌名)为 UTF-8 中文。
|
||||
* 参考文件:D:\拼豆\competitor-analysis\palettes\zippland-品牌色号对应表.csv
|
||||
* 容器等不含该 CSV 的环境可用环境变量 PALETTES_CSV_PATH 指定路径;
|
||||
* 读取失败时告警并回退为空列表(不阻断服务启动)。
|
||||
* 3. colorCount = 该品牌在 291 标准色映射中的色号条数("-" 无对应色号的行不计),
|
||||
* 与前端实测一致:MARD 291 / COCO 291 / 漫漫 290 / 盼盼 291 / 咪小窝 291。
|
||||
* 注意:漫漫 的映射含一个重复色号(S4),去重后实际列表为 289 条。
|
||||
*/
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
|
||||
/** 品牌元信息(最小注册表,与前端 BRANDS 的 id/name 对齐)。 */
|
||||
export interface BrandMeta {
|
||||
id: string;
|
||||
name: string;
|
||||
colorCount: number;
|
||||
}
|
||||
|
||||
/** 品牌注册表:id/name 取自前端 src/lib/brand-palettes.ts 的 BRANDS。 */
|
||||
export const BRANDS: readonly BrandMeta[] = [
|
||||
{ id: "MARD", name: "MARD 玛德", colorCount: 291 },
|
||||
{ id: "COCO", name: "COCO", colorCount: 291 },
|
||||
{ id: "漫漫", name: "漫漫", colorCount: 290 },
|
||||
{ id: "盼盼", name: "盼盼", colorCount: 291 },
|
||||
{ id: "咪小窝", name: "咪小窝", colorCount: 291 },
|
||||
];
|
||||
|
||||
/** 参考 CSV 默认路径:仓库根目录 D:\拼豆\competitor-analysis\palettes\。 */
|
||||
const DEFAULT_CSV_PATH = resolve(
|
||||
dirname(fileURLToPath(import.meta.url)),
|
||||
"../../..",
|
||||
"competitor-analysis",
|
||||
"palettes",
|
||||
"zippland-品牌色号对应表.csv",
|
||||
);
|
||||
|
||||
/**
|
||||
* 读取参考 CSV(模块加载时执行一次),按品牌 id 派生出
|
||||
* 「去重、排序」的色号列表("-" 与空单元格视为无对应色号,跳过)。
|
||||
*/
|
||||
function loadCodesByBrand(): ReadonlyMap<string, string[]> {
|
||||
const csvPath = process.env["PALETTES_CSV_PATH"] ?? DEFAULT_CSV_PATH;
|
||||
let text: string;
|
||||
try {
|
||||
text = readFileSync(csvPath, "utf8");
|
||||
} catch (err) {
|
||||
// 容器镜像不含参考 CSV:告警并回退为空列表,保持服务可启动。
|
||||
console.warn(`[palettes] 无法读取品牌色号 CSV(${csvPath}):${(err as Error).message}`);
|
||||
return new Map<string, string[]>();
|
||||
}
|
||||
|
||||
const lines = text
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
if (lines.length === 0) return new Map<string, string[]>();
|
||||
|
||||
const headers = lines[0]!.split(",");
|
||||
const raw = new Map<string, Set<string>>();
|
||||
for (const header of headers) {
|
||||
raw.set(header, new Set<string>());
|
||||
}
|
||||
for (const line of lines.slice(1)) {
|
||||
const cells = line.split(",");
|
||||
headers.forEach((header, index) => {
|
||||
const code = cells[index]?.trim() ?? "";
|
||||
if (code !== "" && code !== "-") {
|
||||
raw.get(header)?.add(code);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const result = new Map<string, string[]>();
|
||||
for (const [header, codes] of raw) {
|
||||
result.set(header, [...codes].sort());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 模块加载时读取一次(见任务要求:Read CSV at module load, not per-request)。 */
|
||||
const CODES_BY_BRAND: ReadonlyMap<string, string[]> = loadCodesByBrand();
|
||||
|
||||
/**
|
||||
* 创建 palette 路由。
|
||||
*
|
||||
* GET /api/palettes
|
||||
* 200 → [{ id, name, colorCount }](5 个品牌)
|
||||
*
|
||||
* GET /api/palettes/:brandId/codes
|
||||
* 200 → string[](该品牌色号列表,去重、排序)
|
||||
* 404 → { error: "品牌不存在" }
|
||||
*/
|
||||
export function createPalettesRouter(): Router {
|
||||
const router = Router();
|
||||
|
||||
router.get("/", (_req: Request, res: Response): void => {
|
||||
res.status(200).json(
|
||||
BRANDS.map(({ id, name, colorCount }) => ({ id, name, colorCount })),
|
||||
);
|
||||
});
|
||||
|
||||
router.get("/:brandId/codes", (req: Request, res: Response): void => {
|
||||
const raw = req.params["brandId"];
|
||||
const brandId = typeof raw === "string" ? raw : "";
|
||||
const codes = CODES_BY_BRAND.get(brandId);
|
||||
if (codes === undefined) {
|
||||
res.status(404).json({ error: "品牌不存在" });
|
||||
return;
|
||||
}
|
||||
res.status(200).json(codes);
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -2,27 +2,45 @@ import type { PaymentProvider, PaymentMethod } from "./types.js";
|
||||
import { MockPaymentProvider } from "./mock.js";
|
||||
import { WeChatPayProvider } from "./wechat.js";
|
||||
|
||||
/** 启用真实微信支付所需的环境变量(全部配置齐全才会返回真实 Provider) */
|
||||
const WECHAT_REQUIRED_ENV: readonly string[] = [
|
||||
"WECHAT_MCH_ID",
|
||||
"WECHAT_APP_ID",
|
||||
"WECHAT_API_KEY",
|
||||
"WECHAT_SERIAL_NO",
|
||||
"WECHAT_PRIVATE_KEY",
|
||||
"WECHAT_PLATFORM_CERT",
|
||||
"WECHAT_NOTIFY_URL",
|
||||
];
|
||||
|
||||
/**
|
||||
* 是否启用真实微信支付:
|
||||
* - WECHAT_PAY_ENABLED === "true"(显式开关,防止误开)
|
||||
* - NODE_ENV === "production"(本地开发/测试一律走 mock)
|
||||
* - 所有 WECHAT_* 必需环境变量齐全
|
||||
*/
|
||||
export function isWechatPayEnabled(): boolean {
|
||||
if (process.env.WECHAT_PAY_ENABLED !== "true") return false;
|
||||
if ((process.env.NODE_ENV ?? "development") !== "production") return false;
|
||||
return WECHAT_REQUIRED_ENV.every((key) => !!process.env[key]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Payment provider factory.
|
||||
*
|
||||
* Returns the mock provider when:
|
||||
* - NODE_ENV is not "production" (local development), OR
|
||||
* - the WeChat Pay environment variables are not configured.
|
||||
* 返回 mock provider 当:
|
||||
* - NODE_ENV 不是 "production",或
|
||||
* - WECHAT_PAY_ENABLED 未显式设为 "true",或
|
||||
* - 微信支付环境变量未配置齐全。
|
||||
*
|
||||
* Returns the real WeChatPayProvider in production with credentials present.
|
||||
* 仅在生产环境 + 开关开启 + 凭据齐全时返回真实 WeChatPayProvider。
|
||||
*/
|
||||
export function getPaymentProvider(method: PaymentMethod): PaymentProvider {
|
||||
if (method === "alipay") {
|
||||
// Alipay integration not yet implemented - always fall back to mock for now.
|
||||
// 支付宝尚未接入,一律回退 mock。
|
||||
return new MockPaymentProvider();
|
||||
}
|
||||
const env = process.env.NODE_ENV ?? "development";
|
||||
const configured =
|
||||
!!process.env.WECHAT_MCH_ID &&
|
||||
!!process.env.WECHAT_API_KEY &&
|
||||
!!process.env.WECHAT_NOTIFY_URL;
|
||||
|
||||
if (env !== "production" || !configured) {
|
||||
if (!isWechatPayEnabled()) {
|
||||
return new MockPaymentProvider();
|
||||
}
|
||||
return new WeChatPayProvider();
|
||||
|
||||
@@ -10,7 +10,7 @@ import type { PaymentProvider, PaymentRequest, PaymentResult } from "./types.js"
|
||||
* the user "visits" the URL, then the frontend calls the mock callback endpoint.
|
||||
*/
|
||||
export class MockPaymentProvider implements PaymentProvider {
|
||||
createPayment(request: PaymentRequest): PaymentResult {
|
||||
async createPayment(request: PaymentRequest): Promise<PaymentResult> {
|
||||
const { orderNo, amountCents, method } = request;
|
||||
|
||||
// Build a realistic-looking mock payment URL
|
||||
@@ -26,9 +26,9 @@ export class MockPaymentProvider implements PaymentProvider {
|
||||
return result;
|
||||
}
|
||||
|
||||
verifyCallback(
|
||||
async verifyCallback(
|
||||
params: Record<string, string | string[] | undefined>,
|
||||
): { orderNo: string; transactionId: string } | null {
|
||||
): Promise<{ orderNo: string; transactionId: string } | null> {
|
||||
const orderNo = typeof params["orderNo"] === "string" ? params["orderNo"] : undefined;
|
||||
if (!orderNo) {
|
||||
return null;
|
||||
|
||||
@@ -2,9 +2,10 @@ import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
import type Database from "better-sqlite3";
|
||||
import { getDb } from "../db/index.js";
|
||||
import { getPaymentProvider } from "./index.js";
|
||||
import { getPaymentProvider, isWechatPayEnabled } from "./index.js";
|
||||
import type { PaymentMethod } from "./types.js";
|
||||
import { generateCode, insertCodes } from "../codes/service.js";
|
||||
import { createRateLimiter, RATE_LIMITS } from "../security/rate-limit.js";
|
||||
|
||||
/** 套餐定义(金额单位为分) */
|
||||
const PACKAGES: Record<string, { name: string; cents: number; uses: number }> = {
|
||||
@@ -27,6 +28,19 @@ function genOrderNo(): string {
|
||||
return `PL${ts}${rand}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记订单为已支付并生成权益兑换码(幂等调用方需先判断状态)。
|
||||
*/
|
||||
function markOrderPaid(db: Database.Database, orderNo: string, packageName: string): 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);
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建支付订单路由。
|
||||
* 注入 DB 便于测试(与 codes 模块一致)。
|
||||
@@ -34,12 +48,15 @@ function genOrderNo(): string {
|
||||
export function createPaymentRouter(injectedDb?: Database.Database): 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 }
|
||||
* 响应: 200 { order, payment } / 400 { error } / 429 限流
|
||||
*/
|
||||
router.post("/", (req: Request, res: Response): void => {
|
||||
router.post("/", ordersLimiter, async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const db = resolveDb(injectedDb);
|
||||
const { packageName, paymentMethod } = req.body as {
|
||||
@@ -59,7 +76,7 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
|
||||
const createdAt = new Date().toISOString();
|
||||
db.prepare(
|
||||
`INSERT INTO orders (order_no, package_name, amount_cents, payment_method, status, created_at)
|
||||
VALUES (?, ?, ?, ?, 'pending', ?)`
|
||||
VALUES (?, ?, ?, ?, 'pending', ?)`,
|
||||
).run(orderNo, pkg.name, pkg.cents, paymentMethod, createdAt);
|
||||
|
||||
const order = {
|
||||
@@ -70,7 +87,7 @@ export function createPaymentRouter(injectedDb?: Database.Database): Router {
|
||||
status: "pending",
|
||||
createdAt,
|
||||
};
|
||||
const payment = getPaymentProvider(paymentMethod as PaymentMethod).createPayment({
|
||||
const payment = await getPaymentProvider(paymentMethod as PaymentMethod).createPayment({
|
||||
orderNo,
|
||||
amountCents: pkg.cents,
|
||||
description: `${pkg.name} - ${pkg.uses} 次生成权益`,
|
||||
@@ -109,38 +126,109 @@ 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: "缺少原始请求体" });
|
||||
return;
|
||||
}
|
||||
const headerOf = (name: string): string | undefined => {
|
||||
const value = req.headers[name];
|
||||
return typeof value === "string" ? value : undefined;
|
||||
};
|
||||
const verified = await getPaymentProvider("wechat").verifyCallback({
|
||||
body: rawBody.toString("utf8"),
|
||||
"Wechatpay-Signature": headerOf("wechatpay-signature"),
|
||||
"Wechatpay-Timestamp": headerOf("wechatpay-timestamp"),
|
||||
"Wechatpay-Nonce": headerOf("wechatpay-nonce"),
|
||||
"Wechatpay-Serial": headerOf("wechatpay-serial"),
|
||||
});
|
||||
if (!verified) {
|
||||
res.status(400).json({ code: "FAIL", message: "回调验签失败" });
|
||||
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;
|
||||
if (!row) {
|
||||
res.status(400).json({ code: "FAIL", message: "订单不存在" });
|
||||
return;
|
||||
}
|
||||
if (row.status !== "paid") {
|
||||
// 已支付订单不再重复生成兑换码(微信可能重试回调,保持幂等)
|
||||
markOrderPaid(db, verified.orderNo, row.package_name);
|
||||
}
|
||||
res.status(200).json({ code: "SUCCESS", message: "成功" });
|
||||
return;
|
||||
}
|
||||
|
||||
// ---- mock 模式:简化流程,直接标记 paid(本地开发/前端联调) ----
|
||||
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;
|
||||
if (!row) {
|
||||
res.status(404).json({ error: "订单不存在" });
|
||||
return;
|
||||
}
|
||||
if (row.status === "paid") {
|
||||
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);
|
||||
res.status(200).json({ ok: true, order: updated, accessCode });
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/orders/:orderNo/pay-callback
|
||||
* 模拟支付回调:将订单标记为 paid 并自动生成权益兑换码(幂等)。
|
||||
* mock 模式:模拟支付回调(路径携带订单号,直接标记 paid)。
|
||||
* 真实模式:同 /notify,验签通过后才标记 paid(订单号以回调体为准)。
|
||||
*/
|
||||
router.post("/:orderNo/pay-callback", (req: Request, res: Response): void => {
|
||||
try {
|
||||
const db = resolveDb(injectedDb);
|
||||
const orderNo = req.params.orderNo as string;
|
||||
const row = db.prepare("SELECT * FROM orders WHERE order_no = ?").get(orderNo) as
|
||||
| { order_no: string; status: string; package_name: string }
|
||||
| undefined;
|
||||
if (!row) {
|
||||
res.status(404).json({ error: "订单不存在" });
|
||||
return;
|
||||
}
|
||||
if (row.status === "paid") {
|
||||
res.status(200).json({ ok: true, order: row });
|
||||
return;
|
||||
}
|
||||
// 生成权益兑换码:一条库存记录 + 订单关联
|
||||
const pkg = (PACKAGES[row.package_name] ?? 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);
|
||||
const updated = db.prepare("SELECT * FROM orders WHERE order_no = ?").get(orderNo);
|
||||
res.status(200).json({ ok: true, order: updated, accessCode: code });
|
||||
} catch (err) {
|
||||
handlePayCallback(req, res).catch((err: unknown) => {
|
||||
console.error("POST pay-callback error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
res.status(500).json({ code: "FAIL", message: "服务器内部错误" });
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/orders/notify
|
||||
* 真实微信支付回调入口(WECHAT_NOTIFY_URL 指向此地址)。
|
||||
* mock 模式下不存在真实回调,返回 400。
|
||||
*/
|
||||
router.post("/notify", (req: Request, res: Response): void => {
|
||||
if (!isWechatPayEnabled()) {
|
||||
res.status(400).json({ error: "Mock 模式无真实支付回调" });
|
||||
return;
|
||||
}
|
||||
handlePayCallback(req, res).catch((err: unknown) => {
|
||||
console.error("POST /notify error:", err);
|
||||
res.status(500).json({ code: "FAIL", message: "服务器内部错误" });
|
||||
});
|
||||
});
|
||||
|
||||
return router;
|
||||
|
||||
@@ -32,14 +32,22 @@ export interface PaymentProvider {
|
||||
/**
|
||||
* Create a payment request.
|
||||
* Returns a payment URL and optional QR code for the user to complete payment.
|
||||
* 异步:真实支付渠道需要发起网络请求(微信支付 Native 下单)。
|
||||
*/
|
||||
createPayment(request: PaymentRequest): PaymentResult;
|
||||
createPayment(request: PaymentRequest): Promise<PaymentResult>;
|
||||
|
||||
/**
|
||||
* Verify a payment callback from the provider.
|
||||
* Returns the orderNo and provider transactionId if valid, or null if invalid.
|
||||
*
|
||||
* 参数说明(键值约定):
|
||||
* - mock 模式: { orderNo: string }
|
||||
* - 真实微信支付: { body: 原始请求体, "Wechatpay-Signature": ..., "Wechatpay-Timestamp": ...,
|
||||
* "Wechatpay-Nonce": ..., "Wechatpay-Serial": ... }
|
||||
*/
|
||||
verifyCallback(params: Record<string, string | string[] | undefined>): { orderNo: string; transactionId: string } | null;
|
||||
verifyCallback(
|
||||
params: Record<string, string | string[] | undefined>,
|
||||
): Promise<{ orderNo: string; transactionId: string } | null>;
|
||||
}
|
||||
|
||||
// ---- Payment Provider Error ----
|
||||
|
||||
@@ -1,66 +1,284 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { PaymentProvider, PaymentRequest, PaymentResult } from "./types.js";
|
||||
import { PaymentProviderError } from "./types.js";
|
||||
import crypto from "node:crypto";
|
||||
|
||||
/** 微信支付 v3 Native 下单接口地址 */
|
||||
const NATIVE_API_URL = "https://api.mch.weixin.qq.com/v3/pay/transactions/native";
|
||||
/** 下单接口路径(构造请求签名原文时使用) */
|
||||
const NATIVE_API_PATH = "/v3/pay/transactions/native";
|
||||
/** 请求超时(毫秒) */
|
||||
const REQUEST_TIMEOUT_MS = 10_000;
|
||||
/** 回调时间戳允许的最大偏差(秒),用于防重放 */
|
||||
const TIMESTAMP_TOLERANCE_SEC = 300;
|
||||
|
||||
/**
|
||||
* WeChat Pay v3 provider (skeleton for production).
|
||||
* 从微信支付平台证书中提取公钥。
|
||||
* 优先按 X.509 证书解析;若传入的是裸公钥 PEM 则回退到 createPublicKey。
|
||||
*/
|
||||
function loadPlatformPublicKey(pem: string): crypto.KeyObject {
|
||||
try {
|
||||
return new crypto.X509Certificate(pem).publicKey;
|
||||
} catch {
|
||||
return crypto.createPublicKey(pem);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密微信支付回调报文(AEAD_AES_256_GCM,使用 APIv3 密钥)。
|
||||
*
|
||||
* Requires these environment variables:
|
||||
* - WECHAT_MCH_ID 商户号
|
||||
* - WECHAT_API_KEY APIv3 密钥 (32 bytes)
|
||||
* - WECHAT_NOTIFY_URL 支付回调通知地址 (公网 HTTPS)
|
||||
* 微信加密报文结构:nonce(12 字节) || 密文 || 认证标签(16 字节),
|
||||
* 附加数据(AAD)为回调 JSON 中 resource.associated_data 字段。
|
||||
*
|
||||
* The createPayment / verifyCallback implementations follow the WeChat Pay
|
||||
* v3 API structure but do NOT perform real network calls yet - wire the
|
||||
* actual HTTP calls to https://api.mch.weixin.qq.com/ when merchant
|
||||
* credentials are available.
|
||||
* 独立导出以便单元测试(配合已知测试向量)。
|
||||
*/
|
||||
export function decryptAes256Gcm(ciphertextB64: string, associatedData: string, apiV3Key: string): string {
|
||||
const key = Buffer.from(apiV3Key, "utf8");
|
||||
if (key.length !== 32) {
|
||||
throw new Error("APIv3 密钥必须是 32 字节");
|
||||
}
|
||||
const data = Buffer.from(ciphertextB64, "base64");
|
||||
if (data.length < 12 + 16) {
|
||||
throw new Error("密文长度非法(至少需要 nonce 12 字节 + 认证标签 16 字节)");
|
||||
}
|
||||
const nonce = data.subarray(0, 12);
|
||||
const authTag = data.subarray(data.length - 16);
|
||||
const ciphertext = data.subarray(12, data.length - 16);
|
||||
const decipher = crypto.createDecipheriv("aes-256-gcm", key, nonce);
|
||||
decipher.setAAD(Buffer.from(associatedData, "utf8"));
|
||||
decipher.setAuthTag(authTag);
|
||||
const plain = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
|
||||
return plain.toString("utf8");
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验微信支付回调签名(RSA-SHA256,微信平台证书公钥)。
|
||||
*
|
||||
* 待签名原文:`${Wechatpay-Timestamp}\n${Wechatpay-Nonce}\n${原始请求体}\n`
|
||||
*/
|
||||
export function verifyWechatSignature(
|
||||
message: string,
|
||||
signatureB64: string,
|
||||
platformPublicKey: crypto.KeyObject,
|
||||
): boolean {
|
||||
try {
|
||||
return crypto.verify(
|
||||
"RSA-SHA256",
|
||||
Buffer.from(message, "utf8"),
|
||||
platformPublicKey,
|
||||
Buffer.from(signatureB64, "base64"),
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WeChat Pay v3 真实支付 Provider(Native 扫码支付)。
|
||||
*
|
||||
* 依赖环境变量:
|
||||
* - WECHAT_MCH_ID 商户号
|
||||
* - WECHAT_APP_ID 商户 AppID(Native 下单请求体必填)
|
||||
* - WECHAT_API_KEY APIv3 密钥(32 字节,仅用于回调数据 AES-256-GCM 解密)
|
||||
* - WECHAT_SERIAL_NO 商户 API 证书序列号(请求签名头 serial_no)
|
||||
* - WECHAT_PRIVATE_KEY 商户 API 私钥(PEM,用于请求签名 RSA-SHA256)
|
||||
* - WECHAT_PLATFORM_CERT 微信平台证书(PEM,用于回调验签)
|
||||
* - WECHAT_NOTIFY_URL 支付结果回调通知地址(公网 HTTPS)
|
||||
*
|
||||
* 注意:v3 请求签名使用商户私钥做 RSA-SHA256(Authorization 头名为
|
||||
* WECHATPAY2-SHA256-RSA2048);WECHAT_API_KEY 是对称密钥,只用于解密回调
|
||||
* 报文,不参与签名。
|
||||
*/
|
||||
export class WeChatPayProvider implements PaymentProvider {
|
||||
private readonly mchId: string;
|
||||
private readonly appId: string;
|
||||
private readonly apiKey: string;
|
||||
private readonly serialNo: string;
|
||||
private readonly privateKey: crypto.KeyObject;
|
||||
private readonly notifyUrl: string;
|
||||
private readonly platformPublicKey: crypto.KeyObject;
|
||||
|
||||
constructor() {
|
||||
const mchId = process.env.WECHAT_MCH_ID ?? "";
|
||||
const appId = process.env.WECHAT_APP_ID ?? "";
|
||||
const apiKey = process.env.WECHAT_API_KEY ?? "";
|
||||
const serialNo = process.env.WECHAT_SERIAL_NO ?? "";
|
||||
// 环境变量可能以字面 "\n" 单行形式存储 PEM,先还原为真实换行
|
||||
const privateKeyPem = (process.env.WECHAT_PRIVATE_KEY ?? "").replace(/\\n/g, "\n");
|
||||
const notifyUrl = process.env.WECHAT_NOTIFY_URL ?? "";
|
||||
if (!mchId || !apiKey || !notifyUrl) {
|
||||
throw new PaymentProviderError("微信支付未配置(缺少 WECHAT_MCH_ID / WECHAT_API_KEY / WECHAT_NOTIFY_URL)", "PAYMENT_NOT_CONFIGURED", 500);
|
||||
const platformCert = (process.env.WECHAT_PLATFORM_CERT ?? "").replace(/\\n/g, "\n");
|
||||
|
||||
const missing: string[] = [];
|
||||
if (!mchId) missing.push("WECHAT_MCH_ID");
|
||||
if (!appId) missing.push("WECHAT_APP_ID");
|
||||
if (!apiKey) missing.push("WECHAT_API_KEY");
|
||||
if (!serialNo) missing.push("WECHAT_SERIAL_NO");
|
||||
if (!privateKeyPem) missing.push("WECHAT_PRIVATE_KEY");
|
||||
if (!notifyUrl) missing.push("WECHAT_NOTIFY_URL");
|
||||
if (!platformCert) missing.push("WECHAT_PLATFORM_CERT");
|
||||
if (missing.length > 0) {
|
||||
throw new PaymentProviderError(
|
||||
`微信支付未配置(缺少 ${missing.join(" / ")})`,
|
||||
"PAYMENT_NOT_CONFIGURED",
|
||||
500,
|
||||
);
|
||||
}
|
||||
if (Buffer.byteLength(apiKey, "utf8") !== 32) {
|
||||
throw new PaymentProviderError("WECHAT_API_KEY 必须是 32 字节(APIv3 密钥)", "PAYMENT_NOT_CONFIGURED", 500);
|
||||
}
|
||||
|
||||
this.mchId = mchId;
|
||||
this.appId = appId;
|
||||
this.apiKey = apiKey;
|
||||
this.serialNo = serialNo;
|
||||
this.notifyUrl = notifyUrl;
|
||||
this.platformPublicKey = loadPlatformPublicKey(platformCert);
|
||||
try {
|
||||
this.privateKey = crypto.createPrivateKey(privateKeyPem);
|
||||
} catch {
|
||||
throw new PaymentProviderError("WECHAT_PRIVATE_KEY 不是合法的 PEM 私钥", "PAYMENT_NOT_CONFIGURED", 500);
|
||||
}
|
||||
}
|
||||
|
||||
createPayment(request: PaymentRequest): PaymentResult {
|
||||
const { orderNo, amountCents, description } = request;
|
||||
// 微信支付 v3 下单请求体(Native 扫码支付)
|
||||
/**
|
||||
* 微信支付 v3 Native 下单。
|
||||
* 返回 code_url(扫码支付二维码内容),同时作为 url 与 qrCode 返回:
|
||||
* Native 扫码支付没有跳转页面,前端直接用 qrCode 渲染二维码。
|
||||
*/
|
||||
async createPayment(request: PaymentRequest): Promise<PaymentResult> {
|
||||
const payload = {
|
||||
appid: process.env.WECHAT_APP_ID ?? "",
|
||||
appid: this.appId,
|
||||
mchid: this.mchId,
|
||||
description,
|
||||
out_trade_no: orderNo,
|
||||
description: request.description,
|
||||
out_trade_no: request.orderNo,
|
||||
notify_url: this.notifyUrl,
|
||||
amount: { total: amountCents, currency: "CNY" },
|
||||
amount: { total: request.amountCents, currency: "CNY" },
|
||||
};
|
||||
const sign = this.signPayload(JSON.stringify(payload));
|
||||
// TODO: 调用 https://api.mch.weixin.qq.com/v3/pay/transactions/native
|
||||
// 解析返回的 code_url 作为二维码内容。
|
||||
void sign;
|
||||
const url = `https://pay.weixin.qq.com/native?out_trade_no=${encodeURIComponent(orderNo)}`;
|
||||
return { url, qrCode: url };
|
||||
const body = JSON.stringify(payload);
|
||||
|
||||
// 构造 v3 请求签名原文:POST\n<路径>\n<时间戳>\n<随机串>\n<请求体>\n
|
||||
const timestamp = String(Math.floor(Date.now() / 1000));
|
||||
const nonceStr = crypto.randomBytes(16).toString("hex");
|
||||
const message = `POST\n${NATIVE_API_PATH}\n${timestamp}\n${nonceStr}\n${body}\n`;
|
||||
const signature = crypto
|
||||
.sign("RSA-SHA256", Buffer.from(message, "utf8"), this.privateKey)
|
||||
.toString("base64");
|
||||
const authorization =
|
||||
`WECHATPAY2-SHA256-RSA2048 mchid="${this.mchId}",` +
|
||||
`nonce_str="${nonceStr}",timestamp="${timestamp}",` +
|
||||
`serial_no="${this.serialNo}",signature="${signature}"`;
|
||||
|
||||
let resp: Response;
|
||||
try {
|
||||
resp = await fetch(NATIVE_API_URL, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: authorization,
|
||||
"User-Agent": "perler-lab-server",
|
||||
},
|
||||
body,
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
} catch (err) {
|
||||
throw new PaymentProviderError(
|
||||
`微信支付下单请求失败:${err instanceof Error ? err.message : String(err)}`,
|
||||
"WECHAT_NETWORK_ERROR",
|
||||
502,
|
||||
);
|
||||
}
|
||||
|
||||
const text = await resp.text();
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch {
|
||||
throw new PaymentProviderError(
|
||||
`微信支付下单响应不是合法 JSON(HTTP ${resp.status})`,
|
||||
"WECHAT_API_ERROR",
|
||||
502,
|
||||
);
|
||||
}
|
||||
if (!resp.ok) {
|
||||
const errBody = parsed as { code?: unknown; message?: unknown };
|
||||
throw new PaymentProviderError(
|
||||
`微信支付下单失败(HTTP ${resp.status}):` +
|
||||
`${typeof errBody.message === "string" ? errBody.message : "未知错误"}` +
|
||||
`${typeof errBody.code === "string" ? `(${errBody.code})` : ""}`,
|
||||
"WECHAT_API_ERROR",
|
||||
502,
|
||||
);
|
||||
}
|
||||
const codeUrl = (parsed as { code_url?: unknown }).code_url;
|
||||
if (typeof codeUrl !== "string" || codeUrl.length === 0) {
|
||||
throw new PaymentProviderError("微信支付下单响应缺少 code_url", "WECHAT_API_ERROR", 502);
|
||||
}
|
||||
return { url: codeUrl, qrCode: codeUrl };
|
||||
}
|
||||
|
||||
verifyCallback(params: Record<string, string | string[] | undefined>): { orderNo: string; transactionId: string } | null {
|
||||
// 微信回调以 JSON body + Wechatpay-Signature 请求头验签。
|
||||
// 此处以参数 orderNo 做占位校验,生产环境需验证签名与金额。
|
||||
const orderNo = typeof params["orderNo"] === "string" ? params["orderNo"] : undefined;
|
||||
if (!orderNo) return null;
|
||||
return { orderNo, transactionId: `WX${Date.now()}` };
|
||||
}
|
||||
/**
|
||||
* 校验微信支付回调:
|
||||
* 1. 校验 Wechatpay-Signature(微信平台证书公钥,RSA-SHA256)+ 时间戳防重放
|
||||
* 2. 用 APIv3 密钥 AES-256-GCM 解密 resource.ciphertext
|
||||
* 3. 校验 trade_state === "SUCCESS",返回 out_trade_no 与 transaction_id
|
||||
* 任何一步失败返回 null(路由层拒绝该回调)。
|
||||
*/
|
||||
async verifyCallback(
|
||||
params: Record<string, string | string[] | undefined>,
|
||||
): Promise<{ orderNo: string; transactionId: string } | null> {
|
||||
const header = (key: string): string | undefined => {
|
||||
const value = params[key];
|
||||
return typeof value === "string" ? value : undefined;
|
||||
};
|
||||
const body = header("body");
|
||||
const signature = header("Wechatpay-Signature");
|
||||
const timestamp = header("Wechatpay-Timestamp");
|
||||
const nonce = header("Wechatpay-Nonce");
|
||||
if (!body || !signature || !timestamp || !nonce) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** HMAC-SHA256 签名(占位实现,生产需按微信 v3 规范签名) */
|
||||
private signPayload(payload: string): string {
|
||||
return crypto.createHmac("sha256", this.apiKey).update(payload).digest("hex");
|
||||
// 防重放:回调时间戳偏差超过 5 分钟直接拒绝
|
||||
const ts = Number(timestamp);
|
||||
if (!Number.isFinite(ts) || Math.abs(Date.now() / 1000 - ts) > TIMESTAMP_TOLERANCE_SEC) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 1) 验签:原文 = 时间戳\n随机串\n原始请求体\n
|
||||
const message = `${timestamp}\n${nonce}\n${body}\n`;
|
||||
if (!verifyWechatSignature(message, signature, this.platformPublicKey)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2) 解密 resource(AES-256-GCM,APIv3 密钥)
|
||||
let envelope: { resource?: { ciphertext?: unknown; associated_data?: unknown } };
|
||||
try {
|
||||
envelope = JSON.parse(body) as { resource?: { ciphertext?: unknown; associated_data?: unknown } };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const ciphertext = envelope.resource?.ciphertext;
|
||||
const associatedData = envelope.resource?.associated_data;
|
||||
if (typeof ciphertext !== "string" || ciphertext.length === 0) {
|
||||
return null;
|
||||
}
|
||||
let detail: unknown;
|
||||
try {
|
||||
detail = JSON.parse(
|
||||
decryptAes256Gcm(ciphertext, typeof associatedData === "string" ? associatedData : "", this.apiKey),
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 3) 校验支付结果(金额与订单状态已由平台签名保证真实性)
|
||||
const payment = detail as { out_trade_no?: unknown; transaction_id?: unknown; trade_state?: unknown };
|
||||
if (payment.trade_state !== "SUCCESS") {
|
||||
return null;
|
||||
}
|
||||
if (typeof payment.out_trade_no !== "string" || typeof payment.transaction_id !== "string") {
|
||||
return null;
|
||||
}
|
||||
return { orderNo: payment.out_trade_no, transactionId: payment.transaction_id };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import type Database from "better-sqlite3";
|
||||
|
||||
/**
|
||||
* 兑换码防刷检测(防滥用)。
|
||||
*
|
||||
* 判定规则(命中任一即视为异常):
|
||||
* 1. 同一兑换码 24 小时内被超过 5 个不同 IP 兑换 → 疑似共享/泄露码(薅羊毛);
|
||||
* 2. 同一 IP 10 分钟内对无效兑换码累计超过 50 次尝试 → 疑似暴力枚举。
|
||||
*
|
||||
* IP 追踪依赖 security_events 表(见 src/db/schema.ts):
|
||||
* redemption_logs 无 IP 列,兑换成功/失败事件统一写入 security_events 携带来源 IP。
|
||||
*/
|
||||
|
||||
/** 安全事件类型(对应 security_events.event_type 列的 CHECK 约束) */
|
||||
export type SecurityEventType = "redeem_ok" | "redeem_fail" | "code_disabled";
|
||||
|
||||
/** 安全事件动作(对应 security_events.action) */
|
||||
export type SecurityAction = "redeem" | "consume" | "disable";
|
||||
|
||||
/** 疑似异常时返回给客户端的提示 */
|
||||
export const ABUSE_MESSAGE = "检测到异常操作,请联系客服";
|
||||
|
||||
// ---- 防刷阈值 ----
|
||||
/** 24 小时内同一兑换码来自不同 IP 的数量上限 */
|
||||
const MAX_DISTINCT_IPS_PER_CODE = 5;
|
||||
/** 10 分钟内同一 IP 尝试无效兑换码的次数上限 */
|
||||
const MAX_FAILED_ATTEMPTS_PER_IP = 50;
|
||||
/** 不同 IP 统计窗口 */
|
||||
const DISTINCT_IP_WINDOW_HOURS = 24;
|
||||
/** 无效尝试统计窗口(分钟) */
|
||||
const FAIL_WINDOW_MINUTES = 10;
|
||||
|
||||
/**
|
||||
* 记录一条安全事件(IP 追踪)。
|
||||
* @param ip 来源 IP,可空(如禁用事件无来源)
|
||||
* @param code 涉及/尝试的兑换码(未规范化的原值由调用方负责 normalize)
|
||||
*/
|
||||
export function logSecurityEvent(
|
||||
db: Database.Database,
|
||||
ip: string | null,
|
||||
code: string,
|
||||
action: SecurityAction,
|
||||
eventType: SecurityEventType,
|
||||
): void {
|
||||
db.prepare("INSERT INTO security_events (ip, code, action, event_type) VALUES (?, ?, ?, ?)").run(
|
||||
ip,
|
||||
code,
|
||||
action,
|
||||
eventType,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测兑换码是否存在滥用行为。
|
||||
*
|
||||
* @param db 数据库实例
|
||||
* @param code 兑换码(已规范化)
|
||||
* @param ip 当前请求来源 IP(可选)。提供时同时校验"同一 IP 无效尝试"规则;
|
||||
* 不提供时退化为按该兑换码分组统计。
|
||||
* @returns 判定为滥用返回 true
|
||||
*/
|
||||
export function detectAbuse(db: Database.Database, 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 };
|
||||
if (distinct.c > MAX_DISTINCT_IPS_PER_CODE) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 规则 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', ?)`,
|
||||
)
|
||||
.get(ip, `-${FAIL_WINDOW_MINUTES} minutes`) as { c: number };
|
||||
if (failed.c > MAX_FAILED_ATTEMPTS_PER_IP) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 未提供 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`,
|
||||
)
|
||||
.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 {
|
||||
const result = db
|
||||
.prepare("UPDATE codes SET status = 'disabled' WHERE code = ? AND status != 'disabled'")
|
||||
.run(code);
|
||||
logSecurityEvent(db, null, code, "disable", "code_disabled");
|
||||
return result.changes > 0;
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { NextFunction, Request, RequestHandler, Response } from "express";
|
||||
|
||||
/**
|
||||
* 内存滑动窗口限流器(防刷)。
|
||||
*
|
||||
* 按 (动作名, IP) 维度维护每个窗口内的请求时间戳:
|
||||
* - 窗口内请求数达到 max 时返回 429;
|
||||
* - 时间戳滑出窗口后自动放行(滑动窗口,无需定时器);
|
||||
* - 周期性清理空桶,防止内存无限增长。
|
||||
*
|
||||
* 内存实现适合单进程部署;多进程/多实例部署时应换成 Redis 等共享存储。
|
||||
*/
|
||||
|
||||
/** 限流配置 */
|
||||
export interface RateLimitConfig {
|
||||
/** 窗口大小(毫秒) */
|
||||
windowMs: number;
|
||||
/** 窗口内每个 IP 允许的最大请求数 */
|
||||
max: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 各动作的限流配置(单位:次/小时/IP)。
|
||||
* 常量导出供路由与测试共用。
|
||||
*/
|
||||
export const RATE_LIMITS = {
|
||||
/** 兑换码兑换:10 次/小时/IP */
|
||||
redeem: { windowMs: 60 * 60 * 1000, max: 10 },
|
||||
/** 兑换码核销(下载消耗):30 次/小时/IP */
|
||||
consume: { windowMs: 60 * 60 * 1000, max: 30 },
|
||||
/** 创建支付订单:5 次/小时/IP */
|
||||
orders: { windowMs: 60 * 60 * 1000, max: 5 },
|
||||
/** AI 生成:10 次/小时/IP */
|
||||
chibiGenerate: { windowMs: 60 * 60 * 1000, max: 10 },
|
||||
} as const;
|
||||
|
||||
/** 429 响应文案 */
|
||||
export const RATE_LIMIT_MESSAGE = "操作过于频繁,请稍后再试";
|
||||
|
||||
/**
|
||||
* 限流中间件工厂。
|
||||
* 用法:createRateLimiter(RATE_LIMITS.redeem)("redeem")
|
||||
* 返回的中间件以 action 名称 + req.ip 为键独立计数。
|
||||
*/
|
||||
export function createRateLimiter(config: RateLimitConfig): (action: string) => RequestHandler {
|
||||
/** key = `${action}:${ip}` → 窗口内请求时间戳(升序) */
|
||||
const buckets = new Map<string, number[]>();
|
||||
let lastCleanup = Date.now();
|
||||
|
||||
const pruneExpired = (now: number): void => {
|
||||
for (const [key, timestamps] of buckets) {
|
||||
while (timestamps.length > 0 && timestamps[0]! <= now - config.windowMs) {
|
||||
timestamps.shift();
|
||||
}
|
||||
if (timestamps.length === 0) {
|
||||
buckets.delete(key);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (action: string): RequestHandler => {
|
||||
return (req: Request, res: Response, next: NextFunction): void => {
|
||||
const now = Date.now();
|
||||
|
||||
// 周期性清理过期桶(每个窗口周期一次,摊销成本)
|
||||
if (now - lastCleanup > config.windowMs) {
|
||||
pruneExpired(now);
|
||||
lastCleanup = now;
|
||||
}
|
||||
|
||||
const ip = req.ip ?? "unknown";
|
||||
const key = `${action}:${ip}`;
|
||||
|
||||
// 剔除已滑出窗口的时间戳
|
||||
const timestamps = buckets.get(key) ?? [];
|
||||
while (timestamps.length > 0 && timestamps[0]! <= now - config.windowMs) {
|
||||
timestamps.shift();
|
||||
}
|
||||
|
||||
if (timestamps.length >= config.max) {
|
||||
res.status(429).json({ error: RATE_LIMIT_MESSAGE });
|
||||
return;
|
||||
}
|
||||
|
||||
timestamps.push(now);
|
||||
buckets.set(key, timestamps);
|
||||
next();
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
import express from "express";
|
||||
import type { Express } from "express";
|
||||
import type { Express, Request } from "express";
|
||||
import type Database from "better-sqlite3";
|
||||
import { initDatabase } from "./db/index.js";
|
||||
import { createCodesRouter } from "./codes/routes.js";
|
||||
import { createPaymentRouter } from "./payment/routes.js";
|
||||
import { createChibiRouter } from "./chibi/routes.js";
|
||||
import { createSyncRouter } from "./sync/routes.js";
|
||||
import { createPalettesRouter } from "./palettes/routes.js";
|
||||
import { createExportRouter } from "./export/routes.js";
|
||||
|
||||
const PORT = parseInt(process.env["PORT"] ?? "8788", 10);
|
||||
|
||||
@@ -38,7 +40,17 @@ export function createApp(db?: Database.Database): Express {
|
||||
});
|
||||
|
||||
// ---- Middleware ----
|
||||
app.use(express.json());
|
||||
// 通过 verify 捕获原始请求体:微信支付回调验签必须基于未经解析的原始
|
||||
// body 字节(Wechatpay-Signature 是对原始报文的签名)。
|
||||
// limit 放宽到 20mb:图案导出需要承载 512×512 的大网格 JSON(约 8MB)。
|
||||
app.use(
|
||||
express.json({
|
||||
limit: "20mb",
|
||||
verify: (req, _res, buf) => {
|
||||
(req as Request & { rawBody?: Buffer }).rawBody = buf;
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// ---- Health check ----
|
||||
app.get("/health", (_req, res) => {
|
||||
@@ -50,6 +62,8 @@ export function createApp(db?: Database.Database): Express {
|
||||
app.use("/api/orders", createPaymentRouter(db));
|
||||
app.use("/api/chibi", createChibiRouter(db));
|
||||
app.use("/api/sync", createSyncRouter(db));
|
||||
app.use("/api/palettes", createPalettesRouter());
|
||||
app.use("/api/export", createExportRouter());
|
||||
|
||||
// ---- 404 handler ----
|
||||
app.use((_req, res) => {
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import request from "supertest";
|
||||
import type Database from "better-sqlite3";
|
||||
import type { Express } from "express";
|
||||
import { createApp } from "../server.js";
|
||||
import { createTestDatabase } from "../db/index.js";
|
||||
import { generateCodes, insertCodes, getCodeStatus } from "../codes/service.js";
|
||||
|
||||
/** 建一个含有效兑换码的测试库。 */
|
||||
function setupDb(uses = 3): { db: Database.Database; code: string } {
|
||||
const db = createTestDatabase();
|
||||
const codes = generateCodes(1);
|
||||
insertCodes(db, codes, "体验包", uses);
|
||||
return { db, code: codes[0]! };
|
||||
}
|
||||
|
||||
/** 构造合法 generate 请求体。 */
|
||||
function genRequest(code: string, overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
code,
|
||||
image: "data:image/png;base64,iVBORw0KGgo=",
|
||||
category: "pet",
|
||||
subtype: "cat",
|
||||
gridSize: 48,
|
||||
colorCount: 16,
|
||||
composition: "主体特写",
|
||||
detailTags: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过真实 generate 流程签发一张下载授权(mock 模式,无需 AI 接口)。
|
||||
* 返回 { grant, app, db, code }。
|
||||
*/
|
||||
async function issueGrant(
|
||||
app: Express,
|
||||
code: string,
|
||||
): Promise<{ grant: string; res: request.Response }> {
|
||||
const res = await request(app).post("/api/chibi/generate").send(genRequest(code));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.downloadGrant).toMatch(/^[0-9a-f]{32}$/);
|
||||
return { grant: res.body.downloadGrant as string, res };
|
||||
}
|
||||
|
||||
const FAKE_GRANT = "ab".repeat(16); // 合法长度但数据库中不存在
|
||||
|
||||
describe("下载授权 (download_grants) 核销", () => {
|
||||
it("生成后持有效 grant 消费成功,且 grant 被标记为已使用", async () => {
|
||||
const { db, code } = setupDb(3);
|
||||
const app = createApp(db);
|
||||
|
||||
// 生成消耗 1 次,签发 grant
|
||||
const { grant } = await issueGrant(app, code);
|
||||
expect(getCodeStatus(db, code).remainingUses).toBe(2);
|
||||
|
||||
// 带 grant 消费:校验通过 + 扣减 + 置 used
|
||||
const res = await request(app)
|
||||
.post("/api/codes/consume")
|
||||
.send({ code, fileName: "chibi.png", downloadGrant: grant });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.access.remainingUses).toBe(1);
|
||||
expect(res.body.freeDownload).toBe(true);
|
||||
|
||||
const row = db.prepare("SELECT used FROM download_grants WHERE grant = ?").get(grant) as {
|
||||
used: number;
|
||||
};
|
||||
expect(row.used).toBe(1);
|
||||
});
|
||||
|
||||
it("已使用的 grant 再次消费返回 403,且不再扣减次数", async () => {
|
||||
const { db, code } = setupDb(3);
|
||||
const app = createApp(db);
|
||||
const { grant } = await issueGrant(app, code);
|
||||
|
||||
const first = await request(app)
|
||||
.post("/api/codes/consume")
|
||||
.send({ code, fileName: "a.png", downloadGrant: grant });
|
||||
expect(first.status).toBe(200);
|
||||
|
||||
const second = await request(app)
|
||||
.post("/api/codes/consume")
|
||||
.send({ code, fileName: "b.png", downloadGrant: grant });
|
||||
|
||||
expect(second.status).toBe(403);
|
||||
expect(second.body.error).toBe("下载授权无效或已使用");
|
||||
// 失败时次数保持不变(generate 1 次 + 有效消费 1 次 = 剩 1)
|
||||
expect(getCodeStatus(db, code).remainingUses).toBe(1);
|
||||
});
|
||||
|
||||
it("伪造/不存在的 grant 返回 403,且不扣减次数", async () => {
|
||||
const { db, code } = setupDb(3);
|
||||
const app = createApp(db);
|
||||
await issueGrant(app, code); // generate 消耗 1 次
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/codes/consume")
|
||||
.send({ code, fileName: "a.png", downloadGrant: FAKE_GRANT });
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error).toBe("下载授权无效或已使用");
|
||||
expect(getCodeStatus(db, code).remainingUses).toBe(2);
|
||||
});
|
||||
|
||||
it("不带 grant 直接消费仍可用(向后兼容)", async () => {
|
||||
const { db, code } = setupDb(3);
|
||||
const app = createApp(db);
|
||||
|
||||
const res = await request(app)
|
||||
.post("/api/codes/consume")
|
||||
.send({ code, fileName: "a.png" });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.access.remainingUses).toBe(2);
|
||||
expect(getCodeStatus(db, code).remainingUses).toBe(2);
|
||||
});
|
||||
|
||||
it("grant 归属其他兑换码时返回 403,且双方状态不变", async () => {
|
||||
const db = createTestDatabase();
|
||||
const codes = generateCodes(2);
|
||||
insertCodes(db, codes, "体验包", 3);
|
||||
const [codeA, codeB] = codes;
|
||||
const app = createApp(db);
|
||||
|
||||
// A 生成签发 grant(A 剩 2)
|
||||
const { grant } = await issueGrant(app, codeA!);
|
||||
|
||||
// 用 B 的兑换码携带 A 的 grant 消费 → 403
|
||||
const res = await request(app)
|
||||
.post("/api/codes/consume")
|
||||
.send({ code: codeB, fileName: "a.png", downloadGrant: grant });
|
||||
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error).toBe("下载授权无效或已使用");
|
||||
// B 未扣减,grant 未被置 used
|
||||
expect(getCodeStatus(db, codeB!).remainingUses).toBe(3);
|
||||
const row = db.prepare("SELECT used FROM download_grants WHERE grant = ?").get(grant) as {
|
||||
used: number;
|
||||
};
|
||||
expect(row.used).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* 图案导出模块测试(T-076 用量统计 + T-077 PDF 生成)。
|
||||
*/
|
||||
import { describe, it, expect } from "vitest";
|
||||
import request from "supertest";
|
||||
import { inflateSync } from "node:zlib";
|
||||
import { computeUsageStats } from "../export/usage-stats.js";
|
||||
import { generatePatternPdf, type PatternPdfInput } from "../export/pdf.js";
|
||||
import { createApp } from "../server.js";
|
||||
|
||||
/** 构造一个 2×2 的简单测试图案 */
|
||||
function smallPattern(): PatternPdfInput {
|
||||
const stats = computeUsageStats(
|
||||
[
|
||||
{ code: "RED", hex: "#FF0000", count: 2 },
|
||||
{ code: "BLUE", hex: "#0000FF", count: 2 },
|
||||
],
|
||||
4,
|
||||
);
|
||||
return {
|
||||
title: "Test Pattern",
|
||||
gridSize: 2,
|
||||
grid: [
|
||||
{ color: "#FF0000" },
|
||||
{ color: "#FF0000" },
|
||||
{ color: "#0000FF" },
|
||||
{ color: "#0000FF" },
|
||||
],
|
||||
stats,
|
||||
};
|
||||
}
|
||||
|
||||
describe("图案导出模块", () => {
|
||||
describe("computeUsageStats", () => {
|
||||
it("计算每个颜色的用量与百分比,总和约等于 100", () => {
|
||||
const stats = computeUsageStats(
|
||||
[
|
||||
{ code: "A01", hex: "#FF0000", count: 10 },
|
||||
{ code: "B02", hex: "#00FF00", count: 20 },
|
||||
{ code: "C03", hex: "#0000FF", count: 30 },
|
||||
],
|
||||
60,
|
||||
);
|
||||
expect(stats.totalBeads).toBe(60);
|
||||
expect(stats.colorCount).toBe(3);
|
||||
expect(stats.perColor.map((c) => c.percent)).toEqual([16.7, 33.3, 50]);
|
||||
const sum = stats.perColor.reduce((acc, c) => acc + c.percent, 0);
|
||||
expect(Math.abs(sum - 100)).toBeLessThan(0.5);
|
||||
expect(stats.extra10Percent).toBe(66); // 60 × 1.1 = 66
|
||||
});
|
||||
|
||||
it("10% 额外用量向上取整", () => {
|
||||
expect(computeUsageStats([], 0).extra10Percent).toBe(0);
|
||||
expect(computeUsageStats([], 1).extra10Percent).toBe(2); // 1.1 → 2
|
||||
expect(computeUsageStats([], 9).extra10Percent).toBe(10); // 9.9 → 10
|
||||
expect(computeUsageStats([], 10).extra10Percent).toBe(11);
|
||||
});
|
||||
|
||||
it("过滤掉数量为 0 的颜色", () => {
|
||||
const stats = computeUsageStats(
|
||||
[
|
||||
{ code: "X", hex: "#111111", count: 0 },
|
||||
{ code: "Y", hex: "#222222", count: 5 },
|
||||
],
|
||||
5,
|
||||
);
|
||||
expect(stats.colorCount).toBe(1);
|
||||
expect(stats.perColor.map((c) => c.code)).toEqual(["Y"]);
|
||||
expect(stats.perColor[0]!.percent).toBe(100);
|
||||
});
|
||||
|
||||
it("总珠数为 0 时百分比为 0 而不是 NaN", () => {
|
||||
const stats = computeUsageStats([{ code: "A", hex: "#FF0000", count: 3 }], 0);
|
||||
expect(stats.perColor[0]!.percent).toBe(0);
|
||||
expect(stats.extra10Percent).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generatePatternPdf", () => {
|
||||
it("返回以 %PDF- 开头的 Buffer", () => {
|
||||
const buf = generatePatternPdf(smallPattern());
|
||||
expect(Buffer.isBuffer(buf)).toBe(true);
|
||||
expect(buf.toString("latin1", 0, 5)).toBe("%PDF-");
|
||||
});
|
||||
|
||||
it("包含页面对象,startxref 指向有效的 xref 表,文件以 %%EOF 结束", () => {
|
||||
const buf = generatePatternPdf(smallPattern());
|
||||
const text = buf.toString("latin1");
|
||||
expect(text).toContain("/Type /Page");
|
||||
expect(text).toContain("/MediaBox");
|
||||
expect(text).toContain("Helvetica");
|
||||
expect(text).toContain("%%EOF");
|
||||
// 解析 startxref 偏移量并验证指向 "xref"
|
||||
const sx = text.lastIndexOf("startxref");
|
||||
expect(sx).toBeGreaterThan(-1);
|
||||
const eol = text.indexOf("\n", sx);
|
||||
const offsetEnd = text.indexOf("\n", eol + 1);
|
||||
const offset = Number.parseInt(text.slice(eol + 1, offsetEnd).trim(), 10);
|
||||
expect(Number.isInteger(offset)).toBe(true);
|
||||
expect(buf.toString("latin1", offset, offset + 4)).toBe("xref");
|
||||
});
|
||||
|
||||
it("内容流经 FlateDecode 压缩且可解压出网格绘制指令与标题", () => {
|
||||
const buf = generatePatternPdf(smallPattern());
|
||||
const text = buf.toString("latin1");
|
||||
const streamStart = text.indexOf("stream\n") + "stream\n".length;
|
||||
const streamEnd = text.indexOf("\nendstream", streamStart);
|
||||
expect(streamEnd).toBeGreaterThan(streamStart);
|
||||
const raw = buf.subarray(streamStart, streamEnd);
|
||||
const decoded = inflateSync(raw).toString("utf8");
|
||||
expect(decoded).toContain("re f"); // 网格填充矩形指令
|
||||
expect(decoded).toContain("Tj"); // 文本指令
|
||||
expect(decoded).toContain("Test Pattern");
|
||||
expect(decoded).toContain("+10% extra recommended: 5");
|
||||
});
|
||||
|
||||
it("单元格支持色板编码而非十六进制,空色单元格跳过", () => {
|
||||
const input = smallPattern();
|
||||
const grid = [1, 0, 1, 0].map((i) => ({ color: i === 1 ? "RED" : "" })); // 编码填色 + 空格子
|
||||
const buf = generatePatternPdf({ ...input, grid, stats: computeUsageStats([{ code: "RED", hex: "#FF0000", count: 2 }], 2) });
|
||||
const text = buf.toString("latin1");
|
||||
const streamStart = text.indexOf("stream\n") + "stream\n".length;
|
||||
const streamEnd = text.indexOf("\nendstream", streamStart);
|
||||
const decoded = inflateSync(buf.subarray(streamStart, streamEnd)).toString("utf8");
|
||||
expect(decoded).toContain("re f");
|
||||
expect(decoded).toContain("1 0 0 rg"); // #FF0000 填充
|
||||
});
|
||||
|
||||
it("中文标题做 Latin-1 兜底:生成不报错且输出合法 PDF", () => {
|
||||
const input = smallPattern();
|
||||
const buf = generatePatternPdf({ ...input, title: "拼豆图案 🎨" });
|
||||
expect(buf.toString("latin1", 0, 5)).toBe("%PDF-");
|
||||
expect(buf.toString("latin1")).toContain("%%EOF");
|
||||
});
|
||||
});
|
||||
|
||||
describe("路由 /api/export", () => {
|
||||
it("POST /api/export/stats 返回正确的用量统计 JSON", async () => {
|
||||
const res = await request(createApp())
|
||||
.post("/api/export/stats")
|
||||
.send({
|
||||
palette: [
|
||||
{ code: "A", hex: "#FF0000", count: 3 },
|
||||
{ code: "B", hex: "#00FF00", count: 7 },
|
||||
],
|
||||
totalBeads: 10,
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.stats.totalBeads).toBe(10);
|
||||
expect(res.body.stats.colorCount).toBe(2);
|
||||
expect(res.body.stats.perColor[0].percent).toBe(30);
|
||||
expect(res.body.stats.perColor[1].percent).toBe(70);
|
||||
expect(res.body.stats.extra10Percent).toBe(11);
|
||||
});
|
||||
|
||||
it("POST /api/export/pdf 返回 application/pdf 与 %PDF- 魔数", async () => {
|
||||
const res = await request(createApp())
|
||||
.post("/api/export/pdf")
|
||||
.buffer(true)
|
||||
.send({
|
||||
title: "Test Pattern",
|
||||
gridSize: 2,
|
||||
grid: [
|
||||
{ color: "#FF0000" },
|
||||
{ color: "#FF0000" },
|
||||
{ color: "#0000FF" },
|
||||
{ color: "#0000FF" },
|
||||
],
|
||||
palette: [
|
||||
{ code: "RED", hex: "#FF0000", count: 2 },
|
||||
{ code: "BLUE", hex: "#0000FF", count: 2 },
|
||||
],
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(String(res.headers["content-type"] ?? "")).toContain("application/pdf");
|
||||
expect(String(res.headers["content-disposition"] ?? "")).toContain("attachment");
|
||||
const bytes = Buffer.isBuffer(res.body) ? res.body : Buffer.from(res.text ?? "", "latin1");
|
||||
expect(bytes.toString("latin1", 0, 5)).toBe("%PDF-");
|
||||
});
|
||||
|
||||
it("参数校验失败返回 400 中文提示", async () => {
|
||||
// 网格尺寸无效
|
||||
const badSize = await request(createApp())
|
||||
.post("/api/export/pdf")
|
||||
.send({ gridSize: 999, grid: [], palette: [] });
|
||||
expect(badSize.status).toBe(400);
|
||||
expect(badSize.body.error).toBe("网格尺寸无效");
|
||||
// 网格长度与尺寸不匹配
|
||||
const badGrid = await request(createApp())
|
||||
.post("/api/export/pdf")
|
||||
.send({ gridSize: 2, grid: [{ color: "#FF0000" }], palette: [] });
|
||||
expect(badGrid.status).toBe(400);
|
||||
expect(badGrid.body.error).toBe("网格数据与尺寸不匹配");
|
||||
// 色板非法
|
||||
const badPalette = await request(createApp())
|
||||
.post("/api/export/stats")
|
||||
.send({ palette: "nope", totalBeads: 10 });
|
||||
expect(badPalette.status).toBe(400);
|
||||
expect(badPalette.body.error).toBe("色板数据无效");
|
||||
// 珠子总数非法
|
||||
const badTotal = await request(createApp())
|
||||
.post("/api/export/stats")
|
||||
.send({ palette: [], totalBeads: -5 });
|
||||
expect(badTotal.status).toBe(400);
|
||||
expect(badTotal.body.error).toBe("珠子总数无效");
|
||||
});
|
||||
|
||||
it("支持大网格导出(64×64)", async () => {
|
||||
const n = 64;
|
||||
const grid = new Array<{ color: string }>(n * n).fill({ color: "#FF0000" });
|
||||
const res = await request(createApp())
|
||||
.post("/api/export/pdf")
|
||||
.buffer(true)
|
||||
.send({
|
||||
title: "Large",
|
||||
gridSize: n,
|
||||
grid,
|
||||
palette: [{ code: "RED", hex: "#FF0000", count: n * n }],
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
const bytes = Buffer.isBuffer(res.body) ? res.body : Buffer.from(res.text ?? "", "latin1");
|
||||
expect(bytes.toString("latin1", 0, 5)).toBe("%PDF-");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import request from "supertest";
|
||||
import { createApp } from "../server.js";
|
||||
import { createTestDatabase } from "../db/index.js";
|
||||
import { BRANDS } from "../palettes/routes.js";
|
||||
import { formatExportFileName } from "../export/brand-adapter.js";
|
||||
|
||||
/** 期望的品牌注册表(任务要求:MARD 291 / COCO 291 / 漫漫 290 / 盼盼 291 / 咪小窝 291)。 */
|
||||
const EXPECTED_COUNTS: ReadonlyMap<string, number> = new Map([
|
||||
["MARD", 291],
|
||||
["COCO", 291],
|
||||
["漫漫", 290],
|
||||
["盼盼", 291],
|
||||
["咪小窝", 291],
|
||||
]);
|
||||
|
||||
describe("palette API(品牌色板元数据)", () => {
|
||||
const app = createApp(createTestDatabase());
|
||||
|
||||
it("GET /api/palettes 返回 5 个品牌及预期色号数量", async () => {
|
||||
const res = await request(app).get("/api/palettes");
|
||||
expect(res.status).toBe(200);
|
||||
const list = res.body as { id: string; name: string; colorCount: number }[];
|
||||
expect(list).toHaveLength(5);
|
||||
expect(list.map((brand) => brand.id)).toEqual([
|
||||
"MARD",
|
||||
"COCO",
|
||||
"漫漫",
|
||||
"盼盼",
|
||||
"咪小窝",
|
||||
]);
|
||||
for (const brand of list) {
|
||||
expect(brand.colorCount).toBe(EXPECTED_COUNTS.get(brand.id));
|
||||
expect(typeof brand.name).toBe("string");
|
||||
expect(brand.name.length).toBeGreaterThan(0);
|
||||
}
|
||||
});
|
||||
|
||||
it("品牌注册表 colorCount 与预期一致(BRANDS 常量)", () => {
|
||||
expect(BRANDS).toHaveLength(5);
|
||||
for (const brand of BRANDS) {
|
||||
expect(brand.colorCount).toBe(EXPECTED_COUNTS.get(brand.id));
|
||||
}
|
||||
});
|
||||
|
||||
it("GET /api/palettes/COCO/codes 返回非空字符串数组", async () => {
|
||||
const res = await request(app).get("/api/palettes/COCO/codes");
|
||||
expect(res.status).toBe(200);
|
||||
expect(Array.isArray(res.body)).toBe(true);
|
||||
const codes = res.body as unknown[];
|
||||
expect(codes.length).toBeGreaterThan(0);
|
||||
expect(codes.every((code) => typeof code === "string" && code.length > 0)).toBe(true);
|
||||
});
|
||||
|
||||
it("GET /api/palettes/MARD/codes 返回 291 个不重复色号", async () => {
|
||||
const res = await request(app).get("/api/palettes/MARD/codes");
|
||||
expect(res.status).toBe(200);
|
||||
const codes = res.body as string[];
|
||||
expect(codes).toHaveLength(291);
|
||||
expect(new Set(codes).size).toBe(291);
|
||||
});
|
||||
|
||||
it("GET /api/palettes/漫漫/codes 去重后为 289 条(映射含 S4 重复与 '-' 行)", async () => {
|
||||
const res = await request(app).get("/api/palettes/漫漫/codes");
|
||||
expect(res.status).toBe(200);
|
||||
const codes = res.body as string[];
|
||||
expect(codes).toHaveLength(289);
|
||||
expect(new Set(codes).size).toBe(289);
|
||||
expect(codes).not.toContain("-");
|
||||
});
|
||||
|
||||
it("GET /api/palettes/UNKNOWN/codes 返回 404 中文错误", async () => {
|
||||
const res = await request(app).get("/api/palettes/UNKNOWN/codes");
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: "品牌不存在" });
|
||||
});
|
||||
|
||||
it("GET /api/palettes/不存在的品牌/codes 返回 404 中文错误", async () => {
|
||||
const res = await request(app).get(`/api/palettes/${encodeURIComponent("不存在的品牌")}/codes`);
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body.error).toBe("品牌不存在");
|
||||
});
|
||||
});
|
||||
|
||||
describe("brand-adapter(品牌化导出文件名)", () => {
|
||||
it("MARD:宠物-MARD-64x64-MARD拼豆图纸.png", () => {
|
||||
expect(
|
||||
formatExportFileName({ baseName: "宠物", brand: { id: "MARD" }, gridSize: 64 }),
|
||||
).toBe("宠物-MARD-64x64-MARD拼豆图纸.png");
|
||||
});
|
||||
|
||||
it("COCO:品牌标签随 id 变化(brand-aware)", () => {
|
||||
expect(
|
||||
formatExportFileName({ baseName: "宠物", brand: { id: "COCO" }, gridSize: 64 }),
|
||||
).toBe("宠物-COCO-64x64-COCO拼豆图纸.png");
|
||||
});
|
||||
|
||||
it("自定义品牌标签(如 漫漫)", () => {
|
||||
expect(
|
||||
formatExportFileName({ baseName: "宠物", brand: { id: "漫漫" }, gridSize: 48 }),
|
||||
).toBe("宠物-漫漫-48x48-漫漫拼豆图纸.png");
|
||||
});
|
||||
|
||||
it("空 baseName 回退为「拼豆图纸」", () => {
|
||||
expect(
|
||||
formatExportFileName({ baseName: " ", brand: { id: "MARD" }, gridSize: 48 }),
|
||||
).toBe("拼豆图纸-MARD-48x48-MARD拼豆图纸.png");
|
||||
});
|
||||
|
||||
it("非法网格尺寸抛出中文错误", () => {
|
||||
expect(() =>
|
||||
formatExportFileName({ baseName: "宠物", brand: { id: "MARD" }, gridSize: 0 }),
|
||||
).toThrowError(/网格尺寸不合法/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import { describe, it, expect, afterEach, vi } from "vitest";
|
||||
import crypto from "node:crypto";
|
||||
import { MockPaymentProvider } from "../payment/mock.js";
|
||||
import { WeChatPayProvider, decryptAes256Gcm, verifyWechatSignature } from "../payment/wechat.js";
|
||||
import { getPaymentProvider } from "../payment/index.js";
|
||||
import { PaymentProviderError } from "../payment/types.js";
|
||||
|
||||
/** 32 字节 APIv3 测试密钥 */
|
||||
const API_V3_KEY = "0123456789abcdef0123456789abcdef";
|
||||
const AAD = "transaction";
|
||||
|
||||
/** 测试用 RSA 密钥对(2048 位,模拟商户私钥 / 微信平台公钥) */
|
||||
const keyPair = crypto.generateKeyPairSync("rsa", { modulusLength: 2048 });
|
||||
const PRIVATE_KEY_PEM = keyPair.privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
||||
|
||||
/** 微信支付回调密文构造:nonce(12) || 密文 || 认证标签(16),AAD 参与认证 */
|
||||
function encryptAes256Gcm(plain: string, key: string, aad: string): { ciphertext: string; nonce: string } {
|
||||
const nonce = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv("aes-256-gcm", Buffer.from(key, "utf8"), nonce);
|
||||
cipher.setAAD(Buffer.from(aad, "utf8"));
|
||||
const ct = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
return {
|
||||
ciphertext: Buffer.concat([nonce, ct, tag]).toString("base64"),
|
||||
nonce: nonce.toString("base64"),
|
||||
};
|
||||
}
|
||||
|
||||
/** 构造一份签名合法、资源已加密的微信支付回调报文 */
|
||||
function buildSignedCallback(overrides?: {
|
||||
tradeState?: string;
|
||||
resourcePayload?: Record<string, unknown>;
|
||||
timestamp?: string;
|
||||
bodySuffix?: string;
|
||||
}): { body: string; signature: string; timestamp: string; nonce: string } {
|
||||
const resource = {
|
||||
out_trade_no: "PL20240801000001",
|
||||
transaction_id: "4200001234202408010000000001",
|
||||
trade_state: overrides?.tradeState ?? "SUCCESS",
|
||||
amount: { total: 490, currency: "CNY" },
|
||||
...overrides?.resourcePayload,
|
||||
};
|
||||
const { ciphertext } = encryptAes256Gcm(JSON.stringify(resource), API_V3_KEY, AAD);
|
||||
const body = JSON.stringify({
|
||||
id: "evt-0001",
|
||||
create_time: "2024-08-01T10:00:00+08:00",
|
||||
resource_type: "encrypt-resource",
|
||||
event_type: "TRANSACTION.SUCCESS",
|
||||
summary: "支付成功",
|
||||
resource: {
|
||||
original_type: "transaction",
|
||||
algorithm: "AEAD_AES_256_GCM",
|
||||
ciphertext,
|
||||
associated_data: AAD,
|
||||
nonce: "mock-nonce",
|
||||
},
|
||||
}) + (overrides?.bodySuffix ?? "");
|
||||
const timestamp = overrides?.timestamp ?? String(Math.floor(Date.now() / 1000));
|
||||
const nonce = "callback-random-nonce";
|
||||
const signature = crypto
|
||||
.sign("RSA-SHA256", Buffer.from(`${timestamp}\n${nonce}\n${body}\n`, "utf8"), keyPair.privateKey)
|
||||
.toString("base64");
|
||||
return { body, signature, timestamp, nonce };
|
||||
}
|
||||
|
||||
/** 配置完整微信支付环境变量(供工厂测试 / 构造真实 Provider 使用) */
|
||||
function stubFullWechatEnv(): void {
|
||||
vi.stubEnv("WECHAT_PAY_ENABLED", "true");
|
||||
vi.stubEnv("NODE_ENV", "production");
|
||||
vi.stubEnv("WECHAT_MCH_ID", "1900000001");
|
||||
vi.stubEnv("WECHAT_APP_ID", "wx-test-appid");
|
||||
vi.stubEnv("WECHAT_API_KEY", API_V3_KEY);
|
||||
vi.stubEnv("WECHAT_SERIAL_NO", "1234567890ABCDEF");
|
||||
vi.stubEnv("WECHAT_PRIVATE_KEY", PRIVATE_KEY_PEM);
|
||||
vi.stubEnv("WECHAT_PLATFORM_CERT", keyPair.publicKey.export({ type: "spki", format: "pem" }).toString());
|
||||
vi.stubEnv("WECHAT_NOTIFY_URL", "https://example.com/api/orders/notify");
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
describe("MockPaymentProvider", () => {
|
||||
it("createPayment 返回 mock 支付链接与微信二维码", async () => {
|
||||
const result = await new MockPaymentProvider().createPayment({
|
||||
orderNo: "PL20240801000001",
|
||||
amountCents: 490,
|
||||
description: "体验包",
|
||||
method: "wechat",
|
||||
});
|
||||
expect(result.url).toContain("PL20240801000001");
|
||||
expect(result.url).toContain("490");
|
||||
expect(result.qrCode).toContain("PL20240801000001");
|
||||
});
|
||||
|
||||
it("verifyCallback 校验 orderNo 并返回 MOCK 事务号", async () => {
|
||||
const result = await new MockPaymentProvider().verifyCallback({ orderNo: "PL1" });
|
||||
expect(result?.orderNo).toBe("PL1");
|
||||
expect(result?.transactionId).toMatch(/^MOCK/);
|
||||
});
|
||||
|
||||
it("verifyCallback 缺少 orderNo 返回 null", async () => {
|
||||
expect(await new MockPaymentProvider().verifyCallback({})).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("getPaymentProvider 工厂", () => {
|
||||
it("默认(未开启 WECHAT_PAY_ENABLED)返回 mock", () => {
|
||||
expect(getPaymentProvider("wechat")).toBeInstanceOf(MockPaymentProvider);
|
||||
});
|
||||
|
||||
it("开关开启但 NODE_ENV 非 production 时返回 mock", () => {
|
||||
vi.stubEnv("WECHAT_PAY_ENABLED", "true");
|
||||
vi.stubEnv("NODE_ENV", "development");
|
||||
stubFullWechatEnv();
|
||||
vi.stubEnv("NODE_ENV", "development");
|
||||
expect(getPaymentProvider("wechat")).toBeInstanceOf(MockPaymentProvider);
|
||||
});
|
||||
|
||||
it("production + 开启但缺少任一 WECHAT_* 环境变量时返回 mock", () => {
|
||||
stubFullWechatEnv();
|
||||
vi.stubEnv("WECHAT_SERIAL_NO", "");
|
||||
expect(getPaymentProvider("wechat")).toBeInstanceOf(MockPaymentProvider);
|
||||
});
|
||||
|
||||
it("production + 开启 + 配置齐全时返回真实 WeChatPayProvider", () => {
|
||||
stubFullWechatEnv();
|
||||
expect(getPaymentProvider("wechat")).toBeInstanceOf(WeChatPayProvider);
|
||||
});
|
||||
|
||||
it("alipay 始终返回 mock", () => {
|
||||
stubFullWechatEnv();
|
||||
expect(getPaymentProvider("alipay")).toBeInstanceOf(MockPaymentProvider);
|
||||
});
|
||||
});
|
||||
|
||||
describe("WeChatPayProvider 构造校验", () => {
|
||||
it("环境变量缺失时抛出 PAYMENT_NOT_CONFIGURED", () => {
|
||||
expect(() => new WeChatPayProvider()).toThrowError(PaymentProviderError);
|
||||
expect(() => new WeChatPayProvider()).toThrowError(/PAYMENT_NOT_CONFIGURED|未配置/);
|
||||
});
|
||||
|
||||
it("APIv3 密钥长度不是 32 字节时抛错", () => {
|
||||
stubFullWechatEnv();
|
||||
vi.stubEnv("WECHAT_API_KEY", "too-short");
|
||||
expect(() => new WeChatPayProvider()).toThrowError(/32 字节/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("decryptAes256Gcm(AES-256-GCM 解密)", () => {
|
||||
it("能解密合法的 AEAD_AES_256_GCM 报文", () => {
|
||||
const plain = '{"out_trade_no":"PL20240801000001"}';
|
||||
const { ciphertext } = encryptAes256Gcm(plain, API_V3_KEY, AAD);
|
||||
expect(decryptAes256Gcm(ciphertext, AAD, API_V3_KEY)).toBe(plain);
|
||||
});
|
||||
|
||||
it("AAD 不匹配时解密失败(认证不通过)", () => {
|
||||
const { ciphertext } = encryptAes256Gcm("hello", API_V3_KEY, AAD);
|
||||
expect(() => decryptAes256Gcm(ciphertext, "wrong-aad", API_V3_KEY)).toThrow();
|
||||
});
|
||||
|
||||
it("密钥错误时解密失败", () => {
|
||||
const { ciphertext } = encryptAes256Gcm("hello", API_V3_KEY, AAD);
|
||||
expect(() => decryptAes256Gcm(ciphertext, AAD, "fedcba9876543210fedcba9876543210")).toThrow();
|
||||
});
|
||||
|
||||
it("密文过短(非法)时抛错", () => {
|
||||
expect(() => decryptAes256Gcm("YWJjZA==", AAD, API_V3_KEY)).toThrow(/长度非法/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyWechatSignature(RSA-SHA256 验签)", () => {
|
||||
it("合法签名校验通过", () => {
|
||||
const message = "1722500000\nnonce\n{\"body\":true}\n";
|
||||
const signature = crypto
|
||||
.sign("RSA-SHA256", Buffer.from(message, "utf8"), keyPair.privateKey)
|
||||
.toString("base64");
|
||||
expect(verifyWechatSignature(message, signature, keyPair.publicKey)).toBe(true);
|
||||
});
|
||||
|
||||
it("篡改签名后校验失败", () => {
|
||||
const message = "1722500000\nnonce\n{\"body\":true}\n";
|
||||
const signature = crypto
|
||||
.sign("RSA-SHA256", Buffer.from(message, "utf8"), keyPair.privateKey)
|
||||
.toString("base64");
|
||||
// 篡改签名中间字符(尾部追加会被 base64 宽松解码当作 padding 忽略)
|
||||
const tampered = (signature[0] === "A" ? "B" : "A") + signature.slice(1);
|
||||
expect(tampered).not.toBe(signature);
|
||||
expect(verifyWechatSignature(message, tampered, keyPair.publicKey)).toBe(false);
|
||||
});
|
||||
|
||||
it("篡改报文内容后校验失败", () => {
|
||||
const message = "1722500000\nnonce\n{\"body\":true}\n";
|
||||
const signature = crypto
|
||||
.sign("RSA-SHA256", Buffer.from(message, "utf8"), keyPair.privateKey)
|
||||
.toString("base64");
|
||||
expect(verifyWechatSignature("1722500000\nnonce\n{\"body\":false}\n", signature, keyPair.publicKey)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("WeChatPayProvider.verifyCallback(完整验签 + 解密流程)", () => {
|
||||
it("合法回调返回订单号与微信事务号", async () => {
|
||||
stubFullWechatEnv();
|
||||
const provider = new WeChatPayProvider();
|
||||
const callback = buildSignedCallback();
|
||||
const result = await provider.verifyCallback({
|
||||
body: callback.body,
|
||||
"Wechatpay-Signature": callback.signature,
|
||||
"Wechatpay-Timestamp": callback.timestamp,
|
||||
"Wechatpay-Nonce": callback.nonce,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
orderNo: "PL20240801000001",
|
||||
transactionId: "4200001234202408010000000001",
|
||||
});
|
||||
});
|
||||
|
||||
it("签名被篡改时返回 null", async () => {
|
||||
stubFullWechatEnv();
|
||||
const provider = new WeChatPayProvider();
|
||||
const callback = buildSignedCallback();
|
||||
const result = await provider.verifyCallback({
|
||||
body: callback.body + " ",
|
||||
"Wechatpay-Signature": callback.signature,
|
||||
"Wechatpay-Timestamp": callback.timestamp,
|
||||
"Wechatpay-Nonce": callback.nonce,
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("缺少回调头时返回 null", async () => {
|
||||
stubFullWechatEnv();
|
||||
const provider = new WeChatPayProvider();
|
||||
const callback = buildSignedCallback();
|
||||
expect(
|
||||
await provider.verifyCallback({ body: callback.body, "Wechatpay-Signature": callback.signature }),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("回调时间戳过期(超 5 分钟)时返回 null", async () => {
|
||||
stubFullWechatEnv();
|
||||
const provider = new WeChatPayProvider();
|
||||
const callback = buildSignedCallback({ timestamp: String(Math.floor(Date.now() / 1000) - 600) });
|
||||
const result = await provider.verifyCallback({
|
||||
body: callback.body,
|
||||
"Wechatpay-Signature": callback.signature,
|
||||
"Wechatpay-Timestamp": callback.timestamp,
|
||||
"Wechatpay-Nonce": callback.nonce,
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("trade_state 非 SUCCESS 时返回 null", async () => {
|
||||
stubFullWechatEnv();
|
||||
const provider = new WeChatPayProvider();
|
||||
const callback = buildSignedCallback({ tradeState: "CLOSED" });
|
||||
const result = await provider.verifyCallback({
|
||||
body: callback.body,
|
||||
"Wechatpay-Signature": callback.signature,
|
||||
"Wechatpay-Timestamp": callback.timestamp,
|
||||
"Wechatpay-Nonce": callback.nonce,
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
it("resource.ciphertext 无法解密时返回 null", async () => {
|
||||
stubFullWechatEnv();
|
||||
const provider = new WeChatPayProvider();
|
||||
const callback = buildSignedCallback({
|
||||
resourcePayload: { tampered: true },
|
||||
});
|
||||
const broken = callback.body.replace(/"[A-Za-z0-9+/=]{20,}"/, '"not-a-valid-ciphertext"');
|
||||
const result = await provider.verifyCallback({
|
||||
body: broken,
|
||||
"Wechatpay-Signature": callback.signature,
|
||||
"Wechatpay-Timestamp": callback.timestamp,
|
||||
"Wechatpay-Nonce": callback.nonce,
|
||||
});
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,309 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import request from "supertest";
|
||||
import type Database from "better-sqlite3";
|
||||
import type { NextFunction, Request, RequestHandler, Response } from "express";
|
||||
import { createTestDatabase } from "../db/index.js";
|
||||
import { createApp } from "../server.js";
|
||||
import { generateCode, generateCodes, insertCodes } from "../codes/service.js";
|
||||
import { createRateLimiter, RATE_LIMIT_MESSAGE, RATE_LIMITS } from "../security/rate-limit.js";
|
||||
import {
|
||||
ABUSE_MESSAGE,
|
||||
detectAbuse,
|
||||
logSecurityEvent,
|
||||
markSuspicious,
|
||||
} from "../security/abuse.js";
|
||||
|
||||
/** 构造最小化的 req/res/next 用于直接调用中间件。 */
|
||||
function makeHarness(ip = "127.0.0.1"): {
|
||||
req: Request;
|
||||
res: Response;
|
||||
next: () => void;
|
||||
calls: string[];
|
||||
} {
|
||||
const calls: string[] = [];
|
||||
const req = { ip } as unknown as Request;
|
||||
const res = {
|
||||
status(code: number) {
|
||||
calls.push(`status:${code}`);
|
||||
return this;
|
||||
},
|
||||
json(body: Record<string, unknown>) {
|
||||
calls.push(`json:${JSON.stringify(body)}`);
|
||||
return this;
|
||||
},
|
||||
} as unknown as Response;
|
||||
const next = (): void => {
|
||||
calls.push("next");
|
||||
};
|
||||
return { req, res, next, calls };
|
||||
}
|
||||
|
||||
function runMiddleware(mw: RequestHandler, h: ReturnType<typeof makeHarness>): void {
|
||||
(mw as (req: Request, res: Response, next: NextFunction) => void)(h.req, h.res, h.next);
|
||||
}
|
||||
|
||||
describe("限流配置常量", () => {
|
||||
it("导出各动作限流阈值(次/小时/IP)", () => {
|
||||
expect(RATE_LIMITS.redeem).toEqual({ windowMs: 60 * 60 * 1000, max: 10 });
|
||||
expect(RATE_LIMITS.consume).toEqual({ windowMs: 60 * 60 * 1000, max: 30 });
|
||||
expect(RATE_LIMITS.orders).toEqual({ windowMs: 60 * 60 * 1000, max: 5 });
|
||||
expect(RATE_LIMITS.chibiGenerate).toEqual({ windowMs: 60 * 60 * 1000, max: 10 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("rate-limit 滑动窗口限流器", () => {
|
||||
it("达到上限后第 max+1 次请求返回 429(中文提示)", () => {
|
||||
const mw = createRateLimiter({ windowMs: 60_000, max: 3 })("redeem");
|
||||
const h = makeHarness();
|
||||
for (let i = 0; i < 3; i++) {
|
||||
runMiddleware(mw, h);
|
||||
}
|
||||
expect(h.calls.filter((c) => c === "next")).toHaveLength(3);
|
||||
|
||||
runMiddleware(mw, h);
|
||||
expect(h.calls.filter((c) => c.startsWith("status:429"))).toHaveLength(1);
|
||||
expect(h.calls.at(-1)).toContain(RATE_LIMIT_MESSAGE);
|
||||
expect(h.calls.filter((c) => c === "next")).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("不同 IP 独立计数", () => {
|
||||
const mw = createRateLimiter({ windowMs: 60_000, max: 2 })("redeem");
|
||||
const h1 = makeHarness("1.1.1.1");
|
||||
const h2 = makeHarness("2.2.2.2");
|
||||
runMiddleware(mw, h1);
|
||||
runMiddleware(mw, h1);
|
||||
runMiddleware(mw, h2);
|
||||
expect(h1.calls.filter((c) => c === "next")).toHaveLength(2);
|
||||
expect(h2.calls.filter((c) => c === "next")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("窗口滑出后自动恢复放行(滑动窗口)", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
|
||||
try {
|
||||
const mw = createRateLimiter({ windowMs: 1000, max: 2 })("redeem");
|
||||
const h = makeHarness();
|
||||
runMiddleware(mw, h);
|
||||
runMiddleware(mw, h);
|
||||
runMiddleware(mw, h); // 第 3 次被拦截
|
||||
expect(h.calls.filter((c) => c === "next")).toHaveLength(2);
|
||||
|
||||
vi.advanceTimersByTime(1001);
|
||||
runMiddleware(mw, h);
|
||||
expect(h.calls.filter((c) => c === "next")).toHaveLength(3);
|
||||
expect(h.calls.filter((c) => c.startsWith("status:429"))).toHaveLength(1);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it("不同动作名互不干扰", () => {
|
||||
const limiter = createRateLimiter({ windowMs: 60_000, max: 1 });
|
||||
const redeemMw = limiter("redeem");
|
||||
const consumeMw = limiter("consume");
|
||||
const hRedeem = makeHarness();
|
||||
const hConsume = makeHarness();
|
||||
runMiddleware(redeemMw, hRedeem); // redeem 已满
|
||||
runMiddleware(consumeMw, hConsume); // consume 应放行
|
||||
expect(hRedeem.calls.filter((c) => c === "next")).toHaveLength(1);
|
||||
expect(hConsume.calls.filter((c) => c === "next")).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("abuse 防刷检测", () => {
|
||||
let db: Database.Database;
|
||||
|
||||
beforeEach(() => {
|
||||
db = createTestDatabase();
|
||||
});
|
||||
|
||||
it("security_events 表已创建并可写入/读取", () => {
|
||||
const table = db
|
||||
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'security_events'")
|
||||
.get();
|
||||
expect(table).toBeDefined();
|
||||
|
||||
logSecurityEvent(db, "1.2.3.4", "TESTCODE", "redeem", "redeem_ok");
|
||||
const evt = db
|
||||
.prepare("SELECT ip, code, action, event_type FROM security_events")
|
||||
.get() as { ip: string | null; code: string; action: string; event_type: string };
|
||||
expect(evt).toEqual({ ip: "1.2.3.4", code: "TESTCODE", action: "redeem", event_type: "redeem_ok" });
|
||||
});
|
||||
|
||||
it("同一兑换码 24h 内被超过 5 个不同 IP 兑换 → 判定滥用", () => {
|
||||
const code = generateCode();
|
||||
for (let i = 0; i < 6; i++) {
|
||||
logSecurityEvent(db, `10.0.0.${i}`, code, "redeem", "redeem_ok");
|
||||
}
|
||||
expect(detectAbuse(db, code)).toBe(true);
|
||||
});
|
||||
|
||||
it("同一 IP 10min 内无效尝试超过 50 次 → 判定滥用", () => {
|
||||
const code = generateCode();
|
||||
for (let i = 0; i < 51; i++) {
|
||||
logSecurityEvent(db, "9.9.9.9", code, "redeem", "redeem_fail");
|
||||
}
|
||||
expect(detectAbuse(db, code, "9.9.9.9")).toBe(true);
|
||||
// 未提供 IP 时按兑换码分组同样能识别
|
||||
expect(detectAbuse(db, code)).toBe(true);
|
||||
});
|
||||
|
||||
it("未达阈值不判定滥用(5 个 IP / 50 次尝试)", () => {
|
||||
const code = generateCode();
|
||||
for (let i = 0; i < 5; i++) {
|
||||
logSecurityEvent(db, `10.0.0.${i}`, code, "redeem", "redeem_ok");
|
||||
}
|
||||
for (let i = 0; i < 50; i++) {
|
||||
logSecurityEvent(db, "9.9.9.9", code, "redeem", "redeem_fail");
|
||||
}
|
||||
expect(detectAbuse(db, code)).toBe(false);
|
||||
expect(detectAbuse(db, code, "9.9.9.9")).toBe(false);
|
||||
});
|
||||
|
||||
it("markSuspicious 禁用兑换码并记录安全事件", () => {
|
||||
const code = generateCode();
|
||||
insertCodes(db, [code], "体验包", 3);
|
||||
|
||||
const changed = markSuspicious(db, code);
|
||||
expect(changed).toBe(true);
|
||||
|
||||
const row = db.prepare("SELECT status FROM codes WHERE code = ?").get(code) as { status: string };
|
||||
expect(row.status).toBe("disabled");
|
||||
|
||||
const evt = db
|
||||
.prepare("SELECT action, event_type FROM security_events WHERE code = ?")
|
||||
.get(code) as { action: string; event_type: string };
|
||||
expect(evt).toEqual({ action: "disable", event_type: "code_disabled" });
|
||||
});
|
||||
|
||||
it("markSuspicious 对不存在的兑换码不抛错", () => {
|
||||
expect(() => markSuspicious(db, generateCode())).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("HTTP 路由防刷集成", () => {
|
||||
it("兑换接口超过 10 次/小时 → 429", async () => {
|
||||
const db = createTestDatabase();
|
||||
const codes = generateCodes(1);
|
||||
insertCodes(db, codes, "体验包", 3);
|
||||
const app = createApp(db);
|
||||
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const res = await request(app).post("/api/codes/redeem").send({ code: codes[0] });
|
||||
expect(res.status).toBe(200);
|
||||
}
|
||||
const blocked = await request(app).post("/api/codes/redeem").send({ code: codes[0] });
|
||||
expect(blocked.status).toBe(429);
|
||||
expect(blocked.body.error).toBe(RATE_LIMIT_MESSAGE);
|
||||
});
|
||||
|
||||
it("订单创建超过 5 次/小时 → 429", async () => {
|
||||
const db = createTestDatabase();
|
||||
const app = createApp(db);
|
||||
const body = { packageName: "体验包", paymentMethod: "wechat" };
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const res = await request(app).post("/api/orders").send(body);
|
||||
expect(res.status).toBe(200);
|
||||
}
|
||||
const blocked = await request(app).post("/api/orders").send(body);
|
||||
expect(blocked.status).toBe(429);
|
||||
expect(blocked.body.error).toBe(RATE_LIMIT_MESSAGE);
|
||||
});
|
||||
|
||||
it("chibi 生成超过 10 次/小时 → 429", async () => {
|
||||
const db = createTestDatabase();
|
||||
const codes = generateCodes(1);
|
||||
insertCodes(db, codes, "常用包", 30);
|
||||
const app = createApp(db);
|
||||
const body = {
|
||||
code: codes[0],
|
||||
image: "data:image/png;base64,iVBORw0KGgo=",
|
||||
category: "pet",
|
||||
subtype: "cat",
|
||||
gridSize: 48,
|
||||
colorCount: 16,
|
||||
composition: "主体特写",
|
||||
detailTags: [],
|
||||
};
|
||||
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const res = await request(app).post("/api/chibi/generate").send(body);
|
||||
expect(res.status).toBe(200);
|
||||
}
|
||||
const blocked = await request(app).post("/api/chibi/generate").send(body);
|
||||
expect(blocked.status).toBe(429);
|
||||
expect(blocked.body.error).toBe(RATE_LIMIT_MESSAGE);
|
||||
});
|
||||
|
||||
it("无效兑换码失败请求记录 redeem_fail 事件(含来源 IP)", async () => {
|
||||
const db = createTestDatabase();
|
||||
const fake = generateCode(); // 不存在的兑换码
|
||||
const app = createApp(db);
|
||||
|
||||
const res = await request(app).post("/api/codes/redeem").send({ code: fake });
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body.error).toBe("兑换码不存在,请检查后重试");
|
||||
|
||||
const evt = db
|
||||
.prepare("SELECT ip, code, action, event_type FROM security_events WHERE event_type = 'redeem_fail'")
|
||||
.get() as { ip: string | null; code: string; action: string; event_type: string };
|
||||
expect(evt.code).toBe(fake);
|
||||
expect(evt.action).toBe("redeem");
|
||||
expect(evt.event_type).toBe("redeem_fail");
|
||||
expect(evt.ip).not.toBeNull();
|
||||
});
|
||||
|
||||
it("同一 IP 无效尝试超限 → 检测到异常并返回 403", async () => {
|
||||
const db = createTestDatabase();
|
||||
const fake = generateCode(); // 不存在的兑换码
|
||||
const app = createApp(db);
|
||||
|
||||
// 第一次失败请求:确认安全事件里记录了实际来源 IP
|
||||
const first = await request(app).post("/api/codes/redeem").send({ code: fake });
|
||||
expect(first.status).toBe(404);
|
||||
const evt = db
|
||||
.prepare("SELECT ip FROM security_events WHERE code = ? AND event_type = 'redeem_fail'")
|
||||
.get(fake) as { ip: string | null };
|
||||
expect(evt.ip).not.toBeNull();
|
||||
|
||||
// 补齐 50 次失败 → 加上前面两次共 52 次(> 50 阈值)
|
||||
for (let i = 0; i < 50; i++) {
|
||||
logSecurityEvent(db, evt.ip!, fake, "redeem", "redeem_fail");
|
||||
}
|
||||
|
||||
const blocked = await request(app).post("/api/codes/redeem").send({ code: fake });
|
||||
expect(blocked.status).toBe(403);
|
||||
expect(blocked.body.error).toBe(ABUSE_MESSAGE);
|
||||
});
|
||||
|
||||
it("同一兑换码被超过 5 个不同 IP 兑换 → 禁用兑换码并返回 403", async () => {
|
||||
const db = createTestDatabase();
|
||||
const codes = generateCodes(1);
|
||||
insertCodes(db, codes, "体验包", 3);
|
||||
const code = codes[0]!;
|
||||
|
||||
// 预置 5 个不同 IP 的兑换成功事件
|
||||
for (let i = 0; i < 5; i++) {
|
||||
logSecurityEvent(db, `10.0.0.${i}`, code, "redeem", "redeem_ok");
|
||||
}
|
||||
|
||||
const app = createApp(db);
|
||||
const res = await request(app).post("/api/codes/redeem").send({ code });
|
||||
expect(res.status).toBe(403);
|
||||
expect(res.body.error).toBe(ABUSE_MESSAGE);
|
||||
|
||||
// 兑换码已被禁用(防刷兜底)
|
||||
const row = db.prepare("SELECT status FROM codes WHERE code = ?").get(code) as { status: string };
|
||||
expect(row.status).toBe("disabled");
|
||||
const evt = db
|
||||
.prepare("SELECT event_type FROM security_events WHERE code = ? AND event_type = 'code_disabled'")
|
||||
.get(code);
|
||||
expect(evt).toBeDefined();
|
||||
|
||||
// 已禁用后再兑换 → 400 兑换码已失效
|
||||
const again = await request(app).post("/api/codes/redeem").send({ code });
|
||||
expect(again.status).toBe(400);
|
||||
expect(again.body.error).toBe("兑换码已失效,请联系客服");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user