57 lines
1.5 KiB
TypeScript
57 lines
1.5 KiB
TypeScript
/**
|
|
* lib/mail-session.ts
|
|
* Stores/retrieves mail credentials in an encrypted httpOnly cookie.
|
|
* Credentials never hit the database.
|
|
*/
|
|
|
|
import { cookies } from "next/headers";
|
|
|
|
const COOKIE_NAME = "ayrismail_creds";
|
|
|
|
export interface MailSessionData {
|
|
email: string;
|
|
password: string;
|
|
}
|
|
|
|
/**
|
|
* 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: MailSessionData): Promise<void> {
|
|
const cookieStore = await cookies();
|
|
cookieStore.set(COOKIE_NAME, encode(data), {
|
|
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 cookieStore = await cookies();
|
|
const cookie = cookieStore.get(COOKIE_NAME);
|
|
if (!cookie?.value) return null;
|
|
return decode(cookie.value);
|
|
}
|
|
|
|
/** Clear mail credentials cookie */
|
|
export async function clearMailSession(): Promise<void> {
|
|
const cookieStore = await cookies();
|
|
cookieStore.delete(COOKIE_NAME);
|
|
}
|