Files
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
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
2026-11-26 15:55:45 +08:00

90 lines
3.8 KiB
TypeScript

import "server-only";
import { cookies } from "next/headers";
import { sessionEnded, tokenExpirySeconds, type SessionData } from "@/app/lib/sessionCodec";
import { cachedSessionPolicy, sessionIdleTtlSeconds } from "@/app/lib/server/sessionPolicy";
// sign-session-cookies (F32): the cookie is signed, so its flags and absolute cap cannot be edited.
import { sealSession, openSession } from "@/app/lib/sessionSeal";
import { sessionCookieName } from "@/app/lib/sessionCookieName";
// The env fallbacks now live with the saved policy (enforce-session-timeouts); re-exported for existing callers.
export { sessionIdleTtlSeconds, sessionAbsoluteTtlSeconds } from "@/app/lib/server/sessionPolicy";
function nowSeconds(): number {
return Math.floor(Date.now() / 1000);
}
/**
* The cookie maxAge, derived from the JWT's own expiry so the cookie never outlives the token
* it carries (closing the old 1h-token / 8h-cookie mismatch). Falls back to the configured idle
* TTL only when the token's exp cannot be read.
*/
function maxAgeFromToken(token: string): number {
const exp = tokenExpirySeconds(token);
if (exp == null) return sessionIdleTtlSeconds();
return Math.max(1, exp - nowSeconds());
}
export async function setSession(
token: string,
resetPasswordRequired = false,
absoluteExpiry?: number,
): Promise<void> {
// A fresh session gets a fresh cap unless the caller (e.g. a rewrite path) supplies one; the sliding refresh must
// stop at this deadline. enforce-session-timeouts: it also records sign-in and activity times and the idle limit,
// from the last saved policy this process read (keepalive, called on the first page, brings it up to date).
const now = nowSeconds();
const policy = cachedSessionPolicy();
await writeSession({
token,
resetPasswordRequired,
absoluteExpiry: absoluteExpiry ?? now + policy.absoluteTtlSeconds,
signedInAt: now,
lastActivity: now,
idleTtl: policy.idleTtlSeconds,
});
}
/** Seals `data` into the session cookie; maxAge follows the token's own expiry. */
export async function writeSession(data: SessionData): Promise<void> {
const store = await cookies();
store.set(sessionCookieName(), await sealSession(data), {
httpOnly: true,
secure: true,
sameSite: "lax",
path: "/",
maxAge: maxAgeFromToken(data.token),
});
}
/** The signed-in session, or null when there is none or it is past its idle limit or cap (enforce-session-timeouts). */
export async function readSession(): Promise<SessionData | null> {
const store = await cookies();
const session = await openSession(store.get(sessionCookieName())?.value);
return session && !sessionEnded(session, nowSeconds()) ? session : null;
}
export async function getToken(): Promise<string | null> {
return (await readSession())?.token ?? null;
}
export async function clearSession(): Promise<void> {
const store = await cookies();
// A browser ignores a __Host- cookie deletion that lacks Secure and Path=/, so expire it with the same attributes.
store.set(sessionCookieName(), "", { httpOnly: true, secure: true, sameSite: "lax", path: "/", maxAge: 0 });
}
/** Absolute session cap for a fresh session: now + configured absolute TTL. */
export async function newAbsoluteExpiry(): Promise<number> {
return nowSeconds() + cachedSessionPolicy().absoluteTtlSeconds;
}
/**
* Rewrites the session cookie with a refreshed token, preserving the reset-flag and the absolute
* cap (the sliding session never moves its absolute deadline). maxAge is re-derived from the new
* token's exp, keeping cookie and token aligned after every refresh.
*/
export async function rewriteSessionWithToken(token: string, session: SessionData): Promise<void> {
// Every other field (reset flag, cap, sign-in and activity times, idle limit) carries over unchanged.
await writeSession({ ...session, token });
}