import fs from "node:fs"; import { homedir } from "node:os"; import { join } from "node:path"; import type { Store } from "tough-cookie"; import FileCookieStore from "./fileCookieStore.js"; const configDir = join(homedir(), ".af"); export function getCookieStore(hostname: string): Store { if (!fs.existsSync(configDir)) { fs.mkdirSync(configDir, { recursive: true }); } const file = join(configDir, `${hostname.replace(/[^a-z0-9]+/gi, "_")}-cookies.json`); return new FileCookieStore(file); } async function loadKeytar() { try { // @ts-expect-error const mod = await import("keytar"); return mod.default ?? mod; } catch { return undefined; } } export async function savePassword(host: string, username: string, password: string) { const keytar = await loadKeytar(); if (keytar) { try { await keytar.setPassword("appframe-cli", `${username}@${host}`, password); return; } catch { // ignore } } const path = join(configDir, "credentials.json"); let data: Record = {}; try { data = JSON.parse(fs.readFileSync(path, "utf-8")); } catch {} data[`${username}@${host}`] = password; fs.writeFileSync(path, JSON.stringify(data)); } export async function getSavedPassword(host: string, username: string): Promise { const keytar = await loadKeytar(); if (keytar) { try { return (await keytar.getPassword("appframe-cli", `${username}@${host}`)) ?? undefined; } catch { /* ignore */ } } try { const path = join(configDir, "credentials.json"); const data: Record = JSON.parse(fs.readFileSync(path, "utf-8")); return data[`${username}@${host}`]; } catch { return undefined; } }