| 1 | import os from "os"; |
| 2 | import { readFile } from "fs/promises"; |
| 3 | import path from "path"; |
| 4 | import assert from "assert"; |
| 5 | import { ValidationError, ValidationErrorEnum } from "./errors.js"; |
| 6 | |
| 7 | export async function tryParseTokenFromCredentials(): Promise<string> { |
| 8 | try { |
| 9 | const kernel = os.type(); |
| 10 | let config: string; |
| 11 | const figCredentials = path.join("fig", "credentials.json"); |
| 12 | if (kernel === "Darwin") { |
| 13 | assert(process.env.HOME); |
| 14 | config = await readFile( |
| 15 | path.resolve(process.env.HOME, "Library", "Application Support", figCredentials), |
| 16 | { encoding: "utf-8" } |
| 17 | ); |
| 18 | } else if (kernel === "Linux") { |
| 19 | if (process.env.XDG_DATA_HOME) { |
| 20 | config = await readFile(path.resolve(process.env.XDG_DATA_HOME, figCredentials), { |
| 21 | encoding: "utf-8", |
| 22 | }); |
| 23 | } else { |
| 24 | assert(process.env.HOME); |
| 25 | config = await readFile(path.resolve(process.env.HOME, ".local", "share", figCredentials), { |
| 26 | encoding: "utf-8", |
| 27 | }); |
| 28 | } |
| 29 | } else { |
| 30 | // Windows |
| 31 | assert(process.env.APPDATA); |
| 32 | config = await readFile(path.resolve(process.env.APPDATA, figCredentials), { |
| 33 | encoding: "utf-8", |
| 34 | }); |
| 35 | } |
| 36 | /* eslint-disable camelcase */ |
| 37 | const { access_token, id_token } = JSON.parse(config); |
| 38 | assert(access_token); |
| 39 | assert(id_token); |
| 40 | const token = Buffer.from( |
| 41 | JSON.stringify({ accessToken: access_token, idToken: id_token }), |
| 42 | "utf-8" |
| 43 | ).toString("base64"); |
| 44 | return token; |
| 45 | /* eslint-enable camelcase */ |
| 46 | } catch (error) { |
| 47 | throw new ValidationError(ValidationErrorEnum.missingToken); |
| 48 | } |
| 49 | } |