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

70 lines
3.2 KiB
TypeScript

// sign-session-cookies (F32): the session cookie is HMAC-SHA256 signed, so its flags (reset required, country, the
// absolute cap, ...) cannot be edited by whoever holds it. Web Crypto only: runs in the middleware and in Node.
//
// Shape: the existing URL-encoded JSON (sessionCodec) with one extra last field, `sig`, the base64url HMAC of the JSON
// payload without it. Key: a per-portal label plus SESSION_SECRET, else plus the server-only MOBILE_API_KEY. No key: sealing throws and
// nothing opens (fail closed).
import { decodeSession, encodeSession, type SessionData } from "./sessionCodec";
// Per-portal label (review): a cookie signed for one portal never verifies on the other, even with a shared secret.
const KEY_LABEL = "bb-admin-session-v1:";
const encoder = new TextEncoder();
const keyCache = new Map<string, Promise<CryptoKey>>();
function secret(): string {
const base = process.env.SESSION_SECRET || process.env.MOBILE_API_KEY || "";
return base ? KEY_LABEL + base : "";
}
function hmacKey(value: string): Promise<CryptoKey> {
let key = keyCache.get(value);
if (!key) {
key = crypto.subtle.importKey("raw", encoder.encode(value), { name: "HMAC", hash: "SHA-256" }, false, [
"sign",
"verify",
]);
keyCache.set(value, key);
}
return key;
}
function toBase64Url(bytes: Uint8Array): string {
let binary = "";
for (const b of bytes) binary += String.fromCharCode(b);
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function fromBase64Url(text: string): Uint8Array | null {
if (!/^[A-Za-z0-9_-]+$/.test(text)) return null;
const base64 = text.replace(/-/g, "+").replace(/_/g, "/");
const binary = atob(base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "="));
return Uint8Array.from(binary, c => c.charCodeAt(0));
}
/** The cookie value for `data`: its JSON plus a signature. Throws when no signing key is configured. */
export async function sealSession(data: SessionData): Promise<string> {
const value = secret();
if (!value) throw new Error("Session signing key is not configured (SESSION_SECRET or MOBILE_API_KEY)");
const payload = JSON.parse(decodeURIComponent(encodeSession(data))) as Record<string, unknown>;
const signature = await crypto.subtle.sign("HMAC", await hmacKey(value), encoder.encode(JSON.stringify(payload)));
return encodeURIComponent(JSON.stringify({ ...payload, sig: toBase64Url(new Uint8Array(signature)) }));
}
/** The session in a cookie value, or null when it is absent, malformed, unsigned or its signature does not verify. */
export async function openSession(raw: string | undefined | null): Promise<SessionData | null> {
const value = secret();
if (!raw || !value) return null;
try {
const obj = JSON.parse(decodeURIComponent(raw)) as Record<string, unknown>;
if (!obj || typeof obj !== "object" || typeof obj.sig !== "string") return null;
const signature = fromBase64Url(obj.sig);
if (!signature) return null;
delete obj.sig;
const payload = JSON.stringify(obj);
const valid = await crypto.subtle.verify("HMAC", await hmacKey(value), signature as BufferSource, encoder.encode(payload));
return valid ? decodeSession(encodeURIComponent(payload)) : null;
} catch {
return null;
}
}