API Vault Documentation

Welcome to the API Vault documentation. This guide covers everything you need to know about using API Vault for secure secret management.

JavaScript SDK

The API Vault SDK allows you to securely access your vault keys from JavaScript/TypeScript projects. This SDK is read-only: key creation, update, and deletion must be performed via the API Vault web platform.

✅ Supports both ES Modules and CommonJS - works in any JavaScript environment!

Installation

npm install amay-key-vault-sdk

Getting Started

Step 1: Get Your API Token

  1. 1. Login to your API Vault application
  2. 2. Navigate to the "API" page
  3. 3. Copy your API token (starts with tok_)

Step 2: Initialize the SDK

ES Modules (Recommended)
import KeyVault from 'amay-key-vault-sdk';

const kv = new KeyVault({
  apiUrl: 'https://yourdomain.com/api',
  getToken: () => 'your-api-token',
  onAuthError: () => console.log('Token expired')
});
CommonJS
const KeyVault = require('amay-key-vault-sdk');

const kv = new KeyVault({
  apiUrl: 'https://yourdomain.com/api',
  getToken: () => 'your-api-token',
  onAuthError: () => console.log('Token expired')
});

Step 3: Retrieve Secrets

// Simple function to get a key by name
async function getKey(keyName, folderId) {
  const { keys } = await kv.listKeys({ folderId, limit: 100 });
  const key = keys.find(k => k.name === keyName);
  const keyWithValue = await kv.getKey(key.id, { includeValue: true });
  return keyWithValue.value;
}

// Usage
const apiKey = await getKey('key-name', 'folder-id');

// Or get all keys in a folder
const { keys } = await kv.listKeys({ folderId: 'folder-id' });
console.log('Available keys:', keys.map(k => k.name));

API Reference

new KeyVault({ apiUrl, getToken, onAuthError? })

  • apiUrl (string): Base URL of your API Vault API
  • getToken (function): Function that returns your API token
  • onAuthError (function, optional): Callback for authentication errors

listKeys({ folderId, limit?, offset? })

  • folderId (string, required): Folder to list keys from
  • limit (number, optional): Number of keys to return (default: 20)
  • offset (number, optional): Number of keys to skip (default: 0)
  • Returns: { keys, total, limit, offset } - Array of key metadata (no values)

getKey(keyId, { includeValue })

  • keyId (string, required): The key's ID
  • includeValue (boolean, optional): If true, includes the decrypted key value
  • Returns: key object with metadata and optionally the value

getKey(keyId, { includeValue? })

  • keyId (string, required): The key's ID
  • includeValue (boolean, optional): If true, includes the decrypted key value
  • Returns: key object with metadata and optionally the value

Module Format Support

The SDK automatically detects your module system and provides the appropriate format. No configuration needed - it just works!

ES Modules

// package.json: "type": "module"
import KeyVault from 'amay-key-vault-sdk';

const kv = new KeyVault({
  apiUrl: 'https://yourdomain.com/api',
  getToken: () => 'your-token'
});

CommonJS

// package.json: no "type" field
const KeyVault = require('amay-key-vault-sdk');

const kv = new KeyVault({
  apiUrl: 'https://yourdomain.com/api',
  getToken: () => 'your-token'
});

Usage Examples

Simple Key Retrieval

// Simple function to get any key by name
async function getKey(keyName, folderId) {
  const { keys } = await kv.listKeys({ folderId, limit: 100 });
  const key = keys.find(k => k.name === keyName);
  const keyWithValue = await kv.getKey(key.id, { includeValue: true });
  return keyWithValue.value;
}

// Usage
const apiKey = await getKey('stripe-secret-key', 'your-folder-id');
const dbPassword = await getKey('database-password', 'your-folder-id');

Get Database URL from Key Vault

async function getDatabaseUrl() {
  try {
    // First, list keys to find the one you want
    const { keys } = await kv.listKeys({ folderId: 'your-folder-id' });
    
    // Find the key by name
    const dbUrlKey = keys.find(key => key.name === 'DB_URL');
    
    if (dbUrlKey) {
      // Get the actual value
      const keyWithValue = await kv.getKey(dbUrlKey.id, { includeValue: true });
      console.log('Database URL retrieved successfully');
      return keyWithValue.value;
    } else {
      throw new Error('DB_URL key not found');
    }
  } catch (error) {
    console.error('Error fetching database URL:', error);
    throw error;
  }
}

// Use it
const databaseUrl = await getDatabaseUrl();
const { Pool } = require('pg');
const pool = new Pool({ connectionString: databaseUrl });

Environment-Specific Secrets

const environment = process.env.NODE_ENV || 'development';
const folderId = environment === 'production' ? 'prod-folder' : 'dev-folder';

const secrets = {
  database: await kv.getKeyValue(folderId, 'DB_URL'),
  apiKey: await kv.getKeyValue(folderId, 'API_KEY'),
  jwtSecret: await kv.getKeyValue(folderId, 'JWT_SECRET')
};

Error Handling

try {
  const secret = await kv.getKeyValue('folder-id', 'DB_URL');
  // Use secret
} catch (error) {
  if (error.message.includes('not found')) {
    console.error('DB_URL not found');
  } else if (error.message.includes('Unauthorized')) {
    console.error('Invalid API token');
  } else {
    console.error('Failed to retrieve DB_URL:', error.message);
  }
}

Python SDK

The API Vault Python SDK allows you to securely access your vault keys from Python applications. This SDK is read-only: key creation, update, and deletion must be performed via the API Vault web platform.

✅ Latest Version: v1.0.1 - Fixed URL construction bug for improved reliability.

Installation

pip install amay-key-vault-sdk

Getting Started

Step 1: Get Your API Token

  1. 1. Login to your API Vault application
  2. 2. Navigate to the "API" page
  3. 3. Copy your API token

Step 2: Initialize the SDK

from key_vault_sdk import KeyVault

# Initialize the SDK
kv = KeyVault(
    api_url="https://yourdomain.com/api",
    token="your-api-token-here"
)

Step 3: Retrieve Secrets

# Get a specific secret value by name
secret_value = kv.get_key_by_name("folder-id", "DB_URL")
print("Secret retrieved successfully")

# Or get all keys in a folder
result = kv.list_keys(folder_id="folder-id")
print("Available keys:", [k['name'] for k in result['keys']])

API Reference

KeyVault(api_url, token, timeout=30)

  • api_url (str): Base URL of your API Vault API
  • token (str): Your API token for authentication
  • timeout (int, optional): Request timeout in seconds

list_keys(folder_id, limit=20, offset=0)

  • folder_id (str, required): Folder to list keys from
  • limit (int, optional): Number of keys to return (default: 20)
  • offset (int, optional): Number of keys to skip (default: 0)
  • Returns: dict - Dictionary with keys list and pagination info

get_key(key_id, include_value=False)

  • key_id (str, required): The key's ID
  • include_value (bool, optional): If True, include the decrypted key value
  • Returns: dict - Key object with metadata and optionally the value

get_key_by_name(folder_id, key_name)

  • folder_id (str, required): Folder containing the key
  • key_name (str, required): Name of the key to retrieve
  • Returns: str - The decrypted secret value

Usage Examples

Simple Key Retrieval

from key_vault_sdk import KeyVault

# Initialize
kv = KeyVault(
    api_url="https://yourdomain.com/api",
    token="your-api-token"
)

# Get a key by name
api_key = kv.get_key_by_name("folder-id", "key-name")
print(f"API Key: {api_key}")

# Get multiple keys
keys = kv.get_multiple_keys(
    folder_id="folder-id",
    key_names=["stripe-key", "database-password"]
)
print(f"Retrieved keys: {keys}")

Error Handling

from key_vault_sdk import KeyVault, KeyVaultError, KeyVaultAuthError, KeyVaultNotFoundError

try:
    secret = kv.get_key_by_name("folder-id", "secret-name")
    # Use secret
except KeyVaultNotFoundError:
    print("Secret not found")
except KeyVaultAuthError:
    print("Invalid API token")
except KeyVaultError as e:
    print(f"Failed to retrieve secret: {e}")

REST API

The Key Vault REST API provides full programmatic access to your secrets. All endpoints require authentication.

Base URL

https://yourdomain.com/api

Authentication

All API requests require authentication via:

  • Session Cookie: For web application requests
  • Bearer Token: For API access (Authorization: Bearer <token>)

Direct API Usage (Alternative to SDK)

If you prefer to use direct API calls instead of the SDK:

import fetch from 'node-fetch';

const BASE_URL = 'https://yourdomain.com';
const API_TOKEN = 'tok_your-api-token-here';

async function getDatabaseUrl() {
  try {
    // 1. List folders to get folder ID
    const foldersResponse = await fetch(`${BASE_URL}/api/folders`, {
      headers: {
        'Authorization': `Bearer ${API_TOKEN}`,
        'Content-Type': 'application/json'
      }
    });
    
    const foldersData = await foldersResponse.json();
    const folderId = foldersData.folders[0].id;
    
    // 2. List keys in the folder
    const keysResponse = await fetch(`${BASE_URL}/api/keys?folderId=${folderId}`, {
      headers: {
        'Authorization': `Bearer ${API_TOKEN}`,
        'Content-Type': 'application/json'
      }
    });
    
    const keysData = await keysResponse.json();
    
    // 3. Find the DB_URL key
    const dbUrlKey = keysData.keys.find(key => key.name === 'DB_URL');
    
    if (dbUrlKey) {
      // 4. Get the actual value
      const keyValueResponse = await fetch(`${BASE_URL}/api/keys/${dbUrlKey.id}?includeValue=true`, {
        headers: {
          'Authorization': `Bearer ${API_TOKEN}`,
          'Content-Type': 'application/json'
        }
      });
      
      const keyValueData = await keyValueResponse.json();
      console.log('Database URL retrieved successfully');
      return keyValueData.key.value;
    }
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

// Use it
const databaseUrl = await getDatabaseUrl();

Key Endpoints

Create a Key

POST /api/keys
Content-Type: application/json

{
  "name": "Database Password",
  "value": "secret-password",
  "type": "PASSWORD",
  "folderId": "folder-id",
  "description": "Production database password"
}

List Keys

GET /api/keys?folderId=folder-id

Get Key Value

GET /api/keys/{keyId}?includeValue=true

Update Key

PUT /api/keys/{keyId}
Content-Type: application/json

{
  "name": "Updated Name",
  "value": "new-secret-value"
}

Delete Key

DELETE /api/keys/{keyId}

Folder Endpoints

Create Folder

POST /api/folders
Content-Type: application/json

{
  "name": "Production",
  "description": "Production environment secrets",
  "color": "#ff0000"
}

List Folders

GET /api/folders

Authentication

Getting Your API Token

  1. 1. Log in to your Key Vault account
  2. 2. Navigate to the "API" page
  3. 3. Copy your API token
  4. 4. Use this token in your SDK or API requests

Token Security

  • • Keep your API token secure and never expose it in client-side code
  • • Store tokens in environment variables
  • • Rotate tokens regularly for security
  • • Never commit tokens to version control

Security

Encryption

  • • All secret values are encrypted using AES-256-GCM
  • • Each encryption uses a unique salt and IV
  • • Master encryption key is stored securely

Access Control

  • • Users can only access their own secrets
  • • Admin users have additional privileges
  • • Complete audit logging for compliance

Best Practices

  • • Never log secret values
  • • Use environment variables for configuration
  • • Handle errors gracefully without exposing sensitive information
  • • Regularly rotate API tokens

Subscription Plans

Free Plan

  • • 1 project (folder)
  • • 5 secrets
  • • SDK access
  • • Basic UI dashboard
  • • Community support

Pro Plan ($9/month)

  • • 3 projects
  • • 100 secrets
  • • Audit logs
  • • Expiring secrets
  • • API analytics
  • • Email support

Team Plan ($29/month)

  • • Unlimited projects
  • • 1,000+ secrets
  • • Team members
  • • RBAC (roles & permissions)
  • • SDK token rotation
  • • Priority support

FAQ

How do I get my API token?

Log in to the Key Vault web platform and navigate to the "API" page to copy your API token.

Can I create or delete keys with the SDK?

No, the SDK is read-only for security. Use the web platform or REST API for key management.

What happens if I reach my plan limits?

You'll see warnings in the UI and API calls will be rejected. Upgrade your plan to continue.

Is the SDK open source?

Yes! You can view and contribute to the SDK on our GitHub repository.

How secure is the encryption?

We use AES-256-GCM encryption with unique salts and IVs for each secret. The encryption key is stored securely and never exposed.

Does the SDK support CommonJS?

Yes! The SDK supports both ES Modules and CommonJS. It automatically detects your module system and provides the appropriate format.

Can I use the SDK in the browser?

Yes, the SDK works in both Node.js and browser environments.

Support

Need help? Check out our GitHub repository for issues and feature requests, or contact us through the support channels available in your plan.

License

MIT License - see LICENSE file for details.