@nestbox-ai/cli
Version:
The cli tools that helps developers to build agents
186 lines • 9.79 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerLoginCommand = registerLoginCommand;
const chalk_1 = __importDefault(require("chalk"));
const inquirer_1 = __importDefault(require("inquirer"));
const open_1 = __importDefault(require("open"));
const ora_1 = __importDefault(require("ora"));
const fs_1 = __importDefault(require("fs"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const admin_1 = require("@nestbox-ai/admin");
const axios_1 = __importDefault(require("axios"));
function registerLoginCommand(program) {
program
.command('login <nestbox-domain>')
.description('Login using Google SSO')
.action((domain) => __awaiter(this, void 0, void 0, function* () {
console.log('Login command triggered for domain:', domain);
const spinner = (0, ora_1.default)('Initiating Google login...').start();
try {
// Determine the protocol and construct the auth URL based on the provided domain
let authUrl;
if (domain.includes('localhost')) {
// Use HTTP for localhost and specific port
authUrl = `http://${domain}/cli/auth`;
}
else {
// Use HTTPS for all other domains
authUrl = `https://${domain}/cli/auth`;
}
spinner.text = 'Opening browser for Google authentication...';
// Open the browser for authentication
yield (0, open_1.default)(authUrl);
spinner.succeed('Browser opened for authentication');
// Prompt user to paste the combined token and API URL
const { combinedInput } = yield inquirer_1.default.prompt([
{
type: 'input',
name: 'combinedInput',
message: 'After authenticating, please paste the data here:',
validate: (input) => input.trim().length > 0 || 'Input is required'
}
]);
// Split the input by comma
const [accessToken, apiServerUrl] = combinedInput.split(',').map(item => item.trim());
if (!accessToken || !apiServerUrl) {
spinner.fail('Invalid input format. Expected: token,apiServerUrl');
return;
}
console.log(chalk_1.default.green('Credentials received. Extracting user information...'));
// Fetch user data from the token
let email = '';
let name = '';
let picture = '';
try {
// Try to decode JWT to get user data (email, name, picture, etc.)
const tokenParts = accessToken.split('.');
if (tokenParts.length === 3) {
// Base64 decode the payload part of JWT
const base64Payload = tokenParts[1].replace(/-/g, '+').replace(/_/g, '/');
const decodedPayload = Buffer.from(base64Payload, 'base64').toString('utf-8');
const tokenPayload = JSON.parse(decodedPayload);
// Extract user information
email = tokenPayload.email || '';
name = tokenPayload.name || '';
picture = tokenPayload.picture || '';
}
}
catch (e) {
console.log(chalk_1.default.yellow('Could not decode token payload. Will prompt for email.'));
}
// If email couldn't be extracted from token, prompt user
if (!email) {
const response = yield inquirer_1.default.prompt([
{
type: 'input',
name: 'email',
message: 'Enter your email address:',
validate: (input) => /\S+@\S+\.\S+/.test(input) || 'Please enter a valid email'
}
]);
email = response.email;
}
spinner.start('Verifying access token...');
if (apiServerUrl && email && accessToken) {
// Verify the access token
const configuration = new admin_1.Configuration({
basePath: apiServerUrl,
accessToken: accessToken,
});
const authApi = new admin_1.AuthApi(configuration);
try {
const response = yield authApi.authControllerOAuthLogin({
providerId: accessToken,
type: admin_1.OAuthLoginRequestDTOTypeEnum.Google,
email,
profilePictureUrl: picture || '',
});
const authResponse = response.data;
// Save credentials to file
try {
// Create directory structure
const configDir = path_1.default.join(os_1.default.homedir(), '.config', '.nestbox');
if (!fs_1.default.existsSync(configDir)) {
fs_1.default.mkdirSync(configDir, { recursive: true });
}
// Create the file path
const fileName = `${email.replace('@', '_at_')}_${domain}.json`;
const filePath = path_1.default.join(configDir, fileName);
// Create credentials object
const credentials = {
domain,
email,
token: authResponse.token,
accessToken, // Save the original accessToken
apiServerUrl,
name,
picture,
timestamp: new Date().toISOString()
};
// Write to file
fs_1.default.writeFileSync(filePath, JSON.stringify(credentials, null, 2));
spinner.succeed('Authentication successful');
console.log(chalk_1.default.green(`Successfully logged in as ${email}`));
console.log(chalk_1.default.blue(`Credentials saved to: ${filePath}`));
}
catch (fileError) {
spinner.warn('Authentication successful, but failed to save credentials file');
console.error(chalk_1.default.yellow('File error:'), fileError instanceof Error ? fileError.message : 'Unknown error');
}
}
catch (authError) {
spinner.fail('Failed to verify access token');
if (axios_1.default.isAxiosError(authError) && authError.response) {
if (authError.response.data.message === "user.not_found") {
console.error(chalk_1.default.red('Authentication Error:'), "You need to register your email with the Nestbox platform");
const { openSignup } = yield inquirer_1.default.prompt([
{
type: 'confirm',
name: 'openSignup',
message: 'Would you like to open the signup page to register?',
default: true
}
]);
if (openSignup) {
// Construct signup URL with the same protocol logic as login
let signupUrl;
if (domain.includes('localhost')) {
signupUrl = `http://${domain}`;
}
else {
signupUrl = `https://${domain}`;
}
console.log(chalk_1.default.blue(`Opening signup page: ${signupUrl}`));
yield (0, open_1.default)(signupUrl);
}
}
}
else {
console.error(chalk_1.default.red('Authentication Error:'), authError instanceof Error ? authError.message : 'Unknown error');
}
}
}
else {
spinner.fail('Missing required information for authentication');
}
}
catch (error) {
spinner.fail('Authentication failed');
console.error(chalk_1.default.red('Error:'), error instanceof Error ? error.message : 'Unknown error');
}
}));
}
//# sourceMappingURL=login.js.map