{"_id":"@biorbank/moon-card-issuing-sdk","name":"@biorbank/moon-card-issuing-sdk","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@biorbank/moon-card-issuing-sdk","version":"0.1.0","description":"TypeScript SDK for Moon's Card Issuing API","main":"dist/index.js","module":"dist/index.mjs","types":"dist/index.d.ts","private":false,"scripts":{"build":"tsup","dev":"tsup --watch","test":"jest","test:watch":"jest --watch","type-check":"tsc --noEmit","lint":"eslint src --ext .ts","format":"prettier --write src","generate-types":"node scripts/generate-types.js","prepublishOnly":"npm run build","setup":"npm run setup:env && npm run setup:webhook-secret","setup:env":"cp .env.example .env && echo '✅ Created .env file - please edit with your actual values'","setup:webhook-secret":"node -e \"console.log('\\n🔐 Generated webhook secret:\\n' + require('crypto').randomBytes(32).toString('hex') + '\\n\\nAdd this to your .env file as MOON_WEBHOOK_SECRET')\"","example:basic":"npm run build && node dist/examples/basic-usage.js","example:secure":"npm run build && node dist/examples/secure-integration.js","example:webhooks":"npm run build && node dist/examples/webhook-management.js","example:gift-cards":"npm run build && node dist/examples/gift-card-management.js","security:check":"npm run type-check && echo '✅ Security type checks passed'","security:docs":"echo '📖 Security documentation: ./SECURITY.md'"},"keywords":["moon","card-issuing","api","sdk","typescript","payments","crypto","cards"],"author":{"name":"Moon SDK Team"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/paywithmoon/typescript-sdk.git"},"dependencies":{"axios":"^1.11.0"},"devDependencies":{"@types/jest":"^30.0.0","@types/node":"^24.2.1","@typescript-eslint/eslint-plugin":"^8.39.0","@typescript-eslint/parser":"^8.39.0","eslint":"^9.33.0","jest":"^30.0.5","prettier":"^3.6.2","ts-jest":"^29.4.1","tsup":"^8.5.0","typescript":"^5.9.2"},"engines":{"node":">=16"},"_id":"@biorbank/moon-card-issuing-sdk@0.1.0","gitHead":"bdbbe798b265e81a88c4a34b65109cf2a45da432","bugs":{"url":"https://github.com/paywithmoon/typescript-sdk/issues"},"homepage":"https://github.com/paywithmoon/typescript-sdk#readme","_nodeVersion":"22.17.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-L1lJloOqSrZx/iuHSuf9T8dcbmRfkKpnwtBjBQW/zobA6u25k/DwccQHI7VjCp2s3HGtEUIqWBWprWO9QLFTAg==","shasum":"599c72dd05d6d183c24d4b09d7ea9f27c6242ba3","tarball":"https://registry.npmjs.org/@biorbank/moon-card-issuing-sdk/-/moon-card-issuing-sdk-0.1.0.tgz","fileCount":8,"unpackedSize":878763,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIE3eADaWh8irmDOiPk3f0qY40Nvm+ffiPBTv7ezwAkgiAiEAgjQn52XlB+OcWVIPw1qf2N9gvb6PWkDu6qFuzOp37M4="}]},"_npmUser":{"name":"keithagroves","email":"keithalgroves@gmail.com"},"directories":{},"maintainers":[{"name":"keithagroves","email":"keithalgroves@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/moon-card-issuing-sdk_0.1.0_1757473921449_0.04431435192696487"},"_hasShrinkwrap":false}},"time":{"created":"2025-09-10T03:12:01.322Z","0.1.0":"2025-09-10T03:12:01.776Z","modified":"2025-09-10T03:12:02.039Z"},"maintainers":[{"name":"keithagroves","email":"keithalgroves@gmail.com"}],"description":"TypeScript SDK for Moon's Card Issuing API","homepage":"https://github.com/paywithmoon/typescript-sdk#readme","keywords":["moon","card-issuing","api","sdk","typescript","payments","crypto","cards"],"repository":{"type":"git","url":"git+https://github.com/paywithmoon/typescript-sdk.git"},"author":{"name":"Moon SDK Team"},"bugs":{"url":"https://github.com/paywithmoon/typescript-sdk/issues"},"license":"MIT","readme":"# Moon Card Issuing SDK for TypeScript\n\nA comprehensive TypeScript SDK for Moon's Card Issuing API, providing type-safe access to card management, transaction processing, and crypto funding capabilities.\n\n## Features\n\n- 🔒 **Type Safe** - Full TypeScript support with auto-generated types\n- 🏗️ **Modular** - Clean resource-based architecture  \n- ⚡ **Modern** - Built with async/await and ES modules\n- 🛡️ **Robust** - Comprehensive error handling and retries\n- 🔄 **Auto Retry** - Smart retry logic for transient failures\n- 📖 **Well Documented** - Complete JSDoc documentation\n- 🛡️ **PCI DSS Compliant** - Automatic card data masking and secure handling\n- 🔐 **Webhook Security** - HMAC signature validation and replay protection\n- ⚡ **JIT Authorization** - Sub-second response with rate limiting\n- 🔑 **API Key Management** - Rotation tracking and security monitoring\n- 📋 **Secure Logging** - Environment-aware sensitive data filtering\n- 🔍 **Audit Framework** - Comprehensive security event tracking\n\n## Installation\n\n```bash\nnpm install moon-card-issuing-sdk\n# or\nyarn add moon-card-issuing-sdk\n```\n\n## Setup\n\n### Quick Setup (Recommended)\n\nUse our automated setup script to get started quickly:\n\n```bash\n# Create .env file and generate secure webhook secret\nnpm run setup\n\n# This will:\n# 1. Copy .env.example to .env\n# 2. Generate a cryptographically secure webhook secret\n# 3. Show you what values to edit\n```\n\n### Manual Setup\n\n#### 1. Environment Configuration\n\nCopy the example environment file and configure your settings:\n\n```bash\ncp .env.example .env\n```\n\nEdit `.env` with your actual values:\n\n```bash\n# Required: Your Moon API key\nMOON_API_KEY=your_actual_moon_api_key_here\n\n# Required for webhooks: Secure webhook secret (16+ characters)\nMOON_WEBHOOK_SECRET=your_cryptographically_secure_webhook_secret\n\n# Environment (staging or production)\nNODE_ENV=staging\n```\n\n#### 2. Generate Secure Webhook Secret\n\nFor webhook security, generate a cryptographically secure secret:\n\n```bash\n# Use our built-in generator\nnpm run setup:webhook-secret\n\n# Or generate manually with OpenSSL\nopenssl rand -hex 32\n\n# Or use Node.js\nnode -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"\n```\n\n#### 3. API Key Security\n\n- **Staging**: Use test API keys (may start with `pk_test_`)\n- **Production**: Use live API keys (may start with `pk_live_`)\n- **Never**: Commit API keys to version control\n- **Rotate**: Change keys regularly (monthly recommended)\n\n#### 4. Run Security Checks\n\nValidate your setup with security checks:\n\n```bash\n# Run type checking and security validation\nnpm run security:check\n\n# View security documentation\nnpm run security:docs\n```\n\n## Quick Start\n\n```typescript\nimport { MoonClient } from 'moon-card-issuing-sdk';\n\nconst moon = new MoonClient({\n  apiKey: 'your-api-key',\n  environment: 'staging' // or 'production'\n});\n\n// Create a card\nconst card = await moon.cards.create('card-product-id', {\n  amount: 100,\n  card_type: 'VIRTUAL'\n});\n\n// Add balance\nawait moon.cards.addBalance(card.id, 50);\n\n// Get transactions\nconst transactions = await moon.cards.getTransactions(card.id);\n```\n\n## Configuration\n\n### Client Options\n\n```typescript\nconst moon = new MoonClient({\n  apiKey: 'your-api-key',           // Required: Your Moon API key\n  environment: 'staging',           // 'staging' | 'production' \n  baseURL: 'custom-url',           // Optional: Override base URL\n  timeout: 30000,                  // Optional: Request timeout (ms)\n  retryOptions: {                  // Optional: Retry configuration\n    retries: 3,\n    retryDelay: 1000,\n    retryCondition: (error) => true\n  }\n});\n```\n\n### Environment URLs\n\n- **Staging**: `https://stagingapi.paywithmoon.com`\n- **Production**: `https://api.paywithmoon.com`\n\n## API Reference\n\n### Cards Resource\n\n#### Create Card\n```typescript\nconst card = await moon.cards.create(cardProductId, {\n  amount?: number,\n  card_type?: 'VIRTUAL' | 'PHYSICAL',\n  card_currency?: 'USD' | 'MXN',\n  end_customer_id?: string\n});\n```\n\n#### Get Card\n```typescript\nconst card = await moon.cards.get(cardId);\n```\n\n#### List Cards\n```typescript\nconst cards = await moon.cards.list({\n  currentPage: 1,\n  perPage: 10,\n  end_customer_id?: string,\n  include_inactive_cards?: boolean\n});\n```\n\n#### Add Balance\n```typescript\nconst updatedCard = await moon.cards.addBalance(cardId, amount);\n```\n\n#### Card Management\n```typescript\n// Freeze/unfreeze\nawait moon.cards.freeze(cardId, true);  // freeze\nawait moon.cards.freeze(cardId, false); // unfreeze\n\n// Activate\nawait moon.cards.activate(cardId);\n\n// PIN management\nconst pin = await moon.cards.getPin(cardId);\nawait moon.cards.updatePin(cardId, '1234');\n\n// Assign cardholder\nawait moon.cards.assignCardholder(cardId, externalId);\n```\n\n#### Transactions\n```typescript\n// Get transactions\nconst transactions = await moon.cards.getTransactions(cardId, {\n  currentPage: 1,\n  perPage: 20\n});\n\n// Simulate transaction (sandbox only)\nawait moon.cards.simulateTransaction(cardId, {\n  transactionAmount: 25.00,\n  transactionCurrency: 'USD',\n  transactionType: 'AUTHORIZATION',\n  merchantName: 'Test Store',\n  merchantCountryCode: 'US'\n});\n```\n\n#### Card Products\n```typescript\nconst products = await moon.cards.getCardProducts({\n  currentPage: 1,\n  perPage: 10\n});\n```\n\n### Webhooks Resource\n\n#### Register Webhook\n```typescript\n// Register a webhook endpoint\nawait moon.webhooks.register({\n  url: 'https://your-app.com/webhooks/moon'\n});\n\n// Validate webhook URL before registration\nconst validation = moon.webhooks.validateWebhookUrl('https://your-app.com/webhooks/moon');\nif (!validation.isValid) {\n  console.error('Invalid webhook URL:', validation.error);\n}\n```\n\n#### Delete Webhook\n```typescript\n// Delete registered webhook\nawait moon.webhooks.delete();\n```\n\n#### Complete Webhook Integration\n```typescript\nimport { MoonClient, createWebhookMiddleware, createWebhookConfig } from 'moon-card-issuing-sdk';\nimport express from 'express';\n\nconst moon = new MoonClient({\n  apiKey: 'your-api-key',\n  environment: 'staging'\n});\n\nconst app = express();\n\n// 1. Register webhook endpoint\nawait moon.webhooks.register({\n  url: 'https://your-app.com/webhooks/moon'\n});\n\n// 2. Set up webhook handler with security validation\nconst config = createWebhookConfig(process.env.MOON_WEBHOOK_SECRET!);\n\napp.post('/webhooks/moon', \n  createWebhookMiddleware(config, async (payload) => {\n    console.log('Secure webhook received:', payload.type);\n    \n    // Handle different event types\n    switch (payload.type) {\n      case 'CARD_TRANSACTION':\n        // Handle card transaction\n        break;\n      case 'CARD_DECLINE':\n        // Handle declined transaction\n        break;\n      case 'MOON_CREDIT_FUNDS_CREDITED':\n        // Handle funds credited\n        break;\n    }\n  })\n);\n```\n\n### Gift Cards Resource\n\n#### Purchase Gift Card\n```typescript\n// Purchase a gift card\nconst giftCard = await moon.giftCards.purchase({\n  card_product_id: 'product-id',\n  amount: '50.00'\n});\n\n// Validate purchase amount before buying\nconst product = await moon.giftCards.getProducts();\nconst validation = moon.giftCards.validatePurchaseAmount(product.data[0], 50);\nif (!validation.isValid) {\n  console.error('Invalid amount:', validation.error);\n}\n```\n\n#### Get Gift Card Details\n```typescript\n// Get gift card by ID (returns masked sensitive data)\nconst giftCard = await moon.giftCards.get('gift-card-id');\nconsole.log('Gift card value:', giftCard.value);\nconsole.log('Barcode:', giftCard.barcode);\n// PIN and security code are masked for security: \"***\"\n```\n\n#### Manage Gift Card Usage\n```typescript\n// Mark as used\nawait moon.giftCards.markAsUsed('gift-card-id');\n\n// Mark as unused\nawait moon.giftCards.markAsUnused('gift-card-id');\n\n// Custom usage status\nawait moon.giftCards.updateUsageStatus('gift-card-id', {\n  marked_used: true\n});\n```\n\n#### Browse Gift Card Products\n```typescript\n// Get all available products\nconst products = await moon.giftCards.getProducts({\n  currentPage: 1,\n  perPage: 10\n});\n\n// Filter by category\nconst retailProducts = await moon.giftCards.getProductsByCategory('retail');\n\n// Filter by merchant\nconst amazonCards = await moon.giftCards.getProductsByMerchant('Amazon');\n```\n\n#### Calculate Costs\n```typescript\n// Calculate total cost including fees and discounts\nconst product = products.data[0];\nconst calculation = moon.giftCards.calculateTotalCost(product, 100);\n\nconsole.log('Gift card amount:', calculation.giftCardAmount);\nconsole.log('Fee amount:', calculation.feeAmount);\nconsole.log('Total cost:', calculation.totalCost);\nconsole.log('Final amount (after discount):', calculation.finalAmount);\n```\n\n### Cardholders Resource\n\n#### Create and Manage Cardholders\n```typescript\n// Create a new cardholder\nconst cardholder = await moon.cardholders.create({\n  email: 'user@company.com',\n  external_id: 'EMP-12345',\n  organization_id: 'org-id'\n});\n\n// Get cardholder by ID\nconst cardholder = await moon.cardholders.get('cardholder-id');\n\n// Update cardholder information\nconst updatedCardholder = await moon.cardholders.update('cardholder-id', {\n  external_id: 'NEW-EMP-67890'\n});\n```\n\n#### List and Search Cardholders\n```typescript\n// List all cardholders with pagination\nconst cardholders = await moon.cardholders.list({\n  currentPage: 1,\n  perPage: 10,\n  organization_id: 'org-id'\n});\n\n// Find cardholders by external ID\nconst found = await moon.cardholders.findByExternalId('EMP-12345');\n\n// Find cardholders by email\nconst byEmail = await moon.cardholders.findByEmail('user@company.com');\n```\n\n#### Two-Factor Authentication\n```typescript\n// Step 1: Request login code\nawait moon.cardholders.requestLoginCode({\n  email: 'user@company.com',\n  organization_id: 'org-id'\n});\n\n// Step 2: Redeem code for token\nconst session = await moon.cardholders.redeemLoginCode({\n  email: 'user@company.com',\n  code: '123456',\n  organization_id: 'org-id'\n});\n\n// Use the JWT token for authenticated requests\nconsole.log('Token:', session.token);\nconsole.log('Expires:', session.expiresAt);\n\n// Complete authentication flow with convenience method\nconst auth = await moon.cardholders.authenticate(\n  'user@company.com',\n  'org-id',\n  async () => {\n    // This function should prompt user for the 6-digit code\n    // and return it (e.g., from a form input)\n    return prompt('Enter the 6-digit code from your email:') || '';\n  }\n);\n```\n\n#### Cardholder-Card Associations\n```typescript\n// Get all cards for a cardholder\nconst cards = await moon.cardholders.getCards('cardholder-id', {\n  currentPage: 1,\n  perPage: 10,\n  include_inactive_cards: false\n});\n\n// Check if cardholder has active cards\nconst hasCards = await moon.cardholders.hasActiveCards('cardholder-id');\n\n// Get total card count\nconst cardCount = await moon.cardholders.getCardCount('cardholder-id', true);\n```\n\n#### Utility Methods\n```typescript\n// Update external ID\nawait moon.cardholders.updateExternalId('cardholder-id', 'NEW-ID-123');\n\n// Move to different organization\nawait moon.cardholders.moveToOrganization('cardholder-id', 'new-org-id');\n\n// Update KYC status\nawait moon.cardholders.updateKYCStatus('cardholder-id', true);\n```\n\n## Error Handling\n\nThe SDK provides specific error types for different scenarios:\n\n```typescript\nimport { \n  MoonError, \n  MoonAPIError, \n  MoonNetworkError,\n  MoonValidationError,\n  MoonRateLimitError,\n  MoonAuthenticationError,\n  MoonNotFoundError\n} from 'moon-card-issuing-sdk';\n\ntry {\n  const card = await moon.cards.get('invalid-id');\n} catch (error) {\n  if (error instanceof MoonNotFoundError) {\n    console.log('Card not found');\n  } else if (error instanceof MoonAuthenticationError) {\n    console.log('Invalid API key');\n  } else if (error instanceof MoonRateLimitError) {\n    console.log('Rate limited, retry after:', error.retryAfter);\n  } else if (error instanceof MoonAPIError) {\n    console.log('API error:', error.status, error.message);\n  }\n}\n```\n\n## TypeScript Support\n\nThe SDK is fully typed with auto-generated interfaces:\n\n```typescript\nimport { Card, Transaction, CardProduct } from 'moon-card-issuing-sdk';\n\n// All responses are properly typed\nconst card: Card = await moon.cards.get('card-id');\nconst transactions: PaginatedResponse<Transaction> = await moon.cards.getTransactions('card-id');\n```\n\n## Pagination\n\nList methods return paginated responses:\n\n```typescript\ninterface PaginatedResponse<T> {\n  data: T[];\n  pagination: {\n    currentPage: number;\n    from: number;\n    lastPage: number;\n    perPage: number;\n    total: number;\n  };\n}\n```\n\n## Development\n\n### Building\n\n```bash\nnpm run build          # Build for production\nnpm run dev           # Build in watch mode\n```\n\n### Testing\n\n```bash\nnpm test              # Run tests\nnpm run test:watch    # Run tests in watch mode\n```\n\n### Type Generation\n\n```bash\nnpm run generate-types # Regenerate types from API schemas\n```\n\n## Examples\n\nCheck the [examples](./examples) directory for complete usage examples:\n\n- [Basic Usage](./examples/basic-usage.ts) - Card creation and management with PCI DSS compliance\n- [Secure Integration](./examples/secure-integration.ts) - Complete security implementation\n- [Webhook Management](./examples/webhook-management.ts) - Secure webhook integration\n- [Gift Card Management](./examples/gift-card-management.ts) - Complete gift card lifecycle\n\n### Running Examples\n\nUse the built-in npm scripts to run examples easily:\n\n```bash\n# Run basic card management example\nnpm run example:basic\n\n# Run complete security integration example (includes webhook server)\nnpm run example:secure\n\n# Run webhook management example\nnpm run example:webhooks\n\n# Run gift card management example\nnpm run example:gift-cards\n```\n\nMake sure to configure your `.env` file first with:\n```bash\nnpm run setup\n```\n\n## 🛡️ Security Features\n\nThis SDK implements comprehensive security measures for production use:\n\n### PCI DSS Compliance\n- Automatic card data masking (PAN shows only last 4 digits)\n- CVV always redacted in responses\n- PIN protection (never shown in production)\n- Secure logging without sensitive data\n\n### Webhook Security\n- HMAC-SHA256 signature validation\n- Replay attack protection with timestamp validation\n- Automatic idempotency handling\n- Secure error handling\n\n### JIT Authorization\n- Sub-second response time enforcement\n- Rate limiting per card\n- Request validation and sanitization\n- Comprehensive audit logging\n\n### API Key Management\n- Automatic rotation tracking\n- Environment-specific security recommendations\n- Usage monitoring and analytics\n- Secure key masking for logs\n\nSee [SECURITY.md](./SECURITY.md) for complete security documentation.\n\n## Webhook Support\n\nFull webhook security implementation with HMAC validation:\n\n```typescript\nimport { createWebhookMiddleware, createWebhookConfig } from 'moon-card-issuing-sdk';\n\n// CRITICAL: Never use hardcoded secrets or fallbacks\nif (!process.env.MOON_WEBHOOK_SECRET) {\n  throw new Error('MOON_WEBHOOK_SECRET environment variable is required');\n}\n\nconst config = createWebhookConfig(process.env.MOON_WEBHOOK_SECRET);\n\napp.post('/webhooks/moon', \n  createWebhookMiddleware(config, async (payload) => {\n    console.log('Secure webhook received:', payload.type);\n  })\n);\n```\n\n## API Coverage\n\n### Implemented Resources\n- ✅ **Cards** - Full CRUD, balance management, transactions, PIN management\n- ✅ **Webhooks** - Register and delete webhook endpoints with security validation\n- ✅ **Gift Cards** - Purchase, manage, and track branded gift cards\n- ✅ **Cardholders** - Identity management, two-factor authentication, card associations\n- ⏳ **Invoices** - Coming soon  \n- ⏳ **Velocity Controls** - Coming soon\n- ⏳ **Organizations** - Coming soon\n- ⏳ **Accounts** - Coming soon\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature-name`\n3. Make your changes and add tests\n4. Run tests: `npm test`\n5. Commit changes: `git commit -m 'Add feature'`\n6. Push to the branch: `git push origin feature-name`\n7. Submit a pull request\n\n## License\n\nMIT License - see [LICENSE](LICENSE) file for details.\n\n## Support\n\n- [Documentation](https://docs.paywithmoon.com)\n- [API Reference](https://docs.paywithmoon.com/reference)  \n- [GitHub Issues](https://github.com/paywithmoon/typescript-sdk/issues)\n- Email: support@paywithmoon.com","readmeFilename":"README.md","_rev":"1-2bfcf8243b8e883ba708985098321b2f"}