bitwarden-estensione-browser/apps/browser/src/decorators/session-sync-observable/session-syncer.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

84 lines
2.5 KiB
TypeScript
Raw Normal View History

import { BehaviorSubject, concatMap, Subscription } from "rxjs";
import { Utils } from "@bitwarden/common/misc/utils";
import { BrowserApi } from "../../browser/browserApi";
import { StateService } from "../../services/abstractions/state.service";
import { SyncedItemMetadata } from "./sync-item-metadata";
export class SessionSyncer {
subscription: Subscription;
id = Utils.newGuid();
// everyone gets the same initial values
private ignoreNextUpdate = true;
constructor(
private behaviorSubject: BehaviorSubject<any>,
private stateService: StateService,
private metaData: SyncedItemMetadata
) {
if (!(behaviorSubject instanceof BehaviorSubject)) {
throw new Error("behaviorSubject must be an instance of BehaviorSubject");
}
if (metaData.ctor == null && metaData.initializer == null) {
throw new Error("ctor or initializer must be provided");
}
}
init() {
Ps 1291 fix extension icon updates (#3571) * Add needed factories for AuthService WIP: Allow console logs * Add badge updates * Init by listener * Improve tab identification * Define MV3 background init * Init services in factories. Requires conversion of all factories to promises. We need to initialize in factory since the requester of a service doesn't necessarily know all dependencies for that service. The only alternative is to create an out parameter for a generated init function, which isn't ideal. * Improve badge setting * Use `update-badge` in mv2 and mv3 Separates menu and badge updates * Use update-badge everywhere * Use BrowserApi where possible * Update factories * Merge duplicated methods * Continue using private mode messager for now * Add static platform determination. * Break down methods and extract BrowserApi Concerns * Prefer strict equals * Init two-factor service in factory * Use globalThis types * Prefer `globalThis` * Use Window type definition updated with Opera Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> * Distinguish Opera from Safari Opera includes Gecko, Chrome, Safari, and Opera in its user agent. We need to make sure that we're not in Opera prior to testing Safari. * Update import * Initialize search-service for update badge context * Build all browser MV3 artifacts only uploading Chrome, Edge and Opera artifacts for now, as those support manifest V3 Also corrects build artifact to lower case. * Remove individual dist Co-authored-by: Justin Baur <justindbaur@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com>
2022-10-19 15:55:57 +02:00
if (BrowserApi.manifestVersion !== 3) {
return;
}
this.observe();
this.listenForUpdates();
}
private observe() {
// This may be a memory leak.
// There is no good time to unsubscribe from this observable. Hopefully Manifest V3 clears memory from temporary
// contexts. If so, this is handled by destruction of the context.
this.subscription = this.behaviorSubject
.pipe(
concatMap(async (next) => {
if (this.ignoreNextUpdate) {
this.ignoreNextUpdate = false;
return;
}
await this.updateSession(next);
})
)
.subscribe();
}
private listenForUpdates() {
// This is an unawaited promise, but it will be executed asynchronously in the background.
BrowserApi.messageListener(
this.updateMessageCommand,
async (message) => await this.updateFromMessage(message)
);
}
async updateFromMessage(message: any) {
if (message.command != this.updateMessageCommand || message.id === this.id) {
return;
}
Ps 1291/apply to from json pattern to state (#3425) * Clean up dangling behaviorSubject * Handle null in utils * fix null check * Await promises, even in async functions * Add to/fromJSON methods to State and Accounts This is needed since all storage in manifest v3 is key-value-pair-based and session storage of most data is actually serialized into an encrypted string. * Simplify AccountKeys json parsing * Fix account key (de)serialization * Remove unused DecodedToken state * Correct filename typo * Simplify keys `toJSON` tests * Explain AccountKeys `toJSON` return type * Remove unnecessary `any`s * Remove unique ArrayBuffer serialization * Initialize items in MemoryStorageService * Revert "Fix account key (de)serialization" This reverts commit b1dffb5c2cb7c02feec079704af52f7d9b07359b, which was breaking serializations * Move fromJSON to owning object * Add DeepJsonify type * Use Records for storage * Add new Account Settings to serialized data * Fix failing serialization tests * Extract complex type conversion to helper methods * Remove unnecessary decorator * Return null from json deserializers * Remove unnecessary decorators * Remove obsolete test * Use type-fest `Jsonify` formatting rules for external library * Update jsonify comment Co-authored-by: @eliykat * Remove erroneous comment * Fix unintended deep-jsonify changes * Fix prettierignore * Fix formatting of deep-jsonify.ts Co-authored-by: Thomas Rittson <trittson@bitwarden.com> Co-authored-by: Thomas Rittson <31796059+eliykat@users.noreply.github.com>
2022-09-22 14:51:14 +02:00
const builder = SyncedItemMetadata.builder(this.metaData);
const value = await this.stateService.getFromSessionMemory(this.metaData.sessionKey, builder);
this.ignoreNextUpdate = true;
this.behaviorSubject.next(value);
}
private async updateSession(value: any) {
await this.stateService.setInSessionMemory(this.metaData.sessionKey, value);
await BrowserApi.sendMessage(this.updateMessageCommand, { id: this.id });
}
private get updateMessageCommand() {
return `${this.metaData.sessionKey}_update`;
}
}