179 lines
6.5 KiB
TypeScript
179 lines
6.5 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
|
|
import jwt, { type JwtPayload } from "jsonwebtoken";
|
|
|
|
export const CHAT_GATEWAY_TOKEN_ISSUER = "web-app";
|
|
export const CHAT_GATEWAY_TOKEN_AUDIENCE = "team-chat-gateway";
|
|
export const CHAT_GATEWAY_TOKEN_PURPOSE = "team-chat";
|
|
export const CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS = 15 * 60;
|
|
export const CHAT_GATEWAY_TOKEN_DEFAULT_TTL_SECONDS = CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS;
|
|
export const CHAT_GATEWAY_TOKEN_MAX_CLOCK_TOLERANCE_SECONDS = 30;
|
|
export const CHAT_GATEWAY_TOKEN_DEFAULT_CLOCK_TOLERANCE_SECONDS = 15;
|
|
export const CHAT_GATEWAY_MIN_SECRET_BYTES = 32;
|
|
|
|
const MAX_TOKEN_LENGTH = 4_096;
|
|
const MAX_ID_LENGTH = 191;
|
|
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
|
|
const REQUIRED_CLAIMS = ["aud", "exp", "iat", "iss", "jti", "purpose", "sid", "sub", "tenantId"] as const;
|
|
const ALLOWED_CLAIMS = new Set<string>(REQUIRED_CLAIMS);
|
|
|
|
export type ChatGatewayTokenIdentity = {
|
|
readonly userId: string;
|
|
readonly tenantId: string;
|
|
readonly sessionId: string;
|
|
readonly tokenId: string;
|
|
readonly issuedAt: number;
|
|
readonly expiresAt: number;
|
|
};
|
|
|
|
export type IssueChatGatewayTokenInput = {
|
|
readonly userId: string;
|
|
readonly tenantId: string;
|
|
readonly sessionId: string;
|
|
/** Dedicated gateway secret. It must not be shared with Hocuspocus or another audience. */
|
|
readonly secret: string;
|
|
readonly ttlSeconds?: number;
|
|
readonly now?: Date;
|
|
};
|
|
|
|
export type VerifyChatGatewayTokenOptions = {
|
|
/** Dedicated gateway secret. It must not be shared with Hocuspocus or another audience. */
|
|
readonly secret: string;
|
|
readonly clockToleranceSeconds?: number;
|
|
readonly now?: Date;
|
|
};
|
|
|
|
/**
|
|
* Issues the short-lived identity capability used only by the standalone team-chat gateway.
|
|
* Authorization stays server-side: permissions and channel memberships are deliberately absent.
|
|
*/
|
|
export function issueChatGatewayToken(input: IssueChatGatewayTokenInput): string {
|
|
const secret = requireStrongSecret(input.secret);
|
|
const userId = requireIdentifier(input.userId, "userId");
|
|
const tenantId = requireIdentifier(input.tenantId, "tenantId");
|
|
const sessionId = requireIdentifier(input.sessionId, "sessionId");
|
|
const ttlSeconds = input.ttlSeconds ?? CHAT_GATEWAY_TOKEN_DEFAULT_TTL_SECONDS;
|
|
if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1 || ttlSeconds > CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS) {
|
|
throw new Error("Chat gateway token TTL is invalid");
|
|
}
|
|
|
|
const nowSeconds = requireClockTimestamp(input.now);
|
|
const tokenId = randomUUID();
|
|
|
|
return jwt.sign(
|
|
{
|
|
tenantId,
|
|
sid: sessionId,
|
|
purpose: CHAT_GATEWAY_TOKEN_PURPOSE,
|
|
iat: nowSeconds,
|
|
},
|
|
secret,
|
|
{
|
|
algorithm: "HS256",
|
|
audience: CHAT_GATEWAY_TOKEN_AUDIENCE,
|
|
expiresIn: ttlSeconds,
|
|
issuer: CHAT_GATEWAY_TOKEN_ISSUER,
|
|
jwtid: tokenId,
|
|
subject: userId,
|
|
}
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Verifies signature, audience, issuer, lifetime and the exact claim allow-list.
|
|
* Any malformed token or unsafe verifier configuration fails closed with `null`.
|
|
*/
|
|
export function verifyChatGatewayToken(token: string, options: VerifyChatGatewayTokenOptions): ChatGatewayTokenIdentity | null {
|
|
const secret = normalizeStrongSecret(options.secret);
|
|
if (!secret || typeof token !== "string" || token.length === 0 || token.length > MAX_TOKEN_LENGTH) return null;
|
|
|
|
const clockToleranceSeconds = options.clockToleranceSeconds ?? CHAT_GATEWAY_TOKEN_DEFAULT_CLOCK_TOLERANCE_SECONDS;
|
|
if (!Number.isInteger(clockToleranceSeconds) || clockToleranceSeconds < 0 || clockToleranceSeconds > CHAT_GATEWAY_TOKEN_MAX_CLOCK_TOLERANCE_SECONDS) {
|
|
return null;
|
|
}
|
|
|
|
let nowSeconds: number;
|
|
try {
|
|
nowSeconds = requireClockTimestamp(options.now);
|
|
} catch {
|
|
return null;
|
|
}
|
|
|
|
let claims: JwtPayload | string;
|
|
try {
|
|
claims = jwt.verify(token, secret, {
|
|
algorithms: ["HS256"],
|
|
audience: CHAT_GATEWAY_TOKEN_AUDIENCE,
|
|
clockTimestamp: nowSeconds,
|
|
clockTolerance: clockToleranceSeconds,
|
|
issuer: CHAT_GATEWAY_TOKEN_ISSUER,
|
|
maxAge: `${CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS}s`,
|
|
});
|
|
} catch {
|
|
return null;
|
|
}
|
|
|
|
if (typeof claims === "string" || !hasExactClaims(claims)) return null;
|
|
if (claims.iss !== CHAT_GATEWAY_TOKEN_ISSUER || claims.aud !== CHAT_GATEWAY_TOKEN_AUDIENCE) return null;
|
|
if (claims.purpose !== CHAT_GATEWAY_TOKEN_PURPOSE) return null;
|
|
if (!isIdentifier(claims.sub) || !isIdentifier(claims.tenantId) || !isIdentifier(claims.sid)) return null;
|
|
if (typeof claims.jti !== "string" || !UUID_PATTERN.test(claims.jti)) return null;
|
|
if (!Number.isInteger(claims.iat) || !Number.isInteger(claims.exp)) return null;
|
|
|
|
const issuedAt = claims.iat as number;
|
|
const expiresAt = claims.exp as number;
|
|
if (expiresAt <= issuedAt || expiresAt - issuedAt > CHAT_GATEWAY_TOKEN_MAX_TTL_SECONDS) return null;
|
|
if (issuedAt > nowSeconds + clockToleranceSeconds || expiresAt <= nowSeconds - clockToleranceSeconds) return null;
|
|
|
|
return {
|
|
userId: claims.sub,
|
|
tenantId: claims.tenantId,
|
|
sessionId: claims.sid,
|
|
tokenId: claims.jti,
|
|
issuedAt,
|
|
expiresAt,
|
|
};
|
|
}
|
|
|
|
function hasExactClaims(claims: JwtPayload): claims is JwtPayload & {
|
|
aud: string;
|
|
exp: number;
|
|
iat: number;
|
|
iss: string;
|
|
jti: string;
|
|
purpose: string;
|
|
sid: string;
|
|
sub: string;
|
|
tenantId: string;
|
|
} {
|
|
const keys = Object.keys(claims);
|
|
return keys.length === REQUIRED_CLAIMS.length && REQUIRED_CLAIMS.every((claim) => claim in claims) && keys.every((claim) => ALLOWED_CLAIMS.has(claim));
|
|
}
|
|
|
|
function requireStrongSecret(secret: string): string {
|
|
const normalized = normalizeStrongSecret(secret);
|
|
if (!normalized) throw new Error("Chat gateway auth secret is unavailable");
|
|
return normalized;
|
|
}
|
|
|
|
function normalizeStrongSecret(secret: unknown): string | null {
|
|
if (typeof secret !== "string" || secret !== secret.trim()) return null;
|
|
if (Buffer.byteLength(secret, "utf8") < CHAT_GATEWAY_MIN_SECRET_BYTES) return null;
|
|
return secret;
|
|
}
|
|
|
|
function requireIdentifier(value: string, name: "userId" | "tenantId" | "sessionId"): string {
|
|
if (!isIdentifier(value)) throw new Error(`Chat gateway ${name} is invalid`);
|
|
return value;
|
|
}
|
|
|
|
function isIdentifier(value: unknown): value is string {
|
|
return typeof value === "string" && value.length > 0 && value.length <= MAX_ID_LENGTH && value === value.trim() && !value.includes("\u0000");
|
|
}
|
|
|
|
function requireClockTimestamp(now: Date | undefined): number {
|
|
const timestamp = now?.getTime() ?? Date.now();
|
|
if (!Number.isFinite(timestamp)) throw new Error("Chat gateway token clock is invalid");
|
|
return Math.floor(timestamp / 1_000);
|
|
}
|