feat : update
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
import type { SQL } from "drizzle-orm";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const authorizeTicket = vi.fn();
|
||||
const selectLimit = vi.fn();
|
||||
const selectWhere = vi.fn((condition: SQL) => { void condition; return { limit: selectLimit }; });
|
||||
const insertReturning = vi.fn();
|
||||
const insertValues = vi.fn(() => ({ returning: insertReturning }));
|
||||
const updateWhere = vi.fn();
|
||||
const tx = { insert: vi.fn(() => ({ values: insertValues })), update: vi.fn(() => ({ set: () => ({ where: updateWhere }) })) };
|
||||
const notifyCommission = vi.fn();
|
||||
|
||||
vi.mock("@/lib/commission/tickets", () => ({ authorizeTicket }));
|
||||
vi.mock("@/lib/commission/server", () => ({ notifyCommission }));
|
||||
vi.mock("@/lib/commission/push", () => ({ sendCommissionMessagePush: vi.fn() }));
|
||||
vi.mock("@/lib/security/rate-limit", () => ({ limitRequest: async () => undefined }));
|
||||
vi.mock("next/server", () => ({ after: vi.fn() }));
|
||||
vi.mock("@/db", () => ({ getDb: () => ({
|
||||
select: () => ({ from: () => ({ where: selectWhere }) }),
|
||||
transaction: async (run: (value: typeof tx) => Promise<unknown>) => run(tx),
|
||||
}) }));
|
||||
|
||||
const { POST } = await import("./route");
|
||||
const ticketId = "11111111-1111-4111-8111-111111111111";
|
||||
const parentId = "22222222-2222-4222-8222-222222222222";
|
||||
const messageId = "33333333-3333-4333-8333-333333333333";
|
||||
|
||||
function request(replyToId: string) {
|
||||
const body = new FormData();
|
||||
body.set("text", "A reply");
|
||||
body.set("replyToId", replyToId);
|
||||
return new Request(`https://guide.sudloh.com/api/commission/tickets/${ticketId}/messages`, {
|
||||
method: "POST", headers: { Origin: "https://guide.sudloh.com" }, body,
|
||||
});
|
||||
}
|
||||
|
||||
function context() {
|
||||
return { params: Promise.resolve({ id: ticketId }) } as RouteContext<"/api/commission/tickets/[id]/messages">;
|
||||
}
|
||||
|
||||
describe("commission message replies", () => {
|
||||
beforeEach(() => {
|
||||
process.env.BETTER_AUTH_URL = "https://guide.sudloh.com";
|
||||
vi.clearAllMocks();
|
||||
authorizeTicket.mockResolvedValue({ ticket: { status: "open", userId: "user-1", title: "A ticket" },
|
||||
user: { id: "user-1", name: "User" } });
|
||||
selectLimit.mockResolvedValue([{ id: parentId }]);
|
||||
insertReturning.mockResolvedValue([{ id: messageId }]);
|
||||
});
|
||||
|
||||
it("accepts a reply only after looking up its parent in the same ticket", async () => {
|
||||
const response = await POST(request(parentId), context());
|
||||
expect(response.status).toBe(201);
|
||||
const condition = new PgDialect().sqlToQuery(selectWhere.mock.calls[0][0]);
|
||||
expect(condition.sql).toContain('"ticket_id"');
|
||||
expect(condition.params).toContain(ticketId);
|
||||
expect(condition.params).toContain(parentId);
|
||||
expect(insertValues).toHaveBeenCalledWith(expect.objectContaining({ replyToId: parentId }));
|
||||
});
|
||||
|
||||
it("rejects a parent that is absent from this ticket", async () => {
|
||||
selectLimit.mockResolvedValue([]);
|
||||
const response = await POST(request(parentId), context());
|
||||
expect(response.status).toBe(404);
|
||||
expect(insertValues).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { after } from "next/server";
|
||||
import { getDb } from "@/db";
|
||||
import { commissionMessages, commissionTickets } from "@/db/schema";
|
||||
@@ -10,6 +10,7 @@ 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";
|
||||
import * as z from "zod";
|
||||
|
||||
export async function POST(request: Request, context: RouteContext<"/api/commission/tickets/[id]/messages">) {
|
||||
try {
|
||||
@@ -25,8 +26,17 @@ export async function POST(request: Request, context: RouteContext<"/api/commiss
|
||||
const value = form.get("text");
|
||||
const body = typeof value === "string" ? value.trim() : "";
|
||||
const image = form.get("image");
|
||||
const replyValue = form.get("replyToId");
|
||||
const replyToId = replyValue === null || replyValue === "" ? null : replyValue;
|
||||
if (body.length > 4000 || (image && !(image instanceof File)))
|
||||
throw new HttpError(400, "invalid-message");
|
||||
if (replyToId !== null) {
|
||||
if (typeof replyToId !== "string" || !z.uuid().safeParse(replyToId).success)
|
||||
throw new HttpError(400, "invalid-reply");
|
||||
const [parent] = await getDb().select({ id: commissionMessages.id }).from(commissionMessages)
|
||||
.where(and(eq(commissionMessages.id, replyToId), eq(commissionMessages.ticketId, id))).limit(1);
|
||||
if (!parent) throw new HttpError(404, "reply-not-found");
|
||||
}
|
||||
if (!body && !image) throw new HttpError(400, "empty-message");
|
||||
let imageObjectKey: string | null = null;
|
||||
if (image instanceof File) {
|
||||
@@ -41,7 +51,7 @@ export async function POST(request: Request, context: RouteContext<"/api/commiss
|
||||
let messageId: string;
|
||||
try {
|
||||
messageId = await getDb().transaction(async (tx) => {
|
||||
const [message] = await tx.insert(commissionMessages).values({ ticketId: id, authorId: user.id,
|
||||
const [message] = await tx.insert(commissionMessages).values({ ticketId: id, authorId: user.id, replyToId,
|
||||
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));
|
||||
|
||||
@@ -5,9 +5,10 @@ import { notifyCommission } from "@/lib/commission/server";
|
||||
import { authorizeTicket } from "@/lib/commission/tickets";
|
||||
import { errorResponse, HttpError, readJson, requireSameOrigin } from "@/lib/security/http";
|
||||
import { limitRequest } from "@/lib/security/rate-limit";
|
||||
import { isSingleEmoji } from "@/lib/commission/reaction";
|
||||
import * as z from "zod";
|
||||
|
||||
const inputSchema = z.object({ messageId: z.uuid(), emoji: z.enum(["👍", "❤️", "😂", "😮", "😢", "🎉"]) });
|
||||
const inputSchema = z.object({ messageId: z.uuid(), emoji: z.string().refine(isSingleEmoji) });
|
||||
|
||||
export async function POST(request: Request, context: RouteContext<"/api/commission/tickets/[id]/reactions">) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { HttpError } from "@/lib/security/http";
|
||||
|
||||
const requireAdmin = vi.fn();
|
||||
const notifyCommission = vi.fn();
|
||||
const returning = vi.fn();
|
||||
const where = vi.fn(() => ({ returning }));
|
||||
const set = vi.fn(() => ({ where }));
|
||||
|
||||
vi.mock("@/lib/auth/server", () => ({ requireAdmin }));
|
||||
vi.mock("@/lib/commission/server", () => ({ notifyCommission }));
|
||||
vi.mock("@/db", () => ({ getDb: () => ({ update: () => ({ set }) }) }));
|
||||
|
||||
const { PATCH } = await import("./route");
|
||||
const ticketId = "11111111-1111-4111-8111-111111111111";
|
||||
|
||||
function statusRequest(status: string, origin = "https://guide.sudloh.com") {
|
||||
return new Request(`https://guide.sudloh.com/api/commission/tickets/${ticketId}/status`, {
|
||||
method: "PATCH", headers: { Origin: origin, "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ status }),
|
||||
});
|
||||
}
|
||||
|
||||
function context() {
|
||||
return { params: Promise.resolve({ id: ticketId }) } as RouteContext<"/api/commission/tickets/[id]/status">;
|
||||
}
|
||||
|
||||
describe("commission ticket status", () => {
|
||||
beforeEach(() => {
|
||||
process.env.BETTER_AUTH_URL = "https://guide.sudloh.com";
|
||||
vi.clearAllMocks();
|
||||
requireAdmin.mockResolvedValue({ user: { id: "admin-1" } });
|
||||
returning.mockResolvedValue([{ userId: "customer-1" }]);
|
||||
});
|
||||
|
||||
it("publishes a distinct closure event for the customer", async () => {
|
||||
const response = await PATCH(statusRequest("closed"), context());
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({ status: "closed" });
|
||||
expect(notifyCommission).toHaveBeenCalledWith(ticketId, "customer-1", "status:closed");
|
||||
});
|
||||
|
||||
it("rejects non-admin and cross-origin attempts", async () => {
|
||||
expect((await PATCH(statusRequest("closed", "https://elsewhere.test"), context())).status).toBe(403);
|
||||
expect(requireAdmin).not.toHaveBeenCalled();
|
||||
requireAdmin.mockRejectedValueOnce(new HttpError(401, "unauthorized"));
|
||||
expect((await PATCH(statusRequest("closed"), context())).status).toBe(401);
|
||||
expect(notifyCommission).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,7 @@ export async function PATCH(request: Request, context: RouteContext<"/api/commis
|
||||
.set({ status: parsed.data.status, updatedAt: new Date() })
|
||||
.where(eq(commissionTickets.id, id)).returning({ userId: commissionTickets.userId });
|
||||
if (!ticket) throw new HttpError(404, "ticket-not-found");
|
||||
await notifyCommission(id, ticket.userId);
|
||||
await notifyCommission(id, ticket.userId, `status:${parsed.data.status}`);
|
||||
return Response.json({ status: parsed.data.status });
|
||||
} catch (cause) { return errorResponse(cause); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import sharp from "sharp";
|
||||
import { HttpError } from "@/lib/security/http";
|
||||
|
||||
const requireCommissionUser = vi.fn();
|
||||
const returning = vi.fn();
|
||||
const where = vi.fn(() => ({ returning }));
|
||||
const set = vi.fn(() => ({ where }));
|
||||
const write = vi.fn();
|
||||
|
||||
vi.mock("@/lib/commission/server", () => ({ requireCommissionUser }));
|
||||
vi.mock("@/db", () => ({ getDb: () => ({ update: () => ({ set }) }) }));
|
||||
vi.mock("@/lib/media/storage", () => ({ getMediaStorage: async () => ({ write }), publicMediaUrl: (key: string) => `https://cdn.test/${key}` }));
|
||||
vi.mock("@/lib/security/rate-limit", () => ({ limitRequest: async () => undefined }));
|
||||
|
||||
const { POST } = await import("./route");
|
||||
|
||||
function profileRequest(name: string, image?: File, origin = "https://guide.sudloh.com") {
|
||||
const body = new FormData();
|
||||
body.set("name", name);
|
||||
if (image) body.set("image", image);
|
||||
return new Request("https://guide.sudloh.com/api/profile", { method: "POST", headers: { Origin: origin }, body });
|
||||
}
|
||||
|
||||
describe("profile update", () => {
|
||||
beforeEach(() => {
|
||||
process.env.BETTER_AUTH_URL = "https://guide.sudloh.com";
|
||||
vi.clearAllMocks();
|
||||
requireCommissionUser.mockResolvedValue({ id: "user-1", image: null });
|
||||
returning.mockResolvedValue([{ name: "New Name", image: null }]);
|
||||
});
|
||||
|
||||
it("updates the signed-in user's display name", async () => {
|
||||
const response = await POST(profileRequest(" New Name "));
|
||||
expect(response.status).toBe(200);
|
||||
expect(set).toHaveBeenCalledWith({ name: "New Name" });
|
||||
expect(await response.json()).toEqual({ name: "New Name", image: null });
|
||||
});
|
||||
|
||||
it("rejects invalid names, image types, and cross-origin submissions", async () => {
|
||||
expect((await POST(profileRequest("x"))).status).toBe(400);
|
||||
expect((await POST(profileRequest("New Name", new File(["x"], "avatar.svg", { type: "image/svg+xml" })))).status).toBe(415);
|
||||
expect((await POST(profileRequest("New Name", undefined, "https://elsewhere.test"))).status).toBe(403);
|
||||
expect(set).not.toHaveBeenCalled();
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("validates and stores an uploaded image", async () => {
|
||||
const bytes = await sharp({ create: { width: 8, height: 8, channels: 3, background: "red" } }).png().toBuffer();
|
||||
const response = await POST(profileRequest("New Name", new File([bytes], "avatar.png", { type: "image/png" })));
|
||||
expect(response.status).toBe(200);
|
||||
expect(write).toHaveBeenCalledWith(expect.stringMatching(/^profiles\/.+\.webp$/),
|
||||
expect.any(Uint8Array), { type: "image/webp", acl: "public-read" });
|
||||
expect(set).toHaveBeenCalledWith(expect.objectContaining({ name: "New Name",
|
||||
image: expect.stringMatching(/^https:\/\/cdn\.test\/profiles\/.+\.webp$/) }));
|
||||
});
|
||||
|
||||
it("requires an authenticated user", async () => {
|
||||
requireCommissionUser.mockRejectedValueOnce(new HttpError(401, "unauthorized"));
|
||||
expect((await POST(profileRequest("New Name"))).status).toBe(401);
|
||||
expect(set).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { eq } from "drizzle-orm";
|
||||
import sharp from "sharp";
|
||||
import { getDb } from "@/db";
|
||||
import { users } from "@/db/schema";
|
||||
import { requireCommissionUser } from "@/lib/commission/server";
|
||||
import { inspectImage } from "@/lib/media/inspect";
|
||||
import { getMediaStorage, publicMediaUrl } from "@/lib/media/storage";
|
||||
import { boundedBody, errorResponse, HttpError, requireSameOrigin, withUploadSlot } from "@/lib/security/http";
|
||||
import { limitRequest } from "@/lib/security/rate-limit";
|
||||
|
||||
const MAX_PROFILE_IMAGE_BYTES = 6 * 1024 * 1024;
|
||||
const IMAGE_TYPES = ["image/png", "image/jpeg", "image/webp"] as const;
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
requireSameOrigin(request);
|
||||
const user = await requireCommissionUser();
|
||||
await limitRequest("profile-update", user.id, 20);
|
||||
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_PROFILE_IMAGE_BYTES + 64 * 1024).formData();
|
||||
const rawName = form.get("name");
|
||||
const name = typeof rawName === "string" ? rawName.trim() : "";
|
||||
if (name.length < 2 || name.length > 80) throw new HttpError(400, "invalid-display-name");
|
||||
const image = form.get("image");
|
||||
if (image !== null && !(image instanceof File)) throw new HttpError(400, "invalid-profile-image");
|
||||
let objectKey: string | null = null;
|
||||
if (image instanceof File) {
|
||||
if (image.size === 0 || image.size > MAX_PROFILE_IMAGE_BYTES ||
|
||||
!IMAGE_TYPES.includes(image.type as typeof IMAGE_TYPES[number]))
|
||||
throw new HttpError(415, "invalid-profile-image");
|
||||
const bytes = new Uint8Array(await image.arrayBuffer());
|
||||
await inspectImage(bytes, image.type as typeof IMAGE_TYPES[number]);
|
||||
const output = await sharp(bytes).rotate().resize(256, 256, { fit: "cover" }).webp({ quality: 82 }).toBuffer();
|
||||
objectKey = `profiles/${crypto.randomUUID()}.webp`;
|
||||
await (await getMediaStorage()).write(objectKey, output, { type: "image/webp", acl: "public-read" });
|
||||
}
|
||||
try {
|
||||
const [updated] = await getDb().update(users).set({ name,
|
||||
...(objectKey ? { image: publicMediaUrl(objectKey) } : {}) })
|
||||
.where(eq(users.id, user.id)).returning({ name: users.name, image: users.image });
|
||||
if (!updated) throw new HttpError(401, "unauthorized");
|
||||
if (objectKey && user.image) {
|
||||
const prefix = publicMediaUrl("profiles/");
|
||||
if (user.image.startsWith(prefix)) {
|
||||
const previousKey = `profiles/${user.image.slice(prefix.length)}`;
|
||||
if (/^profiles\/[0-9a-f-]{36}\.webp$/u.test(previousKey))
|
||||
await (await getMediaStorage()).delete(previousKey).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
return Response.json(updated);
|
||||
} catch (cause) {
|
||||
if (objectKey) await (await getMediaStorage()).delete(objectKey).catch(() => undefined);
|
||||
throw cause;
|
||||
}
|
||||
});
|
||||
} catch (cause) { return errorResponse(cause); }
|
||||
}
|
||||
Reference in New Issue
Block a user