From ab0cb581965615ceee87ef47e3a4c4045f685201 Mon Sep 17 00:00:00 2001 From: Dominic Ferrando Date: Sun, 4 Oct 2026 01:18:07 -0400 Subject: [PATCH] Bugfixing --- .gitignore | 3 -- apps/api/.gitignore | 2 ++ apps/api/src/controllers/assessments.ts | 10 +++--- apps/api/src/controllers/auth.ts | 42 ++++++++++++++----------- apps/api/src/controllers/standards.ts | 23 ++++++++++---- apps/api/src/services/accounts.ts | 2 +- apps/api/src/services/calculator.ts | 3 ++ apps/api/src/services/standards.ts | 32 ++++++++++--------- 8 files changed, 70 insertions(+), 47 deletions(-) create mode 100644 apps/api/.gitignore diff --git a/.gitignore b/.gitignore index 1bf087f..187db5a 100644 --- a/.gitignore +++ b/.gitignore @@ -38,6 +38,3 @@ report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json # Agents .claude/settings.local.json - -# Local test media for seed scripts -apps/api/src/scripts/fixtures diff --git a/apps/api/.gitignore b/apps/api/.gitignore new file mode 100644 index 0000000..a7e9809 --- /dev/null +++ b/apps/api/.gitignore @@ -0,0 +1,2 @@ +# Local test media for seed scripts +src/scripts/test-verification-media diff --git a/apps/api/src/controllers/assessments.ts b/apps/api/src/controllers/assessments.ts index 09e831e..361c045 100644 --- a/apps/api/src/controllers/assessments.ts +++ b/apps/api/src/controllers/assessments.ts @@ -2,18 +2,20 @@ import Elysia, { NotFoundError, t } from "elysia"; import { ActivityPerformanceSchema, PlayerSchema } from "@blade-and-brawn/domain"; import { authPlugin } from "../plugins/auth"; import { s } from "../services"; -import { BigIntIdSchema } from "../util/models"; +import { AccountIdSchema, BigIntIdSchema } from "../util/models"; const AssessmentsController = new Elysia({ prefix: "/assessments" }) .use(authPlugin) .guard({ authAdmin: true }) - .post("/", async ({ body: { player, activityPerformances, id } }) => { - return await s.Assessments.create(player, activityPerformances, id); + .post("/", async ({ body: { player, activityPerformances, accountId } }) => { + const account = await s.Accounts.get(accountId); + if (!account) throw new NotFoundError("Account not found"); + return await s.Assessments.create(player, activityPerformances, account.id); }, { body: t.Object({ player: PlayerSchema, activityPerformances: t.Array(ActivityPerformanceSchema), - id: t.Optional(t.String()), + accountId: AccountIdSchema, }) }) .put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => { diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.ts index d617102..194b159 100644 --- a/apps/api/src/controllers/auth.ts +++ b/apps/api/src/controllers/auth.ts @@ -22,7 +22,7 @@ const AuthController = new Elysia({ prefix: "/auth" }) .post("/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) throw new UnauthorizedError("Invalid credentials"); + if (!account?.password_hash || !password_match) throw new UnauthorizedError("Invalid credentials"); auth.set({ value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }), @@ -62,9 +62,11 @@ const AuthController = new Elysia({ prefix: "/auth" }) .get("/callback", async ({ query, cookie: { authDiscord, auth }, jwt }) => { if (query.error) throw new BadRequestError(query.error_description ? `${query.error}: ${query.error_description}` : query.error); + // Validate input 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"); + // Retrieve access token from discord const tokenRes = await fetch("https://discord.com/api/oauth2/token", { method: "POST", headers: { @@ -80,36 +82,38 @@ const AuthController = new Elysia({ prefix: "/auth" }) }); if (!tokenRes.ok) { const errorBody = await tokenRes.json().catch(() => null); - throw new BadGatewayError(errorBody ?? "Discord token exchange failed"); + throw new BadGatewayError(errorBody ? JSON.stringify(errorBody) : "Discord token exchange failed"); } - const tokenResPayload = await tokenRes.json(); Value.Assert(t.Object({ access_token: t.String() }), tokenResPayload); + // Retrieve user's discord identity const identityRes = await fetch("https://discord.com/api/users/@me", { headers: { "Authorization": `Bearer ${tokenResPayload.access_token}` } }); if (!identityRes.ok) { const errorBody = await identityRes.json().catch(() => null); - throw new BadGatewayError(errorBody ?? "Failed to fetch Discord identity"); + throw new BadGatewayError(errorBody ? JSON.stringify(errorBody) : "Failed to fetch Discord identity"); + } + const discordIdentity = await identityRes.json(); + Value.Assert(t.Object({ id: t.String(), email: t.Optional(t.Nullable(t.String())), username: t.String(), verified: t.Boolean() }), discordIdentity); + + // Get account or create if it dosent exist + let account = await s.Accounts.get(`@${discordIdentity.id}`); + if (!account) { + // only accept VERIFIED emails not already used by another account + const email = discordIdentity.verified && discordIdentity.email ? discordIdentity.email : undefined; + const emailTaken = email !== undefined && !!(await s.Accounts.getByEmail(email)); + account = await s.Accounts.create( + discordIdentity.id, + emailTaken ? undefined : email, + discordIdentity.username + ); } - const identityResPayload = await identityRes.json(); - Value.Assert(t.Object({ id: t.String(), email: t.Optional(t.String()), username: t.String() }), identityResPayload); - - // Create the account - let accountId = (await s.Accounts.get(`@${identityResPayload.id}`))?.id; - if (!accountId) { - accountId = (await s.Accounts.create( - identityResPayload.id, - identityResPayload.email, - identityResPayload.username - )).id; - } - - // Authenticate + // Setup and sign auth cookie auth.set({ - value: await jwt.sign({ role: "user" satisfies AccountRole, sessionId: randomUUIDv7(), accountId, exp: JWT_EXP }), + value: await jwt.sign({ role: account.role, sessionId: randomUUIDv7(), accountId: account.id, exp: JWT_EXP }), path: "/", maxAge: JWT_EXP_SECONDS, sameSite: env.NODE_ENV === "production" ? "lax" : "none", diff --git a/apps/api/src/controllers/standards.ts b/apps/api/src/controllers/standards.ts index 94707bb..3e10deb 100644 --- a/apps/api/src/controllers/standards.ts +++ b/apps/api/src/controllers/standards.ts @@ -1,8 +1,9 @@ -import Elysia, { t } from "elysia"; +import Elysia, { NotFoundError, t } from "elysia"; import { StandardsParamsSchema } from "@blade-and-brawn/calculator"; import { authPlugin } from "../plugins/auth"; import { s } from "../services"; import { BigIntIdSchema } from "../util/models"; +import { ConflictError } from "../util/error"; const StandardsController = new Elysia({ prefix: "/standards" }) .use(authPlugin) @@ -17,18 +18,25 @@ const StandardsController = new Elysia({ prefix: "/standards" }) }) .group("/:id", (app) => app .get("/", async ({ params: { id } }) => { - return await s.Standards.Configs.get(id); + const config = await s.Standards.Configs.get(id); + if (!config) throw new NotFoundError("Standards config not found"); + return config; }, { params: t.Object({ id: BigIntIdSchema }) }) .put("/", async ({ params: { id }, body: { name, datasetId, params: parameters } }) => { - await s.Standards.Configs.update(id, name, datasetId, parameters); + const activeConfig = await s.Calculator.Standards.Config.get(); + if (activeConfig.id === id) throw new ConflictError("Cannot edit the active standards config"); + const updated = await s.Standards.Configs.update(id, name, datasetId, parameters); + if (!updated) throw new NotFoundError("Standards config not found"); }, { params: t.Object({ id: BigIntIdSchema }), body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema }) }) .delete("/", async ({ params: { id } }) => { - await s.Standards.Configs.delete(id); + if (await s.Standards.Configs.count() <= 1) throw new ConflictError("Cannot delete the last remaining standards config"); + const deleted = await s.Standards.Configs.delete(id); + if (!deleted) throw new NotFoundError("Standards config not found"); }, { params: t.Object({ id: BigIntIdSchema }) }) ) ) @@ -38,12 +46,15 @@ const StandardsController = new Elysia({ prefix: "/standards" }) }) .group("/:id", (app) => app .get("/", async ({ params: { id } }) => { - return await s.Standards.Datasets.get(id); + const dataset = await s.Standards.Datasets.get(id); + if (!dataset) throw new NotFoundError("Standards dataset not found"); + return dataset; }, { params: t.Object({ id: BigIntIdSchema }) }) .patch("/", async ({ params: { id }, body: { name } }) => { - await s.Standards.Datasets.update(id, name); + const updated = await s.Standards.Datasets.update(id, name); + if (!updated) throw new NotFoundError("Standards dataset not found"); }, { params: t.Object({ id: BigIntIdSchema }), body: t.Object({ name: t.String() }) diff --git a/apps/api/src/services/accounts.ts b/apps/api/src/services/accounts.ts index ea17a65..6cd069a 100644 --- a/apps/api/src/services/accounts.ts +++ b/apps/api/src/services/accounts.ts @@ -22,7 +22,7 @@ export class AccountsService { name: name ?? "", email: email ?? null }) - .returning("id") + .returning(["id", "discord_id", "name", "email", "gender", "role"]) .executeTakeFirstOrThrow(); } diff --git a/apps/api/src/services/calculator.ts b/apps/api/src/services/calculator.ts index 60bb3bf..f49a642 100644 --- a/apps/api/src/services/calculator.ts +++ b/apps/api/src/services/calculator.ts @@ -64,6 +64,9 @@ class CalculatorStandardsConfigService { config: null as StandardsConfig | null }, isStale: async () => { + // Becomes stale only when standards are switched + // We currently enforce read-only view of selected calculator's standards config + // So only way to update calculator is to make new standards config, edit, then switch const { standards_config_id: selectedConfigId } = await db.selectFrom("calculators") .select("standards_config_id") .where("name", "=", this.name) diff --git a/apps/api/src/services/standards.ts b/apps/api/src/services/standards.ts index d68b006..2cba0ff 100644 --- a/apps/api/src/services/standards.ts +++ b/apps/api/src/services/standards.ts @@ -31,7 +31,7 @@ class StandardsConfigService { .execute(); } - async get(id: string): Promise { + async get(id: string): Promise<(StandardsConfig & { id: string, name: string, datasetId: string }) | undefined> { const result = await db.selectFrom("standards_configs") .innerJoin("standards_datasets", "standards_datasets.id", "standards_configs.dataset_id") .select([ @@ -42,7 +42,8 @@ class StandardsConfigService { "standards_datasets.data as data", ]) .where("standards_configs.id", "=", id) - .executeTakeFirstOrThrow({ errorConstructor: () => new Error(`No config with id "${id}"`) }); + .executeTakeFirst(); + if (!result) return; Value.Assert(StandardsParamsSchema, result.params); Value.Assert(StandardsDataSchema, result.data); return { @@ -54,24 +55,26 @@ class StandardsConfigService { }; } - async update(id: string, name: string, datasetId: string, params: StandardsParams) { + async update(id: string, name: string, datasetId: string, params: StandardsParams): Promise { const result = await db.updateTable("standards_configs") .set({ name, params, dataset_id: datasetId }) .where("id", "=", id) - .execute(); - if (result[0]?.numUpdatedRows === 0n) throw new Error(`No config with id "${id}"`); + .executeTakeFirst(); + return result.numUpdatedRows > 0n; } - async delete(id: string) { + async count(): Promise { const { count } = await db.selectFrom("standards_configs") .select(db.fn.countAll().as("count")) .executeTakeFirstOrThrow(); - if (Number(count) <= 1) throw new Error("Cannot delete the last remaining standards configuration"); + return Number(count); + } + async delete(id: string): Promise { const result = await db.deleteFrom("standards_configs") .where("id", "=", id) - .execute(); - if (result[0]?.numDeletedRows === 0n) throw new Error(`No config with id "${id}"`); + .executeTakeFirst(); + return result.numDeletedRows > 0n; } } @@ -83,20 +86,21 @@ class StandardsDatasetService { .execute(); } - async get(id: string): Promise<{ id: string, name: string, data: StandardsData }> { + async get(id: string): Promise<{ id: string, name: string, data: StandardsData } | undefined> { const result = await db.selectFrom("standards_datasets") .select(["id", "name", "data"]) .where("id", "=", id) - .executeTakeFirstOrThrow({ errorConstructor: () => new Error(`No dataset with id "${id}"`) }); + .executeTakeFirst(); + if (!result) return; Value.Assert(StandardsDataSchema, result.data); return { id: result.id, name: result.name, data: result.data }; } - async update(id: string, name: string) { + async update(id: string, name: string): Promise { const result = await db.updateTable("standards_datasets") .set({ name }) .where("id", "=", id) - .execute(); - if (result[0]?.numUpdatedRows === 0n) throw new Error(`No dataset with id "${id}"`); + .executeTakeFirst(); + return result.numUpdatedRows > 0n; } }