[BEEEP: PM-10190] Use strict TS checks in CLI service container (#10298)

* move cli service-container to new folder

* fix imports

* add tsconfig and fix type issues in other services

* fix more imports in service-container

* make ts server happy in service-container

* fix actual bugs in cli service-container

* fix package json reference path

* fix service-container import

* update type on cipher service
This commit is contained in:
Jake Fink 2024-08-05 11:39:08 -04:00 committed by GitHub
parent 157f3a5d39
commit 2819ac597f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
24 changed files with 110 additions and 81 deletions

View File

@ -10,7 +10,7 @@ import { ListResponse } from "./models/response/list.response";
import { MessageResponse } from "./models/response/message.response";
import { StringResponse } from "./models/response/string.response";
import { TemplateResponse } from "./models/response/template.response";
import { ServiceContainer } from "./service-container";
import { ServiceContainer } from "./service-container/service-container";
import { CliUtils } from "./utils";
const writeLn = CliUtils.writeLn;

View File

@ -3,7 +3,7 @@ import { program } from "commander";
import { OssServeConfigurator } from "./oss-serve-configurator";
import { registerOssPrograms } from "./register-oss-programs";
import { ServeProgram } from "./serve.program";
import { ServiceContainer } from "./service-container";
import { ServiceContainer } from "./service-container/service-container";
async function main() {
const serviceContainer = new ServiceContainer();

View File

@ -7,7 +7,7 @@ import * as koaJson from "koa-json";
import { Utils } from "@bitwarden/common/platform/misc/utils";
import { OssServeConfigurator } from "../oss-serve-configurator";
import { ServiceContainer } from "../service-container";
import { ServiceContainer } from "../service-container/service-container";
export class ServeCommand {
constructor(

View File

@ -13,7 +13,7 @@ import { RestoreCommand } from "./commands/restore.command";
import { StatusCommand } from "./commands/status.command";
import { Response } from "./models/response";
import { FileResponse } from "./models/response/file.response";
import { ServiceContainer } from "./service-container";
import { ServiceContainer } from "./service-container/service-container";
import { GenerateCommand } from "./tools/generate.command";
import {
SendEditCommand,

View File

@ -1,5 +1,5 @@
import { Program } from "./program";
import { ServiceContainer } from "./service-container";
import { ServiceContainer } from "./service-container/service-container";
import { SendProgram } from "./tools/send/send.program";
import { VaultProgram } from "./vault.program";

View File

@ -3,7 +3,7 @@ import { program } from "commander";
import { BaseProgram } from "./base-program";
import { ServeCommand } from "./commands/serve.command";
import { OssServeConfigurator } from "./oss-serve-configurator";
import { ServiceContainer } from "./service-container";
import { ServiceContainer } from "./service-container/service-container";
import { CliUtils } from "./utils";
const writeLn = CliUtils.writeLn;

View File

@ -44,7 +44,10 @@ import { TokenService } from "@bitwarden/common/auth/services/token.service";
import { TwoFactorService } from "@bitwarden/common/auth/services/two-factor.service";
import { UserVerificationApiService } from "@bitwarden/common/auth/services/user-verification/user-verification-api.service";
import { UserVerificationService } from "@bitwarden/common/auth/services/user-verification/user-verification.service";
import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service";
import {
AutofillSettingsService,
AutofillSettingsServiceAbstraction,
} from "@bitwarden/common/autofill/services/autofill-settings.service";
import {
DefaultDomainSettingsService,
DomainSettingsService,
@ -147,18 +150,18 @@ import {
VaultExportServiceAbstraction,
} from "@bitwarden/vault-export-core";
import { CliPlatformUtilsService } from "./platform/services/cli-platform-utils.service";
import { ConsoleLogService } from "./platform/services/console-log.service";
import { I18nService } from "./platform/services/i18n.service";
import { LowdbStorageService } from "./platform/services/lowdb-storage.service";
import { NodeApiService } from "./platform/services/node-api.service";
import { NodeEnvSecureStorageService } from "./platform/services/node-env-secure-storage.service";
import { CliPlatformUtilsService } from "../platform/services/cli-platform-utils.service";
import { ConsoleLogService } from "../platform/services/console-log.service";
import { I18nService } from "../platform/services/i18n.service";
import { LowdbStorageService } from "../platform/services/lowdb-storage.service";
import { NodeApiService } from "../platform/services/node-api.service";
import { NodeEnvSecureStorageService } from "../platform/services/node-env-secure-storage.service";
// Polyfills
global.DOMParser = new jsdom.JSDOM().window.DOMParser;
// eslint-disable-next-line
const packageJson = require("../package.json");
const packageJson = require("../../package.json");
/**
* Instantiates services and makes them available for dependency injection.
@ -254,13 +257,13 @@ export class ServiceContainer {
} else if (process.env.BITWARDENCLI_APPDATA_DIR) {
p = path.resolve(process.env.BITWARDENCLI_APPDATA_DIR);
} else if (process.platform === "darwin") {
p = path.join(process.env.HOME, "Library/Application Support/Bitwarden CLI");
p = path.join(process.env.HOME ?? "", "Library/Application Support/Bitwarden CLI");
} else if (process.platform === "win32") {
p = path.join(process.env.APPDATA, "Bitwarden CLI");
p = path.join(process.env.APPDATA ?? "", "Bitwarden CLI");
} else if (process.env.XDG_CONFIG_HOME) {
p = path.join(process.env.XDG_CONFIG_HOME, "Bitwarden CLI");
} else {
p = path.join(process.env.HOME, ".config/Bitwarden CLI");
p = path.join(process.env.HOME ?? "", ".config/Bitwarden CLI");
}
const logoutCallback = async () => await this.logout();
@ -452,8 +455,6 @@ export class ServiceContainer {
customUserAgent,
);
this.organizationApiService = new OrganizationApiService(this.apiService, this.syncService);
this.containerService = new ContainerService(this.cryptoService, this.encryptService);
this.domainSettingsService = new DefaultDomainSettingsService(this.stateProvider);
@ -524,6 +525,40 @@ export class ServiceContainer {
this.stateProvider,
);
this.authRequestService = new AuthRequestService(
this.appIdService,
this.accountService,
this.masterPasswordService,
this.cryptoService,
this.apiService,
this.stateProvider,
);
this.billingAccountProfileStateService = new DefaultBillingAccountProfileStateService(
this.stateProvider,
);
this.taskSchedulerService = new DefaultTaskSchedulerService(this.logService);
this.authService = new AuthService(
this.accountService,
this.messagingService,
this.cryptoService,
this.apiService,
this.stateService,
this.tokenService,
);
this.configApiService = new ConfigApiService(this.apiService, this.tokenService);
this.configService = new DefaultConfigService(
this.configApiService,
this.environmentService,
this.logService,
this.stateProvider,
this.authService,
);
this.devicesApiService = new DevicesApiServiceImplementation(this.apiService);
this.deviceTrustService = new DeviceTrustService(
this.keyGenerationService,
@ -541,20 +576,6 @@ export class ServiceContainer {
this.configService,
);
this.authRequestService = new AuthRequestService(
this.appIdService,
this.accountService,
this.masterPasswordService,
this.cryptoService,
this.apiService,
this.stateProvider,
);
this.billingAccountProfileStateService = new DefaultBillingAccountProfileStateService(
this.stateProvider,
);
this.taskSchedulerService = new DefaultTaskSchedulerService(this.logService);
this.loginStrategyService = new LoginStrategyService(
this.accountService,
this.masterPasswordService,
@ -583,23 +604,10 @@ export class ServiceContainer {
this.taskSchedulerService,
);
this.authService = new AuthService(
this.accountService,
this.messagingService,
this.cryptoService,
this.apiService,
this.stateService,
this.tokenService,
);
this.configApiService = new ConfigApiService(this.apiService, this.tokenService);
this.configService = new DefaultConfigService(
this.configApiService,
this.environmentService,
this.logService,
// FIXME: CLI does not support autofill
this.autofillSettingsService = new AutofillSettingsService(
this.stateProvider,
this.authService,
this.policyService,
);
this.cipherService = new CipherService(
@ -661,7 +669,7 @@ export class ServiceContainer {
this.taskSchedulerService,
this.logService,
lockedCallback,
null,
undefined,
);
this.avatarService = new AvatarService(this.apiService, this.stateProvider);
@ -752,6 +760,8 @@ export class ServiceContainer {
this.accountService,
);
this.organizationApiService = new OrganizationApiService(this.apiService, this.syncService);
this.providerApiService = new ProviderApiService(this.apiService);
}
@ -774,7 +784,7 @@ export class ServiceContainer {
await this.stateService.clean();
await this.accountService.clean(userId);
await this.accountService.switchAccount(null);
process.env.BW_SESSION = null;
process.env.BW_SESSION = undefined;
}
async init() {
@ -790,7 +800,7 @@ export class ServiceContainer {
this.twoFactorService.init();
const activeAccount = await firstValueFrom(this.accountService.activeAccount$);
if (activeAccount) {
if (activeAccount?.id) {
await this.userAutoUnlockKeyService.setUserKeyInMemoryIfAutoUserKeySet(activeAccount.id);
}

View File

@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"strictNullChecks": true,
"strictPropertyInitialization": true
}
}

View File

@ -2,7 +2,7 @@ import {
OrganizationAuthRequestService,
OrganizationAuthRequestApiService,
} from "@bitwarden/bit-common/admin-console/auth-requests";
import { ServiceContainer as OssServiceContainer } from "@bitwarden/cli/service-container";
import { ServiceContainer as OssServiceContainer } from "@bitwarden/cli/service-container/service-container";
/**
* Instantiates services and makes them available for dependency injection.

View File

@ -1,4 +1,4 @@
import { map } from "rxjs";
import { Observable, map } from "rxjs";
import {
ActiveUserState,
@ -25,8 +25,8 @@ export class UserDecryptionOptionsService
{
private userDecryptionOptionsState: ActiveUserState<UserDecryptionOptions>;
userDecryptionOptions$;
hasMasterPassword$;
userDecryptionOptions$: Observable<UserDecryptionOptions>;
hasMasterPassword$: Observable<boolean>;
constructor(private stateProvider: StateProvider) {
this.userDecryptionOptionsState = this.stateProvider.getActive(USER_DECRYPTION_OPTIONS);
@ -37,7 +37,7 @@ export class UserDecryptionOptionsService
);
}
userDecryptionOptionsById$(userId: UserId) {
userDecryptionOptionsById$(userId: UserId): Observable<UserDecryptionOptions> {
return this.stateProvider.getUser(userId, USER_DECRYPTION_OPTIONS).state$;
}

View File

@ -16,6 +16,8 @@ export class PolicyApiServiceAbstraction {
organizationUserId: string,
) => Promise<Policy[] | undefined>;
getMasterPasswordPolicyOptsForOrgUser: (orgId: string) => Promise<MasterPasswordPolicyOptions>;
getMasterPasswordPolicyOptsForOrgUser: (
orgId: string,
) => Promise<MasterPasswordPolicyOptions | null>;
putPolicy: (organizationId: string, type: PolicyType, request: PolicyRequest) => Promise<any>;
}

View File

@ -64,8 +64,10 @@ function mapToSingleOrganization(organizationId: string) {
}
export class OrganizationService implements InternalOrganizationServiceAbstraction {
organizations$ = this.getOrganizationsFromState$();
memberOrganizations$ = this.organizations$.pipe(mapToExcludeProviderOrganizations());
organizations$: Observable<Organization[]> = this.getOrganizationsFromState$();
memberOrganizations$: Observable<Organization[]> = this.organizations$.pipe(
mapToExcludeProviderOrganizations(),
);
constructor(private stateProvider: StateProvider) {}

View File

@ -32,7 +32,7 @@ export class PolicyService implements InternalPolicyServiceAbstraction {
private organizationService: OrganizationService,
) {}
get$(policyType: PolicyType) {
get$(policyType: PolicyType): Observable<Policy> {
const filteredPolicies$ = this.activeUserPolicies$.pipe(
map((policies) => policies.filter((p) => p.type === policyType)),
);

View File

@ -72,7 +72,7 @@ export abstract class AccountService {
* Updates the `activeAccount$` observable with the new active account.
* @param userId
*/
abstract switchAccount(userId: UserId): Promise<void>;
abstract switchAccount(userId: UserId | null): Promise<void>;
/**
* Cleans personal information for the given account from the `accounts$` observable. Does not remove the userId from the observable.
*

View File

@ -1,4 +1,11 @@
import { combineLatestWith, map, distinctUntilChanged, shareReplay, combineLatest } from "rxjs";
import {
combineLatestWith,
map,
distinctUntilChanged,
shareReplay,
combineLatest,
Observable,
} from "rxjs";
import {
AccountInfo,
@ -42,11 +49,11 @@ export class AccountServiceImplementation implements InternalAccountService {
private accountsState: GlobalState<Record<UserId, AccountInfo>>;
private activeAccountIdState: GlobalState<UserId | undefined>;
accounts$;
activeAccount$;
accountActivity$;
sortedUserIds$;
nextUpAccount$;
accounts$: Observable<Record<UserId, AccountInfo>>;
activeAccount$: Observable<{ id: UserId | undefined } & AccountInfo>;
accountActivity$: Observable<Record<UserId, Date>>;
sortedUserIds$: Observable<UserId[]>;
nextUpAccount$: Observable<{ id: UserId } & AccountInfo>;
constructor(
private messagingService: MessagingService,
@ -61,7 +68,7 @@ export class AccountServiceImplementation implements InternalAccountService {
);
this.activeAccount$ = this.activeAccountIdState.state$.pipe(
combineLatestWith(this.accounts$),
map(([id, accounts]) => (id ? { id, ...accounts[id] } : undefined)),
map(([id, accounts]) => (id ? { id, ...(accounts[id] as AccountInfo) } : undefined)),
distinctUntilChanged((a, b) => a?.id === b?.id && accountInfoEqual(a, b)),
shareReplay({ bufferSize: 1, refCount: false }),
);
@ -118,7 +125,7 @@ export class AccountServiceImplementation implements InternalAccountService {
await this.removeAccountActivity(userId);
}
async switchAccount(userId: UserId): Promise<void> {
async switchAccount(userId: UserId | null): Promise<void> {
let updateActivity = false;
await this.activeAccountIdState.update(
(_, accounts) => {

View File

@ -5,6 +5,7 @@ import { LogoutReason } from "@bitwarden/auth/common";
import { ApiService } from "../../abstractions/api.service";
import { OrganizationService } from "../../admin-console/abstractions/organization/organization.service.abstraction";
import { OrganizationUserType } from "../../admin-console/enums";
import { Organization } from "../../admin-console/models/domain/organization";
import { KeysRequest } from "../../models/request/keys.request";
import { CryptoService } from "../../platform/abstractions/crypto.service";
import { KeyGenerationService } from "../../platform/abstractions/key-generation.service";
@ -114,7 +115,7 @@ export class KeyConnectorService implements KeyConnectorServiceAbstraction {
}
}
async getManagingOrganization() {
async getManagingOrganization(): Promise<Organization> {
const orgs = await this.organizationService.getAll();
return orgs.find(
(o) =>

View File

@ -888,7 +888,7 @@ export class CryptoService implements CryptoServiceAbstraction {
return this.encryptService.decryptToBytes(encBuffer, key);
}
userKey$(userId: UserId) {
userKey$(userId: UserId): Observable<UserKey> {
return this.stateProvider.getUser(userId, USER_KEY).state$;
}
@ -1013,7 +1013,7 @@ export class CryptoService implements CryptoServiceAbstraction {
);
}
orgKeys$(userId: UserId) {
orgKeys$(userId: UserId): Observable<Record<OrganizationId, OrgKey> | null> {
return this.cipherDecryptionKeys$(userId, true).pipe(map((keys) => keys?.orgKeys));
}

View File

@ -269,7 +269,7 @@ export class DefaultEnvironmentService implements EnvironmentService {
}
}
async getEnvironment(userId?: UserId) {
async getEnvironment(userId?: UserId): Promise<Environment | undefined> {
if (userId == null) {
return await firstValueFrom(this.environment$);
}

View File

@ -129,7 +129,7 @@ export abstract class CipherService implements UserKeyRotationDataProvider<Ciphe
*/
upsert: (cipher: CipherData | CipherData[]) => Promise<Record<CipherId, CipherData>>;
replace: (ciphers: { [id: string]: CipherData }) => Promise<any>;
clear: (userId: string) => Promise<any>;
clear: (userId?: string) => Promise<void>;
moveManyWithServer: (ids: string[], folderId: string) => Promise<any>;
delete: (id: string | string[]) => Promise<any>;
deleteWithServer: (id: string, asAdmin?: boolean) => Promise<any>;

View File

@ -23,6 +23,6 @@ export abstract class CollectionService {
getNested: (id: string) => Promise<TreeNode<CollectionView>>;
upsert: (collection: CollectionData | CollectionData[]) => Promise<any>;
replace: (collections: { [id: string]: CollectionData }) => Promise<any>;
clear: (userId: string) => Promise<any>;
clear: (userId?: string) => Promise<void>;
delete: (id: string | string[]) => Promise<any>;
}

View File

@ -17,7 +17,7 @@ export abstract class FolderService implements UserKeyRotationDataProvider<Folde
clearCache: () => Promise<void>;
encrypt: (model: FolderView, key?: SymmetricCryptoKey) => Promise<Folder>;
get: (id: string) => Promise<Folder>;
getDecrypted$: (id: string) => Observable<FolderView>;
getDecrypted$: (id: string) => Observable<FolderView | undefined>;
getAllFromState: () => Promise<Folder[]>;
/**
* @deprecated Only use in CLI!
@ -46,6 +46,6 @@ export abstract class FolderService implements UserKeyRotationDataProvider<Folde
export abstract class InternalFolderService extends FolderService {
upsert: (folder: FolderData | FolderData[]) => Promise<void>;
replace: (folders: { [id: string]: FolderData }) => Promise<void>;
clear: (userId: string) => Promise<any>;
clear: (userId?: string) => Promise<void>;
delete: (id: string | string[]) => Promise<any>;
}

View File

@ -571,7 +571,7 @@ export class CipherService implements CipherServiceAbstraction {
return this.sortedCiphersCache.getNext(cacheKey);
}
async getNextIdentityCipher() {
async getNextIdentityCipher(): Promise<CipherView> {
const cacheKey = "identityCiphers";
if (!this.sortedCiphersCache.isCached(cacheKey)) {
@ -926,7 +926,7 @@ export class CipherService implements CipherServiceAbstraction {
return updatedCiphers;
}
async clear(userId?: UserId): Promise<any> {
async clear(userId?: UserId): Promise<void> {
userId ??= await firstValueFrom(this.stateProvider.activeUserId$);
await this.clearEncryptedCiphersState(userId);
await this.clearCache(userId);

View File

@ -188,7 +188,7 @@ export class CollectionService implements CollectionServiceAbstraction {
await this.encryptedCollectionDataState.update(() => collections);
}
async clear(userId?: UserId): Promise<any> {
async clear(userId?: UserId): Promise<void> {
if (userId == null) {
await this.encryptedCollectionDataState.update(() => null);
await this.decryptedCollectionDataState.forceValue(null);