-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
/
config.service.ts
493 lines (459 loc) · 17.5 KB
/
config.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
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import deepClone from 'clone-deep'
import deepEqual from 'deep-equal'
import { v4 as uuidv4 } from 'uuid'
import * as yaml from 'js-yaml'
import { Observable, Subject, AsyncSubject, lastValueFrom } from 'rxjs'
import { Injectable, Inject } from '@angular/core'
import { TranslateService } from '@ngx-translate/core'
import { ConfigProvider } from '../api/configProvider'
import { PlatformService } from '../api/platform'
import { HostAppService } from '../api/hostApp'
import { Vault, VaultService } from './vault.service'
import { serializeFunction } from '../utils'
import { PartialProfileGroup, ProfileGroup } from '../api/profileProvider'
const deepmerge = require('deepmerge')
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const configMerge = (a, b) => deepmerge(a, b, { arrayMerge: (_d, s) => s }) // eslint-disable-line @typescript-eslint/no-var-requires
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export const configMergeByDefault = (a, b) => deepmerge(a, b) // eslint-disable-line @typescript-eslint/no-var-requires
const LATEST_VERSION = 1
function isStructuralMember (v) {
return v instanceof Object && !(v instanceof Array) &&
Object.keys(v).length > 0 && !v.__nonStructural
}
function isNonStructuralObjectMember (v): boolean {
return v instanceof Object && (v instanceof Array || v.__nonStructural)
}
/** @hidden */
export class ConfigProxy {
constructor (real: Record<string, any>, defaults: Record<string, any>) {
for (const key in defaults) {
if (isStructuralMember(defaults[key])) {
if (!real[key]) {
real[key] = {}
}
const proxy = new ConfigProxy(real[key], defaults[key])
Object.defineProperty(
this,
key,
{
enumerable: true,
configurable: false,
get: () => proxy,
},
)
} else {
Object.defineProperty(
this,
key,
{
enumerable: true,
configurable: false,
get: () => this.__getValue(key),
set: (value) => {
this.__setValue(key, value)
},
},
)
}
}
this.__getValue = (key: string) => { // eslint-disable-line @typescript-eslint/unbound-method
if (real[key] !== undefined) {
return real[key]
} else {
if (isNonStructuralObjectMember(defaults[key])) {
// The object might be modified outside
real[key] = this.__getDefault(key)
delete real[key].__nonStructural
return real[key]
}
return this.__getDefault(key)
}
}
this.__getDefault = (key: string) => { // eslint-disable-line @typescript-eslint/unbound-method
return deepClone(defaults[key])
}
this.__setValue = (key: string, value: any) => { // eslint-disable-line @typescript-eslint/unbound-method
if (deepEqual(value, this.__getDefault(key))) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete real[key]
} else {
real[key] = value
}
}
this.__cleanup = () => { // eslint-disable-line @typescript-eslint/unbound-method
// Trigger removal of default values
for (const key in defaults) {
if (isStructuralMember(defaults[key])) {
this[key].__cleanup()
} else {
const v = this.__getValue(key)
this.__setValue(key, v)
}
}
}
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-empty-function
__getValue (_key: string): any { }
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-empty-function
__setValue (_key: string, _value: any) { }
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-empty-function
__getDefault (_key: string): any { }
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-empty-function
__cleanup () { }
}
@Injectable({ providedIn: 'root' })
export class ConfigService {
/**
* Contains the actual config values
*/
store: any
/**
* Whether an app restart is required due to recent changes
*/
restartRequested: boolean
/** Fires once when the config is loaded */
get ready$ (): Observable<boolean> { return this.ready }
private ready = new AsyncSubject<boolean>()
private changed = new Subject<void>()
private _store: any
private defaults: any
private servicesCache: Record<string, Function[]>|null = null // eslint-disable-line @typescript-eslint/ban-types
get changed$ (): Observable<void> { return this.changed }
/** @hidden */
private constructor (
private hostApp: HostAppService,
private platform: PlatformService,
private vault: VaultService,
private translate: TranslateService,
@Inject(ConfigProvider) private configProviders: ConfigProvider[],
) {
this.defaults = this.mergeDefaults()
setTimeout(() => this.init())
vault.contentChanged$.subscribe(() => {
this.store.vault = vault.store
this.save()
})
this.save = serializeFunction(this.save.bind(this))
}
mergeDefaults (): unknown {
const providers = this.configProviders
return providers.map(provider => {
let defaults = provider.platformDefaults[this.hostApp.configPlatform] ?? {}
defaults = configMerge(
defaults,
provider.platformDefaults[this.hostApp.platform] ?? {},
)
if (provider.defaults) {
defaults = configMerge(provider.defaults, defaults)
}
return defaults
}).reduce(configMergeByDefault)
}
getDefaults (): Record<string, any> {
const cleanup = o => {
if (o instanceof Array) {
return o.map(cleanup)
} else if (o instanceof Object) {
const r = {}
for (const k of Object.keys(o)) {
if (k !== '__nonStructural') {
r[k] = cleanup(o[k])
}
}
return r
} else {
return o
}
}
return cleanup(this.defaults)
}
async load (): Promise<void> {
const content = await this.platform.loadConfig()
if (content) {
this._store = yaml.load(content)
} else {
this._store = { version: LATEST_VERSION }
}
this._store = await this.maybeDecryptConfig(this._store)
this.migrate(this._store)
this.store = new ConfigProxy(this._store, this.defaults)
this.vault.setStore(this.store.vault)
}
async save (): Promise<void> {
await lastValueFrom(this.ready$)
if (!this._store) {
throw new Error('Cannot save an empty store')
}
// Scrub undefined values
let cleanStore = JSON.parse(JSON.stringify(this._store))
cleanStore = await this.maybeEncryptConfig(cleanStore)
await this.platform.saveConfig(yaml.dump(cleanStore))
this.emitChange()
}
/**
* Reads config YAML as string
*/
readRaw (): string {
// Scrub undefined values
const cleanStore = JSON.parse(JSON.stringify(this._store))
return yaml.dump(cleanStore)
}
/**
* Writes config YAML as string
*/
async writeRaw (data: string): Promise<void> {
this._store = yaml.load(data)
await this.save()
await this.load()
this.emitChange()
}
requestRestart (): void {
this.restartRequested = true
}
/**
* Filters a list of Angular services to only include those provided
* by plugins that are enabled
*
* @typeparam T Base provider type
*/
enabledServices<T extends object> (services: T[]|undefined): T[] { // eslint-disable-line @typescript-eslint/ban-types
if (!services) {
return []
}
if (!this.servicesCache) {
this.servicesCache = {}
for (const imp of window['pluginModules']) {
const module = imp.ngModule || imp
if (module.ɵinj?.providers) {
this.servicesCache[module.pluginName] = module.ɵinj.providers.map(provider => {
return provider.useClass ?? provider.useExisting ?? provider
})
}
}
}
return services.filter(service => {
for (const pluginName in this.servicesCache) {
if (this.servicesCache[pluginName].includes(service.constructor)) {
const id = `${pluginName}:${service.constructor.name}`
return !this.store?.pluginBlacklist?.includes(pluginName)
&& !this.store?.providerBlacklist?.includes(id)
}
}
return true
})
}
private async init () {
await this.load()
this.ready.next(true)
this.ready.complete()
this.hostApp.configChangeBroadcast$.subscribe(async () => {
await this.load()
this.emitChange()
})
}
private emitChange (): void {
this.vault.setStore(this.store.vault)
this.changed.next()
}
private migrate (config) {
config.version ??= 0
if (config.version < 1) {
for (const connection of config.ssh?.connections ?? []) {
if (connection.privateKey) {
connection.privateKeys = [connection.privateKey]
delete connection.privateKey
}
}
config.version = 1
}
if (config.version < 2) {
config.profiles ??= []
if (config.terminal?.recoverTabs !== undefined) {
config.recoverTabs = config.terminal.recoverTabs
delete config.terminal.recoverTabs
}
for (const profile of config.terminal?.profiles ?? []) {
if (profile.sessionOptions) {
profile.options = profile.sessionOptions
delete profile.sessionOptions
}
profile.type = 'local'
profile.id = `local:custom:${uuidv4()}`
}
if (config.terminal?.profiles) {
config.profiles = config.terminal.profiles
delete config.terminal.profiles
delete config.terminal.environment
config.terminal.profile = `local:${config.terminal.profile}`
}
config.version = 2
}
if (config.version < 3) {
delete config.ssh?.recentConnections
for (const c of config.ssh?.connections ?? []) {
const p = {
id: `ssh:${uuidv4()}`,
type: 'ssh',
icon: 'fas fa-desktop',
name: c.name,
group: c.group ?? undefined,
color: c.color,
disableDynamicTitle: c.disableDynamicTitle,
options: c,
}
config.profiles.push(p)
}
for (const p of config.profiles ?? []) {
if (p.type === 'ssh') {
if (p.options.jumpHost) {
p.options.jumpHost = config.profiles.find(x => x.name === p.options.jumpHost)?.id
}
}
}
for (const c of config.serial?.connections ?? []) {
const p = {
id: `serial:${uuidv4()}`,
type: 'serial',
icon: 'fas fa-microchip',
name: c.name,
group: c.group ?? undefined,
color: c.color,
options: c,
}
config.profiles.push(p)
}
delete config.ssh?.connections
delete config.serial?.connections
delete window.localStorage.lastSerialConnection
config.version = 3
}
if (config.version < 4) {
for (const p of config.profiles ?? []) {
if (!p.id) {
p.id = `${p.type}:custom:${uuidv4()}`
}
}
config.version = 4
}
if (config.version < 5) {
const groups: PartialProfileGroup<ProfileGroup>[] = []
for (const p of config.profiles ?? []) {
if (!(p.group ?? '').trim()) {
continue
}
let group = groups.find(x => x.name === p.group)
if (!group) {
group = {
id: `${uuidv4()}`,
name: `${p.group}`,
}
groups.push(group)
}
p.group = group.id
}
const profileGroupCollapsed = JSON.parse(window.localStorage.profileGroupCollapsed ?? '{}')
for (const g of groups) {
if (profileGroupCollapsed[g.name]) {
const collapsed = profileGroupCollapsed[g.name]
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete profileGroupCollapsed[g.name]
profileGroupCollapsed[g.id] = collapsed
}
}
window.localStorage.profileGroupCollapsed = JSON.stringify(profileGroupCollapsed)
config.groups = groups
config.version = 5
}
if (config.version < 6) {
if (config.ssh?.clearServiceMessagesOnConnect === false) {
config.profileDefaults ??= {}
config.profileDefaults.ssh ??= {}
config.profileDefaults.ssh.clearServiceMessagesOnConnect = false
delete config.ssh?.clearServiceMessagesOnConnect
}
config.version = 6
}
if (config.version < 7) {
if (!config.configSync?.host || config.configSync?.host === 'https://api.tabby.sh') {
config.configSync ??= {}
delete config.configSync.host
delete config.configSync.token
}
config.version = 7
}
}
private async maybeDecryptConfig (store) {
if (!store.encrypted) {
return store
}
// eslint-disable-next-line @typescript-eslint/init-declarations
let decryptedVault: Vault
while (true) {
try {
const passphrase = await this.vault.getPassphrase()
decryptedVault = await this.vault.decrypt(store.vault, passphrase)
break
} catch (e) {
let result = await this.platform.showMessageBox({
type: 'error',
message: this.translate.instant('Could not decrypt config'),
detail: e.toString(),
buttons: [
this.translate.instant('Try again'),
this.translate.instant('Erase config'),
this.translate.instant('Quit'),
],
defaultId: 0,
})
if (result.response === 2) {
this.platform.quit()
}
if (result.response === 1) {
result = await this.platform.showMessageBox({
type: 'warning',
message: this.translate.instant('Are you sure?'),
detail: e.toString(),
buttons: [
this.translate.instant('Erase config'),
this.translate.instant('Quit'),
],
defaultId: 1,
cancelId: 1,
})
if (result.response === 1) {
this.platform.quit()
}
return {}
}
}
}
delete decryptedVault.config.vault
delete decryptedVault.config.encrypted
delete decryptedVault.config.configSync
return {
...decryptedVault.config,
vault: store.vault,
encrypted: store.encrypted,
configSync: store.configSync,
}
}
private async maybeEncryptConfig (store) {
if (!store.encrypted) {
return store
}
const vault = await this.vault.load()
if (!vault) {
throw new Error('Vault not configured')
}
vault.config = { ...store }
delete vault.config.vault
delete vault.config.encrypted
delete vault.config.configSync
return {
vault: await this.vault.encrypt(vault),
encrypted: true,
configSync: store.configSync,
}
}
}