UNPKG

optimus-init

Version:

Initialization utility for Optimus Security

258 lines (257 loc) 9.95 kB
"use strict"; 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 }); exports.OptimusAuth = void 0; const fs = __importStar(require("fs")); const crypto = __importStar(require("crypto")); const axios_1 = __importDefault(require("axios")); /** * Optimus Authentication Client * Handles authentication for API requests to Optimus endpoints */ class OptimusAuth { /** * Create a new OptimusAuth client * @param envPath Path to the optimus.env file * @param baseUrl Base URL for the API (optional, will use OPTIMUS_ENDPOINT from env file if not provided) */ constructor(envPath = './optimus.env', baseUrl) { // Load credentials from env file const envVars = this.loadEnvFile(envPath); this.keyId = envVars.OPTIMUS_KEY_ID; this.token = envVars.OPTIMUS_TOKEN; // Use provided baseUrl or extract from OPTIMUS_ENDPOINT if (baseUrl) { this.baseUrl = baseUrl; } else if (envVars.OPTIMUS_ENDPOINT) { // Extract base URL from OPTIMUS_ENDPOINT (remove /optimus_security/ suffix) this.baseUrl = envVars.OPTIMUS_ENDPOINT.replace(/\/optimus_security\/?$/, ''); } else { throw new Error('Missing OPTIMUS_ENDPOINT in env file and no baseUrl provided'); } if (!this.keyId || !this.token) { throw new Error('Missing OPTIMUS_KEY_ID or OPTIMUS_TOKEN in env file'); } } /** * Load environment variables from file */ loadEnvFile(filePath) { try { const content = fs.readFileSync(filePath, 'utf8'); const result = {}; content.split('\n').forEach(line => { line = line.trim(); if (line && !line.startsWith('#')) { const [key, value] = line.split('=', 2); if (key && value) { result[key.trim()] = value.trim(); } } }); return result; } catch (err) { console.error('Error loading env file:', err); throw new Error(`Could not load env file: ${err}`); } } /** * Generate authentication signature */ generateSignature(timestamp, payload) { // Convert payload to string if needed let payloadStr; if (typeof payload === 'string') { payloadStr = payload; } else { // Create a sorted object for consistent signature generation const sortedPayload = {}; Object.keys(payload).sort().forEach(key => { sortedPayload[key] = payload[key]; }); // Match Python's json.dumps() format exactly (with spaces after colons) payloadStr = JSON.stringify(sortedPayload).replace(/":/g, '": '); } // Create the string to sign const stringToSign = `${timestamp}:${payloadStr}`; // Generate HMAC-SHA256 signature return crypto .createHmac('sha256', this.token) .update(stringToSign) .digest('hex'); } /** * Get authentication headers * @param payload Request payload (for signature generation) * @returns Authentication headers */ getAuthHeaders(payload = {}) { const timestamp = Math.floor(Date.now() / 1000).toString(); const signature = this.generateSignature(timestamp, payload); return { 'X-Key-ID': this.keyId, 'X-Signature': signature, 'X-Timestamp': timestamp }; } /** * Make authenticated GET request * @param endpoint API endpoint path (will be appended to baseUrl) * @param params Query parameters * @returns Response data */ async get(endpoint, params = {}) { var _a, _b; try { const url = `${this.baseUrl}${endpoint}`; const headers = this.getAuthHeaders(params); const response = await axios_1.default.get(url, { headers, params }); return response.data; } catch (err) { if (axios_1.default.isAxiosError(err)) { throw new Error(`API request failed: ${(_a = err.response) === null || _a === void 0 ? void 0 : _a.status} ${(_b = err.response) === null || _b === void 0 ? void 0 : _b.statusText}`); } throw err; } } /** * Make authenticated POST request * @param endpoint API endpoint path * @param data Request body * @returns Response data */ async post(endpoint, data = {}) { var _a, _b; try { const url = `${this.baseUrl}${endpoint}`; const headers = this.getAuthHeaders(data); const response = await axios_1.default.post(url, data, { headers }); return response.data; } catch (err) { if (axios_1.default.isAxiosError(err)) { throw new Error(`API request failed: ${(_a = err.response) === null || _a === void 0 ? void 0 : _a.status} ${(_b = err.response) === null || _b === void 0 ? void 0 : _b.statusText}`); } throw err; } } /** * Download a file from an authenticated endpoint * @param endpoint API endpoint path * @param outputPath Path to save the file * @param params Query parameters */ async downloadFile(endpoint, outputPath, params = {}) { var _a, _b; try { const url = `${this.baseUrl}${endpoint}`; const headers = this.getAuthHeaders(params); const response = await axios_1.default.get(url, { headers, params, responseType: 'stream' }); // Ensure directory exists const dir = outputPath.substring(0, outputPath.lastIndexOf('/')); if (dir && !fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } // Save the file const writer = fs.createWriteStream(outputPath); response.data.pipe(writer); return new Promise((resolve, reject) => { writer.on('finish', resolve); writer.on('error', reject); }); } catch (err) { if (axios_1.default.isAxiosError(err)) { throw new Error(`File download failed: ${(_a = err.response) === null || _a === void 0 ? void 0 : _a.status} ${(_b = err.response) === null || _b === void 0 ? void 0 : _b.statusText}`); } throw err; } } /** * Download a file from an authenticated endpoint with a specific timestamp * @param endpoint API endpoint path * @param outputPath Path to save the file * @param params Query parameters * @param timestamp Specific timestamp to use for authentication */ async downloadFileWithTimestamp(endpoint, outputPath, params = {}, timestamp) { var _a, _b; try { const url = `${this.baseUrl}${endpoint}`; const signature = this.generateSignature(timestamp, params); const headers = { 'X-Key-ID': this.keyId, 'X-Signature': signature, 'X-Timestamp': timestamp }; const response = await axios_1.default.get(url, { headers, params, responseType: 'stream' }); // Ensure directory exists const dir = outputPath.substring(0, outputPath.lastIndexOf('/')); if (dir && !fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } // Save the file const writer = fs.createWriteStream(outputPath); response.data.pipe(writer); return new Promise((resolve, reject) => { writer.on('finish', resolve); writer.on('error', reject); }); } catch (err) { if (axios_1.default.isAxiosError(err)) { throw new Error(`File download failed: ${(_a = err.response) === null || _a === void 0 ? void 0 : _a.status} ${(_b = err.response) === null || _b === void 0 ? void 0 : _b.statusText}`); } throw err; } } } exports.OptimusAuth = OptimusAuth;