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

@@ -3,6 +3,11 @@ import { auditRouter } from "./routers/audit";
import { analyticsRouter } from "./routers/analytics";
import { databaseRouter } from "./routers/database";
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 { userRouter } from "./routers/user";
import { blogRouter } from "./routers/blog";

View File

@@ -6,7 +6,11 @@ import {
} from "~/server/utils";
import { env } from "~/env/server";
import { TRPCError } from "@trpc/server";
import { createTRPCRouter, publicProcedure, csrfProtectedProcedure } from "~/server/api/utils";
import {
createTRPCRouter,
publicProcedure,
csrfProtectedProcedure
} from "~/server/api/utils";
import {
fetchWithTimeout,
checkResponse,
@@ -16,8 +20,78 @@ import {
} from "~/server/fetch-utils";
export const lineageDatabaseRouter = createTRPCRouter({
// credentials endpoint removed (p8-008): was exposing persistent DB tokens to clients.
// Database access should be proxied through tRPC server-side procedures.
// Per-user DB credentials endpoint.
//
// 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
.input(

View File

@@ -52,84 +52,90 @@ import sanityOptions from "~/lineage-json/misc-route/sanityOptions.json";
import pvpRewards from "~/lineage-json/misc-route/pvpRewards.json";
export const lineageJsonServiceRouter = createTRPCRouter({
attacks: publicProcedure.query(() => {
return {
ok: true,
playerAttacks,
mageBooks,
mageSpells,
necroBooks,
necroSpells,
rangerBooks,
rangerSpells,
paladinBooks,
paladinSpells,
summons
};
}),
attacks: publicProcedure
.query(() => {
return {
ok: true,
playerAttacks,
mageBooks,
mageSpells,
necroBooks,
necroSpells,
rangerBooks,
rangerSpells,
paladinBooks,
paladinSpells,
summons
};
}),
conditions: publicProcedure.query(() => {
return {
ok: true,
conditions,
debilitations,
sanityDebuffs
};
}),
conditions: publicProcedure
.query(() => {
return {
ok: true,
conditions,
debilitations,
sanityDebuffs
};
}),
dungeons: publicProcedure.query(() => {
return {
ok: true,
dungeons,
specialEncounters
};
}),
dungeons: publicProcedure
.query(() => {
return {
ok: true,
dungeons,
specialEncounters
};
}),
enemies: publicProcedure.query(() => {
return {
ok: true,
bosses,
enemies,
enemyAttacks
};
}),
enemies: publicProcedure
.query(() => {
return {
ok: true,
bosses,
enemies,
enemyAttacks
};
}),
items: publicProcedure.query(() => {
return {
ok: true,
arrows,
bows,
foci,
hats,
junk,
melee,
robes,
wands,
ingredients,
storyItems,
artifacts,
shields,
bodyArmor,
helmets,
suffix,
prefix,
potions,
poison,
staves
};
}),
items: publicProcedure
.query(() => {
return {
ok: true,
arrows,
bows,
foci,
hats,
junk,
melee,
robes,
wands,
ingredients,
storyItems,
artifacts,
shields,
bodyArmor,
helmets,
suffix,
prefix,
potions,
poison,
staves
};
}),
misc: publicProcedure.query(() => {
return {
ok: true,
activities,
investments,
jobs,
manaOptions,
otherOptions,
healthOptions,
sanityOptions,
pvpRewards
};
})
misc: publicProcedure
.query(() => {
return {
ok: true,
activities,
investments,
jobs,
manaOptions,
otherOptions,
healthOptions,
sanityOptions,
pvpRewards
};
})
});

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 { LineageConnectionFactory } from "~/server/utils";
import { env } from "~/env/server";
@@ -15,7 +20,7 @@ export const lineageMiscRouter = createTRPCRouter({
proficiencies: z.record(z.unknown()),
jobs: z.record(z.unknown()),
resistanceTable: z.record(z.unknown()),
damageTable: z.record(z.unknown()),
damageTable: z.record(z.unknown())
})
)
.mutation(async ({ input }) => {
@@ -27,7 +32,7 @@ export const lineageMiscRouter = createTRPCRouter({
proficiencies,
jobs,
resistanceTable,
damageTable,
damageTable
} = input;
const conn = LineageConnectionFactory();
@@ -47,8 +52,8 @@ export const lineageMiscRouter = createTRPCRouter({
JSON.stringify(proficiencies),
JSON.stringify(jobs),
JSON.stringify(resistanceTable),
JSON.stringify(damageTable),
],
JSON.stringify(damageTable)
]
});
return { success: true, status: 200 };
@@ -56,7 +61,7 @@ export const lineageMiscRouter = createTRPCRouter({
console.error("Analytics error:", e);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to store analytics",
message: "Failed to store analytics"
});
}
}),
@@ -69,7 +74,7 @@ export const lineageMiscRouter = createTRPCRouter({
if (!token) {
throw new TRPCError({
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) {
const queryUpdate =
"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 };
} else {
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 };
}
}),
@@ -99,7 +110,7 @@ export const lineageMiscRouter = createTRPCRouter({
try {
const res = await conn.execute({
sql: `SELECT * FROM Analytics`,
args: [],
args: []
});
const rows = res.rows.map((row: any) => ({
@@ -110,7 +121,7 @@ export const lineageMiscRouter = createTRPCRouter({
proficiencies: safeJsonParse(row.proficiencies),
jobs: safeJsonParse(row.jobs),
resistanceTable: safeJsonParse(row.resistanceTable),
damageTable: safeJsonParse(row.damageTable),
damageTable: safeJsonParse(row.damageTable)
}));
return { success: true, players: rows };
@@ -118,7 +129,7 @@ export const lineageMiscRouter = createTRPCRouter({
console.error("Failed to fetch lineage analytics:", e);
return { success: false, players: [] };
}
}),
})
});
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 { LineageConnectionFactory } from "~/server/utils";
import { TRPCError } from "@trpc/server";
@@ -17,7 +21,7 @@ const characterSchema = z.object({
resistanceTable: z.string(),
damageTable: z.string(),
attackStrings: z.string(),
knownSpells: z.string(),
knownSpells: z.string()
});
export const lineagePvpRouter = createTRPCRouter({
@@ -27,7 +31,7 @@ export const lineagePvpRouter = createTRPCRouter({
character: characterSchema,
linkID: z.string(),
pushToken: z.string().optional(),
pushCurrentlyEnabled: z.boolean().optional(),
pushCurrentlyEnabled: z.boolean().optional()
})
)
.mutation(async ({ input }) => {
@@ -37,7 +41,7 @@ export const lineagePvpRouter = createTRPCRouter({
const conn = LineageConnectionFactory();
const res = await conn.execute({
sql: `SELECT * FROM PvP_Characters WHERE linkID = ?`,
args: [linkID],
args: [linkID]
});
if (res.rows.length === 0) {
@@ -78,8 +82,8 @@ export const lineagePvpRouter = createTRPCRouter({
character.attackStrings,
character.knownSpells,
pushToken,
pushCurrentlyEnabled,
],
pushCurrentlyEnabled
]
});
return {
@@ -87,7 +91,7 @@ export const lineagePvpRouter = createTRPCRouter({
winCount: 0,
lossCount: 0,
tokenRedemptionCount: 0,
status: 201,
status: 201
};
} else {
await conn.execute({
@@ -126,8 +130,8 @@ export const lineagePvpRouter = createTRPCRouter({
character.knownSpells,
pushToken,
pushCurrentlyEnabled,
linkID,
],
linkID
]
});
return {
@@ -135,24 +139,25 @@ export const lineagePvpRouter = createTRPCRouter({
winCount: res.rows[0].winCount as number,
lossCount: res.rows[0].lossCount as number,
tokenRedemptionCount: res.rows[0].tokenRedemptionCount as number,
status: 200,
status: 200
};
}
} catch (e) {
console.error(e);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to register character",
message: "Failed to register character"
});
}
}),
getOpponents: publicProcedure.query(async () => {
const conn = LineageConnectionFactory();
getOpponents: publicProcedure
.query(async () => {
const conn = LineageConnectionFactory();
try {
const res = await conn.execute(
`
try {
const res = await conn.execute(
`
SELECT playerClass,
blessing,
name,
@@ -174,27 +179,27 @@ export const lineagePvpRouter = createTRPCRouter({
ORDER BY RANDOM()
LIMIT 3
`
);
);
return {
ok: true,
characters: res.rows,
status: 200,
};
} catch (e) {
console.error(e);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to get opponents",
});
}
}),
return {
ok: true,
characters: res.rows,
status: 200
};
} catch (e) {
console.error(e);
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to get opponents"
});
}
}),
battleResult: csrfProtectedProcedure
.input(
z.object({
winnerLinkID: z.string(),
loserLinkID: z.string(),
loserLinkID: z.string()
})
)
.mutation(async ({ input }) => {
@@ -211,19 +216,19 @@ export const lineagePvpRouter = createTRPCRouter({
lossCount = lossCount + CASE WHEN linkID = ? THEN 1 ELSE 0 END
WHERE linkID IN (?, ?)
`,
args: [winnerLinkID, loserLinkID, winnerLinkID, loserLinkID],
args: [winnerLinkID, loserLinkID, winnerLinkID, loserLinkID]
});
return {
ok: true,
status: 200,
status: 200
};
} catch (e) {
console.error(e);
throw new TRPCError({
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
export const csrfProtectedProcedure = t.procedure.use(csrfProtection);
export { csrfProtection };