diff --git a/src/server/Gatekeeper.ts b/src/server/Gatekeeper.ts index 97a98c6e9..2a828f25c 100644 --- a/src/server/Gatekeeper.ts +++ b/src/server/Gatekeeper.ts @@ -26,6 +26,18 @@ export interface Gatekeeper { ) => (message: string) => Promise; } +let gk: Gatekeeper = null; + +async function getGatekeeperCached(): Promise { + if (gk != null) { + return gk; + } + return getGatekeeper().then((g) => { + gk = g; + return gk; + }); +} + // Function to get the appropriate security middleware implementation async function getGatekeeper(): Promise { try { @@ -78,6 +90,41 @@ async function getGatekeeper(): Promise { } } +export class GatekeeperWrapper implements Gatekeeper { + constructor(private getGK: () => Promise) {} + + httpHandler( + limiterType: LimiterType, + fn: (req: Request, res: Response, next: NextFunction) => Promise, + ) { + return async (req: Request, res: Response, next: NextFunction) => { + try { + const gk = await this.getGK(); + const handler = gk.httpHandler(limiterType, fn); + return handler(req, res, next); + } catch (error) { + next(error); + } + }; + } + + // Corrected implementation for WebSocket handler wrapper + wsHandler( + req: http.IncomingMessage | string, + fn: (message: string) => Promise, + ) { + return async (message: string) => { + try { + const gk = await this.getGK(); + const handler = gk.wsHandler(req, fn); + return handler(message); + } catch (error) { + console.error("WebSocket handler error:", error); + } + }; + } +} + export class NoOpGatekeeper implements Gatekeeper { // Simple pass-through with no rate limiting httpHandler( @@ -108,17 +155,6 @@ export class NoOpGatekeeper implements Gatekeeper { } } -// Initialize the security middleware with a default implementation -// We'll use the NoOpSecurityMiddleware initially and then replace it -// with the real implementation once it's loaded -export const gatekeeper: Gatekeeper = new NoOpGatekeeper(); - -// Immediately try to load the real middleware -getGatekeeper() - .then((middleware) => { - // Replace the methods of securityMiddleware with those from the loaded middleware - Object.assign(gatekeeper, middleware); - }) - .catch((error) => { - console.error("Failed to initialize gatekeeper:", error); - }); +export const gatekeeper: Gatekeeper = new GatekeeperWrapper(() => + getGatekeeperCached(), +); diff --git a/src/server/gatekeeper b/src/server/gatekeeper index 97ef39f2e..ca3525eca 160000 --- a/src/server/gatekeeper +++ b/src/server/gatekeeper @@ -1 +1 @@ -Subproject commit 97ef39f2e47684adbb6a94852a8a350da49937ef +Subproject commit ca3525eca143d6c00e7bf8323d0e1b2f53387eb9