@katlux/toolkit 0.1.1-alpha.144 → 0.1.1-alpha.146
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/bin/ai-init.mjs +517 -0
- package/bin/ai-tokens.mjs +1043 -0
- package/bin/cli.mjs +80 -43
- package/bin/create-preset.mjs +1 -0
- package/bin/preset-contracts.json +2941 -0
- package/dist/compiled/composables/locales.mjs +204 -25
- package/dist/compiled/composables/useDataProvider.mjs +36 -25
- package/dist/compiled/composables/useFilterLogic.mjs +10 -2
- package/dist/compiled/composables/useKatluxForm.mjs +6 -4
- package/dist/compiled/composables/useVirtualDataset.mjs +689 -0
- package/dist/compiled/composables/useVirtualScroll.mjs +29 -9
- package/dist/module.cjs +63 -77
- package/dist/module.d.cts +5 -0
- package/dist/module.d.mts +4 -1
- package/dist/module.json +1 -1
- package/dist/module.mjs +60 -78
- package/dist/runtime/components/KAccordion/KAccordion.global.d.vue.ts +2 -2
- package/dist/runtime/components/KAccordion/KAccordion.global.vue.d.ts +2 -2
- package/dist/runtime/components/KAlert/KAlert.global.d.vue.ts +1 -1
- package/dist/runtime/components/KAlert/KAlert.global.vue.d.ts +1 -1
- package/dist/runtime/components/KBulkActions/KBulkActions.global.d.vue.ts +7 -3
- package/dist/runtime/components/KBulkActions/KBulkActions.global.vue +4 -1
- package/dist/runtime/components/KBulkActions/KBulkActions.global.vue.d.ts +7 -3
- package/dist/runtime/components/KBulkActions/KBulkActions.logic.d.ts +4 -2
- package/dist/runtime/components/KBulkActions/KBulkActions.logic.js +70 -37
- package/dist/runtime/components/KButton/KButton.global.d.vue.ts +2 -2
- package/dist/runtime/components/KButton/KButton.global.vue.d.ts +2 -2
- package/dist/runtime/components/KButton/KButton.logic.d.ts +1 -1
- package/dist/runtime/components/KCalendar/KCalendar.global.d.vue.ts +19 -10
- package/dist/runtime/components/KCalendar/KCalendar.global.vue +7 -2
- package/dist/runtime/components/KCalendar/KCalendar.global.vue.d.ts +19 -10
- package/dist/runtime/components/KCalendar/KCalendar.logic.d.ts +14 -201
- package/dist/runtime/components/KCalendar/KCalendar.logic.js +60 -11
- package/dist/runtime/components/KCalendar/KCalendarMonth.global.d.vue.ts +25 -5
- package/dist/runtime/components/KCalendar/KCalendarMonth.global.vue +11 -1
- package/dist/runtime/components/KCalendar/KCalendarMonth.global.vue.d.ts +25 -5
- package/dist/runtime/components/KCalendar/KCalendarMonth.logic.d.ts +19 -3
- package/dist/runtime/components/KCalendar/KCalendarMonth.logic.js +115 -1
- package/dist/runtime/components/KCheckbox/KCheckbox.global.d.vue.ts +2 -2
- package/dist/runtime/components/KCheckbox/KCheckbox.global.vue.d.ts +2 -2
- package/dist/runtime/components/KCombobox/KCombobox.global.d.vue.ts +9 -9
- package/dist/runtime/components/KCombobox/KCombobox.global.vue +1 -1
- package/dist/runtime/components/KCombobox/KCombobox.global.vue.d.ts +9 -9
- package/dist/runtime/components/KCombobox/KCombobox.logic.d.ts +7 -1
- package/dist/runtime/components/KCombobox/KCombobox.logic.js +1 -1
- package/dist/runtime/components/KCompositeInput/KCompositeInput.global.d.vue.ts +14 -14
- package/dist/runtime/components/KCompositeInput/KCompositeInput.global.vue.d.ts +14 -14
- package/dist/runtime/components/KCompositeInput/KCompositeInput.logic.d.ts +3 -3
- package/dist/runtime/components/KContextMenu/KContextMenu.logic.js +5 -0
- package/dist/runtime/components/KDatatable/KDataIterator.global.d.vue.ts +22 -18
- package/dist/runtime/components/KDatatable/KDataIterator.global.vue +23 -16
- package/dist/runtime/components/KDatatable/KDataIterator.global.vue.d.ts +22 -18
- package/dist/runtime/components/KDatatable/KDataIterator.logic.d.ts +13 -10
- package/dist/runtime/components/KDatatable/KDataIterator.logic.js +25 -20
- package/dist/runtime/components/KDatatable/KDatatable.global.d.vue.ts +9 -13
- package/dist/runtime/components/KDatatable/KDatatable.global.vue +6 -5
- package/dist/runtime/components/KDatatable/KDatatable.global.vue.d.ts +9 -13
- package/dist/runtime/components/KDatatable/KDatatable.logic.d.ts +4 -6
- package/dist/runtime/components/KDatatable/KDatatable.logic.js +26 -19
- package/dist/runtime/components/KDatePicker/KDatePicker.global.d.vue.ts +31 -15
- package/dist/runtime/components/KDatePicker/KDatePicker.global.vue +38 -13
- package/dist/runtime/components/KDatePicker/KDatePicker.global.vue.d.ts +31 -15
- package/dist/runtime/components/KDatePicker/KDatePicker.logic.d.ts +28 -6
- package/dist/runtime/components/KDatePicker/KDatePicker.logic.js +197 -53
- package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.d.vue.ts +3 -3
- package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.vue.d.ts +3 -3
- package/dist/runtime/components/KDateTimePicker/KDateTimePicker.logic.js +2 -0
- package/dist/runtime/components/KDropdown/KDropdown.global.d.vue.ts +1 -1
- package/dist/runtime/components/KDropdown/KDropdown.global.vue.d.ts +1 -1
- package/dist/runtime/components/KGantt/KGantt.global.d.vue.ts +55 -6
- package/dist/runtime/components/KGantt/KGantt.global.vue +12 -3
- package/dist/runtime/components/KGantt/KGantt.global.vue.d.ts +55 -6
- package/dist/runtime/components/KGantt/KGantt.logic.d.ts +33 -5
- package/dist/runtime/components/KGantt/KGantt.logic.js +39 -6
- package/dist/runtime/components/KHourPicker/KHourPicker.global.d.vue.ts +2 -2
- package/dist/runtime/components/KHourPicker/KHourPicker.global.vue.d.ts +2 -2
- package/dist/runtime/components/KHourSelect/KHourSelect.global.d.vue.ts +1 -1
- package/dist/runtime/components/KHourSelect/KHourSelect.global.vue.d.ts +1 -1
- package/dist/runtime/components/KLoader/KLoader.global.vue +2 -0
- package/dist/runtime/components/KMaskTextbox/KMaskTextbox.global.d.vue.ts +2 -2
- package/dist/runtime/components/KMaskTextbox/KMaskTextbox.global.vue.d.ts +2 -2
- package/dist/runtime/components/KMultiTabs/MultiTabs.global.d.vue.ts +23 -0
- package/dist/runtime/components/KMultiTabs/MultiTabs.global.vue +22 -0
- package/dist/runtime/components/KMultiTabs/MultiTabs.global.vue.d.ts +23 -0
- package/dist/runtime/components/KPagination/KPagination.global.d.vue.ts +4 -2
- package/dist/runtime/components/KPagination/KPagination.global.vue +2 -1
- package/dist/runtime/components/KPagination/KPagination.global.vue.d.ts +4 -2
- package/dist/runtime/components/KPagination/KPagination.logic.d.ts +1 -0
- package/dist/runtime/components/KPagination/KPagination.logic.js +57 -5
- package/dist/runtime/components/KRadiobox/KRadiobox.global.d.vue.ts +1 -1
- package/dist/runtime/components/KRadiobox/KRadiobox.global.vue.d.ts +1 -1
- package/dist/runtime/components/KRangeSlider/KRangeSlider.global.d.vue.ts +1 -1
- package/dist/runtime/components/KRangeSlider/KRangeSlider.global.vue.d.ts +1 -1
- package/dist/runtime/components/KSlider/KSlider.global.d.vue.ts +1 -1
- package/dist/runtime/components/KSlider/KSlider.global.vue.d.ts +1 -1
- package/dist/runtime/components/KTabs/KTabs.global.d.vue.ts +2 -2
- package/dist/runtime/components/KTabs/KTabs.global.vue.d.ts +2 -2
- package/dist/runtime/components/KTextarea/KTextarea.global.d.vue.ts +2 -2
- package/dist/runtime/components/KTextarea/KTextarea.global.vue.d.ts +2 -2
- package/dist/runtime/components/KTextbox/KTextbox.global.d.vue.ts +3 -3
- package/dist/runtime/components/KTextbox/KTextbox.global.vue.d.ts +3 -3
- package/dist/runtime/components/KToast/KToast.global.d.vue.ts +3 -3
- package/dist/runtime/components/KToast/KToast.global.vue.d.ts +3 -3
- package/dist/runtime/components/KTooltip/KTooltip.global.d.vue.ts +1 -1
- package/dist/runtime/components/KTooltip/KTooltip.global.vue.d.ts +1 -1
- package/dist/runtime/components/KTree/KTree.global.d.vue.ts +7 -7
- package/dist/runtime/components/KTree/KTree.global.vue.d.ts +7 -7
- package/dist/runtime/components/KTree/KTree.logic.d.ts +2 -2
- package/dist/runtime/components/KTree/KTree.logic.js +16 -12
- package/dist/runtime/components/KTreePicker/KTreePicker.global.d.vue.ts +7 -9
- package/dist/runtime/components/KTreePicker/KTreePicker.global.vue +1 -5
- package/dist/runtime/components/KTreePicker/KTreePicker.global.vue.d.ts +7 -9
- package/dist/runtime/components/KTreeView/KTreeView.global.d.vue.ts +39 -5
- package/dist/runtime/components/KTreeView/KTreeView.global.vue +19 -1
- package/dist/runtime/components/KTreeView/KTreeView.global.vue.d.ts +39 -5
- package/dist/runtime/components/KTreeView/KTreeView.logic.d.ts +23 -3
- package/dist/runtime/components/KTreeView/KTreeView.logic.js +76 -6
- package/dist/runtime/composables/locales.js +204 -25
- package/dist/runtime/composables/useDataProvider.d.ts +5 -3
- package/dist/runtime/composables/useDataProvider.js +36 -25
- package/dist/runtime/composables/useFilterLogic.d.ts +16 -4
- package/dist/runtime/composables/useFilterLogic.js +10 -2
- package/dist/runtime/composables/useKatluxForm.d.ts +4 -4
- package/dist/runtime/composables/useKatluxForm.js +6 -4
- package/dist/runtime/composables/useSortLogic.d.ts +1 -1
- package/dist/runtime/composables/useVirtualDataset.d.ts +121 -0
- package/dist/runtime/composables/useVirtualDataset.js +689 -0
- package/dist/runtime/composables/useVirtualScroll.d.ts +8 -4
- package/dist/runtime/composables/useVirtualScroll.js +29 -9
- package/dist/runtime/plugins/nuxtCompatPlugin.js +9 -1
- package/dist/runtime/presets/default/assets/scss/css-variables.css +3 -0
- package/dist/runtime/presets/default/assets/scss/css-variables.scss +6 -1
- package/dist/runtime/presets/default/assets/scss/index.css +3 -0
- package/dist/runtime/presets/default/assets/svg/katlux-logo.svg +7 -0
- package/dist/runtime/presets/default/assets/svg/katlux.svg +6 -0
- package/dist/runtime/presets/default/components/KBulkActions/KBulkActions.d.vue.ts +3 -2
- package/dist/runtime/presets/default/components/KBulkActions/KBulkActions.vue +31 -3
- package/dist/runtime/presets/default/components/KBulkActions/KBulkActions.vue.d.ts +3 -2
- package/dist/runtime/presets/default/components/KCalendar/KCalendar.d.vue.ts +3 -0
- package/dist/runtime/presets/default/components/KCalendar/KCalendar.vue +6 -0
- package/dist/runtime/presets/default/components/KCalendar/KCalendar.vue.d.ts +3 -0
- package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.d.vue.ts +5 -0
- package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.vue +33 -2
- package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.vue.d.ts +5 -0
- package/dist/runtime/presets/default/components/KCheckbox/KCheckbox.d.vue.ts +2 -2
- package/dist/runtime/presets/default/components/KCheckbox/KCheckbox.vue.d.ts +2 -2
- package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.vue +7 -1
- package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.d.vue.ts +30 -8
- package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.vue +80 -164
- package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.vue.d.ts +30 -8
- package/dist/runtime/presets/default/components/KDatatable/KDatatable.d.vue.ts +16 -9
- package/dist/runtime/presets/default/components/KDatatable/KDatatable.vue +99 -394
- package/dist/runtime/presets/default/components/KDatatable/KDatatable.vue.d.ts +16 -9
- package/dist/runtime/presets/default/components/KDatePicker/KDatePicker.d.vue.ts +6 -0
- package/dist/runtime/presets/default/components/KDatePicker/KDatePicker.vue +71 -4
- package/dist/runtime/presets/default/components/KDatePicker/KDatePicker.vue.d.ts +6 -0
- package/dist/runtime/presets/default/components/KGantt/KGantt.d.vue.ts +11 -12
- package/dist/runtime/presets/default/components/KGantt/KGantt.vue +77 -14
- package/dist/runtime/presets/default/components/KGantt/KGantt.vue.d.ts +11 -12
- package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.vue +1 -0
- package/dist/runtime/presets/default/components/KToast/KToast.d.vue.ts +2 -2
- package/dist/runtime/presets/default/components/KToast/KToast.vue.d.ts +2 -2
- package/dist/runtime/presets/default/components/KTree/KTree.d.vue.ts +4 -4
- package/dist/runtime/presets/default/components/KTree/KTree.vue +48 -14
- package/dist/runtime/presets/default/components/KTree/KTree.vue.d.ts +4 -4
- package/dist/runtime/presets/default/components/KTreeView/KTreeView.d.vue.ts +11 -2
- package/dist/runtime/presets/default/components/KTreeView/KTreeView.vue +14 -2
- package/dist/runtime/presets/default/components/KTreeView/KTreeView.vue.d.ts +11 -2
- package/dist/skills/KATLUX_INDEX.md +9 -6
- package/dist/skills/katlux-components/SKILL.md +2 -0
- package/dist/skills/katlux-components/components/KBulkActions.md +25 -1
- package/dist/skills/katlux-components/components/KCombobox.md +2 -2
- package/dist/skills/katlux-components/components/KDataIterator.md +12 -4
- package/dist/skills/katlux-components/components/KDatatable.md +38 -0
- package/dist/skills/katlux-components/components/KDatePicker.md +3 -1
- package/dist/skills/katlux-components/components/KGantt.md +9 -0
- package/dist/skills/katlux-components/components/KIcon.md +1 -1
- package/dist/skills/katlux-components/components/KLineChart.md +3 -0
- package/dist/skills/katlux-components/components/KProductList.md +0 -1
- package/dist/skills/katlux-components/components/KScatterChart.md +3 -0
- package/dist/skills/katlux-components/components/KTreePicker.md +2 -1
- package/dist/skills/katlux-components/components/KTreeView.md +12 -0
- package/dist/skills/katlux-config/SKILL.md +19 -8
- package/dist/skills/katlux-presets/SKILL.md +121 -1
- package/dist/skills/katlux-presets/creating-a-preset.md +67 -0
- package/dist/skills/katlux-providers/SKILL.md +7 -5
- package/dist/skills/katlux-providers/providers/ADataProvider.md +16 -9
- package/dist/skills/katlux-providers/providers/CAPIFlatClientDataProvider.md +27 -3
- package/dist/skills/katlux-providers/providers/CAPIFlatServerDataProvider.md +11 -1
- package/dist/skills/katlux-providers/providers/CFlatClientDataProvider.md +19 -4
- package/dist/skills/katlux-providers/providers/CFlatServerDataProvider.md +4 -2
- package/dist/skills/katlux-providers/providers/CTreeClientDataProvider.md +2 -2
- package/dist/skills/katlux-providers/providers/RequestProvider.md +10 -0
- package/dist/skills/katlux-providers/providers/encryption-field-level.md +63 -19
- package/dist/skills/katlux-providers/providers/encryption-key-management.md +20 -2
- package/dist/skills/katlux-providers/providers/encryption-key-pinning.md +25 -11
- package/dist/skills/katlux-providers/providers/encryption-searchable.md +218 -0
- package/dist/skills/katlux-providers/providers/encryption-symmetric.md +25 -1
- package/dist/skills/katlux-providers/providers/encryption-threat-model.md +63 -0
- package/dist/skills/katlux-providers/providers/encryption.md +26 -1
- package/dist/skills/katlux-providers/providers/types.md +3 -1
- package/dist/skills/katlux-providers/providers/useDataProvider.md +2 -1
- package/dist/skills/katlux-providers/providers/useVirtualDataset.md +154 -0
- package/dist/skills/katlux-tokens/SKILL.md +2 -1
- package/dist/types.d.mts +1 -1
- package/package.json +9 -3
- package/bin/add-ai-reference.mjs +0 -259
|
@@ -9,6 +9,17 @@
|
|
|
9
9
|
|
|
10
10
|
`CKeyManager` is a static cryptographic utility that manages key generation, tenant key wrapping, RFC 8785 canonical JSON serialization, ECDSA P-256 access grants, domain-separated key derivation, and master passphrase re-keying.
|
|
11
11
|
|
|
12
|
+
Under the hood, `CKeyManager` acts as a lightweight facade delegating to focused domain-specific submodules in `keyManager/`:
|
|
13
|
+
- `encodingUtils.ts`: `randomBytes`, `toBase64`, `fromBase64`, `resolveSalt`
|
|
14
|
+
- `symmetricKeys.ts`: `generateAESKey`, `exportAESKey`, `importAESKey`
|
|
15
|
+
- `asymmetricKeys.ts`: RSA/ECDH keypairs, JWK & PKCS#8/SPKI PEM import/export
|
|
16
|
+
- `keyWrapping.ts`: AES-KW, AES-GCM, RSA-OAEP wrap & ADEK/HMAC sharing
|
|
17
|
+
- `keyDerivation.ts`: PBKDF2 & HKDF-Expand pipelines, `deriveAuthAndEncryptionKeys`
|
|
18
|
+
- `keySignatures.ts`: ECDSA signing, fingerprints, blind index HMAC & grants
|
|
19
|
+
- `keyRekeying.ts`: Multi-user zero-knowledge keypair rekeying
|
|
20
|
+
- `keyPinning.ts`: TOFU key pinning & reset attestation protocol
|
|
21
|
+
- `blindIndexKeyring.ts`: Multi-KID blind index candidate resolution
|
|
22
|
+
|
|
12
23
|
---
|
|
13
24
|
|
|
14
25
|
## 2. Non-Extractable Tenant Keys & ADEK Wrapping
|
|
@@ -106,11 +117,12 @@ const dataKey = derived.encryptionKey
|
|
|
106
117
|
Zero-knowledge client-side user keypair re-keying pipeline that updates the user's master passphrase without changing their underlying RSA decryption or ECDSA signing keys.
|
|
107
118
|
|
|
108
119
|
```ts
|
|
120
|
+
// In production, passphrases must be obtained interactively from the user via secure password prompts
|
|
109
121
|
const result = await CKeyManager.rekeyUserKeypair({
|
|
110
122
|
encryptedPrivateKey: userEncryptedRsaKey,
|
|
111
123
|
encryptedSigningKey: userEncryptedEcdsaKey,
|
|
112
|
-
currentPassphrase:
|
|
113
|
-
newPassphrase:
|
|
124
|
+
currentPassphrase: userPromptCurrentPassword, // Prompted securely from user
|
|
125
|
+
newPassphrase: userPromptNewPassword, // Prompted securely from user
|
|
114
126
|
currentSalt: oldSaltBase64,
|
|
115
127
|
publicKeys: {
|
|
116
128
|
encryption: rsaPublicKey,
|
|
@@ -193,4 +205,10 @@ const summary = await reencryptDataset({
|
|
|
193
205
|
- **Blind Index Synchronization**: Simultaneously generates fresh blind index tokens using `computeWriteBlindIndex` from the active HMAC key and updates `<field>_bidx`.
|
|
194
206
|
- **Bounded Memory & Resumability**: Cursor pagination guarantees flat memory footprint even over millions of rows. Supports `AbortSignal` for graceful pause and resume from `lastProcessedCursor`.
|
|
195
207
|
- **Dry-Run Mode (`dryRun: true`)**: Validates key availability, decodes headers, and simulates re-encryption without invoking `updateRow`.
|
|
208
|
+
- **Resilient Error Strategies (`onRowError`)**: Configure `'abort'` (default), `'skip'`, or `'record'`. In `'skip'` and `'record'` modes, decryption failures on corrupted rows are collected into `failedRows: Array<{ id, field, error }>` without terminating batch processing.
|
|
209
|
+
- **Native Provider AAD Protocol Alignment**: Automatically reconstructs Katlux provider field envelopes (`aad:<base>|record:<id>|ctx:<fields>|field:<name>`) with lexicographically sorted `aadFields`, allowing migration without manual `buildAad` callback glue. Automatically retries with `aad: undefined` for legacy unbound envelopes.
|
|
210
|
+
- **Blind Index & Trigram Synchronization**: Simultaneously generates fresh blind index tokens (`computeWriteBlindIndex`) and trigram substring search token arrays (`trigramFields?: string[]`, `<field>_trigrams`) from the active HMAC key in `blindIndexKeyring`.
|
|
211
|
+
- **Standard PBKDF2 / HKDF Derivation for Passphrases**: When string passphrases are provided in the keyring, keys are derived using PBKDF2 (310,000 iterations with cryptographic salt) matching provider standards, and newly re-encrypted envelopes retain valid KDF metadata (`kdf: 'pbkdf2'`, `iter: 310000`, `salt`). Legacy unsalted envelopes (`kdf: 'none'`) are smoothly decrypted and upgraded.
|
|
212
|
+
- **KDF DoS & Iteration Guards**: Enforces `maxAllowedIterations` (default 350,000 ceiling) to prevent iteration amplification attacks from modified envelopes.
|
|
213
|
+
- **Flexible Salt Strategies**: Automatically shares salt across batches for high-throughput caching efficiency, or generates unique cryptographic salts per record when `perRowSalt: true` is configured.
|
|
196
214
|
|
|
@@ -39,9 +39,13 @@ export interface IKeyPinningStore {
|
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
### Available Adapters
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
42
|
+
All adapters implement `IKeyPinningStore` and are globally auto-imported by `@katlux/toolkit`. They can be instantiated directly or via the `CKeyPinningStore` namespace (`CKeyPinningStore.Memory`, `CKeyPinningStore.LocalStorage`, `CKeyPinningStore.IndexedDB`):
|
|
43
|
+
|
|
44
|
+
1. `CMemoryKeyPinningStore` (or `CKeyPinningStore.Memory`): In-memory `Map` store for tests, ephemeral sessions, and server runtimes.
|
|
45
|
+
2. `CLocalStorageKeyPinningStore` (or `CKeyPinningStore.LocalStorage`): Browser `localStorage` with namespaced keys (`katlux:pin:<namespace>:<entityId>`).
|
|
46
|
+
- *SSR Guard*: Throws a descriptive `ERR_SSR_STORAGE_UNAVAILABLE` error if accessed in environments lacking `localStorage`.
|
|
47
|
+
- *Threat Boundary*: Storing pins in `localStorage` provides defense-in-depth against network MITM. However, origin-level script execution (e.g. XSS) or user cache resets (`localStorage.clear()`) wipes pinned state, reverting the store to unpinned TOFU. For multi-tenant or enterprise requirements, combine with signed reset attestations and server-side attestation logs.
|
|
48
|
+
3. `CIndexedDBKeyPinningStore` (or `CKeyPinningStore.IndexedDB`): Browser `IndexedDB` using the shared `KatluxIndexedDB` singleton (`key_pins` store). Executes `compareAndSet` within a single `readwrite` transaction to ensure strict concurrency isolation.
|
|
45
49
|
|
|
46
50
|
---
|
|
47
51
|
|
|
@@ -84,6 +88,15 @@ const signedAttestation = await CKeyManager.signKeyResetAttestation(
|
|
|
84
88
|
)
|
|
85
89
|
```
|
|
86
90
|
|
|
91
|
+
### Standalone Attestation Verification: `CKeyManager.verifyAttestation`
|
|
92
|
+
```ts
|
|
93
|
+
const { authorityKey, attestation } = await CKeyManager.verifyAttestation(signedAttestation, {
|
|
94
|
+
trustedAuthorities: [authorityPublicKey],
|
|
95
|
+
clockSkewMs: 60000,
|
|
96
|
+
maxExpirationWindowMs: 7 * 86400000
|
|
97
|
+
})
|
|
98
|
+
```
|
|
99
|
+
|
|
87
100
|
---
|
|
88
101
|
|
|
89
102
|
## 4. Verification Pipeline: `CKeyManager.verifyAndPinKey`
|
|
@@ -101,15 +114,16 @@ const result = await CKeyManager.verifyAndPinKey('peer-alice', peerPublicKey, {
|
|
|
101
114
|
})
|
|
102
115
|
```
|
|
103
116
|
|
|
104
|
-
### Verification Flow &
|
|
117
|
+
### Verification Flow & Strict Validation Rules:
|
|
105
118
|
1. **TOFU (First Use)**: If no pin exists, establishes initial pin with sequence `0`, returns `{ trusted: true, firstUse: true }`, and dispatches `onPinChange` with type `'tofu'`.
|
|
106
119
|
2. **Pin Matches**: Returns `{ trusted: true, firstUse: false }`.
|
|
107
120
|
3. **Pin Mismatch (MITM Guard)**: If fingerprints differ and no attestation is returned, throws `ERR_KEY_PINNING_MISMATCH`.
|
|
108
|
-
4. **Attestation Validation**: Accepts new key only if **all
|
|
109
|
-
1. `
|
|
110
|
-
2. `
|
|
111
|
-
3. `
|
|
112
|
-
4. `
|
|
113
|
-
5.
|
|
114
|
-
6. `
|
|
121
|
+
4. **Attestation Validation (`verifyAttestation`)**: Accepts new key only if **all rules** pass (otherwise throws `ERR_KEY_ATTESTATION_INVALID`):
|
|
122
|
+
1. `attestation.version === 1` (strict schema versioning).
|
|
123
|
+
2. `authorityFingerprint` matches an authority in `trustedAuthorities`, and the digital signature verifies.
|
|
124
|
+
3. `entityId` matches target peer.
|
|
125
|
+
4. `oldFingerprint` matches current pinned fingerprint.
|
|
126
|
+
5. `newFingerprint` matches presented key fingerprint.
|
|
127
|
+
6. Time validity: `issuedAt - clockSkewMs <= now <= expiresAt + clockSkewMs` and validity window $\le$ `maxExpirationWindowMs`.
|
|
128
|
+
7. `sequence > currentPin.attestationSequence` (replay/rollback protection).
|
|
115
129
|
5. **Atomic Update**: On success, updates the pin via `compareAndSet` and dispatches `onPinChange` with type `'attested_reset'`.
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# Katlux Encryption Architecture: Searchable Encryption, Threat Model & Field Suitability
|
|
2
|
+
|
|
3
|
+
> Part of the Katlux Cryptographic Architecture (`@katlux/providers`).
|
|
4
|
+
> See [encryption.md](encryption.md) for the master index.
|
|
5
|
+
> Related: [encryption-field-level.md](encryption-field-level.md) · [encryption-threat-model.md](encryption-threat-model.md)
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## 1. Overview & Architectural Intent
|
|
10
|
+
|
|
11
|
+
Standard cryptographic envelope encryption (AES-256-GCM) produces randomized ciphertext using fresh, unpredictable 96-bit initialization vectors (IVs) for every encryption operation. While this guarantees semantic security (IND-CPA), it makes direct searching, point lookups, and substring matching impossible on ciphertext columns without decrypting the entire database.
|
|
12
|
+
|
|
13
|
+
Katlux solves privacy-preserving queries through a decoupled, multi-tiered searchable encryption architecture:
|
|
14
|
+
1. **Confidentiality Layer**: AES-256-GCM envelope encryption stores the primary record payload.
|
|
15
|
+
2. **Deterministic Exact-Match Indexing**: HMAC-SHA256 blind indexing (`_bidx`) provides $O(\log N)$ exact lookups via standard database B-Trees.
|
|
16
|
+
3. **Substring Matching**: Trigram set hashing (`_trigrams`) enables partial queries via PostgreSQL GIN or MySQL fulltext inverted indexes.
|
|
17
|
+
4. **Multi-Era Keyring Support**: `rewriteEncryptedFilters` rewrites high-level AST queries into candidate token arrays (`IN (...)`) across multiple key versions (`active`, `search-only`).
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 2. Threat Model, Controlled Information Leakage & Feature Toggles
|
|
22
|
+
|
|
23
|
+
> [!WARNING]
|
|
24
|
+
> **Controlled Leakage in Searchable Symmetric Encryption (SSE)**:
|
|
25
|
+
> In enterprise cryptography, there is a fundamental law: you cannot have zero metadata leakage while simultaneously running performant index queries over ciphertext.
|
|
26
|
+
> Katlux makes every searchable capability an **explicit opt-in feature toggle** so developers maintain complete governance over what metadata is exposed to database storage and query observers.
|
|
27
|
+
|
|
28
|
+
### The 4 Searchable Feature Toggles & Security Warnings
|
|
29
|
+
|
|
30
|
+
```
|
|
31
|
+
[Raw Encrypted Data (AES-256-GCM)]
|
|
32
|
+
│
|
|
33
|
+
┌──────────────────┼──────────────────┬──────────────────┐
|
|
34
|
+
▼ ▼ ▼ ▼
|
|
35
|
+
1. blindIndex 2. trigrams 3. rangeBuckets 4. decryptedCache
|
|
36
|
+
(Exact match) (Substring >= 3) (Coarse ranges) (Client RAM cache)
|
|
37
|
+
• Leaks: Frequency • Leaks: Substring • Leaks: Coarse • Leaks: RAM
|
|
38
|
+
distribution overlaps & len interval tags persistence
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
1. **`blindIndex` (`_bidx`) [Toggle 1 - Opt-In]**:
|
|
42
|
+
- **Enables**: Exact match (`==`, `!=`, `in`, `nin`).
|
|
43
|
+
- **Controlled Leak**: Deterministic equality preserves frequency distribution.
|
|
44
|
+
- **Security Warning**:
|
|
45
|
+
> [!CAUTION]
|
|
46
|
+
> **Never blind-index low-cardinality fields.** If applied to status, boolean, gender, or small enums, an attacker can recover plaintexts via frequency analysis without having the HMAC key. Apply strictly to high-entropy unique identifiers (email, SSN, UUID, phone).
|
|
47
|
+
2. **`trigrams` (`_trigrams`) [Toggle 2 - Opt-In]**:
|
|
48
|
+
- **Enables**: Substring search (`contains`, `like`) for terms $\ge 3$ characters.
|
|
49
|
+
- **Controlled Leak**: Substring overlap patterns and approximate string length.
|
|
50
|
+
- **Security Warning**:
|
|
51
|
+
> [!WARNING]
|
|
52
|
+
> Do not enable trigrams on confidential tokens, passwords, or short secrets. Substring queries $< 3$ characters throw `ERR_TRIGRAM_QUERY_TOO_SHORT` to enforce vocabulary integrity.
|
|
53
|
+
3. **`rangeBuckets` (`_bucket`) [Toggle 3 - Opt-In]**:
|
|
54
|
+
- **Enables**: Range operators (`<`, `<=`, `>`, `>=`, `between`) and coarse bucket sorting.
|
|
55
|
+
- **Controlled Leak**: Discrete bucket membership (e.g. `[50k, 60k)`, `2026-Q1`). Stored in plaintext companion columns for database B-Tree index traversal.
|
|
56
|
+
- **Security Warning**:
|
|
57
|
+
> [!TIP]
|
|
58
|
+
> Coarse buckets maximize $k$-anonymity privacy (e.g., \$25k–\$50k salary steps or year-level dates). Finer buckets increase query selectivity at the expense of revealing narrower plaintext approximations.
|
|
59
|
+
4. **`decryptedCache` [Toggle 4 - Opt-In Client Memory]**:
|
|
60
|
+
- **Enables**: Re-rendering and navigating back and forth across previously loaded pages without re-running CPU-intensive WebCrypto AES decryption.
|
|
61
|
+
- **Controlled Leak**: Decrypted rows are retained in client JavaScript memory (`WeakMap`/RAM) until page unmount.
|
|
62
|
+
- **Security Notice**: Disabled by default (`false`) to ensure high-security terminals automatically garbage-collect decrypted records upon page transitions.
|
|
63
|
+
|
|
64
|
+
---
|
|
65
|
+
|
|
66
|
+
### 2.1 Client-Side On-the-Fly Lazy Decryption & Verification Lifecycle
|
|
67
|
+
|
|
68
|
+
A common misconception is that client-side providers decrypt the entire dataset into memory. **They do not**:
|
|
69
|
+
1. **Bulk Ciphertext Storage**: The entire ingested dataset (`allData` / `_data`) remains 100% encrypted in browser memory (`__encrypted_payload__`).
|
|
70
|
+
2. **Ciphertext Index Evaluation (Stage 1)**: When a user filters or searches, [`CSearchIndex`](file:///home/cagatay/Desktop/projects/KatluxShowcase/packages/katlux-providers/services/EncryptionProvider/CSearchIndex.ts) evaluates queries against the in-memory HMAC tokens and bucket tags—without decrypting unneeded rows.
|
|
71
|
+
3. **Stage-2 Verification Dispatch (`requiresPostVerification`)**:
|
|
72
|
+
- **Exact Matches (`==`, `!=`, discrete array `in`)**: HMAC-SHA256 has zero false positives. Only the active `pageSize` page slice (`_rowMap.slice(startIndex, endIndex)`) is lazily decrypted.
|
|
73
|
+
- **Fuzzy / Trigram Queries, Range Buckets, and Short Queries ($< 3$ chars)**: Candidate rows identified in stage 1 are decrypted and verified using `verifyDecryptedRows(candidates, filter)` (or `verifyDecryptedRow` in `CTreeClientDataProvider`) to compute the exact `rowCount` and prevent under-filled or empty pages before pagination slicing.
|
|
74
|
+
4. **Tree Provider Verification**: In [`CTreeClientDataProvider`](file:///home/cagatay/Desktop/projects/KatluxShowcase/packages/katlux-providers/services/DataProvider/CTreeClientDataProvider.ts), candidate matching nodes are decrypted, verified with `verifyDecryptedRow`, and the visible ancestor and descendant tree hierarchy is built strictly from verified nodes.
|
|
75
|
+
5. **Memory Cleanup**: Decrypted rows are rendered to `pageData`. Navigating away allows the browser to garbage-collect the previous page slice unless `decryptedCache: true` is explicitly opted into.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
### 2.2 Server-Side Database Query Limitations
|
|
80
|
+
|
|
81
|
+
When querying encrypted persistence columns on the server (`CAPIFlatServerDataProvider`, `CAPITreeServerDataProvider`, `batchLoad: "onDemand"`):
|
|
82
|
+
- ❌ **No SQL `ORDER BY` on Encrypted Columns**: AES-256-GCM ciphertext and HMAC digests are cryptographically randomized. You cannot sort alphabetically or numerically in SQL on ciphertext columns. (Sorting must occur on the client, or coarsely by bucket).
|
|
83
|
+
- ❌ **No Database Aggregations**: SQL `SUM(salary)`, `AVG(salary)`, `MIN(salary)` cannot be computed in the database on encrypted columns.
|
|
84
|
+
- ❌ **Substrings $< 3$ Characters**: Substrings with 1 or 2 characters cannot form trigrams and are rejected.
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
## 3. Field Suitability Matrix ("Hangi Alanlar İçin?")
|
|
89
|
+
|
|
90
|
+
Selecting an appropriate cryptographic representation for application fields requires balancing query utility against privacy exposure:
|
|
91
|
+
|
|
92
|
+
| Storage / Query Strategy | Suitable Fields / Data Types | Required Entropy | Supported Query Capabilities | Information Leakage & Cryptographic Tradeoffs | Recommended Best Practice |
|
|
93
|
+
| :--- | :--- | :--- | :--- | :--- | :--- |
|
|
94
|
+
| **Plaintext / Unencrypted** | Public IDs, system timestamps, foreign keys, non-sensitive categories (e.g. `id`, `created_at`, `status`, `role`) | Public / Any | Full SQL & AST query expressions (`=`, `!=`, `<`, `>`, `LIKE`, `IN`, Sorting, Grouping) | Zero confidentiality. Visible to storage admins, database dumps, and query logs. | **Use for operational metadata & relations**. Do not encrypt fields required for high-throughput relational joins or non-sensitive filters. |
|
|
95
|
+
| **Standard AES-256-GCM Envelope Encryption** | Highly sensitive PII, passwords, private keys, medical notes, credit card CVVs, rich text payloads (e.g. `medical_notes`, `api_secret`, `cvv`) | High or Low | None (direct ciphertext storage only; decrypted in client memory or authorized application layer) | Zero index leakage. Randomized IV/nonce ensures identical plaintexts yield completely different ciphertexts. Immune to frequency analysis. | **Gold standard for confidential data**. Use whenever fields do not require server-side filtering, searching, or indexing. |
|
|
96
|
+
| **Blind Index Equality Token (HMAC-SHA256)** | High-entropy unique / semi-unique identifiers: `email`, `ssn`, `tax_id`, `phone_number`, `national_id`, `uuid` | **High Entropy Only** | Exact match (`==`, `!=`, `IN`, `NOT IN`) via B-Tree index on `*_bidx` column | Deterministic token preserves equality and frequency distributions. Duplicates and recurring values are observable. | **Use strictly for exact lookups of high-entropy identifiers**. Always use a dedicated HMAC key separated from the DEK. Never apply to low-cardinality fields. |
|
|
97
|
+
| **Trigram Substring Search** | Long, high-entropy textual strings requiring substring/contains queries: `full_name`, `address_line`, `company_name` | **High to Medium Entropy** | Substring / Contains search via GIN inverted index (`@>` array containment) on `*_trigrams` | Leaks approximate string length and character co-occurrence frequencies. | **Use with caution on high-entropy text**. Enforce 3+ character minimum query length in client UI. Do not apply to small discrete enum sets. |
|
|
98
|
+
| **Shadow Bucketing / Range Tokens (RFC-001 / TASK-031)** | Numeric ranges, dates, monetary amounts, age groups, salaries (e.g. `salary_bucket`, `created_date_bucket`, `credit_score_range`) | Low to Medium | Range queries (`>`, `<`, `>=`, `<=`, `BETWEEN`) on discretized bucket values | Coarse range leakage. Reveals which discrete bucket (e.g. `$50k-$75k`, `2026-Q1`) a record falls into. | **Recommended when range search is strictly necessary**. Tune bucket granularity to balance query precision against distribution leakage. |
|
|
99
|
+
|
|
100
|
+
---
|
|
101
|
+
|
|
102
|
+
## 4. Query Rewriting & Multi-Era Keyrings (`rewriteEncryptedFilters`)
|
|
103
|
+
|
|
104
|
+
When an application searches on an encrypted column across multiple key rotation eras, `rewriteEncryptedFilters` automatically expands equality, substring, and range AST nodes across active and search-only keys or discrete shadow buckets without generating SQL strings or coupling to ORMs:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { rewriteEncryptedFilters, EDataFilterOperator, type IDataFilter } from '@katlux/providers'
|
|
108
|
+
|
|
109
|
+
const blindIndexKeyring = {
|
|
110
|
+
activeKid: 'k2026',
|
|
111
|
+
keys: {
|
|
112
|
+
k2025: { key: hmacKey2025, status: 'search-only' },
|
|
113
|
+
k2026: { key: hmacKey2026, status: 'active' }
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// User query on encrypted fields:
|
|
118
|
+
const filters: IDataFilter[] = [
|
|
119
|
+
{ operator: EDataFilterOperator.Equal, field: { email: 'alice@securesuite.io' }, active: true },
|
|
120
|
+
{ operator: 'contains' as any, field: { name: 'Elena' }, active: true },
|
|
121
|
+
{ operator: EDataFilterOperator.GreaterThanOrEqual, field: { salary: 82000 }, active: true }
|
|
122
|
+
]
|
|
123
|
+
|
|
124
|
+
// Pure AST transformation (no SQL / no ORM coupling):
|
|
125
|
+
const rewritten = await rewriteEncryptedFilters(filters, {
|
|
126
|
+
blindIndexFields: {
|
|
127
|
+
email: { column: 'email_bidx', keyring: blindIndexKeyring }
|
|
128
|
+
},
|
|
129
|
+
trigramFields: {
|
|
130
|
+
name: { column: 'name_trigrams', keyring: blindIndexKeyring }
|
|
131
|
+
},
|
|
132
|
+
rangeBuckets: {
|
|
133
|
+
salary: { type: 'stepped', step: 25000 }
|
|
134
|
+
}
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
// Output AST:
|
|
138
|
+
// [
|
|
139
|
+
// { operator: EDataFilterOperator.In, field: { email_bidx: ['token_k2026...', 'token_k2025...'] }, active: true },
|
|
140
|
+
// { operator: 'contains', field: { name_trigrams: ['tri1_k2026...', 'tri1_k2025...'] }, active: true },
|
|
141
|
+
// { operator: EDataFilterOperator.In, field: { salary_bucket: ['75000-99999', '100000-124999'] }, active: true }
|
|
142
|
+
// ]
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Safety Guards
|
|
146
|
+
- **Unsupported Operators Guard (`ERR_BIDX_UNSUPPORTED_OPERATOR`)**: Attempting range operations on a blind index column without shadow bucketing throws `ERR_BIDX_UNSUPPORTED_OPERATOR` to prevent unencrypted plaintext leakage.
|
|
147
|
+
- **Short Query Guard (`ERR_TRIGRAM_QUERY_TOO_SHORT`)**: Substring queries with fewer than 3 characters throw `ERR_TRIGRAM_QUERY_TOO_SHORT` to enforce vocabulary integrity.
|
|
148
|
+
- **Candidate Token Cap (`maxCandidateTokens`)**: Protects against query explosion by limiting generated tokens (default: 500).
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## 5. Persistence Schema & Query Execution
|
|
153
|
+
|
|
154
|
+
```sql
|
|
155
|
+
CREATE TABLE users (
|
|
156
|
+
id SERIAL PRIMARY KEY,
|
|
157
|
+
email_encrypted JSONB NOT NULL,
|
|
158
|
+
email_bidx CHAR(64) NOT NULL,
|
|
159
|
+
email_trigrams TEXT[] NOT NULL,
|
|
160
|
+
status VARCHAR(50) DEFAULT 'Active'
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
-- Fast B-Tree index for exact lookups:
|
|
164
|
+
CREATE INDEX idx_users_email_bidx ON users (email_bidx);
|
|
165
|
+
|
|
166
|
+
-- Inverted GIN index for substring containment:
|
|
167
|
+
CREATE INDEX idx_users_email_trigrams ON users USING GIN (email_trigrams);
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
Exact match query:
|
|
171
|
+
```sql
|
|
172
|
+
SELECT id, email_encrypted FROM users WHERE email_bidx = ANY($1::char(64)[]);
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
Substring query:
|
|
176
|
+
```sql
|
|
177
|
+
SELECT id, email_encrypted FROM users WHERE email_trigrams @> $1::text[];
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
## 6. Plaintext Shadow Bucketing Recipes & Range Queries (`TASK-031`)
|
|
183
|
+
|
|
184
|
+
To support range filtering (`<`, `<=`, `>`, `>=`, `between`) and sorting on encrypted numeric or date columns without leaking order via OPE, configure `rangeBuckets`:
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
import { CFlatClientDataProvider, EDataFilterOperator } from '@katlux/providers'
|
|
188
|
+
|
|
189
|
+
const provider = new CFlatClientDataProvider({
|
|
190
|
+
idKey: 'id',
|
|
191
|
+
pageSize: 10,
|
|
192
|
+
encryption: {
|
|
193
|
+
enabled: true,
|
|
194
|
+
key: 'master-encryption-secret',
|
|
195
|
+
fields: ['salary', 'birthDate'],
|
|
196
|
+
rangeBuckets: {
|
|
197
|
+
salary: { type: 'stepped', step: 25000 },
|
|
198
|
+
birthDate: { type: 'date', granularity: 'year' }
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
// Query: salary >= 82000
|
|
204
|
+
// Stage 1 (Coarse Matching): CSearchIndex resolves eligible bucket keys (75000-99999, 100000-124999...)
|
|
205
|
+
// Stage 2 (Fine-Grained Verification): Provider lazily decrypts the current page slice and eliminates false positives (e.g. 76k)
|
|
206
|
+
provider.setFilter({
|
|
207
|
+
operator: EDataFilterOperator.GreaterThanOrEqual,
|
|
208
|
+
field: { salary: 82000 },
|
|
209
|
+
active: true
|
|
210
|
+
})
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
### Supported Bucketing Strategies
|
|
214
|
+
- **Date Granularities**: `'year'` (`2026`), `'quarter'` (`2026-Q1`), `'month'` (`2026-03`), `'week'` (`2026-W08`), `'day'` (`2026-03-15`).
|
|
215
|
+
- **Stepped Numeric**: `{ type: 'stepped', step: 25000, min?: 0 }` -> `'0-24999'`, `'25000-49999'`, `'75000-99999'`.
|
|
216
|
+
- **Threshold / Tier Numeric**: `{ type: 'tier', thresholds: [0, 25000, 50000, 100000] }` -> `'<0'`, `'0-24999'`, `'25000-49999'`, `'>=100000'`.
|
|
217
|
+
|
|
218
|
+
|
|
@@ -24,7 +24,8 @@ Standard native Web Crypto implementation using AES-GCM with a 128-bit authentic
|
|
|
24
24
|
import { CWebCryptoEncryptionProvider } from '@katlux/providers'
|
|
25
25
|
|
|
26
26
|
const cipher = new CWebCryptoEncryptionProvider({
|
|
27
|
-
|
|
27
|
+
// In production, supply credentials dynamically via environment variables, KMS, or runtime config:
|
|
28
|
+
key: process.env.DATA_KEY, // or useRuntimeConfig().public.dataEncryptionKey, or dynamic callback
|
|
28
29
|
kid: 'tenant-v1',
|
|
29
30
|
kdf: 'pbkdf2', // 'pbkdf2' for passwords, 'none' for 256-bit keys
|
|
30
31
|
kdfIterations: 310000
|
|
@@ -37,6 +38,9 @@ const envelope = await cipher.encrypt({ ssn: '123-45-6789', salary: 150000 })
|
|
|
37
38
|
const data = await cipher.decrypt(envelope)
|
|
38
39
|
```
|
|
39
40
|
|
|
41
|
+
> [!IMPORTANT]
|
|
42
|
+
> **Production Key Security**: Never hardcode secret passphrases or keys in frontend bundles or source code. Always source credentials dynamically from secure runtime environments (`process.env`), KMS key agreement, authenticated sessions, or interactive user prompts.
|
|
43
|
+
|
|
40
44
|
---
|
|
41
45
|
|
|
42
46
|
## 3. `CWebCryptoAESCBCProvider` (AES-CBC-256 + HMAC-SHA-256)
|
|
@@ -137,3 +141,23 @@ const envelope = await cipher.encrypt(record, { recordId: 'REC-42' })
|
|
|
137
141
|
```
|
|
138
142
|
|
|
139
143
|
Transposition (moving the ciphertext to a different record or column) causes GCM tag verification to fail immediately.
|
|
144
|
+
|
|
145
|
+
## 8. Request Context AAD Binding (`bindRequestContextAad`)
|
|
146
|
+
|
|
147
|
+
Outer transport envelopes can optionally bind the HTTP request method and canonical normalized URL into AEAD AAD (`req:${method}:${normalizedUrl}`) to prevent replay attacks and cross-endpoint payload redirection:
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
const cipher = new CWebCryptoEncryptionProvider({
|
|
151
|
+
key: myKey,
|
|
152
|
+
bindRequestContextAad: true // default: false (opt-in)
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
// Outbound request bodies bind canonical URL and method:
|
|
156
|
+
const payload = await cipher.encrypt(data, {
|
|
157
|
+
method: 'POST',
|
|
158
|
+
url: '/api/transfers?b=2&a=1&_t=1730000000'
|
|
159
|
+
})
|
|
160
|
+
// Bound AAD: req:POST:/api/transfers?a=1&b=2 (_t stripped, query keys sorted)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
> **Decoupling Rule**: Persistent entity and field-level ciphertext envelopes (`fields` / `valueEncryption`) bind entity identity (`record:<id>|field:<name>`), NOT transient transport methods or URLs. This ensures resources encrypted during `POST` remain seamlessly readable when fetched via `GET`.
|
|
@@ -59,6 +59,7 @@ export interface IProviderEncryptionOptions {
|
|
|
59
59
|
aad?: string | Uint8Array | ArrayBuffer | ((record: Record<string, unknown>, field: string) => string | Uint8Array | ArrayBuffer) // AEAD Additional Data or dynamic callback
|
|
60
60
|
aadFields?: string[] // Sibling record fields to deterministically bind into AAD (e.g. ['contact_id', 'version'])
|
|
61
61
|
baseAad?: string // Optional base prefix for AAD context binding
|
|
62
|
+
bindRequestContextAad?: boolean // default: false. Opt-in request context binding (req:${method}:${normalizedUrl}) into outer transport AEAD AAD
|
|
62
63
|
decryptOnSSR?: boolean // default: false. Prevents SSR decryption unless explicitly enabled with server secrets
|
|
63
64
|
fields?: string[] // Field-level encryption: only encrypt listed fields
|
|
64
65
|
strict?: boolean // Enforces strict decryption: unencrypted plaintext in `fields` triggers injection violation; defaults allowedAlgorithms to ['AES-GCM']
|
|
@@ -66,6 +67,7 @@ export interface IProviderEncryptionOptions {
|
|
|
66
67
|
allowedKids?: string[] // Whitelist of permitted Key Identifiers (kid); defaults to Object.keys(keys)
|
|
67
68
|
onDecryptError?: ((info: IDecryptErrorInfo) => unknown) | boolean | string // Per-field error hook, safe fallback marker, or true for '[⚠ Decryption Error]'
|
|
68
69
|
searchIndex?: boolean // Enables HMAC-SHA256 blind index and trigram search index on encrypted fields
|
|
70
|
+
decryptedCache?: boolean // default: false. Enables in-memory decrypted row cache for local filtering without blind index
|
|
69
71
|
preEncrypted?: boolean // Set to true if API endpoints return pre-encrypted ciphertext envelopes; enables in-memory index decryption
|
|
70
72
|
hmacKey?: TKeyProvider // Optional dedicated HMAC key for search indexing (defaults to encryption key)
|
|
71
73
|
algorithm?: 'AES-GCM' | string // default: 'AES-GCM'
|
|
@@ -108,3 +110,64 @@ const cipher = createEncryptionProvider({
|
|
|
108
110
|
- **Memory Zeroization**: Intermediate plaintext byte buffers (`Uint8Array`, `Buffer`) are immediately zeroed in memory via `.fill(0)` within `finally` blocks.
|
|
109
111
|
- **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
112
|
- **SSR Confidentiality Guard**: With `decryptOnSSR: false` (default zero-trust setting), sensitive payloads remain as encrypted envelopes in server memory and HTML hydration strings.
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## 6. Blind Indexing Trust Models & Cryptographic Threat Analysis (BUG-034 / DEBT-028)
|
|
117
|
+
|
|
118
|
+
### Architectural Trust Models
|
|
119
|
+
1. **End-to-End Zero-Plaintext (Client-Side Query Rewriting)**:
|
|
120
|
+
- The client holds the dedicated HMAC search key (`hmacKey`).
|
|
121
|
+
- The client computes HMAC blind index tokens locally using `rewriteEncryptedFilters` before query transmission.
|
|
122
|
+
- The client transmits **only** opaque HMAC token hashes (`name_bidx = <hash>`) over the wire. The server queries encrypted index columns and never observes plaintext search terms.
|
|
123
|
+
2. **Server-Side Blind Indexing (Protected Persistence)**:
|
|
124
|
+
- The client transmits the search string to the server over HTTPS.
|
|
125
|
+
- The server computes HMAC blind index tokens in memory and filters encrypted rows without decrypting records or persisting plaintext.
|
|
126
|
+
- *Boundary Note*: Because search terms travel over HTTP in this model, it protects database persistence at rest but does **not** constitute "zero plaintext over HTTP".
|
|
127
|
+
|
|
128
|
+
### Controlled Information Leakage & The 4 Opt-In Feature Toggles
|
|
129
|
+
In enterprise cryptography, Searchable Symmetric Encryption (SSE) always introduces controlled information leakage. To ensure zero accidental exposure, Katlux treats all searchable encryption capabilities as **opt-in dials**:
|
|
130
|
+
|
|
131
|
+
1. **`blindIndex` (`_bidx`)**: Enables exact match (`==`, `!=`, `in`, `nin`). Leaks frequency distribution. **Strictly prohibited on low-cardinality columns** (status, gender, boolean, small enums).
|
|
132
|
+
2. **`trigrams` (`_trigrams`)**: Enables substring search (`contains`, `like`) $\ge 3$ characters. Leaks approximate term length and character overlap patterns. Disabled by default.
|
|
133
|
+
3. **`rangeBuckets` (`_bucket`)**: Enables range queries (`<`, `<=`, `>`, `>=`, `between`) and coarse sorting. Leaks discrete interval membership (e.g. `[50k, 60k)`). Coarse buckets maximize $k$-anonymity.
|
|
134
|
+
4. **`decryptedCache`**: Client-side in-memory cache for fast paging. Leaks decrypted plaintext to browser RAM until page unmount. Disabled by default.
|
|
135
|
+
|
|
136
|
+
### Client-Side Lazy Decryption Lifecycle (Zero-Bulk Plaintext in Memory)
|
|
137
|
+
- In `CFlatClientDataProvider` and `CTreeClientDataProvider`, the entire dataset (`allData`) **remains 100% encrypted in RAM**.
|
|
138
|
+
- Client filtering evaluates against ciphertext HMAC tokens and bucket tags in `CSearchIndex`.
|
|
139
|
+
- Only the visible page slice (e.g., 20 or 25 rows) is decrypted on the fly in `loadPageData()`.
|
|
140
|
+
- Coarse bucket or trigram false-positive candidates are pruned via `verifyDecryptedRows()` before render.
|
|
141
|
+
- Navigating away allows previous page rows to be garbage-collected immediately when `decryptedCache: false`.
|
|
142
|
+
|
|
143
|
+
### Cryptographic Leakage Disclosures & Threat Model
|
|
144
|
+
- **Deterministic Equality Tokens (`==`, `in`)**:
|
|
145
|
+
- Deterministic HMAC digests preserve 1-to-1 equivalence (`HMAC(x) === HMAC(x)`). Any observer with read access to the encrypted database or query stream can observe token equality and compute exact frequency distributions.
|
|
146
|
+
- **Frequency Analysis & Dictionary Recovery on Low-Cardinality Fields**:
|
|
147
|
+
- For low-entropy columns with small sets of possible values (e.g. `gender` [M/F/O], `status` ['active', 'inactive'], `country`, boolean flags), an attacker does **not** need the HMAC secret key.
|
|
148
|
+
- By comparing the relative frequencies of distinct token hashes against known real-world demographic or business distributions (e.g. 51% female vs 49% male, or 92% active vs 8% inactive), the attacker can map HMAC tokens back to plaintext with high confidence.
|
|
149
|
+
- **CRITICAL PROHIBITION**: Never use blind indexing on low-cardinality, enum, boolean, or predictable dictionary fields.
|
|
150
|
+
- **Trigram Tokens (Substring Search)**:
|
|
151
|
+
- Substring matching via character trigram sets leaks approximate term lengths and character co-occurrence patterns.
|
|
152
|
+
- An attacker observing trigram sets across rows can deduce language, spelling patterns, and common affixes.
|
|
153
|
+
- UI client queries must enforce a minimum query threshold (≥ 3 characters) to avoid generating trivial or overly broad candidate sets.
|
|
154
|
+
- **Shadow Bucketing (Range Query Leakage)**:
|
|
155
|
+
- Discrete bucket tokens (`2026-Q1`, `50k-60k`) are stored alongside ciphertext. Anyone with database read access sees the coarse range of the encrypted value.
|
|
156
|
+
- Enterprise mitigation: Keep bucket intervals wide (e.g. $25k+ or year intervals) to maximize privacy.
|
|
157
|
+
- **Entropy Separation & Scope Recommendations**:
|
|
158
|
+
- **Safe & Recommended**: High-entropy, unique or semi-unique identifiers with dedicated, domain-isolated HMAC keys (`email`, `ssn`, `tax_id`, `phone_number`, `uuid`, `account_number`).
|
|
159
|
+
- **Actively Discouraged / Unsafe**: Low-entropy enum fields, statuses, boolean flags, small categorical datasets, or common dictionary words.
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## 7. Field Suitability Matrix ("Hangi Alanlar İçin?")
|
|
164
|
+
|
|
165
|
+
| Storage / Query Strategy | Suitable Fields / Data Types | Required Entropy | Supported Query Capabilities | Information Leakage & Cryptographic Tradeoffs | Recommended Best Practice |
|
|
166
|
+
| :--- | :--- | :--- | :--- | :--- | :--- |
|
|
167
|
+
| **Plaintext / Unencrypted** | Public IDs, system timestamps, foreign keys, non-sensitive categories (e.g. `id`, `created_at`, `status`, `role`) | Public / Any | Full SQL & AST query expressions (`=`, `!=`, `<`, `>`, `LIKE`, `IN`, Sorting, Grouping) | Zero confidentiality. Visible to storage admins, database dumps, and query logs. | **Use for operational metadata & relations**. Do not encrypt fields required for high-throughput relational joins or non-sensitive filters. |
|
|
168
|
+
| **Standard AES-256-GCM Envelope Encryption** | Highly sensitive PII, passwords, private keys, medical notes, credit card CVVs, rich text payloads (e.g. `medical_notes`, `api_secret`, `cvv`) | High or Low | None (direct ciphertext storage only; decrypted in client memory or authorized application layer) | Zero index leakage. Randomized IV/nonce ensures identical plaintexts yield completely different ciphertexts. Immune to frequency analysis. | **Gold standard for confidential data**. Use whenever fields do not require server-side filtering, searching, or indexing. |
|
|
169
|
+
| **Blind Index Equality Token (HMAC-SHA256)** | High-entropy unique / semi-unique identifiers: `email`, `ssn`, `tax_id`, `phone_number`, `national_id`, `uuid` | **High Entropy Only** | Exact match (`==`, `!=`, `IN`, `NOT IN`) via B-Tree index on `*_bidx` column | Deterministic token preserves equality and frequency distributions. Duplicates and recurring values are observable. | **Use strictly for exact lookups of high-entropy identifiers**. Always use a dedicated HMAC key separated from the DEK. Never apply to low-cardinality fields. |
|
|
170
|
+
| **Trigram Substring Search** | Long, high-entropy textual strings requiring substring/contains queries: `full_name`, `address_line`, `company_name` | **High to Medium Entropy** | Substring / Contains search via GIN inverted index (`@>` array containment) on `*_trigrams` | Leaks approximate string length and character co-occurrence frequencies. | **Use with caution on high-entropy text**. Enforce 3+ character minimum query length in client UI. Do not apply to small discrete enum sets. |
|
|
171
|
+
| **Shadow Bucketing / Range Tokens (RFC-001 / TASK-031)** | Numeric ranges, dates, monetary amounts, age groups, salaries (e.g. `salary_bucket`, `created_date_bucket`, `credit_score_range`) | Low to Medium | Range queries (`>`, `<`, `>=`, `<=`, `BETWEEN`) on discretized bucket values | Coarse range leakage. Reveals which discrete bucket (e.g. `$50k-$75k`, `2026-Q1`) a record falls into. | **Recommended when range search is strictly necessary**. Tune bucket granularity to balance query precision against distribution leakage. |
|
|
172
|
+
|
|
173
|
+
|
|
@@ -12,9 +12,10 @@
|
|
|
12
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
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
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) |
|
|
15
|
+
| **Key Pinning (TOFU) & Attestations** | Trust-On-First-Use key store, signed key-reset attestation protocol, 6 strict verification rules, memory/storage adapters | `IKeyPinningStore`, `CKeyPinningStore`, `CMemoryKeyPinningStore`, `CLocalStorageKeyPinningStore`, `CIndexedDBKeyPinningStore`, `verifyAndPinKey`, `signKeyResetAttestation` | [encryption-key-pinning.md](encryption-key-pinning.md) |
|
|
16
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
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
|
+
| **Searchable Encryption & Threat Model** | HMAC-SHA256 blind indexing, frequency analysis threats, low-cardinality prohibitions, field suitability matrix | `rewriteEncryptedFilters`, `computeMultiBlindIndex`, `IBlindIndexKeyring` | [encryption-searchable.md](encryption-searchable.md) |
|
|
18
19
|
|
|
19
20
|
---
|
|
20
21
|
|
|
@@ -42,3 +43,27 @@
|
|
|
42
43
|
- **Asymmetric / Hybrid**: `/providers/classes/CRSAEncryptionProvider` · `/providers/classes/CECDHEncryptionProvider`
|
|
43
44
|
- **Key Management**: `/providers/classes/CKeyManager`
|
|
44
45
|
- **Base & Contracts**: `/providers/classes/AEncryptionProvider` · `/providers/interfaces/IEncryptionProvider` · `/providers/interfaces/IProviderEncryptionOptions`
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 4. Production Secret Hygiene & Runtime Configuration
|
|
50
|
+
|
|
51
|
+
- **Never Hardcode Secrets**: Passphrases, symmetric keys, and private keys must never be hardcoded into frontend bundles or repository source files.
|
|
52
|
+
- **Dynamic Key Resolution**:
|
|
53
|
+
- **Web & SSR**: Use Nuxt `useRuntimeConfig()` or environment variables (`process.env.DATA_KEY`).
|
|
54
|
+
- **Interactive & Multi-Tenant**: Pass an asynchronous key getter callback `key: async () => await fetchSessionKey()` to dynamically retrieve keys from an authenticated session or secure KMS ceremony.
|
|
55
|
+
- **Showcase & Local Sandbox**: Use centralized demo constants via `apps/showcase/config/demoCrypto.ts` or runtime generated ephemeral keys (`generateEphemeralTenantKey()`).
|
|
56
|
+
|
|
57
|
+
---
|
|
58
|
+
|
|
59
|
+
## 5. Controlled Information Leakage & Searchable Feature Toggles
|
|
60
|
+
|
|
61
|
+
> [!WARNING]
|
|
62
|
+
> Searchable Symmetric Encryption (SSE) always involves deliberate, controlled metadata leakage. In Katlux, all searchable features are **opt-in dials** so developers maintain governance over exposure:
|
|
63
|
+
> - **`blindIndex` (`_bidx`)**: Enables `==`, `!=`, `in`, `nin`. Leaks frequency distribution. **Strictly forbidden on low-cardinality fields** (status, gender, boolean, small enums).
|
|
64
|
+
> - **`trigrams` (`_trigrams`)**: Enables substring `contains`, `like` $\ge 3$ characters. Leaks substring overlap patterns and length.
|
|
65
|
+
> - **`rangeBuckets` (`_bucket`)**: Enables `<`, `<=`, `>`, `>=`, `between` and coarse sorting. Leaks coarse interval membership. Coarser intervals maximize $k$-anonymity.
|
|
66
|
+
> - **`decryptedCache`**: Enables fast client-side paging. Retains decrypted rows in browser RAM until page unmount. Disabled by default for zero-trust terminal security.
|
|
67
|
+
> - **Client Memory Lifecycle**: Client data providers keep the entire dataset encrypted in RAM (`allData`). Queries filter ciphertext tags via `CSearchIndex`, and only the visible page slice (e.g. 20-50 rows) is decrypted on the fly with candidate false-positive pruning.
|
|
68
|
+
> - **Server Limitations**: In backend SQL databases, encrypted columns cannot be sorted (`ORDER BY`) or aggregated (`SUM`, `AVG`) without client-side decryption.
|
|
69
|
+
|
|
@@ -3,7 +3,7 @@
|
|
|
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:
|
|
6
|
+
| `IDataFilter` | Structured filter query | `{ operator: EDataFilterOperator, field: TDataRow \| IDataFilter \| IDataFilter[], active: boolean }` |
|
|
7
7
|
| `IDataSort` | Sorting configuration | `{ field: string, direction: 'asc' \| 'desc' }` |
|
|
8
8
|
| `IDataResult` | Standardized API response | `{ rowCount: number, rows: T[] }` |
|
|
9
9
|
| `ECacheStrategy` | Caching persistence tiers | `Memory`, `ServerSession`, `BrowserSession`, `LocalStorage`, `IndexedDB`, `Cookie`, `Application` |
|
|
@@ -11,6 +11,8 @@
|
|
|
11
11
|
| `IKDatatableAction` | Row/Bulk action config | `{ label: string, action: Function, icon?: string, iconOnly?: boolean, type?: string, visible?: Function }` |
|
|
12
12
|
| `ITreeNode` | Tree node wrapper | `{ data: Record<string, unknown>, id: string \| number, parentId: string \| number \| null, depth: number, hasChildren: boolean, isExpanded: boolean }` |
|
|
13
13
|
| `ICompositeItem`| Composite input pair | `{ selection: string \| number \| null, value: unknown }` (e.g. `{ selection: 'en', value: 'Hello' }`) |
|
|
14
|
+
| `IBatchProgress`| Batch progress details | `{ loaded: number, total: number, percent: number }` |
|
|
15
|
+
| `IBatchLoadedEvent`| Batch load telemetry event | `{ pageNumber: number, rows: T[], totalLoaded: number, rowCount: number }` |
|
|
14
16
|
|
|
15
17
|
### Standard Data Structure (`IDataResult`)
|
|
16
18
|
All Katlux DataProviders (and components consuming them, such as `KDatatable`, `KLineChart`, `KBarChart`, `KPieChart`, `KCombobox`, etc.) use `IDataResult` as the standard payload format:
|
|
@@ -18,7 +18,6 @@ const { currentPage, pageSize, filter, sortList } = storeToRefs(store)
|
|
|
18
18
|
// Idiomatic Vue 3 refs with automatic scope disposal (no SSR leaks) and recursion-safe two-way syncing:
|
|
19
19
|
const {
|
|
20
20
|
pageData, // ShallowRef<T[]> (current page data)
|
|
21
|
-
virtualRows, // ShallowRef<T[]> (full ordered array of visible rows for virtual scroll)
|
|
22
21
|
rowCount, // Ref<number>
|
|
23
22
|
loading, // Ref<boolean>
|
|
24
23
|
error, // Ref<Error | unknown>
|
|
@@ -26,6 +25,8 @@ const {
|
|
|
26
25
|
pageSize, // Ref<number> (synced with Pinia)
|
|
27
26
|
filter, // Ref<IDataFilter | null> (synced with Pinia)
|
|
28
27
|
sortList, // Ref<IDataSort[]> (synced with Pinia)
|
|
28
|
+
stateVersion, // Ref<number> (monotonically increasing counter bridging markRaw providers into Vue computed effects)
|
|
29
|
+
filterSortVersion,// Ref<number> (increments strictly on filter or sort updates)
|
|
29
30
|
setCurrentPage, // (page: number) => void
|
|
30
31
|
setPageSize, // (size: number) => void
|
|
31
32
|
setFilter, // (filter: IDataFilter | null) => void
|