{"_id":"@appinventiv/aws-s3","_rev":"2-2c31cba61c09108aaf3381a8305e690f","name":"@appinventiv/aws-s3","dist-tags":{"latest":"1.0.1"},"versions":{"1.0.0":{"name":"@appinventiv/aws-s3","version":"1.0.0","keywords":[],"author":"","license":"ISC","_id":"@appinventiv/aws-s3@1.0.0","maintainers":[{"name":"developer-at","email":"abhishektyagi199816@gmail.com"},{"name":"abhishek.tyagi1","email":"abhishek.tyagi1@appinventiv.com"}],"dist":{"shasum":"64621807d8cd51f8bac3190ea912b994d074df8d","tarball":"https://registry.npmjs.org/@appinventiv/aws-s3/-/aws-s3-1.0.0.tgz","fileCount":7,"integrity":"sha512-p5aHcAnt7sWqXBio9W42O90qOQCmV3RHtINGNpDm0VQVRpRE/bSMUn8aBV+B8dlolAjRxTaGp+9Fc/rwI9q+4Q==","signatures":[{"sig":"MEYCIQCm9k2NmtLONiSSP+Q+3nnsNtrrtkKkusx/cySRaKGNkQIhAP28quIXA3mUtPw1dKcz3sp36JSE4tJ4BZZDSTDQ4bRv","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":37185},"main":"dist/index.js","types":"dist/index.d.ts","scripts":{"test":"echo \"Error: no test specified\" && exit 1","build":"tsc"},"_npmUser":{"name":"abhishek.tyagi1","email":"abhishek.tyagi1@appinventiv.com"},"_npmVersion":"10.9.3","description":"A comprehensive AWS S3 client package for Node.js applications. Provides easy-to-use methods for uploading, reading, deleting files, and generating presigned URLs for both S3 and CloudFront.","directories":{},"_nodeVersion":"22.19.0","dependencies":{"@aws-sdk/client-s3":"^3.975.0","@aws-sdk/cloudfront-signer":"^3.975.0","@aws-sdk/s3-request-presigner":"^3.975.0"},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^5.9.3","@types/node":"^25.0.10"},"_npmOperationalInternal":{"tmp":"tmp/aws-s3_1.0.0_1769575627005_0.7218929807469932","host":"s3://npm-registry-packages-npm-production"}},"1.0.1":{"name":"@appinventiv/aws-s3","version":"1.0.1","description":"A comprehensive AWS S3 client package for Node.js applications. Provides easy-to-use methods for uploading, reading, deleting files, and generating presigned URLs for both S3 and CloudFront.","main":"dist/index.js","types":"dist/index.d.ts","scripts":{"build":"tsc","test":"echo \"Error: no test specified\" && exit 1"},"keywords":[],"author":"","license":"ISC","devDependencies":{"@types/node":"^25.0.10","typescript":"^5.9.3"},"dependencies":{"@aws-sdk/client-s3":"^3.975.0","@aws-sdk/cloudfront-signer":"^3.975.0","@aws-sdk/s3-request-presigner":"^3.975.0"},"_id":"@appinventiv/aws-s3@1.0.1","_nodeVersion":"22.19.0","_npmVersion":"10.9.3","dist":{"integrity":"sha512-19UcV52cNQtioV0k9BvMQ3xVgMl2eUppego3XE3atg6fmu3f72ejX/s5nouRHic3bTtxBJskBD4TkegF1OzKmA==","shasum":"c1d2863f606c0b3b92e8877a9f2bb13fb0fb1170","tarball":"https://registry.npmjs.org/@appinventiv/aws-s3/-/aws-s3-1.0.1.tgz","fileCount":20,"unpackedSize":226144,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEYCIQDU6rP9+dveqIDhAOYNLlfxw5IJZwVIZo3JTgf1uh5XmgIhANey7dMfnIz0bJdFUSyxgxGA2H7nPAF6XOQdmMiKGldN"}]},"_npmUser":{"name":"abhishek.tyagi1","email":"abhishek.tyagi1@appinventiv.com"},"directories":{},"maintainers":[{"name":"developer-at","email":"abhishektyagi199816@gmail.com"},{"name":"abhishek.tyagi1","email":"abhishek.tyagi1@appinventiv.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/aws-s3_1.0.1_1769589867810_0.8446256166156649"},"_hasShrinkwrap":false}},"time":{"created":"2026-01-28T04:47:06.858Z","modified":"2026-01-28T08:44:28.120Z","1.0.0":"2026-01-28T04:47:07.211Z","1.0.1":"2026-01-28T08:44:27.980Z"},"license":"ISC","keywords":[],"description":"A comprehensive AWS S3 client package for Node.js applications. Provides easy-to-use methods for uploading, reading, deleting files, and generating presigned URLs for both S3 and CloudFront.","maintainers":[{"name":"developer-at","email":"abhishektyagi199816@gmail.com"},{"name":"abhishek.tyagi1","email":"abhishek.tyagi1@appinventiv.com"}],"readme":"# @appinventiv/aws-s3\n\nA comprehensive AWS S3 client package for Node.js applications. Provides easy-to-use methods for uploading, reading, deleting files, and generating presigned URLs for both S3 and CloudFront.\n\n## Installation\n\n```bash\nnpm install @appinventiv/aws-s3\n```\n\n## Features\n\n- Upload files to S3 using presigned URLs\n- Read files from S3 buckets\n- Delete files from S3 buckets\n- Generate S3 presigned URLs for uploads\n- Generate CloudFront signed URLs for secure file access\n- Generate CloudFront signed cookies for folder access\n- Get file content as Base64 encoded string\n- Support for private key loading from local filesystem or S3\n\n## Prerequisites\n\n- AWS account with S3 access\n- AWS credentials configured (via environment variables, IAM role, or AWS credentials file)\n- `AWS_REGION` environment variable set\n- (Optional) CloudFront distribution for signed URL generation\n\n## AWS Setup\n\n1. Create an S3 bucket in AWS\n2. Ensure your AWS credentials have permissions to access S3\n3. Set the `AWS_REGION` environment variable\n4. (Optional) Configure CloudFront distribution for signed URLs\n\n### Required IAM Permissions\n\n```json\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Action\": [\n        \"s3:GetObject\",\n        \"s3:PutObject\",\n        \"s3:DeleteObject\",\n        \"s3:ListBucket\"\n      ],\n      \"Resource\": [\n        \"arn:aws:s3:::your-bucket-name\",\n        \"arn:aws:s3:::your-bucket-name/*\"\n      ]\n    }\n  ]\n}\n```\n\n## Usage\n\n### Basic Setup\n\n```typescript\nimport { s3Service } from '@appinventiv/aws-s3';\n\n// Set AWS region (required)\nprocess.env.AWS_REGION = 'us-east-1';\n\n// Initialize S3 service\ns3Service.initialiseS3Manager({\n  cloudfrontDomain: 'https://d1234567890.cloudfront.net',  // Optional\n  cloudfrontKeyPairId: 'APKAIOSFODNN7EXAMPLE'              // Optional\n});\n```\n\n### Generate Presigned URL for Upload\n\nGenerate a presigned URL that allows clients to upload files directly to S3:\n\n```typescript\nimport { s3Service } from '@appinventiv/aws-s3';\n\n// Initialize S3 service\ns3Service.initialiseS3Manager();\n\n// Generate presigned URL for file upload\nconst presignedUrl = await s3Service.getPreSignedUrl(\n  'my-bucket',           // Bucket name\n  'uploads/images',      // Base path/folder\n  'photo.jpg',           // File name\n  3600                   // Expiration in seconds (1 hour)\n);\n\nconsole.log('Presigned URL:', presignedUrl);\n\n// Client can now upload file using this URL\n// Example: PUT request to presignedUrl with file in body\n```\n\n### Read File from S3\n\nRead a file directly from S3 bucket:\n\n```typescript\nimport { s3Service } from '@appinventiv/aws-s3';\n\n// Initialize S3 service\ns3Service.initialiseS3Manager();\n\n// Read file content\nconst fileContent = await s3Service.readFile(\n  'uploads/images/photo.jpg',  // S3 object key\n  'my-bucket',                  // Bucket name\n  'utf-8'                       // Optional encoding (default: UTF-8)\n);\n\nconsole.log('File content:', fileContent);\n```\n\n### Delete File from S3\n\nDelete a file from S3 bucket:\n\n```typescript\nimport { s3Service } from '@appinventiv/aws-s3';\n\n// Initialize S3 service\ns3Service.initialiseS3Manager();\n\n// Delete file\nawait s3Service.deleteFile(\n  'my-bucket',                  // Bucket name\n  'uploads/images/photo.jpg'    // S3 object key\n);\n\nconsole.log('File deleted successfully');\n```\n\n### Get File as Base64\n\nGet file content as Base64 encoded string:\n\n```typescript\nimport { s3Service } from '@appinventiv/aws-s3';\n\n// Initialize S3 service\ns3Service.initialiseS3Manager();\n\n// Get file as Base64\nconst base64Data = await s3Service.getFileBase64Data({\n  bucket: 'my-bucket',\n  path: 'uploads/images/photo.jpg'\n});\n\nconsole.log('Base64 data:', base64Data);\n// Use this for embedding in HTML, sending via API, etc.\n```\n\n### CloudFront Signed URLs\n\nGenerate CloudFront signed URLs for secure file access:\n\n#### Setup CloudFront Private Key\n\nFirst, load the CloudFront private key:\n\n```typescript\nimport { s3Service } from '@appinventiv/aws-s3';\n\n// Load private key from local filesystem\nawait s3Service.loadConfigForReadablePresignedUrl(\n  '/path/to/private-key.pem',  // Local file path\n  false                         // Not stored on S3\n);\n\n// Or load private key from S3\nawait s3Service.loadConfigForReadablePresignedUrl(\n  'keys/cloudfront-private-key.pem',  // S3 key\n  true,                                // Stored on S3\n  'my-config-bucket'                   // S3 bucket name\n);\n```\n\n#### Generate CloudFront Signed URL for File\n\n```typescript\nimport { s3Service } from '@appinventiv/aws-s3';\n\n// Initialize with CloudFront config\ns3Service.initialiseS3Manager({\n  cloudfrontDomain: 'https://d1234567890.cloudfront.net',\n  cloudfrontKeyPairId: 'APKAIOSFODNN7EXAMPLE'\n});\n\n// Load private key\nawait s3Service.loadConfigForReadablePresignedUrl(\n  '/path/to/private-key.pem',\n  false\n);\n\n// Generate signed URL for a file\nconst signedUrl = await s3Service.getPreSignedUrlToReadFile(\n  '/uploads/images/photo.jpg',  // File path (relative to CloudFront domain)\n  3600000                       // Expiration in milliseconds (1 hour)\n);\n\nconsole.log('Signed URL:', signedUrl);\n// URL is valid for the specified expiration time\n```\n\n#### Generate CloudFront Signed Cookies for Folder\n\nGenerate signed cookies that allow access to all files in a folder:\n\n```typescript\nimport { s3Service } from '@appinventiv/aws-s3';\n\n// Initialize with CloudFront config\ns3Service.initialiseS3Manager({\n  cloudfrontDomain: 'https://d1234567890.cloudfront.net',\n  cloudfrontKeyPairId: 'APKAIOSFODNN7EXAMPLE'\n});\n\n// Load private key\nawait s3Service.loadConfigForReadablePresignedUrl(\n  '/path/to/private-key.pem',\n  false\n);\n\n// Generate signed cookies for folder access\nconst cookies = await s3Service.getPreSignedUrlToReadFolder(\n  '/uploads/images/',  // Folder path (relative to CloudFront domain)\n  3600000              // Expiration in milliseconds (1 hour)\n);\n\nconsole.log('Signed cookies:', cookies);\n// Set these cookies in the browser to access all files in the folder\n```\n\n### Complete Example\n\n```typescript\nimport { s3Service } from '@appinventiv/aws-s3';\n\nasync function setupS3Service() {\n  // Set AWS region\n  process.env.AWS_REGION = 'us-east-1';\n\n  // Initialize S3 service with CloudFront config\n  s3Service.initialiseS3Manager({\n    cloudfrontDomain: 'https://d1234567890.cloudfront.net',\n    cloudfrontKeyPairId: 'APKAIOSFODNN7EXAMPLE'\n  });\n\n  // Load CloudFront private key\n  await s3Service.loadConfigForReadablePresignedUrl(\n    './keys/cloudfront-private-key.pem',\n    false\n  );\n\n  // Generate presigned URL for upload\n  const uploadUrl = await s3Service.getPreSignedUrl(\n    'my-bucket',\n    'uploads',\n    'document.pdf',\n    3600\n  );\n  console.log('Upload URL:', uploadUrl);\n\n  // Read file from S3\n  const content = await s3Service.readFile(\n    'uploads/document.pdf',\n    'my-bucket'\n  );\n  console.log('File content:', content);\n\n  // Get file as Base64\n  const base64 = await s3Service.getFileBase64Data({\n    bucket: 'my-bucket',\n    path: 'uploads/document.pdf'\n  });\n  console.log('Base64:', base64);\n\n  // Generate CloudFront signed URL\n  const signedUrl = await s3Service.getPreSignedUrlToReadFile(\n    '/uploads/document.pdf',\n    3600000\n  );\n  console.log('Signed URL:', signedUrl);\n}\n\nsetupS3Service().catch(console.error);\n```\n\n### Express.js Integration Example\n\n```typescript\nimport express from 'express';\nimport { s3Service } from '@appinventiv/aws-s3';\n\nconst app = express();\n\n// Initialize S3 on startup\ns3Service.initialiseS3Manager({\n  cloudfrontDomain: process.env.CLOUDFRONT_DOMAIN || '',\n  cloudfrontKeyPairId: process.env.CLOUDFRONT_KEY_PAIR_ID || ''\n});\n\n// Load CloudFront private key\nif (process.env.CLOUDFRONT_PRIVATE_KEY_PATH) {\n  await s3Service.loadConfigForReadablePresignedUrl(\n    process.env.CLOUDFRONT_PRIVATE_KEY_PATH,\n    false\n  );\n}\n\n// Generate upload URL endpoint\napp.post('/api/upload-url', async (req, res) => {\n  try {\n    const { fileName, folder } = req.body;\n    \n    const presignedUrl = await s3Service.getPreSignedUrl(\n      process.env.S3_BUCKET || 'my-bucket',\n      folder || 'uploads',\n      fileName,\n      3600\n    );\n    \n    res.json({ uploadUrl: presignedUrl });\n  } catch (error) {\n    res.status(500).json({ error: 'Failed to generate upload URL' });\n  }\n});\n\n// Get file endpoint\napp.get('/api/file/:key', async (req, res) => {\n  try {\n    const content = await s3Service.readFile(\n      req.params.key,\n      process.env.S3_BUCKET || 'my-bucket'\n    );\n    \n    res.send(content);\n  } catch (error) {\n    res.status(404).json({ error: 'File not found' });\n  }\n});\n\n// Generate signed URL endpoint\napp.post('/api/signed-url', async (req, res) => {\n  try {\n    const { filePath, expiration } = req.body;\n    \n    const signedUrl = await s3Service.getPreSignedUrlToReadFile(\n      filePath,\n      expiration || 3600000\n    );\n    \n    res.json({ signedUrl });\n  } catch (error) {\n    res.status(500).json({ error: 'Failed to generate signed URL' });\n  }\n});\n\napp.listen(3000, () => {\n  console.log('Server started on port 3000');\n});\n```\n\n## API Reference\n\n### `s3Service` (Singleton Instance)\n\nPre-configured S3 service instance ready to use.\n\n### `AWSS3Provider` Class\n\nMain S3 provider class.\n\n#### `initialiseS3Manager(config?: IS3Config)`\n\nInitializes the S3 service with optional CloudFront configuration.\n\n**Parameters:**\n- `config.cloudfrontDomain` (string, optional): CloudFront distribution domain\n- `config.cloudfrontKeyPairId` (string, optional): CloudFront key pair ID\n\n**Example:**\n```typescript\ns3Service.initialiseS3Manager({\n  cloudfrontDomain: 'https://d1234567890.cloudfront.net',\n  cloudfrontKeyPairId: 'APKAIOSFODNN7EXAMPLE'\n});\n```\n\n#### `loadConfigForReadablePresignedUrl(privateKeyPath: string, isStoredOnS3: boolean, bucket?: string)`\n\nLoads CloudFront private key from local filesystem or S3.\n\n**Parameters:**\n- `privateKeyPath` (string): Path to private key (local path or S3 key)\n- `isStoredOnS3` (boolean): Whether key is stored in S3\n- `bucket` (string, optional): S3 bucket name (required if `isStoredOnS3` is true)\n\n**Example:**\n```typescript\n// From local filesystem\nawait s3Service.loadConfigForReadablePresignedUrl('/path/to/key.pem', false);\n\n// From S3\nawait s3Service.loadConfigForReadablePresignedUrl('keys/key.pem', true, 'my-bucket');\n```\n\n#### `getPreSignedUrl(bucketName: string, basePath: string, fileName: string, expiresIn?: number)`\n\nGenerates a presigned URL for uploading files to S3.\n\n**Parameters:**\n- `bucketName` (string): S3 bucket name\n- `basePath` (string): Base path/folder in bucket\n- `fileName` (string): Name of the file\n- `expiresIn` (number, optional): Expiration time in seconds (default: 120)\n\n**Returns:**\n- `Promise<string>`: Presigned URL for upload\n\n**Example:**\n```typescript\nconst url = await s3Service.getPreSignedUrl('my-bucket', 'uploads', 'file.jpg', 3600);\n```\n\n#### `readFile(key: string, bucket: string, encoding?: string)`\n\nReads a file from S3 bucket.\n\n**Parameters:**\n- `key` (string): S3 object key (file path)\n- `bucket` (string): S3 bucket name\n- `encoding` (string, optional): File encoding (default: UTF-8)\n\n**Returns:**\n- `Promise<string>`: File content as string\n\n**Example:**\n```typescript\nconst content = await s3Service.readFile('uploads/file.txt', 'my-bucket', 'utf-8');\n```\n\n#### `deleteFile(bucket: string, key: string)`\n\nDeletes a file from S3 bucket.\n\n**Parameters:**\n- `bucket` (string): S3 bucket name\n- `key` (string): S3 object key (file path)\n\n**Returns:**\n- `Promise<object>`: Delete operation result\n\n**Example:**\n```typescript\nawait s3Service.deleteFile('my-bucket', 'uploads/file.jpg');\n```\n\n#### `getFileBase64Data(fileData: { bucket: string; path: string })`\n\nGets file content as Base64 encoded string.\n\n**Parameters:**\n- `fileData.bucket` (string): S3 bucket name\n- `fileData.path` (string): S3 object key (file path)\n\n**Returns:**\n- `Promise<string>`: Base64 encoded file content\n\n**Example:**\n```typescript\nconst base64 = await s3Service.getFileBase64Data({\n  bucket: 'my-bucket',\n  path: 'uploads/image.jpg'\n});\n```\n\n#### `getPreSignedUrlToReadFile(filePath: string, expiration: number)`\n\nGenerates a CloudFront signed URL for reading a file.\n\n**Parameters:**\n- `filePath` (string): File path relative to CloudFront domain\n- `expiration` (number): Expiration time in milliseconds\n\n**Returns:**\n- `Promise<string>`: CloudFront signed URL\n\n**Example:**\n```typescript\nconst signedUrl = await s3Service.getPreSignedUrlToReadFile('/uploads/file.jpg', 3600000);\n```\n\n#### `getPreSignedUrlToReadFolder(folderPath: string, expiration: number)`\n\nGenerates CloudFront signed cookies for folder access.\n\n**Parameters:**\n- `folderPath` (string): Folder path relative to CloudFront domain\n- `expiration` (number): Expiration time in milliseconds\n\n**Returns:**\n- `Promise<object>`: CloudFront signed cookies object\n\n**Example:**\n```typescript\nconst cookies = await s3Service.getPreSignedUrlToReadFolder('/uploads/images/', 3600000);\n```\n\n## Environment Variables\n\n- `AWS_REGION` (required): AWS region where your S3 bucket is located (e.g., `us-east-1`)\n\n## CloudFront Setup\n\nTo use CloudFront signed URLs:\n\n1. Create a CloudFront distribution pointing to your S3 bucket\n2. Create a CloudFront key pair in AWS\n3. Download the private key\n4. Configure the package with CloudFront domain and key pair ID\n5. Load the private key using `loadConfigForReadablePresignedUrl()`\n\n## Error Handling\n\nThe package includes structured error handling with `S3Exception` class. All errors are automatically categorized and returned in a consistent format:\n\n```typescript\nimport { s3Service, S3Exception } from '@appinventiv/aws-s3';\n\ntry {\n    await s3Service.readFile('file.jpg', 'my-bucket');\n} catch (error) {\n    if (error instanceof S3Exception) {\n        const errorResponse = error.getError();\n        // Returns: { status: 404, data: { message, type, originalError, context, ... } }\n    }\n}\n```\n\nError types include: Connection, Authentication, Not Found, Validation, Timeout, Server, and Operation errors.\n\n## TypeScript Support\n\nThe package includes full TypeScript definitions and is written in TypeScript.\n\n## Dependencies\n\n- `@aws-sdk/client-s3`: ^3.975.0\n- `@aws-sdk/cloudfront-signer`: ^3.975.0\n- `@aws-sdk/s3-request-presigner`: ^3.975.0\n\n## Security Best Practices\n\n1. **Never commit AWS credentials** to version control\n2. **Use IAM roles** when running on AWS infrastructure (EC2, ECS, Lambda)\n3. **Set appropriate expiration times** for presigned URLs\n4. **Use CloudFront signed URLs** for secure file access\n5. **Store private keys securely** (use AWS Secrets Manager or environment variables)\n6. **Use least privilege IAM policies** for S3 access\n7. **Enable S3 bucket encryption** for sensitive files\n\n## Troubleshooting\n\n### Common Issues\n\n1. **\"Unable to Connect Error\"**\n   - Verify AWS credentials are configured\n   - Check `AWS_REGION` environment variable is set\n   - Ensure IAM permissions are correct\n\n2. **\"File not found\" errors**\n   - Verify bucket name is correct\n   - Check S3 object key (path) is correct\n   - Ensure file exists in the bucket\n\n3. **CloudFront signed URL errors**\n   - Verify CloudFront domain and key pair ID are correct\n   - Ensure private key is loaded before generating signed URLs\n   - Check private key format is correct (PEM format)\n\n4. **Presigned URL expiration**\n   - URLs expire after the specified time\n   - Generate new URLs if expired\n   - Consider longer expiration times for production use\n\n## License\n\nISC\n","readmeFilename":"README.md"}