Files
webmailserver/lib/mail-session.ts

77 lines
2.0 KiB
TypeScript

import { cookies } from "next/headers";
import { auth } from "@/auth";
const COOKIE_NAME = "ayrismail_creds";
export interface MailSessionData {
email: string;
password: string;
ownerId: string; // Dashboard user ID who owns this mail session
}
/**
* Encode credentials to base64 (in production, use proper encryption
* with AES-256-GCM and AUTH_SECRET as key).
*/
function encode(data: MailSessionData): string {
return Buffer.from(JSON.stringify(data)).toString("base64");
}
function decode(token: string): MailSessionData | null {
try {
return JSON.parse(Buffer.from(token, "base64").toString("utf-8"));
} catch {
return null;
}
}
/** Save mail credentials to cookie */
export async function setMailSession(data: Omit<MailSessionData, "ownerId">): Promise<void> {
const session = await auth();
if (!session?.user?.id) {
throw new Error("Cannot set mail session without dashboard session");
}
const cookieStore = await cookies();
const sessionData: MailSessionData = {
...data,
ownerId: session.user.id,
};
cookieStore.set(COOKIE_NAME, encode(sessionData), {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60 * 24, // 24 hours
path: "/",
});
}
/** Get mail credentials from cookie */
export async function getMailSession(): Promise<MailSessionData | null> {
const session = await auth();
if (!session?.user?.id) return null;
const cookieStore = await cookies();
const cookie = cookieStore.get(COOKIE_NAME);
if (!cookie?.value) return null;
const data = decode(cookie.value);
if (!data) return null;
// Verify that this mail session belongs to the current dashboard user
if (data.ownerId !== session.user.id) {
// Session belongs to another user, clear it for safety
await clearMailSession();
return null;
}
return data;
}
/** Clear mail credentials cookie */
export async function clearMailSession(): Promise<void> {
const cookieStore = await cookies();
cookieStore.delete(COOKIE_NAME);
}