All files StorageCore.js

79.13% Statements 91/115
77.17% Branches 71/92
85% Functions 17/20
79.13% Lines 91/115

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505                        1x 1x 1x 1x 1x                                                                                                                         40x     40x 1x   39x     39x     39x             39x 39x   39x                   39x         39x 39x 39x                               1x 1x                                 4x 1x   3x                                   3x 1x     2x 2x 1x 1x   1x                                           5x 1x   4x 1x   3x 1x       2x 2x   2x                                   5x 1x   4x 1x     3x                               3x     3x       3x 3x 1x   2x 1x   1x                                     4x     4x       4x                                   1x     1x       1x                             9x 2x 7x   7x   2x 2x             9x                                               2x     2x     2x       2x 2x   2x 1x         1x                             9x 2x     7x   7x                                     7x                                     2x     2x       2x                                     1x       1x 1x   1x 1x 2x     1x 1x     1x             1x    
/**
 * @module @onlineapps/storage-core
 * @description Core MinIO storage operations for OA Drive
 * 
 * Provides basic storage operations shared by business and infrastructure services.
 * No business logic, caching, or logging - just core MinIO operations.
 * 
 * @author OA Drive Team
 * @license ISC
 * @since 1.0.0
 */
 
const Minio = require('minio');
const crypto = require('crypto');
const http = require('http');
const DEFAULTS = require('./defaults');
const runtimeCfg = require('./config');
 
/**
 * Custom HTTP transport that redirects requests to actual MinIO host
 * while keeping "localhost" as endpoint for AWS Signature compatibility.
 * 
 * MinIO 2025+ validates Host header and only accepts localhost/127.0.0.1.
 * AWS Signature v4 includes Host header in signature calculation.
 * 
 * Solution: 
 * - SDK uses endpoint "localhost" (for signature)
 * - This transport redirects to actual MinIO host (MINIO_ACTUAL_HOST env)
 */
function createMinioTransport(actualHost, actualPort) {
  return {
    request: function(options, callback) {
      // Redirect to actual MinIO host while keeping Host header as localhost
      options.hostname = actualHost;
      options.host = `${actualHost}:${actualPort}`;
      options.port = actualPort;
      return http.request(options, callback);
    }
  };
}
 
/**
 * Core Storage Client for MinIO
 * 
 * Provides basic storage operations without business-specific features.
 * Used by both business services (via conn-base-storage) and infrastructure services.
 * 
 * @class StorageCore
 * 
 * @example
 * const { StorageCore } = require('@onlineapps/storage-core');
 * 
 * const storage = new StorageCore({
 *   endPoint: 'api_shared_storage',
 *   port: 9000,
 *   accessKey: 'minioadmin',
 *   secretKey: 'minioadmin'
 * });
 * 
 * await storage.initialize();
 * await storage.putObject('bucket', 'path/to/file', buffer);
 */
class StorageCore {
  /**
   * Creates a new StorageCore instance
   * 
   * @constructor
   * @param {Object} [config={}] - Configuration options
   * @param {string} [config.endPoint='localhost'] - MinIO server endpoint
   * @param {number} [config.port=9000] - MinIO server port
   * @param {boolean} [config.useSSL=false] - Use SSL/TLS
   * @param {string} [config.accessKey='minioadmin'] - Access key
   * @param {string} [config.secretKey='minioadmin'] - Secret key
   * 
   * @throws {Error} If configuration is invalid
   */
  constructor(config = {}) {
    const resolved = runtimeCfg.resolve(config);
 
    // Validate required config values (explicit empty string should fail)
    if (!resolved.endPoint || String(resolved.endPoint).trim() === '') {
      throw new Error('[StorageCore] Missing required config: endPoint (set MINIO_ENDPOINT env or pass config.endPoint)');
    }
    Iif (!resolved.accessKey || String(resolved.accessKey).trim() === '') {
      throw new Error('[StorageCore] Missing required config: accessKey (set MINIO_ACCESS_KEY env or pass config.accessKey)');
    }
    Iif (!resolved.secretKey || String(resolved.secretKey).trim() === '') {
      throw new Error('[StorageCore] Missing required config: secretKey (set MINIO_SECRET_KEY env or pass config.secretKey)');
    }
    Iif (!Number.isFinite(resolved.port)) {
      throw new Error('[StorageCore] Missing required config: port (set MINIO_PORT env or pass config.port)');
    }
    
    // Check if we need to use transport redirect for MinIO hostname validation
    // When MINIO_ACTUAL_HOST is set, we use "localhost" as endpoint for signature
    // but redirect actual requests to MINIO_ACTUAL_HOST
    const actualHost = resolved.actualHost;
    const useTransportRedirect = actualHost && actualHost !== resolved.endPoint;
    
    const minioConfig = {
      // When using transport redirect, endpoint is "localhost" for AWS signature
      endPoint: useTransportRedirect ? DEFAULTS.signatureEndpoint : resolved.endPoint,
      port: resolved.port,
      useSSL: resolved.useSSL,
      accessKey: resolved.accessKey,
      secretKey: resolved.secretKey
    };
    
    // Add custom transport for hostname validation workaround
    Iif (useTransportRedirect) {
      minioConfig.transport = createMinioTransport(actualHost, resolved.port);
    }
 
    // Create MinIO client
    this.client = new Minio.Client(minioConfig);
    this.config = minioConfig;
    this.initialized = false;
  }
 
  /**
   * Initialize storage client
   * 
   * Currently a no-op, but kept for API consistency and future use.
   * 
   * @async
   * @method initialize
   * @returns {Promise<boolean>} Always returns true
   * 
   * @example
   * await storage.initialize();
   */
  async initialize() {
    this.initialized = true;
    return true;
  }
 
  /**
   * Check if bucket exists
   * 
   * @async
   * @method bucketExists
   * @param {string} bucket - Bucket name
   * @returns {Promise<boolean>} True if bucket exists
   * 
   * @throws {Error} If check fails
   * 
   * @example
   * const exists = await storage.bucketExists('my-bucket');
   */
  async bucketExists(bucket) {
    if (!bucket) {
      throw new Error('[StorageCore] bucketExists: bucket name is required');
    }
    return await this.client.bucketExists(bucket);
  }
 
  /**
   * Ensure bucket exists, create if it doesn't
   * 
   * @async
   * @method ensureBucket
   * @param {string} bucket - Bucket name
   * @param {string} [region='us-east-1'] - Bucket region
   * @returns {Promise<boolean>} True if bucket exists or was created
   * 
   * @throws {Error} If bucket creation fails
   * 
   * @example
   * await storage.ensureBucket('my-bucket');
   */
  async ensureBucket(bucket, region = 'us-east-1') {
    if (!bucket) {
      throw new Error('[StorageCore] ensureBucket: bucket name is required');
    }
    
    const exists = await this.bucketExists(bucket);
    if (!exists) {
      await this.client.makeBucket(bucket, region);
      return true; // Created
    }
    return false; // Already existed
  }
 
  /**
   * Upload object to storage
   * 
   * @async
   * @method putObject
   * @param {string} bucket - Bucket name
   * @param {string} path - Object path
   * @param {Buffer|string} data - Object data
   * @param {Object} [metadata={}] - Object metadata
   * @returns {Promise<void>}
   * 
   * @throws {Error} If upload fails
   * 
   * @example
   * await storage.putObject('bucket', 'path/to/file', buffer, {
   *   'Content-Type': 'application/json'
   * });
   */
  async putObject(bucket, path, data, metadata = {}) {
    if (!bucket) {
      throw new Error('[StorageCore] putObject: bucket name is required');
    }
    if (!path) {
      throw new Error('[StorageCore] putObject: path is required');
    }
    if (!data) {
      throw new Error('[StorageCore] putObject: data is required');
    }
 
    // Convert string to Buffer if needed
    const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data);
    const size = buffer.length;
 
    await this.client.putObject(bucket, path, buffer, size, metadata);
  }
 
  /**
   * Download object from storage
   * 
   * @async
   * @method getObject
   * @param {string} bucket - Bucket name
   * @param {string} path - Object path
   * @returns {Promise<Buffer>} Object data as Buffer
   * 
   * @throws {Error} If download fails or object doesn't exist
   * 
   * @example
   * const buffer = await storage.getObject('bucket', 'path/to/file');
   */
  async getObject(bucket, path) {
    if (!bucket) {
      throw new Error('[StorageCore] getObject: bucket name is required');
    }
    if (!path) {
      throw new Error('[StorageCore] getObject: path is required');
    }
 
    return await this.client.getObject(bucket, path);
  }
 
  /**
   * Check if object exists
   * 
   * @async
   * @method objectExists
   * @param {string} bucket - Bucket name
   * @param {string} path - Object path
   * @returns {Promise<boolean>} True if object exists
   * 
   * @example
   * const exists = await storage.objectExists('bucket', 'path/to/file');
   */
  async objectExists(bucket, path) {
    Iif (!bucket) {
      throw new Error('[StorageCore] objectExists: bucket name is required');
    }
    Iif (!path) {
      throw new Error('[StorageCore] objectExists: path is required');
    }
 
    try {
      await this.statObject(bucket, path);
      return true;
    } catch (err) {
      if (err.code === 'NotFound' || err.code === 'NoSuchKey') {
        return false;
      }
      throw err;
    }
  }
 
  /**
   * Get object metadata
   * 
   * @async
   * @method statObject
   * @param {string} bucket - Bucket name
   * @param {string} path - Object path
   * @returns {Promise<Object>} Object metadata
   * 
   * @throws {Error} If object doesn't exist or stat fails
   * 
   * @example
   * const stat = await storage.statObject('bucket', 'path/to/file');
   */
  async statObject(bucket, path) {
    Iif (!bucket) {
      throw new Error('[StorageCore] statObject: bucket name is required');
    }
    Iif (!path) {
      throw new Error('[StorageCore] statObject: path is required');
    }
 
    return await this.client.statObject(bucket, path);
  }
 
  /**
   * Delete object from storage
   * 
   * @async
   * @method deleteObject
   * @param {string} bucket - Bucket name
   * @param {string} path - Object path
   * @returns {Promise<void>}
   * 
   * @throws {Error} If deletion fails
   * 
   * @example
   * await storage.deleteObject('bucket', 'path/to/file');
   */
  async deleteObject(bucket, path) {
    Iif (!bucket) {
      throw new Error('[StorageCore] deleteObject: bucket name is required');
    }
    Iif (!path) {
      throw new Error('[StorageCore] deleteObject: path is required');
    }
 
    await this.client.removeObject(bucket, path);
  }
 
  /**
   * Generate SHA256 fingerprint for content
   * 
   * @method calculateFingerprint
   * @param {string|Buffer|Object} content - Content to fingerprint
   * @returns {string} SHA256 hash in hex format
   * 
   * @example
   * const hash = storage.calculateFingerprint('Hello World');
   * // Returns: SHA256 hash (64 hex characters)
   */
  calculateFingerprint(content) {
    if (content === undefined || content === null) {
      content = String(content);
    } else Iif (typeof content === 'symbol') {
      content = content.toString();
    } else if (typeof content !== 'string' && !Buffer.isBuffer(content)) {
      // Handle objects and arrays
      try {
        content = JSON.stringify(content);
      } catch (err) {
        // If circular reference, use a deterministic string representation
        content = '[Circular Reference]';
      }
    }
 
    return crypto
      .createHash('sha256')
      .update(content)
      .digest('hex');
  }
 
  /**
   * Verify object fingerprint
   * 
   * Downloads object and verifies its fingerprint matches expected value.
   * 
   * @async
   * @method verifyFingerprint
   * @param {string} bucket - Bucket name
   * @param {string} path - Object path
   * @param {string} expectedFingerprint - Expected SHA256 fingerprint
   * @returns {Promise<boolean>} True if fingerprint matches
   * 
   * @throws {Error} If object doesn't exist or verification fails
   * 
   * @example
   * const verified = await storage.verifyFingerprint('bucket', 'path/to/file', 'abc123...');
   */
  async verifyFingerprint(bucket, path, expectedFingerprint) {
    Iif (!bucket) {
      throw new Error('[StorageCore] verifyFingerprint: bucket name is required');
    }
    Iif (!path) {
      throw new Error('[StorageCore] verifyFingerprint: path is required');
    }
    Iif (!expectedFingerprint) {
      throw new Error('[StorageCore] verifyFingerprint: expectedFingerprint is required');
    }
 
    const buffer = await this.getObject(bucket, path);
    const actualFingerprint = this.calculateFingerprint(buffer);
    
    if (actualFingerprint !== expectedFingerprint) {
      throw new Error(
        `[StorageCore] Fingerprint mismatch: expected ${expectedFingerprint}, got ${actualFingerprint}`
      );
    }
    
    return true;
  }
 
  /**
   * Get content type from filename extension
   * 
   * @method getContentType
   * @param {string} filename - Filename or path
   * @returns {string} MIME type
   * 
   * @example
   * const contentType = storage.getContentType('document.pdf');
   * // Returns: 'application/pdf'
   */
  getContentType(filename) {
    if (!filename || typeof filename !== 'string') {
      return 'application/octet-stream';
    }
 
    const ext = filename.split('.').pop()?.toLowerCase() || '';
    
    const types = {
      'pdf': 'application/pdf',
      'png': 'image/png',
      'jpg': 'image/jpeg',
      'jpeg': 'image/jpeg',
      'gif': 'image/gif',
      'html': 'text/html',
      'json': 'application/json',
      'xml': 'application/xml',
      'txt': 'text/plain',
      'csv': 'text/csv',
      'md': 'text/markdown',
      'markdown': 'text/markdown',
      'doc': 'application/msword',
      'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      'xls': 'application/vnd.ms-excel',
      'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    };
 
    return types[ext] || 'application/octet-stream';
  }
 
  /**
   * Generate presigned URL for object access
   * 
   * @async
   * @method getPresignedUrl
   * @param {string} bucket - Bucket name
   * @param {string} path - Object path
   * @param {number} [expiry=3600] - URL expiration in seconds
   * @returns {Promise<string>} Presigned URL
   * 
   * @throws {Error} If URL generation fails
   * 
   * @example
   * const url = await storage.getPresignedUrl('bucket', 'path/to/file', 3600);
   */
  async getPresignedUrl(bucket, path, expiry = 3600) {
    Iif (!bucket) {
      throw new Error('[StorageCore] getPresignedUrl: bucket name is required');
    }
    Iif (!path) {
      throw new Error('[StorageCore] getPresignedUrl: path is required');
    }
 
    return await this.client.presignedGetObject(bucket, path, expiry);
  }
 
  /**
   * List objects by prefix
   * 
   * @async
   * @method listByPrefix
   * @param {string} bucket - Bucket name
   * @param {string} prefix - Path prefix
   * @param {boolean} [recursive=true] - Recursive listing
   * @returns {Promise<Array>} Array of object names
   * 
   * @throws {Error} If listing fails
   * 
   * @example
   * const objects = await storage.listByPrefix('bucket', 'path/to/');
   */
  async listByPrefix(bucket, prefix = '', recursive = true) {
    Iif (!bucket) {
      throw new Error('[StorageCore] listByPrefix: bucket name is required');
    }
 
    const objects = [];
    const stream = this.client.listObjects(bucket, prefix, recursive);
    
    return new Promise((resolve, reject) => {
      stream.on('data', (obj) => {
        objects.push(obj.name);
      });
      
      stream.on('end', () => {
        resolve(objects);
      });
      
      stream.on('error', (err) => {
        reject(err);
      });
    });
  }
}
 
module.exports = StorageCore;