-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
vault.service.ts
324 lines (282 loc) · 9.96 KB
/
vault.service.ts
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
import * as crypto from 'crypto'
import { promisify } from 'util'
import { Injectable, NgZone } from '@angular/core'
import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
import { AsyncSubject, Subject, Observable } from 'rxjs'
import { wrapPromise, serializeFunction } from '../utils'
import { UnlockVaultModalComponent } from '../components/unlockVaultModal.component'
import { NotificationsService } from './notifications.service'
import { SelectorService } from './selector.service'
import { FileProvider } from '../api/fileProvider'
import { PlatformService } from '../api/platform'
const PBKDF_ITERATIONS = 100000
const PBKDF_DIGEST = 'sha512'
const PBKDF_SALT_LENGTH = 64 / 8
const CRYPT_ALG = 'aes-256-cbc'
const CRYPT_KEY_LENGTH = 256 / 8
const CRYPT_IV_LENGTH = 128 / 8
export interface StoredVault {
version: number
contents: string
keySalt: string
iv: string
}
export interface VaultSecret {
type: string
key: VaultSecretKey
value: string
}
export interface VaultFileSecret extends VaultSecret {
key: {
id: string
description: string
}
}
export interface Vault {
config: any
secrets: VaultSecret[]
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface VaultSecretKey { }
function migrateVaultContent (content: any): Vault {
return {
config: content.config,
secrets: content.secrets ?? [],
}
}
function deriveVaultKey (passphrase: string, salt: Buffer): Promise<Buffer> {
return promisify(crypto.pbkdf2)(
Buffer.from(passphrase),
salt,
PBKDF_ITERATIONS,
CRYPT_KEY_LENGTH,
PBKDF_DIGEST,
)
}
async function encryptVault (content: Vault, passphrase: string): Promise<StoredVault> {
const keySalt = await promisify(crypto.randomBytes)(PBKDF_SALT_LENGTH)
const iv = await promisify(crypto.randomBytes)(CRYPT_IV_LENGTH)
const key = await deriveVaultKey(passphrase, keySalt)
const plaintext = JSON.stringify(content)
const cipher = crypto.createCipheriv(CRYPT_ALG, key, iv)
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf-8'), cipher.final()])
return {
version: 1,
contents: encrypted.toString('base64'),
keySalt: keySalt.toString('hex'),
iv: iv.toString('hex'),
}
}
async function decryptVault (vault: StoredVault, passphrase: string): Promise<Vault> {
if (vault.version !== 1) {
throw new Error(`Unsupported vault format version ${vault.version}`)
}
const keySalt = Buffer.from(vault.keySalt, 'hex')
const key = await deriveVaultKey(passphrase, keySalt)
const iv = Buffer.from(vault.iv, 'hex')
const encrypted = Buffer.from(vault.contents, 'base64')
const decipher = crypto.createDecipheriv(CRYPT_ALG, key, iv)
const plaintext = decipher.update(encrypted, undefined, 'utf-8') + decipher.final('utf-8')
return migrateVaultContent(JSON.parse(plaintext))
}
export const VAULT_SECRET_TYPE_FILE = 'file'
// Don't make it accessible through VaultService fields
let _rememberedPassphrase: string|null = null
@Injectable({ providedIn: 'root' })
export class VaultService {
/** Fires once when the config is loaded */
get ready$ (): Observable<boolean> { return this.ready }
get contentChanged$ (): Observable<void> { return this.contentChanged }
store: StoredVault|null = null
private ready = new AsyncSubject<boolean>()
private contentChanged = new Subject<void>()
/** @hidden */
private constructor (
private zone: NgZone,
private notifications: NotificationsService,
private ngbModal: NgbModal,
) {
this.getPassphrase = serializeFunction(this.getPassphrase.bind(this))
}
async setEnabled (enabled: boolean, passphrase?: string): Promise<void> {
if (enabled) {
if (!this.store) {
await this.save(migrateVaultContent({}), passphrase)
}
} else {
this.store = null
this.contentChanged.next()
}
}
isOpen (): boolean {
return !!_rememberedPassphrase
}
forgetPassphrase (): void {
_rememberedPassphrase = null
}
async decrypt (storage: StoredVault, passphrase?: string): Promise<Vault> {
if (!passphrase) {
passphrase = await this.getPassphrase()
}
try {
return await wrapPromise(this.zone, decryptVault(storage, passphrase))
} catch (e) {
this.forgetPassphrase()
if (e.toString().includes('BAD_DECRYPT')) {
this.notifications.error('Incorrect passphrase')
}
throw e
}
}
async load (passphrase?: string): Promise<Vault|null> {
if (!this.store) {
return null
}
return this.decrypt(this.store, passphrase)
}
async encrypt (vault: Vault, passphrase?: string): Promise<StoredVault|null> {
if (!passphrase) {
passphrase = await this.getPassphrase()
}
if (_rememberedPassphrase) {
_rememberedPassphrase = passphrase
}
return wrapPromise(this.zone, encryptVault(vault, passphrase))
}
async save (vault: Vault, passphrase?: string): Promise<void> {
await this.ready$.toPromise()
this.store = await this.encrypt(vault, passphrase)
this.contentChanged.next()
}
async getPassphrase (): Promise<string> {
if (!_rememberedPassphrase) {
const modal = this.ngbModal.open(UnlockVaultModalComponent)
const { passphrase, rememberFor } = await modal.result
setTimeout(() => {
_rememberedPassphrase = null
// avoid multiple consequent prompts
}, Math.max(1000, rememberFor * 60000))
_rememberedPassphrase = passphrase
}
return _rememberedPassphrase!
}
async getSecret (type: string, key: VaultSecretKey): Promise<VaultSecret|null> {
await this.ready$.toPromise()
const vault = await this.load()
if (!vault) {
return null
}
return vault.secrets.find(s => s.type === type && this.keyMatches(key, s)) ?? null
}
async addSecret (secret: VaultSecret): Promise<void> {
await this.ready$.toPromise()
const vault = await this.load()
if (!vault) {
return
}
vault.secrets = vault.secrets.filter(s => s.type !== secret.type || !this.keyMatches(secret.key, s))
vault.secrets.push(secret)
await this.save(vault)
}
async updateSecret (secret: VaultSecret, update: VaultSecret): Promise<void> {
await this.ready$.toPromise()
const vault = await this.load()
if (!vault) {
return
}
const target = vault.secrets.find(s => s.type === secret.type && this.keyMatches(secret.key, s))
if (!target) {
return
}
Object.assign(target, update)
await this.save(vault)
}
async removeSecret (type: string, key: VaultSecretKey): Promise<void> {
await this.ready$.toPromise()
const vault = await this.load()
if (!vault) {
return
}
vault.secrets = vault.secrets.filter(s => s.type !== type || !this.keyMatches(key, s))
await this.save(vault)
}
private keyMatches (key: VaultSecretKey, secret: VaultSecret): boolean {
return Object.keys(key).every(k => secret.key[k] === key[k])
}
setStore (store: StoredVault): void {
this.store = store
this.ready.next(true)
this.ready.complete()
}
isEnabled (): boolean {
return !!this.store
}
}
@Injectable()
export class VaultFileProvider extends FileProvider {
name = 'Vault'
prefix = 'vault://'
constructor (
private vault: VaultService,
private platform: PlatformService,
private selector: SelectorService,
private zone: NgZone,
) {
super()
}
async isAvailable (): Promise<boolean> {
return this.vault.isEnabled()
}
async selectAndStoreFile (description: string): Promise<string> {
const vault = await this.vault.load()
if (!vault) {
throw new Error('Vault is locked')
}
const files = vault.secrets.filter(x => x.type === VAULT_SECRET_TYPE_FILE) as VaultFileSecret[]
if (files.length) {
const result = await this.selector.show<VaultFileSecret|null>('Select file', [
{
name: 'Add a new file',
icon: 'fas fa-plus',
result: null,
},
...files.map(f => ({
name: f.key.description,
icon: 'fas fa-file',
result: f,
})),
]).catch(() => null)
if (result) {
return `${this.prefix}${result.key.id}`
}
}
return this.addNewFile(description)
}
async addNewFile (description: string): Promise<string> {
const transfers = await this.platform.startUpload()
if (!transfers.length) {
throw new Error('Nothing selected')
}
const transfer = transfers[0]
const id = (await wrapPromise(this.zone, promisify(crypto.randomBytes)(32))).toString('hex')
await this.vault.addSecret({
type: VAULT_SECRET_TYPE_FILE,
key: {
id,
description: `${description} (${transfer.getName()})`,
},
value: (await transfer.readAll()).toString('base64'),
})
return `${this.prefix}${id}`
}
async retrieveFile (key: string): Promise<Buffer> {
if (!key.startsWith(this.prefix)) {
throw new Error('Incorrect type')
}
const secret = await this.vault.getSecret(VAULT_SECRET_TYPE_FILE, { id: key.substring(this.prefix.length) })
if (!secret) {
throw new Error('Not found')
}
return Buffer.from(secret.value, 'base64')
}
}