1
0
mirror of https://github.com/bitwarden/browser synced 2025-12-20 02:03:39 +00:00

[PS-1854] Split services between background and visualizations (#4075)

* Elevate Map <-> Record JSON helpers to Utils

* Build Account from a StateService provided AccountDeserializer

* Allow Manifest V2 usage of session sync

Expands use of SessionSyncer to all Subject types. Correctly handles
replay buffer for each type to ignore the flood of data upon
subscription to each Subject type.

* Create browser-synced Policy Service

* Move BrowserFolderService

* Libs account serialization improvements

* Serialize Browser Accounts

* Separate StateService in background/visualizations

Visualizer state services share storages with background page, which
nicely emulates mv3 synchronization through session/local storage. There
should not be multithreading issues since all of these services are
still running through a single thread, we just now have multiple places
we are reading/writing data from.

Smaller improvements
* Rename browser's state service to BrowserStateService
* Remove unused WithPrototype decorator :celebrate:
* Removed conversion on withPrototypeForArrayMembers. It's reasonable to
think that if the type is maintained, it doesn't need conversion.

Eventually, we should be able to remove the withPrototypeForArrayMembers
decorator as well, but that will require a bit more work on
(de)serialization of the Accounts.data property.

* Make Record <-> Map idempotent

Should we get in a situation where we _think_ an object has been
jsonified, but hasn't been, we need to correctly deal with the object
received to create our target.

* Check all requirements while duck typing

* Name client services after the client

* Use union type to limit initialize options

* Fixup usages of `initializeAs`

* Add OrganizationService to synced services

Co-Authored-By: Daniel James Smith <djsmith85@users.noreply.github.com>

* Add Settings service to synced services

Co-Authored-By: Daniel James Smith <djsmith85@users.noreply.github.com>

* Add missing BrowserStateService

* Fix factories to use browser-specific service overides

* Fix org-service registration in services.module

* Revert "Add missing BrowserStateService"

This reverts commit 81cf384e87.

* Fix session syncer tests

* Fix synced item metadata tests

* Early return null json objects

* Prefer abstract service dependencies

* Prefer minimal browser service overrides

* [SG-632] - Change forwarded providers radio buttons list to dropdown (#4045)

* SG-632 - Changed forwarded providers list of radio buttons to dropdown

* SG-632 - Added role attributes to improve accessibility.

* SG-632 - Added sorting to array and empty option

* SG-632 - Fix styling to match standards.

* rename cipehrs component to vault items component (#4081)

* Update the version hash for the QA Web build artifact to follow SemVer syntax (#4102)

* Remove extra call to toJSON() (#4101)

Co-authored-by: Daniel James Smith <djsmith85@users.noreply.github.com>
Co-authored-by: Daniel James Smith <djsmith@web.de>
Co-authored-by: Carlos Gonçalves <carlosmaccam@gmail.com>
Co-authored-by: Jake Fink <jfink@bitwarden.com>
Co-authored-by: Joseph Flinn <58369717+joseph-flinn@users.noreply.github.com>
Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
This commit is contained in:
Matt Gibson
2022-11-23 17:26:57 -05:00
committed by GitHub
parent be56d29ba0
commit 7fbfce953d
54 changed files with 671 additions and 241 deletions

View File

@@ -412,7 +412,7 @@ export class CipherService implements CipherServiceAbstraction {
: firstValueFrom(this.settingsService.settings$).then(
(settings: AccountSettingsSettings) => {
let matches: any[] = [];
settings.equivalentDomains?.forEach((eqDomain: any) => {
settings?.equivalentDomains?.forEach((eqDomain: any) => {
if (eqDomain.length && eqDomain.indexOf(domain) >= 0) {
matches = matches.concat(eqDomain);
}

View File

@@ -6,7 +6,7 @@ import { OrganizationData } from "../../models/data/organization.data";
import { Organization } from "../../models/domain/organization";
export class OrganizationService implements InternalOrganizationServiceAbstraction {
private _organizations = new BehaviorSubject<Organization[]>([]);
protected _organizations = new BehaviorSubject<Organization[]>([]);
organizations$ = this._organizations.asObservable();

View File

@@ -16,7 +16,7 @@ import { ListResponse } from "../../models/response/list.response";
import { PolicyResponse } from "../../models/response/policy.response";
export class PolicyService implements InternalPolicyServiceAbstraction {
private _policies: BehaviorSubject<Policy[]> = new BehaviorSubject([]);
protected _policies: BehaviorSubject<Policy[]> = new BehaviorSubject([]);
policies$ = this._policies.asObservable();

View File

@@ -6,7 +6,7 @@ import { Utils } from "../misc/utils";
import { AccountSettingsSettings } from "../models/domain/account";
export class SettingsService implements SettingsServiceAbstraction {
private _settings: BehaviorSubject<AccountSettingsSettings> = new BehaviorSubject({});
protected _settings: BehaviorSubject<AccountSettingsSettings> = new BehaviorSubject({});
settings$ = this._settings.asObservable();

View File

@@ -1,4 +1,5 @@
import { BehaviorSubject, concatMap } from "rxjs";
import { Jsonify } from "type-fest";
import { LogService } from "../abstractions/log.service";
import { StateService as StateServiceAbstraction } from "../abstractions/state.service";
@@ -13,6 +14,7 @@ import { StorageLocation } from "../enums/storageLocation";
import { ThemeType } from "../enums/themeType";
import { UriMatchType } from "../enums/uriMatchType";
import { StateFactory } from "../factories/stateFactory";
import { Utils } from "../misc/utils";
import { CipherData } from "../models/data/cipher.data";
import { CollectionData } from "../models/data/collection.data";
import { EncryptedOrganizationKeyData } from "../models/data/encrypted-organization-key.data";
@@ -65,13 +67,13 @@ export class StateService<
TAccount extends Account = Account
> implements StateServiceAbstraction<TAccount>
{
private accountsSubject = new BehaviorSubject<{ [userId: string]: TAccount }>({});
protected accountsSubject = new BehaviorSubject<{ [userId: string]: TAccount }>({});
accounts$ = this.accountsSubject.asObservable();
private activeAccountSubject = new BehaviorSubject<string | null>(null);
protected activeAccountSubject = new BehaviorSubject<string | null>(null);
activeAccount$ = this.activeAccountSubject.asObservable();
private activeAccountUnlockedSubject = new BehaviorSubject<boolean>(false);
protected activeAccountUnlockedSubject = new BehaviorSubject<boolean>(false);
activeAccountUnlocked$ = this.activeAccountUnlockedSubject.asObservable();
private hasBeenInited = false;
@@ -79,6 +81,9 @@ export class StateService<
private accountDiskCache = new Map<string, TAccount>();
// default account serializer, must be overridden by child class
protected accountDeserializer = Account.fromJSON as (json: Jsonify<TAccount>) => TAccount;
constructor(
protected storageService: AbstractStorageService,
protected secureStorageService: AbstractStorageService,
@@ -676,7 +681,7 @@ export class StateService<
const account = await this.getAccount(
this.reconcileOptions(options, await this.defaultInMemoryOptions())
);
return this.recordToMap(account?.keys?.organizationKeys?.decrypted);
return Utils.recordToMap(account?.keys?.organizationKeys?.decrypted);
}
async setDecryptedOrganizationKeys(
@@ -686,7 +691,7 @@ export class StateService<
const account = await this.getAccount(
this.reconcileOptions(options, await this.defaultInMemoryOptions())
);
account.keys.organizationKeys.decrypted = this.mapToRecord(value);
account.keys.organizationKeys.decrypted = Utils.mapToRecord(value);
await this.saveAccount(
account,
this.reconcileOptions(options, await this.defaultInMemoryOptions())
@@ -774,7 +779,7 @@ export class StateService<
const account = await this.getAccount(
this.reconcileOptions(options, await this.defaultInMemoryOptions())
);
return this.recordToMap(account?.keys?.providerKeys?.decrypted);
return Utils.recordToMap(account?.keys?.providerKeys?.decrypted);
}
async setDecryptedProviderKeys(
@@ -784,7 +789,7 @@ export class StateService<
const account = await this.getAccount(
this.reconcileOptions(options, await this.defaultInMemoryOptions())
);
account.keys.providerKeys.decrypted = this.mapToRecord(value);
account.keys.providerKeys.decrypted = Utils.mapToRecord(value);
await this.saveAccount(
account,
this.reconcileOptions(options, await this.defaultInMemoryOptions())
@@ -2744,7 +2749,7 @@ export class StateService<
protected async state(): Promise<State<TGlobalState, TAccount>> {
const state = await this.memoryStorageService.get<State<TGlobalState, TAccount>>(keys.state, {
deserializer: (s) => State.fromJSON(s),
deserializer: (s) => State.fromJSON(s, this.accountDeserializer),
});
return state;
}
@@ -2765,50 +2770,6 @@ export class StateService<
await this.setState(updatedState);
});
}
private mapToRecord<V>(map: Map<string, V>): Record<string, V> {
return map == null ? null : Object.fromEntries(map);
}
private recordToMap<V>(record: Record<string, V>): Map<string, V> {
return record == null ? null : new Map(Object.entries(record));
}
}
export function withPrototype<T>(
constructor: new (...args: any[]) => T,
converter: (input: any) => T = (i) => i
): (
target: any,
propertyKey: string | symbol,
descriptor: PropertyDescriptor
) => { value: (...args: any[]) => Promise<T> } {
return (target: any, propertyKey: string | symbol, descriptor: PropertyDescriptor) => {
const originalMethod = descriptor.value;
return {
value: function (...args: any[]) {
const originalResult: Promise<T> = originalMethod.apply(this, args);
if (!(originalResult instanceof Promise)) {
throw new Error(
`Error applying prototype to stored value -- result is not a promise for method ${String(
propertyKey
)}`
);
}
return originalResult.then((result) => {
return result == null ||
result.constructor.name === constructor.prototype.constructor.name
? converter(result as T)
: converter(
Object.create(constructor.prototype, Object.getOwnPropertyDescriptors(result)) as T
);
});
},
};
};
}
function withPrototypeForArrayMembers<T>(
@@ -2847,7 +2808,7 @@ function withPrototypeForArrayMembers<T>(
return result.map((r) => {
return r == null ||
r.constructor.name === memberConstructor.prototype.constructor.name
? memberConverter(r)
? r
: memberConverter(
Object.create(memberConstructor.prototype, Object.getOwnPropertyDescriptors(r))
);