generated from nhcarrigan/template
a36c8e72a5
## Summary
- Add comprehensive try/catch error handling across all API routes, middleware, and the Hono global error handler, piping every unhandled error to the `@nhcarrigan/logger` service to prevent silent crashes and unhandled Promise rejections
- Add a `logError` utility on the frontend that forwards errors through the overridden `console.error` to the backend telemetry endpoint; apply it to every silent `catch {}` block in the game context, sound, notification, and clipboard utilities, and wrap the React tree in an `ErrorBoundary`
- Add Plausible analytics, Open Graph + Twitter Card meta tags, Tree-Nation widget, and Google Ads to `index.html`
- Make the game sidebar sticky with a `--resource-bar-height` CSS custom property offset so it stays viewport-height without overlapping the resource bar; reset sticky behaviour in the mobile responsive override
## Test plan
- [ ] Lint passes: `pnpm lint`
- [ ] Build passes: `pnpm build`
- [ ] Verify errors thrown in API routes appear in the logger service rather than crashing the process
- [ ] Verify frontend errors appear in the `/api/fe/error` backend log
- [ ] Verify Open Graph tags render correctly when sharing the URL
- [ ] Verify Plausible analytics fires on page load
- [ ] Verify Tree-Nation badge renders in the sidebar
- [ ] Verify sidebar stays fixed while the main content scrolls on desktop
- [ ] Verify mobile layout is unaffected
✨ This issue was created with help from Hikari~ 🌸
Reviewed-on: #44
Co-authored-by: Hikari <hikari@nhcarrigan.com>
Co-committed-by: Hikari <hikari@nhcarrigan.com>
141 lines
4.8 KiB
TypeScript
141 lines
4.8 KiB
TypeScript
/**
|
|
* @file Authentication routes for Discord OAuth.
|
|
* @copyright nhcarrigan
|
|
* @license Naomi's Public License
|
|
* @author Naomi Carrigan
|
|
*/
|
|
/* eslint-disable max-lines-per-function -- Auth callback requires many steps */
|
|
/* eslint-disable max-statements -- Auth callback requires many statements */
|
|
import { Hono } from "hono";
|
|
import { initialGameState } from "../data/initialState.js";
|
|
import { prisma } from "../db/client.js";
|
|
import {
|
|
buildOAuthUrl,
|
|
exchangeCode,
|
|
fetchDiscordUser,
|
|
} from "../services/discord.js";
|
|
import { signToken } from "../services/jwt.js";
|
|
import { logger } from "../services/logger.js";
|
|
import type { Player } from "@elysium/types";
|
|
|
|
const authRouter = new Hono();
|
|
|
|
authRouter.get("/url", (context) => {
|
|
try {
|
|
const url = buildOAuthUrl();
|
|
return context.json({ url });
|
|
} catch {
|
|
return context.json({ error: "Failed to build OAuth URL" }, 500);
|
|
}
|
|
});
|
|
|
|
authRouter.get("/callback", async(context) => {
|
|
const code = context.req.query("code");
|
|
|
|
if (code === undefined || code === "") {
|
|
return context.json({ error: "Missing code parameter" }, 400);
|
|
}
|
|
|
|
try {
|
|
const tokenData = await exchangeCode(code);
|
|
const discordUser = await fetchDiscordUser(tokenData.access_token);
|
|
|
|
const existing = await prisma.player.findUnique({
|
|
where: { discordId: discordUser.id },
|
|
});
|
|
|
|
const now = Date.now();
|
|
|
|
if (!existing) {
|
|
const player = await prisma.player.create({
|
|
data: {
|
|
avatar: discordUser.avatar,
|
|
characterName: discordUser.username,
|
|
createdAt: now,
|
|
discordId: discordUser.id,
|
|
discriminator: discordUser.discriminator,
|
|
lastSavedAt: now,
|
|
totalClicks: 0,
|
|
totalGoldEarned: 0,
|
|
username: discordUser.username,
|
|
},
|
|
});
|
|
|
|
const playerShape: Player = {
|
|
avatar: player.avatar ?? null,
|
|
characterName: player.characterName,
|
|
createdAt: player.createdAt,
|
|
discordId: player.discordId,
|
|
discriminator: player.discriminator,
|
|
lastSavedAt: player.lastSavedAt,
|
|
lifetimeAchievementsUnlocked: player.lifetimeAchievementsUnlocked,
|
|
lifetimeAdventurersRecruited: player.lifetimeAdventurersRecruited,
|
|
lifetimeBossesDefeated: player.lifetimeBossesDefeated,
|
|
lifetimeClicks: player.lifetimeClicks,
|
|
lifetimeGoldEarned: player.lifetimeGoldEarned,
|
|
lifetimeQuestsCompleted: player.lifetimeQuestsCompleted,
|
|
totalClicks: player.totalClicks,
|
|
totalGoldEarned: player.totalGoldEarned,
|
|
username: player.username,
|
|
};
|
|
|
|
const freshState = initialGameState(
|
|
playerShape,
|
|
playerShape.characterName,
|
|
);
|
|
await prisma.gameState.create({
|
|
data: {
|
|
discordId: player.discordId,
|
|
/* eslint-disable-next-line @typescript-eslint/consistent-type-assertions -- Prisma requires never type */
|
|
state: freshState as unknown as never,
|
|
updatedAt: now,
|
|
},
|
|
});
|
|
|
|
const jwtToken = signToken(player.discordId);
|
|
void logger.log("info", `New player registered: ${player.discordId}`);
|
|
void logger.metric("user_registered", 1, { discordId: player.discordId });
|
|
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next -- @preserve */
|
|
const clientUrl = process.env.CORS_ORIGIN ?? "http://localhost:5173";
|
|
return context.redirect(
|
|
`${clientUrl}/auth/callback?token=${jwtToken}&isNew=true`,
|
|
);
|
|
}
|
|
|
|
const updated = await prisma.player.update({
|
|
data: {
|
|
avatar: discordUser.avatar,
|
|
discriminator: discordUser.discriminator,
|
|
username: discordUser.username,
|
|
},
|
|
where: { discordId: discordUser.id },
|
|
});
|
|
|
|
const jwtToken = signToken(updated.discordId);
|
|
void logger.log("info", `Player logged in: ${updated.discordId}`);
|
|
void logger.metric("user_login", 1, { discordId: updated.discordId });
|
|
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next -- @preserve */
|
|
const clientUrl = process.env.CORS_ORIGIN ?? "http://localhost:5173";
|
|
return context.redirect(
|
|
`${clientUrl}/auth/callback?token=${jwtToken}&isNew=false`,
|
|
);
|
|
} catch (error) {
|
|
void logger.error(
|
|
"auth_callback",
|
|
error instanceof Error
|
|
? error
|
|
: new Error(String(error)),
|
|
);
|
|
// eslint-disable-next-line capitalized-comments -- v8 ignore
|
|
/* v8 ignore next -- @preserve */
|
|
const clientUrl = process.env.CORS_ORIGIN ?? "http://localhost:5173";
|
|
return context.redirect(`${clientUrl}/auth/callback?error=auth_failed`);
|
|
}
|
|
});
|
|
|
|
export { authRouter };
|