/
Application.ts
1142 lines (956 loc) · 36.1 KB
/
Application.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { MfaService } from './../Services/Mfa/MfaService'
import { KeyRecoveryService } from './../Services/KeyRecovery/KeyRecoveryService'
import { MigrationService } from './../Services/Migration/MigrationService'
import { LegacyApiService } from './../Services/Api/ApiService'
import { FeaturesService } from '@Lib/Services/Features/FeaturesService'
import { PreferencesService } from './../Services/Preferences/PreferencesService'
import { ProtectionService } from './../Services/Protection/ProtectionService'
import { SessionManager } from './../Services/Session/SessionManager'
import { HttpService, HttpServiceInterface, UserRegistrationResponseBody } from '@standardnotes/api'
import { ApplicationIdentifier, compareVersions, ProtocolVersion, KeyParamsOrigination } from '@standardnotes/common'
import {
DeinitCallback,
SessionEvent,
SyncEvent,
ApplicationStage,
FeaturesEvent,
SyncMode,
SyncSource,
ApplicationStageChangedEventPayload,
StorageValueModes,
ChallengeObserver,
ImportDataResult,
ImportData,
StoragePersistencePolicies,
HomeServerServiceInterface,
DeviceInterface,
SubscriptionManagerInterface,
FeaturesClientInterface,
ItemManagerInterface,
SyncServiceInterface,
UserServiceInterface,
MutatorClientInterface,
StatusServiceInterface,
AlertService,
StorageServiceInterface,
ChallengeServiceInterface,
AsymmetricMessageServiceInterface,
VaultServiceInterface,
ContactServiceInterface,
SharedVaultServiceInterface,
PreferenceServiceInterface,
InternalEventBusInterface,
ApplicationEvent,
ApplicationEventCallback,
ChallengeValidation,
ComponentManagerInterface,
ChallengeValue,
StorageKey,
ChallengeReason,
DeinitMode,
DeinitSource,
AppGroupManagedApplication,
ApplicationInterface,
EncryptionService,
EncryptionServiceEvent,
Challenge,
ErrorAlertStrings,
SessionsClientInterface,
ProtectionsClientInterface,
UserService,
ProtocolUpgradeStrings,
CredentialsChangeFunctionResponse,
SessionStrings,
AccountEvent,
PayloadManagerInterface,
HistoryServiceInterface,
InternalEventPublishStrategy,
EncryptionProviderInterface,
VaultUserServiceInterface,
VaultInviteServiceInterface,
VaultLockServiceInterface,
ApplicationConstructorOptions,
FullyResolvedApplicationOptions,
ApplicationOptionsDefaults,
ChangeAndSaveItem,
ProtectionEvent,
GetHost,
SetHost,
MfaServiceInterface,
GenerateUuid,
CreateDecryptedBackupFile,
CreateEncryptedBackupFile,
WebSocketsService,
PreferencesServiceEvent,
} from '@standardnotes/services'
import {
SNNote,
PrefKey,
PrefValue,
BackupFile,
EncryptedItemInterface,
Environment,
Platform,
} from '@standardnotes/models'
import {
HttpResponse,
SessionListResponse,
SignInResponse,
ClientDisplayableError,
SessionListEntry,
} from '@standardnotes/responses'
import {
SyncService,
SettingsService,
ActionsService,
ChallengeResponse,
ListedClientInterface,
DiskStorageService,
} from '../Services'
import {
nonSecureRandomIdentifier,
assertUnreachable,
removeFromArray,
isNullOrUndefined,
sleep,
useBoolean,
LoggerInterface,
canBlockDeinit,
} from '@standardnotes/utils'
import { UuidString, ApplicationEventPayload } from '../Types'
import { applicationEventForSyncEvent } from '@Lib/Application/Event'
import { BackupServiceInterface, FilesClientInterface } from '@standardnotes/files'
import { ComputePrivateUsername } from '@standardnotes/encryption'
import { SNLog } from '../Log'
import { SignInWithRecoveryCodes } from '@Lib/Domain/UseCase/SignInWithRecoveryCodes/SignInWithRecoveryCodes'
import { UseCaseContainerInterface } from '@Lib/Domain/UseCase/UseCaseContainerInterface'
import { GetRecoveryCodes } from '@Lib/Domain/UseCase/GetRecoveryCodes/GetRecoveryCodes'
import { AddAuthenticator } from '@Lib/Domain/UseCase/AddAuthenticator/AddAuthenticator'
import { ListAuthenticators } from '@Lib/Domain/UseCase/ListAuthenticators/ListAuthenticators'
import { DeleteAuthenticator } from '@Lib/Domain/UseCase/DeleteAuthenticator/DeleteAuthenticator'
import { ListRevisions } from '@Lib/Domain/UseCase/ListRevisions/ListRevisions'
import { GetRevision } from '@Lib/Domain/UseCase/GetRevision/GetRevision'
import { DeleteRevision } from '@Lib/Domain/UseCase/DeleteRevision/DeleteRevision'
import { GetAuthenticatorAuthenticationResponse } from '@Lib/Domain/UseCase/GetAuthenticatorAuthenticationResponse/GetAuthenticatorAuthenticationResponse'
import { GetAuthenticatorAuthenticationOptions } from '@Lib/Domain/UseCase/GetAuthenticatorAuthenticationOptions/GetAuthenticatorAuthenticationOptions'
import { Dependencies } from './Dependencies/Dependencies'
import { TYPES } from './Dependencies/Types'
import { RegisterApplicationServicesEvents } from './Dependencies/DependencyEvents'
import { Result } from '@standardnotes/domain-core'
type LaunchCallback = {
receiveChallenge: (challenge: Challenge) => void
}
type ApplicationObserver = {
singleEvent?: ApplicationEvent
callback: ApplicationEventCallback
}
type ObserverRemover = () => void
export class SNApplication implements ApplicationInterface, AppGroupManagedApplication, UseCaseContainerInterface {
onDeinit!: DeinitCallback
/**
* A runtime based identifier for each dynamic instantiation of the application instance.
* This differs from the persistent application.identifier which persists in storage
* across instantiations.
*/
public readonly ephemeralIdentifier = nonSecureRandomIdentifier()
private eventHandlers: ApplicationObserver[] = []
private serviceObservers: ObserverRemover[] = []
private managedSubscribers: ObserverRemover[] = []
/** True if the result of deviceInterface.openDatabase yields a new database being created */
private createdNewDatabase = false
/** True if the application has started (but not necessarily launched) */
private started = false
/** True if the application has launched */
private launched = false
/** Whether the application has been destroyed via .deinit() */
public dealloced = false
private revokingSession = false
private handledFullSyncStage = false
public readonly environment: Environment
public readonly platform: Platform
public readonly identifier: ApplicationIdentifier
public readonly options: FullyResolvedApplicationOptions
private dependencies: Dependencies
constructor(options: ApplicationConstructorOptions) {
const allOptions: FullyResolvedApplicationOptions = {
...ApplicationOptionsDefaults,
...options,
}
if (!SNLog.onLog) {
throw Error('SNLog.onLog must be set.')
}
if (!SNLog.onError) {
throw Error('SNLog.onError must be set.')
}
const requiredOptions: (keyof FullyResolvedApplicationOptions)[] = [
'deviceInterface',
'environment',
'platform',
'crypto',
'alertService',
'identifier',
'defaultHost',
'appVersion',
'apiVersion',
]
for (const optionName of requiredOptions) {
if (!allOptions[optionName]) {
throw Error(`${optionName} must be supplied when creating an application.`)
}
}
this.environment = options.environment
this.platform = options.platform
this.identifier = options.identifier
this.options = Object.freeze(allOptions)
this.dependencies = new Dependencies(this.options)
const logger = this.dependencies.get<LoggerInterface>(TYPES.Logger)
logger.setLevel('error')
this.registerServiceObservers()
RegisterApplicationServicesEvents(this.dependencies, this.events)
}
private registerServiceObservers() {
const encryptionService = this.dependencies.get<EncryptionService>(TYPES.EncryptionService)
this.serviceObservers.push(
encryptionService.addEventObserver(async (event) => {
if (event === EncryptionServiceEvent.RootKeyStatusChanged) {
await this.notifyEvent(ApplicationEvent.KeyStatusChanged)
}
}),
)
this.dependencies.get<DiskStorageService>(TYPES.DiskStorageService).provideEncryptionProvider(encryptionService)
const apiService = this.dependencies.get<LegacyApiService>(TYPES.LegacyApiService)
this.dependencies
.get<HttpService>(TYPES.HttpService)
.setCallbacks(apiService.processMetaObject.bind(apiService), apiService.setSession.bind(apiService))
this.serviceObservers.push(
this.dependencies.get<SessionManager>(TYPES.SessionManager).addEventObserver(async (event) => {
switch (event) {
case SessionEvent.Restored: {
void (async () => {
await this.sync.sync({ sourceDescription: 'Session restored pre key creation' })
if (encryptionService.needsNewRootKeyBasedItemsKey()) {
void encryptionService.createNewDefaultItemsKey().then(() => {
void this.sync.sync({ sourceDescription: 'Session restored post key creation' })
})
}
})()
break
}
case SessionEvent.Revoked: {
await this.handleRevokedSession()
break
}
case SessionEvent.UserKeyPairChanged:
break
default: {
assertUnreachable(event)
}
}
}),
)
const syncEventCallback = async (eventName: SyncEvent) => {
const appEvent = applicationEventForSyncEvent(eventName)
if (appEvent) {
await encryptionService.onSyncEvent(eventName)
await this.notifyEvent(appEvent)
if (appEvent === ApplicationEvent.CompletedFullSync) {
if (!this.handledFullSyncStage) {
this.handledFullSyncStage = true
await this.handleStage(ApplicationStage.FullSyncCompleted_13)
}
}
}
}
const syncService = this.dependencies.get<SyncService>(TYPES.SyncService)
const uninstall = syncService.addEventObserver(syncEventCallback)
this.serviceObservers.push(uninstall)
const protectionService = this.dependencies.get<ProtectionService>(TYPES.ProtectionService)
this.serviceObservers.push(
protectionService.addEventObserver((event) => {
if (event === ProtectionEvent.UnprotectedSessionBegan) {
void this.notifyEvent(ApplicationEvent.UnprotectedSessionBegan)
} else if (event === ProtectionEvent.UnprotectedSessionExpired) {
void this.notifyEvent(ApplicationEvent.UnprotectedSessionExpired)
}
}),
)
const userService = this.dependencies.get<UserService>(TYPES.UserService)
this.serviceObservers.push(
userService.addEventObserver(async (event, data) => {
switch (event) {
case AccountEvent.SignedInOrRegistered: {
void this.notifyEvent(ApplicationEvent.SignedIn)
break
}
case AccountEvent.SignedOut: {
await this.notifyEvent(ApplicationEvent.SignedOut)
await this.prepareForDeinit()
this.deinit(this.getDeinitMode(), data?.payload.source || DeinitSource.SignOut)
break
}
default: {
assertUnreachable(event)
}
}
}),
)
const preferencesService = this.dependencies.get<PreferencesService>(TYPES.PreferencesService)
this.serviceObservers.push(
preferencesService.addEventObserver((event) => {
if (event === PreferencesServiceEvent.PreferencesChanged) {
void this.notifyEvent(ApplicationEvent.PreferencesChanged)
} else if (event === PreferencesServiceEvent.LocalPreferencesChanged) {
void this.notifyEvent(ApplicationEvent.LocalPreferencesChanged)
}
}),
)
const featuresService = this.dependencies.get<FeaturesService>(TYPES.FeaturesService)
this.serviceObservers.push(
featuresService.addEventObserver((event) => {
switch (event) {
case FeaturesEvent.UserRolesChanged: {
void this.notifyEvent(ApplicationEvent.UserRolesChanged)
break
}
case FeaturesEvent.FeaturesAvailabilityChanged: {
void this.notifyEvent(ApplicationEvent.FeaturesAvailabilityChanged)
break
}
case FeaturesEvent.DidPurchaseSubscription: {
void this.notifyEvent(ApplicationEvent.DidPurchaseSubscription)
break
}
default: {
assertUnreachable(event)
}
}
}),
)
}
public computePrivateUsername(username: string): Promise<string | undefined> {
return ComputePrivateUsername(this.options.crypto, username)
}
/**
* The first thing consumers should call when starting their app.
* This function will load all services in their correct order.
*/
async prepareForLaunch(callback: LaunchCallback): Promise<void> {
if (this.launched) {
throw new Error('Attempting to prelaunch already launched application')
}
await this.options.crypto.initialize()
this.setLaunchCallback(callback)
const databaseResult = await this.device.openDatabase(this.identifier).catch((error) => {
void this.notifyEvent(ApplicationEvent.LocalDatabaseReadError, error)
return undefined
})
this.createdNewDatabase = useBoolean(databaseResult?.isNewDatabase, false)
await this.migrations.initialize()
await this.notifyEvent(ApplicationEvent.MigrationsLoaded)
await this.handleStage(ApplicationStage.PreparingForLaunch_0)
await this.storage.initializeFromDisk()
await this.notifyEvent(ApplicationEvent.StorageReady)
await this.encryption.initialize()
await this.handleStage(ApplicationStage.ReadyForLaunch_05)
this.started = true
await this.notifyEvent(ApplicationEvent.Started)
}
private setLaunchCallback(callback: LaunchCallback) {
this.challenges.sendChallenge = callback.receiveChallenge
}
/**
* Handles device authentication, unlocks application, and
* issues a callback if a device activation requires user input
* (i.e local passcode or fingerprint).
* @param awaitDatabaseLoad
* Option to await database load before marking the app as ready.
*/
public async launch(awaitDatabaseLoad = false): Promise<void> {
if (this.launched) {
throw new Error('Attempting to launch already launched application')
}
this.launched = false
const launchChallenge = this.getLaunchChallenge()
if (launchChallenge) {
const response = await this.challenges.promptForChallengeResponse(launchChallenge)
if (!response) {
throw Error('Launch challenge was cancelled.')
}
await this.handleLaunchChallengeResponse(response)
}
if (this.storage.isStorageWrapped()) {
try {
await this.storage.decryptStorage()
} catch (_error) {
void this.alerts.alert(ErrorAlertStrings.StorageDecryptErrorBody, ErrorAlertStrings.StorageDecryptErrorTitle)
}
}
await this.handleStage(ApplicationStage.StorageDecrypted_09)
const host = this.legacyApi.loadHost()
this.http.setHost(host)
this.sockets.loadWebSocketUrl()
this.settings.initializeFromDisk()
this.launched = true
await this.notifyEvent(ApplicationEvent.Launched)
await this.handleStage(ApplicationStage.Launched_10)
await this.handleStage(ApplicationStage.LoadingDatabase_11)
if (this.createdNewDatabase) {
await this.sync.onNewDatabaseCreated()
}
/**
* We don't want to await this, as we want to begin allowing the app to function
* before local data has been loaded fully.
*/
const loadPromise = this.sync
.loadDatabasePayloads()
.then(async () => {
if (this.dealloced) {
throw 'Application has been destroyed.'
}
await this.handleStage(ApplicationStage.LoadedDatabase_12)
this.sync.beginAutoSyncTimer()
await this.sync.sync({
mode: SyncMode.DownloadFirst,
source: SyncSource.External,
sourceDescription: 'Application Launch',
})
this.vaultUsers.invalidateVaultUsersCache().catch(console.error)
})
.catch((error) => {
void this.notifyEvent(ApplicationEvent.LocalDatabaseReadError, error)
throw error
})
if (awaitDatabaseLoad) {
await loadPromise
}
}
public onStart(): void {
// optional override
}
public onLaunch(): void {
// optional override
}
public getLaunchChallenge(): Challenge | undefined {
return this.protections.createLaunchChallenge()
}
private async handleLaunchChallengeResponse(response: ChallengeResponse) {
if (response.challenge.hasPromptForValidationType(ChallengeValidation.LocalPasscode)) {
let wrappingKey = response.artifacts?.wrappingKey
if (!wrappingKey) {
const value = response.getValueForType(ChallengeValidation.LocalPasscode)
wrappingKey = await this.encryption.computeWrappingKey(value.value as string)
}
await this.encryption.unwrapRootKey(wrappingKey)
}
}
private async handleStage(stage: ApplicationStage) {
await this.events.publishSync(
{
type: ApplicationEvent.ApplicationStageChanged,
payload: { stage } as ApplicationStageChangedEventPayload,
},
InternalEventPublishStrategy.SEQUENCE,
)
}
/**
* @param singleEvent Whether to only listen for a particular event.
*/
public addEventObserver(callback: ApplicationEventCallback, singleEvent?: ApplicationEvent): () => void {
const observer = { callback, singleEvent }
this.eventHandlers.push(observer)
return () => {
removeFromArray(this.eventHandlers, observer)
}
}
public addSingleEventObserver(event: ApplicationEvent, callback: ApplicationEventCallback): () => void {
const filteredCallback = async (firedEvent: ApplicationEvent) => {
if (firedEvent === event) {
void callback(event)
}
}
return this.addEventObserver(filteredCallback, event)
}
private async notifyEvent(event: ApplicationEvent, data?: ApplicationEventPayload) {
if (event === ApplicationEvent.Started) {
this.onStart()
} else if (event === ApplicationEvent.Launched) {
this.onLaunch()
}
for (const observer of this.eventHandlers.slice()) {
if ((observer.singleEvent && observer.singleEvent === event) || !observer.singleEvent) {
await observer.callback(event, data || {})
}
}
this.events.publish({
type: event,
payload: data,
})
void this.migrations.handleApplicationEvent(event)
}
public getSessions(): Promise<HttpResponse<SessionListEntry[]>> {
return this.sessions.getSessionsList()
}
public async revokeSession(sessionId: UuidString): Promise<HttpResponse<SessionListResponse> | undefined> {
if (await this.protections.authorizeSessionRevoking()) {
return this.sessions.revokeSession(sessionId)
}
return undefined
}
/**
* Revokes all sessions except the current one.
*/
public async revokeAllOtherSessions(): Promise<void> {
return this.sessions.revokeAllOtherSessions()
}
public userCanManageSessions(): boolean {
const userVersion = this.getUserVersion()
if (isNullOrUndefined(userVersion)) {
return false
}
return compareVersions(userVersion, ProtocolVersion.V004) >= 0
}
public async setCustomHost(host: string, websocketUrl?: string): Promise<void> {
await this.setHost.execute(host)
this.sockets.setWebSocketUrl(websocketUrl)
}
public getUserPasswordCreationDate(): Date | undefined {
return this.encryption.getPasswordCreatedDate()
}
public getProtocolEncryptionDisplayName(): Promise<string | undefined> {
return this.encryption.getEncryptionDisplayName()
}
public getUserVersion(): ProtocolVersion | undefined {
return this.encryption.getUserVersion()
}
/**
* Returns true if there is an upgrade available for the account or passcode
*/
public protocolUpgradeAvailable(): Promise<boolean> {
return this.encryption.upgradeAvailable()
}
/**
* Returns true if there is an encryption source available
*/
public isEncryptionAvailable(): boolean {
return this.hasAccount() || this.hasPasscode()
}
public async upgradeProtocolVersion(): Promise<{
success?: true
canceled?: true
error?: {
message: string
}
}> {
const result = await this.user.performProtocolUpgrade()
if (result.success) {
if (this.hasAccount()) {
void this.alerts.alert(ProtocolUpgradeStrings.SuccessAccount)
} else {
void this.alerts.alert(ProtocolUpgradeStrings.SuccessPasscodeOnly)
}
} else if (result.error) {
void this.alerts.alert(ProtocolUpgradeStrings.Fail)
}
return result
}
public hasAccount(): boolean {
return this.encryption.hasAccount()
}
/**
* @returns true if the user has a source of protection available, such as a
* passcode, password, or biometrics.
*/
public hasProtectionSources(): boolean {
return this.protections.hasProtectionSources()
}
/**
* When a user specifies a non-zero remember duration on a protection
* challenge, a session will be started during which protections are disabled.
*/
public getProtectionSessionExpiryDate(): Date {
return this.protections.getSessionExpiryDate()
}
public clearProtectionSession(): Promise<void> {
return this.protections.clearSession()
}
public async authorizeProtectedActionForNotes(notes: SNNote[], challengeReason: ChallengeReason): Promise<SNNote[]> {
return await this.protections.authorizeProtectedActionForItems(notes, challengeReason)
}
/**
* @returns whether note access has been granted or not
*/
public authorizeNoteAccess(note: SNNote): Promise<boolean> {
return this.protections.authorizeItemAccess(note)
}
public authorizeAutolockIntervalChange(): Promise<boolean> {
return this.protections.authorizeAutolockIntervalChange()
}
public isEphemeralSession(): boolean {
return this.storage.isEphemeralSession()
}
public setValue(key: string, value: unknown, mode?: StorageValueModes): void {
return this.storage.setValue(key, value, mode)
}
public getValue<T>(key: string, mode?: StorageValueModes): T {
return this.storage.getValue<T>(key, mode)
}
public async removeValue(key: string, mode?: StorageValueModes): Promise<void> {
return this.storage.removeValue(key, mode)
}
public getPreference<K extends PrefKey>(key: K): PrefValue[K] | undefined
public getPreference<K extends PrefKey>(key: K, defaultValue: PrefValue[K]): PrefValue[K]
public getPreference<K extends PrefKey>(key: K, defaultValue?: PrefValue[K]): PrefValue[K] | undefined {
return this.preferences.getValue(key, defaultValue)
}
public async setPreference<K extends PrefKey>(key: K, value: PrefValue[K]): Promise<void> {
return this.preferences.setValue(key, value)
}
/**
* Gives services a chance to complete any sensitive operations before yielding
* @param maxWait The maximum number of milliseconds to wait for services
* to finish tasks. 0 means no limit.
*/
private async prepareForDeinit(maxWait = 0): Promise<void> {
const deps = this.dependencies.getAll().filter(canBlockDeinit)
const promise = Promise.all(deps.map((service) => service.blockDeinit()))
if (maxWait === 0) {
await promise
} else {
/** Await up to maxWait. If not resolved by then, return. */
await Promise.race([promise, sleep(maxWait, false, 'Preparing for deinit...')])
}
}
public addChallengeObserver(challenge: Challenge, observer: ChallengeObserver): () => void {
return this.challenges.addChallengeObserver(challenge, observer)
}
public submitValuesForChallenge(challenge: Challenge, values: ChallengeValue[]): Promise<void> {
return this.challenges.submitValuesForChallenge(challenge, values)
}
public cancelChallenge(challenge: Challenge): void {
this.challenges.cancelChallenge(challenge)
}
public setOnDeinit(onDeinit: DeinitCallback): void {
this.onDeinit = onDeinit
}
/**
* Destroys the application instance.
*/
public deinit(mode: DeinitMode, source: DeinitSource): void {
this.dealloced = true
for (const uninstallObserver of this.serviceObservers) {
uninstallObserver()
}
for (const uninstallSubscriber of this.managedSubscribers) {
uninstallSubscriber()
}
this.options.crypto.deinit()
;(this.options as unknown) = undefined
this.createdNewDatabase = false
this.serviceObservers.length = 0
this.managedSubscribers.length = 0
this.started = false
this.dependencies.deinit()
this.onDeinit?.(this, mode, source)
;(this.onDeinit as unknown) = undefined
}
/**
* @param mergeLocal Whether to merge existing offline data into account. If false,
* any pre-existing data will be fully deleted upon success.
*/
public async register(
email: string,
password: string,
ephemeral = false,
mergeLocal = true,
): Promise<UserRegistrationResponseBody> {
return this.user.register(email, password, ephemeral, mergeLocal)
}
/**
* @param mergeLocal Whether to merge existing offline data into account.
* If false, any pre-existing data will be fully deleted upon success.
*/
public async signIn(
email: string,
password: string,
strict = false,
ephemeral = false,
mergeLocal = true,
awaitSync = false,
): Promise<HttpResponse<SignInResponse>> {
return this.user.signIn(email, password, strict, ephemeral, mergeLocal, awaitSync)
}
public async changeEmail(
newEmail: string,
currentPassword: string,
passcode?: string,
origination = KeyParamsOrigination.EmailChange,
): Promise<CredentialsChangeFunctionResponse> {
return this.user.changeCredentials({
currentPassword,
newEmail,
passcode,
origination,
validateNewPasswordStrength: false,
})
}
public async changePassword(
currentPassword: string,
newPassword: string,
passcode?: string,
origination = KeyParamsOrigination.PasswordChange,
validateNewPasswordStrength = true,
): Promise<CredentialsChangeFunctionResponse> {
return this.user.changeCredentials({
currentPassword,
newPassword,
passcode,
origination,
validateNewPasswordStrength,
})
}
public async importData(data: BackupFile, awaitSync = false): Promise<Result<ImportDataResult>> {
const usecase = this.dependencies.get<ImportData>(TYPES.ImportData)
return usecase.execute(data, awaitSync)
}
private async handleRevokedSession(): Promise<void> {
/**
* Because multiple API requests can come back at the same time
* indicating revoked session we only want to do this once.
*/
if (this.revokingSession) {
return
}
this.revokingSession = true
/** Keep a reference to the soon-to-be-cleared alertService */
const alertService = this.alerts
await this.user.signOut(true)
void alertService.alert(SessionStrings.CurrentSessionRevoked)
}
public async validateAccountPassword(password: string): Promise<boolean> {
const { valid } = await this.encryption.validateAccountPassword(password)
return valid
}
public isStarted(): boolean {
return this.started
}
public isLaunched(): boolean {
return this.launched
}
public hasPasscode(): boolean {
return this.encryption.hasPasscode()
}
public async lock(): Promise<void> {
/**
* Because locking is a critical operation, we want to try to do it safely,
* but only up to a certain limit.
*/
const MaximumWaitTime = 500
await this.prepareForDeinit(MaximumWaitTime)
return this.deinit(this.getDeinitMode(), DeinitSource.Lock)
}
isNativeMobileWeb() {
return this.environment === Environment.Mobile
}
getDeinitMode(): DeinitMode {
const value = this.getValue(StorageKey.DeinitMode)
if (value === 'hard') {
return DeinitMode.Hard
}
return DeinitMode.Soft
}
public addPasscode(passcode: string): Promise<boolean> {
return this.user.addPasscode(passcode)
}
/**
* @returns whether the passcode was successfuly removed
*/
public async removePasscode(): Promise<boolean> {
return this.user.removePasscode()
}
public async changePasscode(
newPasscode: string,
origination = KeyParamsOrigination.PasscodeChange,
): Promise<boolean> {
return this.user.changePasscode(newPasscode, origination)
}
public enableEphemeralPersistencePolicy(): Promise<void> {
return this.storage.setPersistencePolicy(StoragePersistencePolicies.Ephemeral)
}
public hasPendingMigrations(): Promise<boolean> {
return this.migrations.hasPendingMigrations()
}
public presentKeyRecoveryWizard(): void {
const service = this.dependencies.get<KeyRecoveryService>(TYPES.KeyRecoveryService)
return service.presentKeyRecoveryWizard()
}
public canAttemptDecryptionOfItem(item: EncryptedItemInterface): ClientDisplayableError | true {
const service = this.dependencies.get<KeyRecoveryService>(TYPES.KeyRecoveryService)
return service.canAttemptDecryptionOfItem(item)
}
async isUsingHomeServer(): Promise<boolean> {
const homeServerService = this.dependencies.get<HomeServerServiceInterface>(TYPES.HomeServerService)
if (!homeServerService) {
return false
}
return this.getHost.execute().getValue() === (await homeServerService.getHomeServerUrl())
}
get device(): DeviceInterface {
return this.dependencies.get<DeviceInterface>(TYPES.DeviceInterface)
}
get subscriptions(): SubscriptionManagerInterface {
return this.dependencies.get<SubscriptionManagerInterface>(TYPES.SubscriptionManager)
}
get signInWithRecoveryCodes(): SignInWithRecoveryCodes {
return this.dependencies.get<SignInWithRecoveryCodes>(TYPES.SignInWithRecoveryCodes)
}
get getRecoveryCodes(): GetRecoveryCodes {
return this.dependencies.get<GetRecoveryCodes>(TYPES.GetRecoveryCodes)
}
get addAuthenticator(): AddAuthenticator {
return this.dependencies.get<AddAuthenticator>(TYPES.AddAuthenticator)
}
get listAuthenticators(): ListAuthenticators {
return this.dependencies.get<ListAuthenticators>(TYPES.ListAuthenticators)
}
get deleteAuthenticator(): DeleteAuthenticator {
return this.dependencies.get<DeleteAuthenticator>(TYPES.DeleteAuthenticator)
}
get getAuthenticatorAuthenticationOptions(): GetAuthenticatorAuthenticationOptions {
return this.dependencies.get<GetAuthenticatorAuthenticationOptions>(TYPES.GetAuthenticatorAuthenticationOptions)
}
get getAuthenticatorAuthenticationResponse(): GetAuthenticatorAuthenticationResponse {
return this.dependencies.get<GetAuthenticatorAuthenticationResponse>(TYPES.GetAuthenticatorAuthenticationResponse)
}
get listRevisions(): ListRevisions {
return this.dependencies.get<ListRevisions>(TYPES.ListRevisions)
}
get getRevision(): GetRevision {
return this.dependencies.get<GetRevision>(TYPES.GetRevision)
}
get deleteRevision(): DeleteRevision {
return this.dependencies.get<DeleteRevision>(TYPES.DeleteRevision)
}
public get files(): FilesClientInterface {
return this.dependencies.get<FilesClientInterface>(TYPES.FileService)
}
public get features(): FeaturesClientInterface {
return this.dependencies.get<FeaturesClientInterface>(TYPES.FeaturesService)
}
public get items(): ItemManagerInterface {
return this.dependencies.get<ItemManagerInterface>(TYPES.ItemManager)
}
public get payloads(): PayloadManagerInterface {
return this.dependencies.get<PayloadManagerInterface>(TYPES.PayloadManager)
}
public get protections(): ProtectionsClientInterface {
return this.dependencies.get<ProtectionsClientInterface>(TYPES.ProtectionService)
}
public get sync(): SyncServiceInterface {
return this.dependencies.get<SyncServiceInterface>(TYPES.SyncService)