feat:lineage compat, nessa made more similar

This commit is contained in:
2026-07-24 07:40:58 -04:00
parent a876cee6ec
commit 9e285570e1
32 changed files with 536 additions and 129 deletions

View File

@@ -11,14 +11,66 @@
import { For, Show } from "solid-js"; import { For, Show } from "solid-js";
import { A, useLocation } from "@solidjs/router"; import { A, useLocation } from "@solidjs/router";
import { useSite } from "~/context/SiteContext"; import { useSite } from "~/context/SiteContext";
import { useDarkMode } from "~/context/darkMode";
import { NAV_CONFIG, BACK_TO_FRENO } from "~/lib/nav-config"; import { NAV_CONFIG, BACK_TO_FRENO } from "~/lib/nav-config";
/** Simple SVG sun icon for dark mode toggle. */
function SunIcon() {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="h-5 w-5"
aria-hidden="true"
>
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2" />
<path d="M12 20v2" />
<path d="M2 12h2" />
<path d="M20 12h2" />
<path d="m4.93 4.93 1.41 1.41" />
<path d="m17.66 17.66 1.41 1.41" />
<path d="m2 12h2" />
<path d="m20 12h2" />
<path d="m4.93 19.07 1.41-1.41" />
<path d="m17.66 6.34 1.41-1.41" />
</svg>
);
}
/** Simple SVG moon icon for dark mode toggle. */
function MoonIcon() {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="h-5 w-5"
aria-hidden="true"
>
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
<path d="M9 11a5 5 0 0 0 5.5 5.5" />
</svg>
);
}
export default function SubdomainHeader() { export default function SubdomainHeader() {
const site = useSite(); const site = useSite();
const location = useLocation(); const location = useLocation();
const { isDark, toggleDarkMode } = useDarkMode();
const brandName = () => site().displayName; const brandName = () => site().displayName;
const brandColor = () => site().brandColor; const brandColor = () =>
isDark() ? (site().brandColorDark ?? site().brandColor) : site().brandColor;
const navItems = () => const navItems = () =>
NAV_CONFIG[site().id].filter((item) => item.label !== "Home"); NAV_CONFIG[site().id].filter((item) => item.label !== "Home");
@@ -80,6 +132,22 @@ export default function SubdomainHeader() {
> >
{BACK_TO_FRENO.label} {BACK_TO_FRENO.label}
</a> </a>
{/* Dark mode toggle */}
<button
onClick={toggleDarkMode}
class="hover:bg-surface0/40 rounded-full p-2 transition-colors"
aria-label={
isDark() ? "Switch to light mode" : "Switch to dark mode"
}
>
<Show when={isDark()}>
<SunIcon />
</Show>
<Show when={!isDark()}>
<MoonIcon />
</Show>
</button>
</nav> </nav>
</div> </div>
</header> </header>

View File

@@ -33,6 +33,8 @@ export interface Site {
titleSuffix: string; titleSuffix: string;
/** Hex brand color used for theming accents / OG image backgrounds. */ /** Hex brand color used for theming accents / OG image backgrounds. */
brandColor: string; brandColor: string;
/** Dark mode variant of the brand color (used when dark mode is active). */
brandColorDark?: string;
/** Default OpenGraph image path (resolved against the site root). */ /** Default OpenGraph image path (resolved against the site root). */
ogDefaultImage: string; ogDefaultImage: string;
/** Favicon path for this site. */ /** Favicon path for this site. */
@@ -83,7 +85,8 @@ export const SITE_CONFIG: Record<SiteId, Site> = {
baseRoutePrefix: "/nessa", baseRoutePrefix: "/nessa",
displayName: "Nessa", displayName: "Nessa",
titleSuffix: " | Nessa", titleSuffix: " | Nessa",
brandColor: "#cba6f7", brandColor: "#527640",
brandColorDark: "#6CA86C",
ogDefaultImage: "/nessa/og-default.png", ogDefaultImage: "/nessa/og-default.png",
faviconPath: "/nessa/favicon.ico" faviconPath: "/nessa/favicon.ico"
}, },

View File

@@ -0,0 +1,65 @@
// Shared REST handler for the Lineage REST shim.
//
// Each route file calls `rest()` with a function that receives a typed tRPC
// caller (scoped to `caller.lineage.*`) and the SolidStart APIEvent. The
// handler maps `TRPCError` codes → HTTP status + `{ message }` body (the
// legacy client parses `result.message` on non-OK responses), and returns
// the procedure's return value as JSON on success.
import type { APIEvent } from "@solidjs/start/server";
import { TRPCError } from "@trpc/server";
import { createServerCaller } from "~/server/api/root";
const codeToStatus: Record<string, number> = {
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
FORBIDDEN: 403,
NOT_FOUND: 404,
CONFLICT: 409,
TIMEOUT: 408,
PAYLOAD_TOO_LARGE: 413,
METHOD_NOT_SUPPORTED: 405,
TOO_MANY_REQUESTS: 429,
INTERNAL_SERVER_ERROR: 500
};
type Caller = Awaited<ReturnType<typeof createServerCaller>>;
export async function rest(
fn: (caller: Caller, event: APIEvent) => Promise<unknown>,
event: APIEvent
): Promise<Response> {
try {
const caller = await createServerCaller(event);
const result = await fn(caller, event);
return new Response(JSON.stringify(result), {
status: 200,
headers: { "content-type": "application/json" }
});
} catch (e) {
if (e instanceof TRPCError) {
const status = codeToStatus[e.code] ?? 500;
return new Response(JSON.stringify({ message: e.message }), {
status,
headers: { "content-type": "application/json" }
});
}
console.error("Lineage REST shim error:", e);
return new Response(JSON.stringify({ message: "Internal server error" }), {
status: 500,
headers: { "content-type": "application/json" }
});
}
}
/** Extract the Bearer token from the Authorization header. */
export function bearerToken(event: APIEvent): string | null {
const auth = event.request.headers.get("authorization") ?? "";
const m = auth.match(/^Bearer\s+(.+)$/i);
return m?.[1]?.trim() ?? null;
}
/** Parse the JSON request body. */
export async function jsonBody<T = any>(event: APIEvent): Promise<T> {
return await event.request.json();
}

View File

@@ -0,0 +1,8 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "./_lib";
export const POST = (event: APIEvent) =>
rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.misc.analytics(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.auth.appleGetEmail(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.auth.appleRegistration(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.database.databaseCreds(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.database.deletionCancel(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.database.deletionCheck(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.database.deletionInit(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.auth.emailLogin(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest, bearerToken } from "../../_lib";
export const GET = (event: APIEvent) => rest(async (caller) => {
const token = bearerToken(event);
return caller.lineage.auth.refreshToken({ token: token ?? "" });
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.auth.refreshVerification(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.auth.emailRegistration(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.auth.emailVerification(input);
}, event);

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.auth.googleRegistration(input);
}, event);

View File

@@ -0,0 +1,6 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const GET = (event: APIEvent) => rest(async (caller) => {
return caller.lineage.jsonService.attacks();
}, event);

View File

@@ -0,0 +1,6 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const GET = (event: APIEvent) => rest(async (caller) => {
return caller.lineage.jsonService.conditions();
}, event);

View File

@@ -0,0 +1,6 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const GET = (event: APIEvent) => rest(async (caller) => {
return caller.lineage.jsonService.dungeons();
}, event);

View File

@@ -0,0 +1,6 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const GET = (event: APIEvent) => rest(async (caller) => {
return caller.lineage.jsonService.enemies();
}, event);

View File

@@ -0,0 +1,6 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const GET = (event: APIEvent) => rest(async (caller) => {
return caller.lineage.jsonService.items();
}, event);

View File

@@ -0,0 +1,6 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const GET = (event: APIEvent) => rest(async (caller) => {
return caller.lineage.jsonService.misc();
}, event);

View File

@@ -0,0 +1,22 @@
// Plain-text route for the Lineage offline secret.
//
// `misc.offlineSecret` is a tRPC `.query()` returning `{ secret: "…" }`. But
// the Lineage client's `IAPStore.fetchOfflineSecret` does
// `await response.text()` and uses the raw string directly as the decryption
// key. trpc-openapi always JSON-encodes responses, so exposing it via the openapi
// shim would yield `'{"secret":"…"}'` as text and break decryption.
//
// This dedicated route returns the secret verbatim as `text/plain`, matching
// exactly what the legacy endpoint returned. Auth: none (the legacy endpoint
// had none either — the secret is a server-side decryption key shared to all
// clients; it rotates with `LINEAGE_OFFLINE_SERIALIZATION_SECRET`).
import type { APIEvent } from "@solidjs/start/server";
import { env } from "~/env/server";
export const GET = (event: APIEvent) => {
return new Response(env.LINEAGE_OFFLINE_SERIALIZATION_SECRET, {
status: 200,
headers: { "content-type": "text/plain; charset=utf-8" }
});
};

View File

@@ -0,0 +1,7 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.pvp.battleResult(input);
}, event);

View File

@@ -0,0 +1,13 @@
import type { APIEvent } from "@solidjs/start/server";
import { rest } from "../_lib";
// GET /api/lineage/pvp — retrieve opponents
export const GET = (event: APIEvent) => rest(async (caller) => {
return caller.lineage.pvp.getOpponents();
}, event);
// POST /api/lineage/pvp — register/update player character
export const POST = (event: APIEvent) => rest(async (caller) => {
const input = await event.request.json();
return caller.lineage.pvp.registerCharacter(input);
}, event);

View File

@@ -54,7 +54,8 @@ export default function NessaLanding() {
const { isDark } = useDarkMode(); const { isDark } = useDarkMode();
const iconSrc = () => (isDark() ? ICON_DARK : ICON_DEFAULT); const iconSrc = () => (isDark() ? ICON_DARK : ICON_DEFAULT);
const brandColor = () => site().brandColor; const brandColor = () =>
isDark() ? (site().brandColorDark ?? site().brandColor) : site().brandColor;
return ( return (
<> <>

View File

@@ -3,6 +3,11 @@ import { auditRouter } from "./routers/audit";
import { analyticsRouter } from "./routers/analytics"; import { analyticsRouter } from "./routers/analytics";
import { databaseRouter } from "./routers/database"; import { databaseRouter } from "./routers/database";
import { lineageRouter } from "./routers/lineage"; import { lineageRouter } from "./routers/lineage";
// Re-exported so the REST shim (src/routes/api/lineage/[...path].ts) can mount
// ONLY the lineage sub-router as the trpc-openapi REST surface — not the
// whole appRouter. Keeps nessa/community/auth/audit routers unreachable via
// `/api/lineage/*`.
export { lineageRouter };
import { miscRouter } from "./routers/misc"; import { miscRouter } from "./routers/misc";
import { userRouter } from "./routers/user"; import { userRouter } from "./routers/user";
import { blogRouter } from "./routers/blog"; import { blogRouter } from "./routers/blog";

View File

@@ -6,7 +6,11 @@ import {
} from "~/server/utils"; } from "~/server/utils";
import { env } from "~/env/server"; import { env } from "~/env/server";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { createTRPCRouter, publicProcedure, csrfProtectedProcedure } from "~/server/api/utils"; import {
createTRPCRouter,
publicProcedure,
csrfProtectedProcedure
} from "~/server/api/utils";
import { import {
fetchWithTimeout, fetchWithTimeout,
checkResponse, checkResponse,
@@ -16,8 +20,78 @@ import {
} from "~/server/fetch-utils"; } from "~/server/fetch-utils";
export const lineageDatabaseRouter = createTRPCRouter({ export const lineageDatabaseRouter = createTRPCRouter({
// credentials endpoint removed (p8-008): was exposing persistent DB tokens to clients. // Per-user DB credentials endpoint.
// Database access should be proxied through tRPC server-side procedures. //
// Returns the caller's OWN remote Turso DB name + token so the client can
// open a direct libsql connection (game data syncs across devices). This is
// safe to expose to the authenticated user: the token grants full access only
// to that user's own DB, equivalent to an on-device SQLite that travels
// between devices. The generic p8-008 "exposing persistent DB tokens"
// concern does not apply — there is no cross-user escalation possible.
//
// REST surface: POST /api/lineage/database/creds (auth via Bearer header).
databaseCreds: csrfProtectedProcedure
.input(
z.object({
email: z.string().email(),
provider: z.enum(["email", "apple", "google"])
})
)
.mutation(async ({ input, ctx }) => {
const { email, provider } = input;
// Bearer auth token comes from the Authorization header, exactly as the
// legacy REST endpoint read it. For `email` it's a Lineage JWT; for
// `apple` the apple_user_string; for `google` a Google id token.
const authHeader =
(ctx.event.nativeEvent.node?.req?.headers?.authorization as
| string
| undefined) ??
(ctx.event.request?.headers?.get("authorization") as
| string
| undefined);
const authToken = authHeader?.replace(/^Bearer\s+/i, "").trim();
if (!authToken) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Missing Authorization header"
});
}
const conn = LineageConnectionFactory();
const res = await conn.execute({
sql: `SELECT * FROM User WHERE email = ? AND provider = ? LIMIT 1`,
args: [email, provider]
});
if (res.rows.length === 0) {
throw new TRPCError({
code: "NOT_FOUND",
message: "User not found"
});
}
const userRow = res.rows[0];
const valid = await validateLineageRequest({
auth_token: authToken,
userRow
});
if (!valid) {
throw new TRPCError({
code: "UNAUTHORIZED",
message: "Invalid Verification"
});
}
// The legacy endpoint returned `{ db_name, db_token }`; the User row
// stores these as `database_name` / `database_token`.
return {
db_name: userRow.database_name,
db_token: userRow.database_token
};
}),
deletionInit: csrfProtectedProcedure deletionInit: csrfProtectedProcedure
.input( .input(

View File

@@ -52,7 +52,8 @@ import sanityOptions from "~/lineage-json/misc-route/sanityOptions.json";
import pvpRewards from "~/lineage-json/misc-route/pvpRewards.json"; import pvpRewards from "~/lineage-json/misc-route/pvpRewards.json";
export const lineageJsonServiceRouter = createTRPCRouter({ export const lineageJsonServiceRouter = createTRPCRouter({
attacks: publicProcedure.query(() => { attacks: publicProcedure
.query(() => {
return { return {
ok: true, ok: true,
playerAttacks, playerAttacks,
@@ -68,7 +69,8 @@ export const lineageJsonServiceRouter = createTRPCRouter({
}; };
}), }),
conditions: publicProcedure.query(() => { conditions: publicProcedure
.query(() => {
return { return {
ok: true, ok: true,
conditions, conditions,
@@ -77,7 +79,8 @@ export const lineageJsonServiceRouter = createTRPCRouter({
}; };
}), }),
dungeons: publicProcedure.query(() => { dungeons: publicProcedure
.query(() => {
return { return {
ok: true, ok: true,
dungeons, dungeons,
@@ -85,7 +88,8 @@ export const lineageJsonServiceRouter = createTRPCRouter({
}; };
}), }),
enemies: publicProcedure.query(() => { enemies: publicProcedure
.query(() => {
return { return {
ok: true, ok: true,
bosses, bosses,
@@ -94,7 +98,8 @@ export const lineageJsonServiceRouter = createTRPCRouter({
}; };
}), }),
items: publicProcedure.query(() => { items: publicProcedure
.query(() => {
return { return {
ok: true, ok: true,
arrows, arrows,
@@ -119,7 +124,8 @@ export const lineageJsonServiceRouter = createTRPCRouter({
}; };
}), }),
misc: publicProcedure.query(() => { misc: publicProcedure
.query(() => {
return { return {
ok: true, ok: true,
activities, activities,

View File

@@ -1,4 +1,9 @@
import { createTRPCRouter, publicProcedure, adminProcedure, csrfProtectedProcedure } from "../../utils"; import {
createTRPCRouter,
publicProcedure,
adminProcedure,
csrfProtectedProcedure
} from "../../utils";
import { z } from "zod"; import { z } from "zod";
import { LineageConnectionFactory } from "~/server/utils"; import { LineageConnectionFactory } from "~/server/utils";
import { env } from "~/env/server"; import { env } from "~/env/server";
@@ -15,7 +20,7 @@ export const lineageMiscRouter = createTRPCRouter({
proficiencies: z.record(z.unknown()), proficiencies: z.record(z.unknown()),
jobs: z.record(z.unknown()), jobs: z.record(z.unknown()),
resistanceTable: z.record(z.unknown()), resistanceTable: z.record(z.unknown()),
damageTable: z.record(z.unknown()), damageTable: z.record(z.unknown())
}) })
) )
.mutation(async ({ input }) => { .mutation(async ({ input }) => {
@@ -27,7 +32,7 @@ export const lineageMiscRouter = createTRPCRouter({
proficiencies, proficiencies,
jobs, jobs,
resistanceTable, resistanceTable,
damageTable, damageTable
} = input; } = input;
const conn = LineageConnectionFactory(); const conn = LineageConnectionFactory();
@@ -47,8 +52,8 @@ export const lineageMiscRouter = createTRPCRouter({
JSON.stringify(proficiencies), JSON.stringify(proficiencies),
JSON.stringify(jobs), JSON.stringify(jobs),
JSON.stringify(resistanceTable), JSON.stringify(resistanceTable),
JSON.stringify(damageTable), JSON.stringify(damageTable)
], ]
}); });
return { success: true, status: 200 }; return { success: true, status: 200 };
@@ -56,7 +61,7 @@ export const lineageMiscRouter = createTRPCRouter({
console.error("Analytics error:", e); console.error("Analytics error:", e);
throw new TRPCError({ throw new TRPCError({
code: "INTERNAL_SERVER_ERROR", code: "INTERNAL_SERVER_ERROR",
message: "Failed to store analytics", message: "Failed to store analytics"
}); });
} }
}), }),
@@ -69,7 +74,7 @@ export const lineageMiscRouter = createTRPCRouter({
if (!token) { if (!token) {
throw new TRPCError({ throw new TRPCError({
code: "BAD_REQUEST", code: "BAD_REQUEST",
message: "Missing token in body", message: "Missing token in body"
}); });
} }
@@ -80,11 +85,17 @@ export const lineageMiscRouter = createTRPCRouter({
if (res.rows.length > 0) { if (res.rows.length > 0) {
const queryUpdate = const queryUpdate =
"UPDATE Token SET last_updated_at = datetime('now') WHERE token = ?"; "UPDATE Token SET last_updated_at = datetime('now') WHERE token = ?";
const resUpdate = await conn.execute({ sql: queryUpdate, args: [token] }); const resUpdate = await conn.execute({
sql: queryUpdate,
args: [token]
});
return { success: true, action: "updated", result: resUpdate }; return { success: true, action: "updated", result: resUpdate };
} else { } else {
const queryInsert = "INSERT INTO Token (token) VALUES (?)"; const queryInsert = "INSERT INTO Token (token) VALUES (?)";
const resInsert = await conn.execute({ sql: queryInsert, args: [token] }); const resInsert = await conn.execute({
sql: queryInsert,
args: [token]
});
return { success: true, action: "inserted", result: resInsert }; return { success: true, action: "inserted", result: resInsert };
} }
}), }),
@@ -99,7 +110,7 @@ export const lineageMiscRouter = createTRPCRouter({
try { try {
const res = await conn.execute({ const res = await conn.execute({
sql: `SELECT * FROM Analytics`, sql: `SELECT * FROM Analytics`,
args: [], args: []
}); });
const rows = res.rows.map((row: any) => ({ const rows = res.rows.map((row: any) => ({
@@ -110,7 +121,7 @@ export const lineageMiscRouter = createTRPCRouter({
proficiencies: safeJsonParse(row.proficiencies), proficiencies: safeJsonParse(row.proficiencies),
jobs: safeJsonParse(row.jobs), jobs: safeJsonParse(row.jobs),
resistanceTable: safeJsonParse(row.resistanceTable), resistanceTable: safeJsonParse(row.resistanceTable),
damageTable: safeJsonParse(row.damageTable), damageTable: safeJsonParse(row.damageTable)
})); }));
return { success: true, players: rows }; return { success: true, players: rows };
@@ -118,7 +129,7 @@ export const lineageMiscRouter = createTRPCRouter({
console.error("Failed to fetch lineage analytics:", e); console.error("Failed to fetch lineage analytics:", e);
return { success: false, players: [] }; return { success: false, players: [] };
} }
}), })
}); });
function safeJsonParse(val: unknown): unknown { function safeJsonParse(val: unknown): unknown {

View File

@@ -1,4 +1,8 @@
import { createTRPCRouter, publicProcedure, csrfProtectedProcedure } from "../../utils"; import {
createTRPCRouter,
publicProcedure,
csrfProtectedProcedure
} from "../../utils";
import { z } from "zod"; import { z } from "zod";
import { LineageConnectionFactory } from "~/server/utils"; import { LineageConnectionFactory } from "~/server/utils";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
@@ -17,7 +21,7 @@ const characterSchema = z.object({
resistanceTable: z.string(), resistanceTable: z.string(),
damageTable: z.string(), damageTable: z.string(),
attackStrings: z.string(), attackStrings: z.string(),
knownSpells: z.string(), knownSpells: z.string()
}); });
export const lineagePvpRouter = createTRPCRouter({ export const lineagePvpRouter = createTRPCRouter({
@@ -27,7 +31,7 @@ export const lineagePvpRouter = createTRPCRouter({
character: characterSchema, character: characterSchema,
linkID: z.string(), linkID: z.string(),
pushToken: z.string().optional(), pushToken: z.string().optional(),
pushCurrentlyEnabled: z.boolean().optional(), pushCurrentlyEnabled: z.boolean().optional()
}) })
) )
.mutation(async ({ input }) => { .mutation(async ({ input }) => {
@@ -37,7 +41,7 @@ export const lineagePvpRouter = createTRPCRouter({
const conn = LineageConnectionFactory(); const conn = LineageConnectionFactory();
const res = await conn.execute({ const res = await conn.execute({
sql: `SELECT * FROM PvP_Characters WHERE linkID = ?`, sql: `SELECT * FROM PvP_Characters WHERE linkID = ?`,
args: [linkID], args: [linkID]
}); });
if (res.rows.length === 0) { if (res.rows.length === 0) {
@@ -78,8 +82,8 @@ export const lineagePvpRouter = createTRPCRouter({
character.attackStrings, character.attackStrings,
character.knownSpells, character.knownSpells,
pushToken, pushToken,
pushCurrentlyEnabled, pushCurrentlyEnabled
], ]
}); });
return { return {
@@ -87,7 +91,7 @@ export const lineagePvpRouter = createTRPCRouter({
winCount: 0, winCount: 0,
lossCount: 0, lossCount: 0,
tokenRedemptionCount: 0, tokenRedemptionCount: 0,
status: 201, status: 201
}; };
} else { } else {
await conn.execute({ await conn.execute({
@@ -126,8 +130,8 @@ export const lineagePvpRouter = createTRPCRouter({
character.knownSpells, character.knownSpells,
pushToken, pushToken,
pushCurrentlyEnabled, pushCurrentlyEnabled,
linkID, linkID
], ]
}); });
return { return {
@@ -135,19 +139,20 @@ export const lineagePvpRouter = createTRPCRouter({
winCount: res.rows[0].winCount as number, winCount: res.rows[0].winCount as number,
lossCount: res.rows[0].lossCount as number, lossCount: res.rows[0].lossCount as number,
tokenRedemptionCount: res.rows[0].tokenRedemptionCount as number, tokenRedemptionCount: res.rows[0].tokenRedemptionCount as number,
status: 200, status: 200
}; };
} }
} catch (e) { } catch (e) {
console.error(e); console.error(e);
throw new TRPCError({ throw new TRPCError({
code: "INTERNAL_SERVER_ERROR", code: "INTERNAL_SERVER_ERROR",
message: "Failed to register character", message: "Failed to register character"
}); });
} }
}), }),
getOpponents: publicProcedure.query(async () => { getOpponents: publicProcedure
.query(async () => {
const conn = LineageConnectionFactory(); const conn = LineageConnectionFactory();
try { try {
@@ -179,13 +184,13 @@ export const lineagePvpRouter = createTRPCRouter({
return { return {
ok: true, ok: true,
characters: res.rows, characters: res.rows,
status: 200, status: 200
}; };
} catch (e) { } catch (e) {
console.error(e); console.error(e);
throw new TRPCError({ throw new TRPCError({
code: "INTERNAL_SERVER_ERROR", code: "INTERNAL_SERVER_ERROR",
message: "Failed to get opponents", message: "Failed to get opponents"
}); });
} }
}), }),
@@ -194,7 +199,7 @@ export const lineagePvpRouter = createTRPCRouter({
.input( .input(
z.object({ z.object({
winnerLinkID: z.string(), winnerLinkID: z.string(),
loserLinkID: z.string(), loserLinkID: z.string()
}) })
) )
.mutation(async ({ input }) => { .mutation(async ({ input }) => {
@@ -211,19 +216,19 @@ export const lineagePvpRouter = createTRPCRouter({
lossCount = lossCount + CASE WHEN linkID = ? THEN 1 ELSE 0 END lossCount = lossCount + CASE WHEN linkID = ? THEN 1 ELSE 0 END
WHERE linkID IN (?, ?) WHERE linkID IN (?, ?)
`, `,
args: [winnerLinkID, loserLinkID, winnerLinkID, loserLinkID], args: [winnerLinkID, loserLinkID, winnerLinkID, loserLinkID]
}); });
return { return {
ok: true, ok: true,
status: 200, status: 200
}; };
} catch (e) { } catch (e) {
console.error(e); console.error(e);
throw new TRPCError({ throw new TRPCError({
code: "INTERNAL_SERVER_ERROR", code: "INTERNAL_SERVER_ERROR",
message: "Failed to record battle result", message: "Failed to record battle result"
}); });
} }
}), })
}); });

View File

@@ -181,4 +181,3 @@ const csrfProtection = t.middleware(async ({ ctx, next }) => {
// CSRF-protected procedure // CSRF-protected procedure
export const csrfProtectedProcedure = t.procedure.use(csrfProtection); export const csrfProtectedProcedure = t.procedure.use(csrfProtection);
export { csrfProtection }; export { csrfProtection };