mancala/apps/backend/src/server/ExpressApp.ts
Halit Aksoy 30ad51c493 feat(backend): authenticate WebSocket clients with Keycloak tokens
- New auth module verifies Keycloak access tokens offline against the
  realm's signing keys (issuer, RS256, typ=Bearer, allowed azp); guests
  are recognised by the guest realm role
- Clients send an auth message after connecting and get on_auth or
  on_auth_error; unauthenticated sockets are closed after 5 seconds and
  their messages ignored; a socket can refresh its token but not switch user
- A user can be connected from several sockets; a late close of an old
  socket no longer drops the new one
- Malformed messages are ignored instead of throwing
- Games store player names and guest flags and send them with the
  connection info
- Legacy ?userKey= clients and /register stay available behind
  LEGACY_USERKEY_AUTH; legacy keys must be UUIDs so they cannot take a
  Keycloak user's kc: id
- TypeScript target raised to es2020 for async/await
2026-10-14 01:52:07 +03:00

51 lines
1.6 KiB
TypeScript

import cors from "cors";
import express from "express";
import { Request, Response } from "express";
import morgan from "morgan";
import fs from "fs";
import { generateKey } from "../util/key_factory";
import { GameStore } from "../game/gamestore/GameStore";
export class ExpressApp {
app: Express.Application;
gameStore: GameStore;
legacyUserKeyAuth: boolean;
constructor(params: { gameStore: GameStore, legacyUserKeyAuth: boolean }) {
this.gameStore = params.gameStore;
this.legacyUserKeyAuth = params.legacyUserKeyAuth;
this.app = this.createExpressApp();
}
private createAccessLogMiddleware() {
return morgan("common", {
stream: fs.createWriteStream("./access.log", { flags: "a" }),
});
}
public createExpressApp(): Express.Application {
const app = express();
app.use(cors());
app.use(this.createAccessLogMiddleware());
app.use(morgan("dev"));
app.get("/", (req: Request, res: Response) => {
res.send("Server up and running! ci test1");
});
// Issues userKeys for legacy clients; token clients get their identity from Keycloak.
if (this.legacyUserKeyAuth) {
app.get("/register/", (req: Request, res: Response) => {
res.send(generateKey());
});
}
app.get("/game/:id", (req: Request, res: Response) => {
const gameId = req.params.id;
const game = this.gameStore.get(gameId);
if(game) {
res.send(game)
} else {
res.sendStatus(404)
}
});
return app;
}
}