@katlux/toolkit 0.1.1-alpha.139 → 0.1.1-alpha.141
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/module.json +1 -1
- 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/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/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 +2 -2
- package/dist/runtime/components/KCombobox/KCombobox.global.vue.d.ts +2 -2
- 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/KCompositeInput/KCompositeInput.logic.d.ts +3 -3
- package/dist/runtime/components/KDatatable/KDataIterator.global.d.vue.ts +1 -1
- package/dist/runtime/components/KDatatable/KDataIterator.global.vue.d.ts +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 +1 -1
- package/dist/runtime/components/KDateTimePicker/KDateTimePicker.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/KMaskTextbox/KMaskTextbox.global.d.vue.ts +1 -1
- package/dist/runtime/components/KMaskTextbox/KMaskTextbox.global.vue.d.ts +1 -1
- package/dist/runtime/components/KRadiobox/KRadiobox.global.d.vue.ts +1 -1
- package/dist/runtime/components/KRadiobox/KRadiobox.global.vue.d.ts +1 -1
- package/dist/runtime/components/KRangeSlider/KRangeSlider.global.d.vue.ts +1 -1
- package/dist/runtime/components/KRangeSlider/KRangeSlider.global.vue.d.ts +1 -1
- package/dist/runtime/components/KSlider/KSlider.global.d.vue.ts +1 -1
- package/dist/runtime/components/KSlider/KSlider.global.vue.d.ts +1 -1
- package/dist/runtime/components/KTextarea/KTextarea.global.d.vue.ts +1 -1
- package/dist/runtime/components/KTextarea/KTextarea.global.vue.d.ts +1 -1
- package/dist/runtime/components/KTextbox/KTextbox.global.d.vue.ts +2 -2
- package/dist/runtime/components/KTextbox/KTextbox.global.vue.d.ts +2 -2
- 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/skills/katlux-config/SKILL.md +7 -7
- package/dist/skills/katlux-providers/SKILL.md +1 -1
- package/dist/skills/katlux-providers/providers/CAPIFlatServerDataProvider.md +25 -0
- 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 -188
- package/package.json +2 -2
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# Katlux Encryption Architecture: Asymmetric & Hybrid Cipher Providers
|
|
2
|
+
|
|
3
|
+
> Part of the Katlux Cryptographic Architecture (`@katlux/providers`).
|
|
4
|
+
> See [encryption.md](encryption.md) for the master index.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## 1. Overview of Hybrid Asymmetric Ciphers
|
|
9
|
+
|
|
10
|
+
Asymmetric cryptography alone cannot efficiently encrypt arbitrary-sized payloads. Katlux hybrid providers combine public-key cryptography with AES-256-GCM symmetric session keys:
|
|
11
|
+
- The sender generates a random 256-bit AES-GCM Data Encryption Key (DEK).
|
|
12
|
+
- The DEK encrypts the payload.
|
|
13
|
+
- The recipient's public key encrypts/derives the DEK.
|
|
14
|
+
- Only the holder of the recipient's private key can decrypt the DEK and recover the payload.
|
|
15
|
+
|
|
16
|
+
| Provider | Asymmetric Primitive | Symmetric Primitive | Primary Use Case |
|
|
17
|
+
| :--- | :--- | :--- | :--- |
|
|
18
|
+
| `CRSAEncryptionProvider` | RSA-OAEP-4096 / 2048 | AES-GCM-256 | Single-recipient arbitrary payload encryption, user keypair delivery |
|
|
19
|
+
| `CECDHEncryptionProvider` | ECDH (P-256, P-384, P-521) + HKDF | AES-GCM-256 | Forward-secure ephemeral key exchange, role-based key sharing |
|
|
20
|
+
|
|
21
|
+
> [!IMPORTANT]
|
|
22
|
+
> **Sender Authenticity Boundary**:
|
|
23
|
+
> Asymmetric hybrid encryption provides **recipient confidentiality**, not sender authenticity. Anyone with the recipient's public key can encrypt envelopes. For write authenticity, combine with digital signatures (`CKeyManager.sign` / `CKeyManager.verify`) or symmetric role keys.
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## 2. `CRSAEncryptionProvider` (RSA-OAEP-4096 Hybrid)
|
|
28
|
+
|
|
29
|
+
Combines RSA-OAEP key wrapping with AES-256-GCM payload encryption.
|
|
30
|
+
|
|
31
|
+
### Basic Usage
|
|
32
|
+
```ts
|
|
33
|
+
import { CRSAEncryptionProvider, CKeyManager } from '@katlux/providers'
|
|
34
|
+
|
|
35
|
+
// 1. Generate or import recipient keypair:
|
|
36
|
+
const keypair = await CKeyManager.generateRSAKeyPair(4096, 'SHA-256', true)
|
|
37
|
+
|
|
38
|
+
// 2. Sender configures provider with recipient public key:
|
|
39
|
+
const senderCipher = new CRSAEncryptionProvider({
|
|
40
|
+
recipientPublicKey: keypair.publicKey
|
|
41
|
+
})
|
|
42
|
+
const envelope = await senderCipher.encrypt({ secretDocument: 'Confidential content' })
|
|
43
|
+
|
|
44
|
+
// 3. Recipient configures provider with private key:
|
|
45
|
+
const recipientCipher = new CRSAEncryptionProvider({
|
|
46
|
+
recipientPrivateKey: keypair.privateKey
|
|
47
|
+
})
|
|
48
|
+
const data = await recipientCipher.decrypt(envelope)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
---
|
|
52
|
+
|
|
53
|
+
## 3. `CECDHEncryptionProvider` (ECDH Ephemeral Hybrid)
|
|
54
|
+
|
|
55
|
+
Uses Elliptic Curve Diffie-Hellman (P-256 by default) with an ephemeral keypair per encryption operation, stretched via HKDF to derive an AES-256-GCM key.
|
|
56
|
+
|
|
57
|
+
### Basic Usage
|
|
58
|
+
```ts
|
|
59
|
+
import { CECDHEncryptionProvider, CKeyManager } from '@katlux/providers'
|
|
60
|
+
|
|
61
|
+
// 1. Recipient generates ECDH keypair:
|
|
62
|
+
const keypair = await CKeyManager.generateECDHKeyPair('P-256')
|
|
63
|
+
|
|
64
|
+
// 2. Sender encrypts using recipient's public key (generates fresh ephemeral key):
|
|
65
|
+
const senderCipher = new CECDHEncryptionProvider({
|
|
66
|
+
recipientPublicKey: keypair.publicKey,
|
|
67
|
+
curve: 'P-256',
|
|
68
|
+
info: 'tenant-sharing-v1'
|
|
69
|
+
})
|
|
70
|
+
const envelope = await senderCipher.encrypt({ tenantKey: 'wrapped-bytes' })
|
|
71
|
+
// Envelope contains `epk` (ephemeral public key in JWK format)
|
|
72
|
+
|
|
73
|
+
// 3. Recipient derives matching shared secret and decrypts:
|
|
74
|
+
const recipientCipher = new CECDHEncryptionProvider({
|
|
75
|
+
recipientPrivateKey: keypair.privateKey,
|
|
76
|
+
curve: 'P-256',
|
|
77
|
+
info: 'tenant-sharing-v1'
|
|
78
|
+
})
|
|
79
|
+
const decrypted = await recipientCipher.decrypt(envelope)
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## 4. PEM Key Import & Export (`CKeyManager`)
|
|
85
|
+
|
|
86
|
+
Katlux providers natively support standard SPKI and PKCS#8 PEM strings without third-party libraries:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
import { CKeyManager } from '@katlux/providers'
|
|
90
|
+
|
|
91
|
+
// Exporting keys:
|
|
92
|
+
const publicPem = await CKeyManager.exportPublicKeyToPEM(keypair.publicKey)
|
|
93
|
+
const privatePem = await CKeyManager.exportPrivateKeyToPEM(keypair.privateKey)
|
|
94
|
+
|
|
95
|
+
// Importing keys:
|
|
96
|
+
const importedPubKey = await CKeyManager.importPublicKeyFromPEM(publicPem, 'RSA-OAEP', undefined, 'SHA-256')
|
|
97
|
+
const importedPrivKey = await CKeyManager.importPrivateKeyFromPEM(privatePem, 'RSA-OAEP', undefined, 'SHA-256')
|
|
98
|
+
|
|
99
|
+
// ECDSA signing keys:
|
|
100
|
+
const ecdsaPubKey = await CKeyManager.importECDSAPublicKeyFromPEM(ecdsaPubPem, 'P-256')
|
|
101
|
+
const ecdsaPrivKey = await CKeyManager.importECDSAPrivateKeyFromPEM(ecdsaPrivPem, 'P-256')
|
|
102
|
+
```
|
|
@@ -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'`.
|