chore: 项目基线提交 - 拼豆图纸生成器 V1.0 核心代码
- 前端: React+Vite 首页/AI专区, 算法库(MARD色板/量化/背景去除), API对接 - 后端: Express+SQLite, 兑换码/订单/支付/chibi生成, 风控+云端同步 - CI/CD: GitHub Actions + Docker + nginx 配置 - 文档: PRD/DESIGN/LAUNCH/ROADMAP/E2E/竞品对照等 15 份 - 工程: 任务看板(taskboard) + 健康巡检(agent-health) + Git流程(gitflow)
This commit is contained in:
commit
02762400fb
174 files changed
+28059
No files matched your search
@@ -0,0 +1,190 @@
|
||||
import { Router } from "express";
|
||||
import type { Request, Response } from "express";
|
||||
import type Database from "better-sqlite3";
|
||||
import { getDb } from "../db/index.js";
|
||||
import { checkRedeemable, validateFormat, CodeError } from "../codes/service.js";
|
||||
import type { AccessInfo } from "../types/index.js";
|
||||
|
||||
/**
|
||||
* Device ID format: 8-64 chars, alphanumeric + dash.
|
||||
* (Matches how frontend crypto.randomUUID / custom device ids look.)
|
||||
*/
|
||||
export const DEVICE_ID_FORMAT = /^[A-Za-z0-9-]{8,64}$/;
|
||||
|
||||
/** A code bound to a device, plus its current access info. */
|
||||
export interface BoundCode {
|
||||
code: string;
|
||||
packageType: string;
|
||||
remainingUses: number;
|
||||
totalUses: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
interface BindingRow {
|
||||
code: string;
|
||||
package_type: string;
|
||||
total_uses: number;
|
||||
used_uses: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a CodeError into an Express response.
|
||||
*/
|
||||
function handleCodeError(res: Response, err: CodeError): void {
|
||||
res.status(err.status).json({ error: err.message });
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the database instance: use injected DB if provided, otherwise
|
||||
* fall back to the global singleton.
|
||||
*/
|
||||
function resolveDb(injected?: Database.Database): Database.Database {
|
||||
return injected ?? getDb();
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a device id: trim; reject anything not matching the format.
|
||||
* Throws a CodeError (400, "设备标识无效") on invalid input.
|
||||
*/
|
||||
function parseDeviceId(raw: string): string {
|
||||
const deviceId = raw.trim();
|
||||
if (!DEVICE_ID_FORMAT.test(deviceId)) {
|
||||
throw new CodeError("设备标识无效", 400, "DEVICE_ID_INVALID");
|
||||
}
|
||||
return deviceId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the sync router (cloud-sync of redeemed code benefits).
|
||||
* Accepts an optional injected database for testing.
|
||||
*
|
||||
* POST /api/sync/bind
|
||||
* Request: { deviceId: string, code: string }
|
||||
* Response: 200 { ok: true, access: AccessInfo }
|
||||
* 400 { error: "设备标识无效" / "兑换码格式不正确" / ... }
|
||||
* 404 { error: "兑换码不存在,请检查后重试" }
|
||||
* Idempotent: binding an already-bound code is a no-op success.
|
||||
*
|
||||
* GET /api/sync/restore?deviceId=XXX
|
||||
* Response: 200 { codes: BoundCode[] } (empty array when none)
|
||||
* 400 { error: "设备标识无效" }
|
||||
*
|
||||
* POST /api/sync/unbind
|
||||
* Request: { deviceId: string, code: string }
|
||||
* Response: 200 { ok: true }
|
||||
* Idempotent: unbinding a non-existent binding still succeeds.
|
||||
*/
|
||||
export function createSyncRouter(injectedDb?: Database.Database): Router {
|
||||
const router = Router();
|
||||
|
||||
const bindStmt = (db: Database.Database) =>
|
||||
db.prepare("INSERT OR IGNORE INTO device_bindings (device_id, code) VALUES (?, ?)");
|
||||
const unbindStmt = (db: Database.Database) =>
|
||||
db.prepare("DELETE FROM device_bindings WHERE device_id = ? AND code = ?");
|
||||
const bindingsStmt = (db: Database.Database) =>
|
||||
db.prepare(
|
||||
`SELECT c.code, c.package_type, c.total_uses, c.used_uses, c.status
|
||||
FROM device_bindings b
|
||||
JOIN codes c ON c.code = b.code
|
||||
WHERE b.device_id = ?
|
||||
ORDER BY b.created_at, c.code`,
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /api/sync/bind
|
||||
* Bind a redeemed code to a device so it can be restored later.
|
||||
*/
|
||||
router.post("/bind", (req: Request, res: Response): void => {
|
||||
try {
|
||||
const { deviceId, code } = req.body as { deviceId?: string; code?: string };
|
||||
if (!deviceId || typeof deviceId !== "string") {
|
||||
res.status(400).json({ error: "设备标识无效" });
|
||||
return;
|
||||
}
|
||||
if (!code || typeof code !== "string") {
|
||||
res.status(400).json({ error: "请输入兑换码" });
|
||||
return;
|
||||
}
|
||||
const db = resolveDb(injectedDb);
|
||||
const id = parseDeviceId(deviceId);
|
||||
const normalized = validateFormat(code);
|
||||
// Verifies the code exists & is still redeemable (active, not expired,
|
||||
// not exhausted). Throws CodeError with Chinese message + status.
|
||||
const access: AccessInfo = checkRedeemable(db, normalized);
|
||||
bindStmt(db).run(id, access.code);
|
||||
res.status(200).json({ ok: true, access });
|
||||
} catch (err) {
|
||||
if (err instanceof CodeError) {
|
||||
handleCodeError(res, err);
|
||||
} else {
|
||||
console.error("POST /api/sync/bind error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/sync/restore?deviceId=XXX
|
||||
* Return all codes bound to this device with their access info.
|
||||
*/
|
||||
router.get("/restore", (req: Request, res: Response): void => {
|
||||
try {
|
||||
const deviceIdParam = req.query.deviceId;
|
||||
if (!deviceIdParam || typeof deviceIdParam !== "string") {
|
||||
res.status(400).json({ error: "设备标识无效" });
|
||||
return;
|
||||
}
|
||||
const db = resolveDb(injectedDb);
|
||||
const id = parseDeviceId(deviceIdParam);
|
||||
const rows = bindingsStmt(db).all(id) as BindingRow[];
|
||||
const codes: BoundCode[] = rows.map((row) => ({
|
||||
code: row.code,
|
||||
packageType: row.package_type,
|
||||
remainingUses: row.total_uses - row.used_uses,
|
||||
totalUses: row.total_uses,
|
||||
status: row.status,
|
||||
}));
|
||||
res.status(200).json({ codes });
|
||||
} catch (err) {
|
||||
if (err instanceof CodeError) {
|
||||
handleCodeError(res, err);
|
||||
} else {
|
||||
console.error("GET /api/sync/restore error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /api/sync/unbind
|
||||
* Remove a binding. Idempotent: succeeds even if the binding never existed.
|
||||
*/
|
||||
router.post("/unbind", (req: Request, res: Response): void => {
|
||||
try {
|
||||
const { deviceId, code } = req.body as { deviceId?: string; code?: string };
|
||||
if (!deviceId || typeof deviceId !== "string") {
|
||||
res.status(400).json({ error: "设备标识无效" });
|
||||
return;
|
||||
}
|
||||
if (!code || typeof code !== "string") {
|
||||
res.status(400).json({ error: "请输入兑换码" });
|
||||
return;
|
||||
}
|
||||
const db = resolveDb(injectedDb);
|
||||
const id = parseDeviceId(deviceId);
|
||||
const normalized = validateFormat(code);
|
||||
unbindStmt(db).run(id, normalized);
|
||||
res.status(200).json({ ok: true });
|
||||
} catch (err) {
|
||||
if (err instanceof CodeError) {
|
||||
handleCodeError(res, err);
|
||||
} else {
|
||||
console.error("POST /api/sync/unbind error:", err);
|
||||
res.status(500).json({ error: "服务器内部错误,请稍后重试" });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
Reference in new issue
Block a user