feat : also update
CI / Verify (push) Successful in 2m4s
CI / Build immutable images and deploy (push) Successful in 3m8s

This commit is contained in:
2026-10-01 19:47:02 +07:00 Unverified
parent 0022625edb
commit 2517982a27
18 changed files with 609 additions and 83 deletions
@@ -0,0 +1,27 @@
import QRCode from "qrcode";
import { createMobileSlipLink, mobileSlipStatus } from "@/lib/commission/mobile-slip";
import { requireCommissionUser } from "@/lib/commission/server";
import { errorResponse, requireSameOrigin } from "@/lib/security/http";
import { limitRequest } from "@/lib/security/rate-limit";
export async function POST(request: Request, context: RouteContext<"/api/commission/checkouts/[id]/upload-link">) {
try {
requireSameOrigin(request);
const user = await requireCommissionUser();
await limitRequest("commission-upload-link", user.id, 10);
const { id } = await context.params;
const { token, digest, expiresAt } = await createMobileSlipLink(id, user.id);
const url = new URL(`/commission/upload-slip#${token}`, process.env.BETTER_AUTH_URL).toString();
const qr = await QRCode.toDataURL(url, { margin: 2, width: 240 });
return Response.json({ url, qr, digest, expiresAt }, { headers: { "Cache-Control": "no-store" } });
} catch (cause) { return errorResponse(cause); }
}
export async function GET(request: Request, context: RouteContext<"/api/commission/checkouts/[id]/upload-link">) {
try {
const user = await requireCommissionUser();
const { id } = await context.params;
const digest = new URL(request.url).searchParams.get("digest") ?? "";
return Response.json(await mobileSlipStatus(id, user.id, digest), { headers: { "Cache-Control": "no-store" } });
} catch (cause) { return errorResponse(cause); }
}
@@ -1,16 +1,12 @@
import { and, eq } from "drizzle-orm";
import { getDb } from "@/db";
import { commissionCheckouts, commissionPayments, commissionTickets } from "@/db/schema";
import { notifyCommission, requireCommissionUser } from "@/lib/commission/server";
import { notifyPaidTicketDiscord } from "@/lib/commission/discord";
import { verifyCommissionSlip } from "@/lib/commission/payment";
import { getMediaStorage } from "@/lib/media/storage";
import { inspectImage } from "@/lib/media/inspect";
import { commissionCheckouts } from "@/db/schema";
import { requireCommissionUser } from "@/lib/commission/server";
import { invalidateMobileSlipLink } from "@/lib/commission/mobile-slip";
import { MAX_SLIP_BYTES, verifyAndCreateTicket } from "@/lib/commission/slip-upload";
import { boundedBody, errorResponse, HttpError, requireSameOrigin, withUploadSlot } from "@/lib/security/http";
import { limitRequest } from "@/lib/security/rate-limit";
const MAX_SLIP_BYTES = 6 * 1024 * 1024;
export async function POST(request: Request, context: RouteContext<"/api/commission/checkouts/[id]/verify">) {
try {
requireSameOrigin(request);
@@ -20,47 +16,15 @@ export async function POST(request: Request, context: RouteContext<"/api/commiss
const [checkout] = await getDb().select().from(commissionCheckouts)
.where(and(eq(commissionCheckouts.id, id), eq(commissionCheckouts.userId, user.id))).limit(1);
if (!checkout) throw new HttpError(404, "checkout-not-found");
const [existing] = await getDb().select({ id: commissionTickets.id }).from(commissionTickets)
.where(eq(commissionTickets.checkoutId, id)).limit(1);
if (existing) return Response.json({ ticketId: existing.id });
if (!request.headers.get("content-type")?.startsWith("multipart/form-data;"))
throw new HttpError(415, "expected-multipart");
return await withUploadSlot(async () => {
const form = await boundedBody(request, MAX_SLIP_BYTES + 64 * 1024).formData();
const file = form.get("file");
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 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: user.id,
}).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 Response.json({ ticketId: paid.id });
if (cause && typeof cause === "object" && "code" in cause && cause.code === "23505")
throw new HttpError(409, "payment-already-used");
throw cause;
}
await notifyCommission(ticketId, user.id);
await notifyPaidTicketDiscord(ticketId, checkout.amountBaht);
return Response.json({ ticketId }, { status: 201, headers: { "Cache-Control": "no-store" } });
const result = await verifyAndCreateTicket(checkout, form.get("file"));
await invalidateMobileSlipLink(checkout.id).catch(() => undefined);
return Response.json({ ticketId: result.ticketId }, {
status: result.created ? 201 : 200, headers: { "Cache-Control": "no-store" },
});
});
} catch (cause) { return errorResponse(cause); }
}
@@ -0,0 +1,67 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { HttpError } from "@/lib/security/http";
const authorizeMobileSlip = vi.fn();
const consumeMobileSlipLink = vi.fn();
const recordMobileSlipError = vi.fn();
const verifyAndCreateTicket = vi.fn();
const limitRequest = vi.fn();
vi.mock("@/lib/commission/mobile-slip", () => ({
authorizeMobileSlip, consumeMobileSlipLink, recordMobileSlipError,
}));
vi.mock("@/lib/commission/slip-upload", () => ({ MAX_SLIP_BYTES: 6 * 1024 * 1024, verifyAndCreateTicket }));
vi.mock("@/lib/security/rate-limit", () => ({ limitRequest }));
const { GET, POST } = await import("./route");
const token = "x".repeat(43);
const checkout = { id: "checkout-1", userId: "customer-1", amountBaht: 150 };
function upload(origin = "https://guide.sudloh.com") {
const form = new FormData();
form.set("file", new File(["image"], "slip.png", { type: "image/png" }));
return new Request("https://guide.sudloh.com/api/commission/mobile-slip", {
method: "POST", headers: { Origin: origin, Authorization: `Bearer ${token}` }, body: form,
});
}
describe("commission phone slip upload", () => {
beforeEach(() => {
process.env.BETTER_AUTH_URL = "https://guide.sudloh.com";
vi.clearAllMocks();
authorizeMobileSlip.mockResolvedValue({ checkout, ticketId: null, digest: "digest-1" });
verifyAndCreateTicket.mockResolvedValue({ ticketId: "ticket-1", created: true });
consumeMobileSlipLink.mockResolvedValue(undefined);
recordMobileSlipError.mockResolvedValue(undefined);
});
it("checks the bearer link without requiring a login", async () => {
const response = await GET(new Request("https://guide.sudloh.com/api/commission/mobile-slip", {
headers: { Authorization: `Bearer ${token}` },
}));
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ amountBaht: 150, complete: false });
expect(authorizeMobileSlip).toHaveBeenCalledWith(token);
});
it("verifies a phone slip and consumes the link", async () => {
const response = await POST(upload());
expect(response.status).toBe(201);
expect(verifyAndCreateTicket).toHaveBeenCalledWith(checkout, expect.any(File));
expect(consumeMobileSlipLink).toHaveBeenCalledWith("checkout-1", "digest-1");
});
it("rejects cross-origin uploads before using the link", async () => {
expect((await POST(upload("https://example.com"))).status).toBe(403);
expect(authorizeMobileSlip).not.toHaveBeenCalled();
});
it("reports verification failures for the desktop and permits retry", async () => {
const failure = new HttpError(422, "slip-rejected:200402");
verifyAndCreateTicket.mockRejectedValueOnce(failure);
const response = await POST(upload());
expect(response.status).toBe(422);
expect(recordMobileSlipError).toHaveBeenCalledWith("digest-1", "customer-1", failure);
expect(consumeMobileSlipLink).not.toHaveBeenCalled();
});
});
+42
View File
@@ -0,0 +1,42 @@
import { authorizeMobileSlip, consumeMobileSlipLink, recordMobileSlipError } from "@/lib/commission/mobile-slip";
import { MAX_SLIP_BYTES, verifyAndCreateTicket } from "@/lib/commission/slip-upload";
import { boundedBody, errorResponse, HttpError, requireSameOrigin, withUploadSlot } from "@/lib/security/http";
import { limitRequest } from "@/lib/security/rate-limit";
function bearerToken(request: Request) {
const value = request.headers.get("authorization") ?? "";
if (!value.startsWith("Bearer ")) throw new HttpError(401, "upload-link-required");
return value.slice(7);
}
export async function GET(request: Request) {
try {
const { checkout, ticketId } = await authorizeMobileSlip(bearerToken(request));
return Response.json({ amountBaht: checkout.amountBaht, complete: Boolean(ticketId) },
{ headers: { "Cache-Control": "no-store" } });
} catch (cause) { return errorResponse(cause); }
}
export async function POST(request: Request) {
let handoff: Awaited<ReturnType<typeof authorizeMobileSlip>> | undefined;
try {
requireSameOrigin(request);
handoff = await authorizeMobileSlip(bearerToken(request));
await limitRequest("commission-mobile-slip-token", handoff.digest, 10);
if (handoff.ticketId) return Response.json({ complete: true }, { headers: { "Cache-Control": "no-store" } });
if (!request.headers.get("content-type")?.startsWith("multipart/form-data;"))
throw new HttpError(415, "expected-multipart");
const { checkout, digest } = handoff;
const result = await withUploadSlot(async () => {
const form = await boundedBody(request, MAX_SLIP_BYTES + 64 * 1024).formData();
return verifyAndCreateTicket(checkout, form.get("file"));
});
await consumeMobileSlipLink(checkout.id, digest).catch(() => undefined);
return Response.json({ complete: true }, {
status: result.created ? 201 : 200, headers: { "Cache-Control": "no-store" },
});
} catch (cause) {
if (handoff) await recordMobileSlipError(handoff.digest, handoff.checkout.userId, cause).catch(() => undefined);
return errorResponse(cause);
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ async function CommissionContent() {
await connection();
const session = await getCustomerSession();
if (!session) return <div className="flex flex-col gap-4 rounded-xl border p-6">
<p>เข้าสู่ระบบหรือสมัครสมาชิกก่อนเริ่มคำขอคอมมิชชัน</p>
<p>เข้าสู่ระบบหรือสมัครสมาชิกก่อนเริ่มคำขอ</p>
<div className="flex flex-wrap gap-2">
<Button nativeButton={false} render={<Link href="/login?next=%2Fcommission" />}>เข้าสู่ระบบ</Button>
<Button variant="outline" nativeButton={false} render={<Link href="/register?next=%2Fcommission" />}>สมัครสมาชิก</Button>
+9
View File
@@ -0,0 +1,9 @@
import { MobileSlipForm } from "@/components/commission/mobile-slip-form";
import { SiteHeader } from "@/components/public/site-header";
export default function UploadSlipPage() {
return <div className="min-h-svh"><SiteHeader /><main className="mx-auto flex max-w-md flex-col gap-6 p-4 py-10">
<h1 className="font-heading text-3xl font-semibold">อัปโหลดสลิป</h1>
<MobileSlipForm />
</main></div>;
}