@katlux/toolkit 0.1.1-alpha.140 → 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/KButton/KButton.global.d.vue.ts +1 -1
- package/dist/runtime/components/KButton/KButton.global.vue.d.ts +1 -1
- package/dist/runtime/components/KCheckbox/KCheckbox.global.d.vue.ts +1 -1
- package/dist/runtime/components/KCheckbox/KCheckbox.global.vue.d.ts +1 -1
- package/dist/runtime/components/KCombobox/KCombobox.global.d.vue.ts +1 -1
- package/dist/runtime/components/KCombobox/KCombobox.global.vue.d.ts +1 -1
- 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 +1 -1
- package/dist/runtime/components/KDatePicker/KDatePicker.global.vue.d.ts +1 -1
- package/dist/runtime/components/KHourPicker/KHourPicker.global.d.vue.ts +1 -1
- package/dist/runtime/components/KHourPicker/KHourPicker.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/KTreePicker/KTreePicker.global.d.vue.ts +1 -1
- package/dist/runtime/components/KTreePicker/KTreePicker.global.vue.d.ts +1 -1
- package/dist/skills/katlux-config/SKILL.md +7 -7
- package/dist/skills/katlux-providers/SKILL.md +1 -1
- 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/package.json +2 -2
|
@@ -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`.
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# Katlux Encryption Architecture: Symmetric 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 Symmetric Providers
|
|
9
|
+
|
|
10
|
+
| Provider | Algorithm | Environment | Primary Use Case |
|
|
11
|
+
| :--- | :--- | :--- | :--- |
|
|
12
|
+
| `CWebCryptoEncryptionProvider` | AES-GCM-256 | Browser & Server (Async) | Modern Web Crypto standard, built-in AEAD integrity, PBKDF2/HKDF support |
|
|
13
|
+
| `CWebCryptoAESCBCProvider` | AES-CBC-256 + HMAC-SHA-256 | Browser & Server (Async) | Legacy compliance, Encrypt-then-MAC authentication |
|
|
14
|
+
| `CNodeCryptoEncryptionProvider` | AES-GCM-256 | Server (Sync/Async) | Zero-microtask synchronous server routes via `node:crypto` |
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 2. `CWebCryptoEncryptionProvider` (AES-GCM-256)
|
|
19
|
+
|
|
20
|
+
Standard native Web Crypto implementation using AES-GCM with a 128-bit authentication tag and a 96-bit random IV.
|
|
21
|
+
|
|
22
|
+
### Basic Usage
|
|
23
|
+
```ts
|
|
24
|
+
import { CWebCryptoEncryptionProvider } from '@katlux/providers'
|
|
25
|
+
|
|
26
|
+
const cipher = new CWebCryptoEncryptionProvider({
|
|
27
|
+
key: 'my-passphrase-or-raw-32-byte-key',
|
|
28
|
+
kid: 'tenant-v1',
|
|
29
|
+
kdf: 'pbkdf2', // 'pbkdf2' for passwords, 'none' for 256-bit keys
|
|
30
|
+
kdfIterations: 310000
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
// Encrypt arbitrary object, array, or string:
|
|
34
|
+
const envelope = await cipher.encrypt({ ssn: '123-45-6789', salary: 150000 })
|
|
35
|
+
|
|
36
|
+
// Decrypt back to original structure:
|
|
37
|
+
const data = await cipher.decrypt(envelope)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## 3. `CWebCryptoAESCBCProvider` (AES-CBC-256 + HMAC-SHA-256)
|
|
43
|
+
|
|
44
|
+
Combines AES-CBC-256 with HMAC-SHA-256 in a secure **Encrypt-then-MAC** construction for legacy environments.
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
import { CWebCryptoAESCBCProvider } from '@katlux/providers'
|
|
48
|
+
|
|
49
|
+
const cbcCipher = new CWebCryptoAESCBCProvider({
|
|
50
|
+
key: process.env.LEGACY_CIPHER_KEY,
|
|
51
|
+
kid: 'legacy-v1',
|
|
52
|
+
kdf: 'pbkdf2'
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
const envelope = await cbcCipher.encrypt('sensitive-data')
|
|
56
|
+
const decrypted = await cbcCipher.decrypt(envelope)
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
---
|
|
60
|
+
|
|
61
|
+
## 4. `CNodeCryptoEncryptionProvider` (Node.js Sync/Async)
|
|
62
|
+
|
|
63
|
+
Synchronous, zero-microtask AES-GCM encryption using native `node:crypto`. 100% binary-interoperable with `CWebCryptoEncryptionProvider`.
|
|
64
|
+
|
|
65
|
+
### Synchronous Server Route Example
|
|
66
|
+
```ts
|
|
67
|
+
import { CNodeCryptoEncryptionProvider } from '@katlux/providers'
|
|
68
|
+
|
|
69
|
+
const nodeCipher = new CNodeCryptoEncryptionProvider({
|
|
70
|
+
key: process.env.SERVER_ENCRYPTION_KEY,
|
|
71
|
+
kid: 'server-v1',
|
|
72
|
+
strict: true
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
export default defineEventHandler(async (event) => {
|
|
76
|
+
const body = await readBody(event)
|
|
77
|
+
// Zero microtask delay:
|
|
78
|
+
const encrypted = nodeCipher.encryptSync(body, { recordId: 'REC-123', field: 'taxId' })
|
|
79
|
+
return encrypted
|
|
80
|
+
})
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
- **Strict Tag Enforcement**: Strictly enforces a 16-byte (128-bit) GCM tag on all decryption operations, rejecting truncated tags (e.g. 12, 8, or 4 bytes).
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## 5. Built-in Keyring & Multi-Key Rotation
|
|
88
|
+
|
|
89
|
+
Katlux cipher providers natively support multi-key keyrings for zero-downtime rotation.
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
const cipher = new CWebCryptoEncryptionProvider({
|
|
93
|
+
keys: {
|
|
94
|
+
'k2025': oldKey,
|
|
95
|
+
'k2026': newKey
|
|
96
|
+
},
|
|
97
|
+
activeKid: 'k2026' // All outbound encryption uses k2026
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
// Outbound encryption automatically tags kid: 'k2026':
|
|
101
|
+
const newEnvelope = await cipher.encrypt(data)
|
|
102
|
+
|
|
103
|
+
// Decryption dynamically routes through keys[envelope.kid]:
|
|
104
|
+
const oldDecrypted = await cipher.decrypt(legacyEnvelope) // Decrypts with k2025
|
|
105
|
+
const newDecrypted = await cipher.decrypt(newEnvelope) // Decrypts with k2026
|
|
106
|
+
|
|
107
|
+
// Dynamic runtime rotation:
|
|
108
|
+
cipher.setKeyring({ 'k2026': newKey, 'k2027': nextKey }, 'k2027')
|
|
109
|
+
|
|
110
|
+
// Concurrent warmup:
|
|
111
|
+
await cipher.warmupKey()
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
- **Whitelist Enforcement**: Envelopes carrying an unknown `kid` not present in `allowedKids` (defaults to `Object.keys(keys)`) are rejected with `Unauthorized key: kid '${payload.kid}' is not in allowedKids`.
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## 6. Strict Decryption & Whitelisting
|
|
119
|
+
|
|
120
|
+
When `strict: true` is enabled:
|
|
121
|
+
- **Plaintext Injection Prevention**: If any designated sensitive field is unencrypted plaintext, decryption immediately throws a security violation error.
|
|
122
|
+
- **Algorithm Whitelisting**: Restricts accepted decryption algorithms to `allowedAlgorithms` (defaults to `['AES-GCM']`).
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## 7. Dynamic Authenticated Additional Data (AAD)
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
const cipher = new CWebCryptoEncryptionProvider({
|
|
130
|
+
key: myKey,
|
|
131
|
+
baseAad: 'tenant:corp',
|
|
132
|
+
aadFields: ['org_id', 'department_id'] // Binds sibling record fields into AAD
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
// Automatically binds: aad:tenant:corp|record:REC-42|field:salary|org_id:101|department_id:finance
|
|
136
|
+
const envelope = await cipher.encrypt(record, { recordId: 'REC-42' })
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
Transposition (moving the ciphertext to a different record or column) causes GCM tag verification to fail immediately.
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# Katlux Encryption Architecture: Threat Model, Boundaries & Contracts
|
|
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. E2EE Architecture & Threat Model Boundary
|
|
9
|
+
|
|
10
|
+
- **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`).
|
|
11
|
+
- **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.
|
|
12
|
+
- **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).
|
|
13
|
+
- **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.
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## 2. Envelope Contract (`IEncryptedPayload`)
|
|
18
|
+
|
|
19
|
+
All Katlux encrypted payloads conform to a standardized envelope format:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
export interface IEncryptedPayload {
|
|
23
|
+
__encrypted: true
|
|
24
|
+
ciphertext: string // Base64 ciphertext (always present)
|
|
25
|
+
alg: string // 'AES-GCM' | 'AES-CBC-256+HMAC-SHA-256' | 'RSA-OAEP-4096+AES-GCM-256' | 'ECDH-P-256+AES-GCM-256'
|
|
26
|
+
kid?: string // Key identifier / version for key rotation tracking
|
|
27
|
+
iv?: string // Base64 IV
|
|
28
|
+
salt?: string // Base64 KDF salt
|
|
29
|
+
kdf?: string // 'PBKDF2' | 'HKDF'
|
|
30
|
+
iter?: number // PBKDF2 iteration count (default: 310,000, clamped [1,000, 600,000])
|
|
31
|
+
tag?: string // Explicit HMAC tag (AES-CBC)
|
|
32
|
+
wrappedKey?: string // Base64 RSA-wrapped AES key (RSA hybrid)
|
|
33
|
+
sharedKey?: boolean // Shared DEK marker for field-level encryption
|
|
34
|
+
epk?: JsonWebKey // Ephemeral public key (ECDH)
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Polymorphic Verification
|
|
39
|
+
```ts
|
|
40
|
+
import { isEncrypted, AEncryptionProvider } from '@katlux/providers'
|
|
41
|
+
|
|
42
|
+
// Fast runtime envelope check:
|
|
43
|
+
if (isEncrypted(data)) {
|
|
44
|
+
// Safe to route to decrypt()
|
|
45
|
+
}
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## 3. Provider Options (`IProviderEncryptionOptions`)
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
export interface IProviderEncryptionOptions {
|
|
54
|
+
enabled?: boolean // Master toggle (default: false)
|
|
55
|
+
key?: TKeyProvider // Single key or key provider (legacy/simple mode)
|
|
56
|
+
keys?: Record<string, TKeyProvider | IKeyPair> // Built-in Keyring dictionary mapping kid to keys
|
|
57
|
+
activeKid?: string // Active key identifier from keys to use for outbound encryption
|
|
58
|
+
kid?: string // Key identifier / version (e.g. 'v1', 'tenant-a-key-2026')
|
|
59
|
+
aad?: string | Uint8Array | ArrayBuffer | ((record: any, field: string) => string | Uint8Array | ArrayBuffer) // AEAD Additional Data or dynamic callback
|
|
60
|
+
aadFields?: string[] // Sibling record fields to deterministically bind into AAD (e.g. ['contact_id', 'version'])
|
|
61
|
+
baseAad?: string // Optional base prefix for AAD context binding
|
|
62
|
+
decryptOnSSR?: boolean // default: false. Prevents SSR decryption unless explicitly enabled with server secrets
|
|
63
|
+
fields?: string[] // Field-level encryption: only encrypt listed fields
|
|
64
|
+
strict?: boolean // Enforces strict decryption: unencrypted plaintext in `fields` triggers injection violation; defaults allowedAlgorithms to ['AES-GCM']
|
|
65
|
+
allowedAlgorithms?: string[] // Whitelist of permitted cipher algorithms (e.g. ['AES-GCM'])
|
|
66
|
+
allowedKids?: string[] // Whitelist of permitted Key Identifiers (kid); defaults to Object.keys(keys)
|
|
67
|
+
onDecryptError?: ((info: IDecryptErrorInfo) => any) | boolean | string // Per-field error hook, safe fallback marker, or true for '[⚠ Decryption Error]'
|
|
68
|
+
searchIndex?: boolean // Enables HMAC-SHA256 blind index and trigram search index on encrypted fields
|
|
69
|
+
preEncrypted?: boolean // Set to true if API endpoints return pre-encrypted ciphertext envelopes; enables in-memory index decryption
|
|
70
|
+
hmacKey?: TKeyProvider // Optional dedicated HMAC key for search indexing (defaults to encryption key)
|
|
71
|
+
algorithm?: 'AES-GCM' | string // default: 'AES-GCM'
|
|
72
|
+
customProvider?: IEncryptionProvider // Custom cipher adapter (e.g. CRSA, CECDH, AES-CBC)
|
|
73
|
+
kdf?: 'none' | 'pbkdf2' | 'hkdf' // Key derivation strategy:
|
|
74
|
+
// - 'pbkdf2': Recommended for human passphrases/passwords (OWASP recommended rounds)
|
|
75
|
+
// - 'hkdf': For high-entropy IKM / subkey derivation (warns if used with string passwords)
|
|
76
|
+
// - 'none': When supplying pre-derived 256-bit raw keys, Buffers, or CryptoKeys
|
|
77
|
+
kdfIterations?: number // PBKDF2 rounds (default: 310,000 per OWASP, clamped [1,000, 600,000])
|
|
78
|
+
kdfHash?: 'SHA-256' | 'SHA-512' // KDF hash algorithm
|
|
79
|
+
kdfSalt?: string | Uint8Array | ArrayBuffer // Optional static salt (random salt in envelope if omitted)
|
|
80
|
+
publicKey?: CryptoKey // Optional public key for asymmetric encryption
|
|
81
|
+
privateKey?: CryptoKey // Optional private key for asymmetric decryption
|
|
82
|
+
recipientPublicKey?: CryptoKey // Recipient public key for hybrid encryption
|
|
83
|
+
recipientPrivateKey?: CryptoKey // Recipient private key for hybrid decryption
|
|
84
|
+
curve?: 'P-256' | 'P-384' | 'P-521' // Curve for ECDH providers
|
|
85
|
+
info?: string // Optional context/info string for HKDF
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
91
|
+
## 4. Factory & Base Provider Creation
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
import { createEncryptionProvider } from '@katlux/providers'
|
|
95
|
+
|
|
96
|
+
// Automatically selects and configures the appropriate cipher engine:
|
|
97
|
+
const cipher = createEncryptionProvider({
|
|
98
|
+
algorithm: 'AES-GCM',
|
|
99
|
+
key: process.env.DATA_KEY,
|
|
100
|
+
kid: 'v1'
|
|
101
|
+
})
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
---
|
|
105
|
+
|
|
106
|
+
## 5. Security Lifecycle & Memory Hygiene
|
|
107
|
+
|
|
108
|
+
- **Memory Zeroization**: Intermediate plaintext byte buffers (`Uint8Array`, `Buffer`) are immediately zeroed in memory via `.fill(0)` within `finally` blocks.
|
|
109
|
+
- **Session Cleanup (`clearKeys()` / `dispose()`)**: Calling `clearKeys()` or `dispose()` on any provider clears in-memory CryptoKeys, zeroes cached key buffers, and invalidates derived key caches upon user logout.
|
|
110
|
+
- **SSR Confidentiality Guard**: With `decryptOnSSR: false` (default zero-trust setting), sensitive payloads remain as encrypted envelopes in server memory and HTML hydration strings.
|