@katlux/toolkit 0.1.1-alpha.128 → 0.1.1-alpha.130
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/add-ai-reference.mjs +85 -46
- package/dist/module.json +1 -1
- 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/KCombobox/KCombobox.global.d.vue.ts +3 -3
- package/dist/runtime/components/KCombobox/KCombobox.global.vue.d.ts +3 -3
- package/dist/runtime/components/KCompositeInput/KCompositeInput.global.d.vue.ts +6 -6
- package/dist/runtime/components/KCompositeInput/KCompositeInput.global.vue.d.ts +6 -6
- package/dist/runtime/components/KDatePicker/KDatePicker.global.d.vue.ts +1 -1
- package/dist/runtime/components/KDatePicker/KDatePicker.global.vue.d.ts +1 -1
- package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.d.vue.ts +1 -1
- package/dist/runtime/components/KDateTimePicker/KDateTimePicker.global.vue.d.ts +1 -1
- 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/KPagination/KPagination.global.d.vue.ts +1 -1
- package/dist/runtime/components/KPagination/KPagination.global.vue.d.ts +1 -1
- package/dist/runtime/components/KTree/KTree.global.d.vue.ts +1 -1
- package/dist/runtime/components/KTree/KTree.global.vue.d.ts +1 -1
- package/dist/runtime/components/KTreePicker/KTreePicker.global.d.vue.ts +2 -2
- package/dist/runtime/components/KTreePicker/KTreePicker.global.vue.d.ts +2 -2
- package/dist/runtime/presets/default/components/KTree/KTree.d.vue.ts +1 -1
- package/dist/runtime/presets/default/components/KTree/KTree.vue.d.ts +1 -1
- package/dist/skills/KATLUX_INDEX.md +40 -0
- package/dist/skills/katlux-components/SKILL.md +106 -0
- package/dist/skills/katlux-components/components/KAccordion.md +27 -0
- package/dist/skills/katlux-components/components/KAlert.md +22 -0
- package/dist/skills/katlux-components/components/KAreaChart.md +19 -0
- package/dist/skills/katlux-components/components/KBarChart.md +20 -0
- package/dist/skills/katlux-components/components/KBulkActions.md +19 -0
- package/dist/skills/katlux-components/components/KButton.md +12 -0
- package/dist/skills/katlux-components/components/KCalendar.md +17 -0
- package/dist/skills/katlux-components/components/KCheckbox.md +15 -0
- package/dist/skills/katlux-components/components/KCombobox.md +41 -0
- package/dist/skills/katlux-components/components/KCompositeInput.md +67 -0
- package/dist/skills/katlux-components/components/KContextMenu.md +20 -0
- package/dist/skills/katlux-components/components/KDataIterator.md +35 -0
- package/dist/skills/katlux-components/components/KDatatable.md +55 -0
- package/dist/skills/katlux-components/components/KDatePicker.md +26 -0
- package/dist/skills/katlux-components/components/KDropdown.md +18 -0
- package/dist/skills/katlux-components/components/KGantt.md +28 -0
- package/dist/skills/katlux-components/components/KGrid.md +17 -0
- package/dist/skills/katlux-components/components/KHeatMap.md +32 -0
- package/dist/skills/katlux-components/components/KHourSelect.md +11 -0
- package/dist/skills/katlux-components/components/KIcon.md +5 -0
- package/dist/skills/katlux-components/components/KLayout.md +34 -0
- package/dist/skills/katlux-components/components/KLineChart.md +18 -0
- package/dist/skills/katlux-components/components/KLoader.md +7 -0
- package/dist/skills/katlux-components/components/KMaskTextbox.md +12 -0
- package/dist/skills/katlux-components/components/KModal.md +22 -0
- package/dist/skills/katlux-components/components/KPagination.md +22 -0
- package/dist/skills/katlux-components/components/KPanel.md +18 -0
- package/dist/skills/katlux-components/components/KPieChart.md +14 -0
- package/dist/skills/katlux-components/components/KProductList.md +42 -0
- package/dist/skills/katlux-components/components/KScatterChart.md +20 -0
- package/dist/skills/katlux-components/components/KSlider.md +28 -0
- package/dist/skills/katlux-components/components/KTabs.md +31 -0
- package/dist/skills/katlux-components/components/KTextbox.md +15 -0
- package/dist/skills/katlux-components/components/KToast.md +14 -0
- package/dist/skills/katlux-components/components/KTooltip.md +13 -0
- package/dist/skills/katlux-components/components/KTree.md +45 -0
- package/dist/skills/katlux-components/components/KTreePicker.md +35 -0
- package/dist/skills/katlux-components/components/KTreeView.md +30 -0
- package/dist/skills/katlux-components/components/MultiTabs.md +20 -0
- package/dist/skills/katlux-components/components/calendar-customization.md +6 -0
- package/dist/skills/katlux-components/components/datatable-customization.md +14 -0
- package/dist/skills/katlux-components/components/directives.md +11 -0
- package/dist/skills/katlux-components/components/form-validation.md +125 -0
- package/dist/skills/katlux-components/components/tree-customization.md +9 -0
- package/dist/skills/katlux-components/components/useToast.md +27 -0
- package/dist/skills/katlux-components/components/validation-directives.md +6 -0
- package/dist/skills/katlux-config/SKILL.md +156 -0
- package/dist/skills/katlux-presets/SKILL.md +356 -0
- package/dist/skills/katlux-providers/SKILL.md +64 -0
- package/dist/skills/katlux-providers/providers/ADataProvider.md +59 -0
- package/dist/skills/katlux-providers/providers/CAPIFlatClientDataProvider.md +28 -0
- package/dist/skills/katlux-providers/providers/CAPIFlatServerDataProvider.md +20 -0
- package/dist/skills/katlux-providers/providers/CFlatClientDataProvider.md +11 -0
- package/dist/skills/katlux-providers/providers/CFlatServerDataProvider.md +58 -0
- package/dist/skills/katlux-providers/providers/CTreeClientDataProvider.md +14 -0
- package/dist/skills/katlux-providers/providers/CTreeServerDataProvider.md +5 -0
- package/dist/skills/katlux-providers/providers/KatluxIndexedDB.md +10 -0
- package/dist/skills/katlux-providers/providers/RequestProvider.md +49 -0
- package/dist/skills/katlux-providers/providers/RequestQueue.md +52 -0
- package/dist/skills/katlux-providers/providers/api-protocol.md +40 -0
- package/dist/skills/katlux-providers/providers/caching.md +170 -0
- package/dist/skills/katlux-providers/providers/composables.md +107 -0
- package/dist/skills/katlux-providers/providers/encryption.md +151 -0
- package/dist/skills/katlux-providers/providers/react-integration.md +45 -0
- package/dist/skills/katlux-providers/providers/testing-isolation.md +6 -0
- package/dist/skills/katlux-providers/providers/types.md +27 -0
- package/dist/skills/katlux-providers/providers/useDataProvider.md +51 -0
- package/dist/skills/katlux-tokens/SKILL.md +133 -0
- package/package.json +3 -3
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
### `RequestProvider`
|
|
2
|
+
The core engine for all HTTP communication, supporting deduplication, tag-based registry auto-refreshes, offline mutation queuing, and caching.
|
|
3
|
+
- **Methods**:
|
|
4
|
+
| Method | Params | Description |
|
|
5
|
+
| --- | --- | --- |
|
|
6
|
+
| `registerRequest<T>(url, opts)` | `string, IRequestOptions` | Executes a request with deduplication, offline enqueuing (for mutations with `queue: true`), or tag-based registry notifications |
|
|
7
|
+
| `setCacheProvider(provider)` | `ACacheProvider \| ECacheStrategy` | Configures global caching strategy |
|
|
8
|
+
| `setCacheLifetime(ms)` | `number` | Sets default global expiration (milliseconds) |
|
|
9
|
+
| `setDeduplicate(bool)` | `boolean` | Toggle request deduplication |
|
|
10
|
+
| `onDataReceived(cb)` | `(data: any, generation?: number) => void` | Registers a callback triggered when data is successfully received (passes request generation if available) |
|
|
11
|
+
| `refresh(hardRefresh)` | `boolean` | Re-runs the last request. Cache will only be overridden if `hardRefresh` parameter is true. |
|
|
12
|
+
|
|
13
|
+
- **Constructor**: `new RequestProvider(provider?, lifetime?, deduplicate?, tags?)`
|
|
14
|
+
- `provider`: `ACacheProvider | ECacheStrategy` — optional default cache backend
|
|
15
|
+
- `lifetime`: `number` — optional default cache lifetime in ms
|
|
16
|
+
- `deduplicate`: `boolean` — optional deduplication toggle (default `true`)
|
|
17
|
+
- `tags`: `string[]` — optional tag array for subscription to `RequestProviderRegistry`
|
|
18
|
+
|
|
19
|
+
- **`IRequestOptions` Properties**:
|
|
20
|
+
| Property | Type | Description |
|
|
21
|
+
| --- | --- | --- |
|
|
22
|
+
| `method` | `string` | HTTP method (`'GET'`, `'POST'`, `'PUT'`, `'DELETE'`, `'PATCH'`. Default: `'GET'`) |
|
|
23
|
+
| `body` | `any` | Request body data |
|
|
24
|
+
| `query` | `Record<string, any>` | URL query parameters |
|
|
25
|
+
| `headers` | `Record<string, string>` | Custom HTTP headers |
|
|
26
|
+
| `cacheStrategy` | `ECacheStrategy` | Override global strategy for this request |
|
|
27
|
+
| `lifetime` | `number` | Override global expiration for this request |
|
|
28
|
+
| `key` | `string` | Custom unique key for caching/deduplication |
|
|
29
|
+
| `cacheKey` | `string` | Namespace/context key for shared cache storage |
|
|
30
|
+
| `deduplicate` | `boolean` | Override global deduplication setting |
|
|
31
|
+
| `disableCache` | `boolean` | Explicitly override cache for this request |
|
|
32
|
+
| `tags` | `string[]` | Associated tags for invalidation / auto-refresh upon mutation |
|
|
33
|
+
| `queue` | `boolean` | When true (for non-GET requests), enqueues the mutation into `RequestQueue` instead of dispatching immediately |
|
|
34
|
+
| `label` | `string` | Human-readable description for queued mutation display in UI |
|
|
35
|
+
| `nuxtApp` | `any` | Nuxt app instance — enables SSR cookie forwarding via h3 |
|
|
36
|
+
| `_generation` | `number` | Internal request generation counter to discard stale responses |
|
|
37
|
+
|
|
38
|
+
### `RequestProviderRegistry`
|
|
39
|
+
Framework-agnostic static registry mapping active `RequestProvider` instances to tag arrays. When mutations complete (or offline queues flush), `RequestProviderRegistry` automatically triggers `refresh(true)` on all matching registered GET providers.
|
|
40
|
+
|
|
41
|
+
- **Static Methods**:
|
|
42
|
+
| Method | Params | Description |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| `register(provider, tags)` | `RequestProvider, string[]` | Subscribes a provider instance to the specified tags |
|
|
45
|
+
| `unregister(provider)` | `RequestProvider` | Removes a provider instance from the registry |
|
|
46
|
+
| `notifyMutation(tags)` | `string[]` | Refreshes all GET providers registered under any of the specified tags (deduplicated) |
|
|
47
|
+
| `refreshByTag(tag)` | `string` | Refreshes all GET providers registered under the given tag |
|
|
48
|
+
| `getEntries()` | None | Returns all active `{ provider, tags }` registry entries |
|
|
49
|
+
| `clear()` | None | Clears all registered providers |
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
### `RequestQueue` (Offline PWA Queue)
|
|
2
|
+
Static persistent queue manager for queuing mutations offline and flushing them when connectivity is restored.
|
|
3
|
+
|
|
4
|
+
- **Storage Options (`EQueueStorage`)**: `IndexedDB` (default, stored under `KatluxDB`), `LocalStorage`, `Memory`. Automatically falls back if a backend is unavailable.
|
|
5
|
+
- **Native State**:
|
|
6
|
+
- `RequestQueue.queue`: `IQueuedOperation[]` — Pure native array of pending queued mutations.
|
|
7
|
+
- `RequestQueue.deadLetterQueue`: `IDeadLetterItem[]` — Pure native array of permanently failed operations (4xx/5xx errors).
|
|
8
|
+
- `RequestQueue.isFlushing`: `boolean` — Boolean flag indicating active flush state.
|
|
9
|
+
- `RequestQueue.subscribe(listener: () => void): () => void` — Observer subscription hook.
|
|
10
|
+
- **Vue 3 Integration (`useRequestQueue` composable from `@katlux/toolkit`)**:
|
|
11
|
+
```typescript
|
|
12
|
+
import { useRequestQueue } from '#toolkit/composables/useRequestQueue'
|
|
13
|
+
|
|
14
|
+
const {
|
|
15
|
+
queue, // Ref<IQueuedOperation[]>
|
|
16
|
+
deadLetterQueue, // Ref<IDeadLetterItem[]>
|
|
17
|
+
isFlushing, // Ref<boolean>
|
|
18
|
+
enqueue,
|
|
19
|
+
flushAll,
|
|
20
|
+
flushOne,
|
|
21
|
+
retryOne,
|
|
22
|
+
discard,
|
|
23
|
+
init,
|
|
24
|
+
setStorageBackend
|
|
25
|
+
} = useRequestQueue()
|
|
26
|
+
```
|
|
27
|
+
- **Flushing Behavior**:
|
|
28
|
+
- Processed in **FIFO order** (first in, first out).
|
|
29
|
+
- **Stop-on-first-error**: Execution halts immediately if an item fails to preserve queue dependency integrity.
|
|
30
|
+
- **Dead-letter handling**: Server errors (4xx/5xx) move the failed operation to `deadLetterQueue` with `failedAt`, `lastError`, and `httpStatus`.
|
|
31
|
+
- **Dead-letter capacity guard**: When `deadLetterQueue` reaches `MAX_DEAD_LETTER_SIZE`, subsequent additions halt to prevent silent data loss, emitting to `onError` without unhandled promise rejections.
|
|
32
|
+
- **Network errors**: If fetch fails due to connectivity (no HTTP response), the item remains in `queue` for subsequent retry.
|
|
33
|
+
- **Partial refresh**: Successfully processed item tags trigger `RequestProviderRegistry.notifyMutation()` immediately.
|
|
34
|
+
- **Static Methods**:
|
|
35
|
+
| Method | Params | Description |
|
|
36
|
+
| --- | --- | --- |
|
|
37
|
+
| `init()` | None | Initializes queue storage backend and loads persisted state |
|
|
38
|
+
| `setStorageBackend(type)` | `EQueueStorage` | Sets storage backend (`IndexedDB`, `LocalStorage`, `Memory`) |
|
|
39
|
+
| `enqueue(item)` | `IQueuedOperationInput` | Adds a mutation item to the queue |
|
|
40
|
+
| `flushAll(options?)` | `{ tag?: string }` | Flushes queued operations in FIFO order |
|
|
41
|
+
| `flushOne(id)` | `string` | Dispatches a specific queued item by ID |
|
|
42
|
+
| `retryOne(id)` | `string` | Moves a dead-letter item back to the FRONT of the pending queue |
|
|
43
|
+
| `discard(id)` | `string` | Permanently removes an item from `queue` or `deadLetterQueue` |
|
|
44
|
+
| `reorder(ids)` | `string[]` | Reorders pending operations by ID array |
|
|
45
|
+
| `setMaxPayloadSize(bytes)` | `number` | Sets maximum allowed mutation payload size (default: 5MB) |
|
|
46
|
+
| `setMaxQueueSize(limit)` | `number` | Sets maximum pending queue capacity with FIFO eviction (default: 500) |
|
|
47
|
+
| `setMaxDeadLetterSize(limit)` | `number` | Sets maximum dead-letter queue capacity before halting (default: 200) |
|
|
48
|
+
| `onDeadLetter(cb)` | `(item, err) => void` | Event listener fired when an item enters dead-letter |
|
|
49
|
+
| `onFlushComplete(cb)` | `(succeededTags) => void` | Event listener fired when a flush finishes with successes |
|
|
50
|
+
| `onNetworkError(cb)` | `(err) => void` | Event listener fired when a flush halts due to offline network error |
|
|
51
|
+
| `onError(cb)` | `(err) => void` | Event listener fired on fatal queue or capacity errors |
|
|
52
|
+
| `onQueueFatalError(cb)` | `(err) => void` | Alias for `onError` |
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
## 3.8. API Communication Protocol (Server-Side)
|
|
2
|
+
When using `CAPIFlatServerDataProvider` or `CAPITreeServerDataProvider`, the requested URL will include the following query string parameters.
|
|
3
|
+
|
|
4
|
+
### Standard Parameters (Flat & Tree)
|
|
5
|
+
| Parameter | Type | Description |
|
|
6
|
+
| --- | --- | --- |
|
|
7
|
+
| `pageNumber` | `number` | Current 1-based page index |
|
|
8
|
+
| `pageSize` | `number` | Items per page (0 = no pagination) |
|
|
9
|
+
| `filter` | `JSON` | Serialized `IDataFilter` object |
|
|
10
|
+
| `sortList` | `JSON` | Serialized `IDataSort[]` array |
|
|
11
|
+
|
|
12
|
+
### Tree-Specific Parameters
|
|
13
|
+
| Parameter | Type | Description |
|
|
14
|
+
| --- | --- | --- |
|
|
15
|
+
| `expandedNodes` | `JSON` | Stringified array of expanded node IDs |
|
|
16
|
+
| `parentKey` | `string` | Field key for ancestor reference |
|
|
17
|
+
| `idKey` | `string` | Field key for unique identifier |
|
|
18
|
+
| `paginateBy` | `string` | `'all'` or `'root'` |
|
|
19
|
+
| `expandedByDefault`| `boolean` | Initial expansion state |
|
|
20
|
+
|
|
21
|
+
### Filter JSON Structure Example
|
|
22
|
+
```json
|
|
23
|
+
{
|
|
24
|
+
"operator": "in",
|
|
25
|
+
"field": { "product_name": "mont" },
|
|
26
|
+
"active": true
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Complex Filter (OR) Example
|
|
31
|
+
```json
|
|
32
|
+
{
|
|
33
|
+
"operator": "or",
|
|
34
|
+
"field": [
|
|
35
|
+
{ "operator": "==", "field": { "status": "active" }, "active": true },
|
|
36
|
+
{ "operator": "==", "field": { "priority": "high" }, "active": true }
|
|
37
|
+
],
|
|
38
|
+
"active": true
|
|
39
|
+
}
|
|
40
|
+
```
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
### `CacheProvider` (Interface: `ACacheProvider`)
|
|
2
|
+
Standard interface for persistence strategies. **Note**: `ACacheProvider` is an abstract class and cannot be instantiated with `new`.
|
|
3
|
+
|
|
4
|
+
- **`CacheProviderFactory`**: The primary way to obtain a cache provider instance. Unused cache drivers are dynamically loaded and tree-shaken from initial application bundles.
|
|
5
|
+
- `CacheProviderFactory.getProvider(strategy: ECacheStrategy | string): Promise<ACacheProvider | null>`: Asynchronously loads and returns the singleton instance for the specified strategy.
|
|
6
|
+
- `CacheProviderFactory.getProviderSync(strategy: ECacheStrategy | string): ACacheProvider | undefined`: Synchronously returns the singleton instance if already loaded.
|
|
7
|
+
- `CacheProviderFactory.registerDriver(strategy: string, loaderOrClass)`: Registers a custom cache strategy driver or pre-loaded class.
|
|
8
|
+
- `CacheProviderFactory.clearInstances()`: Clears the singleton cache.
|
|
9
|
+
- **Direct Access**: Individual providers (e.g., `CMemoryCache`, `CLocalStorageCache`) can also be accessed via their static `getInstance()` method.
|
|
10
|
+
|
|
11
|
+
> [!NOTE]
|
|
12
|
+
> All `CacheProvider` methods are asynchronous and return a **Promise**. This is required to support non-blocking storage engines like **IndexedDB**.
|
|
13
|
+
|
|
14
|
+
- **Supported Strategies & Execution Scopes**:
|
|
15
|
+
- **Server-Side Caches (Stateful Node.js Runtimes)**:
|
|
16
|
+
- `Application`: Global server-level cache (`CApplicationCache`). Shared across all visitors on the Node.js server (e.g. homepage featured product lists). Never hydrated to the client. Note: In-memory server caches are not supported on stateless/serverless runtimes (e.g. Cloudflare Workers).
|
|
17
|
+
- `ServerSession`: Per-session server-side in-memory cache (`CServerSessionCache`). Emulates traditional server sessions (PHP-style) keyed by session ID. Confined strictly to the server — all methods are server-only with zero client execution paths. Never hydrated to the client. Uses lazy TTL eviction on `get()` and bounded LRU eviction (`MAX_SERVER_SESSIONS = 5000`) on `set()` — no background timers. Note: Not supported on stateless/serverless runtimes.
|
|
18
|
+
- **Client-Side Caches (Browser Execution)**:
|
|
19
|
+
- `BrowserSession`: Tab-lifetime browser cache (`CBrowserSessionCache`). Backed by `window.sessionStorage` with prefix `'bscache:'`. On the server during SSR, `set()` writes only to the SSR context payload; on first client-side `get()` miss, the entry is promoted from the payload into `sessionStorage` (hydration). All other server-side methods are no-ops.
|
|
20
|
+
- `Memory`: In-memory storage (`CMemoryCache`). Kept in client memory; cleared on page reload. On the server, strictly scoped to the per-request SSR payload for client hydration.
|
|
21
|
+
- `LocalStorage`: Browser `localStorage` (`CLocalStorageCache`). Persistent across browser restarts and tabs.
|
|
22
|
+
- `IndexedDB`: Large-scale browser storage (`CIndexedDBCache`, managed via `KatluxIndexedDB`).
|
|
23
|
+
- `Cookie`: Browser cookies with optional server-side read/write via `h3` (`CCookieCache`). Configurable `sameSite`, `secure` (auto-detected), `httpOnly`, `path` — see *Cookie Security Options* below.
|
|
24
|
+
- **Methods (All return `Promise`)**:
|
|
25
|
+
| Method | Params | Description |
|
|
26
|
+
| --- | --- | --- |
|
|
27
|
+
| `get<T>(key)` | `string` | Retrieves cached value |
|
|
28
|
+
| `set<T>(key, val, life)`| `string, any, number`| Persists value with lifetime (ms) |
|
|
29
|
+
| `remove(key)` | `string` | Evicts specific entry |
|
|
30
|
+
| `removeByPrefix(pre)`| `string` | Bulk eviction (e.g., by resource URL) |
|
|
31
|
+
| `getRemainingTime(key)`| `string` | Returns remaining TTL in ms |
|
|
32
|
+
| `cleanupExpired()` | None | Purges stale entries |
|
|
33
|
+
| `getKeyList()` | None | Returns all active cache keys |
|
|
34
|
+
|
|
35
|
+
#### Cookie Security Options (`CCookieCache`)
|
|
36
|
+
Cookie flags are plain constructor options on the cache itself; there is no separate session layer:
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
import { CCookieCache } from '@katlux/providers'
|
|
40
|
+
|
|
41
|
+
const cache = new CCookieCache({ sameSite: 'strict', path: '/app' })
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
| Option | Default | Notes |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| `sameSite` | `'lax'` | `'strict' \| 'lax' \| 'none'`. First line of CSRF defense for cookie-authenticated requests. |
|
|
47
|
+
| `secure` | auto | Follows the request protocol (https => `Secure`). On the server it uses h3 `getRequestProtocol` (honours `x-forwarded-proto`); on the client `location.protocol`. Set `true`/`false` to force. |
|
|
48
|
+
| `httpOnly` | `true` | **Server-written cookies only.** Browsers do not let `document.cookie` set `HttpOnly`, so client writes ignore it. Because of this, a cookie written on the server is not readable by `CCookieCache.get()` in the browser. |
|
|
49
|
+
| `path` | `'/'` | Cookie path scope. |
|
|
50
|
+
|
|
51
|
+
> [!WARNING]
|
|
52
|
+
> Do not keep auth tokens in `BrowserSession`, `LocalStorage`, `Memory`, or a client-written `Cookie`: any XSS can read them. Keep credentials in a server-set `HttpOnly` cookie. The cache strategies are for **application data** (query results, table pages, chart series), not identity. Cookies are also capped at ~4 KB and are sent on every request, so `CCookieCache` skips oversized writes.
|
|
53
|
+
|
|
54
|
+
> [!NOTE]
|
|
55
|
+
> CSRF tokens and Content Security Policy headers are application/server concerns and are intentionally not part of `@katlux/providers`. See the *Security* section in the `katlux-config` skill.
|
|
56
|
+
|
|
57
|
+
#### Registering a Custom Cache Strategy
|
|
58
|
+
|
|
59
|
+
To create a custom caching backend (e.g. Redis, WebWorker, LRU cache, or multi-tab BroadcastChannel), follow these three steps:
|
|
60
|
+
|
|
61
|
+
**Step 1 — Subclass `ACacheProvider`**:
|
|
62
|
+
Implement all abstract methods and provide a static `getInstance()` method.
|
|
63
|
+
|
|
64
|
+
```typescript
|
|
65
|
+
import { ACacheProvider, type ICacheEntry } from '@katlux/providers'
|
|
66
|
+
|
|
67
|
+
export class CMyCustomCache extends ACacheProvider {
|
|
68
|
+
private static instance: CMyCustomCache | null = null
|
|
69
|
+
private storage = new Map<string, ICacheEntry<any>>()
|
|
70
|
+
|
|
71
|
+
public static getInstance(): CMyCustomCache {
|
|
72
|
+
if (!this.instance) {
|
|
73
|
+
this.instance = new CMyCustomCache()
|
|
74
|
+
}
|
|
75
|
+
return this.instance
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async getKeyList(nuxtApp?: any): Promise<string[]> {
|
|
79
|
+
return Array.from(this.storage.keys())
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async get<T>(key: string, nuxtApp?: any): Promise<T | null> {
|
|
83
|
+
const entry = this.storage.get(key)
|
|
84
|
+
if (!entry) return null
|
|
85
|
+
if (Date.now() > entry.timestamp + entry.lifetime) {
|
|
86
|
+
this.storage.delete(key)
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
return entry.data as T
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async set<T>(key: string, data: T, lifetime: number, nuxtApp?: any): Promise<void> {
|
|
93
|
+
this.storage.set(key, { data, timestamp: Date.now(), lifetime })
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async remove(key: string, nuxtApp?: any): Promise<void> {
|
|
97
|
+
this.storage.delete(key)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async removeByPrefix(prefix: string, nuxtApp?: any): Promise<void> {
|
|
101
|
+
for (const key of this.storage.keys()) {
|
|
102
|
+
if (key.startsWith(prefix)) this.storage.delete(key)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async getRemainingTime(key: string, nuxtApp?: any): Promise<number | null> {
|
|
107
|
+
const entry = this.storage.get(key)
|
|
108
|
+
if (!entry) return null
|
|
109
|
+
const remaining = (entry.timestamp + entry.lifetime) - Date.now()
|
|
110
|
+
return remaining > 0 ? remaining : null
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async cleanupExpired(): Promise<void> {
|
|
114
|
+
const now = Date.now()
|
|
115
|
+
for (const [key, entry] of this.storage.entries()) {
|
|
116
|
+
if (now > entry.timestamp + entry.lifetime) {
|
|
117
|
+
this.storage.delete(key)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
**Step 2 — Register with `CacheProviderFactory`**:
|
|
125
|
+
You can register custom drivers at app bootstrap or inside a Nuxt plugin.
|
|
126
|
+
|
|
127
|
+
- **Option A (Recommended for code-splitting)**: Register an async dynamic loader:
|
|
128
|
+
```typescript
|
|
129
|
+
// plugins/custom-cache.ts
|
|
130
|
+
import { defineNuxtPlugin } from '#app'
|
|
131
|
+
import { CacheProviderFactory } from '@katlux/providers'
|
|
132
|
+
|
|
133
|
+
export default defineNuxtPlugin(() => {
|
|
134
|
+
CacheProviderFactory.registerDriver('MyCustom', async () => {
|
|
135
|
+
const { CMyCustomCache } = await import('~/services/cache/CMyCustomCache')
|
|
136
|
+
return CMyCustomCache
|
|
137
|
+
})
|
|
138
|
+
})
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
- **Option B (Synchronous pre-loaded driver)**: Register the class directly:
|
|
142
|
+
```typescript
|
|
143
|
+
import { CacheProviderFactory } from '@katlux/providers'
|
|
144
|
+
import { CMyCustomCache } from '~/services/cache/CMyCustomCache'
|
|
145
|
+
|
|
146
|
+
CacheProviderFactory.registerDriver('MyCustom', CMyCustomCache)
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
**Step 3 — Consume the Strategy**:
|
|
150
|
+
Pass the strategy name to any provider or fetch directly via `CacheProviderFactory`:
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
// 1. With RequestProvider:
|
|
154
|
+
const request = new RequestProvider('MyCustom' as any, 60_000)
|
|
155
|
+
// or dynamically:
|
|
156
|
+
request.setCacheProvider('MyCustom' as any)
|
|
157
|
+
|
|
158
|
+
// 2. With Data Providers:
|
|
159
|
+
const dataProvider = new CAPIFlatServerDataProvider({
|
|
160
|
+
pageSize: 20,
|
|
161
|
+
cacheStrategy: 'MyCustom' as any,
|
|
162
|
+
cacheLifetime: 300_000
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
// 3. Directly via CacheProviderFactory:
|
|
166
|
+
const cache = await CacheProviderFactory.getProvider('MyCustom')
|
|
167
|
+
await cache?.set('my-key', { sample: 123 }, 60_000)
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
---
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
## 3.7. Auto-Imported Composables
|
|
2
|
+
|
|
3
|
+
These composables are globally available in any Nuxt app that installs `@katlux/toolkit`. No import needed.
|
|
4
|
+
|
|
5
|
+
### `useRequestProvider(provider, tags)`
|
|
6
|
+
Vue composable wrapper that registers a `RequestProvider` or `ADataProvider` with `RequestProviderRegistry` under the given tags. Automatically unregisters on component `onUnmounted` to prevent memory leaks in SPAs.
|
|
7
|
+
|
|
8
|
+
```typescript
|
|
9
|
+
// Registers provider with 'invoices' tag, automatically unregisters on unmount
|
|
10
|
+
const provider = useRequestProvider(myInvoiceProvider, ['invoices'])
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
### `useUnregisterProvider(provider)`
|
|
14
|
+
Explicitly unregisters a provider instance from `RequestProviderRegistry`. Useful for mid-lifecycle opt-outs or `<keep-alive>` component deactivation hooks (`onDeactivated`).
|
|
15
|
+
|
|
16
|
+
```typescript
|
|
17
|
+
onDeactivated(() => useUnregisterProvider(provider))
|
|
18
|
+
onActivated(() => RequestProviderRegistry.register(provider, ['invoices']))
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
### `useKatluxContext()`
|
|
22
|
+
Composable that returns the request-scoped H3 event context during SSR (`{ event }`), or `null` in client environments. Pass to server data providers (or `RequestProvider`) to ensure per-request in-flight deduplication isolation and prevent cookie / auth leaking across concurrent SSR user requests.
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
// Provides SSR request isolation
|
|
26
|
+
const context = useKatluxContext()
|
|
27
|
+
const provider = new CAPIFlatServerDataProvider({ context })
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### `useFilterLogic()`
|
|
31
|
+
The same filter engine used internally by client-side data providers. Useful for custom filtering logic.
|
|
32
|
+
```typescript
|
|
33
|
+
const { evaluateFilter, filterData, filterTreeData } = useFilterLogic()
|
|
34
|
+
|
|
35
|
+
// Filter a flat array
|
|
36
|
+
const { results } = filterData(myArray, myFilter)
|
|
37
|
+
|
|
38
|
+
// Filter a flat array representing a tree
|
|
39
|
+
const { results, expandedNodes } = filterData(myArray, myFilter, {
|
|
40
|
+
treeOptions: { idKey: 'id', parentKey: 'parentId' }
|
|
41
|
+
})
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### `useSortLogic()`
|
|
45
|
+
The same stable merge-sort engine used internally by client-side providers.
|
|
46
|
+
```typescript
|
|
47
|
+
const { sortData } = useSortLogic()
|
|
48
|
+
const sorted = sortData([{ field: 'name', direction: 'asc' }], myArray)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### `useDebounce(callback, delay)`
|
|
52
|
+
Returns a debounced version of any function.
|
|
53
|
+
```typescript
|
|
54
|
+
const debouncedSearch = useDebounce((text: string) => { /* ... */ }, 300)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### `useRemainingTime()`
|
|
58
|
+
Returns remaining TTL for a cache key. See `ACacheProvider.getRemainingTime(key)`.
|
|
59
|
+
|
|
60
|
+
### `useTemplate(options)`
|
|
61
|
+
Reactive template resolution for components.
|
|
62
|
+
```typescript
|
|
63
|
+
const { metadata, isCustomTemplate, templateName, refreshTemplate } = useTemplate({
|
|
64
|
+
componentName: 'KButton',
|
|
65
|
+
fallbackToDefault: true
|
|
66
|
+
})
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### `usePresetComponent(name, defaultComponent)`
|
|
70
|
+
Resolves which preset component implementation to render for a given component name across the active preset cascade. Used internally by all global components.
|
|
71
|
+
- **Fast-path**: Evaluates `'default'` preset synchronously with zero glob scanning or iterations.
|
|
72
|
+
- **Instance Caching**: Caches `defineAsyncComponent` instances in a module-level `Map` to preserve component identity and avoid re-wrapping across re-renders.
|
|
73
|
+
- **Synchronous & Asynchronous Support**: Accepts both pre-bundled Vue component objects (zero async suspense boundary overhead) and dynamic loader functions registered via `registerPresetComponents`.
|
|
74
|
+
|
|
75
|
+
### `useKatluxI18n()`
|
|
76
|
+
Resilient, multi-tier internationalization composable providing the `$t` translation function for Katlux components and consumer applications.
|
|
77
|
+
- **Lookup Priority Order**:
|
|
78
|
+
1. `nuxtApp.$t` or `nuxtApp.$i18n.t` (consumer's `@nuxtjs/i18n` or `vue-i18n` instance)
|
|
79
|
+
2. Language-specific overrides: `appConfig.katluxToolkit.translations[locale][key]`
|
|
80
|
+
3. Flat custom overrides: `appConfig.katluxToolkit.translations[key]`
|
|
81
|
+
4. Built-in localized dictionaries (supports 23+ locales: `en`, `es`, `fr`, `de`, `pt`, `it`, `nl`, `pl`, `ru`, `uk`, `zh`, `ja`, `ko`, `hi`, `bn`, `id`, `vi`, `th`, `sv`, `da`, `fi`, `cs`, `el`, `tr`)
|
|
82
|
+
5. Built-in English default dictionary fallback
|
|
83
|
+
6. Raw key fallback
|
|
84
|
+
- **Usage**:
|
|
85
|
+
```typescript
|
|
86
|
+
const { t } = useKatluxI18n()
|
|
87
|
+
const greeting = t('Welcome back, {name}!', { name: 'Alex' })
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### `useRequestQueue()`
|
|
91
|
+
Vue composable interface for the offline mutation queue manager (`RequestQueue`). Enables queuing API mutations while offline and automatically flushing them when connectivity is restored.
|
|
92
|
+
- **Reactive State & Methods**:
|
|
93
|
+
```typescript
|
|
94
|
+
const {
|
|
95
|
+
queue, // Ref<IQueuedOperation[]> - Pending queued mutations
|
|
96
|
+
deadLetterQueue, // Ref<IDeadLetterItem[]> - Permanently failed operations
|
|
97
|
+
isFlushing, // Ref<boolean> - True while active flush is in progress
|
|
98
|
+
enqueue, // (item: IQueuedOperationInput) => Promise<string>
|
|
99
|
+
flushAll, // (options?: { tag?: string }) => Promise<void>
|
|
100
|
+
flushOne, // (id: string) => Promise<void>
|
|
101
|
+
retryOne, // (id: string) => Promise<void>
|
|
102
|
+
discard, // (id: string) => Promise<void>
|
|
103
|
+
setStorageBackend// (type: EQueueStorage) => void
|
|
104
|
+
} = useRequestQueue()
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
---
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
### `EncryptionProvider` (`CWebCryptoEncryptionProvider`, `CWebCryptoAESCBCProvider`, `CRSAEncryptionProvider`, `CECDHEncryptionProvider`, `CNodeCryptoEncryptionProvider`, `CKeyManager`, `AEncryptionProvider`)
|
|
2
|
+
Zero-dependency, native cryptographic toolkit for end-to-end client-side, in-flight, and server-side encryption/decryption using native Web Crypto API (`crypto.subtle`) and `node:crypto`. Zero WASM, zero npm dependencies.
|
|
3
|
+
|
|
4
|
+
> [!IMPORTANT]
|
|
5
|
+
> **E2EE Architecture & Threat Model Boundary**:
|
|
6
|
+
> - **Primary Objective**: Provide robust **End-to-End Encryption (E2EE)** to prevent catastrophic server-side data leaks (database dumps, cloud infrastructure compromises, rogue backend admin access). In multi-tenant, multi-user SaaS architectures, all GDPR-protected and sensitive data is stored and relayed exclusively as ciphertext envelopes (`__encrypted: true`).
|
|
7
|
+
> - **Multi-User Role-Based Key Sharing**: Users with appropriate roles (defined in database permissions) can encrypt and decrypt shared tenant data. Roles may contain symmetric keys or wrapped/encrypted keys. Keys may exist in memory or be wrapped for secure transport across the network to client sessions.
|
|
8
|
+
> - **Asymmetric Sender Authenticity Boundary**: Hybrid asymmetric ciphers (`CRSAEncryptionProvider`, `CECDHEncryptionProvider`) provide **recipient confidentiality** (only the holder of the recipient private key can decrypt), but do **not** provide sender authenticity on their own—anyone possessing the recipient public key can encrypt envelopes. In multi-user multi-tenant architectures where write authenticity must be strictly enforced, pair asymmetric encryption with digital signatures (ECDSA/Ed25519) or symmetric tenant role keys (AES-GCM).
|
|
9
|
+
> - **Explicit Non-Goals (Client Endpoint Security)**: The encryption system does **not** protect against client-side compromise (OS-level trojans, hardware keyloggers, screen grabbers, or malicious browser extensions). Once data is legitimately decrypted in client DOM/memory for the authorized user to view, local endpoint security is the user's/device owner's responsibility.
|
|
10
|
+
|
|
11
|
+
> **Showcase Pages**:
|
|
12
|
+
> - **Overview & SSR**: `/providers/request/encryption`
|
|
13
|
+
> - **Symmetric**: `/providers/classes/CWebCryptoEncryptionProvider` (AES-GCM) · `/providers/classes/CWebCryptoAESCBCProvider` (AES-CBC) · `/providers/classes/CNodeCryptoEncryptionProvider` (Node Sync)
|
|
14
|
+
> - **Asymmetric / Hybrid**: `/providers/classes/CRSAEncryptionProvider` (RSA-OAEP) · `/providers/classes/CECDHEncryptionProvider` (ECDH)
|
|
15
|
+
> - **Key Management**: `/providers/classes/CKeyManager`
|
|
16
|
+
> - **Base & Contracts**: `/providers/classes/AEncryptionProvider` · `/providers/interfaces/IEncryptionProvider` · `/providers/interfaces/IProviderEncryptionOptions` · `/providers/interfaces/IKeyPair` · `/providers/interfaces/IKDFOptions` · `/providers/interfaces/IHKDFFromSecretOptions`
|
|
17
|
+
|
|
18
|
+
- **Available Providers**:
|
|
19
|
+
- `CWebCryptoEncryptionProvider`: AES-GCM-256 with optional PBKDF2/HKDF key derivation. Built-in AEAD, 100% backward-compatible.
|
|
20
|
+
- `CWebCryptoAESCBCProvider`: Authenticated AES-CBC-256 + HMAC-SHA-256 (Encrypt-then-MAC) for legacy system compatibility.
|
|
21
|
+
- `CRSAEncryptionProvider`: Asymmetric RSA-OAEP-4096 + AES-GCM-256 hybrid cipher for arbitrary-sized single-recipient payloads.
|
|
22
|
+
- `CECDHEncryptionProvider`: Forward-secure Elliptic Curve Diffie-Hellman (P-256/384/521) + HKDF + AES-GCM. Ephemeral key per encryption. Ideal for multi-user role sharing (e.g. Kazan Ledger Account Symmetric Key wrapping).
|
|
23
|
+
- `CNodeCryptoEncryptionProvider`: Server-side synchronous AES-GCM via `node:crypto` (`encryptSync`/`decryptSync`). 100% binary-interoperable with `CWebCryptoEncryptionProvider`.
|
|
24
|
+
- **Provider Methods (`IEncryptionProvider` / `AEncryptionProvider`)**:
|
|
25
|
+
- `encrypt(data: any, options?: IEncryptionContext): Promise<IEncryptedPayload | any>`: Encrypts data into an envelope or field-encrypted record (strictly idempotent; already-encrypted fields/envelopes are never double-encrypted). Attaches `kid` when specified.
|
|
26
|
+
- `decrypt(payload: any, options?: IEncryptionContext): Promise<any>`: Decrypts envelope back into original data, immediately zeroing plaintext byte buffers in memory. Automatically leverages record-level DEK caching across multi-field records for up to 90% latency reduction.
|
|
27
|
+
- `warmupKey(options?: IEncryptionContext): Promise<void>`: Pre-derives and caches CryptoKey / Buffer in memory. Supported on `CWebCrypto`, `CWebCryptoAESCBC`, and `CNodeCrypto`.
|
|
28
|
+
- `isEncrypted(payload: any): boolean`: Polymorphic check if given object is an encrypted envelope. Also available as static `AEncryptionProvider.isEncrypted(payload)`.
|
|
29
|
+
- `clearKeys() / dispose()`: Wipes in-memory key caches, zeroes mutable Buffer bytes, and clears sensitive asymmetric keys upon logout/session end.
|
|
30
|
+
- `resolveRawKey(keyProvider?: TKeyProvider)`: (Protected on `AEncryptionProvider`) Resolves key or async keyProvider callback. Supports `string`, `Uint8Array`, `ArrayBuffer`, and `CryptoKey` without byte corruption.
|
|
31
|
+
- **PEM Import/Export (`CKeyManager` / `CRSA` / `CECDH`)**:
|
|
32
|
+
- `importPublicKeyFromPEM(pem, ...)`: Imports SPKI PEM string to `CryptoKey`.
|
|
33
|
+
- `importPrivateKeyFromPEM(pem, ...)`: Imports PKCS#8 PEM string to `CryptoKey`.
|
|
34
|
+
- `exportPublicKeyToPEM(key)`: Exports `CryptoKey` to standard SPKI PEM string.
|
|
35
|
+
- `exportPrivateKeyToPEM(key)`: Exports `CryptoKey` to standard PKCS#8 PEM string.
|
|
36
|
+
|
|
37
|
+
- **Envelope Contract (`IEncryptedPayload`)**:
|
|
38
|
+
```ts
|
|
39
|
+
interface IEncryptedPayload {
|
|
40
|
+
__encrypted: true
|
|
41
|
+
ciphertext: string // Base64 ciphertext (always present)
|
|
42
|
+
alg: string // 'AES-GCM' | 'AES-CBC-256+HMAC-SHA-256' | 'RSA-OAEP-4096+AES-GCM-256' | 'ECDH-P-256+AES-GCM-256'
|
|
43
|
+
kid?: string // Key identifier / version for key rotation tracking
|
|
44
|
+
iv?: string // Base64 IV
|
|
45
|
+
salt?: string // Base64 KDF salt
|
|
46
|
+
kdf?: string // 'PBKDF2' | 'HKDF'
|
|
47
|
+
iter?: number // PBKDF2 iteration count (default: 310,000, clamped [1,000, 600,000])
|
|
48
|
+
tag?: string // Explicit HMAC tag (AES-CBC)
|
|
49
|
+
wrappedKey?: string // Base64 RSA-wrapped AES key (RSA hybrid)
|
|
50
|
+
sharedKey?: boolean // Shared DEK marker for field-level encryption
|
|
51
|
+
epk?: JsonWebKey // Ephemeral public key (ECDH)
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
- **`IProviderEncryptionOptions`**:
|
|
56
|
+
```ts
|
|
57
|
+
interface IProviderEncryptionOptions {
|
|
58
|
+
enabled?: boolean // Master toggle (default: false)
|
|
59
|
+
key?: TKeyProvider // string | Uint8Array | ArrayBuffer | CryptoKey | (() => Promise<...>)
|
|
60
|
+
kid?: string // Key identifier / version (e.g. 'v1', 'tenant-a-key-2026')
|
|
61
|
+
decryptOnSSR?: boolean // default: false. Prevents SSR decryption unless explicitly enabled with server secrets
|
|
62
|
+
fields?: string[] // Field-level encryption: only encrypt listed fields
|
|
63
|
+
searchIndex?: boolean // Enables HMAC-SHA256 blind index and trigram search index on encrypted fields
|
|
64
|
+
hmacKey?: TKeyProvider // Optional dedicated HMAC key for search indexing (defaults to encryption key)
|
|
65
|
+
algorithm?: 'AES-GCM' | string // default: 'AES-GCM'
|
|
66
|
+
customProvider?: IEncryptionProvider // Custom cipher adapter (e.g. CRSA, CECDH, AES-CBC)
|
|
67
|
+
kdf?: 'none' | 'pbkdf2' | 'hkdf' // Key derivation strategy:
|
|
68
|
+
// - 'pbkdf2': Recommended for human passphrases/passwords (OWASP recommended rounds)
|
|
69
|
+
// - 'hkdf': For high-entropy IKM / subkey derivation (warns if used with string passwords)
|
|
70
|
+
// - 'none': When supplying pre-derived 256-bit raw keys, Buffers, or CryptoKeys
|
|
71
|
+
kdfIterations?: number // PBKDF2 rounds (default: 310,000 per OWASP, clamped [1,000, 600,000])
|
|
72
|
+
kdfHash?: 'SHA-256' | 'SHA-512' // KDF hash algorithm
|
|
73
|
+
kdfSalt?: string | Uint8Array | ArrayBuffer // Optional static salt (random salt in envelope if omitted)
|
|
74
|
+
publicKey?: CryptoKey // Optional public key for asymmetric encryption
|
|
75
|
+
privateKey?: CryptoKey // Optional private key for asymmetric decryption
|
|
76
|
+
recipientPublicKey?: CryptoKey // Recipient public key for hybrid encryption
|
|
77
|
+
recipientPrivateKey?: CryptoKey // Recipient private key for hybrid decryption
|
|
78
|
+
curve?: 'P-256' | 'P-384' | 'P-521' // Curve for ECDH providers
|
|
79
|
+
info?: string // Optional context/info string for HKDF
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
- **Factory & Provider Creation**:
|
|
84
|
+
- `createEncryptionProvider(options: IProviderEncryptionOptions): IEncryptionProvider`: Unified factory that instantiates and configures the appropriate cipher provider based on `options.algorithm` (`'AES-GCM'`, `'AES-CBC'`, `'RSA-OAEP'`, `'ECDH'`) or returns `options.customProvider`. Supports `IKeyPair` or individual keys, HKDF info, curve configuration, and KDF options.
|
|
85
|
+
|
|
86
|
+
- **Usage in DataProvider (Client & Server)**:
|
|
87
|
+
Supported uniformly across **all** client and server data providers:
|
|
88
|
+
- **Local (Non-API)**: `CFlatClientDataProvider`, `CTreeClientDataProvider` (via `AEncryptedClientProvider`)
|
|
89
|
+
- **API Client-Side**: `CAPIFlatClientDataProvider`, `CAPITreeClientDataProvider`
|
|
90
|
+
- **Server-Side**: `CAPIFlatServerDataProvider`, `CAPITreeServerDataProvider`
|
|
91
|
+
|
|
92
|
+
#### Local DataProvider Encryption Architecture
|
|
93
|
+
- **Eager Encryption**: `setData(rows)` encrypts designated `fields` immediately before storing in `allData`. Plaintext never persists in `allData`.
|
|
94
|
+
- **Non-blocking Ingestion**: `setDataChunked(rows, { chunkSize: 250, yieldStrategy: 'idle' })` yields between chunks to prevent main-thread freezing on large datasets.
|
|
95
|
+
- **Idempotent Ingestion**: Pre-encrypted envelopes (`__encrypted: true`, e.g. from IndexedDB or Web Workers) pass through untouched without double-encryption.
|
|
96
|
+
- **Lazy Page-Level Decryption**: `loadPageData()` slices `allData` and decrypts only the active page (`pageSize` rows) into `pageData`. Only visible rows are plaintext in memory.
|
|
97
|
+
- **Blind Index Search (`CSearchIndex`)**: When `searchIndex: true`, exact match (`==`, `!=`) and substring search (`in`) operate directly on encrypted fields via deterministic HMAC-SHA256 blind tokens and trigram sets without full dataset decryption.
|
|
98
|
+
- **Zero-Cost Path**: When `enabled` is false, `setData` runs 100% synchronously with zero microtask overhead.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { CFlatClientDataProvider } from '@katlux/providers'
|
|
102
|
+
|
|
103
|
+
const customerProvider = new CFlatClientDataProvider({
|
|
104
|
+
pageSize: 20,
|
|
105
|
+
encryption: {
|
|
106
|
+
enabled: true,
|
|
107
|
+
key: 'secret-key-32-chars-long-12345!',
|
|
108
|
+
kid: 'tenant-key-v1',
|
|
109
|
+
fields: ['ssn', 'salary', 'creditCard'],
|
|
110
|
+
searchIndex: true // Enables search/filter on encrypted fields via CSearchIndex
|
|
111
|
+
}
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
// Eagerly encrypts sensitive fields; leaves id, role, department in plaintext
|
|
115
|
+
await customerProvider.setData(rawEmployees)
|
|
116
|
+
|
|
117
|
+
// Large dataset ingestion with progress reporting:
|
|
118
|
+
await customerProvider.setDataChunked(largeEmployees, {
|
|
119
|
+
chunkSize: 500,
|
|
120
|
+
onProgress: (p) => console.log(`Encryption progress: ${(p * 100).toFixed(0)}%`)
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
// Dynamically rotate key:
|
|
124
|
+
customerProvider.setEncryption({ enabled: true, key: newKey, kid: 'tenant-key-v2', fields: ['ssn', 'salary'] })
|
|
125
|
+
|
|
126
|
+
// Upon user logout / session termination:
|
|
127
|
+
customerProvider.clearEncryption() // Clears keys, zeroes memory, and disables encryption
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
- **Usage with RequestProvider**:
|
|
131
|
+
```ts
|
|
132
|
+
const rp = new RequestProvider()
|
|
133
|
+
rp.setEncryption({ enabled: true, key: 'my-secret-32-char-key!!!', kid: 'tenant-key-2026' })
|
|
134
|
+
// Outbound POST/PUT/PATCH bodies encrypted; encrypted responses auto-decrypted
|
|
135
|
+
|
|
136
|
+
// Upon user logout:
|
|
137
|
+
rp.clearEncryption() // Safely clears cached cipher instance, scoped WeakMap instances, and zeroes keys
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
#### Authenticated Additional Data (AAD) & Security Guarantees
|
|
141
|
+
In multi-tenant, field-encrypted, and SSR scenarios, Katlux cryptographic providers enforce strict, integration-tested security guarantees:
|
|
142
|
+
- **Field & Record Binding**: During value-level and field-level encryption, `AEncryptionProvider` and `CNodeCryptoEncryptionProvider` automatically bind:
|
|
143
|
+
`aad:${baseAad}|record:${recordId}|field:${fieldName}`
|
|
144
|
+
Where `recordId` is extracted from `record.id`, `record._id`, or `options.recordId`.
|
|
145
|
+
- **Transposition Tamper Resistance**: Moving or swapping an encrypted envelope from one database row to another, or from one column (`ssn`) to another (`phone`), causes AES-GCM tag verification to immediately fail with an authentication error.
|
|
146
|
+
- **Cache-at-Rest Full Envelope**: When caching responses where field-level encryption is active (`fields: [...]`), `RequestProvider` automatically wraps the entire object in a full envelope at rest. Neither targeted sensitive fields nor unlisted metadata fields appear as plaintext in raw storage across any client or server cache adapter.
|
|
147
|
+
- **Node GCM 16-Byte Tag Enforcement**: `CNodeCryptoEncryptionProvider` strictly validates a 16-byte (128-bit) authentication tag across all synchronous and asynchronous decryption paths (rejecting truncated 12, 8, or 4-byte tags).
|
|
148
|
+
- **Nonce Misuse Resistance**: Initialization Vectors (IVs) are freshly generated via cryptographically secure RNG per operation (12 bytes for GCM, 16 bytes for CBC) with proven uniqueness across sibling fields, batch arrays, and concurrent executions.
|
|
149
|
+
- **Deterministic Search Token Segregation**: `CSearchIndex` HMAC-SHA256 blind index tokens are deterministic for search matching and strictly segregated from non-deterministic ciphertext IVs.
|
|
150
|
+
- **Non-Extractable Tenant Keys**: `CKeyManager.generateAccountDataKey()` and `CKeyManager.unwrapAccountKeyForUser()` produce `CryptoKey` instances with `extractable: false` by default, safeguarding unwrapped symmetric tenant keys against exfiltration via developer tools or malicious extensions.
|
|
151
|
+
- **SSR Confidentiality & Cache Auth Guard**: With `decryptOnSSR: false` (the secure zero-trust default), plaintext is never exposed in server memory or serialized HTML hydration payloads. Requests with `cookie` or `Authorization` headers automatically bypass shared server caches (`CApplicationCache`), preventing cross-user session cache poisoning.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
## 3.2.2. React 18+ Integration: `useSyncExternalStore`
|
|
2
|
+
|
|
3
|
+
Because `ADataProvider` implements `subscribe(listener)` and `getState()`, it integrates natively with React 18+ without any external dependencies:
|
|
4
|
+
|
|
5
|
+
```tsx
|
|
6
|
+
import { useSyncExternalStore, useMemo } from 'react'
|
|
7
|
+
import { CFlatServerDataProvider } from '@katlux/providers'
|
|
8
|
+
|
|
9
|
+
// Generic React hook for any Katlux DataProvider
|
|
10
|
+
export function useDataProvider(provider) {
|
|
11
|
+
return useSyncExternalStore(
|
|
12
|
+
(onStoreChange) => provider.subscribe(onStoreChange),
|
|
13
|
+
() => provider.getState(),
|
|
14
|
+
() => provider.getState() // SSR snapshot
|
|
15
|
+
)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// In any React component
|
|
19
|
+
export function UserTable() {
|
|
20
|
+
const provider = useMemo(() => new CFlatServerDataProvider({
|
|
21
|
+
pageDataHandler: async (page, pageSize, filter, sort) => {
|
|
22
|
+
const res = await fetch(`/api/users?page=${page}&pageSize=${pageSize}`)
|
|
23
|
+
return await res.json()
|
|
24
|
+
}
|
|
25
|
+
}), [])
|
|
26
|
+
|
|
27
|
+
const { pageData, rowCount, loading, currentPage } = useDataProvider(provider)
|
|
28
|
+
|
|
29
|
+
return (
|
|
30
|
+
<div>
|
|
31
|
+
{loading && <div>Loading...</div>}
|
|
32
|
+
<table>
|
|
33
|
+
<tbody>
|
|
34
|
+
{pageData.map(row => <tr key={row.id}><td>{row.name}</td></tr>)}
|
|
35
|
+
</tbody>
|
|
36
|
+
</table>
|
|
37
|
+
<button onClick={() => provider.setCurrentPage(currentPage + 1)}>Next</button>
|
|
38
|
+
</div>
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 3.3. Client-Side Data Providers
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
### Provider Testing & `nuxtAppCompat` Isolation
|
|
2
|
+
In unit test environments (Vitest), `@katlux/providers/nuxtAppCompat` is aliased to `nuxtAppCompat.server.ts` (stub implementation). This allows unit tests to run fast, deterministic provider assertions without needing a running Nuxt Nitro engine. SSR payload hydration transfers and full browser lifecycle are verified via integration and Playwright E2E test suites.
|
|
3
|
+
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
## 3.5. Infrastructure Providers
|