@digilogiclabs/platform-core 1.3.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,9 +2,9 @@
2
2
 
3
3
  > Vendor-agnostic infrastructure abstraction layer for building portable, enterprise-grade applications.
4
4
 
5
- [![Tests](https://img.shields.io/badge/tests-343%20passing-brightgreen)](./tests)
6
- [![Adapters](https://img.shields.io/badge/adapters-14-blue)](./src/adapters)
7
- [![Interfaces](https://img.shields.io/badge/interfaces-12-blue)](./src/interfaces)
5
+ [![Tests](https://img.shields.io/badge/tests-1270%2B%20passing-brightgreen)](./tests)
6
+ [![Adapters](https://img.shields.io/badge/adapters-50%2B-blue)](./src/adapters)
7
+ [![Interfaces](https://img.shields.io/badge/interfaces-34-blue)](./src/interfaces)
8
8
 
9
9
  ## Overview
10
10
 
@@ -28,6 +28,8 @@ Platform Core provides a unified API for common infrastructure services, allowin
28
28
  - **Hooks** - Lifecycle events for database, cache, email, queue operations
29
29
  - **Resilience** - Retry, circuit breaker, timeout, bulkhead, fallback patterns
30
30
  - **Metrics** - Counters, gauges, histograms, timings with tag support
31
+ - **Security** - HTML escaping, URL detection, content sanitization for emails
32
+ - **API Utilities** - Structured errors, error classification, pagination helpers
31
33
 
32
34
  ## Installation
33
35
 
@@ -547,6 +549,80 @@ const summary = metrics.getSummary();
547
549
  console.log(summary.counters, summary.timings);
548
550
  ```
549
551
 
552
+ ## Security Utilities
553
+
554
+ Helpers for safe rendering of user content in emails and HTML output:
555
+
556
+ ```typescript
557
+ import {
558
+ escapeHtml,
559
+ containsUrls,
560
+ containsHtml,
561
+ stripHtml,
562
+ defangUrl,
563
+ sanitizeForEmail,
564
+ } from "@digilogiclabs/platform-core";
565
+
566
+ // Escape HTML special characters
567
+ escapeHtml('<script>alert("xss")</script>');
568
+ // → '&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
569
+
570
+ // Detect URLs or HTML in user input
571
+ containsUrls("visit https://evil.com"); // true
572
+ containsUrls("visit evil.com"); // true (bare domain detection)
573
+ containsHtml("<b>bold</b>"); // true
574
+
575
+ // Strip HTML tags
576
+ stripHtml("<p>Hello <b>world</b></p>"); // "Hello world"
577
+
578
+ // Defang URLs to prevent auto-linking in email clients
579
+ defangUrl("https://evil.com/path"); // "hxxps://evil[com]/path"
580
+
581
+ // Sanitize user content for HTML email templates
582
+ sanitizeForEmail(userInput); // Escapes all HTML entities
583
+ ```
584
+
585
+ ## API Utilities
586
+
587
+ Framework-agnostic error handling and response helpers:
588
+
589
+ ```typescript
590
+ import {
591
+ ApiError,
592
+ ApiErrorCode,
593
+ CommonApiErrors,
594
+ classifyError,
595
+ buildPagination,
596
+ isApiError,
597
+ } from "@digilogiclabs/platform-core";
598
+ import type {
599
+ ApiSuccessResponse,
600
+ ApiPaginatedResponse,
601
+ } from "@digilogiclabs/platform-core";
602
+
603
+ // Pre-built error factories
604
+ throw CommonApiErrors.notFound("User"); // 404
605
+ throw CommonApiErrors.unauthorized(); // 401
606
+ throw CommonApiErrors.forbidden(); // 403
607
+ throw CommonApiErrors.validationError(details); // 400
608
+ throw CommonApiErrors.rateLimitExceeded(); // 429
609
+
610
+ // Custom API errors
611
+ throw new ApiError(422, "Invalid input", ApiErrorCode.VALIDATION_ERROR, {
612
+ field: "email",
613
+ message: "Invalid format",
614
+ });
615
+
616
+ // Classify any error into { status, body }
617
+ // Handles: ApiError, Zod validation errors, PostgreSQL errors, generic errors
618
+ const { status, body } = classifyError(error, isDev);
619
+ // → { status: 409, body: { error: "Resource already exists", code: "CONFLICT" } }
620
+
621
+ // Pagination helper
622
+ const pagination = buildPagination(1, 20, 100);
623
+ // → { page: 1, limit: 20, total: 100, totalPages: 5, hasMore: true }
624
+ ```
625
+
550
626
  ## Local Development
551
627
 
552
628
  Start the development infrastructure:
@@ -1736,6 +1736,108 @@ declare class MemoryRAG implements IRAG {
1736
1736
  private deduplicateResults;
1737
1737
  }
1738
1738
 
1739
+ /**
1740
+ * ICrypto - Field-Level Encryption Interface
1741
+ * Provides AES-256-GCM encryption with key rotation for PII in databases.
1742
+ */
1743
+ type CryptoAlgorithm = "aes-256-gcm";
1744
+ type CryptoKeyStatus = "active" | "decrypt-only" | "retired";
1745
+ /** Encrypted field stored in database columns */
1746
+ interface EncryptedField {
1747
+ /** Base64-encoded ciphertext */
1748
+ ciphertext: string;
1749
+ /** Base64-encoded initialization vector (96-bit for GCM) */
1750
+ iv: string;
1751
+ /** Base64-encoded GCM authentication tag */
1752
+ tag: string;
1753
+ /** ID of the key used for encryption */
1754
+ keyId: string;
1755
+ /** Algorithm used */
1756
+ algorithm: CryptoAlgorithm;
1757
+ /** Schema version for forward compatibility */
1758
+ version: 1;
1759
+ }
1760
+ /** Deterministic encrypted field — enables WHERE clause lookups */
1761
+ interface DeterministicEncryptedField {
1762
+ /** HMAC-SHA256 hash for equality searches */
1763
+ hash: string;
1764
+ /** Full encrypted field for decryption */
1765
+ encrypted: EncryptedField;
1766
+ }
1767
+ /** Key metadata (never exposes raw key material) */
1768
+ interface CryptoKeyMetadata {
1769
+ keyId: string;
1770
+ createdAt: Date;
1771
+ status: CryptoKeyStatus;
1772
+ }
1773
+ /** Options for encrypt/decrypt operations */
1774
+ interface EncryptOptions {
1775
+ /** Specific key ID to use (defaults to active key) */
1776
+ keyId?: string;
1777
+ /** Additional Authenticated Data for GCM (e.g., table name + row ID) */
1778
+ aad?: string;
1779
+ }
1780
+ /** Result of a key rotation */
1781
+ interface KeyRotationResult {
1782
+ /** ID of the new active key */
1783
+ newKeyId: string;
1784
+ /** ID of the previous active key (now decrypt-only) */
1785
+ previousKeyId: string;
1786
+ }
1787
+ interface ICrypto {
1788
+ /**
1789
+ * Encrypt plaintext using AES-256-GCM with a random IV.
1790
+ * Each call produces unique ciphertext (non-deterministic).
1791
+ */
1792
+ encrypt(plaintext: string, options?: EncryptOptions): Promise<EncryptedField>;
1793
+ /**
1794
+ * Decrypt an encrypted field back to plaintext.
1795
+ * Automatically selects the correct key by keyId.
1796
+ */
1797
+ decrypt(field: EncryptedField, options?: EncryptOptions): Promise<string>;
1798
+ /**
1799
+ * Encrypt with a deterministic hash for searchable encryption.
1800
+ * The hash is stable for the same plaintext (HMAC-SHA256),
1801
+ * while the encrypted value still uses a random IV.
1802
+ */
1803
+ encryptDeterministic(plaintext: string, options?: EncryptOptions): Promise<DeterministicEncryptedField>;
1804
+ /**
1805
+ * Compute a deterministic hash (HMAC-SHA256) for WHERE clause lookups.
1806
+ * Use this to search for records without decrypting.
1807
+ */
1808
+ computeHash(plaintext: string): Promise<string>;
1809
+ /**
1810
+ * Encrypt multiple fields in a single call.
1811
+ */
1812
+ encryptBatch(fields: Record<string, string>, options?: EncryptOptions): Promise<Record<string, EncryptedField>>;
1813
+ /**
1814
+ * Decrypt multiple fields in a single call.
1815
+ */
1816
+ decryptBatch(fields: Record<string, EncryptedField>, options?: EncryptOptions): Promise<Record<string, string>>;
1817
+ /**
1818
+ * Rotate to a new encryption key.
1819
+ * The old key is marked as decrypt-only (can still decrypt, cannot encrypt new data).
1820
+ */
1821
+ rotateKey(): Promise<KeyRotationResult>;
1822
+ /**
1823
+ * Re-encrypt a field with the current active key.
1824
+ * Used after key rotation to migrate old ciphertext.
1825
+ */
1826
+ reEncrypt(field: EncryptedField, options?: EncryptOptions): Promise<EncryptedField>;
1827
+ /**
1828
+ * List all keys and their statuses.
1829
+ */
1830
+ listKeys(): Promise<CryptoKeyMetadata[]>;
1831
+ /**
1832
+ * Get the ID of the current active encryption key.
1833
+ */
1834
+ getActiveKeyId(): Promise<string>;
1835
+ /**
1836
+ * Health check — verifies encrypt/decrypt round-trip works.
1837
+ */
1838
+ healthCheck(): Promise<boolean>;
1839
+ }
1840
+
1739
1841
  /**
1740
1842
  * Main Platform interface
1741
1843
  * Combines all infrastructure services into a single entry point
@@ -1774,6 +1876,8 @@ interface IPlatform {
1774
1876
  readonly ai?: IAI;
1775
1877
  /** RAG service (optional, enabled via RAG_ENABLED=true) */
1776
1878
  readonly rag?: IRAG;
1879
+ /** Crypto service for field-level encryption (optional) */
1880
+ readonly crypto?: ICrypto;
1777
1881
  /**
1778
1882
  * Check health of all services
1779
1883
  */
@@ -2339,6 +2443,37 @@ declare const RAGConfigSchema: z.ZodEffects<z.ZodObject<{
2339
2443
  embeddingApiKey?: string | undefined;
2340
2444
  embeddingModel?: string | undefined;
2341
2445
  }>;
2446
+ declare const CryptoConfigSchema: z.ZodEffects<z.ZodObject<{
2447
+ enabled: z.ZodDefault<z.ZodBoolean>;
2448
+ masterKey: z.ZodOptional<z.ZodString>;
2449
+ hmacKey: z.ZodOptional<z.ZodString>;
2450
+ }, "strip", z.ZodTypeAny, {
2451
+ enabled: boolean;
2452
+ masterKey?: string | undefined;
2453
+ hmacKey?: string | undefined;
2454
+ }, {
2455
+ enabled?: boolean | undefined;
2456
+ masterKey?: string | undefined;
2457
+ hmacKey?: string | undefined;
2458
+ }>, {
2459
+ enabled: boolean;
2460
+ masterKey?: string | undefined;
2461
+ hmacKey?: string | undefined;
2462
+ }, {
2463
+ enabled?: boolean | undefined;
2464
+ masterKey?: string | undefined;
2465
+ hmacKey?: string | undefined;
2466
+ }>;
2467
+ declare const SecurityConfigSchema: z.ZodObject<{
2468
+ enforceTls: z.ZodDefault<z.ZodBoolean>;
2469
+ tlsWarnOnly: z.ZodDefault<z.ZodBoolean>;
2470
+ }, "strip", z.ZodTypeAny, {
2471
+ enforceTls: boolean;
2472
+ tlsWarnOnly: boolean;
2473
+ }, {
2474
+ enforceTls?: boolean | undefined;
2475
+ tlsWarnOnly?: boolean | undefined;
2476
+ }>;
2342
2477
  declare const RetryConfigSchema: z.ZodObject<{
2343
2478
  enabled: z.ZodDefault<z.ZodBoolean>;
2344
2479
  maxAttempts: z.ZodDefault<z.ZodNumber>;
@@ -3170,6 +3305,37 @@ declare const PlatformConfigSchema: z.ZodObject<{
3170
3305
  embeddingApiKey?: string | undefined;
3171
3306
  embeddingModel?: string | undefined;
3172
3307
  }>>;
3308
+ crypto: z.ZodDefault<z.ZodEffects<z.ZodObject<{
3309
+ enabled: z.ZodDefault<z.ZodBoolean>;
3310
+ masterKey: z.ZodOptional<z.ZodString>;
3311
+ hmacKey: z.ZodOptional<z.ZodString>;
3312
+ }, "strip", z.ZodTypeAny, {
3313
+ enabled: boolean;
3314
+ masterKey?: string | undefined;
3315
+ hmacKey?: string | undefined;
3316
+ }, {
3317
+ enabled?: boolean | undefined;
3318
+ masterKey?: string | undefined;
3319
+ hmacKey?: string | undefined;
3320
+ }>, {
3321
+ enabled: boolean;
3322
+ masterKey?: string | undefined;
3323
+ hmacKey?: string | undefined;
3324
+ }, {
3325
+ enabled?: boolean | undefined;
3326
+ masterKey?: string | undefined;
3327
+ hmacKey?: string | undefined;
3328
+ }>>;
3329
+ security: z.ZodDefault<z.ZodObject<{
3330
+ enforceTls: z.ZodDefault<z.ZodBoolean>;
3331
+ tlsWarnOnly: z.ZodDefault<z.ZodBoolean>;
3332
+ }, "strip", z.ZodTypeAny, {
3333
+ enforceTls: boolean;
3334
+ tlsWarnOnly: boolean;
3335
+ }, {
3336
+ enforceTls?: boolean | undefined;
3337
+ tlsWarnOnly?: boolean | undefined;
3338
+ }>>;
3173
3339
  resilience: z.ZodDefault<z.ZodObject<{
3174
3340
  retry: z.ZodDefault<z.ZodObject<{
3175
3341
  enabled: z.ZodDefault<z.ZodBoolean>;
@@ -3489,6 +3655,10 @@ declare const PlatformConfigSchema: z.ZodObject<{
3489
3655
  } | undefined;
3490
3656
  }>>;
3491
3657
  }, "strip", z.ZodTypeAny, {
3658
+ security: {
3659
+ enforceTls: boolean;
3660
+ tlsWarnOnly: boolean;
3661
+ };
3492
3662
  email: {
3493
3663
  provider: "console" | "smtp" | "memory" | "resend";
3494
3664
  secure: boolean;
@@ -3501,6 +3671,11 @@ declare const PlatformConfigSchema: z.ZodObject<{
3501
3671
  from?: string | undefined;
3502
3672
  replyTo?: string | undefined;
3503
3673
  };
3674
+ crypto: {
3675
+ enabled: boolean;
3676
+ masterKey?: string | undefined;
3677
+ hmacKey?: string | undefined;
3678
+ };
3504
3679
  database: {
3505
3680
  provider: "memory" | "postgres" | "supabase";
3506
3681
  poolSize: number;
@@ -3639,6 +3814,10 @@ declare const PlatformConfigSchema: z.ZodObject<{
3639
3814
  };
3640
3815
  };
3641
3816
  }, {
3817
+ security?: {
3818
+ enforceTls?: boolean | undefined;
3819
+ tlsWarnOnly?: boolean | undefined;
3820
+ } | undefined;
3642
3821
  email?: {
3643
3822
  provider?: "console" | "smtp" | "memory" | "resend" | undefined;
3644
3823
  password?: string | undefined;
@@ -3651,6 +3830,11 @@ declare const PlatformConfigSchema: z.ZodObject<{
3651
3830
  replyTo?: string | undefined;
3652
3831
  rateLimitPerSecond?: number | undefined;
3653
3832
  } | undefined;
3833
+ crypto?: {
3834
+ enabled?: boolean | undefined;
3835
+ masterKey?: string | undefined;
3836
+ hmacKey?: string | undefined;
3837
+ } | undefined;
3654
3838
  database?: {
3655
3839
  provider?: "memory" | "postgres" | "supabase" | undefined;
3656
3840
  url?: string | undefined;
@@ -3798,6 +3982,8 @@ type QueueConfig = z.infer<typeof QueueConfigSchema>;
3798
3982
  type ResilienceConfig = z.infer<typeof ResilienceConfigSchema>;
3799
3983
  type ObservabilityConfig = z.infer<typeof ObservabilityConfigSchema>;
3800
3984
  type MiddlewareConfig = z.infer<typeof MiddlewareConfigSchema>;
3985
+ type CryptoConfig = z.infer<typeof CryptoConfigSchema>;
3986
+ type SecurityConfig = z.infer<typeof SecurityConfigSchema>;
3801
3987
  /**
3802
3988
  * Load configuration from environment variables
3803
3989
  */
@@ -4034,4 +4220,4 @@ declare class ConsoleEmail implements IEmail {
4034
4220
  private formatAddresses;
4035
4221
  }
4036
4222
 
4037
- export { type RAGDocument as $, type AIConfig as A, type AIChatRequest as B, ConsoleEmail as C, type AIChatResponse as D, EnvSecrets as E, type AIStreamChunk as F, type AIStreamCallback as G, type AICompletionRequest as H, type IPlatform as I, type Job as J, type AICompletionResponse as K, type AIEmbeddingRequest as L, MemoryDatabase as M, NoopLogger as N, type AIEmbeddingResponse as O, type PlatformHealthStatus as P, type QueryResult as Q, type RepeatOptions as R, type StorageFile as S, type AIModelConfig as T, type UploadOptions as U, type AIModelType as V, type AIProvider as W, type IRAG as X, type RAGConfig as Y, type CreateCollectionOptions as Z, type RAGCollection as _, MemoryCache as a, type EmailAddress as a$, type IngestionOptions as a0, type BulkIngestionResult as a1, type IngestionResult as a2, type DocumentStatus as a3, type RAGChunk as a4, type RAGSearchQuery as a5, type RAGSearchResponse as a6, type RAGSearchResult as a7, type ContextAssemblyConfig as a8, type AssembledContext as a9, type AIToolCall as aA, type AITool as aB, type AIChatChoice as aC, type AIFinishReason as aD, type AIUsageInfo as aE, type RoutingStrategy as aF, type AIRouterConfig as aG, type AIErrorCode as aH, type AIError as aI, MemoryRAG as aJ, ChunkingPresets as aK, type ChunkingStrategy as aL, type ChunkingConfig as aM, type SearchMode as aN, type RAGFilter as aO, type RAGPipelineStep as aP, createPlatformAsync as aQ, createScopedMetrics as aR, MemoryTracing as aS, NoopTracing as aT, type ITracing as aU, type ISpan as aV, type SpanContext as aW, type SpanOptions as aX, type SpanStatus as aY, type SpanKind as aZ, type TracingConfig as a_, type RAGPipeline as aa, type ICacheOptions as ab, type JobResult as ac, type JobContext as ad, type JobEvent as ae, type QueueStats as af, type BackoffOptions as ag, type LogLevel as ah, type LogMeta as ai, type LogEntry as aj, type LoggerConfig as ak, type MetricTags as al, type HistogramStats as am, type TimingStats as an, type Secret as ao, type SecretMetadata as ap, type GetSecretOptions as aq, type SetSecretOptions as ar, type RotateSecretOptions as as, type RotationResult as at, createAIError as au, isAIError as av, AIErrorMessages as aw, MemoryAI as ax, type AIRole as ay, type AIMessage as az, MemoryStorage as b, type EmailAttachment as b0, calculateBackoff as b1, generateJobId as b2, type SpanStatusCode as b3, type SpanEvent as b4, DatabaseProviderSchema as b5, CacheProviderSchema as b6, StorageProviderSchema as b7, EmailProviderSchema as b8, QueueProviderSchema as b9, type EmailConfig as bA, type QueueConfig as bB, type ResilienceConfig as bC, type ObservabilityConfig as bD, type MiddlewareConfig as bE, loadConfig as bF, validateConfig as bG, safeValidateConfig as bH, getDefaultConfig as bI, TracingProviderSchema as ba, LogLevelSchema as bb, AIProviderSchema as bc, RAGProviderSchema as bd, DatabaseConfigSchema as be, CacheConfigSchema as bf, StorageConfigSchema as bg, EmailConfigSchema as bh, QueueConfigSchema as bi, AIConfigSchema as bj, RAGConfigSchema as bk, RetryConfigSchema as bl, CircuitBreakerConfigSchema as bm, TimeoutConfigSchema as bn, BulkheadConfigSchema as bo, ResilienceConfigSchema as bp, LoggingConfigSchema as bq, MetricsConfigSchema as br, TracingConfigSchema as bs, ObservabilityConfigSchema as bt, MiddlewareConfigSchema as bu, PlatformConfigSchema as bv, type PlatformConfig as bw, type DatabaseConfig as bx, type CacheConfig as by, type StorageConfig as bz, MemoryEmail as c, MemoryQueue as d, type IDatabase as e, MemorySecrets as f, createPlatform as g, ConsoleLogger as h, MemoryMetrics as i, NoopMetrics as j, type IQueryBuilder as k, type ICache as l, type IStorage as m, type IEmail as n, type IQueue as o, type ILogger as p, type IMetrics as q, type ISecrets as r, type JobOptions as s, type EmailMessage as t, type MetricsSummary as u, type EmailResult as v, type JobState as w, type JobEventType as x, type JobEventHandler as y, type IAI as z };
4223
+ export { type AIModelType as $, type JobState as A, type JobEventType as B, ConsoleEmail as C, type DeterministicEncryptedField as D, EnvSecrets as E, type JobEventHandler as F, type IAI as G, type AIConfig as H, type IPlatform as I, type Job as J, type KeyRotationResult as K, type AIChatRequest as L, MemoryDatabase as M, NoopLogger as N, type AIChatResponse as O, type PlatformHealthStatus as P, type QueryResult as Q, type RepeatOptions as R, type StorageFile as S, type AIStreamChunk as T, type UploadOptions as U, type AIStreamCallback as V, type AICompletionRequest as W, type AICompletionResponse as X, type AIEmbeddingRequest as Y, type AIEmbeddingResponse as Z, type AIModelConfig as _, MemoryCache as a, NoopTracing as a$, type AIProvider as a0, type IRAG as a1, type RAGConfig as a2, type CreateCollectionOptions as a3, type RAGCollection as a4, type RAGDocument as a5, type IngestionOptions as a6, type BulkIngestionResult as a7, type IngestionResult as a8, type DocumentStatus as a9, createAIError as aA, isAIError as aB, AIErrorMessages as aC, MemoryAI as aD, type AIRole as aE, type AIMessage as aF, type AIToolCall as aG, type AITool as aH, type AIChatChoice as aI, type AIFinishReason as aJ, type AIUsageInfo as aK, type RoutingStrategy as aL, type AIRouterConfig as aM, type AIErrorCode as aN, type AIError as aO, MemoryRAG as aP, ChunkingPresets as aQ, type ChunkingStrategy as aR, type ChunkingConfig as aS, type SearchMode as aT, type RAGFilter as aU, type RAGPipelineStep as aV, type CryptoKeyStatus as aW, type CryptoAlgorithm as aX, createPlatformAsync as aY, createScopedMetrics as aZ, MemoryTracing as a_, type RAGChunk as aa, type RAGSearchQuery as ab, type RAGSearchResponse as ac, type RAGSearchResult as ad, type ContextAssemblyConfig as ae, type AssembledContext as af, type RAGPipeline as ag, type ICacheOptions as ah, type JobResult as ai, type JobContext as aj, type JobEvent as ak, type QueueStats as al, type BackoffOptions as am, type LogLevel as an, type LogMeta as ao, type LogEntry as ap, type LoggerConfig as aq, type MetricTags as ar, type HistogramStats as as, type TimingStats as at, type Secret as au, type SecretMetadata as av, type GetSecretOptions as aw, type SetSecretOptions as ax, type RotateSecretOptions as ay, type RotationResult as az, MemoryStorage as b, type ITracing as b0, type ISpan as b1, type SpanContext as b2, type SpanOptions as b3, type SpanStatus as b4, type SpanKind as b5, type TracingConfig as b6, type EmailAddress as b7, type EmailAttachment as b8, calculateBackoff as b9, LoggingConfigSchema as bA, MetricsConfigSchema as bB, TracingConfigSchema as bC, ObservabilityConfigSchema as bD, MiddlewareConfigSchema as bE, PlatformConfigSchema as bF, type PlatformConfig as bG, type DatabaseConfig as bH, type CacheConfig as bI, type StorageConfig as bJ, type EmailConfig as bK, type QueueConfig as bL, type ResilienceConfig as bM, type ObservabilityConfig as bN, type MiddlewareConfig as bO, type CryptoConfig as bP, type SecurityConfig as bQ, loadConfig as bR, validateConfig as bS, safeValidateConfig as bT, getDefaultConfig as bU, generateJobId as ba, type SpanStatusCode as bb, type SpanEvent as bc, DatabaseProviderSchema as bd, CacheProviderSchema as be, StorageProviderSchema as bf, EmailProviderSchema as bg, QueueProviderSchema as bh, TracingProviderSchema as bi, LogLevelSchema as bj, AIProviderSchema as bk, RAGProviderSchema as bl, DatabaseConfigSchema as bm, CacheConfigSchema as bn, StorageConfigSchema as bo, EmailConfigSchema as bp, QueueConfigSchema as bq, AIConfigSchema as br, RAGConfigSchema as bs, CryptoConfigSchema as bt, SecurityConfigSchema as bu, RetryConfigSchema as bv, CircuitBreakerConfigSchema as bw, TimeoutConfigSchema as bx, BulkheadConfigSchema as by, ResilienceConfigSchema as bz, MemoryEmail as c, MemoryQueue as d, type IDatabase as e, MemorySecrets as f, createPlatform as g, ConsoleLogger as h, MemoryMetrics as i, NoopMetrics as j, type IQueryBuilder as k, type ICache as l, type IStorage as m, type IEmail as n, type IQueue as o, type ILogger as p, type IMetrics as q, type ISecrets as r, type JobOptions as s, type EmailMessage as t, type MetricsSummary as u, type ICrypto as v, type EncryptOptions as w, type EncryptedField as x, type CryptoKeyMetadata as y, type EmailResult as z };
@@ -1736,6 +1736,108 @@ declare class MemoryRAG implements IRAG {
1736
1736
  private deduplicateResults;
1737
1737
  }
1738
1738
 
1739
+ /**
1740
+ * ICrypto - Field-Level Encryption Interface
1741
+ * Provides AES-256-GCM encryption with key rotation for PII in databases.
1742
+ */
1743
+ type CryptoAlgorithm = "aes-256-gcm";
1744
+ type CryptoKeyStatus = "active" | "decrypt-only" | "retired";
1745
+ /** Encrypted field stored in database columns */
1746
+ interface EncryptedField {
1747
+ /** Base64-encoded ciphertext */
1748
+ ciphertext: string;
1749
+ /** Base64-encoded initialization vector (96-bit for GCM) */
1750
+ iv: string;
1751
+ /** Base64-encoded GCM authentication tag */
1752
+ tag: string;
1753
+ /** ID of the key used for encryption */
1754
+ keyId: string;
1755
+ /** Algorithm used */
1756
+ algorithm: CryptoAlgorithm;
1757
+ /** Schema version for forward compatibility */
1758
+ version: 1;
1759
+ }
1760
+ /** Deterministic encrypted field — enables WHERE clause lookups */
1761
+ interface DeterministicEncryptedField {
1762
+ /** HMAC-SHA256 hash for equality searches */
1763
+ hash: string;
1764
+ /** Full encrypted field for decryption */
1765
+ encrypted: EncryptedField;
1766
+ }
1767
+ /** Key metadata (never exposes raw key material) */
1768
+ interface CryptoKeyMetadata {
1769
+ keyId: string;
1770
+ createdAt: Date;
1771
+ status: CryptoKeyStatus;
1772
+ }
1773
+ /** Options for encrypt/decrypt operations */
1774
+ interface EncryptOptions {
1775
+ /** Specific key ID to use (defaults to active key) */
1776
+ keyId?: string;
1777
+ /** Additional Authenticated Data for GCM (e.g., table name + row ID) */
1778
+ aad?: string;
1779
+ }
1780
+ /** Result of a key rotation */
1781
+ interface KeyRotationResult {
1782
+ /** ID of the new active key */
1783
+ newKeyId: string;
1784
+ /** ID of the previous active key (now decrypt-only) */
1785
+ previousKeyId: string;
1786
+ }
1787
+ interface ICrypto {
1788
+ /**
1789
+ * Encrypt plaintext using AES-256-GCM with a random IV.
1790
+ * Each call produces unique ciphertext (non-deterministic).
1791
+ */
1792
+ encrypt(plaintext: string, options?: EncryptOptions): Promise<EncryptedField>;
1793
+ /**
1794
+ * Decrypt an encrypted field back to plaintext.
1795
+ * Automatically selects the correct key by keyId.
1796
+ */
1797
+ decrypt(field: EncryptedField, options?: EncryptOptions): Promise<string>;
1798
+ /**
1799
+ * Encrypt with a deterministic hash for searchable encryption.
1800
+ * The hash is stable for the same plaintext (HMAC-SHA256),
1801
+ * while the encrypted value still uses a random IV.
1802
+ */
1803
+ encryptDeterministic(plaintext: string, options?: EncryptOptions): Promise<DeterministicEncryptedField>;
1804
+ /**
1805
+ * Compute a deterministic hash (HMAC-SHA256) for WHERE clause lookups.
1806
+ * Use this to search for records without decrypting.
1807
+ */
1808
+ computeHash(plaintext: string): Promise<string>;
1809
+ /**
1810
+ * Encrypt multiple fields in a single call.
1811
+ */
1812
+ encryptBatch(fields: Record<string, string>, options?: EncryptOptions): Promise<Record<string, EncryptedField>>;
1813
+ /**
1814
+ * Decrypt multiple fields in a single call.
1815
+ */
1816
+ decryptBatch(fields: Record<string, EncryptedField>, options?: EncryptOptions): Promise<Record<string, string>>;
1817
+ /**
1818
+ * Rotate to a new encryption key.
1819
+ * The old key is marked as decrypt-only (can still decrypt, cannot encrypt new data).
1820
+ */
1821
+ rotateKey(): Promise<KeyRotationResult>;
1822
+ /**
1823
+ * Re-encrypt a field with the current active key.
1824
+ * Used after key rotation to migrate old ciphertext.
1825
+ */
1826
+ reEncrypt(field: EncryptedField, options?: EncryptOptions): Promise<EncryptedField>;
1827
+ /**
1828
+ * List all keys and their statuses.
1829
+ */
1830
+ listKeys(): Promise<CryptoKeyMetadata[]>;
1831
+ /**
1832
+ * Get the ID of the current active encryption key.
1833
+ */
1834
+ getActiveKeyId(): Promise<string>;
1835
+ /**
1836
+ * Health check — verifies encrypt/decrypt round-trip works.
1837
+ */
1838
+ healthCheck(): Promise<boolean>;
1839
+ }
1840
+
1739
1841
  /**
1740
1842
  * Main Platform interface
1741
1843
  * Combines all infrastructure services into a single entry point
@@ -1774,6 +1876,8 @@ interface IPlatform {
1774
1876
  readonly ai?: IAI;
1775
1877
  /** RAG service (optional, enabled via RAG_ENABLED=true) */
1776
1878
  readonly rag?: IRAG;
1879
+ /** Crypto service for field-level encryption (optional) */
1880
+ readonly crypto?: ICrypto;
1777
1881
  /**
1778
1882
  * Check health of all services
1779
1883
  */
@@ -2339,6 +2443,37 @@ declare const RAGConfigSchema: z.ZodEffects<z.ZodObject<{
2339
2443
  embeddingApiKey?: string | undefined;
2340
2444
  embeddingModel?: string | undefined;
2341
2445
  }>;
2446
+ declare const CryptoConfigSchema: z.ZodEffects<z.ZodObject<{
2447
+ enabled: z.ZodDefault<z.ZodBoolean>;
2448
+ masterKey: z.ZodOptional<z.ZodString>;
2449
+ hmacKey: z.ZodOptional<z.ZodString>;
2450
+ }, "strip", z.ZodTypeAny, {
2451
+ enabled: boolean;
2452
+ masterKey?: string | undefined;
2453
+ hmacKey?: string | undefined;
2454
+ }, {
2455
+ enabled?: boolean | undefined;
2456
+ masterKey?: string | undefined;
2457
+ hmacKey?: string | undefined;
2458
+ }>, {
2459
+ enabled: boolean;
2460
+ masterKey?: string | undefined;
2461
+ hmacKey?: string | undefined;
2462
+ }, {
2463
+ enabled?: boolean | undefined;
2464
+ masterKey?: string | undefined;
2465
+ hmacKey?: string | undefined;
2466
+ }>;
2467
+ declare const SecurityConfigSchema: z.ZodObject<{
2468
+ enforceTls: z.ZodDefault<z.ZodBoolean>;
2469
+ tlsWarnOnly: z.ZodDefault<z.ZodBoolean>;
2470
+ }, "strip", z.ZodTypeAny, {
2471
+ enforceTls: boolean;
2472
+ tlsWarnOnly: boolean;
2473
+ }, {
2474
+ enforceTls?: boolean | undefined;
2475
+ tlsWarnOnly?: boolean | undefined;
2476
+ }>;
2342
2477
  declare const RetryConfigSchema: z.ZodObject<{
2343
2478
  enabled: z.ZodDefault<z.ZodBoolean>;
2344
2479
  maxAttempts: z.ZodDefault<z.ZodNumber>;
@@ -3170,6 +3305,37 @@ declare const PlatformConfigSchema: z.ZodObject<{
3170
3305
  embeddingApiKey?: string | undefined;
3171
3306
  embeddingModel?: string | undefined;
3172
3307
  }>>;
3308
+ crypto: z.ZodDefault<z.ZodEffects<z.ZodObject<{
3309
+ enabled: z.ZodDefault<z.ZodBoolean>;
3310
+ masterKey: z.ZodOptional<z.ZodString>;
3311
+ hmacKey: z.ZodOptional<z.ZodString>;
3312
+ }, "strip", z.ZodTypeAny, {
3313
+ enabled: boolean;
3314
+ masterKey?: string | undefined;
3315
+ hmacKey?: string | undefined;
3316
+ }, {
3317
+ enabled?: boolean | undefined;
3318
+ masterKey?: string | undefined;
3319
+ hmacKey?: string | undefined;
3320
+ }>, {
3321
+ enabled: boolean;
3322
+ masterKey?: string | undefined;
3323
+ hmacKey?: string | undefined;
3324
+ }, {
3325
+ enabled?: boolean | undefined;
3326
+ masterKey?: string | undefined;
3327
+ hmacKey?: string | undefined;
3328
+ }>>;
3329
+ security: z.ZodDefault<z.ZodObject<{
3330
+ enforceTls: z.ZodDefault<z.ZodBoolean>;
3331
+ tlsWarnOnly: z.ZodDefault<z.ZodBoolean>;
3332
+ }, "strip", z.ZodTypeAny, {
3333
+ enforceTls: boolean;
3334
+ tlsWarnOnly: boolean;
3335
+ }, {
3336
+ enforceTls?: boolean | undefined;
3337
+ tlsWarnOnly?: boolean | undefined;
3338
+ }>>;
3173
3339
  resilience: z.ZodDefault<z.ZodObject<{
3174
3340
  retry: z.ZodDefault<z.ZodObject<{
3175
3341
  enabled: z.ZodDefault<z.ZodBoolean>;
@@ -3489,6 +3655,10 @@ declare const PlatformConfigSchema: z.ZodObject<{
3489
3655
  } | undefined;
3490
3656
  }>>;
3491
3657
  }, "strip", z.ZodTypeAny, {
3658
+ security: {
3659
+ enforceTls: boolean;
3660
+ tlsWarnOnly: boolean;
3661
+ };
3492
3662
  email: {
3493
3663
  provider: "console" | "smtp" | "memory" | "resend";
3494
3664
  secure: boolean;
@@ -3501,6 +3671,11 @@ declare const PlatformConfigSchema: z.ZodObject<{
3501
3671
  from?: string | undefined;
3502
3672
  replyTo?: string | undefined;
3503
3673
  };
3674
+ crypto: {
3675
+ enabled: boolean;
3676
+ masterKey?: string | undefined;
3677
+ hmacKey?: string | undefined;
3678
+ };
3504
3679
  database: {
3505
3680
  provider: "memory" | "postgres" | "supabase";
3506
3681
  poolSize: number;
@@ -3639,6 +3814,10 @@ declare const PlatformConfigSchema: z.ZodObject<{
3639
3814
  };
3640
3815
  };
3641
3816
  }, {
3817
+ security?: {
3818
+ enforceTls?: boolean | undefined;
3819
+ tlsWarnOnly?: boolean | undefined;
3820
+ } | undefined;
3642
3821
  email?: {
3643
3822
  provider?: "console" | "smtp" | "memory" | "resend" | undefined;
3644
3823
  password?: string | undefined;
@@ -3651,6 +3830,11 @@ declare const PlatformConfigSchema: z.ZodObject<{
3651
3830
  replyTo?: string | undefined;
3652
3831
  rateLimitPerSecond?: number | undefined;
3653
3832
  } | undefined;
3833
+ crypto?: {
3834
+ enabled?: boolean | undefined;
3835
+ masterKey?: string | undefined;
3836
+ hmacKey?: string | undefined;
3837
+ } | undefined;
3654
3838
  database?: {
3655
3839
  provider?: "memory" | "postgres" | "supabase" | undefined;
3656
3840
  url?: string | undefined;
@@ -3798,6 +3982,8 @@ type QueueConfig = z.infer<typeof QueueConfigSchema>;
3798
3982
  type ResilienceConfig = z.infer<typeof ResilienceConfigSchema>;
3799
3983
  type ObservabilityConfig = z.infer<typeof ObservabilityConfigSchema>;
3800
3984
  type MiddlewareConfig = z.infer<typeof MiddlewareConfigSchema>;
3985
+ type CryptoConfig = z.infer<typeof CryptoConfigSchema>;
3986
+ type SecurityConfig = z.infer<typeof SecurityConfigSchema>;
3801
3987
  /**
3802
3988
  * Load configuration from environment variables
3803
3989
  */
@@ -4034,4 +4220,4 @@ declare class ConsoleEmail implements IEmail {
4034
4220
  private formatAddresses;
4035
4221
  }
4036
4222
 
4037
- export { type RAGDocument as $, type AIConfig as A, type AIChatRequest as B, ConsoleEmail as C, type AIChatResponse as D, EnvSecrets as E, type AIStreamChunk as F, type AIStreamCallback as G, type AICompletionRequest as H, type IPlatform as I, type Job as J, type AICompletionResponse as K, type AIEmbeddingRequest as L, MemoryDatabase as M, NoopLogger as N, type AIEmbeddingResponse as O, type PlatformHealthStatus as P, type QueryResult as Q, type RepeatOptions as R, type StorageFile as S, type AIModelConfig as T, type UploadOptions as U, type AIModelType as V, type AIProvider as W, type IRAG as X, type RAGConfig as Y, type CreateCollectionOptions as Z, type RAGCollection as _, MemoryCache as a, type EmailAddress as a$, type IngestionOptions as a0, type BulkIngestionResult as a1, type IngestionResult as a2, type DocumentStatus as a3, type RAGChunk as a4, type RAGSearchQuery as a5, type RAGSearchResponse as a6, type RAGSearchResult as a7, type ContextAssemblyConfig as a8, type AssembledContext as a9, type AIToolCall as aA, type AITool as aB, type AIChatChoice as aC, type AIFinishReason as aD, type AIUsageInfo as aE, type RoutingStrategy as aF, type AIRouterConfig as aG, type AIErrorCode as aH, type AIError as aI, MemoryRAG as aJ, ChunkingPresets as aK, type ChunkingStrategy as aL, type ChunkingConfig as aM, type SearchMode as aN, type RAGFilter as aO, type RAGPipelineStep as aP, createPlatformAsync as aQ, createScopedMetrics as aR, MemoryTracing as aS, NoopTracing as aT, type ITracing as aU, type ISpan as aV, type SpanContext as aW, type SpanOptions as aX, type SpanStatus as aY, type SpanKind as aZ, type TracingConfig as a_, type RAGPipeline as aa, type ICacheOptions as ab, type JobResult as ac, type JobContext as ad, type JobEvent as ae, type QueueStats as af, type BackoffOptions as ag, type LogLevel as ah, type LogMeta as ai, type LogEntry as aj, type LoggerConfig as ak, type MetricTags as al, type HistogramStats as am, type TimingStats as an, type Secret as ao, type SecretMetadata as ap, type GetSecretOptions as aq, type SetSecretOptions as ar, type RotateSecretOptions as as, type RotationResult as at, createAIError as au, isAIError as av, AIErrorMessages as aw, MemoryAI as ax, type AIRole as ay, type AIMessage as az, MemoryStorage as b, type EmailAttachment as b0, calculateBackoff as b1, generateJobId as b2, type SpanStatusCode as b3, type SpanEvent as b4, DatabaseProviderSchema as b5, CacheProviderSchema as b6, StorageProviderSchema as b7, EmailProviderSchema as b8, QueueProviderSchema as b9, type EmailConfig as bA, type QueueConfig as bB, type ResilienceConfig as bC, type ObservabilityConfig as bD, type MiddlewareConfig as bE, loadConfig as bF, validateConfig as bG, safeValidateConfig as bH, getDefaultConfig as bI, TracingProviderSchema as ba, LogLevelSchema as bb, AIProviderSchema as bc, RAGProviderSchema as bd, DatabaseConfigSchema as be, CacheConfigSchema as bf, StorageConfigSchema as bg, EmailConfigSchema as bh, QueueConfigSchema as bi, AIConfigSchema as bj, RAGConfigSchema as bk, RetryConfigSchema as bl, CircuitBreakerConfigSchema as bm, TimeoutConfigSchema as bn, BulkheadConfigSchema as bo, ResilienceConfigSchema as bp, LoggingConfigSchema as bq, MetricsConfigSchema as br, TracingConfigSchema as bs, ObservabilityConfigSchema as bt, MiddlewareConfigSchema as bu, PlatformConfigSchema as bv, type PlatformConfig as bw, type DatabaseConfig as bx, type CacheConfig as by, type StorageConfig as bz, MemoryEmail as c, MemoryQueue as d, type IDatabase as e, MemorySecrets as f, createPlatform as g, ConsoleLogger as h, MemoryMetrics as i, NoopMetrics as j, type IQueryBuilder as k, type ICache as l, type IStorage as m, type IEmail as n, type IQueue as o, type ILogger as p, type IMetrics as q, type ISecrets as r, type JobOptions as s, type EmailMessage as t, type MetricsSummary as u, type EmailResult as v, type JobState as w, type JobEventType as x, type JobEventHandler as y, type IAI as z };
4223
+ export { type AIModelType as $, type JobState as A, type JobEventType as B, ConsoleEmail as C, type DeterministicEncryptedField as D, EnvSecrets as E, type JobEventHandler as F, type IAI as G, type AIConfig as H, type IPlatform as I, type Job as J, type KeyRotationResult as K, type AIChatRequest as L, MemoryDatabase as M, NoopLogger as N, type AIChatResponse as O, type PlatformHealthStatus as P, type QueryResult as Q, type RepeatOptions as R, type StorageFile as S, type AIStreamChunk as T, type UploadOptions as U, type AIStreamCallback as V, type AICompletionRequest as W, type AICompletionResponse as X, type AIEmbeddingRequest as Y, type AIEmbeddingResponse as Z, type AIModelConfig as _, MemoryCache as a, NoopTracing as a$, type AIProvider as a0, type IRAG as a1, type RAGConfig as a2, type CreateCollectionOptions as a3, type RAGCollection as a4, type RAGDocument as a5, type IngestionOptions as a6, type BulkIngestionResult as a7, type IngestionResult as a8, type DocumentStatus as a9, createAIError as aA, isAIError as aB, AIErrorMessages as aC, MemoryAI as aD, type AIRole as aE, type AIMessage as aF, type AIToolCall as aG, type AITool as aH, type AIChatChoice as aI, type AIFinishReason as aJ, type AIUsageInfo as aK, type RoutingStrategy as aL, type AIRouterConfig as aM, type AIErrorCode as aN, type AIError as aO, MemoryRAG as aP, ChunkingPresets as aQ, type ChunkingStrategy as aR, type ChunkingConfig as aS, type SearchMode as aT, type RAGFilter as aU, type RAGPipelineStep as aV, type CryptoKeyStatus as aW, type CryptoAlgorithm as aX, createPlatformAsync as aY, createScopedMetrics as aZ, MemoryTracing as a_, type RAGChunk as aa, type RAGSearchQuery as ab, type RAGSearchResponse as ac, type RAGSearchResult as ad, type ContextAssemblyConfig as ae, type AssembledContext as af, type RAGPipeline as ag, type ICacheOptions as ah, type JobResult as ai, type JobContext as aj, type JobEvent as ak, type QueueStats as al, type BackoffOptions as am, type LogLevel as an, type LogMeta as ao, type LogEntry as ap, type LoggerConfig as aq, type MetricTags as ar, type HistogramStats as as, type TimingStats as at, type Secret as au, type SecretMetadata as av, type GetSecretOptions as aw, type SetSecretOptions as ax, type RotateSecretOptions as ay, type RotationResult as az, MemoryStorage as b, type ITracing as b0, type ISpan as b1, type SpanContext as b2, type SpanOptions as b3, type SpanStatus as b4, type SpanKind as b5, type TracingConfig as b6, type EmailAddress as b7, type EmailAttachment as b8, calculateBackoff as b9, LoggingConfigSchema as bA, MetricsConfigSchema as bB, TracingConfigSchema as bC, ObservabilityConfigSchema as bD, MiddlewareConfigSchema as bE, PlatformConfigSchema as bF, type PlatformConfig as bG, type DatabaseConfig as bH, type CacheConfig as bI, type StorageConfig as bJ, type EmailConfig as bK, type QueueConfig as bL, type ResilienceConfig as bM, type ObservabilityConfig as bN, type MiddlewareConfig as bO, type CryptoConfig as bP, type SecurityConfig as bQ, loadConfig as bR, validateConfig as bS, safeValidateConfig as bT, getDefaultConfig as bU, generateJobId as ba, type SpanStatusCode as bb, type SpanEvent as bc, DatabaseProviderSchema as bd, CacheProviderSchema as be, StorageProviderSchema as bf, EmailProviderSchema as bg, QueueProviderSchema as bh, TracingProviderSchema as bi, LogLevelSchema as bj, AIProviderSchema as bk, RAGProviderSchema as bl, DatabaseConfigSchema as bm, CacheConfigSchema as bn, StorageConfigSchema as bo, EmailConfigSchema as bp, QueueConfigSchema as bq, AIConfigSchema as br, RAGConfigSchema as bs, CryptoConfigSchema as bt, SecurityConfigSchema as bu, RetryConfigSchema as bv, CircuitBreakerConfigSchema as bw, TimeoutConfigSchema as bx, BulkheadConfigSchema as by, ResilienceConfigSchema as bz, MemoryEmail as c, MemoryQueue as d, type IDatabase as e, MemorySecrets as f, createPlatform as g, ConsoleLogger as h, MemoryMetrics as i, NoopMetrics as j, type IQueryBuilder as k, type ICache as l, type IStorage as m, type IEmail as n, type IQueue as o, type ILogger as p, type IMetrics as q, type ISecrets as r, type JobOptions as s, type EmailMessage as t, type MetricsSummary as u, type ICrypto as v, type EncryptOptions as w, type EncryptedField as x, type CryptoKeyMetadata as y, type EmailResult as z };