Skip to main content
code<spar>
Concepts

Authentication

API key management, service authentication, key rotation, and security best practices for the CodeSpar API.

Authentication

CodeSpar uses a two-layer authentication model. Your application authenticates to CodeSpar with an API key (bearer token), and CodeSpar handles authentication to individual MCP servers (payment providers, shipping carriers, fiscal services) on your behalf using service auth credentials you configure once in the dashboard.

This separation means your AI agent never touches raw provider credentials. It only needs the CodeSpar API key.

API keys

API keys authenticate your application to the CodeSpar API. Every request to api.codespar.dev must include a valid key.

Key formats

CodeSpar issues two types of keys, distinguished by prefix:

PrefixEnvironmentBehavior
csk_live_ProductionConnects to real provider APIs. Processes real transactions, issues real invoices, sends real messages.
csk_test_SandboxConnects to mock servers. Returns realistic simulated data. No real money moves, no real documents are issued.

Using API keys with the SDK

import { CodeSpar } from "@codespar/sdk";

// Production -- real transactions
const codespar = new CodeSpar({
  apiKey: "csk_live_abc123def456ghi789...",
});

// Sandbox -- mock data, safe for development
const codespar = new CodeSpar({
  apiKey: "csk_test_abc123def456ghi789...",
});

Using API keys with curl

Pass the key as a Bearer token in the Authorization header:

curl -X POST https://api.codespar.dev/v1/sessions \
  -H "Authorization: Bearer csk_live_abc123def456ghi789..." \
  -H "Content-Type: application/json" \
  -d '{"servers": ["stripe", "mercadopago"]}'

Creating keys in the dashboard

  1. Navigate to codespar.dev/dashboard/settings
  2. Open the API Keys tab
  3. Click Create Key
  4. Name the key (e.g., "Production Backend", "Staging", "CI/CD Pipeline")
  5. Select the environment: Live or Test
  6. Optionally restrict the key's scopes (see below)
  7. Click Create and copy the key immediately -- it is only shown once
# Verify your key works
curl https://api.codespar.dev/v1/servers \
  -H "Authorization: Bearer csk_live_your_new_key..."

Never expose API keys in client-side code. Keys must stay on the server. Use process.env.CODESPAR_API_KEY or your framework's secret management (Vercel Environment Variables, AWS Secrets Manager, etc.).

Key scopes

Each API key can be scoped to specific operations. By default, new keys have all scopes. Narrow the scope for keys used in constrained contexts.

ScopeWhat it allows
sessions:createCreate new sessions
sessions:readList and retrieve session details
tools:executeExecute tool calls via session.execute() and session.send()
servers:readBrowse the server catalog
billing:readView usage and billing data
api-keys:manageCreate and revoke API keys

Example: A key used only by a webhook handler that processes tool results should have only tools:execute and sessions:read scopes.

# This request will fail with 403 if the key lacks sessions:create scope
curl -X POST https://api.codespar.dev/v1/sessions \
  -H "Authorization: Bearer csk_live_webhook_key..." \
  -H "Content-Type: application/json" \
  -d '{"servers": ["stripe"]}'

Response (insufficient scope):

{
  "error": "forbidden",
  "message": "API key does not have the 'sessions:create' scope.",
  "status": 403
}

Key rotation

You can create multiple API keys and rotate them without downtime. This is critical for production systems where you cannot afford an outage during credential updates.

Rotation procedure

  1. Create a new key in the dashboard with the same scopes as the existing key
  2. Deploy the new key to your application (update environment variables, redeploy)
  3. Verify that the new key is working by checking API responses and session creation
  4. Revoke the old key in the dashboard once all instances are using the new key
# Step 1: Create new key via the dashboard

# Step 2: Test the new key
curl https://api.codespar.dev/v1/servers \
  -H "Authorization: Bearer csk_live_new_key..."
# Should return 200 OK

# Step 3: Revoke the old key via the dashboard

Revoking a key immediately terminates all active sessions created with that key. Any in-flight tool calls will fail. Always ensure all traffic has migrated to the new key before revoking.

Rotation schedule

For production systems, rotate API keys at least every 90 days. Set a calendar reminder or automate it with your secrets management system.

Service authentication

Service authentication (also called service auth) is how CodeSpar connects to third-party commerce APIs on your behalf. You store your provider credentials once in the dashboard, and CodeSpar uses them automatically when a session connects to that server.

How it works

  1. You store provider credentials (e.g., Stripe secret key, Mercado Pago access token) in the CodeSpar dashboard under Auth Configs
  2. When a session connects to that server, CodeSpar authenticates using those stored credentials
  3. Your agent code never sees the provider credentials -- they stay encrypted at rest on CodeSpar's infrastructure
// Your agent code does not handle provider auth
const session = await codespar.sessions.create({
  servers: ["stripe"],
  // CodeSpar uses your stored Stripe credentials automatically
});

// This "just works" -- auth is handled by CodeSpar
const result = await session.execute({
  name: "codespar_checkout",
  arguments: { product: "Pro Plan", amount: 9990, currency: "BRL" },
});

Configuring provider credentials

Navigate to codespar.dev/dashboard/auth-configs and add credentials for each server you plan to use:

ServerAuth typeWhat you provide
StripeAPI keySecret key (sk_live_... or sk_test_...)
Mercado PagoOAuth tokenAccess token from the Mercado Pago dashboard
AsaasAPI keyAPI key from the Asaas dashboard
TwilioAPI key + secretAccount SID + Auth Token
CorreiosContract credentialsContract number + administrative password
NF-e / SEFAZCertificateA1 digital certificate (.pfx) + password

Credentials are encrypted with AES-256 at rest and are never returned in API responses. When you view auth configs in the dashboard, only the last 4 characters of each credential are shown.

Service auth via HTTP header

For internal services and microservice architectures, CodeSpar supports a second authentication mechanism: the x-codespar-service-key header. This is used for server-to-server communication where the calling service is trusted infrastructure rather than an end-user application.

curl -X POST https://api.codespar.dev/v1/sessions \
  -H "x-codespar-service-key: cssk_internal_abc123..." \
  -H "Content-Type: application/json" \
  -d '{"servers": ["stripe"]}'

Service keys are issued separately from API keys and have elevated permissions. They bypass rate limits and can access sessions across your entire organization.

Service keys (cssk_internal_) should only be used in trusted server-to-server contexts. Never expose them in client-side code or pass them through user-facing requests.

OAuth flows for end-user connections

When manageConnections is enabled on a session, CodeSpar generates OAuth authorization URLs for servers that support user-level authentication. This allows your end users (e.g., merchants) to connect their own provider accounts through your application.

const session = await codespar.sessions.create({
  servers: ["stripe", "mercadopago"],
  manageConnections: true,
});

const connections = await session.connections();
curl https://api.codespar.dev/v1/sessions/ses_abc123/connections \
  -H "Authorization: Bearer csk_live_..."

Response:

{
  "connections": [
    {
      "server": "stripe",
      "status": "pending",
      "authUrl": "https://codespar.dev/connect/stripe?session=ses_abc123"
    },
    {
      "server": "mercadopago",
      "status": "pending",
      "authUrl": "https://codespar.dev/connect/mercadopago?session=ses_abc123"
    }
  ]
}

The user visits the authUrl, authenticates with the provider, grants permissions, and the connection status transitions to "connected". Subsequent tool calls in that session use the user's own credentials.

Security best practices

  1. Use test keys during development. csk_test_ keys connect to mock servers and never process real transactions. There is no reason to use live keys outside of production.
  2. Scope keys narrowly. A key for a read-only dashboard should only have sessions:read and billing:read scopes.
  3. Rotate keys every 90 days. Automate rotation where possible using your secrets manager.
  4. Never log API keys. Sanitize logs and error reports to avoid accidentally exposing keys. Mask all but the last 4 characters.
  5. Use environment variables. Store keys in process.env, not in source code. Add .env to .gitignore.
  6. Monitor key usage. Check the dashboard regularly for unexpected usage patterns that might indicate a compromised key.
  7. Revoke compromised keys immediately. If a key is exposed, revoke it in the dashboard and create a new one. Do not wait.
// Good: key from environment variable
const codespar = new CodeSpar({
  apiKey: process.env.CODESPAR_API_KEY,
});

// Bad: hardcoded key (will end up in version control)
const codespar = new CodeSpar({
  apiKey: "csk_live_abc123def456...",
});

Next steps