/** * The session credentials a successful sign-in hands to the game: a session token and a JWT. * Nothing local checks them (the char service identifies the player by the uidhint header); * they only have to be well-formed for the game's own use. */ import { createHmac, randomBytes } from 'node:crypto'; import type { Account } from '../accounts/account-store.ts'; /** Seconds a session stays valid; long enough that the game never has to renew it. */ const SESSION_LIFETIME_SECONDS = 365 * 24 * 60 * 60; const signingKey = randomBytes(32); export interface SessionCredentials { readonly token: string; readonly jwt: string; /** Unix time in seconds. */ readonly expires: number; } export function issueCredentials(account: Account): SessionCredentials { const issued = Math.floor(Date.now() / 1000); const expires = issued + SESSION_LIFETIME_SECONDS; const uidHex = BigInt(account.userId).toString(16).padStart(16, '0'); const token = `${uidHex}${randomBytes(8).toString('hex')}`; return { token, jwt: jwt({ uid: account.userId, nick: account.nick, iat: issued, exp: expires }), expires }; } /** Extract the user id encoded in a session token issued by issueCredentials. */ export function userIdFromToken(token: string | undefined): string | undefined { if (!token || !/^[0-9a-f]{32}$/i.test(token)) return undefined; const id = BigInt(`0x${token.slice(0, 16)}`); return id > 0n ? id.toString(10) : undefined; } /** Extract the user id from a JWT issued by issueCredentials. */ export function userIdFromJwt(token: string | undefined): string | undefined { if (!token) return undefined; const parts = token.split('.'); if (parts.length !== 3 || !parts[1]) return undefined; try { const parsed = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as { uid?: unknown }; return typeof parsed.uid === 'string' && /^\d+$/.test(parsed.uid) ? parsed.uid : undefined; } catch { return undefined; } } function jwt(claims: object): string { const header = base64Url(JSON.stringify({ alg: 'HS256', typ: 'JWT' })); const payload = base64Url(JSON.stringify(claims)); const signature = createHmac('sha256', signingKey).update(`${header}.${payload}`).digest('base64url'); return `${header}.${payload}.${signature}`; } function base64Url(text: string): string { return Buffer.from(text, 'utf8').toString('base64url'); }