-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathclientKeyStore.js
More file actions
386 lines (335 loc) · 10.2 KB
/
Copy pathclientKeyStore.js
File metadata and controls
386 lines (335 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import { ed25519 } from '@noble/curves/ed25519'
import { AUTH_ERROR_PATTERNS } from '../shared/constants/auth'
import { CRYPTO_ALGORITHMS } from '../shared/constants/crypto'
import { base64Encode, base64Decode } from '../shared/utils/base64'
import { logger } from '../shared/utils/logger'
import { secureZero } from '../shared/utils/secureZero'
const DB_NAME = 'pearpassClientKeyStore'
const DB_VERSION = 1
const STORE_NAME = 'clientKeys'
const KEY_ID = 'client-ed25519'
let inMemoryKeypair = null
let pendingKeypair = null
let pendingPersistRecord = null
let unlocking = false
const textEncoder = new TextEncoder()
const openDb = () =>
new Promise((resolve, reject) => {
try {
const request = indexedDB.open(DB_NAME, DB_VERSION)
request.onupgradeneeded = () => {
const db = request.result
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: 'id' })
}
}
request.onsuccess = () => {
resolve(request.result)
}
request.onerror = () => {
reject(request.error)
}
} catch (error) {
reject(error)
}
})
const getKeyRecord = (db) =>
new Promise((resolve, reject) => {
try {
const tx = db.transaction(STORE_NAME, 'readonly')
const store = tx.objectStore(STORE_NAME)
const request = store.get(KEY_ID)
request.onsuccess = () => {
resolve(request.result || null)
}
request.onerror = () => {
reject(request.error)
}
} catch (error) {
reject(error)
}
})
const putKeyRecord = (db, record) =>
new Promise((resolve, reject) => {
try {
const tx = db.transaction(STORE_NAME, 'readwrite')
const store = tx.objectStore(STORE_NAME)
const request = store.put(record)
tx.oncomplete = () => {
resolve()
}
tx.onerror = () => {
reject(tx.error)
}
request.onerror = () => {
reject(request.error)
}
} catch (error) {
reject(error)
}
})
const getKeyMaterial = async (password) => {
const encoded = textEncoder.encode(password)
return crypto.subtle.importKey(
'raw',
encoded,
CRYPTO_ALGORITHMS.PBKDF2,
false,
['deriveKey']
)
}
const deriveKey = async (password, salt) => {
const keyMaterial = await getKeyMaterial(password)
return crypto.subtle.deriveKey(
{
name: CRYPTO_ALGORITHMS.PBKDF2,
salt,
iterations: 100000,
hash: CRYPTO_ALGORITHMS.SHA_256
},
keyMaterial,
{ name: CRYPTO_ALGORITHMS.AES_GCM, length: 256 },
false,
['encrypt', 'decrypt']
)
}
const encryptPrivateKey = async (privateKeyBytes, password) => {
const salt = new Uint8Array(16)
crypto.getRandomValues(salt)
const nonce = new Uint8Array(12)
crypto.getRandomValues(nonce)
const key = await deriveKey(password, salt)
const ciphertextBuffer = await crypto.subtle.encrypt(
{ name: CRYPTO_ALGORITHMS.AES_GCM, iv: nonce },
key,
privateKeyBytes
)
return {
salt,
nonce,
ciphertext: new Uint8Array(ciphertextBuffer)
}
}
const decryptPrivateKey = async (record, password) => {
const salt = base64Decode(record.saltB64)
const nonce = base64Decode(record.nonceB64)
const ciphertext = base64Decode(record.ciphertextB64)
const key = await deriveKey(password, salt)
const plaintextBuffer = await crypto.subtle.decrypt(
{ name: CRYPTO_ALGORITHMS.AES_GCM, iv: nonce },
key,
ciphertext
)
return new Uint8Array(plaintextBuffer)
}
/**
* Ensure a client Ed25519 keypair exists for pairing purposes without requiring
* the master password. This may generate a new keypair and keep it only in
* memory (pendingKeypair) until the master password is provided and the key
* can be encrypted and stored.
*
* The private key generated here is never persisted until
* ensureClientKeypairUnlocked is called with a validated master password.
*
* @returns {Promise<{ publicKey: Uint8Array, privateKey: Uint8Array | null }>}
*/
export const ensureClientKeypairGeneratedForPairing = async () => {
if (inMemoryKeypair) {
return inMemoryKeypair
}
if (pendingKeypair) {
return pendingKeypair
}
// If a stored record exists, we can safely return its public key without
// decrypting the private key. The private key will only be loaded once the
// user provides their master password.
const db = await openDb()
const record = await getKeyRecord(db)
if (record?.publicKeyB64) {
const publicKey = base64Decode(record.publicKeyB64)
return { publicKey, privateKey: null }
}
// No existing record – generate a new keypair and keep it only in memory
const privateKey = ed25519.utils.randomPrivateKey()
const publicKey = ed25519.getPublicKey(privateKey)
pendingKeypair = { publicKey, privateKey }
return pendingKeypair
}
/**
* Ensure the client Ed25519 keypair is available in memory and protected at rest
* with the master password. Private key is stored encrypted in IndexedDB and
* only decrypted when the user has provided the correct master password.
*
* If the keypair is not yet unlocked in memory, a non-empty masterPassword
* must be provided. The first time this is called in a session, the caller
* should ensure the password was validated against the vault.
*
* @param {string} [masterPassword]
* @returns {Promise<{ publicKey: Uint8Array, privateKey: Uint8Array }>}
*/
export const ensureClientKeypairUnlocked = async (masterPassword) => {
if (inMemoryKeypair) {
return inMemoryKeypair
}
if (unlocking) {
throw new Error('UnlockInProgress')
}
if (!masterPassword) {
throw new Error(AUTH_ERROR_PATTERNS.MASTER_PASSWORD_REQUIRED)
}
unlocking = true
try {
return await unlockKeypair(masterPassword)
} finally {
unlocking = false
}
}
const unlockKeypair = async (masterPassword) => {
const db = await openDb()
const record = await getKeyRecord(db)
if (!record) {
// First-time pairing: build the encrypted record but hold it in memory.
// Caller must call commitPendingClientKeystore() after vault validation.
let privateKey
let publicKey
if (pendingKeypair) {
;({ privateKey, publicKey } = pendingKeypair)
} else {
privateKey = ed25519.utils.randomPrivateKey()
publicKey = ed25519.getPublicKey(privateKey)
}
const { salt, nonce, ciphertext } = await encryptPrivateKey(
privateKey,
masterPassword
)
pendingPersistRecord = {
id: KEY_ID,
publicKeyB64: base64Encode(publicKey),
saltB64: base64Encode(salt),
nonceB64: base64Encode(nonce),
ciphertextB64: base64Encode(ciphertext),
createdAt: new Date().toISOString()
}
pendingKeypair = null
inMemoryKeypair = { publicKey, privateKey }
return inMemoryKeypair
}
try {
const privateKey = await decryptPrivateKey(record, masterPassword)
const publicKey = base64Decode(record.publicKeyB64)
inMemoryKeypair = { publicKey, privateKey }
return inMemoryKeypair
} catch {
logger.log('[ClientKeyStore]', 'Failed to decrypt client keypair')
throw new Error(AUTH_ERROR_PATTERNS.MASTER_PASSWORD_INVALID)
}
}
/**
* Persist the pending keystore record from unlockKeypair's no-record branch.
* No-op if nothing is pending. Call only after the vault has accepted the
* master password, so an unverified password never lands on disk.
*
* @returns {Promise<void>}
*/
export const commitPendingClientKeystore = async () => {
if (!pendingPersistRecord) return
const db = await openDb()
await putKeyRecord(db, pendingPersistRecord)
pendingPersistRecord = null
}
/**
* Check if a keypair has been persisted to IndexedDB.
* @returns {Promise<boolean>}
*/
export const hasPersistedClientKeypair = async () => {
try {
const db = await openDb()
const record = await getKeyRecord(db)
if (
!record?.publicKeyB64 ||
!record?.saltB64 ||
!record?.nonceB64 ||
!record?.ciphertextB64
) {
logger.log(
'[ClientKeyStore] hasPersistedClientKeypair: false (missing fields)'
)
return false
}
// Validate field lengths by decoding
try {
const publicKey = base64Decode(record.publicKeyB64)
const salt = base64Decode(record.saltB64)
const nonce = base64Decode(record.nonceB64)
const ciphertext = base64Decode(record.ciphertextB64)
// Ed25519 public key must be 32 bytes
// Salt must be 16 bytes (from encryptPrivateKey)
// Nonce must be 12 bytes (from encryptPrivateKey)
// Ciphertext must be 48 bytes (32 byte private key + 16 byte GCM auth tag)
const isValid =
publicKey.length === 32 &&
salt.length === 16 &&
nonce.length === 12 &&
ciphertext.length === 48
logger.log(
'[ClientKeyStore] hasPersistedClientKeypair:',
isValid,
isValid ? 'valid' : 'invalid field lengths'
)
return isValid
} catch (decodeError) {
logger.log(
'[ClientKeyStore] hasPersistedClientKeypair: false (invalid base64)',
decodeError?.message
)
return false
}
} catch (e) {
logger.log(
'[ClientKeyStore] hasPersistedClientKeypair: false (error)',
e?.message
)
return false
}
}
/**
* Clear keypair from memory and storage.
* @returns {Promise<void>}
*/
export const clearClientKeypair = async () => {
// Zero and clear in-memory state
secureZero(inMemoryKeypair?.privateKey)
inMemoryKeypair = null
secureZero(pendingKeypair?.privateKey)
pendingKeypair = null
pendingPersistRecord = null
// Reset unlocking flag to cancel any in-progress unlock
unlocking = false
// Delete from IndexedDB
try {
const db = await openDb()
await deleteKeyRecord(db)
logger.log('[ClientKeyStore]', 'Keypair cleared')
} catch (e) {
logger.log('[ClientKeyStore]', 'Failed to clear keypair:', e?.message)
}
}
const deleteKeyRecord = (db) =>
new Promise((resolve, reject) => {
try {
const tx = db.transaction(STORE_NAME, 'readwrite')
const store = tx.objectStore(STORE_NAME)
const request = store.delete(KEY_ID)
tx.oncomplete = () => {
resolve()
}
tx.onerror = () => {
reject(tx.error)
}
request.onerror = () => {
reject(request.error)
}
} catch (error) {
reject(error)
}
})