Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/config/src/session-cookie.ts
T
2026-07-08 16:15:37 +02:00

71 lines
2.0 KiB
TypeScript

import type { DomainRoutingConfig } from "./routing.js";
export type SessionCookieSameSite = "lax";
export type SessionCookiePolicy = {
name?: string;
domain?: string;
sameSite: SessionCookieSameSite;
secure: boolean;
httpOnly: boolean;
path: "/";
maxAge?: number;
};
export type ResolveSessionCookiePolicyOptions = {
nodeEnv?: string;
routing: Pick<DomainRoutingConfig, "appBaseDomain" | "protocol">;
name?: string;
maxAge?: number;
};
export type ResolveApiSessionCookiePolicyOptions = Omit<ResolveSessionCookiePolicyOptions, "name">;
const API_SESSION_COOKIE_NAME = "hivegrid_api_session";
export function resolveSessionCookiePolicy({ nodeEnv, routing, name, maxAge }: ResolveSessionCookiePolicyOptions): SessionCookiePolicy {
return {
...(name ? { name } : {}),
...(maxAge === undefined ? {} : { maxAge }),
...resolveCookieDomain(routing.appBaseDomain),
sameSite: "lax",
secure: nodeEnv === "production" || routing.protocol === "https",
httpOnly: true,
path: "/",
};
}
export function resolveApiSessionCookiePolicy(options: ResolveApiSessionCookiePolicyOptions): SessionCookiePolicy {
return resolveSessionCookiePolicy({
...options,
name: API_SESSION_COOKIE_NAME,
});
}
function resolveCookieDomain(appBaseDomain: string): Pick<SessionCookiePolicy, "domain"> {
const hostname = stripPort(appBaseDomain.trim().toLowerCase());
if (!hostname || isLocalCookieHost(hostname)) {
return {};
}
return { domain: hostname };
}
function stripPort(host: string) {
if (host.startsWith("[")) {
return host.slice(1, host.indexOf("]"));
}
const firstColon = host.indexOf(":");
return firstColon === -1 ? host : host.slice(0, firstColon);
}
function isLocalCookieHost(hostname: string) {
return hostname === "localhost" || hostname.endsWith(".localhost") || isIpv4Address(hostname) || hostname === "::1";
}
function isIpv4Address(hostname: string) {
return /^\d{1,3}(?:\.\d{1,3}){3}$/.test(hostname);
}