@katlux/toolkit 0.1.1-alpha.145 → 0.1.1-alpha.147
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -22
- package/bin/ai-init.mjs +575 -0
- package/bin/ai-tokens/adapters/antigravityAdapter.mjs +22 -0
- package/bin/ai-tokens/adapters/claudeCodeAdapter.mjs +192 -0
- package/bin/ai-tokens/adapters/codexAdapter.mjs +176 -0
- package/bin/ai-tokens/adapters/cursorAdapter.mjs +202 -0
- package/bin/ai-tokens/adapters/index.mjs +30 -0
- package/bin/ai-tokens/cliViews.mjs +301 -0
- package/bin/ai-tokens/formatAndDates.mjs +89 -0
- package/bin/ai-tokens/reportGenerator.mjs +232 -0
- package/bin/ai-tokens/transcriptParser.mjs +299 -0
- package/bin/ai-tokens.mjs +38 -872
- package/bin/cli.mjs +81 -48
- package/bin/create-preset.mjs +1 -0
- package/bin/preset-contracts.json +2997 -0
- package/dist/compiled/composables/locales/asianAndPacific.mjs +296 -0
- package/dist/compiled/composables/locales/northernAndEasternEuropean.mjs +342 -0
- package/dist/compiled/composables/locales/westernEuropean.mjs +268 -0
- package/dist/compiled/composables/locales.mjs +32 -720
- package/dist/compiled/composables/useDataProvider.mjs +39 -26
- package/dist/compiled/composables/useFilterLogic.mjs +10 -2
- package/dist/compiled/composables/useKatluxForm.mjs +13 -11
- package/dist/compiled/composables/usePresetComponent.mjs +2 -0
- package/dist/compiled/composables/useRequestQueue.mjs +3 -1
- package/dist/compiled/composables/useVirtualDataset.mjs +657 -0
- package/dist/compiled/composables/useVirtualScroll.mjs +93 -66
- package/dist/compiled/composables/virtualDataset/cacheStateHelpers.mjs +76 -0
- package/dist/compiled/composables/virtualDataset/keyboardNavHelpers.mjs +60 -0
- package/dist/compiled/composables/virtualDataset/treeSelectionHelpers.mjs +103 -0
- package/dist/compiled/composables/virtualDataset/types.mjs +0 -0
- package/dist/compiled/utils/deprecation.mjs +44 -0
- package/dist/compiled/utils/dom.mjs +124 -0
- package/dist/module.cjs +58 -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 +54 -77
- package/dist/runtime/app.config.d.ts +3 -0
- package/dist/runtime/components/KAccordion/KAccordion.global.d.vue.ts +1 -1
- package/dist/runtime/components/KAccordion/KAccordion.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 +12 -2
- package/dist/runtime/components/KBulkActions/KBulkActions.logic.js +40 -41
- package/dist/runtime/components/KButton/KButton.global.d.vue.ts +1 -1
- package/dist/runtime/components/KButton/KButton.global.vue.d.ts +1 -1
- 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 +67 -14
- package/dist/runtime/components/KCalendar/KCalendarMonth.global.d.vue.ts +25 -5
- package/dist/runtime/components/KCalendar/KCalendarMonth.global.vue +15 -1
- package/dist/runtime/components/KCalendar/KCalendarMonth.global.vue.d.ts +25 -5
- package/dist/runtime/components/KCalendar/KCalendarMonth.logic.d.ts +21 -3
- package/dist/runtime/components/KCalendar/KCalendarMonth.logic.js +136 -7
- package/dist/runtime/components/KCalendar/recurringUtils.js +6 -5
- 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 +18 -3
- package/dist/runtime/components/KCombobox/KCombobox.global.vue +9 -4
- package/dist/runtime/components/KCombobox/KCombobox.global.vue.d.ts +18 -3
- package/dist/runtime/components/KCombobox/KCombobox.logic.d.ts +16 -2
- package/dist/runtime/components/KCombobox/KCombobox.logic.js +32 -13
- package/dist/runtime/components/KCompositeInput/KCompositeInput.global.d.vue.ts +8 -8
- package/dist/runtime/components/KCompositeInput/KCompositeInput.global.vue.d.ts +8 -8
- package/dist/runtime/components/KCompositeInput/KCompositeInput.logic.d.ts +3 -3
- package/dist/runtime/components/KContextMenu/KContextMenu.global.d.vue.ts +3 -3
- package/dist/runtime/components/KContextMenu/KContextMenu.global.vue +4 -1
- package/dist/runtime/components/KContextMenu/KContextMenu.global.vue.d.ts +3 -3
- package/dist/runtime/components/KContextMenu/KContextMenu.logic.d.ts +24 -4
- package/dist/runtime/components/KContextMenu/KContextMenu.logic.js +43 -22
- package/dist/runtime/components/KDatatable/KDataIterator.global.d.vue.ts +38 -11
- package/dist/runtime/components/KDatatable/KDataIterator.global.vue +39 -20
- package/dist/runtime/components/KDatatable/KDataIterator.global.vue.d.ts +38 -11
- package/dist/runtime/components/KDatatable/KDataIterator.logic.d.ts +31 -8
- package/dist/runtime/components/KDatatable/KDataIterator.logic.js +69 -24
- package/dist/runtime/components/KDatatable/KDatatable.global.d.vue.ts +10 -14
- package/dist/runtime/components/KDatatable/KDatatable.global.vue +6 -5
- package/dist/runtime/components/KDatatable/KDatatable.global.vue.d.ts +10 -14
- package/dist/runtime/components/KDatatable/KDatatable.logic.d.ts +4 -6
- package/dist/runtime/components/KDatatable/KDatatable.logic.js +32 -24
- package/dist/runtime/components/KDatePicker/KDatePicker.global.d.vue.ts +33 -15
- package/dist/runtime/components/KDatePicker/KDatePicker.global.vue +60 -16
- package/dist/runtime/components/KDatePicker/KDatePicker.global.vue.d.ts +33 -15
- package/dist/runtime/components/KDatePicker/KDatePicker.logic.d.ts +30 -6
- package/dist/runtime/components/KDatePicker/KDatePicker.logic.js +249 -59
- package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.d.vue.ts +2 -2
- package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.vue.d.ts +2 -2
- package/dist/runtime/components/KDateTimePicker/KDateTimePicker.logic.js +2 -0
- package/dist/runtime/components/KDropdown/KDropdown.global.d.vue.ts +4 -4
- package/dist/runtime/components/KDropdown/KDropdown.global.vue.d.ts +4 -4
- package/dist/runtime/components/KDropdown/KDropdown.logic.d.ts +3 -2
- package/dist/runtime/components/KDropdown/KDropdown.logic.js +14 -13
- package/dist/runtime/components/KGantt/KGantt.global.d.vue.ts +55 -4
- package/dist/runtime/components/KGantt/KGantt.global.vue +18 -3
- package/dist/runtime/components/KGantt/KGantt.global.vue.d.ts +55 -4
- 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/KGrid/KGrid.global.d.vue.ts +1 -1
- package/dist/runtime/components/KGrid/KGrid.global.vue.d.ts +1 -1
- 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/KIcon/KIcon.global.d.vue.ts +1 -1
- package/dist/runtime/components/KIcon/KIcon.global.vue.d.ts +1 -1
- package/dist/runtime/components/KLayout/KLayout.global.d.vue.ts +4 -1
- package/dist/runtime/components/KLayout/KLayout.global.vue +4 -1
- package/dist/runtime/components/KLayout/KLayout.global.vue.d.ts +4 -1
- package/dist/runtime/components/KLoader/KLoader.global.d.vue.ts +9 -0
- package/dist/runtime/components/KLoader/KLoader.global.vue +3 -0
- package/dist/runtime/components/KLoader/KLoader.global.vue.d.ts +9 -0
- package/dist/runtime/components/KLoader/KLoader.logic.d.ts +5 -0
- package/dist/runtime/components/KLoader/KLoader.logic.js +4 -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/KMaskTextbox/KMaskTextbox.logic.js +30 -7
- package/dist/runtime/components/KMultiTabs/KMultiTabs.logic.d.ts +1 -0
- package/dist/runtime/components/KMultiTabs/MultiTabs.global.d.vue.ts +23 -0
- package/dist/runtime/components/KMultiTabs/MultiTabs.global.vue +24 -0
- package/dist/runtime/components/KMultiTabs/MultiTabs.global.vue.d.ts +23 -0
- package/dist/runtime/components/KPagination/KPagination.global.d.vue.ts +3 -1
- package/dist/runtime/components/KPagination/KPagination.global.vue +2 -1
- package/dist/runtime/components/KPagination/KPagination.global.vue.d.ts +3 -1
- package/dist/runtime/components/KPagination/KPagination.logic.d.ts +2 -1
- package/dist/runtime/components/KPagination/KPagination.logic.js +74 -14
- 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/KTabs/KTabs.logic.js +33 -11
- 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 +15 -4
- package/dist/runtime/components/KTextbox/KTextbox.global.vue +8 -2
- package/dist/runtime/components/KTextbox/KTextbox.global.vue.d.ts +15 -4
- package/dist/runtime/components/KTextbox/KTextbox.logic.d.ts +5 -0
- package/dist/runtime/components/KTextbox/KTextbox.logic.js +4 -0
- package/dist/runtime/components/KTooltip/KTooltip.logic.d.ts +11 -2
- package/dist/runtime/components/KTooltip/KTooltip.logic.js +7 -5
- package/dist/runtime/components/KTree/KTree.global.d.vue.ts +4 -4
- package/dist/runtime/components/KTree/KTree.global.vue.d.ts +4 -4
- package/dist/runtime/components/KTree/KTree.logic.d.ts +2 -2
- package/dist/runtime/components/KTree/KTree.logic.js +37 -13
- package/dist/runtime/components/KTreePicker/KTreePicker.global.d.vue.ts +7 -5
- package/dist/runtime/components/KTreePicker/KTreePicker.global.vue +4 -6
- package/dist/runtime/components/KTreePicker/KTreePicker.global.vue.d.ts +7 -5
- package/dist/runtime/components/KTreePicker/KTreePicker.logic.d.ts +3 -2
- package/dist/runtime/components/KTreePicker/KTreePicker.logic.js +10 -1
- package/dist/runtime/components/KTreeView/KTreeView.global.d.vue.ts +40 -6
- package/dist/runtime/components/KTreeView/KTreeView.global.vue +19 -1
- package/dist/runtime/components/KTreeView/KTreeView.global.vue.d.ts +40 -6
- package/dist/runtime/components/KTreeView/KTreeView.logic.d.ts +24 -4
- package/dist/runtime/components/KTreeView/KTreeView.logic.js +105 -11
- package/dist/runtime/composables/locales/asianAndPacific.d.ts +11 -0
- package/dist/runtime/composables/locales/asianAndPacific.js +296 -0
- package/dist/runtime/composables/locales/northernAndEasternEuropean.d.ts +12 -0
- package/dist/runtime/composables/locales/northernAndEasternEuropean.js +342 -0
- package/dist/runtime/composables/locales/westernEuropean.d.ts +10 -0
- package/dist/runtime/composables/locales/westernEuropean.js +268 -0
- package/dist/runtime/composables/locales.d.ts +4 -24
- package/dist/runtime/composables/locales.js +32 -720
- package/dist/runtime/composables/useDataProvider.d.ts +5 -3
- package/dist/runtime/composables/useDataProvider.js +39 -26
- 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 +13 -11
- package/dist/runtime/composables/usePresetComponent.js +2 -0
- package/dist/runtime/composables/useRequestQueue.d.ts +2 -0
- package/dist/runtime/composables/useRequestQueue.js +3 -1
- package/dist/runtime/composables/useSortLogic.d.ts +1 -1
- package/dist/runtime/composables/useVirtualDataset.d.ts +9 -0
- package/dist/runtime/composables/useVirtualDataset.js +657 -0
- package/dist/runtime/composables/useVirtualScroll.d.ts +14 -10
- package/dist/runtime/composables/useVirtualScroll.js +93 -66
- package/dist/runtime/composables/virtualDataset/cacheStateHelpers.d.ts +49 -0
- package/dist/runtime/composables/virtualDataset/cacheStateHelpers.js +76 -0
- package/dist/runtime/composables/virtualDataset/keyboardNavHelpers.d.ts +26 -0
- package/dist/runtime/composables/virtualDataset/keyboardNavHelpers.js +60 -0
- package/dist/runtime/composables/virtualDataset/treeSelectionHelpers.d.ts +24 -0
- package/dist/runtime/composables/virtualDataset/treeSelectionHelpers.js +103 -0
- package/dist/runtime/composables/virtualDataset/types.d.ts +113 -0
- package/dist/runtime/composables/virtualDataset/types.js +0 -0
- package/dist/runtime/directives/clickOutside.d.ts +1 -1
- package/dist/runtime/directives/clickOutside.js +41 -13
- package/dist/runtime/plugins/nuxtCompatPlugin.d.ts +2 -1
- package/dist/runtime/plugins/nuxtCompatPlugin.js +16 -1
- package/dist/runtime/plugins/toastPlugin.client.js +2 -2
- 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 +7 -0
- package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.vue +57 -2
- package/dist/runtime/presets/default/components/KCalendar/KCalendarMonth.vue.d.ts +7 -0
- package/dist/runtime/presets/default/components/KCalendar/KCalendarWeek.vue +6 -5
- package/dist/runtime/presets/default/components/KCombobox/KCombobox.d.vue.ts +4 -1
- package/dist/runtime/presets/default/components/KCombobox/KCombobox.vue +27 -17
- package/dist/runtime/presets/default/components/KCombobox/KCombobox.vue.d.ts +4 -1
- package/dist/runtime/presets/default/components/KCombobox/KComboboxList.d.vue.ts +1 -1
- package/dist/runtime/presets/default/components/KCombobox/KComboboxList.vue +10 -10
- package/dist/runtime/presets/default/components/KCombobox/KComboboxList.vue.d.ts +1 -1
- package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.d.vue.ts +2 -0
- package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.vue +67 -22
- package/dist/runtime/presets/default/components/KContextMenu/KContextMenu.vue.d.ts +2 -0
- package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.d.vue.ts +41 -8
- package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.vue +184 -174
- package/dist/runtime/presets/default/components/KDataIterator/KDataIterator.vue.d.ts +41 -8
- package/dist/runtime/presets/default/components/KDatatable/KDatatable.d.vue.ts +17 -10
- package/dist/runtime/presets/default/components/KDatatable/KDatatable.vue +113 -394
- package/dist/runtime/presets/default/components/KDatatable/KDatatable.vue.d.ts +17 -10
- 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/KDropdown/KDropdown.d.vue.ts +5 -2
- package/dist/runtime/presets/default/components/KDropdown/KDropdown.vue +15 -12
- package/dist/runtime/presets/default/components/KDropdown/KDropdown.vue.d.ts +5 -2
- package/dist/runtime/presets/default/components/KGantt/KGantt.d.vue.ts +11 -2
- package/dist/runtime/presets/default/components/KGantt/KGantt.vue +46 -29
- package/dist/runtime/presets/default/components/KGantt/KGantt.vue.d.ts +11 -2
- package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.d.vue.ts +6 -2
- package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.vue +23 -8
- package/dist/runtime/presets/default/components/KGantt/KGanttTimeline.vue.d.ts +6 -2
- package/dist/runtime/presets/default/components/KLayout/KLayout.vue +2 -2
- package/dist/runtime/presets/default/components/KLoader/KLoader.d.vue.ts +1 -0
- package/dist/runtime/presets/default/components/KLoader/KLoader.vue +13 -2
- package/dist/runtime/presets/default/components/KLoader/KLoader.vue.d.ts +1 -0
- package/dist/runtime/presets/default/components/KMaskTextbox/KMaskTextbox.vue +1 -94
- package/dist/runtime/presets/default/components/KMultiTabs/KMultiTabs.vue +69 -4
- package/dist/runtime/presets/default/components/KRangeSlider/KRangeSlider.vue +18 -46
- package/dist/runtime/presets/default/components/KSlider/KSlider.vue +11 -23
- package/dist/runtime/presets/default/components/KTextbox/KTextbox.d.vue.ts +4 -1
- package/dist/runtime/presets/default/components/KTextbox/KTextbox.vue +24 -8
- package/dist/runtime/presets/default/components/KTextbox/KTextbox.vue.d.ts +4 -1
- package/dist/runtime/presets/default/components/KTree/KTree.d.vue.ts +3 -3
- package/dist/runtime/presets/default/components/KTree/KTree.vue +61 -56
- package/dist/runtime/presets/default/components/KTree/KTree.vue.d.ts +3 -3
- package/dist/runtime/presets/default/components/KTree/KTreeNodeItem.d.vue.ts +1 -0
- package/dist/runtime/presets/default/components/KTree/KTreeNodeItem.vue +12 -2
- package/dist/runtime/presets/default/components/KTree/KTreeNodeItem.vue.d.ts +1 -0
- 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/runtime/server/middleware/session.js +7 -0
- package/dist/runtime/utils/deprecation.d.ts +14 -0
- package/dist/runtime/utils/deprecation.js +44 -0
- package/dist/runtime/utils/dom.d.ts +31 -0
- package/dist/runtime/utils/dom.js +124 -0
- package/dist/skills/KATLUX_INDEX.md +18 -19
- package/dist/skills/katlux-components/SKILL.md +2 -0
- package/dist/skills/katlux-components/components/KBulkActions.md +26 -2
- package/dist/skills/katlux-components/components/KCombobox.md +2 -2
- package/dist/skills/katlux-components/components/KDataIterator.md +17 -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/KLayout.md +4 -0
- package/dist/skills/katlux-components/components/KLineChart.md +3 -0
- package/dist/skills/katlux-components/components/KLoader.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/KTextbox.md +1 -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 +27 -8
- package/dist/skills/katlux-presets/SKILL.md +163 -3
- package/dist/skills/katlux-presets/creating-a-preset.md +67 -0
- package/dist/skills/katlux-providers/SKILL.md +19 -5
- package/dist/skills/katlux-providers/providers/ADataProvider.md +17 -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/CAPITreeServerDataProvider.md +13 -0
- 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 +67 -20
- package/dist/skills/katlux-providers/providers/encryption-key-management.md +23 -2
- package/dist/skills/katlux-providers/providers/encryption-key-pinning.md +25 -11
- package/dist/skills/katlux-providers/providers/encryption-searchable.md +341 -0
- package/dist/skills/katlux-providers/providers/encryption-symmetric.md +29 -2
- package/dist/skills/katlux-providers/providers/encryption-threat-model.md +70 -1
- 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 +7 -3
- package/bin/add-ai-reference.mjs +0 -259
|
@@ -50,7 +50,8 @@ const customerProvider = new CFlatClientDataProvider({
|
|
|
50
50
|
pageSize: 20,
|
|
51
51
|
encryption: {
|
|
52
52
|
enabled: true,
|
|
53
|
-
|
|
53
|
+
// In production, retrieve credentials dynamically from environment variables, KMS, or runtime config:
|
|
54
|
+
key: () => useRuntimeConfig().public.dataEncryptionKey, // or process.env.DATA_KEY
|
|
54
55
|
kid: 'tenant-key-v1',
|
|
55
56
|
fields: ['ssn', 'salary', 'creditCard'],
|
|
56
57
|
searchIndex: true // Enables search/filter on encrypted fields via CSearchIndex
|
|
@@ -74,6 +75,9 @@ await customerProvider.setDataChunked(largeEmployees, {
|
|
|
74
75
|
### Pre-Encrypted Dataset Ingestion (`preEncrypted: true`)
|
|
75
76
|
When datasets arrive already encrypted from server endpoints, data providers perform a transient in-memory decryption pass on indexed fields to populate `CSearchIndex` without modifying or leaking persistent ciphertext rows in `allData`.
|
|
76
77
|
|
|
78
|
+
> [!IMPORTANT]
|
|
79
|
+
> **Production Key Security**: Never hardcode secret passphrases or master encryption keys in client-side bundles or source code. Always retrieve keys dynamically from secure environment variables (`process.env.DATA_KEY`), Nuxt `useRuntimeConfig()`, an authenticated user session, or an async callback (`key: async () => await fetchSessionKey()`).
|
|
80
|
+
|
|
77
81
|
---
|
|
78
82
|
|
|
79
83
|
## 4. Blind Index Search & Substring Trigram Indexing (`CSearchIndex`)
|
|
@@ -82,9 +86,23 @@ Enables fast exact match (`==`, `!=`) and substring search (`in`) over encrypted
|
|
|
82
86
|
|
|
83
87
|
### Ingestion Pipeline
|
|
84
88
|
1. **Normalization**: Normalize plaintext (`NFKC` + lowercase).
|
|
85
|
-
2. **Blind Index Token**: Generate exact blind index token via `CKeyManager.computeBlindIndex(plain, hmacKey)
|
|
89
|
+
2. **Blind Index Token**: Generate exact blind index token via `CKeyManager.computeBlindIndex(plain, hmacKey)` (deriving string `hmacKey` material via `CKeyManager.deriveBlindIndexHmacKey(keyMaterial, { kdfIterations })`, defaulting to `310,000` PBKDF2 iterations).
|
|
86
90
|
3. **Trigram Slices**: Extract 3-character slices via `extractTrigrams(plain)` and hash each trigram with `searchIndex.computeTrigramTokens(plain)`.
|
|
87
91
|
|
|
92
|
+
> [!WARNING]
|
|
93
|
+
> **Cloud / Edge Runtime PBKDF2 Cap (`kdfIterations: 100_000`)**: `CKeyManager.deriveBlindIndexHmacKey`, `CSearchIndex`, and `IProviderEncryptionOptions` default to `310,000` PBKDF2 iterations for browser E2EE. When deriving blind-index HMAC keys from string passphrases in serverless/edge environments (e.g., **Cloudflare Workers** `workerd`, which caps WebCrypto PBKDF2 at `100,000` iterations and throws `NotSupportedError` above that), explicitly configure `kdfIterations: 100_000` on `CSearchIndex`, `CKeyManager.deriveBlindIndexHmacKey`, or `IProviderEncryptionOptions` (or pass a pre-imported `CryptoKey` / `Uint8Array`). Ensure client and server share the same `kdfIterations` value if tokens are compared across boundaries.
|
|
94
|
+
|
|
95
|
+
### Client Filtering & Sorting on Encrypted Envelopes (`decryptedCache` & Sort Guards)
|
|
96
|
+
In client-side data providers (`CFlatClientDataProvider` and `CTreeClientDataProvider`), data records in `allData` remain encrypted at rest as ciphertext envelopes (`{ __encrypted: true, ciphertext, iv }`).
|
|
97
|
+
|
|
98
|
+
1. **Filtering on Encrypted Fields**:
|
|
99
|
+
- **Blind Index (`searchIndex: true`)**: Recommended for large datasets (10,000+ rows). Uses HMAC tokens and trigram hashes without holding plaintext copies of records at rest.
|
|
100
|
+
- **Decrypted Row Cache (`decryptedCache: true`)**: Opt-in in-memory cache holding plaintext row representations for instant local evaluation across any filter operator (`Equal`, `Contains`, `In`, custom predicates) without blind index setup.
|
|
101
|
+
- **Unconfigured Guard**: Attempting to filter on an encrypted field without `searchIndex` or `decryptedCache` emits an informative console warning. Filter comparisons explicitly guard against `"[object Object]"` string coercion, ensuring raw envelopes never match plaintext queries.
|
|
102
|
+
|
|
103
|
+
2. **Sorting on Encrypted Fields (Sort Guard)**:
|
|
104
|
+
- Client sorting on encrypted fields without deterministic sortable shadow buckets (`TASK-031`) emits a development warning and leaves dataset order unchanged, preventing broken `"[object Object]"` comparisons.
|
|
105
|
+
|
|
88
106
|
---
|
|
89
107
|
|
|
90
108
|
## 5. Backend Persistence & Datatable Encrypted Search
|
|
@@ -136,10 +154,16 @@ CREATE INDEX idx_contacts_email_trigrams ON contacts USING GIN (email_trigrams);
|
|
|
136
154
|
WHERE name_trigrams @> $1::text[] AND department = 'Security'
|
|
137
155
|
```
|
|
138
156
|
|
|
139
|
-
### 3. Production Best Practices
|
|
157
|
+
### 3. Production Best Practices & Security Disclosures (BUG-034)
|
|
140
158
|
- **Strict Key Isolation**: Isolate `DATA_ENCRYPTION_KEY` (AES-256-GCM) from `BLIND_INDEX_HMAC_KEY`.
|
|
159
|
+
- **Architectural Trust Models**:
|
|
160
|
+
- *End-to-End Zero-Plaintext (Client-Side Query Rewriting)*: In true zero-plaintext architectures, the client computes HMAC search tokens locally using client-held keys (`rewriteEncryptedFilters`) and dispatches only opaque hashes (`name_bidx = <hash>`). The server never observes plaintext search strings.
|
|
161
|
+
- *Server-Side Blind Indexing (Protected Persistence)*: When search queries are sent over HTTP and evaluated on the server, backend database records remain encrypted at rest, but wire transport carries search terms (claims of "zero plaintext over HTTP" do not apply).
|
|
162
|
+
- **Leakage Disclosures**:
|
|
163
|
+
- *Deterministic Equality Tokens (`==`, `in`)*: Deterministic HMAC tokens expose dataset frequency distributions. Highly susceptible to dictionary matching and frequency analysis on low-entropy fields. Never blind-index low-cardinality fields (gender, boolean flags, status, city).
|
|
164
|
+
- *Trigram Tokens (Substring Search)*: Expose approximate string length and character combinations.
|
|
165
|
+
- *Safe Fields*: Restrict blind indexing strictly to high-entropy identifiers with dedicated index keys (email addresses, SSNs, tax IDs, account numbers, UUIDs).
|
|
141
166
|
- **Short Queries (< 3 chars)**: Substring search requires at least 3 characters to form a valid trigram. Enforce a 3-character minimum in client UI.
|
|
142
|
-
- **Low-Cardinality Isolation**: Never blind index low-cardinality fields (boolean flags, binary status) to prevent frequency analysis leakage.
|
|
143
167
|
- **Client Decryption Pipeline**: API responses return encrypted envelopes (`__encrypted: true`). Frontend `CAPIFlatServerDataProvider` decrypts only the received page slice via `decryptPageRows()` on arrival.
|
|
144
168
|
|
|
145
169
|
---
|
|
@@ -197,22 +221,19 @@ const writeToken = await CKeyManager.computeWriteBlindIndex('user@example.com',
|
|
|
197
221
|
|
|
198
222
|
### Encrypted Query Rewriting (`rewriteEncryptedFilters`)
|
|
199
223
|
|
|
200
|
-
When an application receives datatable
|
|
224
|
+
When an application receives datatable filter criteria targeting encrypted fields, `rewriteEncryptedFilters` acts as a pure `IDataFilter` AST transformation function (No ORM / No SQL generation), expanding equality and negation predicates into candidate tokens across multi-KID keyrings while preserving compound logical hierarchies (`and`, `or`, `nor`, `nand`):
|
|
201
225
|
|
|
202
226
|
```ts
|
|
203
|
-
import { rewriteEncryptedFilters } from '@katlux/providers'
|
|
227
|
+
import { rewriteEncryptedFilters, EDataFilterOperator, type IDataFilter } from '@katlux/providers'
|
|
204
228
|
|
|
205
229
|
const rewritten = await rewriteEncryptedFilters(
|
|
206
230
|
[
|
|
207
|
-
{
|
|
208
|
-
{
|
|
231
|
+
{ operator: EDataFilterOperator.Equal, field: { email: 'user@example.com' }, active: true },
|
|
232
|
+
{ operator: EDataFilterOperator.Equal, field: { status: 'Active' }, active: true } // unencrypted passthrough
|
|
209
233
|
],
|
|
210
234
|
{
|
|
211
|
-
|
|
212
|
-
fields: {
|
|
235
|
+
blindIndexFields: {
|
|
213
236
|
email: {
|
|
214
|
-
encrypted: true,
|
|
215
|
-
blindIndex: true,
|
|
216
237
|
keyring: emailKeyring,
|
|
217
238
|
column: 'email_bidx'
|
|
218
239
|
}
|
|
@@ -221,19 +242,23 @@ const rewritten = await rewriteEncryptedFilters(
|
|
|
221
242
|
}
|
|
222
243
|
)
|
|
223
244
|
|
|
224
|
-
//
|
|
225
|
-
//
|
|
226
|
-
//
|
|
245
|
+
// Output AST (Pure IDataFilter[]):
|
|
246
|
+
// [
|
|
247
|
+
// { operator: EDataFilterOperator.In, field: { email_bidx: ['bidx_v2', 'bidx_v1'] }, active: true },
|
|
248
|
+
// { operator: EDataFilterOperator.Equal, field: { status: 'Active' }, active: true }
|
|
249
|
+
// ]
|
|
250
|
+
// Total tokens generated: rewritten.totalCandidateTokens
|
|
227
251
|
```
|
|
228
252
|
|
|
229
|
-
#### Operator Mapping &
|
|
230
|
-
- **Equality (`==`) / Set Membership (`in`)**: Expands to
|
|
231
|
-
- **Negation (`!=`) / Exclusion (`nin` / `not in`)**: Expands to
|
|
232
|
-
- **
|
|
253
|
+
#### Operator Mapping & Security Guards
|
|
254
|
+
- **Equality (`==`) / Set Membership (`in`)**: Expands to `{ operator: EDataFilterOperator.In, field: { [col_bidx]: tokenCandidates }, active: true }` over candidate tokens generated from active and `search-only` keys.
|
|
255
|
+
- **Negation (`!=`) / Exclusion (`nin` / `not in`)**: Expands to `{ operator: EDataFilterOperator.NotIn, field: { [col_bidx]: tokenCandidates }, active: true }`.
|
|
256
|
+
- **Compound Hierarchies**: Fully preserves logical groupings (`or`, `and`, `nor`, `nand`) without flattening into `AND`.
|
|
257
|
+
- **Unsupported Operators Guard (`ERR_BIDX_UNSUPPORTED_OPERATOR`)**: Querying a blind-indexed column with unsupported operators (e.g. `>`, `<`, `>=`, `<=`, `contains`, `startsWith`, `endsWith`, `like`) immediately throws `ERR_BIDX_UNSUPPORTED_OPERATOR`. Plaintext fallback values are never leaked.
|
|
258
|
+
- **Pass-through**: Unencrypted fields (e.g. `status = 'Active'`) pass through unmodified in their tree positions.
|
|
233
259
|
|
|
234
260
|
#### Guard Rails
|
|
235
261
|
- `maxCandidateTokens` (default: 500): Prevents query explosion from large `in` lists combined with multiple key versions. Throws `ERR_BIDX_TOO_MANY_CANDIDATES` if exceeded.
|
|
236
|
-
- Parameter Chunking: SQLite/MySQL dialect chunking breaks down long `IN` lists when exceeding parameter limits.
|
|
237
262
|
|
|
238
263
|
---
|
|
239
264
|
|
|
@@ -258,3 +283,25 @@ When rotating a blind index HMAC key:
|
|
|
258
283
|
> [!TIP]
|
|
259
284
|
> **Information Leakage Trade-off**: Keeping historical keys in `'search-only'` mode expands SQL queries to test multiple HMAC hashes per search term. To minimize index leakage and maintain optimal query performance, complete Step 2 (background re-indexing) promptly so older keys can be transitioned to `'retired'`.
|
|
260
285
|
|
|
286
|
+
---
|
|
287
|
+
|
|
288
|
+
## 8. Field Suitability Matrix & Threat Modeling ("Hangi Alanlar İçin?")
|
|
289
|
+
|
|
290
|
+
Selecting an appropriate cryptographic representation for data fields requires balancing **query capability** against **information leakage**:
|
|
291
|
+
|
|
292
|
+
| Storage / Query Strategy | Suitable Fields / Data Types | Required Entropy | Supported Query Capabilities | Information Leakage & Cryptographic Tradeoffs | Recommended Best Practice |
|
|
293
|
+
| :--- | :--- | :--- | :--- | :--- | :--- |
|
|
294
|
+
| **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. |
|
|
295
|
+
| **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. |
|
|
296
|
+
| **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. |
|
|
297
|
+
| **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. |
|
|
298
|
+
| **Deterministic Shadow-Bucket Range Index (`RFC-001` / `TASK-031` / `DEBT-042`)** | Coarse dates (`created_at` by year/quarter), non-PII metrics, or broad compliant financial bands | Low to Medium | Range queries (`>`, `<`, `>=`, `<=`, `BETWEEN`) on discretized bucket tokens | **Not zero-leakage.** Reveals value frequency distributions, bucket order relations, and empirical distribution profiles. | **DO NOT USE narrow buckets on high-sensitivity PII** (`salary`, `age`, `birthDate`, `creditScore`). Leave sensitive attributes unindexed (`AES-256-GCM`) or restrict strictly to broad tiers (`$25,000+` salary bands, `'year'` dates); enforce minimum width (`ERR_BUCKET_STEP_TOO_NARROW`). |
|
|
299
|
+
|
|
300
|
+
### Low-Cardinality Column Warning & Frequency Analysis Attacks
|
|
301
|
+
> [!CAUTION]
|
|
302
|
+
> **Strict Prohibition on Low-Cardinality Blind Indexing**:
|
|
303
|
+
> Deterministic HMAC tokens preserve frequency distribution. In low-cardinality columns (e.g. `gender` [M/F], boolean flags [true/false], order status ['pending', 'shipped', 'delivered'], or country codes), an observer who accesses the encrypted table or query stream can match token frequencies against known population statistics (e.g., 51% female vs 49% male) and instantly deduce the plaintext values without knowing the HMAC secret key.
|
|
304
|
+
>
|
|
305
|
+
> If a field has fewer than 1,000 distinct possible values in the domain, or consists of common dictionary words, **do NOT blind index it**. Use standard envelope encryption combined with in-memory client filtering (`decryptedCache: true`) or leave operational flags in plaintext.
|
|
306
|
+
|
|
307
|
+
|
|
@@ -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
|
|
@@ -99,6 +110,9 @@ const authKey = derived.authKey
|
|
|
99
110
|
const dataKey = derived.encryptionKey
|
|
100
111
|
```
|
|
101
112
|
|
|
113
|
+
> [!WARNING]
|
|
114
|
+
> **Edge / Serverless PBKDF2 Ceiling (`100,000` on Cloudflare Workers)**: Both `deriveAuthAndEncryptionKeys` and `deriveBlindIndexHmacKey` default to `310,000` PBKDF2 iterations for browser E2EE. On serverless/edge runtimes such as Cloudflare Workers (`workerd`), WebCrypto `crypto.subtle` caps PBKDF2 at `100,000` iterations and throws `NotSupportedError` above `100,000`. Pass `{ iterations: 100_000 }` / `{ kdfIterations: 100_000 }` when deriving keys on edge servers.
|
|
115
|
+
|
|
102
116
|
---
|
|
103
117
|
|
|
104
118
|
## 5. Master Passphrase Re-Keying & Keypair Lifecycle (`rekeyUserKeypair`)
|
|
@@ -106,11 +120,12 @@ const dataKey = derived.encryptionKey
|
|
|
106
120
|
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
121
|
|
|
108
122
|
```ts
|
|
123
|
+
// In production, passphrases must be obtained interactively from the user via secure password prompts
|
|
109
124
|
const result = await CKeyManager.rekeyUserKeypair({
|
|
110
125
|
encryptedPrivateKey: userEncryptedRsaKey,
|
|
111
126
|
encryptedSigningKey: userEncryptedEcdsaKey,
|
|
112
|
-
currentPassphrase:
|
|
113
|
-
newPassphrase:
|
|
127
|
+
currentPassphrase: userPromptCurrentPassword, // Prompted securely from user
|
|
128
|
+
newPassphrase: userPromptNewPassword, // Prompted securely from user
|
|
114
129
|
currentSalt: oldSaltBase64,
|
|
115
130
|
publicKeys: {
|
|
116
131
|
encryption: rsaPublicKey,
|
|
@@ -193,4 +208,10 @@ const summary = await reencryptDataset({
|
|
|
193
208
|
- **Blind Index Synchronization**: Simultaneously generates fresh blind index tokens using `computeWriteBlindIndex` from the active HMAC key and updates `<field>_bidx`.
|
|
194
209
|
- **Bounded Memory & Resumability**: Cursor pagination guarantees flat memory footprint even over millions of rows. Supports `AbortSignal` for graceful pause and resume from `lastProcessedCursor`.
|
|
195
210
|
- **Dry-Run Mode (`dryRun: true`)**: Validates key availability, decodes headers, and simulates re-encryption without invoking `updateRow`.
|
|
211
|
+
- **Resilient Error Strategies (`onRowError` / `abortOnError`)**: `reencryptDataset` defaults `onRowError` to `'record'` so corrupted rows are logged and collected into `failedRows` / `failedRowIds` without halting batch processing (pass `abortOnError: true` or `onRowError: 'abort'` for fail-fast semantics; `reencryptBatch` defaults to `'abort'` unless `onRowError` or `abortOnError: false` is set).
|
|
212
|
+
- **Native Provider AAD Protocol Alignment**: Automatically reconstructs Katlux provider field envelopes (`aad:<base>|record:<id>|ctx:<fields>|field:<name>`) using `getRowId` or standard primary key fallbacks (`id`, `_id`, `uuid`, `key`) with lexicographically sorted `aadFields`, allowing migration without manual `buildAad` callback glue. Automatically retries with `aad: undefined` for legacy unbound envelopes.
|
|
213
|
+
- **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`.
|
|
214
|
+
- **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.
|
|
215
|
+
- **KDF DoS & Iteration Guards**: Enforces `maxAllowedIterations` (default 350,000 ceiling) to prevent iteration amplification attacks from modified envelopes.
|
|
216
|
+
- **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
217
|
|
|
@@ -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,341 @@
|
|
|
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 Deterministic Shadow-Bucket Range Index]**:
|
|
54
|
+
- **Enables**: Range operators (`<`, `<=`, `>`, `>=`, `between`) and coarse bucket sorting.
|
|
55
|
+
- **Controlled Leak**: **Not IND-CPA / Not Zero-Leakage.** Deterministic bucket tokens reveal record value frequency distributions, bucket ordering relations, and distribution profiles (coarse Order-Preserving Encryption equivalence) in companion persistence columns.
|
|
56
|
+
- **Sensitive-Field Block & Per-Class Policy (`ERR_RANGE_BUCKET_SENSITIVE_FIELD`, `ERR_BUCKET_STEP_TOO_NARROW`)**: Fields in `SENSITIVE_RANGE_BUCKET_FIELDS` (`salary`, `income`, `compensation`, `netWorth`, `creditScore`, `ssn`, `age`, `birthDate`, `dateOfBirth`, `dob`) throw `ERR_RANGE_BUCKET_SENSITIVE_FIELD` by default unless `allowSensitiveBucket: true` is explicitly configured. Even with `allowSensitiveBucket: true`, `RANGE_BUCKET_POLICY` (`rangeBucketPolicy`) enforces per-class minimum floors (`10,000` for financial, `1,000,000` for `ssn`, `100` for `creditScore`, `10` for `age`, `'year'`/`'quarter'` for sensitive dates; `DEFAULT_MIN_BUCKET_STEP = 100` for general numeric fields) unless `allowNarrowStep: true` / `allowNarrowGranularity: true` is passed.
|
|
57
|
+
- **Sound-or-Throw Open-Ended Range Contract (`ERR_BUCKET_RANGE_UNBOUNDED`)**: Open-ended range queries (`>`, `>=`, `<`, `<=`) and bucket-universe negations (`!=`, `nin`) on `stepped` or `date` buckets require either `knownBuckets` or explicit domain bounds (`min`/`floor`, `max`/`ceiling`, `minDate`, `maxDate`), throwing `ERR_BUCKET_RANGE_UNBOUNDED` otherwise (no silent truncation).
|
|
58
|
+
- **Security Warning ("Do Not Use" Sensitive Field Guidance)**:
|
|
59
|
+
> [!CAUTION]
|
|
60
|
+
> **DO NOT USE deterministic range buckets on high-sensitivity personal data** (`salary`, `age`, `birthDate`, `dob`, `creditScore`, `income`, `ssn`) unless explicitly authorized by compliance (`allowSensitiveBucket: true`) — distribution profiling and order inference attacks apply. Prefer keeping these columns as unindexed **AES-256-GCM** envelope ciphertext (filtered client-side after decryption), or restrict opt-in usage to broad tier bands (`$25,000+` salary bands) and `'year'`/`'quarter'` date granularity.
|
|
61
|
+
4. **`decryptedCache` [Toggle 4 - Opt-In Client Memory]**:
|
|
62
|
+
- **Enables**: Re-rendering and navigating back and forth across previously loaded pages without re-running CPU-intensive WebCrypto AES decryption.
|
|
63
|
+
- **Controlled Leak**: Decrypted rows are retained in client JavaScript memory (`WeakMap`/RAM) until page unmount.
|
|
64
|
+
- **Security Notice**: Disabled by default (`false`) to ensure high-security terminals automatically garbage-collect decrypted records upon page transitions.
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
### 2.1 Client-Side On-the-Fly Lazy Decryption & Verification Lifecycle
|
|
69
|
+
|
|
70
|
+
A common misconception is that client-side providers decrypt the entire dataset into memory. **They do not**:
|
|
71
|
+
1. **Bulk Ciphertext Storage**: The entire ingested dataset (`allData` / `_data`) remains 100% encrypted in browser memory (`__encrypted_payload__`).
|
|
72
|
+
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.
|
|
73
|
+
3. **Stage-2 Verification Dispatch (`requiresPostVerification`)**:
|
|
74
|
+
- **Exact Matches (`==`, `!=`, discrete array `in`)**: HMAC-SHA256 has zero false positives. Only the active `pageSize` page slice (`_rowMap.slice(startIndex, endIndex)`) is lazily decrypted.
|
|
75
|
+
- **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.
|
|
76
|
+
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.
|
|
77
|
+
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.
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
### 2.2 Server-Side Database Query Limitations
|
|
82
|
+
|
|
83
|
+
When querying encrypted persistence columns on the server (`CAPIFlatServerDataProvider`, `CAPITreeServerDataProvider`, `batchLoad: "onDemand"`):
|
|
84
|
+
- ❌ **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).
|
|
85
|
+
- ❌ **No Database Aggregations**: SQL `SUM(salary)`, `AVG(salary)`, `MIN(salary)` cannot be computed in the database on encrypted columns.
|
|
86
|
+
- ❌ **Substrings $< 3$ Characters**: Substrings with 1 or 2 characters cannot form trigrams and are rejected.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## 3. Field Suitability Matrix ("Hangi Alanlar İçin?")
|
|
91
|
+
|
|
92
|
+
Selecting an appropriate cryptographic representation for application fields requires balancing query utility against privacy exposure:
|
|
93
|
+
|
|
94
|
+
| Storage / Query Strategy | Suitable Fields / Data Types | Required Entropy | Supported Query Capabilities | Information Leakage & Cryptographic Tradeoffs | Recommended Best Practice |
|
|
95
|
+
| :--- | :--- | :--- | :--- | :--- | :--- |
|
|
96
|
+
| **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. |
|
|
97
|
+
| **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. |
|
|
98
|
+
| **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. |
|
|
99
|
+
| **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. |
|
|
100
|
+
| **Deterministic Shadow-Bucket Range Index (`RFC-001` / `TASK-031` / `DEBT-042` / `BUG-093`)** | Coarse dates (`created_at` by year/quarter), non-PII amounts/counters, or compliance-approved broad bands | Low to Medium | Range queries (`>`, `<`, `>=`, `<=`, `BETWEEN`) on discretized bucket keys | **Not zero-leakage.** Reveals bucket membership frequency, bucket order relations, and value distribution profiles (coarse OPE-equivalent leakage). | **Prohibited by default on high-sensitivity PII** (`ERR_RANGE_BUCKET_SENSITIVE_FIELD` on `salary`, `age`, `birthDate`, `dob`, `creditScore`, `ssn`). Leave sensitive attributes unindexed (`AES-256-GCM`) or require explicit `allowSensitiveBucket: true` + per-class floors; supply `knownBuckets` or domain bounds (`min`/`max`, `minDate`/`maxDate`) for open-ended queries (`ERR_BUCKET_RANGE_UNBOUNDED`). |
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 4. Query Rewriting & Multi-Era Keyrings (`rewriteEncryptedFilters`)
|
|
105
|
+
|
|
106
|
+
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:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { rewriteEncryptedFilters, EDataFilterOperator, type IDataFilter } from '@katlux/providers'
|
|
110
|
+
|
|
111
|
+
const blindIndexKeyring = {
|
|
112
|
+
activeKid: 'k2026',
|
|
113
|
+
keys: {
|
|
114
|
+
k2025: { key: hmacKey2025, status: 'search-only' },
|
|
115
|
+
k2026: { key: hmacKey2026, status: 'active' }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// User query on encrypted fields:
|
|
120
|
+
const filters: IDataFilter[] = [
|
|
121
|
+
{ operator: EDataFilterOperator.Equal, field: { email: 'alice@securesuite.io' }, active: true },
|
|
122
|
+
{ operator: 'contains' as any, field: { name: 'Elena' }, active: true },
|
|
123
|
+
{ operator: EDataFilterOperator.GreaterThanOrEqual, field: { orderTotal: 82000 }, active: true }
|
|
124
|
+
]
|
|
125
|
+
|
|
126
|
+
// Pure AST transformation (no SQL / no ORM coupling):
|
|
127
|
+
const rewritten = await rewriteEncryptedFilters(filters, {
|
|
128
|
+
blindIndexFields: {
|
|
129
|
+
email: { column: 'email_bidx', keyring: blindIndexKeyring }
|
|
130
|
+
},
|
|
131
|
+
trigramFields: {
|
|
132
|
+
name: { column: 'name_trigrams', keyring: blindIndexKeyring }
|
|
133
|
+
},
|
|
134
|
+
rangeBuckets: {
|
|
135
|
+
// Open-ended >= without knownBuckets requires explicit max/ceiling (or tier config)
|
|
136
|
+
orderTotal: { type: 'stepped', step: 25000, min: 0, max: 150000 }
|
|
137
|
+
}
|
|
138
|
+
})
|
|
139
|
+
|
|
140
|
+
// Output AST:
|
|
141
|
+
// [
|
|
142
|
+
// { operator: EDataFilterOperator.In, field: { email_bidx: ['token_k2026...', 'token_k2025...'] }, active: true },
|
|
143
|
+
// {
|
|
144
|
+
// operator: EDataFilterOperator.Or,
|
|
145
|
+
// field: [
|
|
146
|
+
// { operator: 'contains', field: { name_trigrams: ['ele_k2026...', 'len_k2026...', 'ena_k2026...'] }, active: true },
|
|
147
|
+
// { operator: 'contains', field: { name_trigrams: ['ele_k2025...', 'len_k2025...', 'ena_k2025...'] }, active: true }
|
|
148
|
+
// ],
|
|
149
|
+
// active: true
|
|
150
|
+
// },
|
|
151
|
+
// { operator: EDataFilterOperator.In, field: { orderTotal_bucket: ['75000-99999', '100000-124999', '125000-149999', '150000-174999'] }, active: true }
|
|
152
|
+
// ]
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### Exact Write-Side Token Recipe (Write↔Query Parity)
|
|
156
|
+
|
|
157
|
+
Every writer (`CKeyManager.computeWriteBlindIndex`, `CSearchIndex`, `reencryptBatch`/`reencryptDataset`) MUST pass the exact same domain separation, normalization, and version options as `rewriteEncryptedFilters`:
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
import { CKeyManager, extractTrigrams, computeBlindIndexSchemeId } from '@katlux/providers'
|
|
161
|
+
|
|
162
|
+
const normalizeOpts = { locale: 'tr', asciiFold: false, normalizerId: 'default' } // must match rewriter!
|
|
163
|
+
const versionOpts = { version: 'v2', versionTag: true } // optional: emits `v2:<hex>`
|
|
164
|
+
|
|
165
|
+
// 1. Exact-match equality token (`_bidx`):
|
|
166
|
+
const emailBidx = await CKeyManager.computeWriteBlindIndex(user.email, blindIndexKeyring, {
|
|
167
|
+
field: 'email',
|
|
168
|
+
type: 'eq',
|
|
169
|
+
...normalizeOpts,
|
|
170
|
+
...versionOpts
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
// 2. Substring trigram tokens (`_trigrams`):
|
|
174
|
+
const nameTrigrams = await Promise.all(
|
|
175
|
+
extractTrigrams(user.name, normalizeOpts).map(tri =>
|
|
176
|
+
CKeyManager.computeWriteBlindIndex(tri, blindIndexKeyring, {
|
|
177
|
+
field: 'name',
|
|
178
|
+
type: 'tri',
|
|
179
|
+
...normalizeOpts,
|
|
180
|
+
...versionOpts
|
|
181
|
+
})
|
|
182
|
+
)
|
|
183
|
+
)
|
|
184
|
+
|
|
185
|
+
// 3. Persist scheme identifier to detect normalization/scope/framing drift:
|
|
186
|
+
const emailScheme = computeBlindIndexSchemeId(normalizeOpts) // e.g. 'lp1|scope=field-type|locale=tr|asciiFold=0|norm=default'
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
- **`kid` Framing Convention (Unified Across Writers & Rewriter)**: Neither writers (`computeWriteBlindIndex`, `reencryptField`, `CSearchIndex`) nor `rewriteEncryptedFilters` include `kid` in the HMAC input by default, because each `kid` in `IBlindIndexKeyring` already maps to a separate cryptographic HMAC key. Pass `kid` explicitly to `computeBlindIndex` only if multiple logical key IDs intentionally share the same raw HMAC key.
|
|
190
|
+
- **Versioned Tokens & Multi-Version Querying**: Pass `version` + `versionTag` (and `previousVersions: ['v1', 'unversioned']` during rolling migrations) to `rewriteEncryptedFilters` (or `IProviderEncryptionOptions`) so queries match both newly migrated `v2:<hex>` rows and older rows. Pass `expectedTokenScheme` to `rewriteEncryptedFilters` to fail fast with `ERR_BIDX_SCHEME_MISMATCH` if query normalization or scope diverges from persisted tokens.
|
|
191
|
+
|
|
192
|
+
### Open-Ended Range & Bucket Negation Behavior
|
|
193
|
+
- **Sound-or-Throw Open-Ended Ranges (`ERR_BUCKET_RANGE_UNBOUNDED`)**:
|
|
194
|
+
- `tier` configs have finite bucket universes and always resolve without `knownBuckets`.
|
|
195
|
+
- `stepped` and `date` configs resolve open-ended queries (`>`, `>=`, `<`, `<=`) against `knownBuckets` when provided, or require explicit domain bounds (`max`/`ceiling` for `>`/`>=`, `min`/`floor` for `<`/`<=` on `stepped`; `maxDate`/`minDate` on `date`). Unbounded open-ended queries throw `ERR_BUCKET_RANGE_UNBOUNDED` instead of silently truncating.
|
|
196
|
+
- **Bucket-Only `!=` and `nin` (Scalar & Array)**:
|
|
197
|
+
- Because coarse buckets contain multiple plaintext values, `!=` and `nin` cannot exclude buckets safely. When `knownBuckets`, `tier`, or fully bounded (`min`+`max` / `minDate`+`maxDate`) config is present, `rewriteEncryptedFilters` emits `IN <all buckets>`; when unbounded without `knownBuckets`, it emits a no-op tautology (`{ operator: 'and', field: [], active: true }`) so it never produces `IN []`.
|
|
198
|
+
|
|
199
|
+
### Safety Guards
|
|
200
|
+
- **Keyring Integrity Guard (`ERR_BIDX_KEYRING_INVALID`)**: Validates `blindIndexFields` and `trigramFields` keyrings (`activeKid` presence, single `'active'` key, and valid HMAC `CryptoKey` objects on every `'active'` and `'search-only'` entry) — missing keys never degrade into empty `contains []` queries.
|
|
201
|
+
- **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.
|
|
202
|
+
- **Unbounded Range Guard (`ERR_BUCKET_RANGE_UNBOUNDED`)**: Open-ended range queries on `stepped` or `date` buckets without `knownBuckets` and without required domain bounds throw `ERR_BUCKET_RANGE_UNBOUNDED`.
|
|
203
|
+
- **Sensitive-Field & Per-Class Width Guards (`ERR_RANGE_BUCKET_SENSITIVE_FIELD`, `ERR_BUCKET_STEP_TOO_NARROW`)**: Sensitive fields (`salary`, `age`, `birthDate`, `dob`, `ssn`, `creditScore`, etc.) are rejected by default unless `allowSensitiveBucket: true` is passed, and per-class minimum floors (`RANGE_BUCKET_POLICY`) are enforced.
|
|
204
|
+
- **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.
|
|
205
|
+
- **Candidate Token Cap (`maxCandidateTokens`)**: Protects against query explosion by limiting generated tokens (default: 500).
|
|
206
|
+
- **Edge / Serverless `kdfIterations` Limit**: `CKeyManager.deriveBlindIndexHmacKey` and `CSearchIndex` default to `310,000` PBKDF2 iterations for browser E2EE. Edge runtimes such as **Cloudflare Workers** cap WebCrypto PBKDF2 at `100,000` iterations (`NotSupportedError`); pass `{ kdfIterations: 100_000 }` (matching between client and server if deriving from the same passphrase) or supply a pre-imported HMAC `CryptoKey`.
|
|
207
|
+
|
|
208
|
+
---
|
|
209
|
+
|
|
210
|
+
## 5. Persistence Schema & Query Execution
|
|
211
|
+
|
|
212
|
+
```sql
|
|
213
|
+
CREATE TABLE users (
|
|
214
|
+
id SERIAL PRIMARY KEY,
|
|
215
|
+
email_encrypted JSONB NOT NULL,
|
|
216
|
+
email_bidx VARCHAR(96) NOT NULL, -- CHAR(64) for unversioned, VARCHAR(96) for tagged e.g. 'v2:<64-hex>'
|
|
217
|
+
email_bidx_version VARCHAR(32), -- optional token version ('v2')
|
|
218
|
+
email_bidx_scheme VARCHAR(128), -- optional scheme id from computeBlindIndexSchemeId()
|
|
219
|
+
email_trigrams TEXT[] NOT NULL,
|
|
220
|
+
email_trigrams_version VARCHAR(32),
|
|
221
|
+
email_trigrams_scheme VARCHAR(128),
|
|
222
|
+
status VARCHAR(50) DEFAULT 'Active'
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
-- Fast B-Tree index for exact lookups:
|
|
226
|
+
CREATE INDEX idx_users_email_bidx ON users (email_bidx);
|
|
227
|
+
|
|
228
|
+
-- Inverted GIN index for substring containment:
|
|
229
|
+
CREATE INDEX idx_users_email_trigrams ON users USING GIN (email_trigrams);
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
Exact match query:
|
|
233
|
+
```sql
|
|
234
|
+
SELECT id, email_encrypted FROM users WHERE email_bidx = ANY($1::text[]);
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Substring query:
|
|
238
|
+
```sql
|
|
239
|
+
-- Single active key & version:
|
|
240
|
+
SELECT id, email_encrypted FROM users WHERE email_trigrams @> $1::text[];
|
|
241
|
+
|
|
242
|
+
-- Multi-era keyring / multi-version (matches the rewritten OR AST across active + search-only kids & previousVersions):
|
|
243
|
+
SELECT id, email_encrypted FROM users
|
|
244
|
+
WHERE email_trigrams @> $1::text[]
|
|
245
|
+
OR email_trigrams @> $2::text[];
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### 5.1 Migration Path: Unframed (Pre-DEBT-036), Unscoped & Unversioned Tokens (Lazy Re-Index)
|
|
249
|
+
|
|
250
|
+
When upgrading existing datasets that contain **pre-DEBT-036 unframed tokens**, **legacy unscoped tokens**, or **unversioned tokens** (or after changing `locale`, `asciiFold`, or `normalizerId`):
|
|
251
|
+
|
|
252
|
+
1. **Zero-Downtime Query Compatibility During Rollout**:
|
|
253
|
+
- **Unscoped tokens**: Set `allowLegacyUnscopedTokens: true` on `CSearchIndex` and/or `IEncryptedFilterRewriteOptions` during migration (keep `false` by default in steady state).
|
|
254
|
+
- **Unversioned / prior-version tokens**: Set `version: 'v2', versionTag: true, previousVersions: ['v1', 'unversioned']` on `rewriteEncryptedFilters` so queries match both migrated (`v2:<hex>`) and legacy (`v1:<hex>` / `<hex>`) rows.
|
|
255
|
+
- **Pre-DEBT-036 unframed tokens**: Unframed tokens are not query-compatible with length-prefixed (`lp1`) HMAC tokens; re-index them from the AES-GCM ciphertext via `reencryptDataset` (or lazily via `reencryptBatch` on read/login).
|
|
256
|
+
2. **Background or Lazy Re-Index via `reencryptDataset` (No AES Churn Required)**:
|
|
257
|
+
`reencryptDataset` / `reencryptBatch` automatically detects stale `_version`, missing `versionTag:` prefixes, or drifted `_scheme` values even when `envelope.kid === targetKid` (recomputing only the blind-index columns without re-encrypting AES envelopes):
|
|
258
|
+
|
|
259
|
+
```ts
|
|
260
|
+
import { reencryptDataset } from '@katlux/providers'
|
|
261
|
+
|
|
262
|
+
await reencryptDataset({
|
|
263
|
+
targetKid: 'aes-v2',
|
|
264
|
+
keyring: { 'aes-v1': aesKeyV1, 'aes-v2': aesKeyV2 },
|
|
265
|
+
encryptedFields: ['email', 'name'],
|
|
266
|
+
trigramFields: ['name'],
|
|
267
|
+
locale: 'tr',
|
|
268
|
+
// Select only rows with missing/old token versions (or omit to auto-detect any version/scheme drift):
|
|
269
|
+
staleTokenVersions: ['unversioned', 'v1'],
|
|
270
|
+
blindIndex: {
|
|
271
|
+
fields: ['email'],
|
|
272
|
+
keyring: blindIndexKeyring,
|
|
273
|
+
version: 'v2',
|
|
274
|
+
versionTag: true,
|
|
275
|
+
persistScheme: true // writes `${col}_scheme` using computeBlindIndexSchemeId()
|
|
276
|
+
},
|
|
277
|
+
// Opt out of field+type domain separation ONLY if targeting a legacy unscoped schema:
|
|
278
|
+
// legacyUnscopedTokens: true,
|
|
279
|
+
fetchBatch: (cursor, limit) => db.fetchStaleUsers(cursor, limit),
|
|
280
|
+
updateRow: (id, patch, expectedVersion) => db.updateUserCas(id, patch, expectedVersion)
|
|
281
|
+
})
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
For **lazy on-read migration**, pass `[row]` to `reencryptBatch([row], { ...sameOptions })` when `isFieldBlindIndexStale(row, 'email', opts)` is true (or `row.email_bidx_version !== 'v2'`), persist `result.rows[0].patch`, and then remove `allowLegacyUnscopedTokens` / `previousVersions` once backfill completes.
|
|
285
|
+
|
|
286
|
+
---
|
|
287
|
+
|
|
288
|
+
## 6. Deterministic Shadow-Bucket Range Index Recipes & Security Disclaimer (`TASK-031` / `DEBT-042` / `BUG-093`)
|
|
289
|
+
|
|
290
|
+
> [!CAUTION]
|
|
291
|
+
> **Security Disclaimer & Sensitive Field Policy (`ERR_RANGE_BUCKET_SENSITIVE_FIELD`)**:
|
|
292
|
+
> `rangeBuckets` implements a **Deterministic Shadow-Bucket Range Index**, NOT a zero-leakage or IND-CPA scheme. Observers with access to persistence columns or queries can infer **value frequency distributions**, **bucket ordering relations**, and **empirical distribution profiles** across records.
|
|
293
|
+
> - **Default Sensitive-Field Prohibition**: Fields in `SENSITIVE_RANGE_BUCKET_FIELDS` (`salary`, `income`, `compensation`, `netWorth`, `creditScore`, `ssn`, `age`, `birthDate`, `dateOfBirth`, `dob`) throw `ERR_RANGE_BUCKET_SENSITIVE_FIELD` by default unless `allowSensitiveBucket: true` is explicitly configured.
|
|
294
|
+
> - **Per-Class Minimum Width Floors (`RANGE_BUCKET_POLICY` / `ERR_BUCKET_STEP_TOO_NARROW`)**: Even with `allowSensitiveBucket: true`, per-class floors are enforced (`10,000` for financial, `1,000,000` for `ssn`, `100` for `creditScore`, `10` for `age`, `'year'`/`'quarter'` for sensitive dates; `DEFAULT_MIN_BUCKET_STEP = 100` for non-sensitive fields) unless `allowNarrowStep: true` / `allowNarrowGranularity: true` is also opted into.
|
|
295
|
+
|
|
296
|
+
To support coarse range filtering (`<`, `<=`, `>`, `>=`, `between`) on encrypted numeric or date columns under these constraints, configure `rangeBuckets` on non-sensitive fields with explicit bounds (or `knownBuckets`):
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
import { CFlatClientDataProvider, EDataFilterOperator } from '@katlux/providers'
|
|
300
|
+
|
|
301
|
+
const provider = new CFlatClientDataProvider({
|
|
302
|
+
idKey: 'id',
|
|
303
|
+
pageSize: 10,
|
|
304
|
+
encryption: {
|
|
305
|
+
enabled: true,
|
|
306
|
+
key: 'master-encryption-secret',
|
|
307
|
+
fields: ['orderTotal', 'createdAt'],
|
|
308
|
+
rangeBuckets: {
|
|
309
|
+
// Broad tier bands for commercial order amounts
|
|
310
|
+
orderTotal: { type: 'tier', thresholds: [0, 25000, 50000, 75000, 100000, 250000] },
|
|
311
|
+
createdAt: { type: 'date', granularity: 'quarter', minDate: '2024-01-01', maxDate: '2027-12-31' }
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
})
|
|
315
|
+
|
|
316
|
+
// Query: orderTotal >= 82000
|
|
317
|
+
// Stage 1 (Coarse Matching): CSearchIndex resolves eligible tier keys ('75000-99999', '100000-249999', '>=250000')
|
|
318
|
+
// Stage 2 (Fine-Grained Verification): Provider lazily decrypts the current page slice and eliminates false positives (e.g. 76k)
|
|
319
|
+
provider.setFilter({
|
|
320
|
+
operator: EDataFilterOperator.GreaterThanOrEqual,
|
|
321
|
+
field: { orderTotal: 82000 },
|
|
322
|
+
active: true
|
|
323
|
+
})
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
If compliance explicitly permits coarse bucketing on a sensitive field (e.g. broad `$25,000+` compensation tiers or `'year'` birth dates), opt in with `allowSensitiveBucket: true`:
|
|
327
|
+
|
|
328
|
+
```ts
|
|
329
|
+
rangeBuckets: {
|
|
330
|
+
salary: { type: 'tier', thresholds: [0, 25000, 50000, 100000, 250000], allowSensitiveBucket: true },
|
|
331
|
+
birthDate: { type: 'date', granularity: 'year', allowSensitiveBucket: true, minDate: '1920-01-01', maxDate: '2026-12-31' }
|
|
332
|
+
}
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
### Supported Bucketing Strategies & Date Parsing Rules
|
|
336
|
+
- **Date Granularities**: `'year'` (`2026`), `'quarter'` (`2026-Q1`), `'month'` (`2026-03`), `'week'` (`2026-W08`), `'day'` (`2026-03-15`). Sensitive date fields (`birthDate`, `dateOfBirth`, `dob`) require `allowSensitiveBucket: true` and reject `'month'`, `'week'`, and `'day'` with `ERR_BUCKET_STEP_TOO_NARROW` unless `allowNarrowGranularity: true` is also set. Open-ended `>`/`>=` requires `maxDate` (or `knownBuckets`) and `<`/`<=` requires `minDate` (or `knownBuckets`), throwing `ERR_BUCKET_RANGE_UNBOUNDED` otherwise.
|
|
337
|
+
- **`parseDateValue` Timestamp Heuristic & UTC Anchoring**: Numeric timestamps with `|v| < 1e10` are treated as **Unix seconds** (covering ~1653..2286 in seconds, including negative pre-1970 seconds) and multiplied by `1000`; values with `|v| >= 1e10` are treated as **Unix milliseconds** (including negative pre-1973 ms timestamps such as `1960-01-01`: `-315619200000`). Timezone-naive ISO/SQL strings (`'2023-05-15'`, `'2023-05-15 00:30:00'`) are parsed deterministically as **UTC** so bucket keys do not shift across host timezones.
|
|
338
|
+
- **Stepped Numeric**: `{ type: 'stepped', step: 25000, min?: 0, max?: 250000, minStep?: number, allowNarrowStep?: boolean, allowSensitiveBucket?: boolean }` -> `'0-24999'`, `'25000-49999'`, `'75000-99999'`. Rejects widths below `DEFAULT_MIN_BUCKET_STEP` (`100`) or per-class floor with `ERR_BUCKET_STEP_TOO_NARROW`. Open-ended `>`/`>=` requires `max`/`ceiling` (or `knownBuckets`) and `<`/`<=` requires `min`/`floor` (or `knownBuckets`), throwing `ERR_BUCKET_RANGE_UNBOUNDED` otherwise.
|
|
339
|
+
- **Threshold / Tier Numeric (Recommended when coarse bands suffice)**: `{ type: 'tier', thresholds: [0, 25000, 50000, 100000, 250000] }` -> `'<0'`, `'0-24999'`, `'25000-49999'`, `'50000-99999'`, `'>=250000'`. Enforces minimum threshold gaps unless overridden and resolves open-ended ranges natively without `knownBuckets`.
|
|
340
|
+
|
|
341
|
+
|