@katlux/toolkit 0.1.1-alpha.140 → 0.1.1-alpha.142
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/compiled/composables/useKatluxForm.mjs +29 -21
- package/dist/module.json +1 -1
- package/dist/runtime/components/KDatePicker/KDatePicker.global.d.vue.ts +3 -3
- package/dist/runtime/components/KDatePicker/KDatePicker.global.vue.d.ts +3 -3
- 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/composables/useKatluxForm.d.ts +11 -11
- package/dist/runtime/composables/useKatluxForm.js +29 -21
- package/dist/skills/katlux-components/components/KAreaChart.md +1 -1
- package/dist/skills/katlux-components/components/KBarChart.md +1 -1
- package/dist/skills/katlux-components/components/KBulkActions.md +3 -3
- package/dist/skills/katlux-components/components/KCheckbox.md +2 -2
- package/dist/skills/katlux-components/components/KCombobox.md +3 -3
- package/dist/skills/katlux-components/components/KCompositeInput.md +4 -4
- package/dist/skills/katlux-components/components/KDataIterator.md +3 -3
- package/dist/skills/katlux-components/components/KDatatable.md +7 -7
- package/dist/skills/katlux-components/components/KDatePicker.md +3 -3
- package/dist/skills/katlux-components/components/KGantt.md +12 -12
- package/dist/skills/katlux-components/components/KHeatMap.md +1 -1
- package/dist/skills/katlux-components/components/KLineChart.md +1 -1
- package/dist/skills/katlux-components/components/KPieChart.md +1 -1
- package/dist/skills/katlux-components/components/KScatterChart.md +1 -1
- package/dist/skills/katlux-components/components/KTree.md +8 -8
- package/dist/skills/katlux-components/components/KTreePicker.md +3 -3
- package/dist/skills/katlux-components/components/KTreeView.md +3 -3
- package/dist/skills/katlux-config/SKILL.md +7 -7
- package/dist/skills/katlux-presets/SKILL.md +1 -1
- package/dist/skills/katlux-presets/creating-a-preset.md +1 -1
- package/dist/skills/katlux-providers/SKILL.md +1 -1
- package/dist/skills/katlux-providers/providers/ADataProvider.md +3 -3
- package/dist/skills/katlux-providers/providers/CAPIFlatClientDataProvider.md +3 -3
- package/dist/skills/katlux-providers/providers/CAPIFlatServerDataProvider.md +3 -3
- package/dist/skills/katlux-providers/providers/CFlatClientDataProvider.md +4 -4
- package/dist/skills/katlux-providers/providers/CFlatServerDataProvider.md +1 -1
- package/dist/skills/katlux-providers/providers/CTreeClientDataProvider.md +2 -2
- package/dist/skills/katlux-providers/providers/RequestProvider.md +4 -4
- package/dist/skills/katlux-providers/providers/caching.md +11 -11
- package/dist/skills/katlux-providers/providers/encryption-asymmetric.md +102 -0
- package/dist/skills/katlux-providers/providers/encryption-field-level.md +260 -0
- package/dist/skills/katlux-providers/providers/encryption-key-management.md +196 -0
- package/dist/skills/katlux-providers/providers/encryption-key-pinning.md +115 -0
- package/dist/skills/katlux-providers/providers/encryption-streaming.md +84 -0
- package/dist/skills/katlux-providers/providers/encryption-symmetric.md +139 -0
- package/dist/skills/katlux-providers/providers/encryption-threat-model.md +110 -0
- package/dist/skills/katlux-providers/providers/encryption.md +44 -267
- package/dist/skills/katlux-providers/providers/types.md +5 -5
- package/dist/skills/katlux-providers/providers/useDataProvider.md +1 -1
- package/package.json +2 -2
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
# Katlux Encryption Architecture: Field-Level Encryption, Ingestion & Blind Indexing
|
|
2
|
+
|
|
3
|
+
> Part of the Katlux Cryptographic Architecture (`@katlux/providers`).
|
|
4
|
+
> See [encryption.md](encryption.md) for the master index.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## 1. Overview
|
|
9
|
+
|
|
10
|
+
Katlux supports selective **field-level encryption** across data rows, allowing public identifiers (such as `id`, `status`, `role`) to remain in plaintext for sorting and routing, while sensitive PII (such as `ssn`, `salary`, `email`) is encrypted into individual `IEncryptedPayload` envelopes.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 2. Scalar Field Encryption (`encryptField` / `decryptField`)
|
|
15
|
+
|
|
16
|
+
Encrypt single fields with contextual AAD binding without allocating dummy wrapper objects:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { CWebCryptoEncryptionProvider } from '@katlux/providers'
|
|
20
|
+
|
|
21
|
+
const cipher = new CWebCryptoEncryptionProvider({
|
|
22
|
+
key: process.env.DATA_KEY,
|
|
23
|
+
kid: 'v1',
|
|
24
|
+
baseAad: 'tenant:corp'
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
// Encrypt a single field:
|
|
28
|
+
const envelope = await cipher.encryptField('123-45-6789', {
|
|
29
|
+
recordId: 'REC-101',
|
|
30
|
+
fieldName: 'ssn'
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
// Decrypt verifying contextual AAD:
|
|
34
|
+
const plainSSN = await cipher.decryptField(envelope, {
|
|
35
|
+
recordId: 'REC-101',
|
|
36
|
+
fieldName: 'ssn'
|
|
37
|
+
})
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## 3. DataProvider Integration (`AEncryptedClientProvider`)
|
|
43
|
+
|
|
44
|
+
Supported uniformly across all client providers (`CFlatClientDataProvider`, `CTreeClientDataProvider`):
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { CFlatClientDataProvider } from '@katlux/providers'
|
|
48
|
+
|
|
49
|
+
const customerProvider = new CFlatClientDataProvider({
|
|
50
|
+
pageSize: 20,
|
|
51
|
+
encryption: {
|
|
52
|
+
enabled: true,
|
|
53
|
+
key: 'secret-key-32-chars-long-12345!',
|
|
54
|
+
kid: 'tenant-key-v1',
|
|
55
|
+
fields: ['ssn', 'salary', 'creditCard'],
|
|
56
|
+
searchIndex: true // Enables search/filter on encrypted fields via CSearchIndex
|
|
57
|
+
}
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
// Eagerly encrypts sensitive fields; leaves id, role, department in plaintext:
|
|
61
|
+
await customerProvider.setData(rawEmployees)
|
|
62
|
+
|
|
63
|
+
// Large dataset ingestion with progress reporting:
|
|
64
|
+
await customerProvider.setDataChunked(largeEmployees, {
|
|
65
|
+
chunkSize: 500,
|
|
66
|
+
onProgress: (p) => console.log(`Encryption progress: ${(p * 100).toFixed(0)}%`)
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
// Lazy Page-Level Decryption:
|
|
70
|
+
// loadPageData() decrypts only the active page (pageSize rows) into pageData.
|
|
71
|
+
// Plaintext never persists in allData.
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Pre-Encrypted Dataset Ingestion (`preEncrypted: true`)
|
|
75
|
+
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
|
+
|
|
79
|
+
## 4. Blind Index Search & Substring Trigram Indexing (`CSearchIndex`)
|
|
80
|
+
|
|
81
|
+
Enables fast exact match (`==`, `!=`) and substring search (`in`) over encrypted fields without full dataset decryption.
|
|
82
|
+
|
|
83
|
+
### Ingestion Pipeline
|
|
84
|
+
1. **Normalization**: Normalize plaintext (`NFKC` + lowercase).
|
|
85
|
+
2. **Blind Index Token**: Generate exact blind index token via `CKeyManager.computeBlindIndex(plain, hmacKey)`.
|
|
86
|
+
3. **Trigram Slices**: Extract 3-character slices via `extractTrigrams(plain)` and hash each trigram with `searchIndex.computeTrigramTokens(plain)`.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## 5. Backend Persistence & Datatable Encrypted Search
|
|
91
|
+
|
|
92
|
+
To enable fast exact-match and substring search across AES-256-GCM encrypted records in persisted PostgreSQL/MySQL databases:
|
|
93
|
+
|
|
94
|
+
### 1. Database Schema
|
|
95
|
+
```sql
|
|
96
|
+
CREATE TABLE contacts (
|
|
97
|
+
id SERIAL PRIMARY KEY,
|
|
98
|
+
name_encrypted JSONB NOT NULL,
|
|
99
|
+
email_encrypted JSONB NOT NULL,
|
|
100
|
+
salary_encrypted JSONB,
|
|
101
|
+
name_bidx CHAR(64) NOT NULL,
|
|
102
|
+
email_bidx CHAR(64) NOT NULL,
|
|
103
|
+
name_trigrams TEXT[] NOT NULL,
|
|
104
|
+
email_trigrams TEXT[] NOT NULL,
|
|
105
|
+
role VARCHAR(100),
|
|
106
|
+
department VARCHAR(100),
|
|
107
|
+
status VARCHAR(50) DEFAULT 'Active'
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
-- B-Tree for O(log N) exact lookups:
|
|
111
|
+
CREATE INDEX idx_contacts_name_bidx ON contacts (name_bidx);
|
|
112
|
+
CREATE INDEX idx_contacts_email_bidx ON contacts (email_bidx);
|
|
113
|
+
|
|
114
|
+
-- Inverted index for fast array containment substring search:
|
|
115
|
+
CREATE INDEX idx_contacts_name_trigrams ON contacts USING GIN (name_trigrams);
|
|
116
|
+
CREATE INDEX idx_contacts_email_trigrams ON contacts USING GIN (email_trigrams);
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### 2. Query Execution
|
|
120
|
+
- **Exact Match (`name = $1`)**:
|
|
121
|
+
```sql
|
|
122
|
+
-- Compute HMAC token in API, then point-lookup using B-Tree:
|
|
123
|
+
SELECT id, name_encrypted, email_encrypted, role FROM contacts WHERE name_bidx = $1;
|
|
124
|
+
```
|
|
125
|
+
- **Substring Search (`name CONTAINS $1`)**:
|
|
126
|
+
```sql
|
|
127
|
+
-- Extract & hash search query trigrams, then query via array containment operator (@>):
|
|
128
|
+
SELECT id, name_encrypted, email_encrypted, role
|
|
129
|
+
FROM contacts
|
|
130
|
+
WHERE name_trigrams @> $1::text[]
|
|
131
|
+
ORDER BY id ASC
|
|
132
|
+
LIMIT 10 OFFSET 0;
|
|
133
|
+
```
|
|
134
|
+
- **Compound Filtering**:
|
|
135
|
+
```sql
|
|
136
|
+
WHERE name_trigrams @> $1::text[] AND department = 'Security'
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
### 3. Production Best Practices
|
|
140
|
+
- **Strict Key Isolation**: Isolate `DATA_ENCRYPTION_KEY` (AES-256-GCM) from `BLIND_INDEX_HMAC_KEY`.
|
|
141
|
+
- **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
|
+
- **Client Decryption Pipeline**: API responses return encrypted envelopes (`__encrypted: true`). Frontend `CAPIFlatServerDataProvider` decrypts only the received page slice via `decryptPageRows()` on arrival.
|
|
144
|
+
|
|
145
|
+
---
|
|
146
|
+
|
|
147
|
+
## 6. Multi-KID Blind Index Search & Query Resolution (`IBlindIndexKeyring`)
|
|
148
|
+
|
|
149
|
+
In production environments with periodic cryptographic key rotation, records in storage will be indexed under different key versions (`v1`, `v2`, etc.). Blind index HMAC tokens are deterministic with respect to their key, meaning searching for an exact value under only the active key would fail to find records created before the rotation.
|
|
150
|
+
|
|
151
|
+
Katlux solves this using `IBlindIndexKeyring` and multi-token query expansion (`computeMultiBlindIndex` and `rewriteEncryptedFilters`).
|
|
152
|
+
|
|
153
|
+
### Keyring Schema & Lifecycle Statuses
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import type { IBlindIndexKeyring, TBlindIndexKeyStatus } from '@katlux/providers'
|
|
157
|
+
|
|
158
|
+
const keyring: IBlindIndexKeyring = {
|
|
159
|
+
activeKid: 'bidx-v2',
|
|
160
|
+
keys: {
|
|
161
|
+
'bidx-v2': {
|
|
162
|
+
key: activeHmacKey,
|
|
163
|
+
status: 'active', // Exactly ONE key must be active
|
|
164
|
+
algorithm: 'HMAC'
|
|
165
|
+
},
|
|
166
|
+
'bidx-v1': {
|
|
167
|
+
key: oldHmacKey,
|
|
168
|
+
status: 'search-only', // Historical key used for querying existing rows
|
|
169
|
+
algorithm: 'HMAC'
|
|
170
|
+
},
|
|
171
|
+
'bidx-v0': {
|
|
172
|
+
key: retiredHmacKey,
|
|
173
|
+
status: 'retired', // Completely ignored; rows must already be re-indexed
|
|
174
|
+
algorithm: 'HMAC'
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
- `'active'`: Used for all outbound writes (`computeWriteBlindIndex`) and included first in search tokens.
|
|
181
|
+
- `'search-only'`: Used during queries (`computeMultiBlindIndex`) to match rows created under historical key versions.
|
|
182
|
+
- `'retired'`: Excluded from all token generation. Zero candidate tokens are generated.
|
|
183
|
+
|
|
184
|
+
### Candidate Token Generation
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
import { CKeyManager } from '@katlux/providers'
|
|
188
|
+
|
|
189
|
+
// Multi-token generation for search (returns tokens for active + search-only keys):
|
|
190
|
+
const tokens = await CKeyManager.computeMultiBlindIndex('user@example.com', keyring)
|
|
191
|
+
// Output: [token_v2, token_v1] (active key token is always first, de-duplicated)
|
|
192
|
+
|
|
193
|
+
// Single-token generation for record insertion / update:
|
|
194
|
+
const writeToken = await CKeyManager.computeWriteBlindIndex('user@example.com', keyring)
|
|
195
|
+
// Output: token_v2
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
### Encrypted Query Rewriting (`rewriteEncryptedFilters`)
|
|
199
|
+
|
|
200
|
+
When an application receives datatable or ORM filter criteria targeting encrypted fields, `rewriteEncryptedFilters` expands the filter predicates into database clauses:
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
import { rewriteEncryptedFilters } from '@katlux/providers'
|
|
204
|
+
|
|
205
|
+
const rewritten = await rewriteEncryptedFilters(
|
|
206
|
+
[
|
|
207
|
+
{ field: 'email', operator: '==', value: 'user@example.com' },
|
|
208
|
+
{ field: 'status', operator: '==', value: 'Active' } // unencrypted passthrough
|
|
209
|
+
],
|
|
210
|
+
{
|
|
211
|
+
dialect: 'postgres',
|
|
212
|
+
fields: {
|
|
213
|
+
email: {
|
|
214
|
+
encrypted: true,
|
|
215
|
+
blindIndex: true,
|
|
216
|
+
keyring: emailKeyring,
|
|
217
|
+
column: 'email_bidx'
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
maxCandidateTokens: 500
|
|
221
|
+
}
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
// SQL Generation:
|
|
225
|
+
// email_bidx = ANY($1::text[]) AND status = 'Active'
|
|
226
|
+
// Parameters: [['bidx_hash_v2', 'bidx_hash_v1']]
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
#### Operator Mapping & Negation Semantics
|
|
230
|
+
- **Equality (`==`) / Set Membership (`in`)**: Expands to an abstract `in` clause over candidate tokens generated from active and `search-only` keys.
|
|
231
|
+
- **Negation (`!=`) / Exclusion (`nin` / `not in`)**: Expands to an abstract `notIn` clause requiring the column to not match *any* active or `search-only` tokens. For PostgreSQL: `!= ALL($1::text[])`. For SQLite/MySQL: `NOT IN (?, ?)`.
|
|
232
|
+
- **Pass-through**: Unencrypted fields (e.g. `status = 'Active'`) pass through unmodified.
|
|
233
|
+
|
|
234
|
+
#### Guard Rails
|
|
235
|
+
- `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
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## 7. Key Rotation Runbook for Blind-Indexed Fields
|
|
241
|
+
|
|
242
|
+
When rotating a blind index HMAC key:
|
|
243
|
+
|
|
244
|
+
1. **Step 1: Introduce New Key**:
|
|
245
|
+
- Generate a new HMAC key (`v2`).
|
|
246
|
+
- Add `v2` to the keyring with `status: 'active'`.
|
|
247
|
+
- Demote `v1` from `'active'` to `'search-only'`.
|
|
248
|
+
- Deploy backend/client updates. Queries will now check both `v2` and `v1` tokens; new/updated rows will receive `v2` tokens.
|
|
249
|
+
|
|
250
|
+
2. **Step 2: Background Re-Indexing**:
|
|
251
|
+
- Run a background migration job iterating over records that still have `v1` blind indexes.
|
|
252
|
+
- For each record, recompute the blind index using `computeWriteBlindIndex` (`v2`) and update the row's `_bidx` column.
|
|
253
|
+
|
|
254
|
+
3. **Step 3: Retire Old Key**:
|
|
255
|
+
- Once all rows have been updated to `v2`, update `v1` to `status: 'retired'`.
|
|
256
|
+
- Remove `v1` key material in the subsequent release.
|
|
257
|
+
|
|
258
|
+
> [!TIP]
|
|
259
|
+
> **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
|
+
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
# Katlux Encryption Architecture: Key Lifecycle, Wrapping & Derivation (`CKeyManager`)
|
|
2
|
+
|
|
3
|
+
> Part of the Katlux Cryptographic Architecture (`@katlux/providers`).
|
|
4
|
+
> See [encryption.md](encryption.md) for the master index.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## 1. Overview of `CKeyManager`
|
|
9
|
+
|
|
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
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## 2. Non-Extractable Tenant Keys & ADEK Wrapping
|
|
15
|
+
|
|
16
|
+
To prevent database-wide key exposure in multi-user SaaS architectures:
|
|
17
|
+
- An **Account Data Encryption Key (ADEK)** is generated for a tenant.
|
|
18
|
+
- The ADEK is wrapped for authorized users using their individual RSA-OAEP public keys.
|
|
19
|
+
- When an authorized user logs in, the ADEK is unwrapped as a **non-extractable** `CryptoKey` (`extractable: false`), preventing key exfiltration via browser memory or extensions.
|
|
20
|
+
|
|
21
|
+
### Workflow
|
|
22
|
+
```ts
|
|
23
|
+
import { CKeyManager } from '@katlux/providers'
|
|
24
|
+
|
|
25
|
+
// 1. Admin generates tenant account key (extractable: false for security):
|
|
26
|
+
const adek = await CKeyManager.generateAccountDataKey({ extractable: false })
|
|
27
|
+
|
|
28
|
+
// 2. Admin wraps ADEK for employee using employee's RSA public key:
|
|
29
|
+
const wrappedForAlice = await CKeyManager.wrapAccountKeyForUser(adek, alicePublicKey)
|
|
30
|
+
|
|
31
|
+
// 3. Alice unwraps ADEK in her session:
|
|
32
|
+
const aliceAdek = await CKeyManager.unwrapAccountKeyForUser(wrappedForAlice, alicePrivateKey)
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### Zero-Leak Atomic Key Re-Wrapping (`rewrapAccountKeyForUser`)
|
|
36
|
+
When an existing user shares access with a colleague:
|
|
37
|
+
```ts
|
|
38
|
+
// Atomically decrypts ADEK and re-encrypts for Bob without exposing raw key bytes:
|
|
39
|
+
const wrappedForBob = await CKeyManager.rewrapAccountKeyForUser(
|
|
40
|
+
wrappedForAlice,
|
|
41
|
+
alicePrivateKey,
|
|
42
|
+
bobPublicKey
|
|
43
|
+
)
|
|
44
|
+
```
|
|
45
|
+
- Immediate memory zeroization (`.fill(0)`) is guaranteed in `finally` blocks.
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 3. RFC 8785 Canonical JSON & Access Grants
|
|
50
|
+
|
|
51
|
+
### Deterministic JSON Canonicalization (`canonicalizeJson`)
|
|
52
|
+
Eliminates cross-platform formatting differences (whitespace, property order) to produce identical cryptographic hashes:
|
|
53
|
+
```ts
|
|
54
|
+
import { canonicalizeJson } from '@katlux/providers'
|
|
55
|
+
|
|
56
|
+
const canonical = canonicalizeJson({ b: 2, a: 1 })
|
|
57
|
+
// Guaranteed: '{"a":1,"b":2}'
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Digital Access Grants (`signGrant` / `verifyGrant`)
|
|
61
|
+
Protects against key-substitution attacks by embedding the granter's key fingerprint:
|
|
62
|
+
```ts
|
|
63
|
+
const grant = {
|
|
64
|
+
version: 1,
|
|
65
|
+
tenantId: 'tenant-42',
|
|
66
|
+
granteeId: 'user-bob',
|
|
67
|
+
scope: 'read:records',
|
|
68
|
+
issuedAt: Date.now(),
|
|
69
|
+
expiresAt: Date.now() + 3600000
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 1. Granter signs the grant:
|
|
73
|
+
const signedGrant = await CKeyManager.signGrant(grant, adminPrivateKey, adminPublicKey)
|
|
74
|
+
|
|
75
|
+
// 2. Verifier checks signature and key fingerprint:
|
|
76
|
+
const isValid = await CKeyManager.verifyGrant(signedGrant, adminPublicKey, {
|
|
77
|
+
checkExpiry: true
|
|
78
|
+
})
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
## 4. Domain-Separated Key Derivation (`deriveAuthAndEncryptionKeys`)
|
|
84
|
+
|
|
85
|
+
Derives two cryptographically isolated keys from a single master passphrase and salt using a hardened two-stage PBKDF2 & HKDF-Expand pipeline:
|
|
86
|
+
1. **PBKDF2** stretches the low-entropy passphrase into a high-entropy intermediate master key.
|
|
87
|
+
2. **HKDF-Expand** derives two cryptographically isolated keys using context tags:
|
|
88
|
+
- `authKey`: For authentication challenges (`katlux-auth-key-v1`).
|
|
89
|
+
- `encryptionKey`: For AES-GCM data encryption (`katlux-encryption-key-v1`).
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
const derived = await CKeyManager.deriveAuthAndEncryptionKeys(passphrase, salt, {
|
|
93
|
+
iterations: 310000,
|
|
94
|
+
hash: 'SHA-256'
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
// Compromise of authKey reveals zero mathematical information about encryptionKey:
|
|
98
|
+
const authKey = derived.authKey
|
|
99
|
+
const dataKey = derived.encryptionKey
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
---
|
|
103
|
+
|
|
104
|
+
## 5. Master Passphrase Re-Keying & Keypair Lifecycle (`rekeyUserKeypair`)
|
|
105
|
+
|
|
106
|
+
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
|
+
|
|
108
|
+
```ts
|
|
109
|
+
const result = await CKeyManager.rekeyUserKeypair({
|
|
110
|
+
encryptedPrivateKey: userEncryptedRsaKey,
|
|
111
|
+
encryptedSigningKey: userEncryptedEcdsaKey,
|
|
112
|
+
currentPassphrase: 'OldPassphrase123!',
|
|
113
|
+
newPassphrase: 'NewStrongPassphrase456!',
|
|
114
|
+
currentSalt: oldSaltBase64,
|
|
115
|
+
publicKeys: {
|
|
116
|
+
encryption: rsaPublicKey,
|
|
117
|
+
signing: ecdsaPublicKey
|
|
118
|
+
}
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
// Returns re-encrypted private key envelopes, fresh salt, and newly derived keys:
|
|
122
|
+
const { encryptedPrivateKey, encryptedSigningKey, newSalt, newKeys } = result
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
### Security Guarantees:
|
|
126
|
+
- **Failure Atomicity**: Invalid current passphrase throws `ERR_INVALID_CURRENT_PASSPHRASE` before generating any new salt or keys.
|
|
127
|
+
- **Passphrase Identity Guard**: Disallows identical passphrase (`ERR_REKEY_SAME_PASSPHRASE`).
|
|
128
|
+
- **Cryptographic Self-Check**: Performs a transient test decrypt and verifies consistency against `publicKeys` before returning.
|
|
129
|
+
- **Persistence Contract**: The caller must persist `encryptedPrivateKey`, `encryptedSigningKey`, `newSalt`, and the server auth verifier within a single atomic transaction.
|
|
130
|
+
- **Key Pin Continuity**: Because the underlying public keys do not change, existing peers holding public key pins continue without interruption.
|
|
131
|
+
|
|
132
|
+
---
|
|
133
|
+
|
|
134
|
+
## 6. Batch Re-Encryption & Key Migration Orchestrator (`reencryptDataset`, `reencryptBatch`)
|
|
135
|
+
|
|
136
|
+
When rotating persistence data encryption keys (e.g. retiring `v1` in favor of `v2`) or rotating HMAC blind index keys, rows already in persistence retain old ciphertext envelopes and deprecated blind index tokens until rewritten.
|
|
137
|
+
|
|
138
|
+
`reencryptDataset` provides a storage-agnostic, memory-bounded batch migration orchestrator:
|
|
139
|
+
|
|
140
|
+
```ts
|
|
141
|
+
import { reencryptDataset } from '@katlux/providers'
|
|
142
|
+
|
|
143
|
+
const summary = await reencryptDataset({
|
|
144
|
+
targetKid: 'v2',
|
|
145
|
+
keyring: {
|
|
146
|
+
v1: oldKey,
|
|
147
|
+
v2: newKey
|
|
148
|
+
},
|
|
149
|
+
encryptedFields: ['ssn', 'salary', 'email'],
|
|
150
|
+
blindIndex: {
|
|
151
|
+
fields: ['email'],
|
|
152
|
+
keyring: blindKeyring // Automatically computes and updates email_bidx to active HMAC key!
|
|
153
|
+
},
|
|
154
|
+
batchSize: 100,
|
|
155
|
+
versionField: 'updatedAt',
|
|
156
|
+
maxRetries: 3,
|
|
157
|
+
|
|
158
|
+
// 1. Adapter: fetch batch by cursor
|
|
159
|
+
fetchBatch: async (cursor, limit) => {
|
|
160
|
+
const records = await db.select().from(users)
|
|
161
|
+
.where(cursor ? gt(users.id, cursor) : undefined)
|
|
162
|
+
.limit(limit)
|
|
163
|
+
.orderBy(users.id)
|
|
164
|
+
return {
|
|
165
|
+
rows: records,
|
|
166
|
+
nextCursor: records.length === limit ? records[records.length - 1].id : undefined
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
|
|
170
|
+
// 2. Adapter: update with optimistic concurrency verification
|
|
171
|
+
updateRow: async (id, patch, expectedVersion) => {
|
|
172
|
+
const result = await db.update(users)
|
|
173
|
+
.set(patch)
|
|
174
|
+
.where(and(eq(users.id, id), eq(users.updatedAt, expectedVersion)))
|
|
175
|
+
return result.rowCount > 0 // returns false on concurrency conflict
|
|
176
|
+
},
|
|
177
|
+
|
|
178
|
+
// 3. Adapter: refetch single row on optimistic lock conflict
|
|
179
|
+
refetchRow: async (id) => {
|
|
180
|
+
return await db.select().from(users).where(eq(users.id, id)).first()
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
onProgress: (progress) => {
|
|
184
|
+
console.log(`Progress: ${progress.migratedRows} migrated, ${progress.skippedRows} skipped`)
|
|
185
|
+
}
|
|
186
|
+
})
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### Key Capabilities:
|
|
190
|
+
- **Zero Database Coupling**: Pure callback adapters compatible with Drizzle, Kysely, Prisma, TypeORM, Mongo, or REST endpoints.
|
|
191
|
+
- **Selective Migration & Idempotency**: Automatically skips fields that are already on `targetKid` or unencrypted, resulting in 0 updates on already-migrated datasets.
|
|
192
|
+
- **Optimistic Concurrency Protection**: Verifies `expectedVersion` before updating. If a concurrent writer modifies the row, `refetchRow` pulls the latest version, re-applies re-encryption, and retries up to `maxRetries`.
|
|
193
|
+
- **Blind Index Synchronization**: Simultaneously generates fresh blind index tokens using `computeWriteBlindIndex` from the active HMAC key and updates `<field>_bidx`.
|
|
194
|
+
- **Bounded Memory & Resumability**: Cursor pagination guarantees flat memory footprint even over millions of rows. Supports `AbortSignal` for graceful pause and resume from `lastProcessedCursor`.
|
|
195
|
+
- **Dry-Run Mode (`dryRun: true`)**: Validates key availability, decodes headers, and simulates re-encryption without invoking `updateRow`.
|
|
196
|
+
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Katlux Encryption Architecture: Key Pinning Store (TOFU) & Reset Attestation Protocol
|
|
2
|
+
|
|
3
|
+
> Part of the Katlux Cryptographic Architecture (`@katlux/providers`).
|
|
4
|
+
> See [encryption.md](encryption.md) for the master index.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## 1. Threat Model & Overview
|
|
9
|
+
|
|
10
|
+
Public key pinning detects key directories (server APIs) handing out substituted public keys for peers after first contact. When an authorized admin or recovery flow legitimately replaces a user's keypair, a digitally signed attestation from a trusted authority allows peers holding the old pin to update safely.
|
|
11
|
+
|
|
12
|
+
- ✅ **Protects against**: Substituted public keys from a compromised, rogue, or untrusted key directory *after* initial contact.
|
|
13
|
+
- ❌ **Does not protect against**: First-contact substitution (TOFU attack), malicious JavaScript served by the same origin, or client-side storage tampering via XSS. Pinning in a web application is defense-in-depth.
|
|
14
|
+
|
|
15
|
+
> [!IMPORTANT]
|
|
16
|
+
> **Out-of-Band Authority Distribution**:
|
|
17
|
+
> The `trustedAuthorities` public keys MUST be provisioned **out-of-band** (embedded in application bundle or administrative configuration), and **NEVER** fetched dynamically from the key server being protected.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 2. Storage Adapters (`IKeyPinningStore`)
|
|
22
|
+
|
|
23
|
+
All adapters implement atomic compare-and-set semantics:
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
export interface IKeyPin {
|
|
27
|
+
entityId: string
|
|
28
|
+
fingerprint: string // CKeyManager.getKeyFingerprint() → "SHA256:<base64url>"
|
|
29
|
+
pinnedAt: number
|
|
30
|
+
attestationSequence: number // Sequence counter (0 for TOFU, > 0 for resets)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface IKeyPinningStore {
|
|
34
|
+
get(entityId: string): Promise<IKeyPin | null>
|
|
35
|
+
compareAndSet(entityId: string, expectedFingerprint: string | null, next: IKeyPin): Promise<boolean>
|
|
36
|
+
delete(entityId: string): Promise<void>
|
|
37
|
+
clear(): Promise<void>
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Available Adapters
|
|
42
|
+
1. `CMemoryKeyPinningStore`: In-memory `Map` store for tests, ephemeral sessions, and server runtimes.
|
|
43
|
+
2. `CLocalStorageKeyPinningStore`: Browser `localStorage` with namespaced keys (`katlux:pin:<namespace>:<entityId>`).
|
|
44
|
+
3. `CIndexedDBKeyPinningStore`: Browser `IndexedDB` using the shared `KatluxIndexedDB` singleton (`key_pins` store). Executes `compareAndSet` within a single `readwrite` transaction to ensure strict concurrency isolation.
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## 3. Key-Reset Attestation Schema
|
|
49
|
+
|
|
50
|
+
When an entity's keypair is legitimately replaced, a recovery authority creates and signs an attestation:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
export interface IKeyResetAttestation {
|
|
54
|
+
version: 1
|
|
55
|
+
entityId: string
|
|
56
|
+
oldFingerprint: string
|
|
57
|
+
newFingerprint: string
|
|
58
|
+
sequence: number // Strictly increasing integer per entity
|
|
59
|
+
issuedAt: number // Epoch timestamp in ms
|
|
60
|
+
expiresAt: number // Epoch timestamp in ms (default max window: 7 days)
|
|
61
|
+
authorityFingerprint: string
|
|
62
|
+
reason?: string
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface ISignedKeyResetAttestation {
|
|
66
|
+
attestation: IKeyResetAttestation
|
|
67
|
+
signature: string // Base64 ECDSA P-256 signature
|
|
68
|
+
}
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Authority Helper: `CKeyManager.signKeyResetAttestation`
|
|
72
|
+
```ts
|
|
73
|
+
const signedAttestation = await CKeyManager.signKeyResetAttestation(
|
|
74
|
+
{
|
|
75
|
+
entityId: 'peer-alice',
|
|
76
|
+
oldFingerprint: 'SHA256:old-key-fingerprint',
|
|
77
|
+
newFingerprint: 'SHA256:new-key-fingerprint',
|
|
78
|
+
sequence: 1,
|
|
79
|
+
expiresAt: Date.now() + 86400000,
|
|
80
|
+
reason: 'Hardware token recovery'
|
|
81
|
+
},
|
|
82
|
+
authorityPrivateKey,
|
|
83
|
+
authorityPublicKey
|
|
84
|
+
)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## 4. Verification Pipeline: `CKeyManager.verifyAndPinKey`
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
const result = await CKeyManager.verifyAndPinKey('peer-alice', peerPublicKey, {
|
|
93
|
+
store: keyPinningStore,
|
|
94
|
+
trustedAuthorities: [authorityPublicKey], // Or Map / Record of authorities
|
|
95
|
+
fetchAttestation: async (entityId, oldFp, newFp) => {
|
|
96
|
+
return await api.getResetAttestation(entityId, oldFp, newFp)
|
|
97
|
+
},
|
|
98
|
+
onPinChange: (event) => {
|
|
99
|
+
console.log(`Pin updated for ${event.entityId}: ${event.type}`)
|
|
100
|
+
}
|
|
101
|
+
})
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Verification Flow & 6 Strict Rules:
|
|
105
|
+
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
|
+
2. **Pin Matches**: Returns `{ trusted: true, firstUse: false }`.
|
|
107
|
+
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 6 rules** pass (otherwise throws `ERR_KEY_ATTESTATION_INVALID`):
|
|
109
|
+
1. `authorityFingerprint` matches an authority in `trustedAuthorities`, and the digital signature verifies.
|
|
110
|
+
2. `entityId` matches target peer.
|
|
111
|
+
3. `oldFingerprint` matches current pinned fingerprint.
|
|
112
|
+
4. `newFingerprint` matches presented key fingerprint.
|
|
113
|
+
5. Time validity: `issuedAt - clockSkewMs <= now <= expiresAt + clockSkewMs` and validity window $\le$ `maxExpirationWindowMs`.
|
|
114
|
+
6. `sequence > currentPin.attestationSequence` (replay/rollback protection).
|
|
115
|
+
5. **Atomic Update**: On success, updates the pin via `compareAndSet` and dispatches `onPinChange` with type `'attested_reset'`.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
# Katlux Encryption Architecture: Web Streams Chunked AEAD Encryption
|
|
2
|
+
|
|
3
|
+
> Part of the Katlux Cryptographic Architecture (`@katlux/providers`).
|
|
4
|
+
> See [encryption.md](encryption.md) for the master index.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## 1. Overview
|
|
9
|
+
|
|
10
|
+
Streaming AEAD cipher for large files, document payloads, media, and archives using native Web Streams (`TransformStream`). Built on the **STREAM** construction (Hoang, Reyhanitabar, Rogaway, Vizár — 2015) using AES-256-GCM, per-stream wrapped DEKs, deterministic 96-bit nonces, and authenticated header binding.
|
|
11
|
+
|
|
12
|
+
> [!NOTE]
|
|
13
|
+
> The wire format is Katlux-specific (`KTLXSTRM\x01`) and is **not** interoperable with Tink, `age`, or libsodium.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## 2. Wire Format (Version 1)
|
|
18
|
+
|
|
19
|
+
| Field | Size | Description |
|
|
20
|
+
| :--- | :--- | :--- |
|
|
21
|
+
| **Magic** | 8 bytes | ASCII `KTLXSTRM` (`0x4B 0x54 0x4C 0x58 0x53 0x54 0x52 0x4D`) |
|
|
22
|
+
| **Version** | 1 byte | `0x01` |
|
|
23
|
+
| **Algorithm** | 1 byte | `0x01` (AES-256-GCM) |
|
|
24
|
+
| **Chunk Size** | 4 bytes | Plaintext bytes per block (uint32 BE, default `65536`, range `4096..4194304`) |
|
|
25
|
+
| **Nonce Prefix** | 7 bytes | Cryptographically random bytes generated per stream |
|
|
26
|
+
| **KID Length + KID** | 1 + $n$ bytes | UTF-8 key identifier string ($n \le 255$, `0` if absent) |
|
|
27
|
+
| **Wrapped DEK Length + DEK** | 2 + $m$ bytes | uint16 BE length + binary wrapped 256-bit AES-GCM data encryption key |
|
|
28
|
+
|
|
29
|
+
- **Chunk Nonce Layout (96 bits / 12 bytes)**:
|
|
30
|
+
`noncePrefix (7 bytes) ‖ chunkCounter (uint32 BE, 4 bytes) ‖ finalFlag (1 byte: 0x00 non-final, 0x01 final)`
|
|
31
|
+
- **Header Binding**: The entire serialized header bytes serve as Additional Authenticated Data (`AAD`) for every single chunk, preventing header substitution or cipher downgrade attacks.
|
|
32
|
+
- **Constant Memory Guarantee**: Stream transformers enforce a strict internal buffer ceiling ($\le 2 \times (chunkSize + 16)$ bytes).
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
## 3. Usage Examples
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
import {
|
|
40
|
+
createEncryptionStream,
|
|
41
|
+
createDecryptionStream,
|
|
42
|
+
encryptBlob,
|
|
43
|
+
decryptBlob
|
|
44
|
+
} from '@katlux/providers'
|
|
45
|
+
|
|
46
|
+
// 1. Streaming file encryption
|
|
47
|
+
const fileStream = file.stream()
|
|
48
|
+
const encryptedStream = fileStream.pipeThrough(
|
|
49
|
+
createEncryptionStream({ key: wrappingKey, kid: 'v1', chunkSize: 65536 })
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
// 2. Streaming file decryption
|
|
53
|
+
const decryptedStream = encryptedStream.pipeThrough(
|
|
54
|
+
createDecryptionStream({ key: wrappingKey })
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
// 3. Blob helpers
|
|
58
|
+
const encryptedBlob = await encryptBlob(fileBlob, { key: wrappingKey })
|
|
59
|
+
const decryptedBlob = await decryptBlob(encryptedBlob, { key: wrappingKey }, 'application/pdf')
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## 4. Node.js Stream Interoperability
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { Readable } from 'node:stream'
|
|
68
|
+
import { createEncryptionStream } from '@katlux/providers'
|
|
69
|
+
|
|
70
|
+
// Convert Node.js Readable to Web ReadableStream
|
|
71
|
+
const webStream = Readable.toWeb(nodeReadable)
|
|
72
|
+
const encryptedWebStream = webStream.pipeThrough(createEncryptionStream({ key }))
|
|
73
|
+
|
|
74
|
+
// Convert back to Node.js Readable
|
|
75
|
+
const nodeEncryptedStream = Readable.fromWeb(encryptedWebStream)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## 5. Threat Model & Security Boundaries
|
|
81
|
+
|
|
82
|
+
- **Header Tamper Resistance**: Modifying any byte in the magic, version, algorithm, chunk size, nonce prefix, kid, or wrapped DEK invalidates the AAD tag and aborts with `ERR_STREAM_AUTH_FAILED`.
|
|
83
|
+
- **Truncation Defense**: Dropping chunks or cutting the stream prematurely fails with `ERR_STREAM_TRUNCATED` on `flush()`.
|
|
84
|
+
- **Reordering & Extension Defense**: Swapping blocks or appending unauthorized chunks alters nonces or final flags, immediately throwing `ERR_STREAM_AUTH_FAILED`.
|