Skip to main content
ChainStream employs multiple security mechanisms to protect API access. This document covers API security best practices, common threat protection, and security configuration guidelines.
Last Updated: February 2026 | Version: v2.0

Authentication Security

Access Token Mechanism

ChainStream uses an OAuth 2.0-based authentication mechanism. You generate a JWT Access Token using your Client ID and Client Secret for API authentication. Authentication Flow: Credential Specifications
ItemSpecification
Client IDApplication unique identifier
Client Secret64 random characters
Access TokenJWT format, includes expiration and scopes
Token Validity24 hours

Access Token Generation

import { AuthenticationClient } from 'auth0';

const auth0Client = new AuthenticationClient({
  domain: 'dex.asia.auth.chainstream.io',
  clientId: process.env.CHAINSTREAM_CLIENT_ID,
  clientSecret: process.env.CHAINSTREAM_CLIENT_SECRET
});

const { data } = await auth0Client.oauth.clientCredentialsGrant({
  audience: 'https://api.dex.chainstream.io'
});

const accessToken = data.access_token;

Credential Security

Storage Requirements
Client Secret is a core credential for accessing ChainStream services. Leakage may result in service abuse and financial loss.
Storage MethodSecurity LevelNotes
Environment Variables✅ RecommendedNot in version control
Secret Management Service✅ BestAWS Secrets Manager, HashiCorp Vault, etc.
Config Files⚠️ CautionMust add to .gitignore
Hardcoded❌ ProhibitedHigh leak risk

Code Examples

// ❌ Dangerous: Hardcoded credentials
const clientId = "your_client_id";
const clientSecret = "your_secret";

// ❌ Dangerous: Committed to version control
// config.json: { "client_id": "...", "client_secret": "..." }

// ✅ Secure: Use environment variables
const clientId = process.env.CHAINSTREAM_CLIENT_ID;
const clientSecret = process.env.CHAINSTREAM_CLIENT_SECRET;

// ✅ Secure: Use secret management service
const credentials = await secretsManager.getSecret('chainstream-credentials');

Multi-App Management

We recommend creating separate Apps for different environments and services:
PurposeSuggested App NameDescription
Productionprod-mainProduction workloads
Testingtest-devDevelopment and testing
CI/CDci-pipelineAutomated testing
MonitoringmonitoringMonitoring and alerting

Transport Security

TLS Requirements

ItemRequirement
Minimum VersionTLS 1.2
Recommended VersionTLS 1.3
Certificate ValidationMust be enabled
Not SupportedHTTP, TLS 1.0/1.1

Certificate Validation

Never skip certificate validation in production environments. This exposes your application to man-in-the-middle attack risks.
// ❌ Dangerous: Skip certificate validation
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

// ✅ Secure: Normal certificate validation (default behavior)
const response = await fetch('https://api-dex.chainstream.io/v1/...');

Webhook Security

Webhook messages use a signature mechanism to ensure message source reliability.

Signature Verification

When you receive a Webhook message, you need to verify the signature using your Webhook Secret to confirm the message is from ChainStream and has not been tampered with.
ItemDescription
AlgorithmHMAC-SHA256
KeyWebhook Secret (configured in Dashboard)
Signature HeaderX-Webhook-Signature

Verification Example

const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(JSON.stringify(payload))
    .digest('hex');
  
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expectedSignature)
  );
}

// Express middleware example
app.post('/webhook', (req, res) => {
  const signature = req.headers['x-webhook-signature'];
  const isValid = verifyWebhookSignature(
    req.body,
    signature,
    process.env.WEBHOOK_SECRET
  );
  
  if (!isValid) {
    return res.status(401).send('Invalid signature');
  }
  
  // Process webhook message
  console.log('Received webhook:', req.body);
  res.status(200).send('OK');
});

Webhook Secret Rotation

To rotate your Webhook Secret:
1

Generate New Secret

Dashboard → Webhooks → Select Endpoint → Rotate Secret
2

Update Application Config

Update to the new Webhook Secret in your application
3

Verify Signature

Confirm the new Secret correctly verifies signatures

Usage Monitoring

Metrics Dashboard

In the Dashboard’s Metrics panel, you can view API and WebSocket call statistics:
MetricDescription
Request IPSource IP address
User AgentClient identifier
Status CodeHTTP status code
LatencyRequest response time
Units ConsumedUsage units consumed by this request
Total UsageCumulative usage consumed

Chart Data

The Metrics panel provides charts at multiple time dimensions:
  • Hourly — View call trends for the last 24 hours
  • Daily — View call trends for the last 30 days
  • Monthly — View historical monthly statistics
View Path: Dashboard → Metrics

Security Monitoring

🚧 Coming Soon — Security monitoring features are under development and will be available soon.
Once available, it will support:
  • Anomaly Detection — Auto-detect auth failure spikes, unusual geography, etc.
  • Alert Notifications — Email and Webhook alerts
  • Auto Protection — Temporary bans, rate limiting, etc.

IP Whitelist

🚧 Coming Soon — IP whitelist feature is under development and will be available soon.
Once available, it will support:
  • Single IP configuration (e.g., 203.0.113.50)
  • IP range configuration (e.g., 203.0.113.0/24)
  • Multiple IPs (comma-separated)

Common Attack Protection

Man-in-the-Middle Attack

Attack Method: Attacker intercepts communication between client and server. Protection Measures:
MeasureDescription
Enforce HTTPSOnly TLS 1.2+ supported
Certificate ValidationMust enable certificate verification
HSTSForce HTTPS connections

Injection Attack

Attack Method: Attacker attempts unauthorized operations through malicious input data. Protection Measures:
MeasureDescription
Input ValidationStrict parameter type checking
Parameterized QueriesPrevent SQL/NoSQL injection
Output EncodingPrevent XSS

Credential Leak Response

If you suspect your Client Secret has been leaked, immediately execute the following steps:
1

Delete App Immediately

Dashboard → Apps → Select App → Delete
2

Create New App

Dashboard → Apps → Create New App
3

Update Application Config

Update to new Client ID and Secret in all applications using the old credential
4

Check Metrics

Dashboard → Metrics → Check for abnormal calls
5

Review Security Practices

Investigate leak cause and improve security measures

Security Error Codes

Error CodeHTTP StatusDescription
UNAUTHORIZED401No authentication provided
EXPIRED_TOKEN401Access Token expired
INVALID_TOKEN401Access Token invalid
INVALID_CREDENTIALS401Client ID or Secret incorrect
Error CodeHTTP StatusDescription
FORBIDDEN403No permission or quota exhausted
RATE_LIMITED429Request rate exceeded
INSUFFICIENT_SCOPE403Token permission insufficient
Error CodeDescription
INVALID_SIGNATUREWebhook signature verification failed
MISSING_SIGNATUREMissing signature header

Error Response Example

{
  "error": {
    "code": "EXPIRED_TOKEN",
    "message": "Access token has expired",
    "details": {
      "expired_at": "2024-01-15T10:30:00Z"
    }
  }
}

Security Configuration Checklist

Basic Configuration (Required)

  • Use HTTPS for API access
  • Store Client ID and Client Secret in environment variables or secret management service
  • Don’t commit credentials to code repository
  • Use different Apps for production/test environments
  • Properly verify Webhook signatures
  • Integrate secret management service (AWS Secrets Manager / HashiCorp Vault)
  • Regularly check Metrics dashboard for call statistics
  • Create separate Apps for different services

Enterprise Configuration (Optional)

  • Integrate SIEM system for log analysis
  • Establish security incident response process

FAQ

Immediately log into Dashboard to delete that App, create a new App, then update all application configurations using that credential. See Credential Leak Response.
Access Tokens are valid for 24 hours. Recommendations:
  1. Cache Token — Reuse the same Token within validity period
  2. Refresh Early — Refresh Token about 1 hour before expiration
  3. Error Retry — Automatically get new Token when receiving 401 error
Log into Dashboard → Metrics, where you can view request IP, status codes, latency, Units consumed, and time-dimension charts.
Common causes:
  1. Secret mismatch — Confirm using the correct Webhook Secret
  2. Payload handling error — Ensure using the original JSON string for signature calculation
  3. Missing signature header — Confirm request headers include X-Webhook-Signature
Yes. We recommend creating separate Apps for different environments (production/test) and different services for easier management and troubleshooting.