diff --git a/docs/PERFORMANCE_TUNING.md b/docs/PERFORMANCE_TUNING.md index 24d454cb..c65c419c 100644 --- a/docs/PERFORMANCE_TUNING.md +++ b/docs/PERFORMANCE_TUNING.md @@ -181,133 +181,6 @@ const client = new StellarSplitClient({ ## Technique 5: Multi-Endpoint Load Balancing & Failover ### Explanation -Single-node deployments present a single point of failure. `RpcLoadBalancer` continuously measures latency and error rates across multiple endpoints, routing traffic to the healthiest node and quarantining degraded ones. +Single-node -### Code Example -```typescript -const client = new StellarSplitClient({ - rpcUrl: "https://primary-rpc.example.com", - rpcEndpoints: [ - "https://primary-rpc.example.com", - "https://secondary-rpc.example.com", - "https://fallback-rpc.example.com", - ], - networkPassphrase: "Public Global Stellar Network ; September 2015", - contractId: "CA...", -}); -``` - -### Tradeoffs -- **Advantages**: Zero downtime during vendor outages; routes read traffic to the fastest provider. -- **Drawbacks**: Requires subscriptions or access to multiple RPC provider endpoints. - -### Measurements -| Injected Failure Scenario | Single Endpoint Success Rate | Load Balanced Success Rate | -| :--- | :--- | :--- | -| Primary RPC 100% Down | 0% (Total Failure) | **100% (Transparent Failover)** | -| Primary RPC 30% Packet Loss | 70% | **99.4% (Adaptive rerouting)** | - ---- - -## Technique 6: Soroban Footprint & Storage TTL Batching - -### Explanation -Soroban contract instances and storage entries have Time-To-Live (TTL) values measured in ledgers. If an invoice's storage entry expires, restoring it requires expensive archival recovery transactions (~1.5 XLM per entry). - -The SDK provides `bumpStorageTtlBatch` to batch TTL extensions for multiple invoices in a single transaction. - -### Code Example -```typescript -const invoiceIds = ["inv-001", "inv-002", "inv-003", "inv-004"]; - -// Extend storage TTL by 500,000 ledgers (~30 days) in a single batch transaction -const result = await client.bumpStorageTtlBatch(invoiceIds, 500_000); -console.log(`Extended TTL across ${invoiceIds.length} invoices. Tx: ${result.txHash}`); -``` - -### Tradeoffs -- **Advantages**: 60%+ reduction in transaction fee costs compared to individual TTL bumps; prevents catastrophic storage expiration. -- **Drawbacks**: Consumes minor fee resources upfront. Best scheduled as a recurring background cron job. - -### Measurements -| Extension Strategy | Transactions Submitted | Total Fees Incurred | Execution Time | -| :--- | :--- | :--- | :--- | -| Individual Bumps (20 entries) | 20 transactions | ~2,000,000 stroops | 45.2 s | -| Batch Bump (`bumpStorageTtlBatch`) | 1 transaction | ~760,000 stroops | 2.8 s | -| Resource Savings | **95% fewer txs** | **62% lower fees** | **93.8% faster** | - ---- - -## Technique 7: Real-Time Event Streaming vs. Polling - -### Explanation -Polling Horizon or Soroban RPC endpoints every few seconds creates unnecessary server load and introduces notification lag for end users. - -The SDK supports WebSocket and Server-Sent Events (SSE) streaming through `subscribeInvoice` and `subscribeToInvoice`. - -### Code Example -```typescript -// Stream real-time status transitions and payments -const unsubscribe = client.subscribeInvoice("inv-123", (event) => { - console.log(`Event ${event.type} detected on invoice ${event.invoiceId}`); -}); - -// Clean up when leaving page -// unsubscribe(); -``` - -### Tradeoffs -- **Advantages**: Immediate notification (sub-100ms lag); zero continuous RPC polling load. -- **Drawbacks**: Requires an active WebSocket or SSE connection; falls back to HTTP polling if firewall blocks persistent connections. - -### Measurements -| Metric | HTTP Polling (3s interval) | Real-Time Streaming (SSE/WS) | Improvement | -| :--- | :--- | :--- | :--- | -| Average Notification Lag | 1,520 ms | 36 ms | **97.6% faster** | -| RPC Calls per Client / Hour | 1,200 requests | 1 initial connect | **99.9% fewer calls** | - ---- - -## Performance Decision Matrix & Recommendations - -| Workload Profile | Recommended Configuration | Primary Benefit | -| :--- | :--- | :--- | -| **High-Volume Payment Gateway** | `rpcPoolSize: 12`, `circuitBreaker: enabled`, `rpcEndpoints: [multi]` | 99.99% uptime, zero socket starvation | -| **User Dashboard / Explorer** | `cache: { ttlMs: 30000 }`, `batching: true`, `subscribeInvoice` | Instant UI response, minimal RPC bills | -| **Batch Settlement Bot** | `bumpStorageTtlBatch`, `verifyBatchPay`, `batchPay` | 60%+ gas savings, verified atomic payments | -| **Resource-Constrained Edge / CLI** | `SplitClient` (lazy init), single connection | Instant boot time (< 5ms), zero idle memory | - ---- - -## Profiling Guide - -Measure before tuning. Change one setting at a time and compare against a baseline. - -1. **Run the repository benchmarks** to catch regressions in SDK internals: - ```bash - npm run test:bench - ``` -2. **Compare against the load-test baselines** in `load-tests/baseline.json` (throughput, p50/p90/p95/p99 latency, error rate per scenario) after any performance-related change. -3. **Profile a Node.js script** that exercises your hot path (build first with `npm run build`): - ```bash - node --cpu-prof --cpu-prof-dir=./prof your-script.js # open the .cpuprofile in Chrome DevTools - node --inspect-brk your-script.js # heap snapshots / live debugging - ``` -4. **Time individual RPC calls** with the SDK telemetry hooks (see `docs/TELEMETRY_HOOKS.md`) instead of ad-hoc timers, so latency is attributed per method. -5. **Check bundle size** with `npm run size-audit` and `npm run bundle:check` when optimizing for browser or edge targets. - -Look first at the number of RPC round trips per user action, then cache hit rate, then CPU time in your own code. - ---- - -## Optimization Checklist - -- [ ] Baseline captured (latency percentiles, throughput, RPC calls per operation) -- [ ] Connection pooling enabled for high-concurrency workloads (`rpcPoolSize`) -- [ ] Read-heavy paths use caching with a TTL suited to how fast the data changes -- [ ] Independent reads are batched or issued concurrently rather than sequentially -- [ ] Circuit breaker configured so a failing node does not stall all requests -- [ ] Multiple RPC endpoints configured for failover where uptime matters -- [ ] Storage TTL bumps batched instead of issued per invoice -- [ ] Event subscriptions used instead of tight polling loops -- [ ] Changes re-measured against the baseline and `npm run test:bench` shows no regression +/* … truncated 6137 chars — edit only what you need near the top … */ diff --git a/docs/SDK_TUTORIALS.md b/docs/SDK_TUTORIALS.md index 2256bc2a..482af969 100644 --- a/docs/SDK_TUTORIALS.md +++ b/docs/SDK_TUTORIALS.md @@ -10,7 +10,8 @@ This guide provides step-by-step tutorials for integrating with the StellarSplit 4. [Webhook Integration](#webhook-integration) 5. [Multi-Signature Wallets](#multi-signature-wallets) 6. [Error Handling](#error-handling) -7. [Production Checklist](#production-checklist) +7. [Advanced Usage](#advanced-usage) +8. [Production Checklist](#production-checklist) --- @@ -209,6 +210,153 @@ try { --- +## Advanced Usage + +This section covers patterns for production-grade integrations: batching, retries, pagination, event streaming, and performance tuning. + +### Pattern: Idempotent Invoice Creation + +Generate a deterministic client-side key so retries never create duplicate invoices. + +```typescript +import { createHash } from "node:crypto"; + +function idempotencyKey(creator: string, externalRef: string): string { + return createHash("sha256").update(`${creator}:${externalRef}`).digest("hex"); +} + +async function createInvoiceOnce(creator: string, externalRef: string) { + const key = idempotencyKey(creator, externalRef); + const existing = await client.findInvoiceByReference({ creator, reference: key }); + if (existing) return existing; + + return client.createInvoice({ + creator, + reference: key, + recipients: [{ address: "GABC...RECIPIENT1", amount: parseAmount("100") }], + token: "USDC_CONTRACT_ADDRESS", + deadline: deadlineFromDays(7), + }); +} +``` + +### Pattern: Retry with Exponential Backoff + +Retry only transient failures (network / RPC), never validation errors. + +```typescript +import { StellarSplitError, isRetryableError } from "@stellar-split/sdk"; + +async function withRetry(fn: () => Promise, attempts = 5): Promise { + let lastErr: unknown; + for (let i = 0; i < attempts; i++) { + try { + return await fn(); + } catch (err) { + lastErr = err; + const retryable = err instanceof StellarSplitError && isRetryableError(err); + if (!retryable || i === attempts - 1) throw err; + const delay = Math.min(2 ** i * 250, 8000) + Math.random() * 100; + await new Promise((r) => setTimeout(r, delay)); + } + } + throw lastErr; +} + +await withRetry(() => client.pay({ payer, invoiceId, amount: parseAmount("25") })); +``` + +### Pattern: Batched Payments + +Pay multiple invoices in a single transaction to reduce fees and round-trips. + +```typescript +const { txHash } = await client.payBatch({ + payer, + payments: [ + { invoiceId: "INV_1", amount: parseAmount("10") }, + { invoiceId: "INV_2", amount: parseAmount("15") }, + ], +}); +``` + +### Pattern: Paginated Invoice Listing + +```typescript +async function* allInvoices(creator: string) { + let cursor: string | undefined; + do { + const page = await client.listInvoices({ creator, cursor, limit: 50 }); + for (const invoice of page.items) yield invoice; + cursor = page.nextCursor; + } while (cursor); +} + +for await (const invoice of allInvoices(publicKey)) { + console.log(invoice.invoiceId, invoice.status); +} +``` + +### Pattern: Real-Time Event Streaming + +```typescript +const stream = client.streamEvents({ invoiceId }); + +stream.on("payment", (p) => console.log("Payment received:", p.amount)); +stream.on("completed", () => stream.close()); +stream.on("error", (err) => console.error("Stream error:", err)); +``` + +### Pattern: Concurrent Payment Collection + +```typescript +const results = await Promise.allSettled( + payers.map((payer) => + withRetry(() => client.pay({ payer, invoiceId, amount: parseAmount("5") })) + ) +); + +const failed = results.filter((r) => r.status === "rejected"); +if (failed.length) console.warn(`${failed.length} payments failed`); +``` + +### Best Practices + +- **Reuse a single client instance** per process; it manages connection pooling internally. +- **Never retry non-idempotent operations** without an idempotency key. +- **Validate amounts and addresses** client-side before submitting to avoid wasted fees. +- **Use `payBatch`** when paying many invoices to amortize transaction fees. +- **Stream events** instead of polling for status changes. +- **Pin the SDK version** in production and review changelogs before upgrading. +- **Keep secrets server-side**; never expose `WEBHOOK_SECRET` to the browser. +- **Log `txHash` and error `code`** for every operation to aid debugging. + +### Optimization Guide + +| Area | Recommendation | +|------|----------------| +| Client lifecycle | Create one `StellarSplitClient` and reuse it across requests | +| Network calls | Batch reads with `listInvoices` pagination; batch writes with `payBatch` | +| Concurrency | Cap parallel payments (e.g. 5–10) to avoid RPC rate limits | +| Polling | Replace polling with `streamEvents` | +| Fees | Combine payments into a single transaction where possible | +| Caching | Cache immutable invoice metadata; invalidate on `completed` events | +| Payload size | Request only needed fields via `select` where supported | + +### Advanced Reference + +| Method | Description | +|--------|-------------| +| `client.payBatch({ payer, payments })` | Pay multiple invoices in one transaction | +| `client.listInvoices({ creator, cursor, limit })` | Paginated invoice listing | +| `client.findInvoiceByReference({ creator, reference })` | Look up invoice by idempotency reference | +| `client.streamEvents({ invoiceId })` | Subscribe to real-time invoice events | +| `isRetryableError(err)` | Returns `true` for transient SDK errors | +| `client.getInvoice(invoiceId)` | Fetch a single invoice by ID | +| `client.getBalance({ address, token })` | Query token balance for an address | + +--- + ## Production Checklist Before deploying to production: diff --git a/src/__tests__/configManager.test.ts b/src/__tests__/configManager.test.ts index ed9ff38d..1986c6de 100644 --- a/src/__tests__/configManager.test.ts +++ b/src/__tests__/configManager.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from "vitest"; import { ConfigManager, deepMerge } from "../configManager.js"; +import { CsrfProtection } from "../csrf.js"; describe("ConfigManager", () => { it("deep merges", () => { @@ -23,3 +24,39 @@ describe("ConfigManager", () => { expect(m.get()).toEqual({ rpcUrl: "x" }); }); }); + +describe("CsrfProtection", () => { + it("issues secure tokens and validates them strictly", () => { + const csrf = new CsrfProtection(); + const token = csrf.issueToken(); + expect(token.length).toBeGreaterThanOrEqual(32); + expect(csrf.validateToken(token)).toBe(true); + expect(csrf.validateToken("bogus")).toBe(false); + expect(csrf.validateToken(undefined)).toBe(false); + }); + + it("rejects reused tokens after consumption", () => { + const csrf = new CsrfProtection(); + const token = csrf.issueToken(); + expect(csrf.validateToken(token, { consume: true })).toBe(true); + expect(csrf.validateToken(token)).toBe(false); + }); + + it("refreshes tokens and tracks state", () => { + const csrf = new CsrfProtection(); + const first = csrf.issueToken(); + const refreshed = csrf.refreshToken(first); + expect(refreshed).not.toBe(first); + expect(csrf.validateToken(refreshed)).toBe(true); + expect(csrf.validateToken(first)).toBe(false); + expect(csrf.getStats().issued).toBe(2); + }); + + it("protects state-changing requests only", () => { + const csrf = new CsrfProtection(); + const token = csrf.issueToken(); + expect(csrf.protectRequest("GET", {})).toBe(true); + expect(csrf.protectRequest("POST", {})).toBe(false); + expect(csrf.protectRequest("POST", { "x-csrf-token": token })).toBe(true); + }); +}); diff --git a/src/__tests__/secretsManager.test.ts b/src/__tests__/secretsManager.test.ts new file mode 100644 index 00000000..53b95edd --- /dev/null +++ b/src/__tests__/secretsManager.test.ts @@ -0,0 +1,105 @@ +import { SecretsManager, SecretVersion, RotationPolicy } from '../secrets'; + +describe('SecretsManager', () => { + let manager: SecretsManager; + + beforeEach(() => { + manager = new SecretsManager({ encryptionKey: 'test-encryption-key-32-bytes-long!' }); + }); + + describe('storage', () => { + it('stores and retrieves a secret value', () => { + manager.set('api-key', 'super-secret-value'); + expect(manager.get('api-key')).toBe('super-secret-value'); + }); + + it('does not expose plaintext in the stored record', () => { + manager.set('api-key', 'super-secret-value'); + const record = manager.describe('api-key'); + expect(record).toBeDefined(); + expect(JSON.stringify(record)).not.toContain('super-secret-value'); + }); + + it('throws when retrieving an unknown secret', () => { + expect(() => manager.get('missing')).toThrow(); + }); + + it('deletes a secret', () => { + manager.set('api-key', 'value'); + manager.delete('api-key'); + expect(manager.has('api-key')).toBe(false); + }); + }); + + describe('versioning', () => { + it('creates a new version on each set', () => { + manager.set('api-key', 'v1'); + manager.set('api-key', 'v2'); + const versions = manager.listVersions('api-key'); + expect(versions).toHaveLength(2); + expect(versions[0].version).toBe(1); + expect(versions[1].version).toBe(2); + }); + + it('retrieves a specific version', () => { + manager.set('api-key', 'v1'); + manager.set('api-key', 'v2'); + expect(manager.get('api-key', 1)).toBe('v1'); + expect(manager.get('api-key', 2)).toBe('v2'); + }); + + it('returns the current version by default', () => { + manager.set('api-key', 'v1'); + manager.set('api-key', 'v2'); + expect(manager.get('api-key')).toBe('v2'); + expect(manager.currentVersion('api-key')).toBe(2); + }); + + it('keeps version history immutable', () => { + manager.set('api-key', 'v1'); + manager.set('api-key', 'v2'); + const versions: SecretVersion[] = manager.listVersions('api-key'); + expect(versions[0].value).toBe('v1'); + expect(versions[0].version).toBe(1); + }); + }); + + describe('rotation', () => { + it('rotates a secret producing a new version', () => { + manager.set('api-key', 'v1'); + const rotated = manager.rotate('api-key', () => 'v2-rotated'); + expect(rotated.version).toBe(2); + expect(manager.get('api-key')).toBe('v2-rotated'); + }); + + it('applies a rotation policy based on age', () => { + const policy: RotationPolicy = { maxAgeMs: 1000 }; + manager.set('api-key', 'v1', { policy }); + const due = manager.isRotationDue('api-key', Date.now() + 2000); + expect(due).toBe(true); + }); + + it('reports not due when within policy window', () => { + const policy: RotationPolicy = { maxAgeMs: 100000 }; + manager.set('api-key', 'v1', { policy }); + expect(manager.isRotationDue('api-key')).toBe(false); + }); + }); + + describe('tracking', () => { + it('tracks metadata for each secret', () => { + manager.set('api-key', 'v1'); + const record = manager.describe('api-key'); + expect(record.name).toBe('api-key'); + expect(record.currentVersion).toBe(1); + expect(record.createdAt).toBeInstanceOf(Date); + expect(record.updatedAt).toBeInstanceOf(Date); + }); + + it('lists all tracked secret names', () => { + manager.set('a', '1'); + manager.set('b', '2'); + expect(manager.list().sort()).toEqual(['a', 'b']); + }); + }); +}); diff --git a/src/__tests__/validation.test.ts b/src/__tests__/validation.test.ts new file mode 100644 index 00000000..963dcf1a --- /dev/null +++ b/src/__tests__/validation.test.ts @@ -0,0 +1,146 @@ +import { + validate, + string, + number, + address, + amount, + enumOf, + object, + array, + allOf, + optional, + registerRule, + getValidationStats, + resetValidationStats, + ValidationError, +} from "../validation"; + +describe("SDK input validation framework", () => { + beforeEach(() => { + resetValidationStats(); + }); + + describe("built-in validators", () => { + it("validates strings with constraints", () => { + const v = string({ minLength: 2, maxLength: 4 }); + expect(validate(v, "abc").ok).toBe(true); + expect(validate(v, "a").ok).toBe(false); + expect(validate(v, "abcde").ok).toBe(false); + expect(validate(v, 123).ok).toBe(false); + }); + + it("validates numbers with bounds", () => { + const v = number({ min: 0, max: 10, integer: true }); + expect(validate(v, 5).ok).toBe(true); + expect(validate(v, 5.5).ok).toBe(false); + expect(validate(v, -1).ok).toBe(false); + expect(validate(v, 11).ok).toBe(false); + expect(validate(v, "5").ok).toBe(false); + }); + + it("validates addresses", () => { + const v = address(); + expect(validate(v, "0x1234567890abcdef1234567890abcdef12345678").ok).toBe( + true + ); + expect(validate(v, "0x1234").ok).toBe(false); + expect(validate(v, "not-an-address").ok).toBe(false); + }); + + it("validates amounts", () => { + const v = amount({ min: 0, max: 1000 }); + expect(validate(v, 100).ok).toBe(true); + expect(validate(v, -5).ok).toBe(false); + expect(validate(v, 5000).ok).toBe(false); + expect(validate(v, NaN).ok).toBe(false); + }); + + it("validates enums", () => { + const v = enumOf(["a", "b", "c"] as const); + expect(validate(v, "a").ok).toBe(true); + expect(validate(v, "z").ok).toBe(false); + }); + }); + + describe("composition", () => { + it("validates objects safely", () => { + const v = object({ + name: string({ minLength: 1 }), + age: number({ min: 0 }), + }); + expect(validate(v, { name: "alice", age: 30 }).ok).toBe(true); + expect(validate(v, { name: "", age: 30 }).ok).toBe(false); + expect(validate(v, { name: "alice" }).ok).toBe(false); + expect(validate(v, null).ok).toBe(false); + }); + + it("validates arrays", () => { + const v = array(number({ min: 0 }), { minItems: 1, maxItems: 3 }); + expect(validate(v, [1, 2]).ok).toBe(true); + expect(validate(v, []).ok).toBe(false); + expect(validate(v, [1, 2, 3, 4]).ok).toBe(false); + expect(validate(v, [1, -1]).ok).toBe(false); + }); + + it("supports allOf composition", () => { + const v = allOf(string({ minLength: 3 }), string({ maxLength: 5 })); + expect(validate(v, "abcd").ok).toBe(true); + expect(validate(v, "ab").ok).toBe(false); + expect(validate(v, "abcdef").ok).toBe(false); + }); + + it("supports optional composition", () => { + const v = optional(string({ minLength: 1 })); + expect(validate(v, undefined).ok).toBe(true); + expect(validate(v, "x").ok).toBe(true); + expect(validate(v, "").ok).toBe(false); + }); + }); + + describe("custom rules", () => { + it("registers and applies custom rules", () => { + registerRule("even", (value: unknown) => + typeof value === "number" && value % 2 === 0 + ? null + : "must be even" + ); + const v = number({ rules: ["even"] }); + expect(validate(v, 4).ok).toBe(true); + const result = validate(v, 3); + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.errors[0].message).toBe("must be even"); + } + }); + }); + + describe("tracking", () => { + it("tracks validation counts", () => { + const v = string({ minLength: 1 }); + validate(v, "ok"); + validate(v, ""); + const stats = getValidationStats(); + expect(stats.total).toBe(2); + expect(stats.passed).toBe(1); + expect(stats.failed).toBe(1); + }); + }); + + describe("injection prevention", () => { + it("rejects prototype pollution keys", () => { + const v = object({ name: string() }); + const payload = JSON.parse('{"__proto__": {"polluted": true}}'); + const result = validate(v, payload); + expect(result.ok).toBe(false); + expect(({} as Record).polluted).toBeUndefined(); + }); + + it("throws ValidationError on assert", () => { + const v = string({ minLength: 1 }); + expect(() => { + const r = validate(v, ""); + if (!r.ok) throw new ValidationError(r.errors); + }).toThrow(ValidationError); + }); + }); +}); diff --git a/src/secrets/index.ts b/src/secrets/index.ts new file mode 100644 index 00000000..1ac5e1ce --- /dev/null +++ b/src/secrets/index.ts @@ -0,0 +1,203 @@ +/** + * SDK secrets management. + * + * Provides a pluggable, encrypted-at-rest secrets store with immutable + * versioning, manual and policy-driven rotation, and access tracking. + * Plaintext secret values are never exposed through listing/tracking APIs. + */ + +export type SecretValue = string; + +export interface SecretVersion { + readonly version: number; + readonly createdAt: number; + readonly rotatedBy: 'manual' | 'policy' | 'initial'; + /** Ciphertext only — never the plaintext value. */ + readonly ciphertext: string; +} + +export interface SecretRecord { + readonly name: string; + readonly currentVersion: number; + readonly versions: ReadonlyArray; + readonly createdAt: number; + readonly updatedAt: number; + readonly rotationPolicy?: RotationPolicy; +} + +export interface RotationPolicy { + /** Maximum age in milliseconds before a secret should be rotated. */ + readonly maxAgeMs: number; +} + +export interface SecretAccessEvent { + readonly name: string; + readonly version: number; + readonly at: number; + readonly action: 'read' | 'write' | 'rotate'; +} + +/** + * Pluggable encryption backend. Implementations must be deterministic for a + * given key so that stored ciphertext can be decrypted on read. + */ +export interface SecretCipher { + encrypt(plaintext: SecretValue): string; + decrypt(ciphertext: string): SecretValue; +} + +/** + * Default in-memory cipher. This is an abstraction boundary: production + * deployments should supply a real cipher (e.g. KMS-backed). The default + * keeps plaintext out of stored records and tracking output. + */ +export class InMemoryCipher implements SecretCipher { + private readonly key: string; + + constructor(key: string) { + if (!key) { + throw new Error('InMemoryCipher requires a non-empty key'); + } + this.key = key; + } + + encrypt(plaintext: SecretValue): string { + return Buffer.from(this.xor(plaintext), 'utf8').toString('base64'); + } + + decrypt(ciphertext: string): SecretValue { + return this.xor(Buffer.from(ciphertext, 'base64').toString('utf8')); + } + + private xor(input: string): string { + let out = ''; + for (let i = 0; i < input.length; i++) { + out += String.fromCharCode( + input.charCodeAt(i) ^ this.key.charCodeAt(i % this.key.length), + ); + } + return out; + } +} + +export interface SecretsManagerOptions { + cipher?: SecretCipher; + now?: () => number; +} + +export class SecretsManager { + private readonly cipher: SecretCipher; + private readonly now: () => number; + private readonly records = new Map(); + private readonly accessLog: SecretAccessEvent[] = []; + + constructor(options: SecretsManagerOptions = {}) { + this.cipher = options.cipher ?? new InMemoryCipher('sdk-default-secrets-key'); + this.now = options.now ?? (() => Date.now()); + } + + /** Store a new secret, creating version 1. */ + set(name: string, value: SecretValue, policy?: RotationPolicy): SecretRecord { + this.assertName(name); + const at = this.now(); + const version: SecretVersion = { + version: 1, + createdAt: at, + rotatedBy: 'initial', + ciphertext: this.cipher.encrypt(value), + }; + const record: SecretRecord = { + name, + currentVersion: 1, + versions: [version], + createdAt: at, + updatedAt: at, + rotationPolicy: policy, + }; + this.records.set(name, record); + this.track(name, 1, 'write'); + return record; + } + + /** Retrieve the plaintext value of the current version. */ + get(name: string): SecretValue { + const record = this.require(name); + return this.getVersion(name, record.currentVersion); + } + + /** Retrieve the plaintext value of a specific version. */ + getVersion(name: string, version: number): SecretValue { + const record = this.require(name); + const entry = record.versions.find((v) => v.version === version); + if (!entry) { + throw new Error(`Secret "${name}" has no version ${version}`); + } + this.track(name, version, 'read'); + return this.cipher.decrypt(entry.ciphertext); + } + + /** Rotate a secret, producing a new immutable version. */ + rotate(name: string, value: SecretValue, rotatedBy: 'manual' | 'policy' = 'manual'): SecretRecord { + const record = this.require(name); + const at = this.now(); + const nextVersion = record.currentVersion + 1; + const version: SecretVersion = { + version: nextVersion, + createdAt: at, + rotatedBy, + ciphertext: this.cipher.encrypt(value), + }; + const updated: SecretRecord = { + ...record, + currentVersion: nextVersion, + versions: [...record.versions, version], + updatedAt: at, + }; + this.records.set(name, updated); + this.track(name, nextVersion, 'rotate'); + return updated; + } + + /** Rotate every secret whose policy maxAgeMs has elapsed. */ + rotateDue(rotateValue: (name: string, current: SecretValue) => SecretValue): string[] { + const rotated: string[] = []; + const at = this.now(); + for (const record of this.records.values()) { + if (!record.rotationPolicy) continue; + if (at - record.updatedAt >= record.rotationPolicy.maxAgeMs) { + const current = this.getVersion(record.name, record.currentVersion); + this.rotate(record.name, rotateValue(record.name, current), 'policy'); + rotated.push(record.name); + } + } + return rotated; + } + + /** List secret metadata without exposing values. */ + list(): SecretRecord[] { + return Array.from(this.records.values()); + } + + /** Full access tracking log. */ + getAccessLog(): SecretAccessEvent[] { + return [...this.accessLog]; + } + + private track(name: string, version: number, action: SecretAccessEvent['action']): void { + this.accessLog.push({ name, version, at: this.now(), action }); + } + + private require(name: string): SecretRecord { + const record = this.records.get(name); + if (!record) { + throw new Error(`Secret "${name}" not found`); + } + return record; + } + + private assertName(name: string): void { + if (!name || typeof name !== 'string') { + throw new Error('Secret name must be a non-empty string'); + } + } +} diff --git a/src/secrets/secretsManager.ts b/src/secrets/secretsManager.ts new file mode 100644 index 00000000..a3f6d3e9 --- /dev/null +++ b/src/secrets/secretsManager.ts @@ -0,0 +1,206 @@ +/** + * SDK secrets management. + * + * Provides secure storage, versioning, rotation, and tracking of secrets. + * Secrets are never exposed in plaintext through the public API: values are + * encrypted at rest via a pluggable backend and only decrypted on explicit + * retrieval. + */ + +export interface SecretVersion { + /** Monotonically increasing version number, starting at 1. */ + version: number; + /** Encrypted payload (opaque to callers). */ + ciphertext: string; + /** ISO timestamp of when this version was created. */ + createdAt: string; + /** Optional reason for the version (e.g. "initial", "rotation"). */ + reason?: string; +} + +export interface SecretRecord { + name: string; + /** Current active version number. */ + currentVersion: number; + /** Immutable version history, ordered by version ascending. */ + versions: SecretVersion[]; + /** ISO timestamp of last rotation, if any. */ + lastRotatedAt?: string; + /** Rotation policy in milliseconds, if configured. */ + rotationIntervalMs?: number; +} + +export interface SecretMetadata { + name: string; + currentVersion: number; + versionCount: number; + createdAt: string; + lastRotatedAt?: string; + rotationIntervalMs?: number; +} + +export interface RotationPolicy { + /** Rotate automatically once the current version is older than this. */ + intervalMs: number; +} + +/** + * Pluggable encryption backend. Implementations must be deterministic enough + * to round-trip values and must never store plaintext. + */ +export interface SecretsBackend { + encrypt(plaintext: string): string; + decrypt(ciphertext: string): string; +} + +/** + * Default in-memory backend. Uses a reversible encoding so the abstraction is + * usable without external dependencies; production deployments should supply + * a real crypto backend implementing {@link SecretsBackend}. + */ +export class InMemorySecretsBackend implements SecretsBackend { + encrypt(plaintext: string): string { + return Buffer.from(plaintext, "utf8").toString("base64"); + } + + decrypt(ciphertext: string): string { + return Buffer.from(ciphertext, "base64").toString("utf8"); + } +} + +export interface SecretsManagerOptions { + backend?: SecretsBackend; + /** Clock injection for deterministic testing. */ + now?: () => Date; +} + +export class SecretsManager { + private readonly backend: SecretsBackend; + private readonly now: () => Date; + private readonly secrets = new Map(); + + constructor(options: SecretsManagerOptions = {}) { + this.backend = options.backend ?? new InMemorySecretsBackend(); + this.now = options.now ?? (() => new Date()); + } + + /** + * Store a new secret. Creates version 1. Throws if the secret already + * exists; use {@link rotate} to create new versions. + */ + set(name: string, value: string, policy?: RotationPolicy): SecretMetadata { + this.assertName(name); + if (this.secrets.has(name)) { + throw new Error(`Secret "${name}" already exists; use rotate() to update it.`); + } + const createdAt = this.now().toISOString(); + const record: SecretRecord = { + name, + currentVersion: 1, + versions: [ + { + version: 1, + ciphertext: this.backend.encrypt(value), + createdAt, + reason: "initial", + }, + ], + rotationIntervalMs: policy?.intervalMs, + }; + this.secrets.set(name, record); + return this.toMetadata(record); + } + + /** + * Retrieve the plaintext value of a secret. Defaults to the current version. + * Throws if the secret or version does not exist. + */ + get(name: string, version?: number): string { + const record = this.requireRecord(name); + const target = version ?? record.currentVersion; + const entry = record.versions.find((v) => v.version === target); + if (!entry) { + throw new Error(`Secret "${name}" has no version ${target}.`); + } + return this.backend.decrypt(entry.ciphertext); + } + + /** + * Rotate a secret, creating a new immutable version and advancing the + * current-version pointer. Returns metadata for the updated secret. + */ + rotate(name: string, value: string, reason = "rotation"): SecretMetadata { + const record = this.requireRecord(name); + const nextVersion = record.currentVersion + 1; + const createdAt = this.now().toISOString(); + record.versions.push({ + version: nextVersion, + ciphertext: this.backend.encrypt(value), + createdAt, + reason, + }); + record.currentVersion = nextVersion; + record.lastRotatedAt = createdAt; + return this.toMetadata(record); + } + + /** + * Rotate every secret whose configured policy interval has elapsed. + * The provided value factory produces the new plaintext for each secret. + * Returns the names of secrets that were rotated. + */ + rotateDue(valueFactory: (name: string) => string): string[] { + const rotated: string[] = []; + const nowMs = this.now().getTime(); + for (const record of this.secrets.values()) { + if (!record.rotationIntervalMs) continue; + const last = record.lastRotatedAt ?? record.versions[record.versions.length - 1].createdAt; + if (nowMs - new Date(last).getTime() >= record.rotationIntervalMs) { + this.rotate(record.name, valueFactory(record.name), "policy"); + rotated.push(record.name); + } + } + return rotated; + } + + /** List metadata for all tracked secrets (never plaintext). */ + list(): SecretMetadata[] { + return Array.from(this.secrets.values()).map((r) => this.toMetadata(r)); + } + + /** Return metadata for a single secret, or undefined if untracked. */ + describe(name: string): SecretMetadata | undefined { + const record = this.secrets.get(name); + return record ? this.toMetadata(record) : undefined; + } + + /** Remove a secret and all of its versions. */ + delete(name: string): boolean { + return this.secrets.delete(name); + } + + private requireRecord(name: string): SecretRecord { + const record = this.secrets.get(name); + if (!record) { + throw new Error(`Secret "${name}" not found.`); + } + return record; + } + + private assertName(name: string): void { + if (!name || typeof name !== "string") { + throw new Error("Secret name must be a non-empty string."); + } + } + + private toMetadata(record: SecretRecord): SecretMetadata { + return { + name: record.name, + currentVersion: record.currentVersion, + versionCount: record.versions.length, + createdAt: record.versions[0].createdAt, + lastRotatedAt: record.lastRotatedAt, + rotationIntervalMs: record.rotationIntervalMs, + }; + } +} diff --git a/src/secrets/types.ts b/src/secrets/types.ts new file mode 100644 index 00000000..4889d663 --- /dev/null +++ b/src/secrets/types.ts @@ -0,0 +1,114 @@ +/** + * Secrets management type definitions. + * + * These types describe secret records, immutable version history, and + * rotation policy. They are intentionally backend-agnostic so that the + * storage layer can be swapped without changing consumers. + */ + +/** + * A single immutable version of a secret. + * + * The plaintext value is never stored here directly; `ciphertext` holds the + * encrypted payload produced by the storage backend. + */ +export interface SecretVersion { + /** Monotonically increasing version number, starting at 1. */ + version: number; + /** Encrypted secret payload. Never plaintext. */ + ciphertext: string; + /** Initialization vector / nonce used for encryption, if applicable. */ + iv?: string; + /** Identifier of the key used to encrypt this version. */ + keyId?: string; + /** ISO-8601 timestamp of when this version was created. */ + createdAt: string; + /** Optional actor or system that created this version. */ + createdBy?: string; + /** Whether this version has been revoked and must not be used. */ + revoked?: boolean; +} + +/** + * Metadata describing a tracked secret without exposing its value. + */ +export interface SecretMetadata { + /** Unique secret name/identifier. */ + name: string; + /** Human-readable description. */ + description?: string; + /** Current active version number. */ + currentVersion: number; + /** Total number of retained versions. */ + versionCount: number; + /** ISO-8601 timestamp of creation. */ + createdAt: string; + /** ISO-8601 timestamp of the last update/rotation. */ + updatedAt: string; + /** ISO-8601 timestamp of the last rotation, if any. */ + lastRotatedAt?: string; + /** Optional rotation policy attached to this secret. */ + rotationPolicy?: RotationPolicy; + /** Arbitrary non-sensitive labels for tracking. */ + labels?: Record; +} + +/** + * Policy describing when and how a secret should be rotated. + */ +export interface RotationPolicy { + /** Maximum age in milliseconds before rotation is due. */ + maxAgeMs?: number; + /** Maximum number of retained versions (older versions are pruned). */ + maxVersions?: number; + /** Whether rotation should be performed automatically when due. */ + autoRotate?: boolean; +} + +/** + * Result of a rotation operation. + */ +export interface RotationResult { + /** Secret name that was rotated. */ + name: string; + /** Version number that was active before rotation. */ + previousVersion: number; + /** Newly created active version number. */ + newVersion: number; + /** ISO-8601 timestamp of the rotation. */ + rotatedAt: string; +} + +/** + * Pluggable storage backend contract. + * + * Implementations are responsible for encrypting values at rest. The manager + * only ever hands plaintext to `put` and receives plaintext from `get`. + */ +export interface SecretsBackend { + /** Persist an encrypted version for the given secret name. */ + put(name: string, version: SecretVersion, plaintext: string): Promise | void; + /** Retrieve and decrypt a specific version. */ + get(name: string, version: number): Promise | string | undefined; + /** List all stored versions for a secret, newest first. */ + listVersions(name: string): Promise | SecretVersion[]; + /** Remove a specific version. */ + deleteVersion(name: string, version: number): Promise | void; + /** Remove all versions for a secret. */ + delete(name: string): Promise | void; +} + +/** + * Options for constructing a secrets manager. + */ +export interface SecretsManagerOptions { + /** Storage backend. Defaults to an in-memory encrypted backend. */ + backend?: SecretsBackend; + /** Default rotation policy applied to secrets without an explicit policy. */ + defaultRotationPolicy?: RotationPolicy; +} + +export interface SecretRecord { + metadata: SecretMetadata; + versions: SecretVersion[]; +} diff --git a/src/validation/composition.ts b/src/validation/composition.ts new file mode 100644 index 00000000..7e31a041 --- /dev/null +++ b/src/validation/composition.ts @@ -0,0 +1,212 @@ +/** + * SDK input validation framework — composition helpers. + * + * Provides a small, dependency-free validator abstraction plus safe + * composition primitives (allOf / anyOf / object / array / optional). + * Every validator returns a structured result so callers can track + * validation outcomes without throwing on invalid input. + */ + +export interface ValidationIssue { + path: string; + message: string; +} + +export interface ValidationResult { + ok: boolean; + value?: T; + issues: ValidationIssue[]; +} + +export interface Validator { + readonly name: string; + validate(input: unknown, path?: string): ValidationResult; +} + +export type ValidatorMap = Record>; + +export interface ValidationTracker { + record(validator: string, result: ValidationResult): void; + stats(): Record; +} + +function ok(value: T): ValidationResult { + return { ok: true, value, issues: [] }; +} + +function fail(path: string, message: string): ValidationResult { + return { ok: false, issues: [{ path, message }] }; +} + +function joinPath(base: string, key: string | number): string { + if (typeof key === 'number') return `${base}[${key}]`; + return base ? `${base}.${key}` : key; +} + +/** + * Create a validator from a predicate. Custom rules are just validators, + * so they compose with the built-ins below. + */ +export function rule( + name: string, + check: (input: unknown) => input is T, + message = `invalid ${name}`, +): Validator { + return { + name, + validate(input, path = '') { + return check(input) ? ok(input) : fail(path, message); + }, + }; +} + +/** + * Registry for custom rules. Registration is explicit and namespaced so + * user-supplied rules cannot silently shadow built-ins. + */ +export class RuleRegistry { + private readonly rules = new Map>(); + + register(validator: Validator): this { + if (this.rules.has(validator.name)) { + throw new Error(`validator already registered: ${validator.name}`); + } + this.rules.set(validator.name, validator as Validator); + return this; + } + + get(name: string): Validator | undefined { + return this.rules.get(name); + } + + has(name: string): boolean { + return this.rules.has(name); + } +} + +/** + * In-memory tracker so callers can observe how often each validator runs + * and how often it rejects input. + */ +export class InMemoryTracker implements ValidationTracker { + private readonly counts = new Map(); + + record(validator: string, result: ValidationResult): void { + const entry = this.counts.get(validator) ?? { runs: 0, failures: 0 }; + entry.runs += 1; + if (!result.ok) entry.failures += 1; + this.counts.set(validator, entry); + } + + stats(): Record { + return Object.fromEntries(this.counts); + } +} + +/** Run a validator and record the outcome when a tracker is supplied. */ +export function tracked( + validator: Validator, + tracker: ValidationTracker, +): Validator { + return { + name: validator.name, + validate(input, path = '') { + const result = validator.validate(input, path); + tracker.record(validator.name, result as ValidationResult); + return result; + }, + }; +} + +/** All validators must pass; the first failure short-circuits. */ +export function allOf(...validators: Validator[]): Validator { + return { + name: `allOf(${validators.map((v) => v.name).join(',')})`, + validate(input, path = '') { + for (const validator of validators) { + const result = validator.validate(input, path); + if (!result.ok) return { ok: false, issues: result.issues }; + } + return ok(input as T); + }, + }; +} + +/** At least one validator must pass; issues are merged on failure. */ +export function anyOf(...validators: Validator[]): Validator { + return { + name: `anyOf(${validators.map((v) => v.name).join(',')})`, + validate(input, path = '') { + const issues: ValidationIssue[] = []; + for (const validator of validators) { + const result = validator.validate(input, path); + if (result.ok) return ok(result.value as T); + issues.push(...result.issues); + } + return { ok: false, issues }; + }, + }; +} + +/** Allow `undefined`/`null` to pass through untouched. */ +export function optional(validator: Validator): Validator { + return { + name: `optional(${validator.name})`, + validate(input, path = '') { + if (input === undefined || input === null) return ok(undefined); + return validator.validate(input, path); + }, + }; +} + +/** Validate each element of an array with the given element validator. */ +export function array(element: Validator): Validator { + return { + name: `array(${element.name})`, + validate(input, path = '') { + if (!Array.isArray(input)) return fail(path, 'expected array'); + const values: T[] = []; + const issues: ValidationIssue[] = []; + input.forEach((item, index) => { + const result = element.validate(item, joinPath(path, index)); + if (result.ok) values.push(result.value as T); + else issues.push(...result.issues); + }); + return issues.length ? { ok: false, issues } : ok(values); + }, + }; +} + +/** + * Validate an object against a schema. Unknown keys are rejected so that + * unexpected input cannot be smuggled through to downstream consumers. + */ +export function object( + schema: S, +): Validator<{ [K in keyof S]: unknown }> { + return { + name: `object(${Object.keys(schema).join(',')})`, + validate(input, path = '') { + if (typeof input !== 'object' || input === null || Array.isArray(input)) { + return fail(path, 'expected object'); + } + const source = input as Record; + const issues: ValidationIssue[] = []; + const value: Record = {}; + + for (const key of Object.keys(source)) { + if (!(key in schema)) { + issues.push({ path: joinPath(path, key), message: 'unknown field' }); + } + } + + for (const [key, validator] of Object.entries(schema)) { + const result = validator.validate(source[key], joinPath(path, key)); + if (result.ok) value[key] = result.value; + else issues.push(...result.issues); + } + + return issues.length ? { ok: false, issues } : ok(value as { [K in keyof S]: unknown }); + }, + }; +} diff --git a/src/validation/index.ts b/src/validation/index.ts new file mode 100644 index 00000000..c0e0e6f7 --- /dev/null +++ b/src/validation/index.ts @@ -0,0 +1,326 @@ +/** + * SDK input validation framework. + * + * Provides a small, composable validation system: + * - `Validator` interface with a `validate` method returning a `ValidationResult`. + * - Built-in validators for common SDK inputs (string, number, address, amount, enum). + * - Custom rule registration via `registerRule` / `createRule`. + * - Safe composition helpers (`allOf`, `object`, `array`, `optional`). + * - Validation tracking via `ValidationTracker`. + * + * All validators are pure and never throw on invalid input; they return a + * result object so callers can handle failures explicitly. This prevents + * injection by rejecting unexpected shapes/values before they reach the SDK. + */ + +export interface ValidationError { + /** Dotted path to the offending field (empty for root). */ + path: string; + /** Human-readable message. */ + message: string; + /** Machine-readable rule code. */ + code: string; +} + +export interface ValidationResult { + ok: boolean; + value?: T; + errors: ValidationError[]; +} + +export interface Validator { + validate(input: unknown, path?: string): ValidationResult; +} + +export type Rule = (input: unknown) => ValidationResult; + +const ok = (value: T): ValidationResult => ({ ok: true, value, errors: [] }); + +const fail = (path: string, code: string, message: string): ValidationResult => ({ + ok: false, + errors: [{ path, code, message }], +}); + +const joinPath = (base: string, key: string | number): string => + base ? `${base}.${key}` : String(key); + +/** Wrap a plain rule function into a `Validator`. */ +export function createValidator(rule: Rule): Validator { + return { + validate(input: unknown, path = ''): ValidationResult { + const result = rule(input); + if (result.ok) return result; + return { + ok: false, + errors: result.errors.map((e) => ({ ...e, path: e.path || path })), + }; + }, + }; +} + +// --------------------------------------------------------------------------- +// Custom rule registry +// --------------------------------------------------------------------------- + +const customRules = new Map>(); + +/** Register a named custom rule usable via `rule(name)`. */ +export function registerRule(name: string, rule: Rule): void { + if (!name) throw new Error('Rule name is required'); + customRules.set(name, rule as Rule); +} + +/** Look up a registered custom rule and wrap it as a validator. */ +export function rule(name: string): Validator { + const found = customRules.get(name); + if (!found) throw new Error(`Unknown validation rule: ${name}`); + return createValidator(found as Rule); +} + +// --------------------------------------------------------------------------- +// Built-in validators +// --------------------------------------------------------------------------- + +export interface StringOptions { + minLength?: number; + maxLength?: number; + pattern?: RegExp; + /** Reject control characters and other injection-prone content. */ + noControlChars?: boolean; +} + +export function string(options: StringOptions = {}): Validator { + return createValidator((input) => { + if (typeof input !== 'string') return fail('', 'string.type', 'Expected a string'); + if (options.minLength !== undefined && input.length < options.minLength) { + return fail('', 'string.minLength', `Must be at least ${options.minLength} characters`); + } + if (options.maxLength !== undefined && input.length > options.maxLength) { + return fail('', 'string.maxLength', `Must be at most ${options.maxLength} characters`); + } + if (options.pattern && !options.pattern.test(input)) { + return fail('', 'string.pattern', 'Value does not match required pattern'); + } + if (options.noControlChars && /[\u0000-\u001f\u007f]/.test(input)) { + return fail('', 'string.controlChars', 'Value contains control characters'); + } + return ok(input); + }); +} + +export interface NumberOptions { + min?: number; + max?: number; + integer?: boolean; +} + +export function number(options: NumberOptions = {}): Validator { + return createValidator((input) => { + if (typeof input !== 'number' || !Number.isFinite(input)) { + return fail('', 'number.type', 'Expected a finite number'); + } + if (options.integer && !Number.isInteger(input)) { + return fail('', 'number.integer', 'Expected an integer'); + } + if (options.min !== undefined && input < options.min) { + return fail('', 'number.min', `Must be at least ${options.min}`); + } + if (options.max !== undefined && input > options.max) { + return fail('', 'number.max', `Must be at most ${options.max}`); + } + return ok(input); + }); +} + +const ADDRESS_PATTERN = /^0x[0-9a-fA-F]{40}$/; + +/** Validate a hex EVM-style address. */ +export function address(): Validator { + return createValidator((input) => { + if (typeof input !== 'string') return fail('', 'address.type', 'Expected a string'); + if (!ADDRESS_PATTERN.test(input)) { + return fail('', 'address.format', 'Invalid address format'); + } + return ok(input); + }); +} + +export interface AmountOptions { + min?: bigint; + max?: bigint; +} + +/** Validate a non-negative integer amount (bigint or numeric string). */ +export function amount(options: AmountOptions = {}): Validator { + return createValidator((input) => { + let value: bigint; + if (typeof input === 'bigint') { + value = input; + } else if (typeof input === 'string' && /^\d+$/.test(input)) { + value = BigInt(input); + } else if (typeof input === 'number' && Number.isInteger(input) && input >= 0) { + value = BigInt(input); + } else { + return fail('', 'amount.type', 'Expected a non-negative integer amount'); + } + if (value < 0n) return fail('', 'amount.negative', 'Amount must not be negative'); + if (options.min !== undefined && value < options.min) { + return fail('', 'amount.min', `Amount must be at least ${options.min}`); + } + if (options.max !== undefined && value > options.max) { + return fail('', 'amount.max', `Amount must be at most ${options.max}`); + } + return ok(value); + }); +} + +/** Validate that input is one of the allowed enum values. */ +export function enumOf(values: readonly T[]): Validator { + const allowed = new Set(values); + return createValidator((input) => { + if (!allowed.has(input)) { + return fail('', 'enum.value', `Expected one of: ${values.join(', ')}`); + } + return ok(input as T); + }); +} + +// --------------------------------------------------------------------------- +// Composition +// --------------------------------------------------------------------------- + +/** Run all validators; succeed only if every one succeeds. */ +export function allOf(...validators: Validator[]): Validator { + return { + validate(input: unknown, path = ''): ValidationResult { + const errors: ValidationError[] = []; + for (const v of validators) { + const result = v.validate(input, path); + if (!result.ok) errors.push(...result.errors); + } + if (errors.length > 0) return { ok: false, errors }; + return ok(input as T); + }, + }; +} + +export type Shape = Record>; + +export type InferShape = { + [K in keyof S]: S[K] extends Validator ? T : never; +}; + +/** Validate an object against a shape of validators. Unknown keys are rejected. */ +export function object(shape: S): Validator> { + const keys = Object.keys(shape); + return { + validate(input: unknown, path = ''): ValidationResult> { + if (typeof input !== 'object' || input === null || Array.isArray(input)) { + return fail(path, 'object.type', 'Expected an object'); + } + const source = input as Record; + const errors: ValidationError[] = []; + const output: Record = {}; + + for (const key of Object.keys(source)) { + if (!keys.includes(key)) { + errors.push({ + path: joinPath(path, key), + code: 'object.unknownKey', + message: `Unexpected key: ${key}`, + }); + } + } + + for (const key of keys) { + const result = shape[key].validate(source[key], joinPath(path, key)); + if (result.ok) { + output[key] = result.value; + } else { + errors.push(...result.errors); + } + } + + if (errors.length > 0) return { ok: false, errors }; + return ok(output as InferShape); + }, + }; +} + +/** Validate an array where every element matches the given validator. */ +export function array(item: Validator, options: { minLength?: number; maxLength?: number } = {}): Validator { + return { + validate(input: unknown, path = ''): ValidationResult { + if (!Array.isArray(input)) return fail(path, 'array.type', 'Expected an array'); + if (options.minLength !== undefined && input.length < options.minLength) { + return fail(path, 'array.minLength', `Must have at least ${options.minLength} items`); + } + if (options.maxLength !== undefined && input.length > options.maxLength) { + return fail(path, 'array.maxLength', `Must have at most ${options.maxLength} items`); + } + const errors: ValidationError[] = []; + const output: T[] = []; + input.forEach((entry, index) => { + const result = item.validate(entry, joinPath(path, index)); + if (result.ok) output.push(result.value as T); + else errors.push(...result.errors); + }); + if (errors.length > 0) return { ok: false, errors }; + return ok(output); + }, + }; +} + +/** Allow `undefined`/`null` to pass through as `undefined`. */ +export function optional(validator: Validator): Validator { + return { + validate(input: unknown, path = ''): ValidationResult { + if (input === undefined || input === null) return ok(undefined); + return validator.validate(input, path); + }, + }; +} + +// --------------------------------------------------------------------------- +// Tracking +// --------------------------------------------------------------------------- + +export interface ValidationRecord { + path: string; + ok: boolean; + errors: ValidationError[]; + timestamp: number; +} + +/** Records validation outcomes for observability/debugging. */ +export class ValidationTracker { + private readonly records: ValidationRecord[] = []; + + /** Wrap a validator so each run is recorded. */ + track(validator: Validator): Validator { + return { + validate: (input: unknown, path = ''): ValidationResult => { + const result = validator.validate(input, path); + this.records.push({ + path, + ok: result.ok, + errors: result.errors, + timestamp: Date.now(), + }); + return result; + }, + }; + } + + getRecords(): readonly ValidationRecord[] { + return this.records; + } + + getFailures(): readonly ValidationRecord[] { + return this.records.filter((r) => !r.ok); + } + + clear(): void { + this.records.length = 0; + } +} diff --git a/src/validation/validators.ts b/src/validation/validators.ts new file mode 100644 index 00000000..794dcab4 --- /dev/null +++ b/src/validation/validators.ts @@ -0,0 +1,161 @@ +/** + * SDK input validation framework. + * + * Composable validators with built-in rules, custom rule registration, + * and validation tracking. Validators never throw on invalid input; they + * return a structured result so callers can handle failures safely. + */ + +export interface ValidationError { + path: string; + message: string; + rule: string; +} + +export interface ValidationResult { + valid: boolean; + value?: T; + errors: ValidationError[]; +} + +export interface Validator { + readonly name: string; + validate(input: unknown, path?: string): ValidationResult; +} + +export interface ValidationRecord { + validator: string; + path: string; + valid: boolean; + timestamp: number; +} + +const history: ValidationRecord[] = []; + +function track(validator: string, path: string, valid: boolean): void { + history.push({ validator, path, valid, timestamp: Date.now() }); +} + +export function getValidationHistory(): ValidationRecord[] { + return history.slice(); +} + +export function clearValidationHistory(): void { + history.length = 0; +} + +function ok(value: T): ValidationResult { + return { valid: true, value, errors: [] }; +} + +function fail(path: string, rule: string, message: string): ValidationResult { + return { valid: false, errors: [{ path, rule, message }] }; +} + +function make(name: string, check: (input: unknown, path: string) => ValidationResult): Validator { + return { + name, + validate(input: unknown, path = '$'): ValidationResult { + const result = check(input, path); + track(name, path, result.valid); + return result; + }, + }; +} + +export const string = (opts: { min?: number; max?: number; pattern?: RegExp } = {}): Validator => + make('string', (input, path) => { + if (typeof input !== 'string') return fail(path, 'string', 'Expected a string'); + if (opts.min !== undefined && input.length < opts.min) return fail(path, 'string', `Must be at least ${opts.min} characters`); + if (opts.max !== undefined && input.length > opts.max) return fail(path, 'string', `Must be at most ${opts.max} characters`); + if (opts.pattern && !opts.pattern.test(input)) return fail(path, 'string', 'Does not match required pattern'); + return ok(input); + }); + +export const number = (opts: { min?: number; max?: number; integer?: boolean } = {}): Validator => + make('number', (input, path) => { + if (typeof input !== 'number' || Number.isNaN(input)) return fail(path, 'number', 'Expected a number'); + if (opts.integer && !Number.isInteger(input)) return fail(path, 'number', 'Expected an integer'); + if (opts.min !== undefined && input < opts.min) return fail(path, 'number', `Must be >= ${opts.min}`); + if (opts.max !== undefined && input > opts.max) return fail(path, 'number', `Must be <= ${opts.max}`); + return ok(input); + }); + +export const address = (): Validator => + make('address', (input, path) => { + if (typeof input !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(input)) return fail(path, 'address', 'Invalid address'); + return ok(input); + }); + +export const amount = (opts: { min?: number; max?: number } = {}): Validator => + make('amount', (input, path) => { + if (typeof input !== 'number' || !Number.isFinite(input) || input < 0) return fail(path, 'amount', 'Invalid amount'); + if (opts.min !== undefined && input < opts.min) return fail(path, 'amount', `Must be >= ${opts.min}`); + if (opts.max !== undefined && input > opts.max) return fail(path, 'amount', `Must be <= ${opts.max}`); + return ok(input); + }); + +export const enumOf = (values: readonly T[]): Validator => + make('enum', (input, path) => { + if (typeof input !== 'string' || !values.includes(input as T)) return fail(path, 'enum', `Must be one of: ${values.join(', ')}`); + return ok(input as T); + }); + +export const optional = (validator: Validator): Validator => + make(`optional(${validator.name})`, (input, path) => { + if (input === undefined || input === null) return ok(undefined); + return validator.validate(input, path); + }); + +export const allOf = (...validators: Validator[]): Validator => + make('allOf', (input, path) => { + const errors: ValidationError[] = []; + let value: T | undefined; + for (const v of validators) { + const r = v.validate(input, path); + if (!r.valid) errors.push(...r.errors); + else value = r.value; + } + return errors.length ? { valid: false, errors } : ok(value as T); + }); + +export const arrayOf = (validator: Validator): Validator => + make('arrayOf', (input, path) => { + if (!Array.isArray(input)) return fail(path, 'arrayOf', 'Expected an array'); + const errors: ValidationError[] = []; + const value: T[] = []; + input.forEach((item, i) => { + const r = validator.validate(item, `${path}[${i}]`); + if (r.valid) value.push(r.value as T); + else errors.push(...r.errors); + }); + return errors.length ? { valid: false, errors } : ok(value); + }); + +export const objectOf = >( + shape: { [K in keyof T]: Validator }, +): Validator => + make('objectOf', (input, path) => { + if (typeof input !== 'object' || input === null || Array.isArray(input)) return fail(path, 'objectOf', 'Expected an object'); + const errors: ValidationError[] = []; + const value = {} as T; + for (const key of Object.keys(shape) as (keyof T)[]) { + const r = shape[key].validate((input as Record)[key as string], `${path}.${String(key)}`); + if (r.valid) value[key] = r.value as T[keyof T]; + else errors.push(...r.errors); + } + return errors.length ? { valid: false, errors } : ok(value); + }); + +const customRules = new Map boolean>(); + +export function registerRule(name: string, predicate: (input: unknown) => boolean): void { + customRules.set(name, predicate); +} + +export const custom = (name: string, message = `Failed rule: ${name}`): Validator => + make(`custom(${name})`, (input, path) => { + const predicate = customRules.get(name); + if (!predicate) return fail(path, name, `Unknown rule: ${name}`); + return predicate(input) ? ok(input) : fail(path, name, message); + });