OpenAI API with NervePay Vault

Store your OpenAI API key in Vault and let agents fetch it securely at runtime. No keys in code, full audit trail, instant key rotation.

Why Vault for API Keys?

Without Vault

  • • Keys in environment variables
  • • No audit of who accessed keys
  • • Key rotation requires code deploy
  • • Keys visible to anyone with env access

With Vault

  • • Keys fetched at runtime with signature
  • • Every access logged with agent DID
  • • Update key in dashboard, no deploy needed
  • • Only signed requests can retrieve keys

Step 1: Store Your OpenAI Key

  1. Go to Dashboard → Agent Identities → Your Agent → Secrets
  2. Click New Secret
  3. Enter:
    • Name: OPENAI_API_KEY
    • Value: Your OpenAI API key (sk-...)
  4. Click Save

Step 2: TypeScript Example

import nacl from 'tweetnacl';
import bs58 from 'bs58';
import { v4 as uuidv4 } from 'uuid';

const NERVEPAY_DID = process.env.NERVEPAY_DID!;
const NERVEPAY_PRIVATE_KEY = process.env.NERVEPAY_PRIVATE_KEY!;

function signRequest(method: string, path: string) {
  const keyBytes = bs58.decode(NERVEPAY_PRIVATE_KEY);
  const nonce = uuidv4();
  const timestamp = new Date().toISOString();

  const payload = `${method}\n${path}\n${nonce}\n${timestamp}\n${NERVEPAY_DID}`;
  const signature = nacl.sign.detached(
    new TextEncoder().encode(payload),
    keyBytes
  );

  return {
    'Agent-DID': NERVEPAY_DID,
    'X-Agent-Signature': `ed25519:${Buffer.from(signature).toString('base64')}`,
    'X-Agent-Nonce': nonce,
    'X-Signature-Timestamp': timestamp,
  };
}

async function getVaultSecret(name: string) {
  const path = `/v1/vault/secrets/${encodeURIComponent(name)}`;
  const res = await fetch(`https://api.nervepay.xyz${path}`, {
    method: 'GET',
    headers: signRequest('GET', path),
  });

  if (!res.ok) throw new Error(await res.text());
  return (await res.json()).value;
}

async function callOpenAI(prompt: string) {
  const apiKey = await getVaultSecret('OPENAI_API_KEY');

  const res = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'gpt-4',
      messages: [{ role: 'user', content: prompt }],
    }),
  });

  if (!res.ok) throw new Error(await res.text());
  return (await res.json()).choices[0].message.content;
}

Step 3: Python Example

import nacl.signing
import nacl.encoding
import base64
import time
import uuid
import requests

NERVEPAY_DID = "did:nervepay:agent:..."
NERVEPAY_PRIVATE_KEY = "5Jvb..."  # Base58 private key

def sign_request(method: str, path: str) -> dict:
    key_bytes = nacl.encoding.Base58Decoder.decode(NERVEPAY_PRIVATE_KEY)
    signing_key = nacl.signing.SigningKey(key_bytes[:32])

    nonce = str(uuid.uuid4())
    timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())

    payload = f"{method}\n{path}\n{nonce}\n{timestamp}\n{NERVEPAY_DID}"
    signed = signing_key.sign(payload.encode('utf-8'))

    return {
        'Agent-DID': NERVEPAY_DID,
        'X-Agent-Signature': f'ed25519:{base64.b64encode(signed.signature).decode()}',
        'X-Agent-Nonce': nonce,
        'X-Signature-Timestamp': timestamp,
    }

def get_vault_secret(name: str) -> str:
    path = f"/v1/vault/secrets/{name}"
    headers = sign_request('GET', path)

    r = requests.get(f"https://api.nervepay.xyz{path}", headers=headers)
    if not r.ok: raise Exception(r.text)
    return r.json()['value']

def call_openai(prompt: str) -> str:
    api_key = get_vault_secret('OPENAI_API_KEY')

    r = requests.post(
        'https://api.openai.com/v1/chat/completions',
        headers={
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json',
        },
        json={'model': 'gpt-4', 'messages': [{'role': 'user', 'content': prompt}]},
    )

    if not r.ok: raise Exception(r.text)
    return r.json()['choices'][0]['message']['content']

Environment Setup

# .env or deployment environment
NERVEPAY_DID=did:nervepay:agent:...
NERVEPAY_PRIVATE_KEY=5Jvb...  # Base58 private key from agent passport

Error Handling

try {
  const apiKey = await getVaultSecret('OPENAI_API_KEY');
} catch (e) {
  if (e.message.includes('401')) {
    console.error('Signature failed — check your private key');
  } else if (e.message.includes('404')) {
    console.error('Secret not found — create it in the dashboard');
  } else {
    console.error('Vault error:', e.message);
  }
}

Related