mirror of
https://github.com/bitwarden/jslib
synced 2025-12-06 00:03:29 +00:00
* [refactor] Extract, rename, and expand StorageServiceOptions * Pulled StorageServiceOptions into its own file * Renamed StorageServiceOptions to StorageOptions * Pulled KeySuffixOpptions into its own file * Converted KeySuffixOptions into an enum from a union type * [refactor] Expand StateService into a full coverage storage proxy * Expand StateService to allow it to manage all data points of the application state regardless of memory. * Expand StateService to allow for storing and managing multiple accounts * [refactor] Create helper services for managing organization and provider state data * [refactor] Implement StateService across service layer * Remove service level variables used for in memory data storage and replaced with calls to StateService * Remove direct calls to StorageService in favor of using StateService as a proxy * [feature] Implement account switching capable services across components and processes * Replace calls to StorageService and deprecated services with calls to a StateService * [chore] Remove unused services Several services are no longer in use because of the expanded state service. These have simply been removed. * [bug] Add loginRedirect to the account model * [bug] Add awaits to newly async calls in TokenService * [bug] Add several missing awaits * [bug] Add state service handlers for AutoConfirmFingerprint * [bug] Move TwoFactorToken to global state * Update unauth-guard.service.ts Add back return true * [refactor] Slim down the boilerplate needed to manage options on StateService calls * [bug] Allow the lock message handler to manipulate a specific acount * [bug] Add missing await to auth guard * [bug] Adjust state scope of several biometric data points * [bug] Ensure vault locking logic can operate over non-active accounts * [style] Fix lint complaints * [bug] Move disableFavicon to global state * [refactor] Remove an unecassary parameter from a StorageOptions instance * [bug] Ensure HtmlStorageService paths are accounted for in StateService * [feature] Add a server url helper to the account model for the account switcher * [refactor] Remove some unused getters from the account model * [bug] Ensure locking and logging out can function over any user * Fix account getting set to null in getAccountFromDisk * [bug] Ensure lock component is always working with the latest active account in state * [chore] Update recent KeyConnector changes to use stateService * [style] Fix lint complaints * [chore] Resolve TokenService merge issues from KeyConnector * [bug] Add missing service arguement * [bug] Correct several default storage option types * [bug] Check for the right key in hasEncKey * [bug] Add enableFullWidth to the account model * [style] Fix lint complaints * [review] Revist remember email * [refactor] Remove RememberEmail from state * setDisableFavicon to correct storage location * [bug] Convert vault lock loop returns into continues to not skip secondary accounts * [review] Sorted state service methods * [bug] Correct neverDomains type on the account model * [review] Rename stateService.purge to stateService.clean * [review] [refactor] Extract lock refresh logic to a load function * [review] [refactor] Extract some timeout logic to dedicated functions * [review] [refactor] Move AuthenticationStatus to a dedicated file * [review] [refactor] Rename Globals to GlobalState * [style] Fix lint complaints * [review] Remove unused global state property for decodedToken * [review] [bug] Adjust state scope for OrganizationInvitation * [review] [bug] Put back the homepage variable in lock guard * [review] Un-try-catch the window creation function * Revert "[review] [bug] Adjust state scope for OrganizationInvitation" This reverts commitcaa4574a65. * [bug] Change || to && in recent vault timeout refactor * [bug] Keep up with entire state in storage instead of just accounts and globals Not having access to the last active user was creating issues across clients when restarting the process. For example: when refreshing the page on web we no longer maintain an understanding of who is logged in. To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals. This allows for more flexible saving, like saving activeUserId as a top level storage item. * [style] Fix lint complaints * Revert "[bug] Keep up with entire state in storage instead of just accounts and globals" This reverts commite8970725be. * [bug] Initialize GlobalState by default * [bug] Only get key hash from storage * [bug] Remove settings storage location overrides * [bug] Only save accessToken to storage * [refactor] Remove unecassary argements from electron crypto state calls * [bug] Ensure keys and tokens load and save to the right locations for web * [style] Fix lint complaints * [bug] Remove keySuffix storage option and split uses into unique methods The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state. This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly. * [bug] Add default vault timeouts to new accounts * [bug] Save appId as a top level storage item * [bug] Add missing await to timeout logic * [bug] Adjust state scope for everBeenUnlocked * [bug] Clear access tokens when loading account state from disk * [bug] Adjust theme to be a global state item * [bug] Adjust null checking for window in state * [bug] Correct getGlobals not pulling from the stored state item * [bug] Null check in memory account before claiming it has a userId * [bug] Scaffold secure storage service when building storage objects on init * [bug] Adjusted state scope of event collection * [bug] Adjusted state scope of vault timeout and action * [bug] Grab account from normal storage if secure storage is requested but does not exist * [bug] Create a State if one is requested from memory before it exists * [bug] Ensure all storage locations are cleared on state clean * [style] Fix lint complaints * [bug] Remove uneeded clearing of access token * [bug] Reset tokens when toggling * [refactor] Split up the Account model Until this point the account model has been very flat, holding many kinds of data. In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale, the Account model has been divided into logical chunks. * [bug] Correct the serverUrl helpers return * Fix sends always coming back as empty in browser * Get settings properly (I think) * [bug] Fix lint error * [bug] Add missing await to identity token refresh This was causing weird behavior in web that was creating a lot of 429s * [bug] Scaffold memory storage for web Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in. Namely, encrypted data that was recently synced had nowhere to save to and was lost. * [bug] Implement better null handling in a few places for retrieving state * [bug] Update correct storage locations on account removal * [bug] Added missing awaits to lock component * [bug] Reload lock component on account switching vs. account update * [bug] Store master keys correctly * [bug] Move some biometrics storage items to global state * [feature] Add platform helper isMac() * [refactor] Comment emphasis and call order refresh * [refactor] Remove unecassary using * [bug] Relocate authenticationStatus check logic to component * [bug] Stop not clearing everything on state clean * [style] Fix lint complaints * [bug] Correct mismatched uses of encrypted and decrypted pin states * Add browser specific state classes and methods * lint fixes * [bug] Migrate existing persistant data to new schema * [style] Fix lint complaints * [bug] Dont clear settings on state clean * [bug] Maintain the right storage items on logout * [chore] resolve issues from merge * [bug] Resolve settings clearing on lock * [chore] Added a comment * [review] fromatting for code review * Revert browser state items Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com> Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
384 lines
16 KiB
TypeScript
384 lines
16 KiB
TypeScript
import { ApiService } from '../abstractions/api.service';
|
|
import { CipherService } from '../abstractions/cipher.service';
|
|
import { CollectionService } from '../abstractions/collection.service';
|
|
import { CryptoService } from '../abstractions/crypto.service';
|
|
import { FolderService } from '../abstractions/folder.service';
|
|
import { KeyConnectorService } from '../abstractions/keyConnector.service';
|
|
import { LogService } from '../abstractions/log.service';
|
|
import { MessagingService } from '../abstractions/messaging.service';
|
|
import { OrganizationService } from '../abstractions/organization.service';
|
|
import { PolicyService } from '../abstractions/policy.service';
|
|
import { ProviderService } from '../abstractions/provider.service';
|
|
import { SendService } from '../abstractions/send.service';
|
|
import { SettingsService } from '../abstractions/settings.service';
|
|
import { StateService } from '../abstractions/state.service';
|
|
import { SyncService as SyncServiceAbstraction } from '../abstractions/sync.service';
|
|
|
|
import { CipherData } from '../models/data/cipherData';
|
|
import { CollectionData } from '../models/data/collectionData';
|
|
import { FolderData } from '../models/data/folderData';
|
|
import { OrganizationData } from '../models/data/organizationData';
|
|
import { PolicyData } from '../models/data/policyData';
|
|
import { ProviderData } from '../models/data/providerData';
|
|
import { SendData } from '../models/data/sendData';
|
|
|
|
import { CipherResponse } from '../models/response/cipherResponse';
|
|
import { CollectionDetailsResponse } from '../models/response/collectionResponse';
|
|
import { DomainsResponse } from '../models/response/domainsResponse';
|
|
import { FolderResponse } from '../models/response/folderResponse';
|
|
import {
|
|
SyncCipherNotification,
|
|
SyncFolderNotification,
|
|
SyncSendNotification,
|
|
} from '../models/response/notificationResponse';
|
|
import { PolicyResponse } from '../models/response/policyResponse';
|
|
import { ProfileResponse } from '../models/response/profileResponse';
|
|
import { SendResponse } from '../models/response/sendResponse';
|
|
|
|
export class SyncService implements SyncServiceAbstraction {
|
|
syncInProgress: boolean = false;
|
|
|
|
constructor(private apiService: ApiService, private settingsService: SettingsService,
|
|
private folderService: FolderService, private cipherService: CipherService,
|
|
private cryptoService: CryptoService, private collectionService: CollectionService,
|
|
private messagingService: MessagingService, private policyService: PolicyService,
|
|
private sendService: SendService, private logService: LogService,
|
|
private keyConnectorService: KeyConnectorService, private stateService: StateService,
|
|
private organizationService: OrganizationService, private providerService: ProviderService,
|
|
private logoutCallback: (expired: boolean) => Promise<void>) { }
|
|
|
|
async getLastSync(): Promise<Date> {
|
|
if (await this.stateService.getUserId() == null) {
|
|
return null;
|
|
}
|
|
|
|
const lastSync = await this.stateService.getLastSync();
|
|
if (lastSync) {
|
|
return new Date(lastSync);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
async setLastSync(date: Date, userId?: string): Promise<any> {
|
|
await this.stateService.setLastSync(date.toJSON(), { userId: userId });
|
|
}
|
|
|
|
async fullSync(forceSync: boolean, allowThrowOnError = false): Promise<boolean> {
|
|
this.syncStarted();
|
|
const isAuthenticated = await this.stateService.getIsAuthenticated();
|
|
if (!isAuthenticated) {
|
|
return this.syncCompleted(false);
|
|
}
|
|
|
|
const now = new Date();
|
|
let needsSync = false;
|
|
try {
|
|
needsSync = await this.needsSyncing(forceSync);
|
|
} catch (e) {
|
|
if (allowThrowOnError) {
|
|
throw e;
|
|
}
|
|
}
|
|
|
|
if (!needsSync) {
|
|
await this.setLastSync(now);
|
|
return this.syncCompleted(false);
|
|
}
|
|
|
|
const userId = await this.stateService.getUserId();
|
|
try {
|
|
await this.apiService.refreshIdentityToken();
|
|
const response = await this.apiService.getSync();
|
|
|
|
await this.syncProfile(response.profile);
|
|
await this.syncFolders(userId, response.folders);
|
|
await this.syncCollections(response.collections);
|
|
await this.syncCiphers(userId, response.ciphers);
|
|
await this.syncSends(userId, response.sends);
|
|
await this.syncSettings(response.domains);
|
|
await this.syncPolicies(response.policies);
|
|
|
|
await this.setLastSync(now);
|
|
return this.syncCompleted(true);
|
|
} catch (e) {
|
|
if (allowThrowOnError) {
|
|
throw e;
|
|
} else {
|
|
return this.syncCompleted(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
async syncUpsertFolder(notification: SyncFolderNotification, isEdit: boolean): Promise<boolean> {
|
|
this.syncStarted();
|
|
if (await this.stateService.getIsAuthenticated()) {
|
|
try {
|
|
const localFolder = await this.folderService.get(notification.id);
|
|
if ((!isEdit && localFolder == null) ||
|
|
(isEdit && localFolder != null && localFolder.revisionDate < notification.revisionDate)) {
|
|
const remoteFolder = await this.apiService.getFolder(notification.id);
|
|
if (remoteFolder != null) {
|
|
const userId = await this.stateService.getUserId();
|
|
await this.folderService.upsert(new FolderData(remoteFolder, userId));
|
|
this.messagingService.send('syncedUpsertedFolder', { folderId: notification.id });
|
|
return this.syncCompleted(true);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
this.logService.error(e);
|
|
}
|
|
}
|
|
return this.syncCompleted(false);
|
|
}
|
|
|
|
async syncDeleteFolder(notification: SyncFolderNotification): Promise<boolean> {
|
|
this.syncStarted();
|
|
if (await this.stateService.getIsAuthenticated()) {
|
|
await this.folderService.delete(notification.id);
|
|
this.messagingService.send('syncedDeletedFolder', { folderId: notification.id });
|
|
this.syncCompleted(true);
|
|
return true;
|
|
}
|
|
return this.syncCompleted(false);
|
|
}
|
|
|
|
async syncUpsertCipher(notification: SyncCipherNotification, isEdit: boolean): Promise<boolean> {
|
|
this.syncStarted();
|
|
if (await this.stateService.getIsAuthenticated()) {
|
|
try {
|
|
let shouldUpdate = true;
|
|
const localCipher = await this.cipherService.get(notification.id);
|
|
if (localCipher != null && localCipher.revisionDate >= notification.revisionDate) {
|
|
shouldUpdate = false;
|
|
}
|
|
|
|
let checkCollections = false;
|
|
if (shouldUpdate) {
|
|
if (isEdit) {
|
|
shouldUpdate = localCipher != null;
|
|
checkCollections = true;
|
|
} else {
|
|
if (notification.collectionIds == null || notification.organizationId == null) {
|
|
shouldUpdate = localCipher == null;
|
|
} else {
|
|
shouldUpdate = false;
|
|
checkCollections = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!shouldUpdate && checkCollections && notification.organizationId != null &&
|
|
notification.collectionIds != null && notification.collectionIds.length > 0) {
|
|
const collections = await this.collectionService.getAll();
|
|
if (collections != null) {
|
|
for (let i = 0; i < collections.length; i++) {
|
|
if (notification.collectionIds.indexOf(collections[i].id) > -1) {
|
|
shouldUpdate = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (shouldUpdate) {
|
|
const remoteCipher = await this.apiService.getCipher(notification.id);
|
|
if (remoteCipher != null) {
|
|
const userId = await this.stateService.getUserId();
|
|
await this.cipherService.upsert(new CipherData(remoteCipher, userId));
|
|
this.messagingService.send('syncedUpsertedCipher', { cipherId: notification.id });
|
|
return this.syncCompleted(true);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
if (e != null && e.statusCode === 404 && isEdit) {
|
|
await this.cipherService.delete(notification.id);
|
|
this.messagingService.send('syncedDeletedCipher', { cipherId: notification.id });
|
|
return this.syncCompleted(true);
|
|
}
|
|
}
|
|
}
|
|
return this.syncCompleted(false);
|
|
}
|
|
|
|
async syncDeleteCipher(notification: SyncCipherNotification): Promise<boolean> {
|
|
this.syncStarted();
|
|
if (await this.stateService.getIsAuthenticated()) {
|
|
await this.cipherService.delete(notification.id);
|
|
this.messagingService.send('syncedDeletedCipher', { cipherId: notification.id });
|
|
return this.syncCompleted(true);
|
|
}
|
|
return this.syncCompleted(false);
|
|
}
|
|
|
|
async syncUpsertSend(notification: SyncSendNotification, isEdit: boolean): Promise<boolean> {
|
|
this.syncStarted();
|
|
if (await this.stateService.getIsAuthenticated()) {
|
|
try {
|
|
const localSend = await this.sendService.get(notification.id);
|
|
if ((!isEdit && localSend == null) ||
|
|
(isEdit && localSend != null && localSend.revisionDate < notification.revisionDate)) {
|
|
const remoteSend = await this.apiService.getSend(notification.id);
|
|
if (remoteSend != null) {
|
|
const userId = await this.stateService.getUserId();
|
|
await this.sendService.upsert(new SendData(remoteSend, userId));
|
|
this.messagingService.send('syncedUpsertedSend', { sendId: notification.id });
|
|
return this.syncCompleted(true);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
this.logService.error(e);
|
|
}
|
|
}
|
|
return this.syncCompleted(false);
|
|
}
|
|
|
|
async syncDeleteSend(notification: SyncSendNotification): Promise<boolean> {
|
|
this.syncStarted();
|
|
if (await this.stateService.getIsAuthenticated()) {
|
|
await this.sendService.delete(notification.id);
|
|
this.messagingService.send('syncedDeletedSend', { sendId: notification.id });
|
|
this.syncCompleted(true);
|
|
return true;
|
|
}
|
|
return this.syncCompleted(false);
|
|
}
|
|
|
|
// Helpers
|
|
|
|
private syncStarted() {
|
|
this.syncInProgress = true;
|
|
this.messagingService.send('syncStarted');
|
|
}
|
|
|
|
private syncCompleted(successfully: boolean): boolean {
|
|
this.syncInProgress = false;
|
|
this.messagingService.send('syncCompleted', { successfully: successfully });
|
|
return successfully;
|
|
}
|
|
|
|
private async needsSyncing(forceSync: boolean) {
|
|
if (forceSync) {
|
|
return true;
|
|
}
|
|
|
|
const lastSync = await this.getLastSync();
|
|
if (lastSync == null || lastSync.getTime() === 0) {
|
|
return true;
|
|
}
|
|
|
|
const response = await this.apiService.getAccountRevisionDate();
|
|
if (new Date(response) <= lastSync) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
private async syncProfile(response: ProfileResponse) {
|
|
const stamp = await this.stateService.getSecurityStamp();
|
|
if (stamp != null && stamp !== response.securityStamp) {
|
|
if (this.logoutCallback != null) {
|
|
await this.logoutCallback(true);
|
|
}
|
|
|
|
throw new Error('Stamp has changed');
|
|
}
|
|
|
|
await this.cryptoService.setEncKey(response.key);
|
|
await this.cryptoService.setEncPrivateKey(response.privateKey);
|
|
await this.cryptoService.setProviderKeys(response.providers);
|
|
await this.cryptoService.setOrgKeys(response.organizations, response.providerOrganizations);
|
|
await this.stateService.setSecurityStamp(response.securityStamp);
|
|
await this.stateService.setEmailVerified(response.emailVerified);
|
|
await this.stateService.setForcePasswordReset(response.forcePasswordReset);
|
|
await this.keyConnectorService.setUsesKeyConnector(response.usesKeyConnector);
|
|
|
|
const organizations: { [id: string]: OrganizationData; } = {};
|
|
response.organizations.forEach(o => {
|
|
organizations[o.id] = new OrganizationData(o);
|
|
});
|
|
|
|
const providers: { [id: string]: ProviderData; } = {};
|
|
response.providers.forEach(p => {
|
|
providers[p.id] = new ProviderData(p);
|
|
});
|
|
|
|
response.providerOrganizations.forEach(o => {
|
|
if (organizations[o.id] == null) {
|
|
organizations[o.id] = new OrganizationData(o);
|
|
organizations[o.id].isProviderUser = true;
|
|
}
|
|
});
|
|
|
|
await Promise.all([
|
|
this.organizationService.save(organizations),
|
|
this.providerService.save(providers),
|
|
]);
|
|
|
|
if (await this.keyConnectorService.userNeedsMigration()) {
|
|
this.messagingService.send('convertAccountToKeyConnector');
|
|
} else {
|
|
this.keyConnectorService.removeConvertAccountRequired();
|
|
}
|
|
}
|
|
|
|
private async syncFolders(userId: string, response: FolderResponse[]) {
|
|
const folders: { [id: string]: FolderData; } = {};
|
|
response.forEach(f => {
|
|
folders[f.id] = new FolderData(f, userId);
|
|
});
|
|
return await this.folderService.replace(folders);
|
|
}
|
|
|
|
private async syncCollections(response: CollectionDetailsResponse[]) {
|
|
const collections: { [id: string]: CollectionData; } = {};
|
|
response.forEach(c => {
|
|
collections[c.id] = new CollectionData(c);
|
|
});
|
|
return await this.collectionService.replace(collections);
|
|
}
|
|
|
|
private async syncCiphers(userId: string, response: CipherResponse[]) {
|
|
const ciphers: { [id: string]: CipherData; } = {};
|
|
response.forEach(c => {
|
|
ciphers[c.id] = new CipherData(c, userId);
|
|
});
|
|
return await this.cipherService.replace(ciphers);
|
|
}
|
|
|
|
private async syncSends(userId: string, response: SendResponse[]) {
|
|
const sends: { [id: string]: SendData; } = {};
|
|
response.forEach(s => {
|
|
sends[s.id] = new SendData(s, userId);
|
|
});
|
|
return await this.sendService.replace(sends);
|
|
}
|
|
|
|
private async syncSettings(response: DomainsResponse) {
|
|
let eqDomains: string[][] = [];
|
|
if (response != null && response.equivalentDomains != null) {
|
|
eqDomains = eqDomains.concat(response.equivalentDomains);
|
|
}
|
|
|
|
if (response != null && response.globalEquivalentDomains != null) {
|
|
response.globalEquivalentDomains.forEach(global => {
|
|
if (global.domains.length > 0) {
|
|
eqDomains.push(global.domains);
|
|
}
|
|
});
|
|
}
|
|
|
|
return this.settingsService.setEquivalentDomains(eqDomains);
|
|
}
|
|
|
|
private async syncPolicies(response: PolicyResponse[]) {
|
|
const policies: { [id: string]: PolicyData; } = {};
|
|
if (response != null) {
|
|
response.forEach(p => {
|
|
policies[p.id] = new PolicyData(p);
|
|
});
|
|
}
|
|
return await this.policyService.replace(policies);
|
|
}
|
|
}
|