convex
Version:
Client for the Convex Cloud
200 lines (199 loc) • 6.19 kB
JavaScript
;
import { errors, custom } from "openid-client";
import {
globalConfigPath,
rootDirectory,
getAuthHeader,
bigBrainAPI
} from "./utils.js";
import open from "open";
import chalk from "chalk";
import { provisionHost } from "./config.js";
import { version } from "../../index.js";
import axios from "axios";
import { Issuer } from "openid-client";
import inquirer from "inquirer";
import { hostname } from "os";
import { execSync } from "child_process";
const SCOPE = "openid email profile";
custom.setHttpOptionsDefaults({
timeout: 1e4
});
async function writeGlobalConfig(ctx, config) {
const dirName = rootDirectory();
ctx.fs.mkdir(dirName, { allowExisting: true });
const path = globalConfigPath();
try {
ctx.fs.writeUtf8File(path, JSON.stringify(config));
} catch (err) {
console.log(
chalk.red(`Failed to write auth config to ${path} with error: ${err}`)
);
return await ctx.fatalError(1, "fs", err);
}
console.log(
chalk.green(`Successfully wrote your auth credentials to ${path}!`)
);
}
export async function checkAuthorization(ctx) {
const header = await getAuthHeader(ctx);
if (!header) {
return false;
}
try {
const resp = await axios.head(`${provisionHost}/api/${version}/authorize`, {
headers: { Authorization: header },
validateStatus: (_) => true
});
return resp.status === 200;
} catch (e) {
console.log(chalk.gray(`Unexpected error when authorizing: ${e}`));
return false;
}
}
async function performDeviceAuthorization(ctx, auth0Client, shouldOpen) {
const handle = await auth0Client.deviceAuthorization({
scope: SCOPE,
audience: "https://console.convex.dev/api/"
});
const { verification_uri_complete, user_code, expires_in } = handle;
console.log(
`Visit ${verification_uri_complete} to finish logging in. You should see the following code which expires in ${expires_in % 60 === 0 ? `${expires_in / 60} minutes` : `${expires_in} seconds`}: ${user_code}`
);
if (shouldOpen) {
shouldOpen = (await inquirer.prompt([
{
name: "openBrowser",
message: `Open in browser?`,
type: "confirm",
default: true
}
])).openBrowser;
}
if (shouldOpen) {
console.log(
`Opening ${verification_uri_complete} in your browser to log in...`
);
try {
await open(verification_uri_complete);
} catch (err) {
console.log(chalk.red(`Unable to open browser.`));
console.log(
`Manually open ${verification_uri_complete} in your browser to log in.`
);
}
} else {
console.log(`Open ${verification_uri_complete} in your browser to log in.`);
}
try {
const tokens = await handle.poll();
if (typeof tokens.access_token === "string") {
return tokens.access_token;
} else {
throw Error("Access token is missing");
}
} catch (err) {
switch (err.error) {
case "access_denied":
console.error("Access denied.");
return await ctx.fatalError(1, err);
case "expired_token":
console.error("Device flow expired.");
return await ctx.fatalError(1, err);
default:
if (err instanceof errors.OPError) {
console.error(
`Error = ${err.error}; error_description = ${err.error_description}`
);
} else {
console.error(`Login failed with error: ${err}`);
}
return await ctx.fatalError(1, err);
}
}
}
async function performPasswordAuthentication(ctx, issuer, clientId, username, password) {
const options = {
method: "POST",
url: new URL("/oauth/token", issuer).href,
headers: { "content-type": "application/x-www-form-urlencoded" },
data: new URLSearchParams({
grant_type: "password",
username,
password,
scope: SCOPE,
client_id: clientId,
audience: "https://console.convex.dev/api/"
})
};
try {
const response = await axios.request(options);
if (typeof response.data.access_token === "string") {
return response.data.access_token;
} else {
throw Error("Access token is missing");
}
} catch (err) {
console.log(`Password flow failed: ${err}`);
if (err.response) {
console.log(`${JSON.stringify(err.response.data)}`);
}
return await ctx.fatalError(1, err);
}
}
export async function performLogin(ctx, overrideAuthUrl, overrideAuthClient, overrideAuthUsername, overrideAuthPassword, open2 = true, deviceNameOverride) {
let deviceName = deviceNameOverride ?? "";
if (!deviceName && process.platform === "darwin") {
try {
deviceName = execSync("scutil --get ComputerName").toString().trim();
} catch {
}
}
if (!deviceName) {
deviceName = hostname();
}
if (process.stdin.isTTY && !deviceNameOverride) {
const answers = await inquirer.prompt([
{
type: "input",
name: "deviceName",
message: "Enter a name for the device being authorized:",
default: deviceName
}
]);
deviceName = answers.deviceName;
}
const issuer = overrideAuthUrl ?? "https://auth.convex.dev";
const auth0 = await Issuer.discover(issuer);
const clientId = overrideAuthClient ?? "HFtA247jp9iNs08NTLIB7JsNPMmRIyfi";
const auth0Client = new auth0.Client({
client_id: clientId,
token_endpoint_auth_method: "none",
id_token_signed_response_alg: "RS256"
});
let accessToken;
if (overrideAuthUsername && overrideAuthPassword) {
accessToken = await performPasswordAuthentication(
ctx,
issuer,
clientId,
overrideAuthUsername,
overrideAuthPassword
);
} else {
accessToken = await performDeviceAuthorization(ctx, auth0Client, open2);
}
const authorizeArgs = {
authnToken: accessToken,
deviceName
};
const data = await bigBrainAPI(ctx, "POST", "authorize", authorizeArgs);
const globalConfig = { accessToken: data.accessToken };
try {
await writeGlobalConfig(ctx, globalConfig);
} catch (err) {
return await ctx.fatalError(1, "fs", err);
}
console.log(chalk.green("Successfully logged in and authorized device"));
}
//# sourceMappingURL=login.js.map