@katlux/toolkit 0.1.1-alpha.140 → 0.1.1-alpha.142

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.
Files changed (48) hide show
  1. package/dist/compiled/composables/useKatluxForm.mjs +29 -21
  2. package/dist/module.json +1 -1
  3. package/dist/runtime/components/KDatePicker/KDatePicker.global.d.vue.ts +3 -3
  4. package/dist/runtime/components/KDatePicker/KDatePicker.global.vue.d.ts +3 -3
  5. package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.d.vue.ts +2 -2
  6. package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.vue.d.ts +2 -2
  7. package/dist/runtime/composables/useKatluxForm.d.ts +11 -11
  8. package/dist/runtime/composables/useKatluxForm.js +29 -21
  9. package/dist/skills/katlux-components/components/KAreaChart.md +1 -1
  10. package/dist/skills/katlux-components/components/KBarChart.md +1 -1
  11. package/dist/skills/katlux-components/components/KBulkActions.md +3 -3
  12. package/dist/skills/katlux-components/components/KCheckbox.md +2 -2
  13. package/dist/skills/katlux-components/components/KCombobox.md +3 -3
  14. package/dist/skills/katlux-components/components/KCompositeInput.md +4 -4
  15. package/dist/skills/katlux-components/components/KDataIterator.md +3 -3
  16. package/dist/skills/katlux-components/components/KDatatable.md +7 -7
  17. package/dist/skills/katlux-components/components/KDatePicker.md +3 -3
  18. package/dist/skills/katlux-components/components/KGantt.md +12 -12
  19. package/dist/skills/katlux-components/components/KHeatMap.md +1 -1
  20. package/dist/skills/katlux-components/components/KLineChart.md +1 -1
  21. package/dist/skills/katlux-components/components/KPieChart.md +1 -1
  22. package/dist/skills/katlux-components/components/KScatterChart.md +1 -1
  23. package/dist/skills/katlux-components/components/KTree.md +8 -8
  24. package/dist/skills/katlux-components/components/KTreePicker.md +3 -3
  25. package/dist/skills/katlux-components/components/KTreeView.md +3 -3
  26. package/dist/skills/katlux-config/SKILL.md +7 -7
  27. package/dist/skills/katlux-presets/SKILL.md +1 -1
  28. package/dist/skills/katlux-presets/creating-a-preset.md +1 -1
  29. package/dist/skills/katlux-providers/SKILL.md +1 -1
  30. package/dist/skills/katlux-providers/providers/ADataProvider.md +3 -3
  31. package/dist/skills/katlux-providers/providers/CAPIFlatClientDataProvider.md +3 -3
  32. package/dist/skills/katlux-providers/providers/CAPIFlatServerDataProvider.md +3 -3
  33. package/dist/skills/katlux-providers/providers/CFlatClientDataProvider.md +4 -4
  34. package/dist/skills/katlux-providers/providers/CFlatServerDataProvider.md +1 -1
  35. package/dist/skills/katlux-providers/providers/CTreeClientDataProvider.md +2 -2
  36. package/dist/skills/katlux-providers/providers/RequestProvider.md +4 -4
  37. package/dist/skills/katlux-providers/providers/caching.md +11 -11
  38. package/dist/skills/katlux-providers/providers/encryption-asymmetric.md +102 -0
  39. package/dist/skills/katlux-providers/providers/encryption-field-level.md +260 -0
  40. package/dist/skills/katlux-providers/providers/encryption-key-management.md +196 -0
  41. package/dist/skills/katlux-providers/providers/encryption-key-pinning.md +115 -0
  42. package/dist/skills/katlux-providers/providers/encryption-streaming.md +84 -0
  43. package/dist/skills/katlux-providers/providers/encryption-symmetric.md +139 -0
  44. package/dist/skills/katlux-providers/providers/encryption-threat-model.md +110 -0
  45. package/dist/skills/katlux-providers/providers/encryption.md +44 -267
  46. package/dist/skills/katlux-providers/providers/types.md +5 -5
  47. package/dist/skills/katlux-providers/providers/useDataProvider.md +1 -1
  48. package/package.json +2 -2
@@ -0,0 +1,139 @@
1
+ # Katlux Encryption Architecture: Symmetric Cipher Providers
2
+
3
+ > Part of the Katlux Cryptographic Architecture (`@katlux/providers`).
4
+ > See [encryption.md](encryption.md) for the master index.
5
+
6
+ ---
7
+
8
+ ## 1. Overview of Symmetric Providers
9
+
10
+ | Provider | Algorithm | Environment | Primary Use Case |
11
+ | :--- | :--- | :--- | :--- |
12
+ | `CWebCryptoEncryptionProvider` | AES-GCM-256 | Browser & Server (Async) | Modern Web Crypto standard, built-in AEAD integrity, PBKDF2/HKDF support |
13
+ | `CWebCryptoAESCBCProvider` | AES-CBC-256 + HMAC-SHA-256 | Browser & Server (Async) | Legacy compliance, Encrypt-then-MAC authentication |
14
+ | `CNodeCryptoEncryptionProvider` | AES-GCM-256 | Server (Sync/Async) | Zero-microtask synchronous server routes via `node:crypto` |
15
+
16
+ ---
17
+
18
+ ## 2. `CWebCryptoEncryptionProvider` (AES-GCM-256)
19
+
20
+ Standard native Web Crypto implementation using AES-GCM with a 128-bit authentication tag and a 96-bit random IV.
21
+
22
+ ### Basic Usage
23
+ ```ts
24
+ import { CWebCryptoEncryptionProvider } from '@katlux/providers'
25
+
26
+ const cipher = new CWebCryptoEncryptionProvider({
27
+ key: 'my-passphrase-or-raw-32-byte-key',
28
+ kid: 'tenant-v1',
29
+ kdf: 'pbkdf2', // 'pbkdf2' for passwords, 'none' for 256-bit keys
30
+ kdfIterations: 310000
31
+ })
32
+
33
+ // Encrypt arbitrary object, array, or string:
34
+ const envelope = await cipher.encrypt({ ssn: '123-45-6789', salary: 150000 })
35
+
36
+ // Decrypt back to original structure:
37
+ const data = await cipher.decrypt(envelope)
38
+ ```
39
+
40
+ ---
41
+
42
+ ## 3. `CWebCryptoAESCBCProvider` (AES-CBC-256 + HMAC-SHA-256)
43
+
44
+ Combines AES-CBC-256 with HMAC-SHA-256 in a secure **Encrypt-then-MAC** construction for legacy environments.
45
+
46
+ ```ts
47
+ import { CWebCryptoAESCBCProvider } from '@katlux/providers'
48
+
49
+ const cbcCipher = new CWebCryptoAESCBCProvider({
50
+ key: process.env.LEGACY_CIPHER_KEY,
51
+ kid: 'legacy-v1',
52
+ kdf: 'pbkdf2'
53
+ })
54
+
55
+ const envelope = await cbcCipher.encrypt('sensitive-data')
56
+ const decrypted = await cbcCipher.decrypt(envelope)
57
+ ```
58
+
59
+ ---
60
+
61
+ ## 4. `CNodeCryptoEncryptionProvider` (Node.js Sync/Async)
62
+
63
+ Synchronous, zero-microtask AES-GCM encryption using native `node:crypto`. 100% binary-interoperable with `CWebCryptoEncryptionProvider`.
64
+
65
+ ### Synchronous Server Route Example
66
+ ```ts
67
+ import { CNodeCryptoEncryptionProvider } from '@katlux/providers'
68
+
69
+ const nodeCipher = new CNodeCryptoEncryptionProvider({
70
+ key: process.env.SERVER_ENCRYPTION_KEY,
71
+ kid: 'server-v1',
72
+ strict: true
73
+ })
74
+
75
+ export default defineEventHandler(async (event) => {
76
+ const body = await readBody(event)
77
+ // Zero microtask delay:
78
+ const encrypted = nodeCipher.encryptSync(body, { recordId: 'REC-123', field: 'taxId' })
79
+ return encrypted
80
+ })
81
+ ```
82
+
83
+ - **Strict Tag Enforcement**: Strictly enforces a 16-byte (128-bit) GCM tag on all decryption operations, rejecting truncated tags (e.g. 12, 8, or 4 bytes).
84
+
85
+ ---
86
+
87
+ ## 5. Built-in Keyring & Multi-Key Rotation
88
+
89
+ Katlux cipher providers natively support multi-key keyrings for zero-downtime rotation.
90
+
91
+ ```ts
92
+ const cipher = new CWebCryptoEncryptionProvider({
93
+ keys: {
94
+ 'k2025': oldKey,
95
+ 'k2026': newKey
96
+ },
97
+ activeKid: 'k2026' // All outbound encryption uses k2026
98
+ })
99
+
100
+ // Outbound encryption automatically tags kid: 'k2026':
101
+ const newEnvelope = await cipher.encrypt(data)
102
+
103
+ // Decryption dynamically routes through keys[envelope.kid]:
104
+ const oldDecrypted = await cipher.decrypt(legacyEnvelope) // Decrypts with k2025
105
+ const newDecrypted = await cipher.decrypt(newEnvelope) // Decrypts with k2026
106
+
107
+ // Dynamic runtime rotation:
108
+ cipher.setKeyring({ 'k2026': newKey, 'k2027': nextKey }, 'k2027')
109
+
110
+ // Concurrent warmup:
111
+ await cipher.warmupKey()
112
+ ```
113
+
114
+ - **Whitelist Enforcement**: Envelopes carrying an unknown `kid` not present in `allowedKids` (defaults to `Object.keys(keys)`) are rejected with `Unauthorized key: kid '${payload.kid}' is not in allowedKids`.
115
+
116
+ ---
117
+
118
+ ## 6. Strict Decryption & Whitelisting
119
+
120
+ When `strict: true` is enabled:
121
+ - **Plaintext Injection Prevention**: If any designated sensitive field is unencrypted plaintext, decryption immediately throws a security violation error.
122
+ - **Algorithm Whitelisting**: Restricts accepted decryption algorithms to `allowedAlgorithms` (defaults to `['AES-GCM']`).
123
+
124
+ ---
125
+
126
+ ## 7. Dynamic Authenticated Additional Data (AAD)
127
+
128
+ ```ts
129
+ const cipher = new CWebCryptoEncryptionProvider({
130
+ key: myKey,
131
+ baseAad: 'tenant:corp',
132
+ aadFields: ['org_id', 'department_id'] // Binds sibling record fields into AAD
133
+ })
134
+
135
+ // Automatically binds: aad:tenant:corp|record:REC-42|field:salary|org_id:101|department_id:finance
136
+ const envelope = await cipher.encrypt(record, { recordId: 'REC-42' })
137
+ ```
138
+
139
+ Transposition (moving the ciphertext to a different record or column) causes GCM tag verification to fail immediately.
@@ -0,0 +1,110 @@
1
+ # Katlux Encryption Architecture: Threat Model, Boundaries & Contracts
2
+
3
+ > Part of the Katlux Cryptographic Architecture (`@katlux/providers`).
4
+ > See [encryption.md](encryption.md) for the master index.
5
+
6
+ ---
7
+
8
+ ## 1. E2EE Architecture & Threat Model Boundary
9
+
10
+ - **Primary Objective**: Provide robust **End-to-End Encryption (E2EE)** to prevent catastrophic server-side data leaks (database dumps, cloud infrastructure compromises, rogue backend admin access). In multi-tenant, multi-user SaaS architectures, all GDPR-protected and sensitive data is stored and relayed exclusively as ciphertext envelopes (`__encrypted: true`).
11
+ - **Multi-User Role-Based Key Sharing**: Users with appropriate roles (defined in database permissions) can encrypt and decrypt shared tenant data. Roles may contain symmetric keys or wrapped/encrypted keys. Keys may exist in memory or be wrapped for secure transport across the network to client sessions.
12
+ - **Asymmetric Sender Authenticity Boundary**: Hybrid asymmetric ciphers (`CRSAEncryptionProvider`, `CECDHEncryptionProvider`) provide **recipient confidentiality** (only the holder of the recipient private key can decrypt), but do **not** provide sender authenticity on their own—anyone possessing the recipient public key can encrypt envelopes. In multi-user multi-tenant architectures where write authenticity must be strictly enforced, pair asymmetric encryption with digital signatures (ECDSA/Ed25519) or symmetric tenant role keys (AES-GCM).
13
+ - **Explicit Non-Goals (Client Endpoint Security)**: The encryption system does **not** protect against client-side compromise (OS-level trojans, hardware keyloggers, screen grabbers, or malicious browser extensions). Once data is legitimately decrypted in client DOM/memory for the authorized user to view, local endpoint security is the user's/device owner's responsibility.
14
+
15
+ ---
16
+
17
+ ## 2. Envelope Contract (`IEncryptedPayload`)
18
+
19
+ All Katlux encrypted payloads conform to a standardized envelope format:
20
+
21
+ ```ts
22
+ export interface IEncryptedPayload {
23
+ __encrypted: true
24
+ ciphertext: string // Base64 ciphertext (always present)
25
+ alg: string // 'AES-GCM' | 'AES-CBC-256+HMAC-SHA-256' | 'RSA-OAEP-4096+AES-GCM-256' | 'ECDH-P-256+AES-GCM-256'
26
+ kid?: string // Key identifier / version for key rotation tracking
27
+ iv?: string // Base64 IV
28
+ salt?: string // Base64 KDF salt
29
+ kdf?: string // 'PBKDF2' | 'HKDF'
30
+ iter?: number // PBKDF2 iteration count (default: 310,000, clamped [1,000, 600,000])
31
+ tag?: string // Explicit HMAC tag (AES-CBC)
32
+ wrappedKey?: string // Base64 RSA-wrapped AES key (RSA hybrid)
33
+ sharedKey?: boolean // Shared DEK marker for field-level encryption
34
+ epk?: JsonWebKey // Ephemeral public key (ECDH)
35
+ }
36
+ ```
37
+
38
+ ### Polymorphic Verification
39
+ ```ts
40
+ import { isEncrypted, AEncryptionProvider } from '@katlux/providers'
41
+
42
+ // Fast runtime envelope check:
43
+ if (isEncrypted(data)) {
44
+ // Safe to route to decrypt()
45
+ }
46
+ ```
47
+
48
+ ---
49
+
50
+ ## 3. Provider Options (`IProviderEncryptionOptions`)
51
+
52
+ ```ts
53
+ export interface IProviderEncryptionOptions {
54
+ enabled?: boolean // Master toggle (default: false)
55
+ key?: TKeyProvider // Single key or key provider (legacy/simple mode)
56
+ keys?: Record<string, TKeyProvider | IKeyPair> // Built-in Keyring dictionary mapping kid to keys
57
+ activeKid?: string // Active key identifier from keys to use for outbound encryption
58
+ kid?: string // Key identifier / version (e.g. 'v1', 'tenant-a-key-2026')
59
+ aad?: string | Uint8Array | ArrayBuffer | ((record: Record<string, unknown>, field: string) => string | Uint8Array | ArrayBuffer) // AEAD Additional Data or dynamic callback
60
+ aadFields?: string[] // Sibling record fields to deterministically bind into AAD (e.g. ['contact_id', 'version'])
61
+ baseAad?: string // Optional base prefix for AAD context binding
62
+ decryptOnSSR?: boolean // default: false. Prevents SSR decryption unless explicitly enabled with server secrets
63
+ fields?: string[] // Field-level encryption: only encrypt listed fields
64
+ strict?: boolean // Enforces strict decryption: unencrypted plaintext in `fields` triggers injection violation; defaults allowedAlgorithms to ['AES-GCM']
65
+ allowedAlgorithms?: string[] // Whitelist of permitted cipher algorithms (e.g. ['AES-GCM'])
66
+ allowedKids?: string[] // Whitelist of permitted Key Identifiers (kid); defaults to Object.keys(keys)
67
+ onDecryptError?: ((info: IDecryptErrorInfo) => unknown) | boolean | string // Per-field error hook, safe fallback marker, or true for '[⚠ Decryption Error]'
68
+ searchIndex?: boolean // Enables HMAC-SHA256 blind index and trigram search index on encrypted fields
69
+ preEncrypted?: boolean // Set to true if API endpoints return pre-encrypted ciphertext envelopes; enables in-memory index decryption
70
+ hmacKey?: TKeyProvider // Optional dedicated HMAC key for search indexing (defaults to encryption key)
71
+ algorithm?: 'AES-GCM' | string // default: 'AES-GCM'
72
+ customProvider?: IEncryptionProvider // Custom cipher adapter (e.g. CRSA, CECDH, AES-CBC)
73
+ kdf?: 'none' | 'pbkdf2' | 'hkdf' // Key derivation strategy:
74
+ // - 'pbkdf2': Recommended for human passphrases/passwords (OWASP recommended rounds)
75
+ // - 'hkdf': For high-entropy IKM / subkey derivation (warns if used with string passwords)
76
+ // - 'none': When supplying pre-derived 256-bit raw keys, Buffers, or CryptoKeys
77
+ kdfIterations?: number // PBKDF2 rounds (default: 310,000 per OWASP, clamped [1,000, 600,000])
78
+ kdfHash?: 'SHA-256' | 'SHA-512' // KDF hash algorithm
79
+ kdfSalt?: string | Uint8Array | ArrayBuffer // Optional static salt (random salt in envelope if omitted)
80
+ publicKey?: CryptoKey // Optional public key for asymmetric encryption
81
+ privateKey?: CryptoKey // Optional private key for asymmetric decryption
82
+ recipientPublicKey?: CryptoKey // Recipient public key for hybrid encryption
83
+ recipientPrivateKey?: CryptoKey // Recipient private key for hybrid decryption
84
+ curve?: 'P-256' | 'P-384' | 'P-521' // Curve for ECDH providers
85
+ info?: string // Optional context/info string for HKDF
86
+ }
87
+ ```
88
+
89
+ ---
90
+
91
+ ## 4. Factory & Base Provider Creation
92
+
93
+ ```ts
94
+ import { createEncryptionProvider } from '@katlux/providers'
95
+
96
+ // Automatically selects and configures the appropriate cipher engine:
97
+ const cipher = createEncryptionProvider({
98
+ algorithm: 'AES-GCM',
99
+ key: process.env.DATA_KEY,
100
+ kid: 'v1'
101
+ })
102
+ ```
103
+
104
+ ---
105
+
106
+ ## 5. Security Lifecycle & Memory Hygiene
107
+
108
+ - **Memory Zeroization**: Intermediate plaintext byte buffers (`Uint8Array`, `Buffer`) are immediately zeroed in memory via `.fill(0)` within `finally` blocks.
109
+ - **Session Cleanup (`clearKeys()` / `dispose()`)**: Calling `clearKeys()` or `dispose()` on any provider clears in-memory CryptoKeys, zeroes cached key buffers, and invalidates derived key caches upon user logout.
110
+ - **SSR Confidentiality Guard**: With `decryptOnSSR: false` (default zero-trust setting), sensitive payloads remain as encrypted envelopes in server memory and HTML hydration strings.
@@ -1,267 +1,44 @@
1
- ### `EncryptionProvider` (`CWebCryptoEncryptionProvider`, `CWebCryptoAESCBCProvider`, `CRSAEncryptionProvider`, `CECDHEncryptionProvider`, `CNodeCryptoEncryptionProvider`, `CKeyManager`, `AEncryptionProvider`)
2
- Zero-dependency, native cryptographic toolkit for end-to-end client-side, in-flight, and server-side encryption/decryption using native Web Crypto API (`crypto.subtle`) and `node:crypto`. Zero WASM, zero npm dependencies.
3
-
4
- > [!IMPORTANT]
5
- > **E2EE Architecture & Threat Model Boundary**:
6
- > - **Primary Objective**: Provide robust **End-to-End Encryption (E2EE)** to prevent catastrophic server-side data leaks (database dumps, cloud infrastructure compromises, rogue backend admin access). In multi-tenant, multi-user SaaS architectures, all GDPR-protected and sensitive data is stored and relayed exclusively as ciphertext envelopes (`__encrypted: true`).
7
- > - **Multi-User Role-Based Key Sharing**: Users with appropriate roles (defined in database permissions) can encrypt and decrypt shared tenant data. Roles may contain symmetric keys or wrapped/encrypted keys. Keys may exist in memory or be wrapped for secure transport across the network to client sessions.
8
- > - **Asymmetric Sender Authenticity Boundary**: Hybrid asymmetric ciphers (`CRSAEncryptionProvider`, `CECDHEncryptionProvider`) provide **recipient confidentiality** (only the holder of the recipient private key can decrypt), but do **not** provide sender authenticity on their own—anyone possessing the recipient public key can encrypt envelopes. In multi-user multi-tenant architectures where write authenticity must be strictly enforced, pair asymmetric encryption with digital signatures (ECDSA/Ed25519) or symmetric tenant role keys (AES-GCM).
9
- > - **Explicit Non-Goals (Client Endpoint Security)**: The encryption system does **not** protect against client-side compromise (OS-level trojans, hardware keyloggers, screen grabbers, or malicious browser extensions). Once data is legitimately decrypted in client DOM/memory for the authorized user to view, local endpoint security is the user's/device owner's responsibility.
10
-
11
- > **Showcase Pages**:
12
- > - **Overview & SSR**: `/providers/request/encryption`
13
- > - **Symmetric**: `/providers/classes/CWebCryptoEncryptionProvider` (AES-GCM) · `/providers/classes/CWebCryptoAESCBCProvider` (AES-CBC) · `/providers/classes/CNodeCryptoEncryptionProvider` (Node Sync)
14
- > - **Asymmetric / Hybrid**: `/providers/classes/CRSAEncryptionProvider` (RSA-OAEP) · `/providers/classes/CECDHEncryptionProvider` (ECDH)
15
- > - **Key Management**: `/providers/classes/CKeyManager`
16
- > - **Base & Contracts**: `/providers/classes/AEncryptionProvider` · `/providers/interfaces/IEncryptionProvider` · `/providers/interfaces/IProviderEncryptionOptions` · `/providers/interfaces/IKeyPair` · `/providers/interfaces/IKDFOptions` · `/providers/interfaces/IHKDFFromSecretOptions`
17
-
18
- - **Available Providers**:
19
- - `CWebCryptoEncryptionProvider`: AES-GCM-256 with optional PBKDF2/HKDF key derivation. Built-in AEAD, 100% backward-compatible.
20
- - `CWebCryptoAESCBCProvider`: Authenticated AES-CBC-256 + HMAC-SHA-256 (Encrypt-then-MAC) for legacy system compatibility.
21
- - `CRSAEncryptionProvider`: Asymmetric RSA-OAEP-4096 + AES-GCM-256 hybrid cipher for arbitrary-sized single-recipient payloads.
22
- - `CECDHEncryptionProvider`: Forward-secure Elliptic Curve Diffie-Hellman (P-256/384/521) + HKDF + AES-GCM. Ephemeral key per encryption. Ideal for multi-user role sharing (e.g. Account Symmetric Key wrapping).
23
- - `CNodeCryptoEncryptionProvider`: Server-side synchronous AES-GCM via `node:crypto` (`encryptSync`/`decryptSync`). 100% binary-interoperable with `CWebCryptoEncryptionProvider`.
24
- - **Provider Methods (`IEncryptionProvider` / `AEncryptionProvider`)**:
25
- - `encrypt(data: any, options?: IEncryptionContext): Promise<IEncryptedPayload | any>`: Encrypts data into an envelope or field-encrypted record (strictly idempotent; already-encrypted fields/envelopes are never double-encrypted). Attaches `kid` when specified or uses `activeKid`.
26
- - `decrypt(payload: any, options?: IEncryptionContext): Promise<any>`: Decrypts envelope back into original data, immediately zeroing plaintext byte buffers in memory. Dynamically routes decryption through `keys[envelope.kid]` or fallback keys, validating against `allowedKids`. Automatically leverages record-level DEK caching across multi-field records for up to 90% latency reduction.
27
- - `encryptField(value: any, context?: IFieldEncryptionContext): Promise<IEncryptedPayload>`: Atomically encrypts a single scalar value with contextual AAD binding (`recordId`, `fieldName`, sibling `aadFields`) into an `IEncryptedPayload` envelope without requiring dummy object allocation.
28
- - `decryptField(envelope: IEncryptedPayload, context?: IFieldEncryptionContext): Promise<any>`: Symmetrically decrypts a single scalar field envelope, verifying contextual AAD integrity and tamper resistance.
29
- - `computeBlindIndex(value: any, hmacKey?: CryptoKey | TKeyProvider): Promise<string>`: Computes deterministic HMAC-SHA256 blind index hex hash with Unicode NFKC normalization and lowercasing for exact-match database lookups.
30
- - `warmupKey(options?: IEncryptionContext): Promise<void>`: Pre-derives and caches CryptoKey / Buffer in memory. When a keyring (`keys`) is configured, resolves and warms up all keys concurrently via `Promise.all`. Supported on `CWebCrypto`, `CWebCryptoAESCBC`, and `CNodeCrypto` (`warmupKeySync` also available on Node).
31
- - `setKeyring(keys: Record<string, TKeyProvider | IKeyPair>, activeKid?: string): void`: Replaces or updates the active keyring dictionary and optionally sets the active outbound key identifier.
32
- - `getKeyring(): Record<string, TKeyProvider | IKeyPair>`: Returns the currently configured keyring dictionary.
33
- - `setActiveKid(kid: string): void`: Sets the active key identifier used for all outbound encryption.
34
- - `getActiveKid(): string | undefined`: Returns the currently active outbound key identifier.
35
- - `isEncrypted(payload: any): boolean`: Polymorphic check if given object is an encrypted envelope. Also available as static `AEncryptionProvider.isEncrypted(payload)`.
36
- - `clearKeys() / dispose()`: Wipes in-memory key caches, zeroes mutable Buffer bytes and keyring caches, and clears sensitive asymmetric keys upon logout/session end.
37
- - `resolveRawKey(keyProvider?: TKeyProvider)`: (Protected on `AEncryptionProvider`) Resolves key or async keyProvider callback. Supports `string`, `Uint8Array`, `ArrayBuffer`, and `CryptoKey` without byte corruption.
38
- - **PEM Import/Export (`CKeyManager` / `CRSA` / `CECDH`)**:
39
- - `importPublicKeyFromPEM(pem, algorithm?, curve?, hash?)`: Imports SPKI PEM string to `CryptoKey` (`RSA-OAEP`, `ECDH`, or `ECDSA`).
40
- - `importPrivateKeyFromPEM(pem, algorithm?, curve?, hash?)`: Imports PKCS#8 PEM string to `CryptoKey` (`RSA-OAEP`, `ECDH`, or `ECDSA`).
41
- - `importECDSAPublicKeyFromPEM(pem, curve?): Promise<CryptoKey>`: Imports an ECDSA public key from PEM SPKI for signature verification.
42
- - `importECDSAPrivateKeyFromPEM(pem, curve?): Promise<CryptoKey>`: Imports an ECDSA private key from PEM PKCS#8 for signing.
43
- - `exportPublicKeyToPEM(key)`: Exports `CryptoKey` to standard SPKI PEM string.
44
- - `exportPrivateKeyToPEM(key)`: Exports `CryptoKey` to standard PKCS#8 PEM string.
45
- - **Account & HMAC Key Wrapping (`CKeyManager`)**:
46
- - `wrapAccountKeyForUser(adek, userPublicKey): Promise<string>`: Wraps an ADEK for a user using RSA-OAEP.
47
- - `unwrapAccountKeyForUser(wrappedKeyBase64, userPrivateKey, unwrappedKeyAlgorithm?, extractable?): Promise<CryptoKey>`: Restores an unextractable AES-GCM ADEK from envelope using RSA-OAEP.
48
- - `wrapHMACKeyForUser(hmacKey, userPublicKey): Promise<string>`: Wraps an HMAC blind indexing key for a user using RSA-OAEP.
49
- - `unwrapHMACKeyForUser(wrappedKeyBase64, userPrivateKey, hash?, extractable?): Promise<CryptoKey>`: Restores an HMAC search key using recipient RSA-OAEP private key.
50
- - `rewrapAccountKeyForUser(wrappedKeyBase64, myPrivateKey, recipientPublicKey): Promise<string>`: Atomically re-wraps an ADEK envelope for a new recipient without exposing raw extractable keys to application memory, guaranteeing memory zeroization via `finally`.
51
- - **Blind Index & Token Utilities (`CKeyManager` / `CSearchIndex`)**:
52
- - `CKeyManager.computeBlindIndex(value, hmacKey): Promise<string>`: Computes deterministic HMAC-SHA256 blind index hash for arbitrary values.
53
- - `searchIndex.computeBlindIndex(term): Promise<string>`: Computes blind index using configured search HMAC key.
54
- - `searchIndex.indexRowDecrypted(row, decryptedPlaintext): Promise<void>`: Indexes a row using pre-decrypted plaintext fields while preserving raw ciphertext in data tables.
55
- - **Digital Signatures & Access Grants (`CKeyManager` / `canonicalizeJson`)**:
56
- - `canonicalizeJson(value): string`: Serializes a JavaScript value to a deterministic, canonical JSON string conforming to RFC 8785 (JCS).
57
- - `generateSigningKeyPair(curve?, extractable?): Promise<IKeyPair>` / `generateECDSAKeyPair()`: Generates an ECDSA signing key pair (`P-256`, `P-384`, `P-521`).
58
- - `getKeyFingerprint(publicKey): Promise<string>`: Generates a deterministic SHA-256 fingerprint for a public key formatted as `SHA256:<base64url>`.
59
- - `sign(data, privateKey): Promise<string>`: Signs arbitrary data or JSON objects using an ECDSA P-256 private key (objects automatically canonicalized via RFC 8785).
60
- - `verify(data, signature, publicKey): Promise<boolean>`: Verifies an ECDSA P-256 signature against original data or JSON object.
61
- - `signGrant(grant: IAccessGrant, granterPrivateKey, granterPublicKey?): Promise<ISignedGrant>`: Signs a structured access grant, embedding signature and granter key fingerprint.
62
- - `verifyGrant(signedGrant: ISignedGrant, granterPublicKey, options?): Promise<boolean>`: Verifies authenticity, integrity, and granter key fingerprint of an access grant, defeating key-substitution attacks.
63
- - **Domain-Separated Key Derivation (`CKeyManager.deriveAuthAndEncryptionKeys`)**:
64
- - `deriveAuthAndEncryptionKeys(password, salt?, options?): Promise<IDomainDerivedKeys>`: Hardened two-stage derivation pipeline. PBKDF2 stretches low-entropy user password and salt, then HKDF-Expand produces two cryptographically isolated keys (`authKey` for authentication challenges and `encryptionKey` for AES-GCM data encryption) using domain-separated context tags (`katlux-auth-key-v1` and `katlux-encryption-key-v1`). Full compromise of `authKey` reveals zero mathematical information about `encryptionKey`. Intermediate master secret buffers are immediately zeroized in memory.
65
-
66
-
67
-
68
- - **Envelope Contract (`IEncryptedPayload`)**:
69
- ```ts
70
- interface IEncryptedPayload {
71
- __encrypted: true
72
- ciphertext: string // Base64 ciphertext (always present)
73
- alg: string // 'AES-GCM' | 'AES-CBC-256+HMAC-SHA-256' | 'RSA-OAEP-4096+AES-GCM-256' | 'ECDH-P-256+AES-GCM-256'
74
- kid?: string // Key identifier / version for key rotation tracking
75
- iv?: string // Base64 IV
76
- salt?: string // Base64 KDF salt
77
- kdf?: string // 'PBKDF2' | 'HKDF'
78
- iter?: number // PBKDF2 iteration count (default: 310,000, clamped [1,000, 600,000])
79
- tag?: string // Explicit HMAC tag (AES-CBC)
80
- wrappedKey?: string // Base64 RSA-wrapped AES key (RSA hybrid)
81
- sharedKey?: boolean // Shared DEK marker for field-level encryption
82
- epk?: JsonWebKey // Ephemeral public key (ECDH)
83
- }
84
- ```
85
-
86
- - **`IProviderEncryptionOptions`**:
87
- ```ts
88
- interface IProviderEncryptionOptions {
89
- enabled?: boolean // Master toggle (default: false)
90
- key?: TKeyProvider // Single key or key provider (legacy/simple mode)
91
- keys?: Record<string, TKeyProvider | IKeyPair> // Built-in Keyring dictionary mapping kid to keys
92
- activeKid?: string // Active key identifier from keys to use for outbound encryption
93
- kid?: string // Key identifier / version (e.g. 'v1', 'tenant-a-key-2026')
94
- aad?: string | Uint8Array | ArrayBuffer | ((record: any, field: string) => string | Uint8Array | ArrayBuffer) // AEAD Additional Data or dynamic callback
95
- aadFields?: string[] // Sibling record fields to deterministically bind into AAD (e.g. ['contact_id', 'version'])
96
- baseAad?: string // Optional base prefix for AAD context binding
97
- decryptOnSSR?: boolean // default: false. Prevents SSR decryption unless explicitly enabled with server secrets
98
- fields?: string[] // Field-level encryption: only encrypt listed fields
99
- strict?: boolean // Enforces strict decryption: unencrypted plaintext in `fields` triggers injection violation; defaults allowedAlgorithms to ['AES-GCM']
100
- allowedAlgorithms?: string[] // Whitelist of permitted cipher algorithms (e.g. ['AES-GCM'])
101
- allowedKids?: string[] // Whitelist of permitted Key Identifiers (kid); defaults to Object.keys(keys)
102
- onDecryptError?: ((info: IDecryptErrorInfo) => any) | boolean | string // Per-field error hook, safe fallback marker, or true for '[⚠ Decryption Error]'
103
- searchIndex?: boolean // Enables HMAC-SHA256 blind index and trigram search index on encrypted fields
104
- preEncrypted?: boolean // Set to true if API endpoints return pre-encrypted ciphertext envelopes; enables in-memory index decryption
105
- hmacKey?: TKeyProvider // Optional dedicated HMAC key for search indexing (defaults to encryption key)
106
- algorithm?: 'AES-GCM' | string // default: 'AES-GCM'
107
- customProvider?: IEncryptionProvider // Custom cipher adapter (e.g. CRSA, CECDH, AES-CBC)
108
- kdf?: 'none' | 'pbkdf2' | 'hkdf' // Key derivation strategy:
109
- // - 'pbkdf2': Recommended for human passphrases/passwords (OWASP recommended rounds)
110
- // - 'hkdf': For high-entropy IKM / subkey derivation (warns if used with string passwords)
111
- // - 'none': When supplying pre-derived 256-bit raw keys, Buffers, or CryptoKeys
112
- kdfIterations?: number // PBKDF2 rounds (default: 310,000 per OWASP, clamped [1,000, 600,000])
113
- kdfHash?: 'SHA-256' | 'SHA-512' // KDF hash algorithm
114
- kdfSalt?: string | Uint8Array | ArrayBuffer // Optional static salt (random salt in envelope if omitted)
115
- publicKey?: CryptoKey // Optional public key for asymmetric encryption
116
- privateKey?: CryptoKey // Optional private key for asymmetric decryption
117
- recipientPublicKey?: CryptoKey // Recipient public key for hybrid encryption
118
- recipientPrivateKey?: CryptoKey // Recipient private key for hybrid decryption
119
- curve?: 'P-256' | 'P-384' | 'P-521' // Curve for ECDH providers
120
- info?: string // Optional context/info string for HKDF
121
- }
122
- ```
123
-
124
- - **Factory & Provider Creation**:
125
- - `createEncryptionProvider(options: IProviderEncryptionOptions): IEncryptionProvider`: Unified factory that instantiates and configures the appropriate cipher provider based on `options.algorithm` (`'AES-GCM'`, `'AES-CBC'`, `'RSA-OAEP'`, `'ECDH'`) or returns `options.customProvider`. Supports `IKeyPair` or individual keys, HKDF info, curve configuration, and KDF options.
126
-
127
- - **Usage in DataProvider (Client & Server)**:
128
- Supported uniformly across **all** client and server data providers:
129
- - **Local (Non-API)**: `CFlatClientDataProvider`, `CTreeClientDataProvider` (via `AEncryptedClientProvider`)
130
- - **API Client-Side**: `CAPIFlatClientDataProvider`, `CAPITreeClientDataProvider`
131
- - **Server-Side**: `CAPIFlatServerDataProvider`, `CAPITreeServerDataProvider`
132
-
133
- #### Local DataProvider Encryption Architecture
134
- - **Eager Encryption**: `setData(rows)` encrypts designated `fields` immediately before storing in `allData`. Plaintext never persists in `allData`.
135
- - **Pre-Encrypted Ingest & Search**: When datasets arrive already encrypted (`preEncrypted: true`), data providers (`CFlatClientDataProvider`, `CAPIFlatClientDataProvider`) perform a transient in-memory decryption pass on indexed fields to populate `CSearchIndex` without modifying or leaking the persistent ciphertext rows in `allData`.
136
- - **Non-blocking Ingestion**: `setDataChunked(rows, { chunkSize: 250, yieldStrategy: 'idle' })` yields between chunks to prevent main-thread freezing on large datasets.
137
- - **Idempotent Ingestion**: Pre-encrypted envelopes (`__encrypted: true`, e.g. from IndexedDB or Web Workers) pass through untouched without double-encryption.
138
- - **Lazy Page-Level Decryption**: `loadPageData()` slices `allData` and decrypts only the active page (`pageSize` rows) into `pageData`. Only visible rows are plaintext in memory.
139
- - **Blind Index Search (`CSearchIndex`)**: When `searchIndex: true`, exact match (`==`, `!=`) and substring search (`in`) operate directly on encrypted fields via deterministic HMAC-SHA256 blind tokens and trigram sets without full dataset decryption.
140
- - **Zero-Cost Path**: When `enabled` is false, `setData` runs 100% synchronously with zero microtask overhead.
141
-
142
- ```ts
143
- import { CFlatClientDataProvider } from '@katlux/providers'
144
-
145
- const customerProvider = new CFlatClientDataProvider({
146
- pageSize: 20,
147
- encryption: {
148
- enabled: true,
149
- key: 'secret-key-32-chars-long-12345!',
150
- kid: 'tenant-key-v1',
151
- fields: ['ssn', 'salary', 'creditCard'],
152
- searchIndex: true // Enables search/filter on encrypted fields via CSearchIndex
153
- }
154
- })
155
-
156
- // Eagerly encrypts sensitive fields; leaves id, role, department in plaintext
157
- await customerProvider.setData(rawEmployees)
158
-
159
- // Large dataset ingestion with progress reporting:
160
- await customerProvider.setDataChunked(largeEmployees, {
161
- chunkSize: 500,
162
- onProgress: (p) => console.log(`Encryption progress: ${(p * 100).toFixed(0)}%`)
163
- })
164
-
165
- // Dynamically rotate key:
166
- customerProvider.setEncryption({ enabled: true, key: newKey, kid: 'tenant-key-v2', fields: ['ssn', 'salary'] })
167
-
168
- // Upon user logout / session termination:
169
- customerProvider.clearEncryption() // Clears keys, zeroes memory, and disables encryption
170
- ```
171
-
172
- - **Usage with RequestProvider**:
173
- ```ts
174
- const rp = new RequestProvider()
175
- rp.setEncryption({ enabled: true, key: 'my-secret-32-char-key!!!', kid: 'tenant-key-2026' })
176
- // Outbound POST/PUT/PATCH bodies encrypted; encrypted responses auto-decrypted
177
-
178
- // Upon user logout:
179
- rp.clearEncryption() // Safely clears cached cipher instance, scoped WeakMap instances, and zeroes keys
180
- ```
181
-
182
- #### Authenticated Additional Data (AAD) & Security Guarantees
183
- In multi-tenant, field-encrypted, and SSR scenarios, Katlux cryptographic providers enforce strict, integration-tested security guarantees:
184
- - **Field & Record Binding**: During value-level and field-level encryption, `AEncryptionProvider` and `CNodeCryptoEncryptionProvider` automatically bind:
185
- `aad:${baseAad}|record:${recordId}|field:${fieldName}`
186
- Where `recordId` is extracted from `record.id`, `record._id`, or `options.recordId`.
187
- - **Transposition Tamper Resistance**: Moving or swapping an encrypted envelope from one database row to another, or from one column (`ssn`) to another (`phone`), causes AES-GCM tag verification to immediately fail with an authentication error.
188
- - **Cache-at-Rest Full Envelope**: When caching responses where field-level encryption is active (`fields: [...]`), `RequestProvider` automatically wraps the entire object in a full envelope at rest. Neither targeted sensitive fields nor unlisted metadata fields appear as plaintext in raw storage across any client or server cache adapter.
189
- - **Node GCM 16-Byte Tag Enforcement**: `CNodeCryptoEncryptionProvider` strictly validates a 16-byte (128-bit) authentication tag across all synchronous and asynchronous decryption paths (rejecting truncated 12, 8, or 4-byte tags).
190
- - **Nonce Misuse Resistance**: Initialization Vectors (IVs) are freshly generated via cryptographically secure RNG per operation (12 bytes for GCM, 16 bytes for CBC) with proven uniqueness across sibling fields, batch arrays, and concurrent executions.
191
- - **Deterministic Search Token Segregation**: `CSearchIndex` HMAC-SHA256 blind index tokens are deterministic for search matching and strictly segregated from non-deterministic ciphertext IVs.
192
- - **Non-Extractable Tenant Keys**: `CKeyManager.generateAccountDataKey()` and `CKeyManager.unwrapAccountKeyForUser()` produce `CryptoKey` instances with `extractable: false` by default, safeguarding unwrapped symmetric tenant keys against exfiltration via developer tools or malicious extensions.
193
- - **Atomic Key Re-Wrapping (`CKeyManager.rewrapAccountKeyForUser`)**: When sharing an Account Data Encryption Key (ADEK) between users, `CKeyManager.rewrapAccountKeyForUser(wrappedKey, myPrivateKey, recipientPublicKey)` atomically decrypts the raw key material and re-encrypts it with the recipient's RSA-OAEP public key without ever exposing the raw extractable symmetric key to caller application memory or leaving extractable CryptoKeys in memory. Immediate memory zeroization (`fill(0)`) is guaranteed across all paths.
194
- - **SSR Confidentiality & Cache Auth Guard**: With `decryptOnSSR: false` (the secure zero-trust default), plaintext is never exposed in server memory or serialized HTML hydration payloads. Requests with `cookie` or `Authorization` headers automatically bypass shared server caches (`CApplicationCache`), preventing cross-user session cache poisoning.
195
-
196
- #### Built-in Keyring & Multi-Key Rotation Architecture
197
- - **Zero-Downtime Key Rotation**: Configuring `keys: { 'k2025': key1, 'k2026': key2 }` alongside `activeKid: 'k2026'` ensures all outbound writes are automatically tagged with `kid: 'k2026'` and encrypted with `key2`, while legacy records tagged with `k2025` decrypt seamlessly under `key1`.
198
- - **Automatic Whitelisting & Untrusted `kid` Protection**: `allowedKids` automatically defaults to `Object.keys(keys)` when `keys` is provided. Incoming envelopes carrying an unknown or unregistered `kid` are immediately rejected with an unauthorized key security error (`Unauthorized key: kid '${payload.kid}' is not in allowedKids.`).
199
- - **Concurrent Multi-Key Warmup**: Calling `warmupKey()` (or `warmupKeySync()` on Node) resolves and primes all cryptographic keys across the entire keyring concurrently using `Promise.all`, preventing runtime latency spikes or race conditions during rotation periods.
200
- - **Dynamic Runtime Keyring Management**: Keyrings can be rotated dynamically at runtime using `provider.setKeyring(newKeys, newActiveKid)` or `provider.setActiveKid(newKid)` without recreating provider instances or dropping existing session caches.
201
-
202
- #### Backend Persistence & Datatable Encrypted Search Architecture
203
- To enable fast exact-match and substring search across AES-256-GCM encrypted records in persisted storage and server-side datatables without decrypting rows or leaking plaintext to the persistence server:
204
-
205
- 1. **Schema Column Mapping**:
206
- - **Ciphertext (`JSONB` or `TEXT`)**: Holds the complete Katlux envelope `{ __encrypted: true, ciphertext, iv, tag, v: 1 }`.
207
- - **Blind Index (`CHAR(64)`)**: Deterministic HMAC-SHA256 hash of normalized plaintext, indexed with a **B-Tree** for $O(\log N)$ point lookups (`=` / `IN`).
208
- - **Trigram Array (`TEXT[]` or `BIGINT[]`)**: Set of hashed 3-character slices, indexed with an **inverted index (e.g. GIN / array index)** for substring queries.
209
-
210
- ```sql
211
- CREATE TABLE contacts (
212
- id SERIAL PRIMARY KEY,
213
- name_encrypted JSONB NOT NULL,
214
- email_encrypted JSONB NOT NULL,
215
- salary_encrypted JSONB,
216
- name_bidx CHAR(64) NOT NULL,
217
- email_bidx CHAR(64) NOT NULL,
218
- name_trigrams TEXT[] NOT NULL,
219
- email_trigrams TEXT[] NOT NULL,
220
- role VARCHAR(100),
221
- department VARCHAR(100),
222
- status VARCHAR(50) DEFAULT 'Active'
223
- );
224
-
225
- -- B-Tree for exact lookups:
226
- CREATE INDEX idx_contacts_name_bidx ON contacts (name_bidx);
227
- CREATE INDEX idx_contacts_email_bidx ON contacts (email_bidx);
228
-
229
- -- Inverted index for fast array containment substring search:
230
- CREATE INDEX idx_contacts_name_trigrams ON contacts USING GIN (name_trigrams);
231
- CREATE INDEX idx_contacts_email_trigrams ON contacts USING GIN (email_trigrams);
232
- ```
233
-
234
- 2. **Ingestion Pipeline**:
235
- - Normalize plaintext (`NFKC` + lowercase).
236
- - Generate exact blind index token via `CKeyManager.computeBlindIndex(plain, hmacKey)` or `searchIndex.computeToken(plain)`.
237
- - Extract 3-character slices via `extractTrigrams(plain)` and hash each trigram with `searchIndex.computeTrigramTokens(plain)`.
238
- - Encrypt sensitive columns with `cipher.encryptField(plain, { recordId: id, fieldName: 'name' })`.
239
- - Persist encrypted envelopes and token arrays into the persistence datatable storage.
240
-
241
- 3. **Query Execution**:
242
- - **Exact Match (`name = $1`)**:
243
- ```sql
244
- -- Compute HMAC token in API, then point-lookup using B-Tree:
245
- SELECT id, name_encrypted, email_encrypted, role FROM contacts WHERE name_bidx = $1;
246
- ```
247
- - **Substring Search (`name CONTAINS $1`)**:
248
- ```sql
249
- -- Extract & hash search query trigrams, then query via array containment operator (@>):
250
- SELECT id, name_encrypted, email_encrypted, role
251
- FROM contacts
252
- WHERE name_trigrams @> $1::text[]
253
- ORDER BY id ASC
254
- LIMIT 10 OFFSET 0;
255
- ```
256
- - **Compound Filtering**:
257
- Combine plain columns with encrypted token clauses:
258
- ```sql
259
- WHERE name_trigrams @> $1::text[] AND department = 'Security'
260
- ```
261
-
262
- 4. **Security & Production Best Practices**:
263
- - **Strict Key Isolation**: Isolate `DATA_ENCRYPTION_KEY` (AES-256-GCM) from `BLIND_INDEX_HMAC_KEY`. Persistence storage compromise cannot decrypt plaintext; cipher key exposure cannot reverse blind indices.
264
- - **Short Queries (< 3 chars)**: Substring search requires at least 3 characters to form a valid trigram. Enforce a 3-character minimum in client UI.
265
- - **Low-Cardinality Isolation**: Never blind index low-cardinality fields (boolean flags, binary status) to avoid frequency analysis leakage.
266
- - **Client Decryption Pipeline**: API responses return encrypted envelopes (`__encrypted: true`). Frontend `CAPIFlatServerDataProvider` decrypts only the received page slice via `decryptPageRows()` on arrival.
267
-
1
+ # Katlux Cryptographic Architecture & Encryption Suite (`@katlux/providers`) Master Index
2
+
3
+ > **Atomic Architecture**: To minimize prompt context and token consumption, the Katlux encryption architecture is split into 7 focused atomic specifications. Read **only** the atomic document required for your task.
4
+
5
+ ---
6
+
7
+ ## 1. Atomic Encryption Specifications
8
+
9
+ | Document | Topic & Focus | Core Classes & Primitives | Document Link |
10
+ | :--- | :--- | :--- | :--- |
11
+ | **Threat Model & Contracts** | E2EE architecture, boundary rules, non-goals, envelope schema, provider options | `IEncryptedPayload`, `IProviderEncryptionOptions`, `createEncryptionProvider`, `isEncrypted` | [encryption-threat-model.md](encryption-threat-model.md) |
12
+ | **Symmetric Ciphers** | AES-GCM-256, authenticated AES-CBC, Node sync cipher, keyring rotation, strict decryption, dynamic AAD | `CWebCryptoEncryptionProvider`, `CWebCryptoAESCBCProvider`, `CNodeCryptoEncryptionProvider` | [encryption-symmetric.md](encryption-symmetric.md) |
13
+ | **Asymmetric Hybrid Ciphers** | RSA-OAEP-4096 and ECDH ephemeral hybrid encryption, SPKI/PKCS#8 PEM import/export | `CRSAEncryptionProvider`, `CECDHEncryptionProvider`, `importPublicKeyFromPEM` | [encryption-asymmetric.md](encryption-asymmetric.md) |
14
+ | **Key Lifecycle & Derivation** | Tenant key generation, ADEK wrapping/rewrapping, RFC 8785 canonical JSON access grants, domain-separated KDF, master passphrase re-keying | `CKeyManager`, `canonicalizeJson`, `deriveAuthAndEncryptionKeys`, `rekeyUserKeypair` | [encryption-key-management.md](encryption-key-management.md) |
15
+ | **Key Pinning (TOFU) & Attestations** | Trust-On-First-Use key store, signed key-reset attestation protocol, 6 strict verification rules, memory/storage adapters | `IKeyPinningStore`, `CMemoryKeyPinningStore`, `CLocalStorageKeyPinningStore`, `CIndexedDBKeyPinningStore`, `verifyAndPinKey`, `signKeyResetAttestation` | [encryption-key-pinning.md](encryption-key-pinning.md) |
16
+ | **Web Streams Chunked AEAD** | Constant-memory chunked streaming cipher, 16-byte header framing protocol, blob helpers, Node stream interoperability | `CWebCryptoStreamCipher`, `createEncryptionStream`, `createDecryptionStream`, `encryptBlob`, `decryptBlob` | [encryption-streaming.md](encryption-streaming.md) |
17
+ | **Field Encryption & Ingestion** | Row scalar encryption, eager client ingestion, pre-encrypted datasets, blind indexing, trigram substring queries, SQL schema | `encryptField`, `decryptField`, `AEncryptedClientProvider`, `CSearchIndex`, `computeBlindIndex` | [encryption-field-level.md](encryption-field-level.md) |
18
+
19
+ ---
20
+
21
+ ## 2. Decision Matrix: Which Cryptographic Tool to Use?
22
+
23
+ | Requirement / Scenario | Recommended Solution | Documentation |
24
+ | :--- | :--- | :--- |
25
+ | Encrypting database rows or API payloads in browser/server | `CWebCryptoEncryptionProvider` (AES-GCM-256) | [encryption-symmetric.md](encryption-symmetric.md) |
26
+ | Fast synchronous encryption in high-throughput Node.js server routes | `CNodeCryptoEncryptionProvider.encryptSync` | [encryption-symmetric.md](encryption-symmetric.md) |
27
+ | Encrypting large files, media, or archives (> 5 MB) without memory bloat | `createEncryptionStream` / `encryptBlob` | [encryption-streaming.md](encryption-streaming.md) |
28
+ | Sharing tenant symmetric keys with specific users | `CKeyManager.wrapAccountKeyForUser` (RSA-OAEP) | [encryption-key-management.md](encryption-key-management.md) |
29
+ | Re-wrapping keys between users without exposing raw bytes | `CKeyManager.rewrapAccountKeyForUser` | [encryption-key-management.md](encryption-key-management.md) |
30
+ | Forward-secure ephemeral key exchange | `CECDHEncryptionProvider` | [encryption-asymmetric.md](encryption-asymmetric.md) |
31
+ | User password change without re-encrypting database payloads | `CKeyManager.rekeyUserKeypair` | [encryption-key-management.md](encryption-key-management.md) |
32
+ | Preventing rogue-admin public key substitution on peers | `CKeyManager.verifyAndPinKey` (TOFU store) | [encryption-key-pinning.md](encryption-key-pinning.md) |
33
+ | Encrypting sensitive columns while leaving IDs plaintext for sorting | `encryptField` / `AEncryptedClientProvider` | [encryption-field-level.md](encryption-field-level.md) |
34
+ | Exact-match lookups or substring search on encrypted database fields | `CSearchIndex` (HMAC-SHA256 blind indices & trigrams) | [encryption-field-level.md](encryption-field-level.md) |
35
+
36
+ ---
37
+
38
+ ## 3. Showcase Live Reference Pages
39
+
40
+ - **Overview & SSR**: `/providers/request/encryption`
41
+ - **Symmetric**: `/providers/classes/CWebCryptoEncryptionProvider` · `/providers/classes/CWebCryptoAESCBCProvider` · `/providers/classes/CNodeCryptoEncryptionProvider`
42
+ - **Asymmetric / Hybrid**: `/providers/classes/CRSAEncryptionProvider` · `/providers/classes/CECDHEncryptionProvider`
43
+ - **Key Management**: `/providers/classes/CKeyManager`
44
+ - **Base & Contracts**: `/providers/classes/AEncryptionProvider` · `/providers/interfaces/IEncryptionProvider` · `/providers/interfaces/IProviderEncryptionOptions`
@@ -3,19 +3,19 @@
3
3
  | Interface / Enum | Purpose | Key Properties / Values |
4
4
  | --- | --- | --- |
5
5
  | `EDataFilterOperator` | Available filter operators | `Equal` (`==`), `NotEqual` (`!=`), `GreaterThan` (`>`), `LessThan` (`<`), `GreaterThanOrEqual` (`>=`), `LessThanOrEqual` (`<=`), `In`, `NotIn`, `And`, `Or`, `Nand`, `Nor` |
6
- | `IDataFilter` | Structured filter query | `{ operator: EDataFilterOperator, field: string \| IDataFilter[], active: boolean }` |
6
+ | `IDataFilter` | Structured filter query | `{ operator: EDataFilterOperator, field: string \| TDataRow \| IDataFilter \| IDataFilter[], active: boolean }` |
7
7
  | `IDataSort` | Sorting configuration | `{ field: string, direction: 'asc' \| 'desc' }` |
8
- | `IDataResult` | Standardized API response | `{ rowCount: number, rows: any[] }` |
8
+ | `IDataResult` | Standardized API response | `{ rowCount: number, rows: T[] }` |
9
9
  | `ECacheStrategy` | Caching persistence tiers | `Memory`, `ServerSession`, `BrowserSession`, `LocalStorage`, `IndexedDB`, `Cookie`, `Application` |
10
10
  | `IDataProviderOptions` | Constructor configuration | See table in §3.2 |
11
11
  | `IKDatatableAction` | Row/Bulk action config | `{ label: string, action: Function, icon?: string, iconOnly?: boolean, type?: string, visible?: Function }` |
12
- | `ITreeNode` | Tree node wrapper | `{ data: any, id: any, parentId: any, depth: number, hasChildren: boolean, isExpanded: boolean }` |
13
- | `ICompositeItem`| Composite input pair | `{ selection: any, value: any }` (e.g. `{ selection: 'en', value: 'Hello' }`) |
12
+ | `ITreeNode` | Tree node wrapper | `{ data: Record<string, unknown>, id: string \| number, parentId: string \| number \| null, depth: number, hasChildren: boolean, isExpanded: boolean }` |
13
+ | `ICompositeItem`| Composite input pair | `{ selection: string \| number \| null, value: unknown }` (e.g. `{ selection: 'en', value: 'Hello' }`) |
14
14
 
15
15
  ### Standard Data Structure (`IDataResult`)
16
16
  All Katlux DataProviders (and components consuming them, such as `KDatatable`, `KLineChart`, `KBarChart`, `KPieChart`, `KCombobox`, etc.) use `IDataResult` as the standard payload format:
17
17
  ```typescript
18
- interface IDataResult<T = any> {
18
+ interface IDataResult<T = unknown> {
19
19
  rowCount: number // Total record count (for pagination math)
20
20
  rows: T[] // Array of row item objects
21
21
  }
@@ -21,7 +21,7 @@ const {
21
21
  virtualRows, // ShallowRef<T[]> (full ordered array of visible rows for virtual scroll)
22
22
  rowCount, // Ref<number>
23
23
  loading, // Ref<boolean>
24
- error, // Ref<any>
24
+ error, // Ref<Error | unknown>
25
25
  currentPage, // Ref<number> (synced with Pinia)
26
26
  pageSize, // Ref<number> (synced with Pinia)
27
27
  filter, // Ref<IDataFilter | null> (synced with Pinia)