diff --git a/apps/api/src/scripts/seed-test-verification.ts b/apps/api/src/scripts/seed-test-verification.ts index 68fd3b0..3d3de5c 100644 --- a/apps/api/src/scripts/seed-test-verification.ts +++ b/apps/api/src/scripts/seed-test-verification.ts @@ -9,7 +9,7 @@ import type { AccountRole } from "../services/accounts"; import { VerificationsService } from "../services/verifications"; const DEFAULT_DISCORD_ID = "1325552430942916731"; -const FIXTURES_DIR = path.join(import.meta.dir, "fixtures"); +const MEDIA_DIR = path.join(import.meta.dir, "test-verification-media"); const BUCKET = `verification-media${env.NODE_ENV === "production" ? "" : "-dev"}`; const { values: args } = parseArgs({ @@ -68,12 +68,12 @@ async function seedTestAssessment(accountId: string): Promise { return result.id; } -async function uploadFixtures(assessmentId: string) { - const names = await readdir(FIXTURES_DIR).catch(() => []); - if (names.length === 0) log.warn({ dir: FIXTURES_DIR }, "no fixture media found, verification will have no media"); +async function uploadMedia(assessmentId: string) { + const names = await readdir(MEDIA_DIR).catch(() => []); + if (names.length === 0) log.warn({ dir: MEDIA_DIR }, "no fixture media found, verification will have no media"); for (const name of names) { - const file = Bun.file(path.join(FIXTURES_DIR, name)); + const file = Bun.file(path.join(MEDIA_DIR, name)); const key = `${assessmentId}/${crypto.randomUUID()}`; await r2.write(key, file, { type: file.type }); log.info({ key, name, size: file.size }, "uploaded fixture media"); @@ -96,7 +96,7 @@ async function uploadFixtures(assessmentId: string) { const verification = await verifications.create(assessmentId); if (!verification) throw new Error("Failed to create test verification"); - await uploadFixtures(assessmentId); + await uploadMedia(assessmentId); const submitted = await verifications.submit(verification.id); if (!submitted) throw new Error("Failed to submit test verification"); diff --git a/apps/api/src/scripts/test-verification-media/6bb683ae5a62f8963d210ac1852026bd389f3f58a47cadf2e953d502454d1f70_1.mp4 b/apps/api/src/scripts/test-verification-media/6bb683ae5a62f8963d210ac1852026bd389f3f58a47cadf2e953d502454d1f70_1.mp4 new file mode 100644 index 0000000..5653141 Binary files /dev/null and b/apps/api/src/scripts/test-verification-media/6bb683ae5a62f8963d210ac1852026bd389f3f58a47cadf2e953d502454d1f70_1.mp4 differ diff --git a/apps/api/src/scripts/test-verification-media/go-6.mp4 b/apps/api/src/scripts/test-verification-media/go-6.mp4 new file mode 100644 index 0000000..2edd349 Binary files /dev/null and b/apps/api/src/scripts/test-verification-media/go-6.mp4 differ diff --git a/apps/api/src/server.ts b/apps/api/src/server.ts index 4719722..f44d550 100644 --- a/apps/api/src/server.ts +++ b/apps/api/src/server.ts @@ -5,14 +5,14 @@ import { Activity, } from "@blade-and-brawn/domain" import { cors } from "@elysiajs/cors"; -import { Elysia, redirect, status, t } from "elysia"; +import { Elysia, NotFoundError, redirect, status, t } from "elysia"; import { PrintfulError, WebflowError, Printful, Webflow, } from "@blade-and-brawn/commerce"; -import { AccountIdSchema, BigIntIdSchema, DEFAULT_NAME, DUMMY_PASSWORD_HASH, env, log } from "./util"; +import { AccountIdSchema, BadGatewayError, BadRequestError, BigIntIdSchema, ConflictError, DEFAULT_NAME, DUMMY_PASSWORD_HASH, env, ForbiddenError, HttpError, log, UnauthorizedError } from "./util"; import serverTiming from "@elysia/server-timing"; import jwt from "@elysia/jwt"; import { CommerceService, WOrderStatusSchema } from "./services/commerce"; @@ -33,6 +33,7 @@ import { VerificationsService, VerificationStatusSchema } from "./services/verif const EVENT_QUEUE_MANAGE_DELAY_MS = 1000 // 1 sec const JWT_EXP = "1d"; const JWT_EXP_SECONDS = 60 * 60 * 24; // keep in sync with JWT_EXP; used for cookie maxAge +const PG_UNIQUE_VIOLATION = "23505"; // SERVICES // ----------------------- @@ -117,35 +118,31 @@ export const app = new Elysia() }) .use(authPlugin) - .error({ - PrintfulError, - WebflowError, - CalculatorUnavailableError - }) - + .error({ PrintfulError, WebflowError, CalculatorUnavailableError, HttpError }) .onError(({ code, error }) => { - // Database Errors - if (error instanceof DatabaseError && error.code === "23505") - return status(409, { error: "Conflicts with an existing record" }); + // Database errors + if (error instanceof DatabaseError) { + if (error.code === PG_UNIQUE_VIOLATION) + return status(409, { error: "Conflicts with an existing record" }); + log.error({ err: error }, "Database error"); + return status(500, { error: "Internal Server Error" }); + } - // Custom Errors + // All other errors switch (code) { + case "HttpError": + break; case "PrintfulError": case "WebflowError": - log.error( - { upstreamStatus: error.upstreamStatus, payload: error.payload }, - error.message, - ); - return status(502, { error: error.message }); - case "CalculatorUnavailableError": - log.error({ err: error.cause }, error.message); - return status(503, { error: error.message }); + log.error({ upstreamStatus: error.upstreamStatus, payload: error.payload }, error.message); + break; case "NOT_FOUND": return status(404, { error: error.message || "NOT_FOUND" }); case "VALIDATION": - return status(422, { error: error.message }); + return status(422, { error: error.message, detail: error.detail }); default: - log.error({ err: error }, "unhandled error"); + log.error({ err: error }, "Unhandled error"); + return status(500, { error: "Internal Server Error" }) } }) @@ -171,7 +168,7 @@ export const app = new Elysia() .post("/auth/login", async ({ jwt, body: { password, email }, cookie: { auth } }) => { const account = await s.Accounts.getByEmail(email); const password_match = await Bun.password.verify(password, account?.password_hash ?? DUMMY_PASSWORD_HASH); - if (!account || !password_match) return status(401, { error: "Invalid credentials" }); + if (!account || !password_match) throw new UnauthorizedError("Invalid credentials"); auth.set({ value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }), @@ -209,10 +206,10 @@ export const app = new Elysia() return redirect(url.toString(), 302); }) .get("/callback", async ({ query, cookie: { authDiscord, auth }, jwt }) => { - if (query.error) return status(400, { error: query.error_description ? `${query.error}: ${query.error_description}` : query.error }); + if (query.error) throw new BadRequestError(query.error_description ? `${query.error}: ${query.error_description}` : query.error); - if (!query.state) return status(400, { error: "No Discord OAuth2 state query parameter provided" }); - if (query.state !== authDiscord.value) return status(400, { error: "Invalid Discord OAuth state" }); + if (!query.state) throw new BadRequestError("No Discord OAuth2 state query parameter provided"); + if (query.state !== authDiscord.value) throw new BadRequestError("Invalid Discord OAuth state"); const tokenRes = await fetch("https://discord.com/api/oauth2/token", { method: "POST", @@ -229,7 +226,7 @@ export const app = new Elysia() }); if (!tokenRes.ok) { const errorBody = await tokenRes.json().catch(() => null); - return status(502, { error: errorBody ?? "Discord token exchange failed" }); + throw new BadGatewayError(errorBody ?? "Discord token exchange failed"); } const tokenResPayload = await tokenRes.json(); @@ -240,7 +237,7 @@ export const app = new Elysia() }); if (!identityRes.ok) { const errorBody = await identityRes.json().catch(() => null); - return status(502, { error: errorBody ?? "Failed to fetch Discord identity" }); + throw new BadGatewayError(errorBody ?? "Failed to fetch Discord identity"); } const identityResPayload = await identityRes.json(); @@ -368,7 +365,7 @@ export const app = new Elysia() // Sync status .get("/", async ({ sessionId }) => { const latestSyncState = await s.Commerce.Apparel.Syncs.getLatestSyncState(sessionId); - if (!latestSyncState) return status(404, { error: "No product sync found for the provided session" }); + if (!latestSyncState) throw new NotFoundError("No product sync found for the provided session"); return latestSyncState; }) // Run sync @@ -387,10 +384,10 @@ export const app = new Elysia() ) .get("/:pProductId", async ({ params: { pProductId } }) => { const pProduct = await s.Commerce.Printful.Products.get(pProductId); - if (!pProduct) return status(404, { error: "Missing printful product" }); + if (!pProduct) throw new NotFoundError("Missing printful product"); const wProductId = pProduct.sync_product.external_id.split("-")[0]; - if (!wProductId) return status(404, { error: "Missing webflow product ID" }); + if (!wProductId) throw new NotFoundError("Missing webflow product ID"); const wProduct = await s.Commerce.Webflow.Products.get(wProductId); @@ -423,7 +420,7 @@ export const app = new Elysia() }) .get("/:wOrderId", async ({ params: { wOrderId } }) => { const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId); - if (!wOrder) return status(404, { error: "Missing webflow order" }); + if (!wOrder) throw new NotFoundError("Missing webflow order"); const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`); @@ -431,10 +428,10 @@ export const app = new Elysia() }, { params: t.Object({ wOrderId: t.String() }) }) .post("/sync/:wOrderId", async ({ params: { wOrderId } }) => { const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId); - if (!wOrder) return status(404, { error: "Missing webflow order" }); + if (!wOrder) throw new NotFoundError("Missing webflow order"); const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`); - if (pOrder) return status(409, { error: "Cannot sync an already synced webflow order" }); + if (pOrder) throw new ConflictError("Cannot sync an already synced webflow order"); await s.Commerce.Apparel.Orders.Queue.enqueue({ type: "apparel_order_create", @@ -466,14 +463,14 @@ export const app = new Elysia() }) .get("/:id", async ({ params: { id } }) => { const event = await s.Events.get(id); - if (!event) return status(404, { error: "Event not found" }); + if (!event) throw new NotFoundError("Event not found"); return { ...event, status: EventsService.status(event) }; }, { params: t.Object({ id: BigIntIdSchema }) }) .post("/:id/retry", async ({ params: { id } }) => { const retried = await s.Events.retry(id); - if (!retried) return status(404, { error: "Event not found or not in a failed state" }); + if (!retried) throw new NotFoundError("Event not found or not in a failed state"); }, { params: t.Object({ id: BigIntIdSchema }) }) @@ -485,7 +482,7 @@ export const app = new Elysia() // TODO: for added security, could enforce bot or admin only access .get("/:id/stats", async ({ params: { id } }) => { const stats = await s.Accounts.stats(id); - if (!stats) return status(404, { error: "Account stats not found" }); + if (!stats) throw new NotFoundError("Account stats not found"); return stats; }, { params: t.Object({ id: AccountIdSchema }) @@ -508,7 +505,7 @@ export const app = new Elysia() .guard({ authAdmin: true }, (app) => app .get("/:id", async ({ params: { id } }) => { const account = await s.Accounts.get(id); - if (!account) return status(404, { error: "Account not found" }); + if (!account) throw new NotFoundError("Account not found"); return account; }, { params: t.Object({ id: AccountIdSchema }) @@ -517,7 +514,7 @@ export const app = new Elysia() .group("/me", { auth: true }, (app) => app .get("/stats", async ({ accountId }) => { const stats = await s.Accounts.stats(accountId); - if (!stats) return status(404, { error: "Account stats not found" }); + if (!stats) throw new NotFoundError("Account stats not found"); return stats; }) .post("/assessments", async ({ body: { player, activityPerformances }, accountId }) => { @@ -534,7 +531,7 @@ export const app = new Elysia() }) .delete("/assessments/:id", async ({ params: { id }, accountId }) => { const deleted = await s.Assessments.delete(id, accountId); - if (!deleted) return status(404, { error: "Assessment not found" }); + if (!deleted) throw new NotFoundError("Assessment not found"); }, { params: t.Object({ id: BigIntIdSchema }) }) @@ -553,12 +550,12 @@ export const app = new Elysia() }) .post("/verifications", async ({ body: { assessmentId }, accountId }) => { const assessment = await s.Assessments.get(assessmentId, accountId); - if (!assessment) return status(404, { error: "Assessment not found" }); + if (!assessment) throw new NotFoundError("Assessment not found"); // TODO: only allow a single active non-completed verification at a time const created = await s.Verifications.create(assessmentId); - if (!created) return status(409, { error: "This assessment already has a verification" }); + if (!created) throw new ConflictError("This assessment already has a verification"); return { ...created, uploadUrls: presignVerificationUploads(assessmentId) }; }, { @@ -568,10 +565,10 @@ export const app = new Elysia() }) .post("/verifications/:id/reopen", async ({ params: { id }, accountId }) => { const verification = await s.Verifications.get(id, accountId); - if (!verification) return status(404, { error: "Verification not found" }); + if (!verification) throw new NotFoundError("Verification not found"); const reopened = await s.Verifications.reopen(id); - if (!reopened) return status(409, { error: `Cannot reopen a ${verification.status} verification` }); + if (!reopened) throw new ConflictError(`Cannot reopen a ${verification.status} verification`); return { ...reopened, uploadUrls: presignVerificationUploads(verification.assessment_id) }; }, { @@ -579,11 +576,11 @@ export const app = new Elysia() }) .post("/verifications/:id/submit", async ({ params: { id }, accountId }) => { const verification = await s.Verifications.get(id, accountId); - if (!verification) return status(404, { error: "Verification not found" }); + if (!verification) throw new NotFoundError("Verification not found"); if (verification.status === "draft") { const { contents } = await r2.verificationMedia.list({ prefix: `${verification.assessment_id}/`, maxKeys: 1 }); - if (!contents?.length) return status(409, { error: "No media uploaded" }); + if (!contents?.length) throw new ConflictError("No media uploaded"); } const submitted = await s.Verifications.submit(id); @@ -593,9 +590,9 @@ export const app = new Elysia() } const current = await s.Verifications.get(id, accountId); - if (!current) return status(404, { error: "Verification not found" }); + if (!current) throw new NotFoundError("Verification not found"); if (current.status === "submitted") return { id: current.id, status: current.status }; - return status(409, { error: `Cannot submit a ${current.status} verification` }); + throw new ConflictError(`Cannot submit a ${current.status} verification`); }, { params: t.Object({ id: BigIntIdSchema }) }) @@ -615,7 +612,7 @@ export const app = new Elysia() }) .put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => { const updated = await s.Assessments.update(id, player, activityPerformances); - if (!updated) return status(404, { error: "Assessment not found" }); + if (!updated) throw new NotFoundError("Assessment not found"); return updated; }, { params: t.Object({ id: BigIntIdSchema }), @@ -645,7 +642,7 @@ export const app = new Elysia() // TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth .get("/:id", async ({ params: { id } }) => { const verification = await s.Verifications.get(id); - if (!verification) return status(404, { error: "Verification not found" }); + if (!verification) throw new NotFoundError("Verification not found"); const { contents = [] } = await r2.verificationMedia.list({ prefix: `${verification.assessment_id}/` }); const media = contents.map(({ key, size, lastModified }) => ({ @@ -665,8 +662,8 @@ export const app = new Elysia() if (updated) return updated; const verification = await s.Verifications.get(id); - if (!verification) return status(404, { error: "Verification not found" }); - return status(409, { error: `Cannot request action on a ${verification.status} verification` }); + if (!verification) throw new NotFoundError("Verification not found"); + throw new ConflictError(`Cannot request action on a ${verification.status} verification`); }, { params: t.Object({ id: BigIntIdSchema }), body: t.Object({ @@ -679,14 +676,14 @@ export const app = new Elysia() const portalSession = auth.value && await jwt.verify(auth.value); const completerId = completedBy ?? (portalSession ? portalSession.accountId?.toString() : undefined); const completer = completerId && await s.Accounts.get(completerId); - if (!completer || completer.role !== "admin") return status(403, { error: "Only a classmaster can complete a verification" }); + if (!completer || completer.role !== "admin") throw new ForbiddenError("Only a classmaster can complete a verification"); const updated = await s.Verifications.complete(id, completer.id, activityVerifications); if (updated) return updated; const verification = await s.Verifications.get(id); - if (!verification) return status(404, { error: "Verification not found" }); - return status(409, { error: `Cannot complete a ${verification.status} verification` }); + if (!verification) throw new NotFoundError("Verification not found"); + throw new ConflictError(`Cannot complete a ${verification.status} verification`); }, { params: t.Object({ id: BigIntIdSchema }), body: t.Object({ @@ -700,7 +697,7 @@ export const app = new Elysia() .post("/webhooks/printful", async ({ body, query }) => { // https://webflow.com/integrations/printful if (!s.Commerce.Printful.Util.verifySecret(query.secret)) - return status(400, { error: "Invalid secret" }); + throw new BadRequestError("Invalid secret"); const payload = body as Printful.Webhook.EventPayload; @@ -723,7 +720,7 @@ export const app = new Elysia() const pProduct = payload.data.sync_product; const wProductId = pProduct.external_id.split("-")[0]; log.info({ externalId: payload.data.sync_product.external_id, wProductId }, "printful webhook: product deleted"); - if (!wProductId) return status(404, { error: "Missing webflow product ID" }); + if (!wProductId) throw new NotFoundError("Missing webflow product ID"); await s.Commerce.Apparel.Syncs.Queue.enqueue({ type: "apparel_sync_delete", @@ -755,7 +752,7 @@ export const app = new Elysia() }, { query: t.Object({ secret: t.String() }) }) .post("/webhooks/webflow", async ({ request, body }) => { if (!s.Commerce.Webflow.Util.verifySecret(request, body)) - return status(400, { error: "Invalid signature" }); + throw new BadRequestError("Invalid signature"); const payload = body as Webflow.Webhook.EventPayload; diff --git a/apps/api/src/services/calculator.ts b/apps/api/src/services/calculator.ts index 860ed40..12ad1e7 100644 --- a/apps/api/src/services/calculator.ts +++ b/apps/api/src/services/calculator.ts @@ -6,6 +6,13 @@ import { Value } from "@sinclair/typebox/value"; export class CalculatorUnavailableError extends Error { status: number = 503 + + toResponse() { + return new Response(JSON.stringify({ error: this.message }), { + status: this.status, + headers: { 'content-type': 'application/json' } + }) + } } export class CalculatorService { diff --git a/apps/api/src/util.ts b/apps/api/src/util.ts index 9be31ca..bdf3701 100644 --- a/apps/api/src/util.ts +++ b/apps/api/src/util.ts @@ -42,6 +42,36 @@ export const WORKER_COUNT = Math.min(os.availableParallelism(), +env.MAX_WORKER_ export const DEFAULT_NAME = "Default"; export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy"); +export class HttpError extends Error { + constructor(public status: number, message: string) { + super(message); + } + + toResponse() { + return Response.json({ error: this.message }, { status: this.status }); + } +} + +export class BadRequestError extends HttpError { + constructor(message: string) { super(400, message); } +} + +export class UnauthorizedError extends HttpError { + constructor(message: string) { super(401, message); } +} + +export class ForbiddenError extends HttpError { + constructor(message: string) { super(403, message); } +} + +export class ConflictError extends HttpError { + constructor(message: string) { super(409, message); } +} + +export class BadGatewayError extends HttpError { + constructor(message: string) { super(502, message); } +} + export const BigIntIdSchema = t.String({ pattern: "^\\d+$" }); export const AccountIdSchema = t.String({ pattern: "^(@.+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$" }); diff --git a/packages/commerce/src/printful.ts b/packages/commerce/src/printful.ts index 15a8eca..927ac2c 100644 --- a/packages/commerce/src/printful.ts +++ b/packages/commerce/src/printful.ts @@ -25,7 +25,13 @@ export class PrintfulError extends Error { public status: number = 502 ) { super(message); - this.name = "PrintfulError"; + } + + toResponse() { + return new Response(JSON.stringify({ error: this.message }), { + status: this.status, + headers: { 'content-type': 'application/json' } + }) } } diff --git a/packages/commerce/src/webflow.ts b/packages/commerce/src/webflow.ts index 5bc6712..15f940a 100644 --- a/packages/commerce/src/webflow.ts +++ b/packages/commerce/src/webflow.ts @@ -32,7 +32,13 @@ export class WebflowError extends Error { public status: number = 502 ) { super(message); - this.name = "WebflowError"; + } + + toResponse() { + return new Response(JSON.stringify({ error: this.message }), { + status: this.status, + headers: { 'content-type': 'application/json' } + }) } }