A tool for parsing traffic on the jetstream and applying a moderation workstream based on regexp based rules
1import {
2 chmodSync,
3 existsSync,
4 readFileSync,
5 unlinkSync,
6 writeFileSync,
7} from "node:fs";
8import { join } from "node:path";
9import { logger } from "./logger.js";
10
11const SESSION_FILE_PATH = join(process.cwd(), ".session");
12
13export interface SessionData {
14 accessJwt: string;
15 refreshJwt: string;
16 did: string;
17 handle: string;
18 email?: string;
19 emailConfirmed?: boolean;
20 emailAuthFactor?: boolean;
21 active: boolean;
22 status?: string;
23}
24
25export function loadSession(): SessionData | null {
26 try {
27 if (!existsSync(SESSION_FILE_PATH)) {
28 logger.debug("No session file found");
29 return null;
30 }
31
32 const data = readFileSync(SESSION_FILE_PATH, "utf-8");
33 const session = JSON.parse(data) as SessionData;
34
35 if (!session.accessJwt || !session.refreshJwt || !session.did) {
36 logger.warn("Session file is missing required fields, ignoring");
37 return null;
38 }
39
40 logger.info("Loaded existing session from file");
41 return session;
42 } catch (error) {
43 logger.error(
44 { error },
45 "Failed to load session file, will authenticate fresh",
46 );
47 return null;
48 }
49}
50
51export function saveSession(session: SessionData): void {
52 try {
53 const data = JSON.stringify(session, null, 2);
54 writeFileSync(SESSION_FILE_PATH, data, "utf-8");
55 chmodSync(SESSION_FILE_PATH, 0o600);
56 logger.info("Session saved to file");
57 } catch (error) {
58 logger.error({ error }, "Failed to save session to file");
59 }
60}
61
62export function clearSession(): void {
63 try {
64 if (existsSync(SESSION_FILE_PATH)) {
65 unlinkSync(SESSION_FILE_PATH);
66 logger.info("Session file cleared");
67 }
68 } catch (error) {
69 logger.error({ error }, "Failed to clear session file");
70 }
71}