Files
co-lite/solvway-admin-portal/app/lib/sessionCodec.ts
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

92 lines
3.8 KiB
TypeScript

// Pure, edge-safe session serialization (no `next/headers`, no Buffer) so it can
// be used from both server route handlers and the edge middleware.
//
// Deliberately narrow: the admin session cookie carries only the JWT, the
// resetPasswordRequired flag, and the absolute session cap (epoch seconds). It
// MUST NOT carry `aclMenu` (too large for a cookie) or `roles` — both are
// re-fetched via session hydration (`/api/auth/session` -> `/api/admin/me`)
// instead. See admin-portal-auth spec, "The Admin JWT Lives Only In An httpOnly
// Cookie".
export interface SessionData {
token: string;
resetPasswordRequired?: boolean;
/** Absolute session cap (epoch seconds): the sliding refresh must stop at this point. */
absoluteExpiry?: number;
/** enforce-session-timeouts: original sign-in (epoch seconds); the cap is measured from here. */
signedInAt?: number;
/** enforce-session-timeouts: last click/tap/key press reported by keepalive (epoch seconds). */
lastActivity?: number;
/** enforce-session-timeouts: the idle limit in force (seconds), from the saved session policy. */
idleTtl?: number;
}
const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
/**
* True once the session is past its idle limit or its cap (enforce-session-timeouts). A cookie written before that
* change carries no activity time and never ends here; keepalive gives it times on its first call.
*/
export function sessionEnded(data: SessionData, nowSeconds: number): boolean {
if (data.lastActivity == null) return false;
if (data.idleTtl != null && nowSeconds - data.lastActivity > data.idleTtl) return true;
return data.absoluteExpiry != null && nowSeconds >= data.absoluteExpiry;
}
export function encodeSession(data: SessionData): string {
return encodeURIComponent(JSON.stringify(data));
}
export function decodeSession(raw: string | undefined | null): SessionData | null {
if (!raw) return null;
try {
const obj = JSON.parse(decodeURIComponent(raw)) as Partial<SessionData>;
if (obj && typeof obj.token === "string") {
// Backward-compatible: older cookies predate resetPasswordRequired / absoluteExpiry.
return {
token: obj.token,
resetPasswordRequired: !!obj.resetPasswordRequired,
absoluteExpiry:
typeof obj.absoluteExpiry === "number" ? obj.absoluteExpiry : undefined,
signedInAt: num(obj.signedInAt),
lastActivity: num(obj.lastActivity),
idleTtl: num(obj.idleTtl),
};
}
return null;
} catch {
return null;
}
}
/**
* The JWT's `exp` claim (epoch seconds), decoded without any crypto — the payload is plain
* base64url JSON and the signature is validated by the services, not here. Returns null for a
* malformed/unparseable token. The session cookie's maxAge is derived from this so the cookie
* never outlives the token it carries (spec: "The Admin Cookie Lifetime Is Aligned To The Token
* Lifetime").
*/
export function tokenExpirySeconds(token: string): number | null {
if (!token) return null;
const parts = token.split(".");
if (parts.length < 2) return null;
try {
const payloadJson = decodeBase64Url(parts[1]);
const payload = JSON.parse(payloadJson) as { exp?: unknown };
return typeof payload.exp === "number" && Number.isFinite(payload.exp) ? payload.exp : null;
} catch {
return null;
}
}
function decodeBase64Url(segment: string): string {
const base64 = segment.replace(/-/g, "+").replace(/_/g, "/");
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
// Node's Buffer is available in the server runtime (route handlers); the middleware
// (edge) also supports atob. Prefer Buffer, fall back to atob.
if (typeof Buffer !== "undefined") {
return Buffer.from(padded, "base64").toString("utf-8");
}
return atob(padded);
}