@nekuda/nekuda-js
v0.2.14
Published
nekuda Node.js SDK for payment processing
Maintainers
Readme
nekuda Node.js SDK
The official TypeScript SDK for nekuda - secure credit card handling for AI web agents and crawlers. Full documentation is available at nekuda Docs.
Purpose
The nekuda SDK enables AI agents to securely collect and handle credit card information without ever handling sensitive card data directly. It provides a lightweight TypeScript client that:
- Creates mandates - Describes what the AI agent intends to purchase on behalf of users
- Manages secure tokens - Handles the token-based flow for revealing card details
- Ensures compliance - Keeps your AI application PCI-compliant by design
Requirements
Node.js 14.0 or higher.
Installation
npm install @nekuda/nekuda-js
# or with yarn
yarn add @nekuda/nekuda-js
# or with pnpm
pnpm add @nekuda/nekuda-jsQuick Start
Card Reveal Flow
import { NekudaClient, MandateData } from '@nekuda/nekuda-js';
// Initialize client with your API key
const client = NekudaClient.fromEnv();
const user = client.user('user_123');
// 1. Create a mandate describing the purchase
const mandate = new MandateData({
product: 'Premium Subscription',
price: 49.99,
currency: 'USD',
merchant: 'Example Corp',
confidenceScore: 0.95,
});
const mandateResponse = await user.createMandate(mandate);
const mandateId = mandateResponse.mandateId;
// 2. Request a one-time reveal token
const tokenData = await user.requestCardRevealToken(mandateId);
const revealToken = tokenData.revealToken;
// 3. Exchange token for card details (one-time use)
const card = await user.revealCardDetails(revealToken);
console.log(`Card: **** **** **** ${card.last4Digits}`);
// 4. Optionally retrieve billing details for shipping/contact info
const billingDetails = await user.getBillingDetails();
console.log(`Billing: ${billingDetails.cardholderName}, ${billingDetails.phoneNumber}`);Billing Details Retrieval
import { NekudaClient } from '@nekuda/nekuda-js';
const client = NekudaClient.fromEnv();
const user = client.user('user_123');
// Retrieve non-sensitive billing information for shipping/contact
const billingDetails = await user.getBillingDetails();
console.log('Billing Details:', {
cardholder: billingDetails.cardholderName,
phone: billingDetails.phoneNumber,
address: billingDetails.billingAddress,
city: billingDetails.city,
state: billingDetails.state,
zipCode: billingDetails.zipCode
});Use Cases:
- Shipping verification - Pre-fill shipping address forms
- Contact information - Send order updates and notifications
- Address validation - Verify billing vs shipping addresses
- Customer service - Support and assistance
- Express checkout - Faster checkout experiences
Key differences from card details:
- Contains no sensitive payment data (no card numbers, CVV, etc.)
- Safe for logging and storage (non-PCI data)
- Uses separate API endpoint with customer_id context
Key Features
Core Capabilities
- Fully typed: Complete TypeScript support with comprehensive type definitions
- Promise-based: Modern async/await API
- Secure authentication: Private API key authentication
- Retry logic: Automatic retry with exponential backoff for transient failures
- Modern JavaScript: ES2018+ compatible with tree-shaking support
Enhanced Error Handling
- Context-aware errors: Detailed error messages with operation and user context
- Authentication guidance: Clear messages for authentication failures
- Troubleshooting help: Built-in guidance for common error scenarios
- Debug logging: Built-in logging to help troubleshoot integration issues
Example Use Cases
The SDK is designed for AI agents that need to:
- Purchase products on e-commerce sites
- Subscribe to services
- Book travel arrangements
- Make any other legitimate purchases on behalf of users
Error Handling
The SDK provides granular exception types for different error scenarios:
import { NekudaClient } from '@nekuda/nekuda-js';
import {
AuthenticationError,
InvalidRequestError,
RateLimitError,
ServerError,
NekudaValidationError,
} from '@nekuda/nekuda-js';
try {
// Create mandate and reveal card
const mandate = new MandateData({ product: 'Test Product', price: 10.00 });
const mandateResponse = await user.createMandate(mandate);
const tokenData = await user.requestCardRevealToken(mandateResponse.mandateId);
const card = await user.revealCardDetails(tokenData.revealToken);
} catch (error) {
if (error instanceof AuthenticationError) {
console.log('Check your API key');
} else if (error instanceof RateLimitError) {
console.log('Rate limited, implement exponential backoff');
} else if (error instanceof ServerError) {
console.log('Server error, retry with backoff');
} else if (error instanceof NekudaValidationError) {
console.log(`Validation error: ${error.message}`);
}
}Configuration
Environment Variables
Set these environment variables:
NEKUDA_API_KEY=sk_test_your_api_key_here
NEKUDA_BASE_URL=https://api.nekuda.ai # Optional, defaults to productionClient Configuration
import { NekudaClient } from '@nekuda/nekuda-js';
// Option 1: From environment variables
const client = NekudaClient.fromEnv();
// Option 2: Explicit configuration
const client = new NekudaClient('your-api-key', {
timeout: 30000,
maxRetries: 3,
});
// Option 3: Mixed (env vars + overrides)
const client = NekudaClient.fromEnv({
timeout: 60000,
maxRetries: 5,
});TypeScript Support
This SDK is written in TypeScript and provides complete type definitions:
import {
NekudaClient,
MandateData,
CardRevealTokenResponse,
CardDetailsResponse,
MandateCreateResponse,
} from '@nekuda/nekuda-js';
// All methods return properly typed promises
const tokenResponse: CardRevealTokenResponse = await client.requestCardRevealToken(
'user123',
'mandate456'
);
// TypeScript will catch errors at compile time
const card: CardDetailsResponse = await client.revealCardDetails(
'user123',
tokenResponse.revealToken
);API Reference
Core Methods
Create Mandate
const mandate = new MandateData({
product: 'Premium Plan',
price: 99.99,
currency: 'USD',
merchant: 'Your Company',
confidenceScore: 0.95,
});
const mandateResponse = await user.createMandate(mandate);Request Card Reveal Token
const tokenData = await user.requestCardRevealToken(mandateId);
const revealToken = tokenData.revealToken;Reveal Card Details
const card = await user.revealCardDetails(revealToken);
console.log(`Card ending in: ${card.last4Digits}`);Get Billing Details
const billingDetails = await user.getBillingDetails();
console.log(`Billing: ${billingDetails.cardholderName}, ${billingDetails.phoneNumber}`);Response Types
Card Details Response
interface CardDetailsResponse {
cardNumber?: string; // Optional - not always available for security
cardExpiryDate: string; // MM/YY format
cardholderName: string; // Cardholder name
last4Digits?: string; // Last 4 digits of card
cardCvv?: string; // CVV (when available)
email?: string; // Email address
billingAddress?: string; // Billing address
city?: string; // City
state?: string; // State/province
zipCode?: string; // ZIP code
phoneNumber?: string; // Phone number
}Card Reveal Token Response
interface CardRevealTokenResponse {
revealToken: string; // One-time token for card reveal
expiresAt?: Date; // Token expiration time
}Mandate Create Response
interface MandateCreateResponse {
mandateId: number; // Unique mandate identifier
requestId: string; // Request tracking ID
customerId: string; // Customer ID
createdAt: Date; // Creation timestamp
updatedAt?: Date; // Last update timestamp
}Billing Details Response
interface BillingDetailsResponse {
userId: string; // User identifier
cardholderName: string; // Cardholder name
phoneNumber: string; // Phone number in E.164 format
billingAddress: string; // Street address
city?: string; // City (optional)
state?: string; // State/province (optional)
zipCode: string; // ZIP/postal code
}Development & Release
Building from Source
# Install dependencies
npm install
# Build the package
npm run build
# Run tests
npm test
# Run comprehensive validation
npm run validate:publishRelease Process
This SDK uses an automated release process with environment-specific publishing:
Development Releases
For testing experimental features and early development:
git tag dev_v1.2.3
git push origin dev_v1.2.3Publishes to: @nekuda/nekuda-js-dev (PRIVATE) with dev tag
Test/Staging Releases
For pre-production validation:
git tag test_v1.2.3
git push origin test_v1.2.3Publishes to: @nekuda/nekuda-js-test (PRIVATE) with test tag
Production Releases
For stable, production-ready releases:
git tag prod_v1.2.3
git push origin prod_v1.2.3Publishes to: @nekuda/nekuda-js (PUBLIC) with latest tag
Release Validation
Before creating any release, ensure:
- [ ] All tests pass:
npm test - [ ] Code coverage ≥ 70%:
npm run test:coverage - [ ] No linting errors:
npm run lint - [ ] TypeScript compiles:
npm run typecheck - [ ] Build validation passes:
npm run validate:build
See SDK_PUBLISH_CHECKLIST.md for the complete release checklist.
GitHub Actions
The release process is fully automated via GitHub Actions:
- Extract version from git tag
- Update package.json with environment-specific naming
- Run comprehensive tests and validation
- Build and verify artifacts
- Publish to NPM with appropriate tag
- Create GitHub release (production only)
License
Apache License 2.0 - see LICENSE for details.
Support
Security
The nekuda SDK is designed with security as a priority:
- No card data storage: Card details are never stored locally
- Token-based flow: One-time tokens minimize exposure
- TLS encryption: All API communication is encrypted
- PCI compliance: Helps keep your application compliant
