Security
Threat model, cryptographic primitives, and production hardening checklist.
API PIN encryption
Stackr is infrastructure for integrating projects. Your project keeps its Stackr API key on its backend; that key authenticates your operator account. The PIN belongs to your end user and authorizes their account operation. API authentication and PIN verification serve separate purposes.
Who encrypts the PIN?
- Your backend calls the REST API: collect the user’s PIN through your own secure flow, encrypt it on your backend, and send the envelope to Stackr with your project’s bearer key.
- Stackr handles the telco USSD callback: the telco posts its normal session input to
/ussd/callback. This REST envelope does not change the telco protocol. Stackr verifies the entered PIN internally. - Keep PINs, bearer keys and USSD session text out of logs. Never embed your project’s API key in a browser or mobile application.
Encrypt the PIN on your backend using AES-256-GCM. Derive a 32-byte key with HKDF-SHA256 from your API key, salt stackr-api-pin-v1 and info aes-256-gcm. Use a fresh random 12-byte nonce and authenticate stackr-api-pin-v1
METHOD
PATH
TIMESTAMP as additional data.
Copy this helper into your backend
Save it as encrypt-pin.mjs. It uses built-in Node.js cryptography and needs no additional package.
// Server-side only. Never ship your Stackr API key to a browser.
import { createCipheriv, hkdfSync, randomBytes } from 'node:crypto';
export function encryptPin(pin, apiKey, path, method = 'POST') {
if (!/^[0-9]{4}$/.test(pin)) throw new Error('PIN must be four ASCII digits');
if (!apiKey || !path.startsWith('/api/v1/')) throw new Error('API key and API path required');
const timestamp = Math.floor(Date.now() / 1000);
const nonce = randomBytes(12);
const key = hkdfSync('sha256', apiKey, 'stackr-api-pin-v1', 'aes-256-gcm', 32);
const cipher = createCipheriv('aes-256-gcm', key, nonce);
cipher.setAAD(Buffer.from(`stackr-api-pin-v1\n${method}\n${path}\n${timestamp}`));
const ciphertext = Buffer.concat([cipher.update(pin, 'utf8'), cipher.final(), cipher.getAuthTag()]);
return { version: 1, timestamp, nonce: nonce.toString('base64'), ciphertext: ciphertext.toString('base64') };
}
// Backend integration
import { encryptPin } from './encrypt-pin.mjs';
const pin = encryptPin(userPin, apiKey, '/api/v1/transfers');
// Include the object in your JSON request:
// { sender_phone, recipient_phone, amount, pin }The envelope contains version: 1, a Unix-second timestamp, Base64 nonce, and Base64 ciphertext with the 16-byte authentication tag appended. The server rejects timestamps over five minutes old or more than 30 seconds ahead. Redis prevents nonce reuse.
Set REQUIRE_ENCRYPTED_API_PINS=true to reject legacy PIN strings. Always use HTTPS and redact credentials and request bodies from logs. This field encryption uses your API key and does not protect against compromise of that key. It binds the method and route; HTTPS protects the remaining request fields.
Request and retry rules
- The plaintext PIN must be exactly four ASCII digits. Leading zeros are preserved.
- Use the same project API key for encryption and the bearer header. When rotating keys, create a new envelope with the new key.
- Bind the envelope to the exact HTTP method and path, excluding the host and query string. A PIN encrypted for
/api/v1/transferscannot be used for/api/v1/swaps. - A nonce is consumed before account/PIN verification and business processing. Generate a new envelope for every retry, even if the previous request failed. Reuse the same Idempotency-Key and payment details with the new envelope. Quote-based swaps reuse quote_id. Never create a new payment identity to resolve a timeout.
- HTTP 400 means a malformed, expired, reused, or route-mismatched envelope, or legacy plaintext rejected by configuration. HTTP 401 means authentication or PIN verification failed. HTTP 202 means payment settlement is pending. HTTP 409 means conflicting request details or an unresolved payment. Infrastructure failures return HTTP 500; a timeout does not prove payment failure.
- The same format applies to account creation, transfers, deposits, withdrawals, merchant payments, airtime, bills and swap confirmation. Quotes and status reads do not require a PIN.
Payment recovery and account protection
- Signed payments and their hashes are committed to Postgres before submission. Pending payments are reconciled every 15 seconds after startup using the original signed bytes.
- Daily spend is reserved atomically before a debit. Confirmed debits retain their spend; definitive failures release the reservation once. A later bill refund does not reset the gross daily limit.
- Five failed or in-flight PIN attempts exhaust an operator/account’s shared 15-minute budget across API and USSD. Successful verification refunds only its own attempt slot.
- SEP-10 challenges require the configured network, server signature, sequence zero, valid time bounds, matching client and domain, and permitted Manage Data operations.
- Withdrawal payments validate and preserve the anchor’s memo. Order reads are scoped to the authenticated operator.
- USSD request arguments are excluded from tracing and their Debug representation is redacted. This website’s simulator also masks sample PIN input and logs.
- Unknown bill-provider outcomes require support reconciliation. Delivery claims prevent blindly purchasing the same bill again.
Threat Model
| Threat | Mitigation |
|---|---|
| Brute-force PIN | Argon2id plus five failed/in-flight attempts per operator and phone within 15 minutes |
| Replay attacks | Postgres payment journal and stable request keys; Redis separately blocks encrypted-PIN nonce reuse |
| Webhook forgery | Constant-time secret comparison |
| IP spoofing | X-Forwarded-For only honored from trusted proxies |
| Double-credit | Atomic order state transitions |
| Key compromise | AES-256-GCM encryption at rest |
| Timing attacks | Constant-time webhook secret comparison |
Cryptography
Wallet Key Derivation
HKDF-SHA256 from master seed + phone number → deterministic ed25519 keypair
Encryption at Rest
AES-256-GCM with 12-byte random nonce per record. Key from WALLET_ENCRYPTION_KEY env var.
PIN Hashing
Argon2id: memory-hard, resistant to GPU and ASIC attacks. 4-digit PINs only.
Secret Comparisons
Webhook secrets use constant-time comparison. API keys are SHA-256-hashed for database lookup; PINs use Argon2id.
Production Checklist
Before deploying to mainnet:
- ☐ENVIRONMENT=production
- ☐WEBHOOK_SECRET: strong random value
- ☐INTERNAL_API_KEY: strong random value
- ☐WALLET_MASTER_SEED: backed up offline, encrypted
- ☐WALLET_ENCRYPTION_KEY: backed up separately from master seed
- ☐FEE_PAYER_SECRET: funded mainnet account
- ☐DATABASE_SSL=true
- ☐TLS at reverse proxy (Caddy / nginx / ALB)
- ☐TRUSTED_PROXY_IPS set to proxy IP only
- ☐AT_ALLOWED_IPS set to Africa's Talking production IPs
- ☐STELLAR_HORIZON_URL → mainnet Horizon
- ☐STELLAR_NETWORK_PASSPHRASE → mainnet passphrase
- ☐USDC_ISSUER → mainnet Circle USDC issuer
- ☐Security audit of wallet derivation and transaction signing
- ☐Monitoring on failed transactions and refund failures