feat : also update
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const limit = vi.fn();
|
||||
const where = vi.fn(() => ({ limit }));
|
||||
const from = vi.fn(() => ({ where }));
|
||||
const select = vi.fn(() => ({ from }));
|
||||
const get = vi.fn();
|
||||
const set = vi.fn();
|
||||
const redis = { get, set };
|
||||
|
||||
vi.mock("server-only", () => ({}));
|
||||
vi.mock("@/db", () => ({ getDb: () => ({ select }) }));
|
||||
vi.mock("@/lib/redis/client", () => ({ getRedisClient: async () => redis }));
|
||||
|
||||
const { authorizeMobileSlip, createMobileSlipLink } = await import("./mobile-slip");
|
||||
const checkout = { id: "checkout-1", userId: "customer-1", amountBaht: 150 };
|
||||
|
||||
describe("commission mobile slip links", () => {
|
||||
beforeEach(() => { vi.clearAllMocks(); set.mockResolvedValue("OK"); });
|
||||
|
||||
it("requires checkout ownership before issuing a link", async () => {
|
||||
limit.mockResolvedValueOnce([]);
|
||||
await expect(createMobileSlipLink("checkout-1", "wrong-user")).rejects.toMatchObject({ status: 404 });
|
||||
expect(set).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("issues a ten-minute link and rejects an expired or replaced token", async () => {
|
||||
limit.mockResolvedValueOnce([{ id: checkout.id }]).mockResolvedValueOnce([]);
|
||||
const { token, digest } = await createMobileSlipLink(checkout.id, checkout.userId);
|
||||
expect(token).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
||||
expect(digest).toBe(createHash("sha256").update(token).digest("hex"));
|
||||
expect(set).toHaveBeenCalledWith(expect.stringContaining(":token:"),
|
||||
JSON.stringify({ checkoutId: checkout.id, userId: checkout.userId }), "EX", 600);
|
||||
expect(set).toHaveBeenCalledWith(expect.stringContaining(":active:"), digest, "EX", 600);
|
||||
|
||||
get.mockResolvedValueOnce(null);
|
||||
await expect(authorizeMobileSlip(token)).rejects.toMatchObject({ status: 404 });
|
||||
get.mockResolvedValueOnce(JSON.stringify({ checkoutId: checkout.id, userId: checkout.userId }))
|
||||
.mockResolvedValueOnce("another-digest");
|
||||
await expect(authorizeMobileSlip(token)).rejects.toMatchObject({ status: 404 });
|
||||
});
|
||||
|
||||
it("accepts the active token only for its stored checkout", async () => {
|
||||
const token = "x".repeat(43);
|
||||
const digest = createHash("sha256").update(token).digest("hex");
|
||||
get.mockResolvedValueOnce(JSON.stringify({ checkoutId: checkout.id, userId: checkout.userId }))
|
||||
.mockResolvedValueOnce(digest);
|
||||
limit.mockResolvedValueOnce([checkout]).mockResolvedValueOnce([]);
|
||||
expect(await authorizeMobileSlip(token)).toEqual({ checkout, ticketId: null, digest });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import "server-only";
|
||||
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { getDb } from "@/db";
|
||||
import { commissionCheckouts, commissionTickets } from "@/db/schema";
|
||||
import { getRedisClient, redisEventChannel } from "@/lib/redis/client";
|
||||
import { HttpError } from "@/lib/security/http";
|
||||
|
||||
const TTL_SECONDS = 600;
|
||||
const prefix = () => `${process.env.REDIS_SECURITY_PREFIX || "buzz:security"}:commission-mobile-slip`;
|
||||
const activeKey = (checkoutId: string) => `${prefix()}:active:${checkoutId}`;
|
||||
const tokenKey = (digest: string) => `${prefix()}:token:${digest}`;
|
||||
const errorKey = (digest: string) => `${prefix()}:error:${digest}`;
|
||||
const digestToken = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||
|
||||
export async function createMobileSlipLink(checkoutId: string, userId: string) {
|
||||
const [checkout] = await getDb().select({ id: commissionCheckouts.id }).from(commissionCheckouts)
|
||||
.where(and(eq(commissionCheckouts.id, checkoutId), eq(commissionCheckouts.userId, userId))).limit(1);
|
||||
if (!checkout) throw new HttpError(404, "checkout-not-found");
|
||||
const [ticket] = await getDb().select({ id: commissionTickets.id }).from(commissionTickets)
|
||||
.where(eq(commissionTickets.checkoutId, checkoutId)).limit(1);
|
||||
if (ticket) throw new HttpError(409, "checkout-already-paid");
|
||||
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const digest = digestToken(token);
|
||||
const redis = await getRedisClient();
|
||||
await redis.set(tokenKey(digest), JSON.stringify({ checkoutId, userId }), "EX", TTL_SECONDS);
|
||||
await redis.set(activeKey(checkoutId), digest, "EX", TTL_SECONDS);
|
||||
return { token, digest, expiresAt: Date.now() + TTL_SECONDS * 1000 };
|
||||
}
|
||||
|
||||
export async function authorizeMobileSlip(token: string) {
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) throw new HttpError(404, "upload-link-invalid");
|
||||
const digest = digestToken(token);
|
||||
const redis = await getRedisClient();
|
||||
const raw = await redis.get(tokenKey(digest));
|
||||
if (!raw) throw new HttpError(404, "upload-link-expired");
|
||||
const { checkoutId, userId } = JSON.parse(raw) as { checkoutId: string; userId: string };
|
||||
if (await redis.get(activeKey(checkoutId)) !== digest)
|
||||
throw new HttpError(404, "upload-link-expired");
|
||||
const [checkout] = await getDb().select().from(commissionCheckouts)
|
||||
.where(and(eq(commissionCheckouts.id, checkoutId), eq(commissionCheckouts.userId, userId))).limit(1);
|
||||
if (!checkout) throw new HttpError(404, "checkout-not-found");
|
||||
const [ticket] = await getDb().select({ id: commissionTickets.id }).from(commissionTickets)
|
||||
.where(eq(commissionTickets.checkoutId, checkoutId)).limit(1);
|
||||
return { checkout, ticketId: ticket?.id ?? null, digest };
|
||||
}
|
||||
|
||||
export async function mobileSlipStatus(checkoutId: string, userId: string, digest: string) {
|
||||
const [checkout] = await getDb().select({ id: commissionCheckouts.id }).from(commissionCheckouts)
|
||||
.where(and(eq(commissionCheckouts.id, checkoutId), eq(commissionCheckouts.userId, userId))).limit(1);
|
||||
if (!checkout) throw new HttpError(404, "checkout-not-found");
|
||||
const [ticket] = await getDb().select({ id: commissionTickets.id }).from(commissionTickets)
|
||||
.where(eq(commissionTickets.checkoutId, checkoutId)).limit(1);
|
||||
if (ticket) return { state: "complete", ticketId: ticket.id };
|
||||
if (!/^[a-f0-9]{64}$/.test(digest)) throw new HttpError(400, "invalid-upload-link");
|
||||
const redis = await getRedisClient();
|
||||
if (await redis.get(activeKey(checkoutId)) !== digest) return { state: "expired" };
|
||||
return { state: "pending", error: await redis.get(errorKey(digest)) };
|
||||
}
|
||||
|
||||
export async function recordMobileSlipError(digest: string, userId: string, cause: unknown) {
|
||||
const code = cause instanceof HttpError ? cause.message : "service-unavailable";
|
||||
const redis = await getRedisClient();
|
||||
const ttl = await redis.ttl(tokenKey(digest));
|
||||
if (ttl > 0) {
|
||||
await redis.set(errorKey(digest), code, "EX", ttl);
|
||||
await redis.publish(redisEventChannel(`commission:user:${userId}`), "changed");
|
||||
}
|
||||
}
|
||||
|
||||
export async function consumeMobileSlipLink(checkoutId: string, digest: string) {
|
||||
const redis = await getRedisClient();
|
||||
await redis.eval("if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0", 1,
|
||||
activeKey(checkoutId), digest);
|
||||
}
|
||||
|
||||
export async function invalidateMobileSlipLink(checkoutId: string) {
|
||||
await (await getRedisClient()).del(activeKey(checkoutId));
|
||||
}
|
||||
@@ -28,6 +28,19 @@ describe("commission request pricing and shape", () => {
|
||||
expect(commissionRequestSchema.safeParse({ ...selected, teams: [{ members: selected.teams[0].members.map((member, index) =>
|
||||
index === 0 ? { ...member, refinement: "6" } : member) }] }).success).toBe(false);
|
||||
});
|
||||
it("keeps each compared weapon's refinement and defaults older requests to R1", () => {
|
||||
const selected = { ...request, weapons: [{ characterKey: "a", weaponKeys: ["weapon-a", "weapon-b"],
|
||||
refinements: { "weapon-a": "5", "weapon-b": "2" } }] };
|
||||
expect(commissionRequestSchema.parse(selected).weapons[0].refinements).toEqual({
|
||||
"weapon-a": "5", "weapon-b": "2",
|
||||
});
|
||||
expect(commissionPrice(commissionRequestSchema.parse(selected))).toBe(180);
|
||||
expect(commissionRequestSchema.parse(request).weapons[0].refinements).toBeUndefined();
|
||||
expect(commissionRequestSchema.safeParse({ ...selected, weapons: [{ ...selected.weapons[0],
|
||||
refinements: { "weapon-a": "6" } }] }).success).toBe(false);
|
||||
expect(commissionRequestSchema.safeParse({ ...selected, weapons: [{ ...selected.weapons[0],
|
||||
refinements: { "weapon-c": "3" } }] }).success).toBe(false);
|
||||
});
|
||||
it("prices independent request types together", () => {
|
||||
expect(commissionPrice(commissionRequestSchema.parse(request))).toBe(200);
|
||||
expect(commissionPrice(commissionRequestSchema.parse({ teams: [], weapons: [],
|
||||
|
||||
@@ -12,10 +12,14 @@ const team = z.object({ members: z.array(member).length(4) }).refine(
|
||||
({ members }) => new Set(members.map((item) => item.characterKey)).size === 4,
|
||||
"A team needs four different characters",
|
||||
);
|
||||
const weaponComparison = z.object({ characterKey: key, weaponKeys: z.array(key).min(2).max(100) }).refine(
|
||||
({ weaponKeys }) => new Set(weaponKeys).size === weaponKeys.length,
|
||||
"Choose different weapons",
|
||||
);
|
||||
const weaponComparison = z.object({
|
||||
characterKey: key,
|
||||
weaponKeys: z.array(key).min(2).max(100),
|
||||
refinements: z.record(key, z.enum(["1", "2", "3", "4", "5"])).optional(),
|
||||
}).refine(({ weaponKeys }) => new Set(weaponKeys).size === weaponKeys.length, "Choose different weapons")
|
||||
.refine(({ weaponKeys, refinements }) =>
|
||||
Object.keys(refinements ?? {}).every((weaponKey) => weaponKeys.includes(weaponKey)),
|
||||
"Refinements must belong to selected weapons");
|
||||
const constellationComparison = z.object({
|
||||
characterKey: key,
|
||||
levels: z.array(z.number().int().min(0).max(6)).min(1).max(7),
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const set = vi.fn().mockResolvedValue(null);
|
||||
const getRedisClient = vi.fn().mockResolvedValue({ set });
|
||||
const inspectImage = vi.fn();
|
||||
const verifyCommissionSlip = vi.fn();
|
||||
|
||||
vi.mock("server-only", () => ({}));
|
||||
vi.mock("@/lib/redis/client", () => ({ getRedisClient }));
|
||||
vi.mock("@/lib/media/inspect", () => ({ inspectImage }));
|
||||
vi.mock("@/lib/commission/payment", () => ({ verifyCommissionSlip }));
|
||||
|
||||
const { verifyAndCreateTicket } = await import("./slip-upload");
|
||||
|
||||
describe("commission slip submission lock", () => {
|
||||
it("rejects a second verification for the same checkout before calling Slip2Go", async () => {
|
||||
const checkout = { id: "checkout-1", userId: "customer-1", amountBaht: 150 };
|
||||
const file = new File(["image"], "slip.png", { type: "image/png" });
|
||||
await expect(verifyAndCreateTicket(checkout as Parameters<typeof verifyAndCreateTicket>[0], file))
|
||||
.rejects.toMatchObject({ status: 409, message: "slip-verification-in-progress" });
|
||||
expect(set).toHaveBeenCalledWith(expect.stringContaining(":commission-slip-lock:checkout-1"),
|
||||
expect.any(String), "EX", 60, "NX");
|
||||
expect(inspectImage).not.toHaveBeenCalled();
|
||||
expect(verifyCommissionSlip).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import "server-only";
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { getDb } from "@/db";
|
||||
import { commissionCheckouts, commissionPayments, commissionTickets } from "@/db/schema";
|
||||
import { notifyPaidTicketDiscord } from "@/lib/commission/discord";
|
||||
import { verifyCommissionSlip } from "@/lib/commission/payment";
|
||||
import { notifyCommission } from "@/lib/commission/server";
|
||||
import { getMediaStorage } from "@/lib/media/storage";
|
||||
import { inspectImage } from "@/lib/media/inspect";
|
||||
import { getRedisClient } from "@/lib/redis/client";
|
||||
import { HttpError } from "@/lib/security/http";
|
||||
|
||||
export const MAX_SLIP_BYTES = 6 * 1024 * 1024;
|
||||
export type Checkout = typeof commissionCheckouts.$inferSelect;
|
||||
|
||||
export async function verifyAndCreateTicket(checkout: Checkout, file: FormDataEntryValue | null) {
|
||||
if (!(file instanceof File) || file.size === 0 || file.size > MAX_SLIP_BYTES ||
|
||||
!["image/png", "image/jpeg", "image/webp"].includes(file.type))
|
||||
throw new HttpError(415, "invalid-slip-image");
|
||||
|
||||
const redis = await getRedisClient();
|
||||
const lockKey = `${process.env.REDIS_SECURITY_PREFIX || "buzz:security"}:commission-slip-lock:${checkout.id}`;
|
||||
const lockId = crypto.randomUUID();
|
||||
if (await redis.set(lockKey, lockId, "EX", 60, "NX") !== "OK")
|
||||
throw new HttpError(409, "slip-verification-in-progress");
|
||||
try {
|
||||
const [existing] = await getDb().select({ id: commissionTickets.id }).from(commissionTickets)
|
||||
.where(eq(commissionTickets.checkoutId, checkout.id)).limit(1);
|
||||
if (existing) return { ticketId: existing.id, created: false };
|
||||
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
await inspectImage(bytes, file.type as "image/png" | "image/jpeg" | "image/webp");
|
||||
const verified = await verifyCommissionSlip(file, checkout.amountBaht, checkout.createdAt);
|
||||
const objectKey = `commission/slips/${crypto.randomUUID()}`;
|
||||
const storage = await getMediaStorage();
|
||||
await storage.write(objectKey, bytes, { type: file.type, acl: "private" });
|
||||
let ticketId: string;
|
||||
try {
|
||||
ticketId = await getDb().transaction(async (tx) => {
|
||||
const [ticket] = await tx.insert(commissionTickets).values({
|
||||
checkoutId: checkout.id, userId: checkout.userId,
|
||||
}).returning({ id: commissionTickets.id });
|
||||
await tx.insert(commissionPayments).values({
|
||||
checkoutId: checkout.id, ticketId: ticket.id, slipObjectKey: objectKey,
|
||||
slipMimeType: file.type, ...verified,
|
||||
});
|
||||
return ticket.id;
|
||||
});
|
||||
} catch (cause) {
|
||||
await storage.delete(objectKey).catch(() => undefined);
|
||||
const [paid] = await getDb().select({ id: commissionTickets.id }).from(commissionTickets)
|
||||
.where(eq(commissionTickets.checkoutId, checkout.id)).limit(1);
|
||||
if (paid) return { ticketId: paid.id, created: false };
|
||||
if (cause && typeof cause === "object" && "code" in cause && cause.code === "23505")
|
||||
throw new HttpError(409, "payment-already-used");
|
||||
throw cause;
|
||||
}
|
||||
await notifyCommission(ticketId, checkout.userId);
|
||||
await notifyPaidTicketDiscord(ticketId, checkout.amountBaht);
|
||||
return { ticketId, created: true };
|
||||
} finally {
|
||||
await redis.eval("if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end return 0", 1,
|
||||
lockKey, lockId).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
export function verificationError(code: string | undefined): string {
|
||||
const reason = code?.startsWith("slip-rejected:") ? code.slice("slip-rejected:".length)
|
||||
: code?.startsWith("slip2go-service:") ? code.slice("slip2go-service:".length) : code;
|
||||
switch (reason) {
|
||||
case "200000": return "พบสลิป แต่ Slip2Go ยังไม่ได้ยืนยันเงื่อนไขผู้รับและยอดเงิน กรุณาแจ้งผู้ดูแลระบบ (200000)";
|
||||
case "200401": return "บัญชีผู้รับในสลิปไม่ตรงกับบัญชีที่ตั้งไว้ (200401)";
|
||||
case "200402": return "ยอดเงินในสลิปไม่ตรงกับยอดคำขอ (200402)";
|
||||
case "200403": return "วันที่โอนในสลิปไม่ตรงเงื่อนไข (200403)";
|
||||
case "200404": return "Slip2Go ไม่พบข้อมูลสลิปในระบบธนาคาร (200404)";
|
||||
case "200500": return "Slip2Go ระบุว่าสลิปไม่ถูกต้อง (200500)";
|
||||
case "200501": return "สลิปนี้เคยถูกตรวจสอบแล้ว หากชำระเงินแล้ว กรุณาติดต่อผู้ดูแลก่อนโอนซ้ำ (200501)";
|
||||
case "200502": return "ธนาคารไม่สามารถตรวจสอบสลิปได้ในขณะนี้ กรุณาลองอีกครั้ง (200502)";
|
||||
case "400001":
|
||||
case "400002": return `อ่าน QR ในรูปสลิปไม่ได้ กรุณาอัปโหลดรูปสลิปจากแอปธนาคาร (${reason})`;
|
||||
case "400400": return "ตั้งค่าเงื่อนไขตรวจสอบสลิปไม่ถูกต้อง กรุณาแจ้งผู้ดูแลระบบ (400400)";
|
||||
case "401001": return "Slip2Go ไม่ยอมรับ API Secret ที่ตั้งไว้ กรุณาแจ้งผู้ดูแลระบบ (401001)";
|
||||
case "401005": return "โทเคน Slip2Go หมด กรุณาแจ้งผู้ดูแลระบบ (401005)";
|
||||
case "slip-amount-or-date-mismatch": return "ยอดเงินหรือวันเวลาในสลิปไม่ตรงกับคำขอนี้ กรุณาใช้สลิปจากการชำระเงินครั้งนี้";
|
||||
case "payment-already-used": return "สลิปนี้ถูกใช้กับคำขออื่นแล้ว";
|
||||
case "slip-verification-in-progress": return "กำลังตรวจสอบสลิปอยู่ กรุณารอสักครู่";
|
||||
default: return reason && /^\d{6}$/.test(reason)
|
||||
? `ตรวจสอบสลิปไม่ผ่าน (รหัส ${reason}) กรุณาแจ้งผู้ดูแลระบบ`
|
||||
: "ตรวจสอบสลิปไม่สำเร็จ กรุณาลองอีกครั้ง";
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user