feat : big update
CI / Verify (push) Successful in 3m14s
CI / Build immutable images and deploy (push) Successful in 4m0s

This commit is contained in:
2026-10-01 18:37:15 +07:00 Unverified
parent c5037154cb
commit 0022625edb
76 changed files with 18671 additions and 29 deletions
@@ -0,0 +1,76 @@
import { PgDialect } from "drizzle-orm/pg-core";
import { beforeEach, describe, expect, it, vi } from "vitest";
const authorizeTicket = vi.fn();
const notifyCommission = vi.fn();
const deleteObject = vi.fn();
const deleteReturning = vi.fn();
const deleteWhere = vi.fn();
const updateWhere = vi.fn();
const tx = {
delete: vi.fn(() => ({ where: deleteWhere })),
update: vi.fn(() => ({ set: () => ({ where: updateWhere }) })),
};
vi.mock("@/db", () => ({ getDb: () => ({ transaction: async (run: (value: typeof tx) => Promise<unknown>) => run(tx) }) }));
vi.mock("@/lib/commission/tickets", () => ({ authorizeTicket }));
vi.mock("@/lib/commission/server", () => ({ notifyCommission }));
vi.mock("@/lib/media/storage", () => ({ getMediaStorage: async () => ({ delete: deleteObject }) }));
vi.mock("@/lib/security/rate-limit", () => ({ limitRequest: async () => undefined }));
const { DELETE } = await import("./route");
const ticketId = "11111111-1111-4111-8111-111111111111";
const messageId = "22222222-2222-4222-8222-222222222222";
const ownerId = "owner-1";
function deletionRequest(origin = "https://guide.sudloh.com") {
return new Request(`https://guide.sudloh.com/api/commission/tickets/${ticketId}/messages/${messageId}`,
{ method: "DELETE", headers: { Origin: origin } });
}
function context() {
return { params: Promise.resolve({ id: ticketId, messageId }) } as RouteContext<
"/api/commission/tickets/[id]/messages/[messageId]">;
}
describe("commission message deletion", () => {
beforeEach(() => {
process.env.BETTER_AUTH_URL = "https://guide.sudloh.com";
vi.clearAllMocks();
authorizeTicket.mockResolvedValue({ ticket: { userId: ownerId }, user: { id: ownerId } });
deleteWhere.mockImplementation(() => ({ returning: deleteReturning }));
deleteReturning.mockResolvedValue([{ imageObjectKey: "commission/messages/image-1" }]);
updateWhere.mockResolvedValue(undefined);
deleteObject.mockResolvedValue(undefined);
notifyCommission.mockResolvedValue(undefined);
});
it("rejects cross-origin requests before ticket authorization", async () => {
const response = await DELETE(deletionRequest("https://example.com"), context());
expect(response.status).toBe(403);
expect(authorizeTicket).not.toHaveBeenCalled();
});
it("deletes only a message owned by the current user in this ticket", async () => {
const response = await DELETE(deletionRequest(), context());
expect(response.status).toBe(204);
const condition = deleteWhere.mock.calls[0][0];
const query = new PgDialect().sqlToQuery(condition);
expect(query.sql).toContain('"ticket_id"');
expect(query.sql).toContain('"author_id"');
expect(query.params).toContain(ticketId);
expect(query.params).toContain(messageId);
expect(query.params).toContain(ownerId);
expect(deleteObject).toHaveBeenCalledWith("commission/messages/image-1");
expect(notifyCommission).toHaveBeenCalledWith(ticketId, ownerId);
});
it("leaves storage and notifications untouched when no owned message exists", async () => {
deleteReturning.mockResolvedValue([]);
const response = await DELETE(deletionRequest(), context());
expect(response.status).toBe(404);
expect(deleteObject).not.toHaveBeenCalled();
expect(notifyCommission).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,32 @@
import { and, eq } from "drizzle-orm";
import * as z from "zod";
import { getDb } from "@/db";
import { commissionMessages, commissionTickets } from "@/db/schema";
import { notifyCommission } from "@/lib/commission/server";
import { authorizeTicket } from "@/lib/commission/tickets";
import { getMediaStorage } from "@/lib/media/storage";
import { errorResponse, HttpError, requireSameOrigin } from "@/lib/security/http";
import { limitRequest } from "@/lib/security/rate-limit";
export async function DELETE(request: Request,
context: RouteContext<"/api/commission/tickets/[id]/messages/[messageId]">) {
try {
requireSameOrigin(request);
const { id, messageId } = await context.params;
if (!z.uuid().safeParse(messageId).success) throw new HttpError(404, "message-not-found");
const { ticket, user } = await authorizeTicket(id);
await limitRequest("commission-message-delete", user.id, 30);
const imageObjectKey = await getDb().transaction(async (tx) => {
const [message] = await tx.delete(commissionMessages)
.where(and(eq(commissionMessages.id, messageId), eq(commissionMessages.ticketId, id),
eq(commissionMessages.authorId, user.id)))
.returning({ imageObjectKey: commissionMessages.imageObjectKey });
if (!message) throw new HttpError(404, "message-not-found");
await tx.update(commissionTickets).set({ updatedAt: new Date() }).where(eq(commissionTickets.id, id));
return message.imageObjectKey;
});
if (imageObjectKey) await (await getMediaStorage()).delete(imageObjectKey).catch(() => undefined);
await notifyCommission(id, ticket.userId);
return new Response(null, { status: 204 });
} catch (cause) { return errorResponse(cause); }
}
@@ -0,0 +1,55 @@
import { eq } from "drizzle-orm";
import { getDb } from "@/db";
import { commissionMessages, commissionTickets } from "@/db/schema";
import { notifyCommission } from "@/lib/commission/server";
import { authorizeTicket } from "@/lib/commission/tickets";
import { getMediaStorage } from "@/lib/media/storage";
import { inspectImage } from "@/lib/media/inspect";
import { boundedBody, errorResponse, HttpError, requireSameOrigin, withUploadSlot } from "@/lib/security/http";
import { limitRequest } from "@/lib/security/rate-limit";
export async function POST(request: Request, context: RouteContext<"/api/commission/tickets/[id]/messages">) {
try {
requireSameOrigin(request);
const { id } = await context.params;
const { ticket, user } = await authorizeTicket(id);
if (ticket.status !== "open") throw new HttpError(409, "ticket-closed");
await limitRequest("commission-message", user.id, 60);
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, 6 * 1024 * 1024 + 64 * 1024).formData();
const value = form.get("text");
const body = typeof value === "string" ? value.trim() : "";
const image = form.get("image");
if (body.length > 4000 || (image && !(image instanceof File)))
throw new HttpError(400, "invalid-message");
if (!body && !image) throw new HttpError(400, "empty-message");
let imageObjectKey: string | null = null;
if (image instanceof File) {
if (image.size === 0 || image.size > 6 * 1024 * 1024 ||
!["image/png", "image/jpeg", "image/webp"].includes(image.type))
throw new HttpError(415, "invalid-message-image");
const bytes = new Uint8Array(await image.arrayBuffer());
await inspectImage(bytes, image.type as "image/png" | "image/jpeg" | "image/webp");
imageObjectKey = `commission/messages/${crypto.randomUUID()}`;
await (await getMediaStorage()).write(imageObjectKey, bytes, { type: image.type, acl: "private" });
}
let messageId: string;
try {
messageId = await getDb().transaction(async (tx) => {
const [message] = await tx.insert(commissionMessages).values({ ticketId: id, authorId: user.id,
text: body || null, imageObjectKey, imageMimeType: image instanceof File ? image.type : null })
.returning({ id: commissionMessages.id });
await tx.update(commissionTickets).set({ updatedAt: new Date() }).where(eq(commissionTickets.id, id));
return message.id;
});
} catch (cause) {
if (imageObjectKey) await (await getMediaStorage()).delete(imageObjectKey).catch(() => undefined);
throw cause;
}
await notifyCommission(id, ticket.userId);
return Response.json({ ok: true, messageId }, { status: 201 });
});
} catch (cause) { return errorResponse(cause); }
}