Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+110
@@ -0,0 +1,110 @@
|
||||
import { CHAT_PERMISSIONS, chatErrors } from "@hivegrid/chat";
|
||||
import { CHAT_GATEWAY_MIN_SECRET_BYTES, CHAT_GATEWAY_TOKEN_DEFAULT_TTL_SECONDS, issueChatGatewayToken } from "@hivegrid/chat/gateway-auth.server";
|
||||
import { CatalogError } from "@hivegrid/foundation";
|
||||
import type { ActionFunctionArgs } from "react-router";
|
||||
|
||||
import { loadChatContext, requireChatPermission } from "~/modules/chat/routes/chatAccess.server";
|
||||
import { checkChatGatewayTokenRateLimit } from "~/modules/chat/services/chatGatewayRateLimit.server";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { getUserInfo, getValidatedServerSession, validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
const TOKEN_REFRESH_SKEW_SECONDS = 60;
|
||||
const MIN_TOKEN_TTL_SECONDS = 5;
|
||||
const NO_STORE_HEADERS = { "cache-control": "no-store", pragma: "no-cache" } as const;
|
||||
const logger = createScopedLogger("chat.gateway-token");
|
||||
|
||||
export const loader = () => new Response(null, { status: 404 });
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
if (request.method !== "POST") {
|
||||
return new Response(null, { status: 405, headers: { allow: "POST", ...NO_STORE_HEADERS } });
|
||||
}
|
||||
|
||||
let context;
|
||||
try {
|
||||
context = requireChatPermission(await loadChatContext({ request, params }), CHAT_PERMISSIONS.readOwnChannels);
|
||||
} catch (error) {
|
||||
if (error instanceof CatalogError) return new Response(null, { status: 404 });
|
||||
throw error;
|
||||
}
|
||||
|
||||
await validateCSRFToken(request, { headerOnly: true });
|
||||
const userInfo = await getUserInfo(request);
|
||||
if (userInfo.impersonatingFromUserId || userInfo.userId !== context.userId) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
|
||||
const session = await getValidatedServerSession(request, userInfo);
|
||||
if (!session || !("user" in session) || session.userId !== context.userId) {
|
||||
return new Response(null, { status: 404 });
|
||||
}
|
||||
|
||||
const secret = process.env.CHAT_GATEWAY_AUTH_SECRET ?? "";
|
||||
if (secret !== secret.trim() || Buffer.byteLength(secret, "utf8") < CHAT_GATEWAY_MIN_SECRET_BYTES) {
|
||||
return Response.json(
|
||||
{ ok: false, error: chatErrors.realtimeUnavailable.i18nKey, code: chatErrors.realtimeUnavailable.code },
|
||||
{ status: chatErrors.realtimeUnavailable.status, headers: NO_STORE_HEADERS }
|
||||
);
|
||||
}
|
||||
|
||||
let rateLimit;
|
||||
try {
|
||||
rateLimit = await checkChatGatewayTokenRateLimit({
|
||||
tenantId: context.tenantId,
|
||||
userId: context.userId,
|
||||
sessionId: session.id,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.warn(
|
||||
{
|
||||
tenantId: context.tenantId,
|
||||
userId: context.userId,
|
||||
errorName: error instanceof Error ? error.name : "Error",
|
||||
},
|
||||
"Chat gateway token rate limiter failed"
|
||||
);
|
||||
return Response.json(
|
||||
{ ok: false, error: chatErrors.realtimeUnavailable.i18nKey, code: chatErrors.realtimeUnavailable.code },
|
||||
{ status: chatErrors.realtimeUnavailable.status, headers: NO_STORE_HEADERS }
|
||||
);
|
||||
}
|
||||
if (!rateLimit.allowed) {
|
||||
return Response.json(
|
||||
{ ok: false, error: chatErrors.realtimeRateLimited.i18nKey, code: chatErrors.realtimeRateLimited.code },
|
||||
{
|
||||
status: chatErrors.realtimeRateLimited.status,
|
||||
headers: { ...NO_STORE_HEADERS, "retry-after": String(rateLimit.retryAfterSeconds) },
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const sessionExpiryMs = session.expiresAt instanceof Date ? session.expiresAt.getTime() : Number.NaN;
|
||||
const remainingSessionSeconds = Math.floor((sessionExpiryMs - now.getTime()) / 1_000);
|
||||
const expiresIn = Math.min(CHAT_GATEWAY_TOKEN_DEFAULT_TTL_SECONDS, remainingSessionSeconds);
|
||||
if (!Number.isFinite(expiresIn) || expiresIn < MIN_TOKEN_TTL_SECONDS) {
|
||||
return new Response(null, { status: 404, headers: NO_STORE_HEADERS });
|
||||
}
|
||||
const refreshSkew = Math.min(TOKEN_REFRESH_SKEW_SECONDS, Math.max(1, Math.floor(expiresIn / 5)));
|
||||
|
||||
const token = issueChatGatewayToken({
|
||||
userId: context.userId,
|
||||
tenantId: context.tenantId,
|
||||
sessionId: session.id,
|
||||
secret,
|
||||
ttlSeconds: expiresIn,
|
||||
now,
|
||||
});
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
ok: true,
|
||||
data: {
|
||||
token,
|
||||
expiresIn,
|
||||
refreshAfter: expiresIn - refreshSkew,
|
||||
},
|
||||
},
|
||||
{ headers: NO_STORE_HEADERS }
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user