Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,18 +1,25 @@
// @vitest-environment node
import { describe, expect, it, vi } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
type TestWebConfig = {
nodeEnv: string;
sessionSecret: string;
i18n: {
enabledLocales: readonly ["de", "en"];
};
routing: {
appBaseDomain: string;
protocol: "http" | "https";
webAppHost?: string;
adminAppHost?: string;
apiHost?: string;
};
};
const testWebConfig: TestWebConfig = {
nodeEnv: "test",
sessionSecret: "dGVzdC1zZXNzaW9uLXNlY3JldC13aXRoLWVub3VnaC1lbnRyb3B5LTEyMzQ1Njc4OTA=",
i18n: { enabledLocales: ["de", "en"] },
routing: {
appBaseDomain: "localhost",
protocol: "http",
@@ -28,50 +35,42 @@ vi.doMock("@hivegrid/config", async () => {
});
vi.mock("./db/tenants.db.server", () => ({
getMyTenants: vi.fn(),
getTenant: vi.fn(),
getTenantSessionIdentityForUser: vi.fn(),
}));
vi.mock("./db/users.db.server", () => ({
getUser: vi.fn(),
}));
// R-P2a S4b — Store/Lifecycle hinter dem additiven Revoke-Check mocken, um die Revoke-Durchsetzung
// in requireUserId deterministisch zu testen.
const authStoreMock = vi.hoisted(() => ({ getActiveSessionByToken: vi.fn() }));
const adminSessionStoreMock = vi.hoisted(() => ({ getActiveAdminSessionByToken: vi.fn() }));
const sessionLifecycleMock = vi.hoisted(() => ({ endServerSession: vi.fn(), startServerSession: vi.fn() }));
vi.mock("~/services/auth/sessionStore.server", () => ({
getActiveSessionByToken: (...args: unknown[]) => authStoreMock.getActiveSessionByToken(...args),
}));
vi.mock("@hivegrid/db/admin-sessions.server", () => ({
getActiveAdminSessionByToken: (...args: unknown[]) => adminSessionStoreMock.getActiveAdminSessionByToken(...args),
}));
vi.mock("~/services/auth/sessionLifecycle.server", () => ({
endServerSession: vi.fn(),
startServerSession: vi.fn(),
endServerSession: (...args: unknown[]) => sessionLifecycleMock.endServerSession(...args),
startServerSession: (...args: unknown[]) => sessionLifecycleMock.startServerSession(...args),
extractSessionDeviceContext: vi.fn(),
}));
let sessionModule = await import("./session.server");
let { createUserSession, generateCSRFToken, getUserInfo, requireUser, requireUserId, setCSRFToken, storage, validateCSRFToken } =
let { createUserSession, generateCSRFToken, getUserInfo, getValidatedServerSession, requireUser, requireUserId, setCSRFToken, storage, validateCSRFToken } =
sessionModule;
async function importSessionServerWithConfig(config: typeof testWebConfig) {
Object.assign(testWebConfig, config);
vi.resetModules();
sessionModule = await import("./session.server");
({ createUserSession, generateCSRFToken, getUserInfo, requireUser, requireUserId, setCSRFToken, storage, validateCSRFToken } =
({ createUserSession, generateCSRFToken, getUserInfo, getValidatedServerSession, requireUser, requireUserId, setCSRFToken, storage, validateCSRFToken } =
sessionModule);
return sessionModule;
}
async function requestWithSession({
body,
csrf,
headers,
legacyCrsf,
}: {
body?: BodyInit;
csrf?: string;
headers?: HeadersInit;
legacyCrsf?: string;
}) {
async function requestWithSession({ body, csrf, headers, legacyCrsf }: { body?: BodyInit; csrf?: string; headers?: HeadersInit; legacyCrsf?: string }) {
const session = await storage.getSession();
if (csrf !== undefined) session.set("csrf", csrf);
if (legacyCrsf !== undefined) session.set("crsf", legacyCrsf);
@@ -86,61 +85,84 @@ async function requestWithSession({
});
}
describe("setLoggedUser tenant caching", () => {
it("fetches the tenant once and exposes it on the result so callers can skip a second getTenant", async () => {
beforeEach(() => {
authStoreMock.getActiveSessionByToken.mockReset();
authStoreMock.getActiveSessionByToken.mockImplementation(async () => ({ id: "session-1", userId: "user-1" }));
adminSessionStoreMock.getActiveAdminSessionByToken.mockReset();
adminSessionStoreMock.getActiveAdminSessionByToken.mockImplementation(async () => ({ id: "admin-session-1", adminUserId: "admin-1" }));
sessionLifecycleMock.endServerSession.mockReset();
sessionLifecycleMock.startServerSession.mockReset();
sessionLifecycleMock.startServerSession.mockImplementation(async ({ userId }: { userId: string }) => `tok:${userId}`);
});
describe("setLoggedUser tenant identity", () => {
it("binds the authenticated user while resolving the first RLS-protected tenant", async () => {
const tenants = await import("./db/tenants.db.server");
const getTenantMock = vi.mocked(tenants.getTenant);
const getMyTenantsMock = vi.mocked(tenants.getMyTenants);
getTenantMock.mockReset();
getMyTenantsMock.mockReset();
getTenantMock.mockResolvedValue({ id: "tenant-1", slug: "tenant-1", name: "T1" } as never);
const { getRlsExecutionContext } = await import("@hivegrid/db/rls-context.server");
const getTenantSessionIdentityMock = vi.mocked(tenants.getTenantSessionIdentityForUser);
getTenantSessionIdentityMock.mockReset();
getTenantSessionIdentityMock.mockImplementation(async () => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "user-1" });
return { id: "tenant-1", slug: "tenant-1", name: "T1", active: true, deactivatedReason: null };
});
const { setLoggedUser } = await import("./session.server");
await expect(setLoggedUser({ id: "user-1", email: "u@example.com", defaultTenantId: "tenant-1" })).resolves.toMatchObject({
userId: "user-1",
defaultTenantId: "tenant-1",
});
expect(getRlsExecutionContext()).toBeNull();
});
it("fetches a safe tenant identity once and exposes it to auth completion", async () => {
const tenants = await import("./db/tenants.db.server");
const getTenantSessionIdentityMock = vi.mocked(tenants.getTenantSessionIdentityForUser);
getTenantSessionIdentityMock.mockReset();
getTenantSessionIdentityMock.mockResolvedValue({ id: "tenant-1", slug: "tenant-1", name: "T1", active: true, deactivatedReason: null });
const { setLoggedUser } = await import("./session.server");
const result = await setLoggedUser({ id: "user-1", email: "u@example.com", defaultTenantId: "tenant-1" });
expect(getTenantMock).toHaveBeenCalledTimes(1);
expect(getMyTenantsMock).not.toHaveBeenCalled();
expect(getTenantSessionIdentityMock).toHaveBeenCalledOnce();
expect(getTenantSessionIdentityMock).toHaveBeenCalledWith({ userId: "user-1", tenant: "tenant-1" });
expect(result).toEqual({
userId: "user-1",
defaultTenantId: "tenant-1",
defaultTenant: { id: "tenant-1", slug: "tenant-1", name: "T1" },
defaultTenant: { id: "tenant-1", slug: "tenant-1", name: "T1", active: true, deactivatedReason: null },
});
});
it("falls back to the first tenant membership when the stored default tenant is missing", async () => {
const tenants = await import("./db/tenants.db.server");
const getTenantMock = vi.mocked(tenants.getTenant);
const getMyTenantsMock = vi.mocked(tenants.getMyTenants);
getTenantMock.mockReset();
getMyTenantsMock.mockReset();
getTenantMock.mockResolvedValue(null);
getMyTenantsMock.mockResolvedValue([{ id: "tenant-fallback", slug: "fallback", name: "Fallback" }] as never);
const getTenantSessionIdentityMock = vi.mocked(tenants.getTenantSessionIdentityForUser);
getTenantSessionIdentityMock.mockReset();
getTenantSessionIdentityMock
.mockResolvedValueOnce(null)
.mockResolvedValueOnce({ id: "tenant-fallback", slug: "fallback", name: "Fallback", active: true, deactivatedReason: null });
const { setLoggedUser } = await import("./session.server");
const result = await setLoggedUser({ id: "user-1", email: "u@example.com", defaultTenantId: "tenant-missing" });
expect(getTenantMock).toHaveBeenCalledWith("tenant-missing");
expect(getMyTenantsMock).toHaveBeenCalledWith("user-1");
expect(getTenantSessionIdentityMock).toHaveBeenNthCalledWith(1, { userId: "user-1", tenant: "tenant-missing" });
expect(getTenantSessionIdentityMock).toHaveBeenNthCalledWith(2, { userId: "user-1" });
expect(result).toEqual({
userId: "user-1",
defaultTenantId: "tenant-fallback",
defaultTenant: null,
defaultTenant: { id: "tenant-fallback", slug: "fallback", name: "Fallback", active: true, deactivatedReason: null },
});
});
it("returns an empty default tenant id when the user has no tenant memberships", async () => {
const tenants = await import("./db/tenants.db.server");
const getTenantMock = vi.mocked(tenants.getTenant);
const getMyTenantsMock = vi.mocked(tenants.getMyTenants);
getTenantMock.mockReset();
getMyTenantsMock.mockReset();
getMyTenantsMock.mockResolvedValue([]);
const getTenantSessionIdentityMock = vi.mocked(tenants.getTenantSessionIdentityForUser);
getTenantSessionIdentityMock.mockReset();
getTenantSessionIdentityMock.mockResolvedValue(null);
const { setLoggedUser } = await import("./session.server");
const result = await setLoggedUser({ id: "user-1", email: "u@example.com", defaultTenantId: null });
expect(getTenantMock).not.toHaveBeenCalled();
expect(getMyTenantsMock).toHaveBeenCalledWith("user-1");
expect(getTenantSessionIdentityMock).toHaveBeenCalledWith({ userId: "user-1" });
expect(result).toEqual({
userId: "user-1",
defaultTenantId: "",
@@ -165,8 +187,8 @@ describe("session cookie policy", () => {
const header = await storage.commitSession(session);
expect(header).toContain("hivegrid_session=");
expect(header).toContain("Domain=example.com");
expect(header).toContain("__Host-hivegrid_app_session=");
expect(header).not.toContain("Domain=");
expect(header).toContain("SameSite=Lax");
expect(header).toContain("Secure");
expect(header).toContain("HttpOnly");
@@ -185,7 +207,7 @@ describe("session cookie policy", () => {
});
const header = await storage.commitSession(await storage.getSession());
expect(header).toContain("hivegrid_session=");
expect(header).toContain("hivegrid_app_session=");
expect(header).not.toContain("Domain=");
expect(header).not.toContain("Secure");
});
@@ -202,7 +224,7 @@ describe("session cookie policy", () => {
});
const header = await storage.commitSession(await storage.getSession());
expect(header).toContain("hivegrid_session=");
expect(header).toContain("hivegrid_app_session=");
// Restore the canonical test config so subsequent suites see a signed cookie.
await importSessionServerWithConfig({
@@ -214,6 +236,42 @@ describe("session cookie policy", () => {
},
});
});
it("selects separate host-only app and admin cookie namespaces from the request host", async () => {
const module = await importSessionServerWithConfig({
nodeEnv: "production",
sessionSecret: "production-session-secret-with-enough-entropy",
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
protocol: "https",
},
});
const appSession = await module.getUserSession(new Request("https://app.example.test/login"));
appSession.set("surface", "app");
const appHeader = await module.commitSession(appSession);
const adminSession = await module.getUserSession(new Request("https://admin.example.test/login"));
adminSession.set("surface", "admin");
const adminHeader = await module.commitSession(adminSession);
expect(appHeader).toContain("__Host-hivegrid_app_session=");
expect(adminHeader).toContain("__Host-hivegrid_admin_session=");
expect(appHeader).not.toContain("Domain=");
expect(adminHeader).not.toContain("Domain=");
const plantedAppCookie = appHeader.split(";")[0];
const adminRead = await module.getUserSession(new Request("https://admin.example.test/dashboard", { headers: { Cookie: plantedAppCookie } }));
expect(adminRead.get("surface")).toBeUndefined();
await importSessionServerWithConfig({
nodeEnv: "test",
sessionSecret: "dGVzdC1zZXNzaW9uLXNlY3JldC13aXRoLWVub3VnaC1lbnRyb3B5LTEyMzQ1Njc4OTA=",
routing: { appBaseDomain: "localhost", protocol: "http" },
});
});
});
describe("session CSRF helpers", () => {
@@ -373,9 +431,7 @@ describe("session CSRF helpers", () => {
});
const consumed = await request.formData();
await expect(validateCSRFToken(request, { formData: consumed })).rejects.toThrow(
"CSRF tokens do not match, try refreshing the page.",
);
await expect(validateCSRFToken(request, { formData: consumed })).rejects.toThrow("CSRF tokens do not match, try refreshing the page.");
});
it("treats blank injected formData csrf values as missing request tokens", async () => {
@@ -437,6 +493,7 @@ describe("session user guards", () => {
it("requireUserId returns the current user id from the session", async () => {
const session = await storage.getSession();
session.set("userId", "user-1");
session.set("sessionToken", "tok-active");
const request = new Request("https://example.test/app/settings", {
headers: { Cookie: (await storage.commitSession(session)).split(";")[0] },
});
@@ -464,6 +521,7 @@ describe("session user guards", () => {
const getUserMock = vi.mocked(users.getUser);
const session = await storage.getSession();
session.set("userId", "user-1");
session.set("sessionToken", "tok-active");
const request = new Request("https://example.test/app", {
headers: { Cookie: (await storage.commitSession(session)).split(";")[0] },
});
@@ -512,19 +570,99 @@ describe("requireUserId server-session revocation (R-P2a S4b)", () => {
});
it("allows the request when the server session is still active", async () => {
authStoreMock.getActiveSessionByToken.mockResolvedValueOnce({ id: "s1" });
authStoreMock.getActiveSessionByToken.mockResolvedValueOnce({ id: "s1", userId: "user-1" });
await expect(requireUserId(await requestWithToken("tok-active"))).resolves.toBe("user-1");
});
it("fails open (treats the session as valid) when the revoke check throws", async () => {
it("fails closed when the session store throws", async () => {
authStoreMock.getActiveSessionByToken.mockRejectedValueOnce(new Error("db down"));
await expect(requireUserId(await requestWithToken("tok-error"))).resolves.toBe("user-1");
await expect(requireUserId(await requestWithToken("tok-error"))).rejects.toMatchObject({ status: 302 });
});
it("fails open and labels the error generically when the revoke check rejects with a non-Error", async () => {
// Non-Error rejection drives the `error instanceof Error ? error.name : "Error"` fallback.
it("fails closed when the session store rejects with a non-Error", async () => {
authStoreMock.getActiveSessionByToken.mockRejectedValueOnce("boom not an error");
await expect(requireUserId(await requestWithToken("tok-string-error"))).resolves.toBe("user-1");
await expect(requireUserId(await requestWithToken("tok-string-error"))).rejects.toMatchObject({ status: 302 });
});
it("rejects authenticated cookies without a server-session token", async () => {
const session = await storage.getSession();
session.set("userId", "user-1");
const request = new Request("https://example.test/app/x", {
headers: { Cookie: (await storage.commitSession(session)).split(";")[0] },
});
await expect(requireUserId(request)).rejects.toMatchObject({ status: 302 });
expect(authStoreMock.getActiveSessionByToken).not.toHaveBeenCalled();
});
it("rejects a valid token owned by another user", async () => {
authStoreMock.getActiveSessionByToken.mockResolvedValueOnce({ id: "s-foreign", userId: "user-2" });
await expect(requireUserId(await requestWithToken("tok-foreign"))).rejects.toMatchObject({ status: 302 });
});
it("deduplicates server-session validation for repeated reads on one request", async () => {
const request = await requestWithToken("tok-active");
const info = await getUserInfo(request);
expect(info).toMatchObject({ userId: "user-1" });
await expect(getUserInfo(request)).resolves.toMatchObject({ userId: "user-1" });
await expect(getValidatedServerSession(request, info)).resolves.toMatchObject({ userId: "user-1" });
expect(authStoreMock.getActiveSessionByToken).toHaveBeenCalledTimes(1);
});
it("returns no validated row for anonymous, tokenless, and inactive sessions", async () => {
const request = new Request("https://example.test/app/x");
await expect(getValidatedServerSession(request)).resolves.toBeNull();
await expect(
getValidatedServerSession(request, {
userId: "user-1",
lightOrDarkMode: "",
lng: "de",
cookies: [],
})
).resolves.toBeNull();
authStoreMock.getActiveSessionByToken.mockResolvedValueOnce(null);
await expect(
getValidatedServerSession(request, {
userId: "user-1",
lightOrDarkMode: "",
lng: "de",
cookies: [],
sessionToken: "tok-inactive",
})
).resolves.toBeNull();
});
it("validates admin-host tokens against the admin session store", async () => {
const module = await importSessionServerWithConfig({
nodeEnv: "production",
sessionSecret: "production-session-secret-with-enough-entropy",
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
protocol: "https",
},
});
const session = await module.getUserSession(new Request("https://admin.example.test/login"));
session.set("userId", "admin-1");
session.set("sessionToken", "admin-token");
const request = new Request("https://admin.example.test/dashboard", {
headers: { Cookie: (await module.commitSession(session)).split(";")[0] },
});
await expect(module.getValidatedServerSession(request)).resolves.toMatchObject({ adminUserId: "admin-1" });
expect(adminSessionStoreMock.getActiveAdminSessionByToken).toHaveBeenCalledWith("admin-token");
expect(authStoreMock.getActiveSessionByToken).not.toHaveBeenCalled();
await importSessionServerWithConfig({
nodeEnv: "test",
sessionSecret: "dGVzdC1zZXNzaW9uLXNlY3JldC13aXRoLWVub3VnaC1lbnRyb3B5LTEyMzQ1Njc4OTA=",
routing: { appBaseDomain: "localhost", protocol: "http" },
});
});
});
@@ -537,6 +675,7 @@ describe("getUserInfo session token exposure", () => {
headers: { Cookie: (await storage.commitSession(session)).split(";")[0] },
});
authStoreMock.getActiveSessionByToken.mockResolvedValueOnce({ id: "s1", userId: "user-1" });
await expect(getUserInfo(request)).resolves.toMatchObject({ userId: "user-1", sessionToken: "tok-active" });
});
@@ -548,7 +687,7 @@ describe("getUserInfo session token exposure", () => {
headers: { Cookie: (await storage.commitSession(session)).split(";")[0] },
});
await expect(getUserInfo(request)).resolves.toMatchObject({ userId: "user-1", sessionToken: undefined });
await expect(getUserInfo(request)).resolves.toMatchObject({ userId: null, sessionToken: undefined });
});
});
@@ -564,15 +703,14 @@ describe("logout server-session revocation (R-P2a S4b)", () => {
it("ends the server session row and destroys the cookie when a session token is present", async () => {
const { logout } = await import("./session.server");
const lifecycle = await import("~/services/auth/sessionLifecycle.server");
const endServerSessionMock = vi.mocked(lifecycle.endServerSession);
const endServerSessionMock = sessionLifecycleMock.endServerSession;
endServerSessionMock.mockReset();
endServerSessionMock.mockResolvedValueOnce(undefined as never);
const response = await logout(await requestWithLogoutToken("tok-logout"));
expect(endServerSessionMock).toHaveBeenCalledTimes(1);
expect(endServerSessionMock).toHaveBeenCalledWith("tok-logout");
expect(endServerSessionMock).toHaveBeenCalledWith("tok-logout", expect.any(Request));
expect(response.status).toBe(302);
expect(response.headers.get("Location")).toBe("/login");
expect(response.headers.get("Set-Cookie")).toBeTruthy();
@@ -580,8 +718,7 @@ describe("logout server-session revocation (R-P2a S4b)", () => {
it("still destroys the cookie when ending the server session row rejects with an Error (best-effort)", async () => {
const { logout } = await import("./session.server");
const lifecycle = await import("~/services/auth/sessionLifecycle.server");
const endServerSessionMock = vi.mocked(lifecycle.endServerSession);
const endServerSessionMock = sessionLifecycleMock.endServerSession;
endServerSessionMock.mockReset();
endServerSessionMock.mockRejectedValueOnce(new Error("revoke store offline"));
@@ -589,7 +726,7 @@ describe("logout server-session revocation (R-P2a S4b)", () => {
// source of truth for the device and is destroyed regardless.
const response = await logout(await requestWithLogoutToken("tok-error"));
expect(endServerSessionMock).toHaveBeenCalledWith("tok-error");
expect(endServerSessionMock).toHaveBeenCalledWith("tok-error", expect.any(Request));
expect(response.status).toBe(302);
expect(response.headers.get("Location")).toBe("/login");
expect(response.headers.get("Set-Cookie")).toBeTruthy();
@@ -597,23 +734,21 @@ describe("logout server-session revocation (R-P2a S4b)", () => {
it("swallows non-Error rejections from the revoke call and still logs out", async () => {
const { logout } = await import("./session.server");
const lifecycle = await import("~/services/auth/sessionLifecycle.server");
const endServerSessionMock = vi.mocked(lifecycle.endServerSession);
const endServerSessionMock = sessionLifecycleMock.endServerSession;
endServerSessionMock.mockReset();
// A non-Error rejection drives the `error instanceof Error ? … : "Error"` fallback.
endServerSessionMock.mockRejectedValueOnce("string failure" as never);
const response = await logout(await requestWithLogoutToken("tok-string-error"));
expect(endServerSessionMock).toHaveBeenCalledWith("tok-string-error");
expect(endServerSessionMock).toHaveBeenCalledWith("tok-string-error", expect.any(Request));
expect(response.status).toBe(302);
expect(response.headers.get("Location")).toBe("/login");
});
it("does not touch the server-session store when the cookie carries no token", async () => {
const { logout } = await import("./session.server");
const lifecycle = await import("~/services/auth/sessionLifecycle.server");
const endServerSessionMock = vi.mocked(lifecycle.endServerSession);
const endServerSessionMock = sessionLifecycleMock.endServerSession;
endServerSessionMock.mockReset();
const response = await logout(await requestWithLogoutToken());
@@ -626,8 +761,7 @@ describe("logout server-session revocation (R-P2a S4b)", () => {
it("does not touch the server-session store when the token is an empty string", async () => {
const { logout } = await import("./session.server");
const lifecycle = await import("~/services/auth/sessionLifecycle.server");
const endServerSessionMock = vi.mocked(lifecycle.endServerSession);
const endServerSessionMock = sessionLifecycleMock.endServerSession;
endServerSessionMock.mockReset();
// Empty-string token: `typeof === "string"` is true but `length > 0` is false,
@@ -663,13 +797,16 @@ describe("commitPendingMfaLoginCookie (D1 — 2FA login gate)", () => {
const setCookie = await commitPendingMfaLoginCookie(await requestWithAuthenticatedSession(), {
userId: "user-99",
redirectTo: "/app/dashboard",
primaryMethod: "password",
});
expect(setCookie).toContain("hivegrid_session=");
expect(setCookie).toContain("hivegrid_app_session=");
const info = await readBack(setCookie);
expect(info.pendingMfaUserId).toBe("user-99");
expect(info.pendingMfaRedirectTo).toBe("/app/dashboard");
expect(info.pendingMfaStartedAt).toEqual(expect.any(String));
expect(info.pendingMfaPrimaryMethod).toBe("password");
// userId and sessionToken must be gone — the pending state must NOT grant access.
expect(info.userId).toBeNull();
expect(info.sessionToken).toBeUndefined();
@@ -682,6 +819,7 @@ describe("commitPendingMfaLoginCookie (D1 — 2FA login gate)", () => {
const setCookie = await commitPendingMfaLoginCookie(await requestWithAuthenticatedSession(), {
userId: "user-99",
redirectTo: "/app/dashboard",
primaryMethod: "magic-link",
});
const request = new Request("https://example.test/app/secret", {
@@ -703,11 +841,13 @@ describe("commitPendingMfaLoginCookie (D1 — 2FA login gate)", () => {
const { commitPendingMfaLoginCookie } = await import("./session.server");
const setCookie = await commitPendingMfaLoginCookie(await requestWithAuthenticatedSession(), {
userId: "user-99",
primaryMethod: "invitation",
});
const info = await readBack(setCookie);
expect(info.pendingMfaUserId).toBe("user-99");
expect(info.pendingMfaRedirectTo).toBeUndefined();
expect(info.pendingMfaPrimaryMethod).toBe("invitation");
});
it("unsets the redirect key when redirectTo is an empty string (length guard is false)", async () => {
@@ -715,15 +855,25 @@ describe("commitPendingMfaLoginCookie (D1 — 2FA login gate)", () => {
const setCookie = await commitPendingMfaLoginCookie(await requestWithAuthenticatedSession(), {
userId: "user-99",
redirectTo: "",
primaryMethod: "password-reset",
});
const info = await readBack(setCookie);
expect(info.pendingMfaUserId).toBe("user-99");
expect(info.pendingMfaRedirectTo).toBeUndefined();
expect(info.pendingMfaPrimaryMethod).toBe("password-reset");
});
});
describe("createUserSession", () => {
it("blocks an external redirect at the central session issuance boundary", async () => {
const response = await createUserSession({ userId: "", lightOrDarkMode: "", lng: "de", cookies: [] }, "https://evil.example/phish", {
request: new Request("https://app.localhost/login"),
});
expect(response.headers.get("Location")).toBe("/");
});
it("persists supported session metadata and omits falsey password-policy flags", async () => {
const response = await createUserSession(
{
@@ -736,7 +886,8 @@ describe("createUserSession", () => {
theme: "system",
passwordPolicyOutdated: false,
},
"/dashboard"
"/dashboard",
{ request: new Request("https://example.test/login"), rotate: true }
);
expect(response.status).toBe(302);
expect(response.headers.get("Location")).toBe("/dashboard");
@@ -754,6 +905,84 @@ describe("createUserSession", () => {
cookies: [{ category: "analytics", allowed: true }],
theme: "system",
passwordPolicyOutdated: undefined,
sessionToken: "tok:user-1",
});
expect(sessionLifecycleMock.startServerSession).toHaveBeenCalledWith({
request: expect.any(Request),
userId: "user-1",
});
});
it("does not issue an authenticated cookie when creating the server session fails", async () => {
sessionLifecycleMock.startServerSession.mockRejectedValueOnce(new Error("session store offline"));
await expect(
createUserSession({ userId: "user-1", lightOrDarkMode: "", lng: "de", cookies: [] }, "/dashboard", {
request: new Request("https://example.test/login"),
rotate: true,
})
).rejects.toThrow("session store offline");
});
it("keeps an empty user id unauthenticated and does not create a server session", async () => {
const response = await createUserSession({ userId: "", lightOrDarkMode: "", lng: "de", cookies: [] }, "/login", {
request: new Request("https://example.test/login"),
rotate: false,
});
expect(sessionLifecycleMock.startServerSession).not.toHaveBeenCalled();
const request = new Request("https://example.test/login", {
headers: { Cookie: (response.headers.get("Set-Cookie") ?? "").split(";")[0] },
});
await expect(getUserInfo(request)).resolves.toMatchObject({ userId: null, sessionToken: undefined });
});
it("revokes the previous token before rotating an authenticated session", async () => {
const response = await createUserSession({ userId: "user-1", lightOrDarkMode: "", lng: "de", cookies: [], sessionToken: "tok-old" }, "/dashboard", {
request: new Request("https://example.test/login"),
rotate: true,
});
expect(sessionLifecycleMock.endServerSession).toHaveBeenCalledWith("tok-old", expect.any(Request));
expect(sessionLifecycleMock.startServerSession).toHaveBeenCalledWith({
request: expect.any(Request),
userId: "user-1",
});
expect(response.status).toBe(302);
});
it("forwards admin assurance metadata when rotating an admin session", async () => {
const adminMfaAssuredAt = new Date("2026-08-02T03:00:00.000Z");
await createUserSession({ userId: "admin-1", lightOrDarkMode: "", lng: "de", cookies: [] }, "/admin", {
request: new Request("https://admin.localhost/login"),
rotate: true,
adminAuthenticationMethods: ["password", "totp"],
adminMfaAssuredAt,
});
expect(sessionLifecycleMock.startServerSession).toHaveBeenCalledWith({
request: expect.any(Request),
userId: "admin-1",
adminAuthenticationMethods: ["password", "totp"],
adminMfaAssuredAt,
});
});
it("forwards admin assurance metadata when creating a new unrotated admin session", async () => {
const adminMfaAssuredAt = new Date("2026-08-02T03:00:00.000Z");
await createUserSession({ userId: "admin-1", lightOrDarkMode: "", lng: "de", cookies: [] }, "/admin", {
request: new Request("https://admin.localhost/login"),
adminAuthenticationMethods: ["password"],
adminMfaAssuredAt,
});
expect(sessionLifecycleMock.startServerSession).toHaveBeenCalledWith({
request: expect.any(Request),
userId: "admin-1",
adminAuthenticationMethods: ["password"],
adminMfaAssuredAt,
});
});
});