mirror of
https://github.com/bitwarden/browser
synced 2025-12-10 13:23:34 +00:00
Ps/pm 5965/better config polling (#8325)
* Create tracker that can await until expected observables are received. * Test dates are almost equal * Remove unused class method * Allow for updating active account in accout service fake * Correct observable tracker behavior Clarify documentation * Transition config service to state provider Updates the config fetching behavior to be lazy and ensure that any emitted value has been updated if older than a configurable value (statically compiled). If desired, config fetching can be ensured fresh through an async. * Update calls to config service in DI and bootstrapping * Migrate account server configs * Fix global config fetching * Test migration rollback * Adhere to implementation naming convention * Adhere to abstract class naming convention * Complete config abstraction rename * Remove unnecessary cli config service * Fix builds * Validate observable does not complete * Use token service to determine authed or unauthed config pull * Remove superfluous factory config * Name describe blocks after the thing they test * Remove implementation documentation Unfortunately the experience when linking to external documentation is quite poor. Instead of following the link and retrieving docs, you get a link that can be clicked to take you out of context to the docs. No link _does_ retrieve docs, but lacks indication in the implementation that documentation exists at all. On the balance, removing the link is the better experience. * Fix storybook
This commit is contained in:
@@ -16,7 +16,7 @@ import { SsoLoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/
|
||||
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
|
||||
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
|
||||
import { ForceSetPasswordReason } from "@bitwarden/common/auth/models/domain/force-set-password-reason";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
@@ -66,7 +66,7 @@ describe("SsoComponent", () => {
|
||||
let mockPasswordGenerationService: MockProxy<PasswordGenerationServiceAbstraction>;
|
||||
let mockLogService: MockProxy<LogService>;
|
||||
let mockUserDecryptionOptionsService: MockProxy<UserDecryptionOptionsServiceAbstraction>;
|
||||
let mockConfigService: MockProxy<ConfigServiceAbstraction>;
|
||||
let mockConfigService: MockProxy<ConfigService>;
|
||||
|
||||
// Mock authService.logIn params
|
||||
let code: string;
|
||||
@@ -107,16 +107,16 @@ describe("SsoComponent", () => {
|
||||
queryParams: mockQueryParams,
|
||||
} as any as ActivatedRoute;
|
||||
|
||||
mockSsoLoginService = mock<SsoLoginServiceAbstraction>();
|
||||
mockStateService = mock<StateService>();
|
||||
mockPlatformUtilsService = mock<PlatformUtilsService>();
|
||||
mockApiService = mock<ApiService>();
|
||||
mockCryptoFunctionService = mock<CryptoFunctionService>();
|
||||
mockEnvironmentService = mock<EnvironmentService>();
|
||||
mockPasswordGenerationService = mock<PasswordGenerationServiceAbstraction>();
|
||||
mockLogService = mock<LogService>();
|
||||
mockUserDecryptionOptionsService = mock<UserDecryptionOptionsServiceAbstraction>();
|
||||
mockConfigService = mock<ConfigServiceAbstraction>();
|
||||
mockSsoLoginService = mock();
|
||||
mockStateService = mock();
|
||||
mockPlatformUtilsService = mock();
|
||||
mockApiService = mock();
|
||||
mockCryptoFunctionService = mock();
|
||||
mockEnvironmentService = mock();
|
||||
mockPasswordGenerationService = mock();
|
||||
mockLogService = mock();
|
||||
mockUserDecryptionOptionsService = mock();
|
||||
mockConfigService = mock();
|
||||
|
||||
// Mock loginStrategyService.logIn params
|
||||
code = "code";
|
||||
@@ -198,7 +198,7 @@ describe("SsoComponent", () => {
|
||||
useValue: mockUserDecryptionOptionsService,
|
||||
},
|
||||
{ provide: LogService, useValue: mockLogService },
|
||||
{ provide: ConfigServiceAbstraction, useValue: mockConfigService },
|
||||
{ provide: ConfigService, useValue: mockConfigService },
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import { SsoLoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/
|
||||
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
|
||||
import { ForceSetPasswordReason } from "@bitwarden/common/auth/models/domain/force-set-password-reason";
|
||||
import { SsoPreValidateResponse } from "@bitwarden/common/auth/models/response/sso-pre-validate.response";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
@@ -65,7 +65,7 @@ export class SsoComponent {
|
||||
protected passwordGenerationService: PasswordGenerationServiceAbstraction,
|
||||
protected logService: LogService,
|
||||
protected userDecryptionOptionsService: UserDecryptionOptionsServiceAbstraction,
|
||||
protected configService: ConfigServiceAbstraction,
|
||||
protected configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async ngOnInit() {
|
||||
|
||||
@@ -21,7 +21,7 @@ import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
|
||||
import { ForceSetPasswordReason } from "@bitwarden/common/auth/models/domain/force-set-password-reason";
|
||||
import { TokenTwoFactorRequest } from "@bitwarden/common/auth/models/request/identity-token/token-two-factor.request";
|
||||
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
@@ -62,7 +62,7 @@ describe("TwoFactorComponent", () => {
|
||||
let mockLoginService: MockProxy<LoginService>;
|
||||
let mockUserDecryptionOptionsService: MockProxy<UserDecryptionOptionsServiceAbstraction>;
|
||||
let mockSsoLoginService: MockProxy<SsoLoginServiceAbstraction>;
|
||||
let mockConfigService: MockProxy<ConfigServiceAbstraction>;
|
||||
let mockConfigService: MockProxy<ConfigService>;
|
||||
|
||||
let mockUserDecryptionOpts: {
|
||||
noMasterPassword: UserDecryptionOptions;
|
||||
@@ -92,7 +92,7 @@ describe("TwoFactorComponent", () => {
|
||||
mockLoginService = mock<LoginService>();
|
||||
mockUserDecryptionOptionsService = mock<UserDecryptionOptionsServiceAbstraction>();
|
||||
mockSsoLoginService = mock<SsoLoginServiceAbstraction>();
|
||||
mockConfigService = mock<ConfigServiceAbstraction>();
|
||||
mockConfigService = mock<ConfigService>();
|
||||
|
||||
mockUserDecryptionOpts = {
|
||||
noMasterPassword: new UserDecryptionOptions({
|
||||
@@ -169,7 +169,7 @@ describe("TwoFactorComponent", () => {
|
||||
useValue: mockUserDecryptionOptionsService,
|
||||
},
|
||||
{ provide: SsoLoginServiceAbstraction, useValue: mockSsoLoginService },
|
||||
{ provide: ConfigServiceAbstraction, useValue: mockConfigService },
|
||||
{ provide: ConfigService, useValue: mockConfigService },
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import { TwoFactorEmailRequest } from "@bitwarden/common/auth/models/request/two
|
||||
import { TwoFactorProviders } from "@bitwarden/common/auth/services/two-factor.service";
|
||||
import { WebAuthnIFrame } from "@bitwarden/common/auth/webauthn-iframe";
|
||||
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
@@ -91,7 +91,7 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
protected loginService: LoginService,
|
||||
protected userDecryptionOptionsService: UserDecryptionOptionsServiceAbstraction,
|
||||
protected ssoLoginService: SsoLoginServiceAbstraction,
|
||||
protected configService: ConfigServiceAbstraction,
|
||||
protected configService: ConfigService,
|
||||
) {
|
||||
super(environmentService, i18nService, platformUtilsService);
|
||||
this.webAuthnSupported = this.platformUtilsService.supportsWebAuthn(win);
|
||||
|
||||
@@ -4,7 +4,7 @@ import { By } from "@angular/platform-browser";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
|
||||
import { FeatureFlag, FeatureFlagValue } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
|
||||
import { IfFeatureDirective } from "./if-feature.directive";
|
||||
@@ -39,7 +39,7 @@ class TestComponent {
|
||||
describe("IfFeatureDirective", () => {
|
||||
let fixture: ComponentFixture<TestComponent>;
|
||||
let content: HTMLElement;
|
||||
let mockConfigService: MockProxy<ConfigServiceAbstraction>;
|
||||
let mockConfigService: MockProxy<ConfigService>;
|
||||
|
||||
const mockConfigFlagValue = (flag: FeatureFlag, flagValue: FeatureFlagValue) => {
|
||||
mockConfigService.getFeatureFlag.mockImplementation((f, defaultValue) =>
|
||||
@@ -51,14 +51,14 @@ describe("IfFeatureDirective", () => {
|
||||
fixture.debugElement.query(By.css(`[data-testid="${testId}"]`))?.nativeElement;
|
||||
|
||||
beforeEach(async () => {
|
||||
mockConfigService = mock<ConfigServiceAbstraction>();
|
||||
mockConfigService = mock<ConfigService>();
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [IfFeatureDirective, TestComponent],
|
||||
providers: [
|
||||
{ provide: LogService, useValue: mock<LogService>() },
|
||||
{
|
||||
provide: ConfigServiceAbstraction,
|
||||
provide: ConfigService,
|
||||
useValue: mockConfigService,
|
||||
},
|
||||
],
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Directive, Input, OnInit, TemplateRef, ViewContainerRef } from "@angular/core";
|
||||
|
||||
import { FeatureFlag, FeatureFlagValue } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
|
||||
/**
|
||||
@@ -30,7 +30,7 @@ export class IfFeatureDirective implements OnInit {
|
||||
constructor(
|
||||
private templateRef: TemplateRef<any>,
|
||||
private viewContainer: ViewContainerRef,
|
||||
private configService: ConfigServiceAbstraction,
|
||||
private configService: ConfigService,
|
||||
private logService: LogService,
|
||||
) {}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { RouterTestingModule } from "@angular/router/testing";
|
||||
import { mock, MockProxy } from "jest-mock-extended";
|
||||
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
@@ -21,11 +21,11 @@ describe("canAccessFeature", () => {
|
||||
const featureRoute = "enabled-feature";
|
||||
const redirectRoute = "redirect";
|
||||
|
||||
let mockConfigService: MockProxy<ConfigServiceAbstraction>;
|
||||
let mockConfigService: MockProxy<ConfigService>;
|
||||
let mockPlatformUtilsService: MockProxy<PlatformUtilsService>;
|
||||
|
||||
const setup = (featureGuard: CanActivateFn, flagValue: any) => {
|
||||
mockConfigService = mock<ConfigServiceAbstraction>();
|
||||
mockConfigService = mock<ConfigService>();
|
||||
mockPlatformUtilsService = mock<PlatformUtilsService>();
|
||||
|
||||
// Mock the correct getter based on the type of flagValue; also mock default values if one is not provided
|
||||
@@ -56,7 +56,7 @@ describe("canAccessFeature", () => {
|
||||
]),
|
||||
],
|
||||
providers: [
|
||||
{ provide: ConfigServiceAbstraction, useValue: mockConfigService },
|
||||
{ provide: ConfigService, useValue: mockConfigService },
|
||||
{ provide: PlatformUtilsService, useValue: mockPlatformUtilsService },
|
||||
{ provide: LogService, useValue: mock<LogService>() },
|
||||
{
|
||||
|
||||
@@ -2,7 +2,7 @@ import { inject } from "@angular/core";
|
||||
import { CanActivateFn, Router } from "@angular/router";
|
||||
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
@@ -23,7 +23,7 @@ export const canAccessFeature = (
|
||||
redirectUrlOnDisabled?: string,
|
||||
): CanActivateFn => {
|
||||
return async () => {
|
||||
const configService = inject(ConfigServiceAbstraction);
|
||||
const configService = inject(ConfigService);
|
||||
const platformUtilsService = inject(PlatformUtilsService);
|
||||
const router = inject(Router);
|
||||
const i18nService = inject(I18nService);
|
||||
|
||||
@@ -111,7 +111,7 @@ import { PaymentMethodWarningsService } from "@bitwarden/common/billing/services
|
||||
import { AppIdService as AppIdServiceAbstraction } from "@bitwarden/common/platform/abstractions/app-id.service";
|
||||
import { BroadcasterService as BroadcasterServiceAbstraction } from "@bitwarden/common/platform/abstractions/broadcaster.service";
|
||||
import { ConfigApiServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config-api.service.abstraction";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto-function.service";
|
||||
import { CryptoService as CryptoServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto.service";
|
||||
import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service";
|
||||
@@ -135,7 +135,7 @@ import { Account } from "@bitwarden/common/platform/models/domain/account";
|
||||
import { GlobalState } from "@bitwarden/common/platform/models/domain/global-state";
|
||||
import { AppIdService } from "@bitwarden/common/platform/services/app-id.service";
|
||||
import { ConfigApiService } from "@bitwarden/common/platform/services/config/config-api.service";
|
||||
import { ConfigService } from "@bitwarden/common/platform/services/config/config.service";
|
||||
import { DefaultConfigService } from "@bitwarden/common/platform/services/config/default-config.service";
|
||||
import { ConsoleLogService } from "@bitwarden/common/platform/services/console-log.service";
|
||||
import { CryptoService } from "@bitwarden/common/platform/services/crypto.service";
|
||||
import { EncryptServiceImplementation } from "@bitwarden/common/platform/services/cryptography/encrypt.service.implementation";
|
||||
@@ -400,7 +400,7 @@ const typesafeProviders: Array<SafeProvider> = [
|
||||
autofillSettingsService: AutofillSettingsServiceAbstraction,
|
||||
encryptService: EncryptService,
|
||||
fileUploadService: CipherFileUploadServiceAbstraction,
|
||||
configService: ConfigServiceAbstraction,
|
||||
configService: ConfigService,
|
||||
) =>
|
||||
new CipherService(
|
||||
cryptoService,
|
||||
@@ -424,7 +424,7 @@ const typesafeProviders: Array<SafeProvider> = [
|
||||
AutofillSettingsServiceAbstraction,
|
||||
EncryptService,
|
||||
CipherFileUploadServiceAbstraction,
|
||||
ConfigServiceAbstraction,
|
||||
ConfigService,
|
||||
],
|
||||
}),
|
||||
safeProvider({
|
||||
@@ -851,25 +851,18 @@ const typesafeProviders: Array<SafeProvider> = [
|
||||
deps: [],
|
||||
}),
|
||||
safeProvider({
|
||||
provide: ConfigService,
|
||||
useClass: ConfigService,
|
||||
deps: [
|
||||
StateServiceAbstraction,
|
||||
ConfigApiServiceAbstraction,
|
||||
AuthServiceAbstraction,
|
||||
EnvironmentService,
|
||||
LogService,
|
||||
StateProvider,
|
||||
],
|
||||
provide: DefaultConfigService,
|
||||
useClass: DefaultConfigService,
|
||||
deps: [ConfigApiServiceAbstraction, EnvironmentService, LogService, StateProvider],
|
||||
}),
|
||||
safeProvider({
|
||||
provide: ConfigServiceAbstraction,
|
||||
useExisting: ConfigService,
|
||||
provide: ConfigService,
|
||||
useExisting: DefaultConfigService,
|
||||
}),
|
||||
safeProvider({
|
||||
provide: ConfigApiServiceAbstraction,
|
||||
useClass: ConfigApiService,
|
||||
deps: [ApiServiceAbstraction, AuthServiceAbstraction],
|
||||
deps: [ApiServiceAbstraction, TokenServiceAbstraction],
|
||||
}),
|
||||
safeProvider({
|
||||
provide: AnonymousHubServiceAbstraction,
|
||||
|
||||
@@ -14,7 +14,7 @@ import { Organization } from "@bitwarden/common/admin-console/models/domain/orga
|
||||
import { EventType } from "@bitwarden/common/enums";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { UriMatchStrategy } from "@bitwarden/common/models/domain/domain-service";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
|
||||
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
|
||||
@@ -119,7 +119,7 @@ export class AddEditComponent implements OnInit, OnDestroy {
|
||||
protected dialogService: DialogService,
|
||||
protected win: Window,
|
||||
protected datePipe: DatePipe,
|
||||
protected configService: ConfigServiceAbstraction,
|
||||
protected configService: ConfigService,
|
||||
) {
|
||||
this.typeOptions = [
|
||||
{ name: i18nService.t("typeLogin"), value: CipherType.Login },
|
||||
|
||||
54
libs/common/spec/matchers/to-almost-equal.spec.ts
Normal file
54
libs/common/spec/matchers/to-almost-equal.spec.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
describe("toAlmostEqual custom matcher", () => {
|
||||
it("matches identical Dates", () => {
|
||||
const date = new Date();
|
||||
expect(date).toAlmostEqual(date);
|
||||
});
|
||||
|
||||
it("matches when older but within default ms", () => {
|
||||
const date = new Date();
|
||||
const olderDate = new Date(date.getTime() - 5);
|
||||
expect(date).toAlmostEqual(olderDate);
|
||||
});
|
||||
|
||||
it("matches when newer but within default ms", () => {
|
||||
const date = new Date();
|
||||
const olderDate = new Date(date.getTime() + 5);
|
||||
expect(date).toAlmostEqual(olderDate);
|
||||
});
|
||||
|
||||
it("doesn't match if older than default ms", () => {
|
||||
const date = new Date();
|
||||
const olderDate = new Date(date.getTime() - 11);
|
||||
expect(date).not.toAlmostEqual(olderDate);
|
||||
});
|
||||
|
||||
it("doesn't match if newer than default ms", () => {
|
||||
const date = new Date();
|
||||
const olderDate = new Date(date.getTime() + 11);
|
||||
expect(date).not.toAlmostEqual(olderDate);
|
||||
});
|
||||
|
||||
it("matches when older but within custom ms", () => {
|
||||
const date = new Date();
|
||||
const olderDate = new Date(date.getTime() - 15);
|
||||
expect(date).toAlmostEqual(olderDate, 20);
|
||||
});
|
||||
|
||||
it("matches when newer but within custom ms", () => {
|
||||
const date = new Date();
|
||||
const olderDate = new Date(date.getTime() + 15);
|
||||
expect(date).toAlmostEqual(olderDate, 20);
|
||||
});
|
||||
|
||||
it("doesn't match if older than custom ms", () => {
|
||||
const date = new Date();
|
||||
const olderDate = new Date(date.getTime() - 21);
|
||||
expect(date).not.toAlmostEqual(olderDate, 20);
|
||||
});
|
||||
|
||||
it("doesn't match if newer than custom ms", () => {
|
||||
const date = new Date();
|
||||
const olderDate = new Date(date.getTime() + 21);
|
||||
expect(date).not.toAlmostEqual(olderDate, 20);
|
||||
});
|
||||
});
|
||||
20
libs/common/spec/matchers/to-almost-equal.ts
Normal file
20
libs/common/spec/matchers/to-almost-equal.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Matches the expected date within an optional ms precision
|
||||
* @param received The received date
|
||||
* @param expected The expected date
|
||||
* @param msPrecision The optional precision in milliseconds
|
||||
*/
|
||||
export const toAlmostEqual: jest.CustomMatcher = function (
|
||||
received: Date,
|
||||
expected: Date,
|
||||
msPrecision: number = 10,
|
||||
) {
|
||||
const receivedTime = received.getTime();
|
||||
const expectedTime = expected.getTime();
|
||||
const difference = Math.abs(receivedTime - expectedTime);
|
||||
return {
|
||||
pass: difference <= msPrecision,
|
||||
message: () =>
|
||||
`expected ${received} to be within ${msPrecision}ms of ${expected} (actual difference: ${difference}ms)`,
|
||||
};
|
||||
};
|
||||
86
libs/common/spec/observable-tracker.ts
Normal file
86
libs/common/spec/observable-tracker.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { Observable, Subscription, firstValueFrom, throwError, timeout } from "rxjs";
|
||||
|
||||
/** Test class to enable async awaiting of observable emissions */
|
||||
export class ObservableTracker<T> {
|
||||
private subscription: Subscription;
|
||||
emissions: T[] = [];
|
||||
constructor(private observable: Observable<T>) {
|
||||
this.emissions = this.trackEmissions(observable);
|
||||
}
|
||||
|
||||
/** Unsubscribes from the observable */
|
||||
unsubscribe() {
|
||||
this.subscription.unsubscribe();
|
||||
}
|
||||
|
||||
/**
|
||||
* Awaits the next emission from the observable, or throws if the timeout is exceeded
|
||||
* @param msTimeout The maximum time to wait for another emission before throwing
|
||||
*/
|
||||
async expectEmission(msTimeout = 50) {
|
||||
await firstValueFrom(
|
||||
this.observable.pipe(
|
||||
timeout({
|
||||
first: msTimeout,
|
||||
with: () => throwError(() => new Error("Timeout exceeded waiting for another emission.")),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Awaits until the the total number of emissions observed by this tracker equals or exceeds {@link count}
|
||||
* @param count The number of emissions to wait for
|
||||
*/
|
||||
async pauseUntilReceived(count: number, msTimeout = 50): Promise<T[]> {
|
||||
for (let i = 0; i < count - this.emissions.length; i++) {
|
||||
await this.expectEmission(msTimeout);
|
||||
}
|
||||
return this.emissions;
|
||||
}
|
||||
|
||||
private trackEmissions<T>(observable: Observable<T>): T[] {
|
||||
const emissions: T[] = [];
|
||||
this.subscription = observable.subscribe((value) => {
|
||||
switch (value) {
|
||||
case undefined:
|
||||
case null:
|
||||
emissions.push(value);
|
||||
return;
|
||||
default:
|
||||
// process by type
|
||||
break;
|
||||
}
|
||||
|
||||
switch (typeof value) {
|
||||
case "string":
|
||||
case "number":
|
||||
case "boolean":
|
||||
emissions.push(value);
|
||||
break;
|
||||
case "symbol":
|
||||
// Cheating types to make symbols work at all
|
||||
emissions.push(value.toString() as T);
|
||||
break;
|
||||
default: {
|
||||
emissions.push(clone(value));
|
||||
}
|
||||
}
|
||||
});
|
||||
return emissions;
|
||||
}
|
||||
}
|
||||
function clone(value: any): any {
|
||||
if (global.structuredClone != undefined) {
|
||||
return structuredClone(value);
|
||||
} else {
|
||||
return JSON.parse(JSON.stringify(value));
|
||||
}
|
||||
}
|
||||
|
||||
/** A test helper that builds an @see{@link ObservableTracker}, which can be used to assert things about the
|
||||
* emissions of the given observable
|
||||
* @param observable The observable to track
|
||||
*/
|
||||
export function subscribeTo<T>(observable: Observable<T>) {
|
||||
return new ObservableTracker(observable);
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
import { UserId } from "../../../types/guid";
|
||||
import { ServerConfigResponse } from "../../models/response/server-config.response";
|
||||
|
||||
export abstract class ConfigApiServiceAbstraction {
|
||||
get: () => Promise<ServerConfigResponse>;
|
||||
/**
|
||||
* Fetches the server configuration for the given user. If no user is provided, the configuration will not contain user-specific context.
|
||||
*/
|
||||
get: (userId: UserId | undefined) => Promise<ServerConfigResponse>;
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
import { Observable } from "rxjs";
|
||||
import { SemVer } from "semver";
|
||||
|
||||
import { FeatureFlag } from "../../../enums/feature-flag.enum";
|
||||
import { Region } from "../environment.service";
|
||||
|
||||
import { ServerConfig } from "./server-config";
|
||||
|
||||
export abstract class ConfigServiceAbstraction {
|
||||
serverConfig$: Observable<ServerConfig | null>;
|
||||
cloudRegion$: Observable<Region>;
|
||||
getFeatureFlag$: <T extends boolean | number | string>(
|
||||
key: FeatureFlag,
|
||||
defaultValue?: T,
|
||||
) => Observable<T>;
|
||||
getFeatureFlag: <T extends boolean | number | string>(
|
||||
key: FeatureFlag,
|
||||
defaultValue?: T,
|
||||
) => Promise<T>;
|
||||
checkServerMeetsVersionRequirement$: (
|
||||
minimumRequiredServerVersion: SemVer,
|
||||
) => Observable<boolean>;
|
||||
|
||||
/**
|
||||
* Force ConfigService to fetch an updated config from the server and emit it from serverConfig$
|
||||
* @deprecated The service implementation should subscribe to an observable and use that to trigger a new fetch from
|
||||
* server instead
|
||||
*/
|
||||
triggerServerConfigFetch: () => void;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Observable } from "rxjs";
|
||||
import { SemVer } from "semver";
|
||||
|
||||
import { FeatureFlag } from "../../../enums/feature-flag.enum";
|
||||
import { Region } from "../environment.service";
|
||||
|
||||
import { ServerConfig } from "./server-config";
|
||||
|
||||
export abstract class ConfigService {
|
||||
/** The server config of the currently active user */
|
||||
serverConfig$: Observable<ServerConfig | null>;
|
||||
/** The cloud region of the currently active user */
|
||||
cloudRegion$: Observable<Region>;
|
||||
/**
|
||||
* Retrieves the value of a feature flag for the currently active user
|
||||
* @param key The feature flag to retrieve
|
||||
* @param defaultValue The default value to return if the feature flag is not set or the server's config is irretrievable
|
||||
* @returns An observable that emits the value of the feature flag, updates as the server config changes
|
||||
*/
|
||||
getFeatureFlag$: <T extends boolean | number | string>(
|
||||
key: FeatureFlag,
|
||||
defaultValue?: T,
|
||||
) => Observable<T>;
|
||||
/**
|
||||
* Retrieves the value of a feature flag for the currently active user
|
||||
* @param key The feature flag to retrieve
|
||||
* @param defaultValue The default value to return if the feature flag is not set or the server's config is irretrievable
|
||||
* @returns The value of the feature flag
|
||||
*/
|
||||
getFeatureFlag: <T extends boolean | number | string>(
|
||||
key: FeatureFlag,
|
||||
defaultValue?: T,
|
||||
) => Promise<T>;
|
||||
/**
|
||||
* Verifies whether the server version meets the minimum required version
|
||||
* @param minimumRequiredServerVersion The minimum version required
|
||||
* @returns True if the server version is greater than or equal to the minimum required version
|
||||
*/
|
||||
checkServerMeetsVersionRequirement$: (
|
||||
minimumRequiredServerVersion: SemVer,
|
||||
) => Observable<boolean>;
|
||||
|
||||
/**
|
||||
* Triggers a check that the config for the currently active user is up-to-date. If it is not, it will be fetched from the server and stored.
|
||||
*/
|
||||
abstract ensureConfigFetched(): Promise<void>;
|
||||
}
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
} from "../../models/data/server-config.data";
|
||||
|
||||
const dayInMilliseconds = 24 * 3600 * 1000;
|
||||
const eighteenHoursInMilliseconds = 18 * 3600 * 1000;
|
||||
|
||||
export class ServerConfig {
|
||||
version: string;
|
||||
@@ -38,10 +37,6 @@ export class ServerConfig {
|
||||
return this.getAgeInMilliseconds() <= dayInMilliseconds;
|
||||
}
|
||||
|
||||
expiresSoon(): boolean {
|
||||
return this.getAgeInMilliseconds() >= eighteenHoursInMilliseconds;
|
||||
}
|
||||
|
||||
static fromJSON(obj: Jsonify<ServerConfig>): ServerConfig {
|
||||
if (obj == null) {
|
||||
return null;
|
||||
|
||||
@@ -16,7 +16,6 @@ import { LocalData } from "../../vault/models/data/local.data";
|
||||
import { CipherView } from "../../vault/models/view/cipher.view";
|
||||
import { AddEditCipherInfo } from "../../vault/types/add-edit-cipher-info";
|
||||
import { KdfType } from "../enums";
|
||||
import { ServerConfigData } from "../models/data/server-config.data";
|
||||
import { Account } from "../models/domain/account";
|
||||
import { EncString } from "../models/domain/enc-string";
|
||||
import { StorageOptions } from "../models/domain/storage-options";
|
||||
@@ -278,14 +277,6 @@ export abstract class StateService<T extends Account = Account> {
|
||||
setVaultTimeoutAction: (value: string, options?: StorageOptions) => Promise<void>;
|
||||
getApproveLoginRequests: (options?: StorageOptions) => Promise<boolean>;
|
||||
setApproveLoginRequests: (value: boolean, options?: StorageOptions) => Promise<void>;
|
||||
/**
|
||||
* @deprecated Do not call this directly, use ConfigService
|
||||
*/
|
||||
getServerConfig: (options?: StorageOptions) => Promise<ServerConfigData>;
|
||||
/**
|
||||
* @deprecated Do not call this directly, use ConfigService
|
||||
*/
|
||||
setServerConfig: (value: ServerConfigData, options?: StorageOptions) => Promise<void>;
|
||||
/**
|
||||
* fetches string value of URL user tried to navigate to while unauthenticated.
|
||||
* @param options Defines the storage options for the URL; Defaults to session Storage.
|
||||
|
||||
@@ -18,7 +18,6 @@ import { CipherView } from "../../../vault/models/view/cipher.view";
|
||||
import { AddEditCipherInfo } from "../../../vault/types/add-edit-cipher-info";
|
||||
import { KdfType } from "../../enums";
|
||||
import { Utils } from "../../misc/utils";
|
||||
import { ServerConfigData } from "../../models/data/server-config.data";
|
||||
|
||||
import { EncryptedString, EncString } from "./enc-string";
|
||||
import { SymmetricCryptoKey } from "./symmetric-crypto-key";
|
||||
@@ -196,7 +195,6 @@ export class AccountSettings {
|
||||
protectedPin?: string;
|
||||
vaultTimeout?: number;
|
||||
vaultTimeoutAction?: string = "lock";
|
||||
serverConfig?: ServerConfigData;
|
||||
approveLoginRequests?: boolean;
|
||||
avatarColor?: string;
|
||||
trustDeviceChoiceForDecryption?: boolean;
|
||||
@@ -214,7 +212,6 @@ export class AccountSettings {
|
||||
obj?.pinProtected,
|
||||
EncString.fromJSON,
|
||||
),
|
||||
serverConfig: ServerConfigData.fromJSON(obj?.serverConfig),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
import { ApiService } from "../../../abstractions/api.service";
|
||||
import { AuthService } from "../../../auth/abstractions/auth.service";
|
||||
import { AuthenticationStatus } from "../../../auth/enums/authentication-status";
|
||||
import { TokenService } from "../../../auth/abstractions/token.service";
|
||||
import { UserId } from "../../../types/guid";
|
||||
import { ConfigApiServiceAbstraction } from "../../abstractions/config/config-api.service.abstraction";
|
||||
import { ServerConfigResponse } from "../../models/response/server-config.response";
|
||||
|
||||
export class ConfigApiService implements ConfigApiServiceAbstraction {
|
||||
constructor(
|
||||
private apiService: ApiService,
|
||||
private authService: AuthService,
|
||||
private tokenService: TokenService,
|
||||
) {}
|
||||
|
||||
async get(): Promise<ServerConfigResponse> {
|
||||
async get(userId: UserId | undefined): Promise<ServerConfigResponse> {
|
||||
// Authentication adds extra context to config responses, if the user has an access token, we want to use it
|
||||
// We don't particularly care about ensuring the token is valid and not expired, just that it exists
|
||||
const authed: boolean =
|
||||
(await this.authService.getAuthStatus()) !== AuthenticationStatus.LoggedOut;
|
||||
userId == null ? false : (await this.tokenService.getAccessToken(userId)) != null;
|
||||
|
||||
const r = await this.apiService.send("GET", "/config", null, authed, true);
|
||||
return new ServerConfigResponse(r);
|
||||
|
||||
@@ -1,200 +1,264 @@
|
||||
import { MockProxy, mock } from "jest-mock-extended";
|
||||
import { ReplaySubject, skip, take } from "rxjs";
|
||||
/**
|
||||
* need to update test environment so structuredClone works appropriately
|
||||
* @jest-environment ../../libs/shared/test.environment.ts
|
||||
*/
|
||||
|
||||
import { FakeStateProvider, mockAccountServiceWith } from "../../../../spec";
|
||||
import { AuthService } from "../../../auth/abstractions/auth.service";
|
||||
import { AuthenticationStatus } from "../../../auth/enums/authentication-status";
|
||||
import { mock } from "jest-mock-extended";
|
||||
import { Subject, firstValueFrom, of } from "rxjs";
|
||||
|
||||
import {
|
||||
FakeGlobalState,
|
||||
FakeSingleUserState,
|
||||
FakeStateProvider,
|
||||
awaitAsync,
|
||||
mockAccountServiceWith,
|
||||
} from "../../../../spec";
|
||||
import { subscribeTo } from "../../../../spec/observable-tracker";
|
||||
import { UserId } from "../../../types/guid";
|
||||
import { ConfigApiServiceAbstraction } from "../../abstractions/config/config-api.service.abstraction";
|
||||
import { ServerConfig } from "../../abstractions/config/server-config";
|
||||
import { Environment, EnvironmentService } from "../../abstractions/environment.service";
|
||||
import { LogService } from "../../abstractions/log.service";
|
||||
import { StateService } from "../../abstractions/state.service";
|
||||
import { Utils } from "../../misc/utils";
|
||||
import { ServerConfigData } from "../../models/data/server-config.data";
|
||||
import {
|
||||
EnvironmentServerConfigResponse,
|
||||
ServerConfigResponse,
|
||||
ThirdPartyServerConfigResponse,
|
||||
} from "../../models/response/server-config.response";
|
||||
import { StateProvider } from "../../state";
|
||||
|
||||
import { ConfigService } from "./config.service";
|
||||
import {
|
||||
ApiUrl,
|
||||
DefaultConfigService,
|
||||
RETRIEVAL_INTERVAL,
|
||||
GLOBAL_SERVER_CONFIGURATIONS,
|
||||
USER_SERVER_CONFIG,
|
||||
} from "./default-config.service";
|
||||
|
||||
describe("ConfigService", () => {
|
||||
let stateService: MockProxy<StateService>;
|
||||
let configApiService: MockProxy<ConfigApiServiceAbstraction>;
|
||||
let authService: MockProxy<AuthService>;
|
||||
let environmentService: MockProxy<EnvironmentService>;
|
||||
let logService: MockProxy<LogService>;
|
||||
let replaySubject: ReplaySubject<Environment>;
|
||||
let stateProvider: StateProvider;
|
||||
|
||||
let serverResponseCount: number; // increments to track distinct responses received from server
|
||||
|
||||
// Observables will start emitting as soon as this is created, so only create it
|
||||
// after everything is mocked
|
||||
const configServiceFactory = () => {
|
||||
const configService = new ConfigService(
|
||||
stateService,
|
||||
configApiService,
|
||||
authService,
|
||||
environmentService,
|
||||
logService,
|
||||
stateProvider,
|
||||
);
|
||||
configService.init();
|
||||
return configService;
|
||||
};
|
||||
const configApiService = mock<ConfigApiServiceAbstraction>();
|
||||
const environmentService = mock<EnvironmentService>();
|
||||
const logService = mock<LogService>();
|
||||
let stateProvider: FakeStateProvider;
|
||||
let globalState: FakeGlobalState<Record<ApiUrl, ServerConfig>>;
|
||||
let userState: FakeSingleUserState<ServerConfig>;
|
||||
const activeApiUrl = apiUrl(0);
|
||||
const userId = "userId" as UserId;
|
||||
const accountService = mockAccountServiceWith(userId);
|
||||
const tooOld = new Date(Date.now() - 1.1 * RETRIEVAL_INTERVAL);
|
||||
|
||||
beforeEach(() => {
|
||||
stateService = mock();
|
||||
configApiService = mock();
|
||||
authService = mock();
|
||||
environmentService = mock();
|
||||
logService = mock();
|
||||
replaySubject = new ReplaySubject<Environment>(1);
|
||||
const accountService = mockAccountServiceWith("0" as UserId);
|
||||
stateProvider = new FakeStateProvider(accountService);
|
||||
|
||||
environmentService.environment$ = replaySubject.asObservable();
|
||||
|
||||
serverResponseCount = 1;
|
||||
configApiService.get.mockImplementation(() =>
|
||||
Promise.resolve(serverConfigResponseFactory("server" + serverResponseCount++)),
|
||||
);
|
||||
|
||||
jest.useFakeTimers();
|
||||
globalState = stateProvider.global.getFake(GLOBAL_SERVER_CONFIGURATIONS);
|
||||
userState = stateProvider.singleUser.getFake(userId, USER_SERVER_CONFIG);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
it("Uses storage as fallback", (done) => {
|
||||
const storedConfigData = serverConfigDataFactory("storedConfig");
|
||||
stateService.getServerConfig.mockResolvedValueOnce(storedConfigData);
|
||||
describe.each([null, userId])("active user: %s", (activeUserId) => {
|
||||
let sut: DefaultConfigService;
|
||||
|
||||
configApiService.get.mockRejectedValueOnce(new Error("Unable to fetch"));
|
||||
|
||||
const configService = configServiceFactory();
|
||||
|
||||
configService.serverConfig$.pipe(take(1)).subscribe((config) => {
|
||||
expect(config).toEqual(new ServerConfig(storedConfigData));
|
||||
expect(stateService.getServerConfig).toHaveBeenCalledTimes(1);
|
||||
expect(stateService.setServerConfig).not.toHaveBeenCalled();
|
||||
done();
|
||||
beforeAll(async () => {
|
||||
await accountService.switchAccount(activeUserId);
|
||||
});
|
||||
|
||||
configService.triggerServerConfigFetch();
|
||||
});
|
||||
|
||||
it("Stream does not error out if fetch fails", (done) => {
|
||||
const storedConfigData = serverConfigDataFactory("storedConfig");
|
||||
stateService.getServerConfig.mockResolvedValueOnce(storedConfigData);
|
||||
|
||||
const configService = configServiceFactory();
|
||||
|
||||
configService.serverConfig$.pipe(skip(1), take(1)).subscribe((config) => {
|
||||
try {
|
||||
expect(config.gitHash).toEqual("server1");
|
||||
done();
|
||||
} catch (e) {
|
||||
done(e);
|
||||
}
|
||||
});
|
||||
|
||||
configApiService.get.mockRejectedValueOnce(new Error("Unable to fetch"));
|
||||
configService.triggerServerConfigFetch();
|
||||
|
||||
configApiService.get.mockResolvedValueOnce(serverConfigResponseFactory("server1"));
|
||||
configService.triggerServerConfigFetch();
|
||||
});
|
||||
|
||||
describe("Fetches config from server", () => {
|
||||
beforeEach(() => {
|
||||
stateService.getServerConfig.mockResolvedValueOnce(null);
|
||||
environmentService.environment$ = of(environmentFactory(activeApiUrl));
|
||||
sut = new DefaultConfigService(
|
||||
configApiService,
|
||||
environmentService,
|
||||
logService,
|
||||
stateProvider,
|
||||
);
|
||||
});
|
||||
|
||||
it.each<number | jest.DoneCallback>([1, 2, 3])(
|
||||
"after %p hour/s",
|
||||
(hours: number, done: jest.DoneCallback) => {
|
||||
const configService = configServiceFactory();
|
||||
describe("serverConfig$", () => {
|
||||
it.each([{}, null])("handles null stored state", async (globalTestState) => {
|
||||
globalState.stateSubject.next(globalTestState);
|
||||
userState.nextState(null);
|
||||
await expect(firstValueFrom(sut.serverConfig$)).resolves.not.toThrow();
|
||||
});
|
||||
|
||||
// skip previous hours (if any)
|
||||
configService.serverConfig$.pipe(skip(hours - 1), take(1)).subscribe((config) => {
|
||||
try {
|
||||
expect(config.gitHash).toEqual("server" + hours);
|
||||
expect(configApiService.get).toHaveBeenCalledTimes(hours);
|
||||
done();
|
||||
} catch (e) {
|
||||
done(e);
|
||||
}
|
||||
describe.each(["stale", "missing"])("%s config", (configStateDescription) => {
|
||||
const userStored =
|
||||
configStateDescription === "missing"
|
||||
? null
|
||||
: serverConfigFactory(activeApiUrl + userId, tooOld);
|
||||
const globalStored =
|
||||
configStateDescription === "missing"
|
||||
? {}
|
||||
: {
|
||||
[activeApiUrl]: serverConfigFactory(activeApiUrl, tooOld),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
globalState.stateSubject.next(globalStored);
|
||||
userState.nextState(userStored);
|
||||
});
|
||||
|
||||
const oneHourInMs = 1000 * 3600;
|
||||
jest.advanceTimersByTime(oneHourInMs * hours + 1);
|
||||
},
|
||||
);
|
||||
// sanity check
|
||||
test("authed and unauthorized state are different", () => {
|
||||
expect(globalStored[activeApiUrl]).not.toEqual(userStored);
|
||||
});
|
||||
|
||||
it("when environment URLs change", (done) => {
|
||||
const configService = configServiceFactory();
|
||||
describe("fail to fetch", () => {
|
||||
beforeEach(() => {
|
||||
configApiService.get.mockRejectedValue(new Error("Unable to fetch"));
|
||||
});
|
||||
|
||||
configService.serverConfig$.pipe(take(1)).subscribe((config) => {
|
||||
try {
|
||||
expect(config.gitHash).toEqual("server1");
|
||||
done();
|
||||
} catch (e) {
|
||||
done(e);
|
||||
}
|
||||
it("uses storage as fallback", async () => {
|
||||
const actual = await firstValueFrom(sut.serverConfig$);
|
||||
expect(actual).toEqual(activeUserId ? userStored : globalStored[activeApiUrl]);
|
||||
expect(configApiService.get).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("does not error out when fetch fails", async () => {
|
||||
await expect(firstValueFrom(sut.serverConfig$)).resolves.not.toThrow();
|
||||
expect(configApiService.get).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("logs an error when unable to fetch", async () => {
|
||||
await firstValueFrom(sut.serverConfig$);
|
||||
|
||||
expect(logService.error).toHaveBeenCalledWith(
|
||||
`Unable to fetch ServerConfig from ${activeApiUrl}: Unable to fetch`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("fetch success", () => {
|
||||
const response = serverConfigResponseFactory();
|
||||
const newConfig = new ServerConfig(new ServerConfigData(response));
|
||||
|
||||
it("should be a new config", async () => {
|
||||
expect(newConfig).not.toEqual(activeUserId ? userStored : globalStored[activeApiUrl]);
|
||||
});
|
||||
|
||||
it("fetches config from server when it's older than an hour", async () => {
|
||||
await firstValueFrom(sut.serverConfig$);
|
||||
|
||||
expect(configApiService.get).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("returns the updated config", async () => {
|
||||
configApiService.get.mockResolvedValue(response);
|
||||
|
||||
const actual = await firstValueFrom(sut.serverConfig$);
|
||||
|
||||
// This is the time the response is converted to a config
|
||||
expect(actual.utcDate).toAlmostEqual(newConfig.utcDate, 1000);
|
||||
delete actual.utcDate;
|
||||
delete newConfig.utcDate;
|
||||
|
||||
expect(actual).toEqual(newConfig);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
replaySubject.next(null);
|
||||
});
|
||||
describe("fresh configuration", () => {
|
||||
const userStored = serverConfigFactory(activeApiUrl + userId);
|
||||
const globalStored = {
|
||||
[activeApiUrl]: serverConfigFactory(activeApiUrl),
|
||||
};
|
||||
beforeEach(() => {
|
||||
globalState.stateSubject.next(globalStored);
|
||||
userState.nextState(userStored);
|
||||
});
|
||||
it("does not fetch from server", async () => {
|
||||
await firstValueFrom(sut.serverConfig$);
|
||||
|
||||
it("when triggerServerConfigFetch() is called", (done) => {
|
||||
const configService = configServiceFactory();
|
||||
expect(configApiService.get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
configService.serverConfig$.pipe(take(1)).subscribe((config) => {
|
||||
try {
|
||||
expect(config.gitHash).toEqual("server1");
|
||||
done();
|
||||
} catch (e) {
|
||||
done(e);
|
||||
}
|
||||
it("uses stored value", async () => {
|
||||
const actual = await firstValueFrom(sut.serverConfig$);
|
||||
expect(actual).toEqual(activeUserId ? userStored : globalStored[activeApiUrl]);
|
||||
});
|
||||
|
||||
it("does not complete after emit", async () => {
|
||||
const emissions = [];
|
||||
const subscription = sut.serverConfig$.subscribe((v) => emissions.push(v));
|
||||
await awaitAsync();
|
||||
expect(emissions.length).toBe(1);
|
||||
expect(subscription.closed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
configService.triggerServerConfigFetch();
|
||||
});
|
||||
});
|
||||
|
||||
it("Saves server config to storage when the user is logged in", (done) => {
|
||||
stateService.getServerConfig.mockResolvedValueOnce(null);
|
||||
authService.getAuthStatus.mockResolvedValue(AuthenticationStatus.Locked);
|
||||
const configService = configServiceFactory();
|
||||
describe("environment change", () => {
|
||||
let sut: DefaultConfigService;
|
||||
let environmentSubject: Subject<Environment>;
|
||||
|
||||
configService.serverConfig$.pipe(take(1)).subscribe(() => {
|
||||
try {
|
||||
expect(stateService.setServerConfig).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ gitHash: "server1" }),
|
||||
);
|
||||
done();
|
||||
} catch (e) {
|
||||
done(e);
|
||||
}
|
||||
beforeAll(async () => {
|
||||
// updating environment with an active account is undefined behavior
|
||||
await accountService.switchAccount(null);
|
||||
});
|
||||
|
||||
configService.triggerServerConfigFetch();
|
||||
beforeEach(() => {
|
||||
environmentSubject = new Subject<Environment>();
|
||||
environmentService.environment$ = environmentSubject;
|
||||
sut = new DefaultConfigService(
|
||||
configApiService,
|
||||
environmentService,
|
||||
logService,
|
||||
stateProvider,
|
||||
);
|
||||
});
|
||||
|
||||
describe("serverConfig$", () => {
|
||||
it("emits a new config when the environment changes", async () => {
|
||||
const globalStored = {
|
||||
[apiUrl(0)]: serverConfigFactory(apiUrl(0)),
|
||||
[apiUrl(1)]: serverConfigFactory(apiUrl(1)),
|
||||
};
|
||||
globalState.stateSubject.next(globalStored);
|
||||
|
||||
const spy = subscribeTo(sut.serverConfig$);
|
||||
|
||||
environmentSubject.next(environmentFactory(apiUrl(0)));
|
||||
environmentSubject.next(environmentFactory(apiUrl(1)));
|
||||
|
||||
const expected = [globalStored[apiUrl(0)], globalStored[apiUrl(1)]];
|
||||
|
||||
const actual = await spy.pauseUntilReceived(2);
|
||||
expect(actual.length).toBe(2);
|
||||
|
||||
// validate dates this is done separately because the dates are created when ServerConfig is initialized
|
||||
expect(actual[0].utcDate).toAlmostEqual(expected[0].utcDate, 1000);
|
||||
expect(actual[1].utcDate).toAlmostEqual(expected[1].utcDate, 1000);
|
||||
delete actual[0].utcDate;
|
||||
delete actual[1].utcDate;
|
||||
delete expected[0].utcDate;
|
||||
delete expected[1].utcDate;
|
||||
|
||||
expect(actual).toEqual(expected);
|
||||
spy.unsubscribe();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
function serverConfigDataFactory(gitHash: string) {
|
||||
return new ServerConfigData(serverConfigResponseFactory(gitHash));
|
||||
function apiUrl(count: number) {
|
||||
return `https://api${count}.test.com`;
|
||||
}
|
||||
|
||||
function serverConfigResponseFactory(gitHash: string) {
|
||||
function serverConfigFactory(hash: string, date: Date = new Date()) {
|
||||
const config = new ServerConfig(serverConfigDataFactory(hash));
|
||||
config.utcDate = date;
|
||||
return config;
|
||||
}
|
||||
|
||||
function serverConfigDataFactory(hash?: string) {
|
||||
return new ServerConfigData(serverConfigResponseFactory(hash));
|
||||
}
|
||||
|
||||
function serverConfigResponseFactory(hash?: string) {
|
||||
return new ServerConfigResponse({
|
||||
version: "myConfigVersion",
|
||||
gitHash: gitHash,
|
||||
gitHash: hash ?? Utils.newGuid(), // Use optional git hash to store uniqueness value
|
||||
server: new ThirdPartyServerConfigResponse({
|
||||
name: "myThirdPartyServer",
|
||||
url: "www.example.com",
|
||||
@@ -209,3 +273,9 @@ function serverConfigResponseFactory(gitHash: string) {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function environmentFactory(apiUrl: string) {
|
||||
return {
|
||||
getApiUrl: () => apiUrl,
|
||||
} as Environment;
|
||||
}
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
import {
|
||||
ReplaySubject,
|
||||
Subject,
|
||||
catchError,
|
||||
concatMap,
|
||||
defer,
|
||||
delayWhen,
|
||||
firstValueFrom,
|
||||
map,
|
||||
merge,
|
||||
timer,
|
||||
} from "rxjs";
|
||||
import { SemVer } from "semver";
|
||||
|
||||
import { AuthService } from "../../../auth/abstractions/auth.service";
|
||||
import { AuthenticationStatus } from "../../../auth/enums/authentication-status";
|
||||
import { FeatureFlag, FeatureFlagValue } from "../../../enums/feature-flag.enum";
|
||||
import { ConfigApiServiceAbstraction } from "../../abstractions/config/config-api.service.abstraction";
|
||||
import { ConfigServiceAbstraction } from "../../abstractions/config/config.service.abstraction";
|
||||
import { ServerConfig } from "../../abstractions/config/server-config";
|
||||
import { EnvironmentService, Region } from "../../abstractions/environment.service";
|
||||
import { LogService } from "../../abstractions/log.service";
|
||||
import { StateService } from "../../abstractions/state.service";
|
||||
import { ServerConfigData } from "../../models/data/server-config.data";
|
||||
import { StateProvider } from "../../state";
|
||||
|
||||
const ONE_HOUR_IN_MILLISECONDS = 1000 * 3600;
|
||||
|
||||
export class ConfigService implements ConfigServiceAbstraction {
|
||||
private inited = false;
|
||||
|
||||
protected _serverConfig = new ReplaySubject<ServerConfig | null>(1);
|
||||
serverConfig$ = this._serverConfig.asObservable();
|
||||
|
||||
private _forceFetchConfig = new Subject<void>();
|
||||
protected refreshTimer$ = timer(ONE_HOUR_IN_MILLISECONDS, ONE_HOUR_IN_MILLISECONDS); // after 1 hour, then every hour
|
||||
|
||||
cloudRegion$ = this.serverConfig$.pipe(
|
||||
map((config) => config?.environment?.cloudRegion ?? Region.US),
|
||||
);
|
||||
|
||||
constructor(
|
||||
private stateService: StateService,
|
||||
private configApiService: ConfigApiServiceAbstraction,
|
||||
private authService: AuthService,
|
||||
private environmentService: EnvironmentService,
|
||||
private logService: LogService,
|
||||
private stateProvider: StateProvider,
|
||||
|
||||
// Used to avoid duplicate subscriptions, e.g. in browser between the background and popup
|
||||
private subscribe = true,
|
||||
) {}
|
||||
|
||||
init() {
|
||||
if (!this.subscribe || this.inited) {
|
||||
return;
|
||||
}
|
||||
|
||||
const latestServerConfig$ = defer(() => this.configApiService.get()).pipe(
|
||||
map((response) => new ServerConfigData(response)),
|
||||
delayWhen((data) => this.saveConfig(data)),
|
||||
catchError((e: unknown) => {
|
||||
// fall back to stored ServerConfig (if any)
|
||||
this.logService.error("Unable to fetch ServerConfig: " + (e as Error)?.message);
|
||||
return this.stateService.getServerConfig();
|
||||
}),
|
||||
);
|
||||
|
||||
// If you need to fetch a new config when an event occurs, add an observable that emits on that event here
|
||||
merge(
|
||||
this.refreshTimer$, // an overridable interval
|
||||
this.environmentService.environment$, // when environment URLs change (including when app is started)
|
||||
this._forceFetchConfig, // manual
|
||||
)
|
||||
.pipe(
|
||||
concatMap(() => latestServerConfig$),
|
||||
map((data) => (data == null ? null : new ServerConfig(data))),
|
||||
)
|
||||
.subscribe((config) => this._serverConfig.next(config));
|
||||
|
||||
this.inited = true;
|
||||
}
|
||||
|
||||
getFeatureFlag$<T extends FeatureFlagValue>(key: FeatureFlag, defaultValue?: T) {
|
||||
return this.serverConfig$.pipe(
|
||||
map((serverConfig) => {
|
||||
if (serverConfig?.featureStates == null || serverConfig.featureStates[key] == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return serverConfig.featureStates[key] as T;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async getFeatureFlag<T extends FeatureFlagValue>(key: FeatureFlag, defaultValue?: T) {
|
||||
return await firstValueFrom(this.getFeatureFlag$(key, defaultValue));
|
||||
}
|
||||
|
||||
triggerServerConfigFetch() {
|
||||
this._forceFetchConfig.next();
|
||||
}
|
||||
|
||||
private async saveConfig(data: ServerConfigData) {
|
||||
if ((await this.authService.getAuthStatus()) === AuthenticationStatus.LoggedOut) {
|
||||
return;
|
||||
}
|
||||
|
||||
const userId = await firstValueFrom(this.stateProvider.activeUserId$);
|
||||
await this.stateService.setServerConfig(data);
|
||||
await this.environmentService.setCloudRegion(userId, data.environment?.cloudRegion);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verifies whether the server version meets the minimum required version
|
||||
* @param minimumRequiredServerVersion The minimum version required
|
||||
* @returns True if the server version is greater than or equal to the minimum required version
|
||||
*/
|
||||
checkServerMeetsVersionRequirement$(minimumRequiredServerVersion: SemVer) {
|
||||
return this.serverConfig$.pipe(
|
||||
map((serverConfig) => {
|
||||
if (serverConfig == null) {
|
||||
return false;
|
||||
}
|
||||
const serverVersion = new SemVer(serverConfig.version);
|
||||
return serverVersion.compare(minimumRequiredServerVersion) >= 0;
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import {
|
||||
NEVER,
|
||||
Observable,
|
||||
Subject,
|
||||
combineLatest,
|
||||
firstValueFrom,
|
||||
map,
|
||||
mergeWith,
|
||||
of,
|
||||
shareReplay,
|
||||
switchMap,
|
||||
tap,
|
||||
} from "rxjs";
|
||||
import { SemVer } from "semver";
|
||||
|
||||
import { FeatureFlag, FeatureFlagValue } from "../../../enums/feature-flag.enum";
|
||||
import { UserId } from "../../../types/guid";
|
||||
import { ConfigApiServiceAbstraction } from "../../abstractions/config/config-api.service.abstraction";
|
||||
import { ConfigService } from "../../abstractions/config/config.service";
|
||||
import { ServerConfig } from "../../abstractions/config/server-config";
|
||||
import { EnvironmentService, Region } from "../../abstractions/environment.service";
|
||||
import { LogService } from "../../abstractions/log.service";
|
||||
import { ServerConfigData } from "../../models/data/server-config.data";
|
||||
import { CONFIG_DISK, KeyDefinition, StateProvider, UserKeyDefinition } from "../../state";
|
||||
|
||||
export const RETRIEVAL_INTERVAL = 3_600_000; // 1 hour
|
||||
|
||||
export type ApiUrl = string;
|
||||
|
||||
export const USER_SERVER_CONFIG = new UserKeyDefinition<ServerConfig>(CONFIG_DISK, "serverConfig", {
|
||||
deserializer: (data) => (data == null ? null : ServerConfig.fromJSON(data)),
|
||||
clearOn: ["logout"],
|
||||
});
|
||||
|
||||
// TODO MDG: When to clean these up?
|
||||
export const GLOBAL_SERVER_CONFIGURATIONS = KeyDefinition.record<ServerConfig, ApiUrl>(
|
||||
CONFIG_DISK,
|
||||
"byServer",
|
||||
{
|
||||
deserializer: (data) => (data == null ? null : ServerConfig.fromJSON(data)),
|
||||
},
|
||||
);
|
||||
|
||||
// FIXME: currently we are limited to api requests for active users. Update to accept a UserId and APIUrl once ApiService supports it.
|
||||
export class DefaultConfigService implements ConfigService {
|
||||
private failedFetchFallbackSubject = new Subject<ServerConfig>();
|
||||
|
||||
serverConfig$: Observable<ServerConfig>;
|
||||
|
||||
cloudRegion$: Observable<Region>;
|
||||
|
||||
constructor(
|
||||
private configApiService: ConfigApiServiceAbstraction,
|
||||
private environmentService: EnvironmentService,
|
||||
private logService: LogService,
|
||||
private stateProvider: StateProvider,
|
||||
) {
|
||||
const apiUrl$ = this.environmentService.environment$.pipe(
|
||||
map((environment) => environment.getApiUrl()),
|
||||
);
|
||||
|
||||
this.serverConfig$ = combineLatest([this.stateProvider.activeUserId$, apiUrl$]).pipe(
|
||||
switchMap(([userId, apiUrl]) => {
|
||||
const config$ =
|
||||
userId == null ? this.globalConfigFor$(apiUrl) : this.userConfigFor$(userId);
|
||||
return config$.pipe(map((config) => [config, userId, apiUrl] as const));
|
||||
}),
|
||||
tap(async (rec) => {
|
||||
const [existingConfig, userId, apiUrl] = rec;
|
||||
// Grab new config if older retrieval interval
|
||||
if (!existingConfig || this.olderThanRetrievalInterval(existingConfig.utcDate)) {
|
||||
await this.renewConfig(existingConfig, userId, apiUrl);
|
||||
}
|
||||
}),
|
||||
switchMap(([existingConfig]) => {
|
||||
// If we needed to fetch, stop this emit, we'll get a new one after update
|
||||
// This is split up with the above tap because we need to return an observable from a failed promise,
|
||||
// which isn't very doable since promises are converted to observables in switchMap
|
||||
if (!existingConfig || this.olderThanRetrievalInterval(existingConfig.utcDate)) {
|
||||
return NEVER;
|
||||
}
|
||||
return of(existingConfig);
|
||||
}),
|
||||
// If fetch fails, we'll emit on this subject to fallback to the existing config
|
||||
mergeWith(this.failedFetchFallbackSubject),
|
||||
shareReplay({ refCount: true, bufferSize: 1 }),
|
||||
);
|
||||
|
||||
this.cloudRegion$ = this.serverConfig$.pipe(
|
||||
map((config) => config?.environment?.cloudRegion ?? Region.US),
|
||||
);
|
||||
}
|
||||
getFeatureFlag$<T extends FeatureFlagValue>(key: FeatureFlag, defaultValue?: T) {
|
||||
return this.serverConfig$.pipe(
|
||||
map((serverConfig) => {
|
||||
if (serverConfig?.featureStates == null || serverConfig.featureStates[key] == null) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return serverConfig.featureStates[key] as T;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async getFeatureFlag<T extends FeatureFlagValue>(key: FeatureFlag, defaultValue?: T) {
|
||||
return await firstValueFrom(this.getFeatureFlag$(key, defaultValue));
|
||||
}
|
||||
|
||||
checkServerMeetsVersionRequirement$(minimumRequiredServerVersion: SemVer) {
|
||||
return this.serverConfig$.pipe(
|
||||
map((serverConfig) => {
|
||||
if (serverConfig == null) {
|
||||
return false;
|
||||
}
|
||||
const serverVersion = new SemVer(serverConfig.version);
|
||||
return serverVersion.compare(minimumRequiredServerVersion) >= 0;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async ensureConfigFetched() {
|
||||
// Triggering a retrieval for the given user ensures that the config is less than RETRIEVAL_INTERVAL old
|
||||
await firstValueFrom(this.serverConfig$);
|
||||
}
|
||||
|
||||
private olderThanRetrievalInterval(date: Date) {
|
||||
return new Date().getTime() - date.getTime() > RETRIEVAL_INTERVAL;
|
||||
}
|
||||
|
||||
// Updates the on-disk configuration with a newly retrieved configuration
|
||||
private async renewConfig(
|
||||
existingConfig: ServerConfig,
|
||||
userId: UserId,
|
||||
apiUrl: string,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const response = await this.configApiService.get(userId);
|
||||
const newConfig = new ServerConfig(new ServerConfigData(response));
|
||||
|
||||
// Update the environment region
|
||||
if (
|
||||
newConfig?.environment?.cloudRegion != null &&
|
||||
existingConfig?.environment?.cloudRegion != newConfig.environment.cloudRegion
|
||||
) {
|
||||
// Null userId sets global, otherwise sets to the given user
|
||||
await this.environmentService.setCloudRegion(userId, newConfig?.environment?.cloudRegion);
|
||||
}
|
||||
|
||||
if (userId == null) {
|
||||
// update global state with new pulled config
|
||||
await this.stateProvider.getGlobal(GLOBAL_SERVER_CONFIGURATIONS).update((configs) => {
|
||||
return { ...configs, [apiUrl]: newConfig };
|
||||
});
|
||||
} else {
|
||||
// update state with new pulled config
|
||||
await this.stateProvider.setUserState(USER_SERVER_CONFIG, newConfig, userId);
|
||||
}
|
||||
} catch (e) {
|
||||
// mutate error to be handled by catchError
|
||||
this.logService.error(
|
||||
`Unable to fetch ServerConfig from ${apiUrl}: ${(e as Error)?.message}`,
|
||||
);
|
||||
// Emit the existing config
|
||||
this.failedFetchFallbackSubject.next(existingConfig);
|
||||
}
|
||||
}
|
||||
|
||||
private globalConfigFor$(apiUrl: string): Observable<ServerConfig> {
|
||||
return this.stateProvider
|
||||
.getGlobal(GLOBAL_SERVER_CONFIGURATIONS)
|
||||
.state$.pipe(map((configs) => configs?.[apiUrl]));
|
||||
}
|
||||
|
||||
private userConfigFor$(userId: UserId): Observable<ServerConfig> {
|
||||
return this.stateProvider.getUser(userId, USER_SERVER_CONFIG).state$;
|
||||
}
|
||||
}
|
||||
@@ -32,7 +32,6 @@ import {
|
||||
import { HtmlStorageLocation, KdfType, StorageLocation } from "../enums";
|
||||
import { StateFactory } from "../factories/state-factory";
|
||||
import { Utils } from "../misc/utils";
|
||||
import { ServerConfigData } from "../models/data/server-config.data";
|
||||
import { Account, AccountData, AccountSettings } from "../models/domain/account";
|
||||
import { EncString } from "../models/domain/enc-string";
|
||||
import { GlobalState } from "../models/domain/global-state";
|
||||
@@ -1377,23 +1376,6 @@ export class StateService<
|
||||
);
|
||||
}
|
||||
|
||||
async setServerConfig(value: ServerConfigData, options?: StorageOptions): Promise<void> {
|
||||
const account = await this.getAccount(
|
||||
this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()),
|
||||
);
|
||||
account.settings.serverConfig = value;
|
||||
return await this.saveAccount(
|
||||
account,
|
||||
this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()),
|
||||
);
|
||||
}
|
||||
|
||||
async getServerConfig(options: StorageOptions): Promise<ServerConfigData> {
|
||||
return (
|
||||
await this.getAccount(this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()))
|
||||
)?.settings?.serverConfig;
|
||||
}
|
||||
|
||||
async getDeepLinkRedirectUrl(options?: StorageOptions): Promise<string> {
|
||||
return (
|
||||
await this.getGlobals(this.reconcileOptions(options, await this.defaultOnDiskOptions()))
|
||||
|
||||
@@ -73,6 +73,9 @@ export const APPLICATION_ID_DISK = new StateDefinition("applicationId", "disk",
|
||||
});
|
||||
export const BIOMETRIC_SETTINGS_DISK = new StateDefinition("biometricSettings", "disk");
|
||||
export const CLEAR_EVENT_DISK = new StateDefinition("clearEvent", "disk");
|
||||
export const CONFIG_DISK = new StateDefinition("config", "disk", {
|
||||
web: "disk-local",
|
||||
});
|
||||
export const CRYPTO_DISK = new StateDefinition("crypto", "disk");
|
||||
export const CRYPTO_MEMORY = new StateDefinition("crypto", "memory");
|
||||
export const DESKTOP_SETTINGS_DISK = new StateDefinition("desktopSettings", "disk");
|
||||
|
||||
@@ -44,6 +44,7 @@ import { MergeEnvironmentState } from "./migrations/45-merge-environment-state";
|
||||
import { DeleteBiometricPromptCancelledData } from "./migrations/46-delete-orphaned-biometric-prompt-data";
|
||||
import { MoveDesktopSettingsMigrator } from "./migrations/47-move-desktop-settings";
|
||||
import { MoveDdgToStateProviderMigrator } from "./migrations/48-move-ddg-to-state-provider";
|
||||
import { AccountServerConfigMigrator } from "./migrations/49-move-account-server-configs";
|
||||
import { AddKeyTypeToOrgKeysMigrator } from "./migrations/5-add-key-type-to-org-keys";
|
||||
import { RemoveLegacyEtmKeyMigrator } from "./migrations/6-remove-legacy-etm-key";
|
||||
import { MoveBiometricAutoPromptToAccount } from "./migrations/7-move-biometric-auto-prompt-to-account";
|
||||
@@ -52,8 +53,7 @@ import { MoveBrowserSettingsToGlobal } from "./migrations/9-move-browser-setting
|
||||
import { MinVersionMigrator } from "./migrations/min-version";
|
||||
|
||||
export const MIN_VERSION = 3;
|
||||
export const CURRENT_VERSION = 48;
|
||||
|
||||
export const CURRENT_VERSION = 49;
|
||||
export type MinVersion = typeof MIN_VERSION;
|
||||
|
||||
export function createMigrationBuilder() {
|
||||
@@ -103,7 +103,8 @@ export function createMigrationBuilder() {
|
||||
.with(MergeEnvironmentState, 44, 45)
|
||||
.with(DeleteBiometricPromptCancelledData, 45, 46)
|
||||
.with(MoveDesktopSettingsMigrator, 46, 47)
|
||||
.with(MoveDdgToStateProviderMigrator, 47, CURRENT_VERSION);
|
||||
.with(MoveDdgToStateProviderMigrator, 47, 48)
|
||||
.with(AccountServerConfigMigrator, 48, CURRENT_VERSION);
|
||||
}
|
||||
|
||||
export async function currentVersion(
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { runMigrator } from "../migration-helper.spec";
|
||||
|
||||
import { AccountServerConfigMigrator } from "./49-move-account-server-configs";
|
||||
|
||||
describe("AccountServerConfigMigrator", () => {
|
||||
const migrator = new AccountServerConfigMigrator(48, 49);
|
||||
|
||||
describe("all data", () => {
|
||||
function toMigrate() {
|
||||
return {
|
||||
authenticatedAccounts: ["user1", "user2"],
|
||||
user1: {
|
||||
settings: {
|
||||
serverConfig: {
|
||||
config: "user1 server config",
|
||||
},
|
||||
},
|
||||
},
|
||||
user2: {
|
||||
settings: {
|
||||
serverConfig: {
|
||||
config: "user2 server config",
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function migrated() {
|
||||
return {
|
||||
authenticatedAccounts: ["user1", "user2"],
|
||||
|
||||
user1: {
|
||||
settings: {},
|
||||
},
|
||||
user2: {
|
||||
settings: {},
|
||||
},
|
||||
user_user1_config_serverConfig: {
|
||||
config: "user1 server config",
|
||||
},
|
||||
user_user2_config_serverConfig: {
|
||||
config: "user2 server config",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function rolledBack(previous: object) {
|
||||
return {
|
||||
...previous,
|
||||
user_user1_config_serverConfig: null as unknown,
|
||||
user_user2_config_serverConfig: null as unknown,
|
||||
};
|
||||
}
|
||||
|
||||
it("migrates", async () => {
|
||||
const output = await runMigrator(migrator, toMigrate(), "migrate");
|
||||
expect(output).toEqual(migrated());
|
||||
});
|
||||
|
||||
it("rolls back", async () => {
|
||||
const output = await runMigrator(migrator, migrated(), "rollback");
|
||||
expect(output).toEqual(rolledBack(toMigrate()));
|
||||
});
|
||||
});
|
||||
|
||||
describe("missing parts", () => {
|
||||
function toMigrate() {
|
||||
return {
|
||||
authenticatedAccounts: ["user1", "user2"],
|
||||
user1: {
|
||||
settings: {
|
||||
serverConfig: {
|
||||
config: "user1 server config",
|
||||
},
|
||||
},
|
||||
},
|
||||
user2: null as unknown,
|
||||
};
|
||||
}
|
||||
|
||||
function migrated() {
|
||||
return {
|
||||
authenticatedAccounts: ["user1", "user2"],
|
||||
user1: {
|
||||
settings: {},
|
||||
},
|
||||
user2: null as unknown,
|
||||
user_user1_config_serverConfig: {
|
||||
config: "user1 server config",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function rollback(previous: object) {
|
||||
return {
|
||||
...previous,
|
||||
user_user1_config_serverConfig: null as unknown,
|
||||
};
|
||||
}
|
||||
|
||||
it("migrates", async () => {
|
||||
const output = await runMigrator(migrator, toMigrate(), "migrate");
|
||||
expect(output).toEqual(migrated());
|
||||
});
|
||||
|
||||
it("rolls back", async () => {
|
||||
const output = await runMigrator(migrator, migrated(), "rollback");
|
||||
expect(output).toEqual(rollback(toMigrate()));
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,51 @@
|
||||
import { KeyDefinitionLike, MigrationHelper, StateDefinitionLike } from "../migration-helper";
|
||||
import { Migrator } from "../migrator";
|
||||
|
||||
const CONFIG_DISK: StateDefinitionLike = { name: "config" };
|
||||
export const USER_SERVER_CONFIG: KeyDefinitionLike = {
|
||||
stateDefinition: CONFIG_DISK,
|
||||
key: "serverConfig",
|
||||
};
|
||||
|
||||
// Note: no need to migrate global configs, they don't currently exist
|
||||
|
||||
type ExpectedAccountType = {
|
||||
settings?: {
|
||||
serverConfig?: unknown;
|
||||
};
|
||||
};
|
||||
|
||||
export class AccountServerConfigMigrator extends Migrator<48, 49> {
|
||||
async migrate(helper: MigrationHelper): Promise<void> {
|
||||
const accounts = await helper.getAccounts<ExpectedAccountType>();
|
||||
|
||||
async function migrateAccount(userId: string, account: ExpectedAccountType): Promise<void> {
|
||||
if (account?.settings?.serverConfig != null) {
|
||||
await helper.setToUser(userId, USER_SERVER_CONFIG, account.settings.serverConfig);
|
||||
delete account.settings.serverConfig;
|
||||
await helper.set(userId, account);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all([...accounts.map(({ userId, account }) => migrateAccount(userId, account))]);
|
||||
}
|
||||
|
||||
async rollback(helper: MigrationHelper): Promise<void> {
|
||||
const accounts = await helper.getAccounts<ExpectedAccountType>();
|
||||
|
||||
async function rollbackAccount(userId: string, account: ExpectedAccountType): Promise<void> {
|
||||
const serverConfig = await helper.getFromUser(userId, USER_SERVER_CONFIG);
|
||||
|
||||
if (serverConfig) {
|
||||
account ??= {};
|
||||
account.settings ??= {};
|
||||
|
||||
account.settings.serverConfig = serverConfig;
|
||||
await helper.setToUser(userId, USER_SERVER_CONFIG, null);
|
||||
await helper.set(userId, account);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all([...accounts.map(({ userId, account }) => rollbackAccount(userId, account))]);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { SearchService } from "../../abstractions/search.service";
|
||||
import { AutofillSettingsService } from "../../autofill/services/autofill-settings.service";
|
||||
import { DomainSettingsService } from "../../autofill/services/domain-settings.service";
|
||||
import { UriMatchStrategy } from "../../models/domain/domain-service";
|
||||
import { ConfigServiceAbstraction } from "../../platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "../../platform/abstractions/config/config.service";
|
||||
import { CryptoService } from "../../platform/abstractions/crypto.service";
|
||||
import { EncryptService } from "../../platform/abstractions/encrypt.service";
|
||||
import { I18nService } from "../../platform/abstractions/i18n.service";
|
||||
@@ -108,7 +108,7 @@ describe("Cipher Service", () => {
|
||||
const i18nService = mock<I18nService>();
|
||||
const searchService = mock<SearchService>();
|
||||
const encryptService = mock<EncryptService>();
|
||||
const configService = mock<ConfigServiceAbstraction>();
|
||||
const configService = mock<ConfigService>();
|
||||
|
||||
let cipherService: CipherService;
|
||||
let cipherObj: Cipher;
|
||||
|
||||
@@ -9,7 +9,7 @@ import { UriMatchStrategySetting } from "../../models/domain/domain-service";
|
||||
import { ErrorResponse } from "../../models/response/error.response";
|
||||
import { ListResponse } from "../../models/response/list.response";
|
||||
import { View } from "../../models/view/view";
|
||||
import { ConfigServiceAbstraction } from "../../platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "../../platform/abstractions/config/config.service";
|
||||
import { CryptoService } from "../../platform/abstractions/crypto.service";
|
||||
import { EncryptService } from "../../platform/abstractions/encrypt.service";
|
||||
import { I18nService } from "../../platform/abstractions/i18n.service";
|
||||
@@ -72,7 +72,7 @@ export class CipherService implements CipherServiceAbstraction {
|
||||
private autofillSettingsService: AutofillSettingsServiceAbstraction,
|
||||
private encryptService: EncryptService,
|
||||
private cipherFileUploadService: CipherFileUploadService,
|
||||
private configService: ConfigServiceAbstraction,
|
||||
private configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async getDecryptedCipherCache(): Promise<CipherView[]> {
|
||||
|
||||
@@ -4,7 +4,7 @@ import { of } from "rxjs";
|
||||
import { AuthService } from "../../../auth/abstractions/auth.service";
|
||||
import { AuthenticationStatus } from "../../../auth/enums/authentication-status";
|
||||
import { DomainSettingsService } from "../../../autofill/services/domain-settings.service";
|
||||
import { ConfigServiceAbstraction } from "../../../platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "../../../platform/abstractions/config/config.service";
|
||||
import { Utils } from "../../../platform/misc/utils";
|
||||
import {
|
||||
Fido2AuthenticatorError,
|
||||
@@ -30,7 +30,7 @@ const VaultUrl = "https://vault.bitwarden.com";
|
||||
|
||||
describe("FidoAuthenticatorService", () => {
|
||||
let authenticator!: MockProxy<Fido2AuthenticatorService>;
|
||||
let configService!: MockProxy<ConfigServiceAbstraction>;
|
||||
let configService!: MockProxy<ConfigService>;
|
||||
let authService!: MockProxy<AuthService>;
|
||||
let vaultSettingsService: MockProxy<VaultSettingsService>;
|
||||
let domainSettingsService: MockProxy<DomainSettingsService>;
|
||||
@@ -39,7 +39,7 @@ describe("FidoAuthenticatorService", () => {
|
||||
|
||||
beforeEach(async () => {
|
||||
authenticator = mock<Fido2AuthenticatorService>();
|
||||
configService = mock<ConfigServiceAbstraction>();
|
||||
configService = mock<ConfigService>();
|
||||
authService = mock<AuthService>();
|
||||
vaultSettingsService = mock<VaultSettingsService>();
|
||||
domainSettingsService = mock<DomainSettingsService>();
|
||||
|
||||
@@ -4,7 +4,7 @@ import { parse } from "tldts";
|
||||
import { AuthService } from "../../../auth/abstractions/auth.service";
|
||||
import { AuthenticationStatus } from "../../../auth/enums/authentication-status";
|
||||
import { DomainSettingsService } from "../../../autofill/services/domain-settings.service";
|
||||
import { ConfigServiceAbstraction } from "../../../platform/abstractions/config/config.service.abstraction";
|
||||
import { ConfigService } from "../../../platform/abstractions/config/config.service";
|
||||
import { LogService } from "../../../platform/abstractions/log.service";
|
||||
import { Utils } from "../../../platform/misc/utils";
|
||||
import {
|
||||
@@ -40,7 +40,7 @@ import { Fido2Utils } from "./fido2-utils";
|
||||
export class Fido2ClientService implements Fido2ClientServiceAbstraction {
|
||||
constructor(
|
||||
private authenticator: Fido2AuthenticatorService,
|
||||
private configService: ConfigServiceAbstraction,
|
||||
private configService: ConfigService,
|
||||
private authService: AuthService,
|
||||
private vaultSettingsService: VaultSettingsService,
|
||||
private domainSettingsService: DomainSettingsService,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { webcrypto } from "crypto";
|
||||
|
||||
import { toEqualBuffer } from "./spec";
|
||||
import { toAlmostEqual } from "./spec/matchers/to-almost-equal";
|
||||
|
||||
Object.defineProperty(window, "crypto", {
|
||||
value: webcrypto,
|
||||
@@ -10,8 +11,15 @@ Object.defineProperty(window, "crypto", {
|
||||
|
||||
expect.extend({
|
||||
toEqualBuffer: toEqualBuffer,
|
||||
toAlmostEqual: toAlmostEqual,
|
||||
});
|
||||
|
||||
export interface CustomMatchers<R = unknown> {
|
||||
toEqualBuffer(expected: Uint8Array | ArrayBuffer): R;
|
||||
/**
|
||||
* Matches the expected date within an optional ms precision
|
||||
* @param expected The expected date
|
||||
* @param msPrecision The optional precision in milliseconds
|
||||
*/
|
||||
toAlmostEqual(expected: Date, msPrecision?: number): R;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user