Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdd8596787 | ||
|
|
6e9ce94d46 | ||
|
|
daaf779562 | ||
|
|
09ac3bfd93 | ||
|
|
3ef0c9e88f | ||
|
|
0576421368 | ||
|
|
0501e63dc7 | ||
|
|
9bf60b7c8b |
@@ -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
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Local test media for seed scripts
|
||||
src/scripts/test-verification-media
|
||||
@@ -0,0 +1,144 @@
|
||||
import Elysia, { NotFoundError, t } from "elysia";
|
||||
import { ActivityPerformanceSchema, PlayerSchema } from "@blade-and-brawn/domain";
|
||||
import { authPlugin } from "../plugins/auth";
|
||||
import { s } from "../services";
|
||||
import { VerificationsService, VerificationStatusSchema } from "../services/verifications";
|
||||
import { ConflictError } from "../util/error";
|
||||
import { AccountIdSchema, BigIntIdSchema } from "../util/models";
|
||||
import { r2 } from "../util/r2";
|
||||
|
||||
const AccountsController = new Elysia({ prefix: "/accounts" })
|
||||
.use(authPlugin)
|
||||
.group("/:id", (app) => app
|
||||
.get("/", async ({ params: { id } }) => {
|
||||
const account = await s.Accounts.get(id);
|
||||
if (!account) throw new NotFoundError("Account not found");
|
||||
return account;
|
||||
}, {
|
||||
authAdmin: true,
|
||||
params: t.Object({ id: AccountIdSchema })
|
||||
})
|
||||
// TODO: for added security, could enforce bot or admin only access
|
||||
.get("/stats", async ({ params: { id } }) => {
|
||||
const stats = await s.Accounts.stats(id);
|
||||
if (!stats) throw new NotFoundError("Account stats not found");
|
||||
return stats;
|
||||
}, {
|
||||
params: t.Object({ id: AccountIdSchema })
|
||||
})
|
||||
// TODO: for added security, MUST enforce bot or admin only access
|
||||
.get("/verifications", async ({ query, params: { id } }) => {
|
||||
return await s.Verifications.list({
|
||||
filter: { status: query.status, accountId: id },
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
});
|
||||
}, {
|
||||
params: t.Object({ id: AccountIdSchema }),
|
||||
query: t.Object({
|
||||
status: t.Optional(VerificationStatusSchema),
|
||||
limit: t.Optional(t.Numeric()),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
)
|
||||
.group("/me", { auth: true }, (app) => app
|
||||
.get("/stats", async ({ accountId }) => {
|
||||
const stats = await s.Accounts.stats(accountId);
|
||||
if (!stats) throw new NotFoundError("Account stats not found");
|
||||
return stats;
|
||||
})
|
||||
.group("/assessments", (app) => app
|
||||
.post("/", async ({ body: { player, activityPerformances }, accountId }) => {
|
||||
return await s.Assessments.create(player, activityPerformances, accountId);
|
||||
}, {
|
||||
body: t.Object({
|
||||
player: PlayerSchema,
|
||||
activityPerformances: t.Array(ActivityPerformanceSchema)
|
||||
})
|
||||
})
|
||||
// TODO: handle @ formatted accountIds
|
||||
.get("/", async ({ accountId }) => {
|
||||
return await s.Assessments.list({ filter: { accountId } });
|
||||
})
|
||||
.delete("/:id", async ({ params: { id }, accountId }) => {
|
||||
const deleted = await s.Assessments.delete(id, accountId);
|
||||
if (!deleted) throw new NotFoundError("Assessment not found");
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
)
|
||||
.group("/verifications", (app) => app
|
||||
.get("/", async ({ query, accountId }) => {
|
||||
return await s.Verifications.list({
|
||||
filter: { status: query.status, accountId },
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
});
|
||||
}, {
|
||||
query: t.Object({
|
||||
status: t.Optional(VerificationStatusSchema),
|
||||
limit: t.Optional(t.Numeric()),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.post("/", async ({ body: { assessmentId }, accountId }) => {
|
||||
const assessment = await s.Assessments.get(assessmentId, accountId);
|
||||
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) throw new ConflictError("This assessment already has a verification");
|
||||
|
||||
return {
|
||||
...created,
|
||||
uploadUrls: VerificationsService.presignMediaUploads(r2.verificationMedia, assessmentId)
|
||||
};
|
||||
}, {
|
||||
body: t.Object({
|
||||
assessmentId: BigIntIdSchema
|
||||
})
|
||||
})
|
||||
.group("/:id", (app) => app
|
||||
.post("/reopen", async ({ params: { id }, accountId }) => {
|
||||
const verification = await s.Verifications.get(id, accountId);
|
||||
if (!verification) throw new NotFoundError("Verification not found");
|
||||
|
||||
const reopened = await s.Verifications.reopen(id);
|
||||
if (!reopened) throw new ConflictError(`Cannot reopen a ${verification.status} verification`);
|
||||
|
||||
return {
|
||||
...reopened,
|
||||
uploadUrls: VerificationsService.presignMediaUploads(r2.verificationMedia, verification.assessment_id)
|
||||
};
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
.post("/submit", async ({ params: { id }, accountId }) => {
|
||||
const verification = await s.Verifications.get(id, accountId);
|
||||
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) throw new ConflictError("No media uploaded");
|
||||
}
|
||||
|
||||
const submitted = await s.Verifications.submit(id);
|
||||
if (submitted) {
|
||||
// TODO: trigger discord webhook here
|
||||
return submitted;
|
||||
}
|
||||
|
||||
const current = await s.Verifications.get(id, accountId);
|
||||
if (!current) throw new NotFoundError("Verification not found");
|
||||
if (current.status === "submitted") return { id: current.id, status: current.status };
|
||||
throw new ConflictError(`Cannot submit a ${current.status} verification`);
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
export default AccountsController;
|
||||
@@ -0,0 +1,33 @@
|
||||
import Elysia, { NotFoundError, t } from "elysia";
|
||||
import { ActivityPerformanceSchema, PlayerSchema } from "@blade-and-brawn/domain";
|
||||
import { authPlugin } from "../plugins/auth";
|
||||
import { s } from "../services";
|
||||
import { AccountIdSchema, BigIntIdSchema } from "../util/models";
|
||||
|
||||
const AssessmentsController = new Elysia({ prefix: "/assessments" })
|
||||
.use(authPlugin)
|
||||
.guard({ authAdmin: true })
|
||||
.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),
|
||||
accountId: AccountIdSchema,
|
||||
})
|
||||
})
|
||||
.put("/:id", async ({ body: { player, activityPerformances }, params: { id } }) => {
|
||||
const updated = await s.Assessments.update(id, player, activityPerformances);
|
||||
if (!updated) throw new NotFoundError("Assessment not found");
|
||||
return updated;
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema }),
|
||||
body: t.Object({
|
||||
player: PlayerSchema,
|
||||
activityPerformances: t.Array(ActivityPerformanceSchema),
|
||||
})
|
||||
});
|
||||
|
||||
export default AssessmentsController;
|
||||
@@ -0,0 +1,138 @@
|
||||
import Elysia, { redirect, t } from "elysia";
|
||||
import { Value } from "@sinclair/typebox/value";
|
||||
import { randomUUIDv7 } from "bun";
|
||||
import { authPlugin } from "../plugins/auth";
|
||||
import { s } from "../services";
|
||||
import type { AccountRole } from "../services/accounts";
|
||||
import { DUMMY_PASSWORD_HASH } from "../util/crypto";
|
||||
import { env } from "../util/env";
|
||||
import { BadGatewayError, BadRequestError, UnauthorizedError } from "../util/error";
|
||||
|
||||
const JWT_EXP = "1d";
|
||||
const JWT_EXP_SECONDS = 60 * 60 * 24; // keep in sync with JWT_EXP; used for cookie maxAge
|
||||
|
||||
const AuthController = new Elysia({ prefix: "/auth" })
|
||||
.use(authPlugin)
|
||||
.guard({
|
||||
cookie: t.Cookie({
|
||||
auth: t.Optional(t.String()),
|
||||
authDiscord: t.Optional(t.String())
|
||||
})
|
||||
})
|
||||
.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_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 }),
|
||||
path: "/",
|
||||
maxAge: JWT_EXP_SECONDS,
|
||||
sameSite: env.NODE_ENV === "production" ? "lax" : "none",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
domain: env.NODE_ENV === "production" ?
|
||||
".bladeandbrawn.com" :
|
||||
undefined
|
||||
});
|
||||
}, { body: t.Object({ email: t.String(), password: t.String() }) })
|
||||
|
||||
.group("/discord", (app) => app
|
||||
.get("/login", async ({ cookie: { authDiscord } }) => {
|
||||
const state = crypto.randomUUID();
|
||||
|
||||
authDiscord.set({
|
||||
value: state,
|
||||
path: "/",
|
||||
maxAge: 60 * 10, // 10 min
|
||||
sameSite: "lax",
|
||||
httpOnly: true,
|
||||
secure: env.NODE_ENV === "production"
|
||||
});
|
||||
|
||||
const url = new URL("https://discord.com/api/oauth2/authorize");
|
||||
url.searchParams.set("client_id", env.BOT_CLIENT_ID);
|
||||
url.searchParams.set("redirect_uri", env.BOT_REDIRECT_URL);
|
||||
url.searchParams.set("response_type", "code");
|
||||
url.searchParams.set("scope", "identify email");
|
||||
url.searchParams.set("state", state);
|
||||
|
||||
return redirect(url.toString(), 302);
|
||||
})
|
||||
.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: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
client_id: env.BOT_CLIENT_ID,
|
||||
client_secret: env.BOT_CLIENT_SECRET,
|
||||
grant_type: "authorization_code",
|
||||
code: query.code ?? "",
|
||||
redirect_uri: env.BOT_REDIRECT_URL
|
||||
}).toString()
|
||||
});
|
||||
if (!tokenRes.ok) {
|
||||
const errorBody = await tokenRes.json().catch(() => null);
|
||||
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 ? 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
|
||||
);
|
||||
}
|
||||
|
||||
// Setup and sign auth cookie
|
||||
auth.set({
|
||||
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",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
domain: env.NODE_ENV === "production" ?
|
||||
".bladeandbrawn.com" :
|
||||
undefined
|
||||
});
|
||||
|
||||
return redirect(env.BOT_LOGIN_REDIRECT_URL, 302);
|
||||
}, {
|
||||
query: t.Object({
|
||||
code: t.Optional(t.String()),
|
||||
state: t.Optional(t.String()),
|
||||
error: t.Optional(t.String()),
|
||||
error_description: t.Optional(t.String()),
|
||||
})
|
||||
})
|
||||
);
|
||||
|
||||
export default AuthController;
|
||||
@@ -0,0 +1,29 @@
|
||||
import Elysia, { t } from "elysia";
|
||||
import { ActivityPerformanceSchema, PlayerSchema } from "@blade-and-brawn/domain";
|
||||
import { BigIntIdSchema } from "../util/models";
|
||||
import { authPlugin } from "../plugins/auth";
|
||||
import { s } from "../services";
|
||||
|
||||
const CalculatorController = new Elysia({ prefix: "/calculator" })
|
||||
.use(authPlugin)
|
||||
// Non-authenticated
|
||||
.post("/calculate", async ({ body }) => {
|
||||
return { levels: await s.Calculator.calculate(body.player, body.activityPerformances) };
|
||||
}, {
|
||||
body: t.Object({
|
||||
player: PlayerSchema,
|
||||
activityPerformances: t.Array(ActivityPerformanceSchema)
|
||||
}),
|
||||
})
|
||||
.group("/standards/config", { authAdmin: true }, (app) => app
|
||||
.get("/", async () => {
|
||||
return await s.Calculator.Standards.Config.get();
|
||||
})
|
||||
.post("/switch", async ({ body: { standardsConfigId } }) => {
|
||||
await s.Calculator.Standards.Config.switch(standardsConfigId);
|
||||
}, {
|
||||
body: t.Object({ standardsConfigId: BigIntIdSchema })
|
||||
})
|
||||
);
|
||||
|
||||
export default CalculatorController;
|
||||
@@ -0,0 +1,110 @@
|
||||
import Elysia, { NotFoundError, t } from "elysia";
|
||||
import { authPlugin } from "../plugins/auth";
|
||||
import { s } from "../services";
|
||||
import { WOrderStatusSchema } from "../services/commerce";
|
||||
import { ConflictError } from "../util/error";
|
||||
|
||||
const CommerceController = new Elysia({ prefix: "/commerce" })
|
||||
.use(authPlugin)
|
||||
.group("/products", { authAdmin: true }, (app) => app
|
||||
.get("/", async ({ query }) => {
|
||||
const [pProducts, wProducts] = await Promise.all([
|
||||
s.Commerce.Printful.Products.list({
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
}),
|
||||
s.Commerce.Webflow.Products.list({ forceAll: true }),
|
||||
]);
|
||||
const wProductIds = new Set(wProducts.map((wProduct) => wProduct.product.id));
|
||||
return pProducts.map((pProduct) => {
|
||||
const wProductId = pProduct.external_id.split("-")[0];
|
||||
return { pProduct, isSynced: wProductId ? wProductIds.has(wProductId) : false };
|
||||
});
|
||||
}, {
|
||||
query: t.Object({
|
||||
limit: t.Optional(t.Numeric({ maximum: 100 })),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.group("/sync", (app) => app
|
||||
// Sync status
|
||||
.get("/", async ({ sessionId }) => {
|
||||
const latestSyncState = await s.Commerce.Apparel.Syncs.getLatestSyncState(sessionId);
|
||||
if (!latestSyncState) throw new NotFoundError("No product sync found for the provided session");
|
||||
return latestSyncState;
|
||||
})
|
||||
// Run sync
|
||||
.post("/:pProductId?", async ({ params: { pProductId }, sessionId }) => {
|
||||
await s.Commerce.Apparel.Syncs.Queue.enqueue({
|
||||
type: "apparel_sync_update",
|
||||
source: "portal",
|
||||
payload: {
|
||||
session: { id: sessionId, name: "Portal" },
|
||||
filter: {
|
||||
pProductIds: pProductId ? [pProductId] : undefined
|
||||
}
|
||||
}
|
||||
});
|
||||
}, { params: t.Object({ pProductId: t.Optional(t.Numeric()) }) }),
|
||||
)
|
||||
.get("/:pProductId", async ({ params: { pProductId } }) => {
|
||||
const pProduct = await s.Commerce.Printful.Products.get(pProductId);
|
||||
if (!pProduct) throw new NotFoundError("Missing printful product");
|
||||
|
||||
const wProductId = pProduct.sync_product.external_id.split("-")[0];
|
||||
if (!wProductId) throw new NotFoundError("Missing webflow product ID");
|
||||
|
||||
const wProduct = await s.Commerce.Webflow.Products.get(wProductId);
|
||||
|
||||
return { pProduct, wProduct };
|
||||
}, {
|
||||
params: t.Object({ pProductId: t.Numeric() })
|
||||
})
|
||||
)
|
||||
.group("/orders", { authAdmin: true }, (app) => app
|
||||
.get("/", async ({ query }) => {
|
||||
const [wOrders, pOrders] = await Promise.all([
|
||||
s.Commerce.Webflow.Orders.list({
|
||||
status: query.status,
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
}),
|
||||
s.Commerce.Printful.Orders.list({ forceAll: true }),
|
||||
]);
|
||||
const pOrderExternalIds = new Set(pOrders.map((pOrder) => pOrder.external_id));
|
||||
return wOrders.map((wOrder) => ({
|
||||
wOrder,
|
||||
isSynced: pOrderExternalIds.has(wOrder.orderId),
|
||||
}));
|
||||
}, {
|
||||
query: t.Object({
|
||||
status: t.Optional(WOrderStatusSchema),
|
||||
limit: t.Optional(t.Numeric({ maximum: 100 })),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.get("/:wOrderId", async ({ params: { wOrderId } }) => {
|
||||
const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId);
|
||||
if (!wOrder) throw new NotFoundError("Missing webflow order");
|
||||
|
||||
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
|
||||
|
||||
return { wOrder, pOrder };
|
||||
}, { params: t.Object({ wOrderId: t.String() }) })
|
||||
.post("/sync/:wOrderId", async ({ params: { wOrderId } }) => {
|
||||
const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId);
|
||||
if (!wOrder) throw new NotFoundError("Missing webflow order");
|
||||
|
||||
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
|
||||
if (pOrder) throw new ConflictError("Cannot sync an already synced webflow order");
|
||||
|
||||
await s.Commerce.Apparel.Orders.Queue.enqueue({
|
||||
type: "apparel_order_create",
|
||||
source: "portal",
|
||||
payload: { wOrder }
|
||||
});
|
||||
|
||||
}, { params: t.Object({ wOrderId: t.String() }) })
|
||||
);
|
||||
|
||||
export default CommerceController;
|
||||
@@ -0,0 +1,43 @@
|
||||
import Elysia, { NotFoundError, t } from "elysia";
|
||||
import { authPlugin } from "../plugins/auth";
|
||||
import { queues, s } from "../services";
|
||||
import { EventsService, EventStatusSchema } from "../services/events";
|
||||
import { BigIntIdSchema } from "../util/models";
|
||||
|
||||
const EventsController = new Elysia({ prefix: "/events" })
|
||||
.use(authPlugin)
|
||||
.guard({ authAdmin: true })
|
||||
.get("/", async ({ query }) => {
|
||||
const events = await s.Events.list({
|
||||
filter: { status: query.status, type: query.type, group: query.group },
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
});
|
||||
return events.map((event) => ({ ...event, status: EventsService.status(event) }));
|
||||
}, {
|
||||
query: t.Object({
|
||||
status: t.Optional(EventStatusSchema),
|
||||
type: t.Optional(t.String()),
|
||||
group: t.Optional(t.String()),
|
||||
limit: t.Optional(t.Numeric()),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.get("/groups", async ({ }) => queues.map((q) => q.group))
|
||||
.group("/:id", (app) => app
|
||||
.get("/", async ({ params: { id } }) => {
|
||||
const event = await s.Events.get(id);
|
||||
if (!event) throw new NotFoundError("Event not found");
|
||||
return { ...event, status: EventsService.status(event) };
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
.post("/retry", async ({ params: { id } }) => {
|
||||
const retried = await s.Events.retry(id);
|
||||
if (!retried) throw new NotFoundError("Event not found or not in a failed state");
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
);
|
||||
|
||||
export default EventsController;
|
||||
@@ -0,0 +1,67 @@
|
||||
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)
|
||||
.group("/configs", { authAdmin: true }, (app) => app
|
||||
.post("/", async ({ body: { name, datasetId, params } }) => {
|
||||
return await s.Standards.Configs.create(name, datasetId, params);
|
||||
}, {
|
||||
body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema })
|
||||
})
|
||||
.get("/", async () => {
|
||||
return await s.Standards.Configs.list();
|
||||
})
|
||||
.group("/:id", (app) => app
|
||||
.get("/", async ({ params: { 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 } }) => {
|
||||
// Active config is not allowed to be edited
|
||||
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 } }) => {
|
||||
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 }) })
|
||||
)
|
||||
)
|
||||
.group("/datasets", { authAdmin: true }, (app) => app
|
||||
.get("/", async () => {
|
||||
return await s.Standards.Datasets.list();
|
||||
})
|
||||
.group("/:id", (app) => app
|
||||
.get("/", async ({ params: { 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 } }) => {
|
||||
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() })
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
export default StandardsController;
|
||||
@@ -0,0 +1,82 @@
|
||||
import Elysia, { NotFoundError, t } from "elysia";
|
||||
import { ActivityVerificationsSchema } from "@blade-and-brawn/domain";
|
||||
import { authPlugin } from "../plugins/auth";
|
||||
import { s } from "../services";
|
||||
import { VerificationStatusSchema } from "../services/verifications";
|
||||
import { ConflictError, ForbiddenError } from "../util/error";
|
||||
import { AccountIdSchema, BigIntIdSchema } from "../util/models";
|
||||
import { r2 } from "../util/r2";
|
||||
|
||||
const VerificationsController = new Elysia({ prefix: "/verifications" })
|
||||
.use(authPlugin)
|
||||
.get("/", async ({ query }) => {
|
||||
return await s.Verifications.list({
|
||||
filter: { status: query.status },
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
});
|
||||
}, {
|
||||
authAdmin: true,
|
||||
query: t.Object({
|
||||
status: t.Optional(VerificationStatusSchema),
|
||||
limit: t.Optional(t.Numeric()),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.group("/:id", (app) => app
|
||||
// TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth
|
||||
.get("/", async ({ params: { id } }) => {
|
||||
const verification = await s.Verifications.get(id);
|
||||
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 }) => ({
|
||||
key,
|
||||
size,
|
||||
lastModified,
|
||||
url: r2.verificationMedia.presign(key, { expiresIn: 60 * 60 }),
|
||||
}));
|
||||
|
||||
return { ...verification, media };
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
// TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth
|
||||
.post("/request-action", async ({ params: { id }, body: { reviewerNotes, activityVerifications } }) => {
|
||||
const updated = await s.Verifications.requestAction(id, reviewerNotes ?? null, activityVerifications);
|
||||
if (updated) return updated;
|
||||
|
||||
const verification = await s.Verifications.get(id);
|
||||
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({
|
||||
reviewerNotes: t.Optional(t.String()),
|
||||
activityVerifications: ActivityVerificationsSchema,
|
||||
})
|
||||
})
|
||||
// TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth and drop completedBy from the body
|
||||
.post("/complete", async ({ params: { id }, body: { activityVerifications, completedBy }, jwt, cookie: { auth } }) => {
|
||||
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") 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) throw new NotFoundError("Verification not found");
|
||||
throw new ConflictError(`Cannot complete a ${verification.status} verification`);
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema }),
|
||||
body: t.Object({
|
||||
activityVerifications: ActivityVerificationsSchema,
|
||||
completedBy: t.Optional(AccountIdSchema),
|
||||
}),
|
||||
cookie: t.Cookie({ auth: t.Optional(t.String()) })
|
||||
})
|
||||
);
|
||||
|
||||
export default VerificationsController;
|
||||
@@ -0,0 +1,89 @@
|
||||
import Elysia, { NotFoundError, t } from "elysia";
|
||||
import { Printful, Webflow } from "@blade-and-brawn/commerce";
|
||||
import { randomUUIDv7 } from "bun";
|
||||
import { s } from "../services";
|
||||
import { BadRequestError } from "../util/error";
|
||||
import { log } from "../util/log";
|
||||
|
||||
const WebhooksController = new Elysia({ prefix: "/webhooks" })
|
||||
.post("/printful", async ({ body, query }) => {
|
||||
// https://webflow.com/integrations/printful
|
||||
if (!s.Commerce.Printful.Util.verifySecret(query.secret))
|
||||
throw new BadRequestError("Invalid secret");
|
||||
|
||||
const payload = body as Printful.Webhook.EventPayload;
|
||||
|
||||
switch (payload.type) {
|
||||
case Printful.Webhook.Event.ProductUpdated: {
|
||||
const pProduct = payload.data.sync_product;
|
||||
log.info({ productId: pProduct.id }, "printful webhook: product updated");
|
||||
|
||||
await s.Commerce.Apparel.Syncs.Queue.enqueue({
|
||||
type: "apparel_sync_update",
|
||||
source: "printful",
|
||||
payload: {
|
||||
session: { id: randomUUIDv7(), name: "Printful" },
|
||||
filter: { pProductIds: [pProduct.id] }
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case Printful.Webhook.Event.ProductDeleted: {
|
||||
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) throw new NotFoundError("Missing webflow product ID");
|
||||
|
||||
await s.Commerce.Apparel.Syncs.Queue.enqueue({
|
||||
type: "apparel_sync_delete",
|
||||
source: "printful",
|
||||
payload: { wProductId }
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
case Printful.Webhook.Event.PackageShipped: {
|
||||
const wOrderId = payload.data.order.external_id;
|
||||
const shipment = payload.data.shipment;
|
||||
log.info({ wOrderId, carrier: shipment.carrier, tracking: shipment.tracking_number }, "printful webhook: package shipped");
|
||||
|
||||
// TODO: possible to have multiple packages shipped
|
||||
// order should NOT be immediately fulfulled in that case
|
||||
|
||||
await s.Commerce.Apparel.Orders.Queue.enqueue({
|
||||
type: "apparel_order_fulfill",
|
||||
source: "printful",
|
||||
payload: { wOrderId, shipment }
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
log.warn({ type: (payload as any).type }, "printful webhook: unhandled event type");
|
||||
}
|
||||
}, { query: t.Object({ secret: t.String() }) })
|
||||
.post("/webflow", async ({ request, body }) => {
|
||||
if (!s.Commerce.Webflow.Util.verifySecret(request, body))
|
||||
throw new BadRequestError("Invalid signature");
|
||||
|
||||
const payload = body as Webflow.Webhook.EventPayload;
|
||||
|
||||
switch (payload.triggerType) {
|
||||
case Webflow.Webhook.Event.OrderCreated: {
|
||||
const wOrder = payload.payload;
|
||||
log.info({ orderId: wOrder.orderId }, "webflow webhook: order created");
|
||||
|
||||
await s.Commerce.Apparel.Orders.Queue.enqueue({
|
||||
type: "apparel_order_create",
|
||||
source: "webflow",
|
||||
payload: { wOrder }
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
log.warn({ triggerType: (payload as any).triggerType }, "webflow webhook: unhandled event type");
|
||||
}
|
||||
});
|
||||
|
||||
export default WebhooksController;
|
||||
@@ -1,7 +1,7 @@
|
||||
import { CreateTableBuilder, Kysely, PostgresDialect, sql } from 'kysely';
|
||||
import { type DB } from "./out/db";
|
||||
import { Pool } from "pg";
|
||||
import { env, WORKER_COUNT } from '../util';
|
||||
import { env, WORKER_COUNT } from '../util/env';
|
||||
|
||||
export const db = new Kysely<DB>({
|
||||
dialect: new PostgresDialect({
|
||||
|
||||
@@ -3,7 +3,8 @@ import { promises as fs } from 'fs'
|
||||
import { FileMigrationProvider, Migrator, type MigrationResultSet } from 'kysely/migration'
|
||||
import { db } from './db'
|
||||
import { argv } from 'bun'
|
||||
import { env, log } from '../util'
|
||||
import { env } from '../util/env';
|
||||
import { log } from '../util/log';
|
||||
|
||||
type HandlerResult = {
|
||||
message: string;
|
||||
|
||||
@@ -3,10 +3,13 @@ import {
|
||||
} from "@blade-and-brawn/calculator";
|
||||
import { Value } from "@sinclair/typebox/value";
|
||||
import { db } from "./db";
|
||||
import { DEFAULT_NAME, env, log } from "../util";
|
||||
import { env } from "../util/env";
|
||||
import { log } from "../util/log";
|
||||
import standardsConfig from "./seed-data/standards-config.json" with {type: "json"};
|
||||
import type { AccountRole } from "../services/accounts";
|
||||
|
||||
export const DEFAULT_NAME = "Default";
|
||||
|
||||
Value.Assert(StandardsConfigSchema, standardsConfig);
|
||||
|
||||
async function seedStandardsDataset(): Promise<string> {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import cluster from 'node:cluster'
|
||||
import { log, WORKER_COUNT } from "./util";
|
||||
import { log } from "./util/log";
|
||||
import { WORKER_COUNT } from "./util/env";
|
||||
|
||||
if (cluster.isPrimary) {
|
||||
log.info(`Starting ${WORKER_COUNT} worker processes`)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import Elysia, { status, t } from "elysia";
|
||||
import jwt from "@elysia/jwt";
|
||||
import { env } from "../util/env";
|
||||
|
||||
export const authPlugin = new Elysia({ name: "auth" })
|
||||
.use(jwt({ name: "jwt", secret: env.AUTH_SECRET }))
|
||||
.guard({ cookie: t.Cookie({ auth: t.Optional(t.String()) }) })
|
||||
.macro({
|
||||
authAdmin: {
|
||||
async resolve({ jwt, cookie: { auth } }) {
|
||||
const token = auth.value && await jwt.verify(auth.value);
|
||||
if (!token || token.role !== "admin" || !token.accountId || !token.sessionId) return status(401, { error: "Unauthorized" });
|
||||
return { role: token.role.toString(), sessionId: token.sessionId.toString(), accountId: token.accountId.toString() };
|
||||
}
|
||||
},
|
||||
auth: {
|
||||
async resolve({ jwt, cookie: { auth } }) {
|
||||
const token = auth.value && await jwt.verify(auth.value);
|
||||
if (!token || !token.role || !token.accountId || !token.sessionId) return status(401, { error: "Unauthorized" });
|
||||
return { role: token.role.toString(), sessionId: token.sessionId.toString(), accountId: token.accountId.toString() };
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { WebflowClient } from "@blade-and-brawn/commerce";
|
||||
import { env } from "../util";
|
||||
import { env } from "../util/env";
|
||||
|
||||
const webflow = new WebflowClient({
|
||||
siteId: env.WEBFLOW_SITE_ID,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Printful, PrintfulClient, PrintfulError, Webflow, WebflowClient, WebflowError } from "@blade-and-brawn/commerce";
|
||||
import { env } from "../util";
|
||||
import { env } from "../util/env";
|
||||
|
||||
const DOMAIN = env.NODE_ENV === "development" ?
|
||||
"dev-api.bladeandbrawn.com" :
|
||||
|
||||
@@ -4,12 +4,13 @@ import { readdir } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { parseArgs } from "node:util";
|
||||
import { db } from "../database/db";
|
||||
import { env, log } from "../util";
|
||||
import { env } from "../util/env";
|
||||
import { log } from "../util/log";
|
||||
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 +69,12 @@ async function seedTestAssessment(accountId: string): Promise<string> {
|
||||
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 +97,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");
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
ProductSyncer,
|
||||
WebflowClient,
|
||||
} from "@blade-and-brawn/commerce";
|
||||
import { env } from "../util";
|
||||
import { env } from "../util/env";
|
||||
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
|
||||
+49
-729
@@ -1,97 +1,29 @@
|
||||
import {
|
||||
ActivityPerformanceSchema,
|
||||
ActivityVerificationsSchema,
|
||||
PlayerSchema,
|
||||
Activity,
|
||||
} from "@blade-and-brawn/domain"
|
||||
import { cors } from "@elysiajs/cors";
|
||||
import { Elysia, 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 { Elysia, status } from "elysia";
|
||||
import { PrintfulError, WebflowError } from "@blade-and-brawn/commerce";
|
||||
import serverTiming from "@elysia/server-timing";
|
||||
import jwt from "@elysia/jwt";
|
||||
import { CommerceService, WOrderStatusSchema } from "./services/commerce";
|
||||
import cluster from "node:cluster";
|
||||
import { randomUUIDv7, sleep, S3Client } from "bun";
|
||||
import { sleep } from "bun";
|
||||
import { DatabaseError } from "pg";
|
||||
import { CalculatorService, CalculatorUnavailableError } from "./services/calculator";
|
||||
import { StandardsParamsSchema } from "@blade-and-brawn/calculator";
|
||||
import { StandardsService } from "./services/standards";
|
||||
import { EventsService, EventStatusSchema } from "./services/events";
|
||||
import { AccountsService, type AccountRole } from "./services/accounts";
|
||||
import { Value } from "@sinclair/typebox/value";
|
||||
import { AssessmentsService } from "./services/assessments";
|
||||
import { VerificationsService, VerificationStatusSchema } from "./services/verifications";
|
||||
import { HttpError } from "./util/error";
|
||||
import { log } from "./util/log";
|
||||
import { queues } from "./services";
|
||||
import { CalculatorUnavailableError } from "./services/calculator";
|
||||
import { EventsService } from "./services/events";
|
||||
import AuthController from "./controllers/auth";
|
||||
import CalculatorController from "./controllers/calculator";
|
||||
import StandardsController from "./controllers/standards";
|
||||
import CommerceController from "./controllers/commerce";
|
||||
import EventsController from "./controllers/events";
|
||||
import AccountsController from "./controllers/accounts";
|
||||
import AssessmentsController from "./controllers/assessments";
|
||||
import VerificationsController from "./controllers/verifications";
|
||||
import WebhooksController from "./controllers/webhooks";
|
||||
|
||||
// CONSTANTS
|
||||
// -----------------------
|
||||
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
|
||||
|
||||
// SERVICES
|
||||
// -----------------------
|
||||
const s = (() => {
|
||||
const Standards = new StandardsService();
|
||||
const Calculator = new CalculatorService(DEFAULT_NAME);
|
||||
const Commerce = new CommerceService();
|
||||
const Accounts = new AccountsService(Calculator);
|
||||
const Events = new EventsService();
|
||||
const Assessments = new AssessmentsService();
|
||||
const Verifications = new VerificationsService();
|
||||
return { Standards, Calculator, Commerce, Accounts, Events, Assessments, Verifications };
|
||||
})();
|
||||
|
||||
// R2 BUCKETS
|
||||
// -----------------------
|
||||
const r2 = {
|
||||
verificationMedia: new S3Client({
|
||||
accessKeyId: env.R2_ACCESS_KEY_ID,
|
||||
secretAccessKey: env.R2_SECRET_ACCESS_KEY,
|
||||
bucket: `verification-media${env.NODE_ENV === "production" ? "" : "-dev"}`,
|
||||
endpoint: env.R2_URL,
|
||||
})
|
||||
};
|
||||
|
||||
const presignVerificationUploads = (assessmentId: string) =>
|
||||
Object.values(Activity).map(() => r2.verificationMedia.presign(`${assessmentId}/${crypto.randomUUID()}`, {
|
||||
method: "PUT",
|
||||
expiresIn: 30 * 60,
|
||||
}));
|
||||
|
||||
// QUEUES
|
||||
// -----------------------
|
||||
const queues = [
|
||||
s.Commerce.Apparel.Syncs.Queue,
|
||||
s.Commerce.Apparel.Orders.Queue,
|
||||
] as const;
|
||||
|
||||
// PLUGINS
|
||||
// -----------------------
|
||||
const authPlugin = new Elysia({ name: "auth" })
|
||||
.use(jwt({ name: "jwt", secret: env.AUTH_SECRET }))
|
||||
.guard({ cookie: t.Cookie({ auth: t.Optional(t.String()) }) })
|
||||
.macro({
|
||||
authAdmin: {
|
||||
async resolve({ jwt, cookie: { auth } }) {
|
||||
const token = auth.value && await jwt.verify(auth.value);
|
||||
if (!token || token.role !== "admin" || !token.accountId || !token.sessionId) return status(401, { error: "Unauthorized" });
|
||||
return { role: token.role.toString(), sessionId: token.sessionId.toString(), accountId: token.accountId.toString() };
|
||||
}
|
||||
},
|
||||
auth: {
|
||||
async resolve({ jwt, cookie: { auth } }) {
|
||||
const token = auth.value && await jwt.verify(auth.value);
|
||||
if (!token || !token.role || !token.accountId || !token.sessionId) return status(401, { error: "Unauthorized" });
|
||||
return { role: token.role.toString(), sessionId: token.sessionId.toString(), accountId: token.accountId.toString() };
|
||||
}
|
||||
}
|
||||
});
|
||||
const QUIET_ROUTES = new Set(["GET /commerce/products/sync/"]); // logged at debug level
|
||||
|
||||
// ELYSIA
|
||||
// -----------------------
|
||||
@@ -109,56 +41,44 @@ export const app = new Elysia()
|
||||
],
|
||||
}),
|
||||
)
|
||||
.guard({
|
||||
cookie: t.Cookie({
|
||||
auth: t.Optional(t.String()),
|
||||
authDiscord: t.Optional(t.String())
|
||||
})
|
||||
})
|
||||
.use(authPlugin)
|
||||
|
||||
.error({
|
||||
PrintfulError,
|
||||
WebflowError,
|
||||
CalculatorUnavailableError
|
||||
})
|
||||
|
||||
.error({ PrintfulError, WebflowError, CalculatorUnavailableError, HttpError })
|
||||
.onError(({ code, error }) => {
|
||||
// Database Errors
|
||||
if (error instanceof DatabaseError && error.code === "23505")
|
||||
// Database errors
|
||||
if (error instanceof DatabaseError) {
|
||||
if (error.code === "23505")
|
||||
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 "PrintfulError":
|
||||
case "WebflowError":
|
||||
log.error(
|
||||
{ upstreamStatus: error.upstreamStatus, payload: error.payload },
|
||||
error.message,
|
||||
);
|
||||
return status(502, { error: error.message });
|
||||
case "HttpError":
|
||||
break;
|
||||
case "CalculatorUnavailableError":
|
||||
log.error({ err: error.cause }, error.message);
|
||||
return status(503, { error: error.message });
|
||||
break;
|
||||
case "PrintfulError":
|
||||
case "WebflowError":
|
||||
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" })
|
||||
}
|
||||
})
|
||||
|
||||
.onAfterResponse(({ request, set, path, responseValue }) => {
|
||||
if (env.NODE_ENV === "development") {
|
||||
const skip: Record<string, string[]> = { "/commerce/products/sync/": ["GET"] };
|
||||
if (skip[path]?.includes(request.method)) return;
|
||||
}
|
||||
|
||||
.onAfterResponse(({ request, route, set, responseValue }) => {
|
||||
const failed = Number(set.status) >= 400;
|
||||
log[failed ? "warn" : "info"]({
|
||||
const level = failed ? "warn" : QUIET_ROUTES.has(`${request.method} ${route}`) ? "debug" : "info";
|
||||
log[level]({
|
||||
method: request.method,
|
||||
path,
|
||||
path: route,
|
||||
status: set.status,
|
||||
...(failed && { response: responseValue }),
|
||||
}, "request");
|
||||
@@ -167,615 +87,15 @@ export const app = new Elysia()
|
||||
.get("/", () => ({ status: "ok" }))
|
||||
.get("/health", () => ({ status: "ok" }))
|
||||
|
||||
// AUTHENTICATION
|
||||
.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" });
|
||||
|
||||
auth.set({
|
||||
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",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
domain: env.NODE_ENV === "production" ?
|
||||
".bladeandbrawn.com" :
|
||||
undefined
|
||||
});
|
||||
}, { body: t.Object({ email: t.String(), password: t.String() }) })
|
||||
|
||||
.group("/auth/discord", (app) => app
|
||||
.get("/login", async ({ cookie: { authDiscord } }) => {
|
||||
const state = crypto.randomUUID();
|
||||
|
||||
authDiscord.set({
|
||||
value: state,
|
||||
path: "/",
|
||||
maxAge: 60 * 10, // 10 min
|
||||
sameSite: "lax",
|
||||
httpOnly: true,
|
||||
secure: env.NODE_ENV === "production"
|
||||
});
|
||||
|
||||
const url = new URL("https://discord.com/api/oauth2/authorize");
|
||||
url.searchParams.set("client_id", env.BOT_CLIENT_ID);
|
||||
url.searchParams.set("redirect_uri", env.BOT_REDIRECT_URL);
|
||||
url.searchParams.set("response_type", "code");
|
||||
url.searchParams.set("scope", "identify email");
|
||||
url.searchParams.set("state", state);
|
||||
|
||||
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.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" });
|
||||
|
||||
const tokenRes = await fetch("https://discord.com/api/oauth2/token", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: new URLSearchParams({
|
||||
client_id: env.BOT_CLIENT_ID,
|
||||
client_secret: env.BOT_CLIENT_SECRET,
|
||||
grant_type: "authorization_code",
|
||||
code: query.code ?? "",
|
||||
redirect_uri: env.BOT_REDIRECT_URL
|
||||
}).toString()
|
||||
});
|
||||
if (!tokenRes.ok) {
|
||||
const errorBody = await tokenRes.json().catch(() => null);
|
||||
return status(502, { error: errorBody ?? "Discord token exchange failed" });
|
||||
}
|
||||
|
||||
const tokenResPayload = await tokenRes.json();
|
||||
Value.Assert(t.Object({ access_token: t.String() }), tokenResPayload);
|
||||
|
||||
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);
|
||||
return status(502, { error: errorBody ?? "Failed to fetch Discord identity" });
|
||||
}
|
||||
|
||||
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
|
||||
auth.set({
|
||||
value: await jwt.sign({ role: "user" satisfies AccountRole, sessionId: randomUUIDv7(), accountId, exp: JWT_EXP }),
|
||||
path: "/",
|
||||
maxAge: JWT_EXP_SECONDS,
|
||||
sameSite: env.NODE_ENV === "production" ? "lax" : "none",
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
domain: env.NODE_ENV === "production" ?
|
||||
".bladeandbrawn.com" :
|
||||
undefined
|
||||
});
|
||||
|
||||
return redirect(env.BOT_LOGIN_REDIRECT_URL, 302);
|
||||
}, {
|
||||
query: t.Object({
|
||||
code: t.Optional(t.String()),
|
||||
state: t.Optional(t.String()),
|
||||
error: t.Optional(t.String()),
|
||||
error_description: t.Optional(t.String()),
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
// CALCULATOR
|
||||
.group("/calculator", (app) => app
|
||||
// Non-authenticated
|
||||
.post("/calculate", async ({ body }) => {
|
||||
return { levels: await s.Calculator.calculate(body.player, body.activityPerformances) };
|
||||
}, {
|
||||
body: t.Object({
|
||||
player: PlayerSchema,
|
||||
activityPerformances: t.Array(ActivityPerformanceSchema)
|
||||
}),
|
||||
})
|
||||
// Authenticated
|
||||
.guard({ authAdmin: true }, (app) => app
|
||||
.get("/standards/config", async () => {
|
||||
return await s.Calculator.Standards.Config.get();
|
||||
})
|
||||
.post("/standards/config/switch", async ({ body: { standardsConfigId } }) => {
|
||||
await s.Calculator.Standards.Config.switch(standardsConfigId);
|
||||
}, {
|
||||
body: t.Object({ standardsConfigId: BigIntIdSchema })
|
||||
})
|
||||
)
|
||||
)
|
||||
.group("/standards", { authAdmin: true }, (app) => app
|
||||
.post("/configs", async ({ body: { name, datasetId, params } }) => {
|
||||
return await s.Standards.Configs.create(name, datasetId, params);
|
||||
}, {
|
||||
body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema })
|
||||
})
|
||||
.get("/configs", async () => {
|
||||
return await s.Standards.Configs.list();
|
||||
})
|
||||
.get("/configs/:id", async ({ params: { id } }) => {
|
||||
return await s.Standards.Configs.get(id);
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
.put("/configs/:id", async ({ params: { id }, body: { name, datasetId, params: parameters } }) => {
|
||||
await s.Standards.Configs.update(id, name, datasetId, parameters);
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema }),
|
||||
body: t.Object({ name: t.String(), datasetId: BigIntIdSchema, params: StandardsParamsSchema })
|
||||
})
|
||||
.delete("/configs/:id", async ({ params: { id } }) => {
|
||||
await s.Standards.Configs.delete(id);
|
||||
}, { params: t.Object({ id: BigIntIdSchema }) })
|
||||
.get("/datasets", async () => {
|
||||
return await s.Standards.Datasets.list();
|
||||
})
|
||||
.get("/datasets/:id", async ({ params: { id } }) => {
|
||||
return await s.Standards.Datasets.get(id);
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
.patch("/datasets/:id", async ({ params: { id }, body: { name } }) => {
|
||||
await s.Standards.Datasets.update(id, name);
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema }),
|
||||
body: t.Object({ name: t.String() })
|
||||
})
|
||||
)
|
||||
|
||||
// COMMERCE
|
||||
.group("/commerce", { authAdmin: true }, (app) => app
|
||||
.group("/products", (app) => app
|
||||
.get("/", async ({ query }) => {
|
||||
const [pProducts, wProducts] = await Promise.all([
|
||||
s.Commerce.Printful.Products.list({
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
}),
|
||||
s.Commerce.Webflow.Products.list({ forceAll: true }),
|
||||
]);
|
||||
const wProductIds = new Set(wProducts.map((wProduct) => wProduct.product.id));
|
||||
return pProducts.map((pProduct) => {
|
||||
const wProductId = pProduct.external_id.split("-")[0];
|
||||
return { pProduct, isSynced: wProductId ? wProductIds.has(wProductId) : false };
|
||||
});
|
||||
}, {
|
||||
query: t.Object({
|
||||
limit: t.Optional(t.Numeric({ maximum: 100 })),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.group("/sync", (app) => app
|
||||
// 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" });
|
||||
return latestSyncState;
|
||||
})
|
||||
// Run sync
|
||||
.post("/:pProductId?", async ({ params: { pProductId }, sessionId }) => {
|
||||
await s.Commerce.Apparel.Syncs.Queue.enqueue({
|
||||
type: "apparel_sync_update",
|
||||
source: "portal",
|
||||
payload: {
|
||||
session: { id: sessionId, name: "Portal" },
|
||||
filter: {
|
||||
pProductIds: pProductId ? [pProductId] : undefined
|
||||
}
|
||||
}
|
||||
});
|
||||
}, { params: t.Object({ pProductId: t.Optional(t.Numeric()) }) }),
|
||||
)
|
||||
.get("/:pProductId", async ({ params: { pProductId } }) => {
|
||||
const pProduct = await s.Commerce.Printful.Products.get(pProductId);
|
||||
if (!pProduct) return status(404, { error: "Missing printful product" });
|
||||
|
||||
const wProductId = pProduct.sync_product.external_id.split("-")[0];
|
||||
if (!wProductId) return status(404, { error: "Missing webflow product ID" });
|
||||
|
||||
const wProduct = await s.Commerce.Webflow.Products.get(wProductId);
|
||||
|
||||
return { pProduct, wProduct };
|
||||
}, {
|
||||
params: t.Object({ pProductId: t.Numeric() })
|
||||
})
|
||||
)
|
||||
.group("/orders", (app) => app
|
||||
.get("/", async ({ query }) => {
|
||||
const [wOrders, pOrders] = await Promise.all([
|
||||
s.Commerce.Webflow.Orders.list({
|
||||
status: query.status,
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
}),
|
||||
s.Commerce.Printful.Orders.list({ forceAll: true }),
|
||||
]);
|
||||
const pOrderExternalIds = new Set(pOrders.map((pOrder) => pOrder.external_id));
|
||||
return wOrders.map((wOrder) => ({
|
||||
wOrder,
|
||||
isSynced: pOrderExternalIds.has(wOrder.orderId),
|
||||
}));
|
||||
}, {
|
||||
query: t.Object({
|
||||
status: t.Optional(WOrderStatusSchema),
|
||||
limit: t.Optional(t.Numeric({ maximum: 100 })),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.get("/:wOrderId", async ({ params: { wOrderId } }) => {
|
||||
const wOrder = await s.Commerce.Webflow.Orders.get(wOrderId);
|
||||
if (!wOrder) return status(404, { error: "Missing webflow order" });
|
||||
|
||||
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
|
||||
|
||||
return { wOrder, pOrder };
|
||||
}, { 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" });
|
||||
|
||||
const pOrder = await s.Commerce.Printful.Orders.get(`@${wOrder.orderId}`);
|
||||
if (pOrder) return status(409, { error: "Cannot sync an already synced webflow order" });
|
||||
|
||||
await s.Commerce.Apparel.Orders.Queue.enqueue({
|
||||
type: "apparel_order_create",
|
||||
source: "portal",
|
||||
payload: { wOrder }
|
||||
});
|
||||
|
||||
}, { params: t.Object({ wOrderId: t.String() }) })
|
||||
)
|
||||
)
|
||||
|
||||
// EVENTS
|
||||
.group("/events", { authAdmin: true }, (app) => app
|
||||
.get("/", async ({ query }) => {
|
||||
const events = await s.Events.list({
|
||||
filter: { status: query.status, type: query.type, group: query.group },
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
});
|
||||
return events.map((event) => ({ ...event, status: EventsService.status(event) }));
|
||||
}, {
|
||||
query: t.Object({
|
||||
status: t.Optional(EventStatusSchema),
|
||||
type: t.Optional(t.String()),
|
||||
group: t.Optional(t.String()),
|
||||
limit: t.Optional(t.Numeric()),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.get("/:id", async ({ params: { id } }) => {
|
||||
const event = await s.Events.get(id);
|
||||
if (!event) return status(404, { error: "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" });
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
.get("/groups", async ({ }) => queues.map((q) => q.group))
|
||||
)
|
||||
|
||||
// ACCOUNTS
|
||||
.group("/accounts", (app) => app
|
||||
// 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" });
|
||||
return stats;
|
||||
}, {
|
||||
params: t.Object({ id: AccountIdSchema })
|
||||
})
|
||||
// TODO: for added security, MUST enforce bot or admin only access
|
||||
.get("/:id/verifications", async ({ query, params: { id } }) => {
|
||||
return await s.Verifications.list({
|
||||
filter: { status: query.status, accountId: id },
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
});
|
||||
}, {
|
||||
params: t.Object({ id: AccountIdSchema }),
|
||||
query: t.Object({
|
||||
status: t.Optional(VerificationStatusSchema),
|
||||
limit: t.Optional(t.Numeric()),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.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" });
|
||||
return account;
|
||||
}, {
|
||||
params: t.Object({ id: AccountIdSchema })
|
||||
})
|
||||
)
|
||||
.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" });
|
||||
return stats;
|
||||
})
|
||||
.post("/assessments", async ({ body: { player, activityPerformances }, accountId }) => {
|
||||
return await s.Assessments.create(player, activityPerformances, accountId);
|
||||
}, {
|
||||
body: t.Object({
|
||||
player: PlayerSchema,
|
||||
activityPerformances: t.Array(ActivityPerformanceSchema)
|
||||
})
|
||||
})
|
||||
// TODO: handle @ formatted accountIds
|
||||
.get("/assessments", async ({ accountId }) => {
|
||||
return await s.Assessments.list({ filter: { accountId } });
|
||||
})
|
||||
.delete("/assessments/:id", async ({ params: { id }, accountId }) => {
|
||||
const deleted = await s.Assessments.delete(id, accountId);
|
||||
if (!deleted) return status(404, { error: "Assessment not found" });
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
.get("/verifications", async ({ query, accountId }) => {
|
||||
return await s.Verifications.list({
|
||||
filter: { status: query.status, accountId },
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
});
|
||||
}, {
|
||||
query: t.Object({
|
||||
status: t.Optional(VerificationStatusSchema),
|
||||
limit: t.Optional(t.Numeric()),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
.post("/verifications", async ({ body: { assessmentId }, accountId }) => {
|
||||
const assessment = await s.Assessments.get(assessmentId, accountId);
|
||||
if (!assessment) return status(404, { error: "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" });
|
||||
|
||||
return { ...created, uploadUrls: presignVerificationUploads(assessmentId) };
|
||||
}, {
|
||||
body: t.Object({
|
||||
assessmentId: BigIntIdSchema
|
||||
})
|
||||
})
|
||||
.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" });
|
||||
|
||||
const reopened = await s.Verifications.reopen(id);
|
||||
if (!reopened) return status(409, { error: `Cannot reopen a ${verification.status} verification` });
|
||||
|
||||
return { ...reopened, uploadUrls: presignVerificationUploads(verification.assessment_id) };
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
.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.status === "draft") {
|
||||
const { contents } = await r2.verificationMedia.list({ prefix: `${verification.assessment_id}/`, maxKeys: 1 });
|
||||
if (!contents?.length) return status(409, { error: "No media uploaded" });
|
||||
}
|
||||
|
||||
const submitted = await s.Verifications.submit(id);
|
||||
if (submitted) {
|
||||
// TODO: trigger discord webhook here
|
||||
return submitted;
|
||||
}
|
||||
|
||||
const current = await s.Verifications.get(id, accountId);
|
||||
if (!current) return status(404, { error: "Verification not found" });
|
||||
if (current.status === "submitted") return { id: current.id, status: current.status };
|
||||
return status(409, { error: `Cannot submit a ${current.status} verification` });
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
// ASSESSMENTS
|
||||
.group("/assessments", { authAdmin: true }, (app) => app
|
||||
.post("/", async ({ body: { player, activityPerformances, id } }) => {
|
||||
return await s.Assessments.create(player, activityPerformances, id);
|
||||
}, {
|
||||
body: t.Object({
|
||||
player: PlayerSchema,
|
||||
activityPerformances: t.Array(ActivityPerformanceSchema),
|
||||
id: t.Optional(t.String()),
|
||||
})
|
||||
})
|
||||
.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" });
|
||||
return updated;
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema }),
|
||||
body: t.Object({
|
||||
player: PlayerSchema,
|
||||
activityPerformances: t.Array(ActivityPerformanceSchema),
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
// VERIFICATIONS
|
||||
.group("/verifications", (app) => app
|
||||
.get("/", async ({ query }) => {
|
||||
return await s.Verifications.list({
|
||||
filter: { status: query.status },
|
||||
limit: query.limit,
|
||||
offset: query.offset,
|
||||
});
|
||||
}, {
|
||||
authAdmin: true,
|
||||
query: t.Object({
|
||||
status: t.Optional(VerificationStatusSchema),
|
||||
limit: t.Optional(t.Numeric()),
|
||||
offset: t.Optional(t.Numeric()),
|
||||
})
|
||||
})
|
||||
// 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" });
|
||||
|
||||
const { contents = [] } = await r2.verificationMedia.list({ prefix: `${verification.assessment_id}/` });
|
||||
const media = contents.map(({ key, size, lastModified }) => ({
|
||||
key,
|
||||
size,
|
||||
lastModified,
|
||||
url: r2.verificationMedia.presign(key, { expiresIn: 60 * 60 }),
|
||||
}));
|
||||
|
||||
return { ...verification, media };
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema })
|
||||
})
|
||||
// TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth
|
||||
.post("/:id/request-action", async ({ params: { id }, body: { reviewerNotes, activityVerifications } }) => {
|
||||
const updated = await s.Verifications.requestAction(id, reviewerNotes ?? null, 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 request action on a ${verification.status} verification` });
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema }),
|
||||
body: t.Object({
|
||||
reviewerNotes: t.Optional(t.String()),
|
||||
activityVerifications: ActivityVerificationsSchema,
|
||||
})
|
||||
})
|
||||
// TODO: dev-only, unguarded so the bot can call it; restore admin/bot auth and drop completedBy from the body
|
||||
.post("/:id/complete", async ({ params: { id }, body: { activityVerifications, completedBy }, jwt, cookie: { auth } }) => {
|
||||
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" });
|
||||
|
||||
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` });
|
||||
}, {
|
||||
params: t.Object({ id: BigIntIdSchema }),
|
||||
body: t.Object({
|
||||
activityVerifications: ActivityVerificationsSchema,
|
||||
completedBy: t.Optional(AccountIdSchema),
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
// WEBHOOKS
|
||||
.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" });
|
||||
|
||||
const payload = body as Printful.Webhook.EventPayload;
|
||||
|
||||
switch (payload.type) {
|
||||
case Printful.Webhook.Event.ProductUpdated: {
|
||||
const pProduct = payload.data.sync_product;
|
||||
log.info({ productId: pProduct.id }, "printful webhook: product updated");
|
||||
|
||||
await s.Commerce.Apparel.Syncs.Queue.enqueue({
|
||||
type: "apparel_sync_update",
|
||||
source: "printful",
|
||||
payload: {
|
||||
session: { id: randomUUIDv7(), name: "Printful" },
|
||||
filter: { pProductIds: [pProduct.id] }
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case Printful.Webhook.Event.ProductDeleted: {
|
||||
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" });
|
||||
|
||||
await s.Commerce.Apparel.Syncs.Queue.enqueue({
|
||||
type: "apparel_sync_delete",
|
||||
source: "printful",
|
||||
payload: { wProductId }
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
case Printful.Webhook.Event.PackageShipped: {
|
||||
const wOrderId = payload.data.order.external_id;
|
||||
const shipment = payload.data.shipment;
|
||||
log.info({ wOrderId, carrier: shipment.carrier, tracking: shipment.tracking_number }, "printful webhook: package shipped");
|
||||
|
||||
// TODO: possible to have multiple packages shipped
|
||||
// order should NOT be immediately fulfulled in that case
|
||||
|
||||
await s.Commerce.Apparel.Orders.Queue.enqueue({
|
||||
type: "apparel_order_fulfill",
|
||||
source: "printful",
|
||||
payload: { wOrderId, shipment }
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
log.warn({ type: (payload as any).type }, "printful webhook: unhandled event type");
|
||||
}
|
||||
}, { 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" });
|
||||
|
||||
const payload = body as Webflow.Webhook.EventPayload;
|
||||
|
||||
switch (payload.triggerType) {
|
||||
case Webflow.Webhook.Event.OrderCreated: {
|
||||
const wOrder = payload.payload;
|
||||
log.info({ orderId: wOrder.orderId }, "webflow webhook: order created");
|
||||
|
||||
await s.Commerce.Apparel.Orders.Queue.enqueue({
|
||||
type: "apparel_order_create",
|
||||
source: "webflow",
|
||||
payload: { wOrder }
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
default:
|
||||
log.warn({ triggerType: (payload as any).triggerType }, "webflow webhook: unhandled event type");
|
||||
}
|
||||
});
|
||||
.use(AuthController)
|
||||
.use(CalculatorController)
|
||||
.use(StandardsController)
|
||||
.use(CommerceController)
|
||||
.use(EventsController)
|
||||
.use(AccountsController)
|
||||
.use(AssessmentsController)
|
||||
.use(VerificationsController)
|
||||
.use(WebhooksController);
|
||||
|
||||
app.listen(3000, async () => {
|
||||
if (cluster.worker?.id === 1)
|
||||
|
||||
@@ -22,7 +22,7 @@ export class AccountsService {
|
||||
name: name ?? "",
|
||||
email: email ?? null
|
||||
})
|
||||
.returning("id")
|
||||
.returning(["id", "discord_id", "name", "email", "gender", "role"])
|
||||
.executeTakeFirstOrThrow();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
import { LevelCalculator, Standards, StandardsParamsSchema, StandardsDataSchema, type StandardsConfig, type LevelCalculatorOutput } from "@blade-and-brawn/calculator";
|
||||
import type { ActivityPerformance, Player } from "@blade-and-brawn/domain";
|
||||
import { log } from "../util";
|
||||
import { log } from "../util/log";
|
||||
import { db } from "../database/db";
|
||||
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 {
|
||||
private static readonly DEFAULT_NAME = "Default";
|
||||
|
||||
private calculator: LevelCalculator | null = null;
|
||||
Standards: CalculatorStandardsService;
|
||||
|
||||
constructor(private name: string) {
|
||||
this.Standards = new CalculatorStandardsService(this.name);
|
||||
constructor() {
|
||||
this.Standards = new CalculatorStandardsService(CalculatorService.DEFAULT_NAME);
|
||||
// eagerly load
|
||||
this.refresh().catch((err) => log.error({ err }, "failed to load initial standards config"));
|
||||
}
|
||||
@@ -55,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)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { PrintfulClient, ProductSyncer, WebflowClient } from "@blade-and-brawn/commerce";
|
||||
import { env, log } from "../util";
|
||||
import { env } from "../util/env";
|
||||
import { log } from "../util/log";
|
||||
import { db } from "../database/db";
|
||||
import { defineEventType, EventQueue } from "./event-queue";
|
||||
import { Type as t } from "@sinclair/typebox";
|
||||
@@ -64,7 +65,7 @@ class ApparelOrdersService {
|
||||
shippingAddress: t.Object({
|
||||
addressee: t.String(),
|
||||
line1: t.String(),
|
||||
line2: t.String(),
|
||||
line2: t.Optional(t.Union([t.String(), t.Null()])),
|
||||
city: t.String(),
|
||||
country: t.String(),
|
||||
postalCode: t.String(),
|
||||
@@ -81,6 +82,12 @@ class ApparelOrdersService {
|
||||
processor: async (payload) => {
|
||||
const wOrder = payload.wOrder;
|
||||
|
||||
// a previous attempt may have created the order before failing
|
||||
if (await this.Printful.Orders.get(`@${wOrder.orderId}`)) {
|
||||
log.info({ wOrderId: wOrder.orderId }, "printful order already exists, skipping creation");
|
||||
return;
|
||||
}
|
||||
|
||||
const stateCode = zipcodesUs.find(
|
||||
wOrder.shippingAddress.postalCode.split("-")[0] ?? "",
|
||||
).stateCode;
|
||||
@@ -94,7 +101,7 @@ class ApparelOrdersService {
|
||||
recipient: {
|
||||
name: wOrder.shippingAddress.addressee,
|
||||
address1: wOrder.shippingAddress.line1,
|
||||
address2: wOrder.shippingAddress.line2,
|
||||
address2: wOrder.shippingAddress.line2 ?? "",
|
||||
city: wOrder.shippingAddress.city,
|
||||
state_code: stateCode,
|
||||
country_code: wOrder.shippingAddress.country,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { type Selectable, type Transaction } from "kysely";
|
||||
import { sql, type Selectable, type Transaction } from "kysely";
|
||||
import type { DB } from "../database/out/db";
|
||||
import { log } from "../util";
|
||||
import { log } from "../util/log";
|
||||
import { sleep } from "bun";
|
||||
import { db } from "../database/db";
|
||||
import { AssertError, Value } from "@sinclair/typebox/value";
|
||||
@@ -29,7 +29,6 @@ type EventQueueCfg = {
|
||||
},
|
||||
};
|
||||
|
||||
class AlreadyClaimedEventError extends Error { }
|
||||
class ConcurrencyLimitReachedError extends Error { }
|
||||
|
||||
export function defineEventType<P extends TSchema, S extends TSchema>(opt: EventTypeOptions<P, S>): EventTypeOptions<P, S> {
|
||||
@@ -46,7 +45,6 @@ function exponentialDelay(initialDelay: number, tries: number, cap: number = Inf
|
||||
}
|
||||
|
||||
export class EventQueue<G extends string, T extends Record<string, EventTypeOptions<any, any>>> {
|
||||
private static readonly DEQUEUE_ALREADY_CLAIMED_SKIP_DELAY_MS = 250;
|
||||
private static readonly DEQUEUE_RETRY_DELAY_MS = secToMs(10);
|
||||
private static readonly DEQUEUE_RETRY_LIMIT = 3;
|
||||
private static readonly RATE_LIMIT_RETRY_LIMIT = 15;
|
||||
@@ -77,15 +75,8 @@ export class EventQueue<G extends string, T extends Record<string, EventTypeOpti
|
||||
consecutiveFailures = 0;
|
||||
}
|
||||
catch (err) {
|
||||
if (err instanceof AlreadyClaimedEventError) {
|
||||
log.warn("event processing already claimed by another worker, skipping");
|
||||
await sleep(EventQueue.DEQUEUE_ALREADY_CLAIMED_SKIP_DELAY_MS);
|
||||
continue;
|
||||
}
|
||||
if (err instanceof ConcurrencyLimitReachedError) {
|
||||
await sleep(EventQueue.DEQUEUE_RETRY_DELAY_MS);
|
||||
continue;
|
||||
}
|
||||
// Return to the manager loop so it can clean timed out events
|
||||
if (err instanceof ConcurrencyLimitReachedError) break;
|
||||
|
||||
if (++consecutiveFailures <= EventQueue.DEQUEUE_RETRY_LIMIT) {
|
||||
log.warn({ err, consecutiveFailures }, "dequeue failed, retrying")
|
||||
@@ -102,37 +93,29 @@ export class EventQueue<G extends string, T extends Record<string, EventTypeOpti
|
||||
async dequeue() {
|
||||
log.trace("dequeueing");
|
||||
|
||||
const front = await this.front();
|
||||
if (!front) return;
|
||||
// Serialize claims per group so concurrent workers see each other's claims when checking the concurrency limit
|
||||
const front = await db.transaction().execute(async (trx) => {
|
||||
await sql`select pg_advisory_xact_lock(hashtext(${this.group}))`.execute(trx);
|
||||
|
||||
const result = await db.updateTable("events")
|
||||
.set({ started_at: new Date(), heartbeat_at: new Date() })
|
||||
.where("id", "=", front.id)
|
||||
.where("started_at", "is", null)
|
||||
.where((eb) =>
|
||||
eb(
|
||||
eb.selectFrom("events")
|
||||
.select(eb.fn.countAll().as("count"))
|
||||
const { count } = await trx.selectFrom("events")
|
||||
.select(trx.fn.countAll().as("count"))
|
||||
.where("group", "=", this.group)
|
||||
.where("started_at", "is not", null)
|
||||
.where("ended_at", "is", null),
|
||||
"<",
|
||||
this.cfg.concurrency.limit
|
||||
)
|
||||
)
|
||||
.where("ended_at", "is", null)
|
||||
.executeTakeFirstOrThrow();
|
||||
if (Number(count) >= this.cfg.concurrency.limit) throw new ConcurrencyLimitReachedError();
|
||||
|
||||
// Guard against another worker/machine having already claimed this event and guard against max concurrency
|
||||
if (result.numUpdatedRows === 0n) {
|
||||
const frontFresh = await db.selectFrom("events")
|
||||
.select("started_at")
|
||||
const front = await this.front(trx);
|
||||
if (!front) return;
|
||||
|
||||
await trx.updateTable("events")
|
||||
.set({ started_at: new Date(), heartbeat_at: new Date() })
|
||||
.where("id", "=", front.id)
|
||||
.executeTakeFirst();
|
||||
.execute();
|
||||
|
||||
if (!frontFresh) throw new AlreadyClaimedEventError();
|
||||
if (frontFresh?.started_at) throw new AlreadyClaimedEventError();
|
||||
throw new ConcurrencyLimitReachedError();
|
||||
};
|
||||
return front;
|
||||
});
|
||||
if (!front) return;
|
||||
|
||||
log.trace({ name: front.id }, "dequeuing event");
|
||||
await this.process(front);
|
||||
|
||||
@@ -3,7 +3,7 @@ import { t } from "elysia";
|
||||
import { sql, type Selectable, type Transaction } from "kysely";
|
||||
import type { DB, JsonValue } from "../database/out/db";
|
||||
import { db } from "../database/db";
|
||||
import { log } from "../util";
|
||||
import { log } from "../util/log";
|
||||
import { minToMs } from "@blade-and-brawn/domain";
|
||||
|
||||
export const EventStatusSchema = t.Union([
|
||||
@@ -120,7 +120,7 @@ export class EventsService {
|
||||
|
||||
async resolve(id: string, trx?: Transaction<DB>): Promise<void> {
|
||||
await (trx ?? db).updateTable("events")
|
||||
.set({ state: null, ended_at: new Date(), last_error: null })
|
||||
.set({ state: null, ended_at: new Date(), has_failed: false, last_error: null })
|
||||
.where("id", "=", id)
|
||||
.execute();
|
||||
}
|
||||
@@ -132,6 +132,8 @@ export class EventsService {
|
||||
started_at: null,
|
||||
ended_at: null,
|
||||
has_failed: false,
|
||||
errors: 0,
|
||||
rate_limits: 0,
|
||||
available_at: new Date(),
|
||||
})
|
||||
.where("id", "=", id)
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { AccountsService } from "./accounts";
|
||||
import { AssessmentsService } from "./assessments";
|
||||
import { CalculatorService } from "./calculator";
|
||||
import { CommerceService } from "./commerce";
|
||||
import { EventsService } from "./events";
|
||||
import { StandardsService } from "./standards";
|
||||
import { VerificationsService } from "./verifications";
|
||||
|
||||
export const s = (() => {
|
||||
const Standards = new StandardsService();
|
||||
const Calculator = new CalculatorService();
|
||||
const Commerce = new CommerceService();
|
||||
const Accounts = new AccountsService(Calculator);
|
||||
const Events = new EventsService();
|
||||
const Assessments = new AssessmentsService();
|
||||
const Verifications = new VerificationsService();
|
||||
return { Standards, Calculator, Commerce, Accounts, Events, Assessments, Verifications };
|
||||
})();
|
||||
|
||||
export const queues = [
|
||||
s.Commerce.Apparel.Syncs.Queue,
|
||||
s.Commerce.Apparel.Orders.Queue,
|
||||
] as const;
|
||||
@@ -31,7 +31,7 @@ class StandardsConfigService {
|
||||
.execute();
|
||||
}
|
||||
|
||||
async get(id: string): Promise<StandardsConfig & { id: string, name: string, datasetId: string }> {
|
||||
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<boolean> {
|
||||
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<number> {
|
||||
const { count } = await db.selectFrom("standards_configs")
|
||||
.select(db.fn.countAll<number>().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<boolean> {
|
||||
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<boolean> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { Static } from "@sinclair/typebox";
|
||||
import { t } from "elysia";
|
||||
import { db } from "../database/db";
|
||||
import { AccountsService } from "./accounts";
|
||||
import { S3Client } from "bun";
|
||||
|
||||
export const VerificationStatusSchema = t.Union([
|
||||
t.Literal("draft"),
|
||||
@@ -21,6 +22,13 @@ const ALLOWED_FROM = {
|
||||
} satisfies Record<string, VerificationStatus[]>;
|
||||
|
||||
export class VerificationsService {
|
||||
public static presignMediaUploads(s3Client: S3Client, assessmentId: string) {
|
||||
return Object.values(Activity).map(() => s3Client.presign(`${assessmentId}/${crypto.randomUUID()}`, {
|
||||
method: "PUT",
|
||||
expiresIn: 30 * 60,
|
||||
}))
|
||||
}
|
||||
|
||||
async create(assessmentId: string) {
|
||||
return await db.insertInto("verifications")
|
||||
.values({ assessment_id: assessmentId, status: "draft" satisfies VerificationStatus })
|
||||
@@ -29,15 +37,6 @@ export class VerificationsService {
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
async reopen(id: string) {
|
||||
return await db.updateTable("verifications")
|
||||
.where("id", "=", id)
|
||||
.where("status", "in", ALLOWED_FROM.reopen)
|
||||
.set({ status: "draft" satisfies VerificationStatus, submitted_at: null })
|
||||
.returning(["id", "status"])
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
async get(id: string, accountId?: string) {
|
||||
return await VerificationsService.baseQuery()
|
||||
.where("verifications.id", "=", id)
|
||||
@@ -110,6 +109,15 @@ export class VerificationsService {
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
async reopen(id: string) {
|
||||
return await db.updateTable("verifications")
|
||||
.where("id", "=", id)
|
||||
.where("status", "in", ALLOWED_FROM.reopen)
|
||||
.set({ status: "draft" satisfies VerificationStatus, submitted_at: null })
|
||||
.returning(["id", "status"])
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
private static accountIdQuery(accountId: string) {
|
||||
return db.selectFrom("accounts")
|
||||
.select("id")
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy");
|
||||
export const sha256Sum = (s: string) => createHash("sha256").update(s).digest();
|
||||
@@ -1,15 +1,5 @@
|
||||
import cluster from 'node:cluster';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { pino } from 'pino';
|
||||
import os from 'node:os'
|
||||
import { t } from 'elysia';
|
||||
|
||||
export const log = pino({
|
||||
level: Bun.env.LOG_LEVEL ?? "info",
|
||||
transport: Bun.env.NODE_ENV != "production"
|
||||
? { target: "pino-pretty" }
|
||||
: undefined,
|
||||
});
|
||||
|
||||
export const env = {
|
||||
PRINTFUL_AUTH: requireEnv("PRINTFUL_AUTH"),
|
||||
@@ -39,17 +29,12 @@ export const env = {
|
||||
};
|
||||
|
||||
export const WORKER_COUNT = Math.min(os.availableParallelism(), +env.MAX_WORKER_COUNT);
|
||||
export const DEFAULT_NAME = "Default";
|
||||
export const DUMMY_PASSWORD_HASH = await Bun.password.hash("Dummy");
|
||||
|
||||
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})$" });
|
||||
|
||||
function requireEnv(key: string): string {
|
||||
const val = Bun.env[key];
|
||||
if (!val) {
|
||||
if (cluster.worker?.id === 1)
|
||||
log.error({ name: key }, "Missing required environment variable");
|
||||
console.error({ name: key }, "Missing required environment variable");
|
||||
throw new Error(`Missing required environment variable: ${key}`)
|
||||
};
|
||||
return val;
|
||||
@@ -59,10 +44,8 @@ function optionEnv(key: string, fallback: string = ""): string {
|
||||
const val = Bun.env[key];
|
||||
if (!val) {
|
||||
if (cluster.worker?.id === 1)
|
||||
log.warn({ name: key }, `Missing optional environmental variable, falling back to "${fallback}"`)
|
||||
console.warn({ name: key }, `Missing optional environmental variable, falling back to "${fallback}"`)
|
||||
return fallback
|
||||
};
|
||||
return val;
|
||||
}
|
||||
|
||||
export const sha256Sum = (s: string) => createHash("sha256").update(s).digest();
|
||||
@@ -0,0 +1,29 @@
|
||||
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); }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { pino } from 'pino';
|
||||
|
||||
export const log = pino({
|
||||
level: Bun.env.LOG_LEVEL ?? "info",
|
||||
transport: Bun.env.NODE_ENV != "production"
|
||||
? { target: "pino-pretty" }
|
||||
: undefined,
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
import { t } from 'elysia';
|
||||
|
||||
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})$" });
|
||||
@@ -0,0 +1,17 @@
|
||||
import { S3Client } from "bun";
|
||||
import { env } from "./env";
|
||||
|
||||
// All buckets should have a variant for development formatted as: "<bucket>-dev"
|
||||
|
||||
function bucketKeyForEnv(key: string) {
|
||||
return `${key}${env.NODE_ENV === "production" ? "" : "-dev"}`
|
||||
}
|
||||
|
||||
export const r2 = {
|
||||
verificationMedia: new S3Client({
|
||||
accessKeyId: env.R2_ACCESS_KEY_ID,
|
||||
secretAccessKey: env.R2_SECRET_ACCESS_KEY,
|
||||
bucket: bucketKeyForEnv("verification-media"),
|
||||
endpoint: env.R2_URL,
|
||||
})
|
||||
};
|
||||
@@ -11,6 +11,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "^1.4.2",
|
||||
"@types/node": "^26.6.4",
|
||||
"@typescript/native": "npm:typescript@7",
|
||||
"typescript": "~6",
|
||||
},
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "^1.4.2",
|
||||
"@types/node": "^26.6.4",
|
||||
"@typescript/native": "npm:typescript@7",
|
||||
"typescript": "~6"
|
||||
},
|
||||
|
||||
@@ -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' }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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' }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user