@pompeii-labs/cli
Version:
Magma CLI
80 lines (79 loc) • 2.54 kB
JavaScript
import os from "os";
import path from "path";
import fs from "fs";
import { refreshTokens } from "./api.js";
import { Security } from "./security.js";
import chalk from "chalk";
const MAGMA_DIR = path.join(os.homedir(), ".magma");
const SESSION_FILE = path.join(MAGMA_DIR, "session");
function isAuthenticated() {
return fs.existsSync(SESSION_FILE);
}
async function storeAuthSession(auth) {
if (!fs.existsSync(MAGMA_DIR)) {
fs.mkdirSync(MAGMA_DIR, { recursive: true });
}
if (!fs.existsSync(SESSION_FILE)) {
fs.writeFileSync(SESSION_FILE, "{}");
}
if (!auth.expires_at) {
auth.expires_at = Date.now() + auth.expires_in * 1e3;
}
const encrypted = Security.encrypt(JSON.stringify(auth));
fs.writeFileSync(SESSION_FILE, encrypted);
fs.chmodSync(SESSION_FILE, 384);
}
async function getAuthSession() {
if (!fs.existsSync(SESSION_FILE)) {
throw new Error("Not authenticated with Magma. Please run `magma login`.");
}
const encrypted = fs.readFileSync(SESSION_FILE, "utf8");
let config = null;
try {
const decrypted = Security.decrypt(encrypted);
config = JSON.parse(decrypted.trim());
} catch (error) {
throw new Error(
`Could not detect a valid magma session. Please run \`magma login\` to re-authenticate.`
);
}
if (config.expires_at < Date.now() + 5 * 60 * 1e3) {
console.log(chalk.dim("\u{1F501} Refreshing tokens..."));
try {
const newTokens = await refreshTokens(config.refresh_token);
if (!newTokens) throw new Error("No tokens received from server");
await storeAuthSession({ ...newTokens, org: config.org });
return newTokens;
} catch (error) {
await removeAuthSession();
throw new Error(
"Failed to refresh authentication. Please run `magma login` to re-authenticate."
);
}
}
return config;
}
async function getOrg() {
const config = await getAuthSession();
return config?.org || null;
}
async function removeAuthSession() {
if (fs.existsSync(SESSION_FILE)) {
const encrypted = fs.readFileSync(SESSION_FILE, "utf8");
const decrypted = Security.decrypt(encrypted);
const config = JSON.parse(decrypted.trim());
delete config.access_token;
delete config.refresh_token;
delete config.expires_at;
delete config.expires_in;
const reencrypted = Security.encrypt(JSON.stringify(config));
fs.writeFileSync(SESSION_FILE, reencrypted, { mode: 384 });
}
}
export {
getAuthSession,
getOrg,
isAuthenticated,
removeAuthSession,
storeAuthSession
};