optimus-init
Version:
Initialization utility for Optimus Security
229 lines (228 loc) • 10.6 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const chalk_1 = __importDefault(require("chalk"));
const auth_1 = require("./auth");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const child_process_1 = require("child_process");
// Define program version and description
commander_1.program
.version('1.0.5')
.description('Optimus Security Initialization Tool');
// Get command - make a GET request to any endpoint
commander_1.program
.command('get <endpoint>')
.description('Make an authenticated GET request to any endpoint')
.option('-e, --env <path>', 'Path to optimus.env file', './optimus.env')
.option('-u, --url <url>', 'Base URL for the API (optional, will use OPTIMUS_ENDPOINT from env file)')
.option('-p, --params <params>', 'Query parameters in JSON format', '{}')
.option('-o, --output <file>', 'Save response to file instead of displaying')
.action(async (endpoint, options) => {
try {
const auth = new auth_1.OptimusAuth(options.env, options.url);
const params = JSON.parse(options.params);
console.log(chalk_1.default.blue(`Making authenticated GET request to ${endpoint}...`));
const response = await auth.get(endpoint, params);
if (options.output) {
fs.writeFileSync(options.output, JSON.stringify(response, null, 2));
console.log(chalk_1.default.green(`Response saved to ${options.output}`));
}
else {
console.log(chalk_1.default.green('Response:'));
// Output the response as-is, let the shell handle formatting
const responseStr = typeof response === 'string' ? response : JSON.stringify(response, null, 2);
console.log(responseStr);
}
}
catch (err) {
console.error(chalk_1.default.red('Error:'), err);
process.exit(1);
}
});
// Check command - check if this is a Unix-like system with tr available
commander_1.program
.command('is-unix')
.description('Check if this is a Unix-like system with tr available and output true/false')
.action(() => {
try {
const platform = os.platform();
// Check if we're on a Unix-like system and tr is available
const isUnixLike = ['darwin', 'linux', 'freebsd', 'openbsd'].includes(platform);
let trAvailable = false;
if (isUnixLike) {
try {
(0, child_process_1.execSync)('which tr', { stdio: 'ignore' });
trAvailable = true;
}
catch (err) {
// tr not available
}
}
// Set exit code without exiting: 0 for true, 1 for false
// On Windows, we'll use Node.js replacement instead of tr
process.exitCode = trAvailable ? 0 : 1;
}
catch (err) {
process.exitCode = 1;
}
});
// Post command - make a POST request to any endpoint
commander_1.program
.command('post <endpoint>')
.description('Make an authenticated POST request to any endpoint')
.option('-e, --env <path>', 'Path to optimus.env file', './optimus.env')
.option('-u, --url <url>', 'Base URL for the API (optional, will use OPTIMUS_ENDPOINT from env file)')
.option('-d, --data <data>', 'Request body in JSON format', '{}')
.option('-o, --output <file>', 'Save response to file instead of displaying')
.action(async (endpoint, options) => {
try {
const auth = new auth_1.OptimusAuth(options.env, options.url);
const data = JSON.parse(options.data);
console.log(chalk_1.default.blue(`Making authenticated POST request to ${endpoint}...`));
const response = await auth.post(endpoint, data);
if (options.output) {
fs.writeFileSync(options.output, JSON.stringify(response, null, 2));
console.log(chalk_1.default.green(`Response saved to ${options.output}`));
}
else {
console.log(chalk_1.default.green('Response:'));
console.log(JSON.stringify(response, null, 2));
}
}
catch (err) {
console.error(chalk_1.default.red('Error:'), err);
process.exit(1);
}
});
// Download command - download a file from any endpoint
commander_1.program
.command('download <endpoint> <outputPath>')
.description('Download a file from an authenticated endpoint')
.option('-e, --env <path>', 'Path to optimus.env file', './optimus.env')
.option('-u, --url <url>', 'Base URL for the API (optional, will use OPTIMUS_ENDPOINT from env file)')
.option('-p, --params <params>', 'Query parameters in JSON format', '{}')
.action(async (endpoint, outputPath, options) => {
try {
const auth = new auth_1.OptimusAuth(options.env, options.url);
const params = JSON.parse(options.params);
console.log(chalk_1.default.blue(`Downloading from ${endpoint} to ${outputPath}...`));
await auth.downloadFile(endpoint, outputPath, params);
console.log(chalk_1.default.green('Download complete!'));
}
catch (err) {
console.error(chalk_1.default.red('Error:'), err);
process.exit(1);
}
});
// Init command - initialize Optimus Security configuration
// This is the main command for setting up Optimus Security
commander_1.program
.command('init')
.description('Initialize Optimus Security configuration')
.option('-e, --env <path>', 'Path to optimus.env file', './optimus.env')
.option('-u, --url <url>', 'Base URL for the API (optional, will use OPTIMUS_ENDPOINT from env file)')
.option('-d, --dir <dir>', 'Directory to store config files', './.cursor')
.action(async (options) => {
var _a;
try {
console.log(chalk_1.default.blue('Initializing Optimus Security...'));
const auth = new auth_1.OptimusAuth(options.env, options.url);
const cursorDir = options.dir;
// Get server version
console.log(chalk_1.default.blue('Checking server version...'));
const versionData = await auth.get('/api/mcp/version/');
console.log(chalk_1.default.green(`Server version: ${versionData.version}`));
// Check local version
let localVersion = '0';
const mcpJsonPath = path.join(cursorDir, 'mcp.json');
if (fs.existsSync(mcpJsonPath)) {
try {
const mcpConfig = JSON.parse(fs.readFileSync(mcpJsonPath, 'utf8'));
localVersion = ((_a = mcpConfig === null || mcpConfig === void 0 ? void 0 : mcpConfig.optimus_config) === null || _a === void 0 ? void 0 : _a.version) || '0';
console.log(chalk_1.default.blue(`Local version: ${localVersion}`));
}
catch (err) {
console.log(chalk_1.default.yellow('Error reading local version, will re-initialize'));
}
}
// Compare versions and initialize if needed
const needsInit = !fs.existsSync(mcpJsonPath) || parseFloat(localVersion) < parseFloat(versionData.version);
if (needsInit) {
console.log(chalk_1.default.green('Downloading configuration files...'));
// Create cursor directory if needed
if (!fs.existsSync(cursorDir)) {
fs.mkdirSync(cursorDir, { recursive: true });
}
// Get git username
let username;
try {
username = (0, child_process_1.execSync)('git config user.name').toString().trim();
}
catch (err) {
username = 'unknown';
console.warn(chalk_1.default.yellow('Warning: Could not get git username, using "unknown"'));
}
// Download all required files with consistent timestamp
const timestamp = Math.floor(Date.now() / 1000).toString();
await auth.downloadFileWithTimestamp('/api/mcp/mcp.json', path.join(cursorDir, 'mcp.json'), { username }, timestamp);
console.log(chalk_1.default.green('✓ Downloaded mcp.json'));
await auth.downloadFileWithTimestamp('/api/mcp/chat-formatting.mdc', path.join(cursorDir, 'chat-formatting.md'), {}, timestamp);
console.log(chalk_1.default.green('✓ Downloaded chat-formatting.md'));
await auth.downloadFileWithTimestamp('/api/mcp/mcp_rules.md', path.join(cursorDir, 'mcp_rules.md'), {}, timestamp);
console.log(chalk_1.default.green('✓ Downloaded mcp_rules.md'));
console.log(chalk_1.default.green('\nOptimus Security has been successfully initialized.'));
}
else {
console.log(chalk_1.default.green('Optimus Security is up to date.'));
}
}
catch (err) {
console.error(chalk_1.default.red('Error:'), err);
process.exit(1);
}
});
// Parse command line arguments
commander_1.program.parse(process.argv);
// If no arguments, display help
if (!process.argv.slice(2).length) {
commander_1.program.outputHelp();
}