UNPKG

@bitzonegaming/roleplay-engine-framework

Version:
61 lines (60 loc) 2.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateApiKey = validateApiKey; exports.validateSessionToken = validateSessionToken; const crypto_1 = require("crypto"); const types_1 = require("../types"); const service_1 = require("../../domains/session/service"); const session_1 = require("../../domains/session/models/session"); const errors_1 = require("../../core/errors"); /** * Validates API key from x-api-key header */ async function validateApiKey(request, gamemodeApiKeyHash) { if (!gamemodeApiKeyHash) { throw new errors_1.UnauthorizedError('API_KEY_NOT_CONFIGURED', {}); } const apiKey = request.headers['x-api-key']; if (!apiKey) { throw new errors_1.UnauthorizedError('API_KEY_MISSING', {}); } const hash = (0, crypto_1.createHash)('sha256').update(apiKey).digest('hex'); if (hash !== gamemodeApiKeyHash) { throw new errors_1.UnauthorizedError('INVALID_API_KEY', {}); } } /** * Validates session token from Basic Auth header */ async function validateSessionToken(request, context, scope, accessPolicy) { const authorization = request.headers.authorization; if (!authorization || !authorization.startsWith('Basic ')) { throw new errors_1.UnauthorizedError('SESSION_TOKEN_MISSING', {}); } const credentials = Buffer.from(authorization.slice(6), 'base64').toString('ascii'); const [sessionId, sessionToken] = credentials.split(':'); if (!sessionId || !sessionToken) { throw new errors_1.UnauthorizedError('INVALID_SESSION_TOKEN_FORMAT', {}); } const sessionService = context.getService(service_1.SessionService); const session = sessionService.getSession(sessionId); if (!session) { throw new errors_1.NotFoundError('SESSION_NOT_FOUND', { id: sessionId }); } const tokenHash = (0, session_1.generateSessionTokenHash)(sessionId, sessionToken); if (session.tokenHash !== tokenHash) { throw new errors_1.UnauthorizedError('INVALID_SESSION_TOKEN', {}); } if (scope === types_1.EndpointScope.ACCOUNT && !session.account) { throw new errors_1.ForbiddenError('SESSION_HAS_NOT_AUTHORIZED', {}); } if (scope === types_1.EndpointScope.CHARACTER && !session.character) { throw new errors_1.ForbiddenError('SESSION_IS_NOT_LINKED_TO_A_CHARACTER', {}); } if (accessPolicy) { context.getService(service_1.SessionService).validateAccessPolicy(sessionId, accessPolicy); } request.sessionId = sessionId; request.accountId = session.account?.id; request.characterId = session.character?.id; }