Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
157 lines
5.2 KiB
TypeScript
157 lines
5.2 KiB
TypeScript
import { describe, it, expect, beforeEach, vi } from "vitest";
|
|
|
|
const h = vi.hoisted(() => {
|
|
const store = new Map<string, string>();
|
|
const setSpy = vi.fn();
|
|
return { store, setSpy };
|
|
});
|
|
|
|
vi.mock("next/headers", () => ({
|
|
cookies: async () => ({
|
|
get: (n: string) => (h.store.has(n) ? { name: n, value: h.store.get(n)! } : undefined),
|
|
set: (name: string, value: string, opts: unknown) => {
|
|
h.store.set(name, value);
|
|
h.setSpy(name, value, opts);
|
|
},
|
|
delete: (n: string) => {
|
|
h.store.delete(n);
|
|
},
|
|
}),
|
|
}));
|
|
|
|
import {
|
|
encodeSession,
|
|
decodeSession,
|
|
tokenExpirySeconds,
|
|
} from "@/app/lib/sessionCodec";
|
|
import {
|
|
setSession,
|
|
readSession,
|
|
getToken,
|
|
clearSession,
|
|
sessionIdleTtlSeconds,
|
|
sessionAbsoluteTtlSeconds,
|
|
} from "./session";
|
|
|
|
function b64url(s: string): string {
|
|
return Buffer.from(s).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
}
|
|
|
|
/** A JWT-shaped string whose payload carries the given exp (epoch seconds). */
|
|
function jwtWithExp(exp: number): string {
|
|
return `header.${b64url(JSON.stringify({ sub: "admin1", exp }))}.signature`;
|
|
}
|
|
|
|
beforeEach(() => {
|
|
h.store.clear();
|
|
h.setSpy.mockClear();
|
|
});
|
|
|
|
describe("sessionCodec", () => {
|
|
it("round-trips the token, resetPasswordRequired and absoluteExpiry", () => {
|
|
const data = { token: "jwt", resetPasswordRequired: true, absoluteExpiry: 999 };
|
|
expect(decodeSession(encodeSession(data))).toEqual(data);
|
|
});
|
|
|
|
it("returns null for garbage", () => {
|
|
expect(decodeSession("not-json")).toBeNull();
|
|
});
|
|
|
|
it("defaults resetPasswordRequired to false when decoding a cookie without it", () => {
|
|
const legacy = { token: "jwt" };
|
|
expect(decodeSession(encodeSession(legacy))).toEqual({
|
|
token: "jwt",
|
|
resetPasswordRequired: false,
|
|
absoluteExpiry: undefined,
|
|
});
|
|
});
|
|
|
|
it("never encodes an aclMenu or roles key, even if smuggled into the input", () => {
|
|
// The session payload type has no aclMenu/roles fields; this guards against
|
|
// a future edit widening SessionData to carry them again (spec: "The ACL
|
|
// tree is not stored in the cookie").
|
|
const encoded = encodeSession({ token: "jwt", resetPasswordRequired: false } as never);
|
|
const decoded = decodeURIComponent(encoded);
|
|
expect(decoded).not.toMatch(/aclMenu/);
|
|
expect(decoded).not.toMatch(/"roles"/);
|
|
});
|
|
|
|
it("extracts the exp claim from a JWT-shaped token", () => {
|
|
expect(tokenExpirySeconds(jwtWithExp(1_800_000_000))).toBe(1_800_000_000);
|
|
});
|
|
|
|
it("returns null for a token without a readable exp", () => {
|
|
expect(tokenExpirySeconds("garbage")).toBeNull();
|
|
expect(tokenExpirySeconds("")).toBeNull();
|
|
expect(tokenExpirySeconds("a.b.c")).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe("session cookie I/O", () => {
|
|
it("sets an httpOnly, Secure, SameSite=Lax cookie whose maxAge is derived from the token exp", async () => {
|
|
const exp = Math.floor(Date.now() / 1000) + 3600;
|
|
await setSession(jwtWithExp(exp));
|
|
expect(h.setSpy).toHaveBeenCalledTimes(1);
|
|
const [name, , opts] = h.setSpy.mock.calls[0];
|
|
expect(name).toBe("__Host-bb_admin");
|
|
expect(opts).toMatchObject({
|
|
httpOnly: true,
|
|
secure: true,
|
|
sameSite: "lax",
|
|
path: "/",
|
|
});
|
|
// The cookie must not outlive the token: maxAge ≈ exp - now (never a longer fixed value).
|
|
expect(opts.maxAge).toBeGreaterThan(3590);
|
|
expect(opts.maxAge).toBeLessThanOrEqual(3600);
|
|
});
|
|
|
|
it("falls back to the configured idle TTL when the token exp is unreadable", async () => {
|
|
await setSession("jwt-xyz");
|
|
expect(h.setSpy.mock.calls[0][2].maxAge).toBe(sessionIdleTtlSeconds());
|
|
});
|
|
|
|
it("records an absolute expiry on a fresh session from the configured absolute TTL", async () => {
|
|
const before = Math.floor(Date.now() / 1000) + sessionAbsoluteTtlSeconds();
|
|
await setSession("jwt-xyz");
|
|
const payload = JSON.parse(decodeURIComponent(h.store.get("__Host-bb_admin")!));
|
|
expect(payload.absoluteExpiry).toBeGreaterThanOrEqual(before - 1);
|
|
expect(payload.absoluteExpiry).toBeLessThanOrEqual(before + 1);
|
|
});
|
|
|
|
it("persists no aclMenu or roles in the cookie payload", async () => {
|
|
await setSession("jwt-xyz", true);
|
|
const [, value] = h.setSpy.mock.calls[0];
|
|
const decoded = decodeURIComponent(value as string);
|
|
expect(decoded).not.toMatch(/aclMenu/);
|
|
expect(decoded).not.toMatch(/"roles"/);
|
|
});
|
|
|
|
it("persists the resetPasswordRequired flag", async () => {
|
|
await setSession("jwt-xyz", true);
|
|
const [, value] = h.setSpy.mock.calls[0];
|
|
expect(JSON.parse(decodeURIComponent(value as string))).toMatchObject({
|
|
token: "jwt-xyz",
|
|
resetPasswordRequired: true,
|
|
});
|
|
});
|
|
|
|
it("reads the session back", async () => {
|
|
await setSession("jwt-xyz");
|
|
const s = await readSession();
|
|
expect(s?.token).toBe("jwt-xyz");
|
|
expect(s?.resetPasswordRequired).toBe(false);
|
|
expect(await getToken()).toBe("jwt-xyz");
|
|
});
|
|
|
|
it("returns null when no cookie is present", async () => {
|
|
expect(await readSession()).toBeNull();
|
|
expect(await getToken()).toBeNull();
|
|
});
|
|
|
|
it("clears the session", async () => {
|
|
await setSession("jwt");
|
|
await clearSession();
|
|
expect(await readSession()).toBeNull();
|
|
});
|
|
});
|