From e1d46045e0d62456378df3e6a9cc0d7f6d82f761 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Garc=C3=ADa?= Date: Mon, 7 Oct 2024 10:38:41 +0200 Subject: [PATCH 01/13] Fix IPC proxy selection in prod when using ELECTRON_IS_DEV (#11412) --- apps/desktop/src/main/native-messaging.main.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/desktop/src/main/native-messaging.main.ts b/apps/desktop/src/main/native-messaging.main.ts index ec57ecdf7b..9c9f1ae6a9 100644 --- a/apps/desktop/src/main/native-messaging.main.ts +++ b/apps/desktop/src/main/native-messaging.main.ts @@ -331,7 +331,7 @@ export class NativeMessagingMain { const ext = process.platform === "win32" ? ".exe" : ""; if (isDev()) { - return path.join( + const devPath = path.join( this.appPath, "..", "desktop_native", @@ -339,6 +339,12 @@ export class NativeMessagingMain { "debug", `desktop_proxy${ext}`, ); + + // isDev() returns true when using a production build with ELECTRON_IS_DEV=1, + // so we need to fall back to the prod binary if the dev binary doesn't exist. + if (existsSync(devPath)) { + return devPath; + } } return path.join(path.dirname(this.exePath), `desktop_proxy${ext}`); From 37faccb7e93500330b38950fa02ae264b99c02be Mon Sep 17 00:00:00 2001 From: SmithThe4th Date: Mon, 7 Oct 2024 11:10:48 +0200 Subject: [PATCH 02/13] [PM-11201] Add the ability to sort by Name, Group, and Permission within the collection and item tables (#11370) * Added sorting to vault, name, permission and group Added default sorting * Fixed import * reverted test on template * Only add sorting functionality to admin console * changed code order --- .../vault-items/vault-items.component.html | 31 +++- .../vault-items/vault-items.component.ts | 143 +++++++++++++++++- 2 files changed, 168 insertions(+), 6 deletions(-) diff --git a/apps/web/src/app/vault/components/vault-items/vault-items.component.html b/apps/web/src/app/vault/components/vault-items/vault-items.component.html index 99516907bb..55fa4bcb4e 100644 --- a/apps/web/src/app/vault/components/vault-items/vault-items.component.html +++ b/apps/web/src/app/vault/components/vault-items/vault-items.component.html @@ -16,13 +16,38 @@ "all" | i18n }} - {{ "name" | i18n }} + + + {{ "name" | i18n }} + + + + {{ "name" | i18n }} + {{ "owner" | i18n }} {{ "collections" | i18n }} - {{ "groups" | i18n }} - + + {{ "groups" | i18n }} + + {{ "permission" | i18n }} diff --git a/apps/web/src/app/vault/components/vault-items/vault-items.component.ts b/apps/web/src/app/vault/components/vault-items/vault-items.component.ts index 404a1affbd..44e38073c9 100644 --- a/apps/web/src/app/vault/components/vault-items/vault-items.component.ts +++ b/apps/web/src/app/vault/components/vault-items/vault-items.component.ts @@ -1,14 +1,19 @@ import { SelectionModel } from "@angular/cdk/collections"; -import { Component, EventEmitter, Input, Output } from "@angular/core"; +import { Component, EventEmitter, inject, Input, Output } from "@angular/core"; -import { Unassigned } from "@bitwarden/admin-console/common"; +import { CollectionAdminView, Unassigned } from "@bitwarden/admin-console/common"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; +import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { CollectionView } from "@bitwarden/common/vault/models/view/collection.view"; import { TableDataSource } from "@bitwarden/components"; import { GroupView } from "../../../admin-console/organizations/core"; +import { + CollectionPermission, + convertToPermission, +} from "./../../../admin-console/organizations/shared/components/access-selector/access-selector.models"; import { VaultItem } from "./vault-item"; import { VaultItemEvent } from "./vault-item-event"; @@ -25,6 +30,7 @@ const MaxSelectionCount = 500; // changeDetection: ChangeDetectionStrategy.OnPush, }) export class VaultItemsComponent { + protected i18nService = inject(I18nService); protected RowHeight = RowHeight; @Input() disabled: boolean; @@ -197,7 +203,7 @@ export class VaultItemsComponent { private refreshItems() { const collections: VaultItem[] = this.collections.map((collection) => ({ collection })); const ciphers: VaultItem[] = this.ciphers.map((cipher) => ({ cipher })); - const items: VaultItem[] = [].concat(collections).concat(ciphers); + let items: VaultItem[] = [].concat(collections).concat(ciphers); this.selection.clear(); @@ -208,6 +214,11 @@ export class VaultItemsComponent { (item.collection !== undefined && item.collection.id !== Unassigned), ); + // Apply sorting only for organization vault + if (this.showAdminActions) { + items = items.sort(this.sortByGroups); + } + this.dataSource.data = items; } @@ -293,6 +304,112 @@ export class VaultItemsComponent { return false; } + /** + * Sorts VaultItems, grouping collections before ciphers, and sorting each group alphabetically by name. + */ + protected sortByName = (a: VaultItem, b: VaultItem) => { + const getName = (item: VaultItem) => item.collection?.name || item.cipher?.name; + + // First, sort collections before ciphers + if (a.collection && !b.collection) { + return -1; + } + if (!a.collection && b.collection) { + return 1; + } + + return getName(a).localeCompare(getName(b)); + }; + + /** + * Sorts VaultItems based on group names + */ + protected sortByGroups = (a: VaultItem, b: VaultItem): number => { + const getGroupNames = (item: VaultItem): string => { + if (item.collection instanceof CollectionAdminView) { + return item.collection.groups + .map((group) => this.getGroupName(group.id)) + .filter(Boolean) + .join(","); + } + + return ""; + }; + + const aGroupNames = getGroupNames(a); + const bGroupNames = getGroupNames(b); + + if (aGroupNames.length !== bGroupNames.length) { + return bGroupNames.length - aGroupNames.length; + } + + return aGroupNames.localeCompare(bGroupNames); + }; + + /** + * Sorts VaultItems based on their permissions, with higher permissions taking precedence. + * If permissions are equal, it falls back to sorting by name. + */ + protected sortByPermissions = (a: VaultItem, b: VaultItem): number => { + const getPermissionPriority = (item: VaultItem): number => { + if (item.collection instanceof CollectionAdminView) { + const permission = this.getCollectionPermission(item.collection); + + switch (permission) { + case CollectionPermission.Manage: + return 5; + case CollectionPermission.Edit: + return 4; + case CollectionPermission.EditExceptPass: + return 3; + case CollectionPermission.View: + return 2; + case CollectionPermission.ViewExceptPass: + return 1; + case "NoAccess": + return 0; + } + } + + return -1; + }; + + const priorityA = getPermissionPriority(a); + const priorityB = getPermissionPriority(b); + + // Higher priority first + if (priorityA !== priorityB) { + return priorityB - priorityA; + } + + return this.sortByName(a, b); + }; + + /** + * Default sorting function for vault items. + * Sorts by: 1. Collections before ciphers + * 2. Highest permission first + * 3. Alphabetical order of collections and ciphers + */ + private defaultSort = (a: VaultItem, b: VaultItem) => { + // First, sort collections before ciphers + if (a.collection && !b.collection) { + return -1; + } + if (!a.collection && b.collection) { + return 1; + } + + // Next, sort by permissions + const permissionSort = this.sortByPermissions(a, b); + if (permissionSort !== 0) { + return permissionSort; + } + + // Finally, sort by name + return this.sortByName(a, b); + }; + private hasPersonalItems(): boolean { return this.selection.selected.some(({ cipher }) => cipher?.organizationId === null); } @@ -306,4 +423,24 @@ export class VaultItemsComponent { private getUniqueOrganizationIds(): Set { return new Set(this.selection.selected.flatMap((i) => i.cipher?.organizationId ?? [])); } + + private getGroupName(groupId: string): string | undefined { + return this.allGroups.find((g) => g.id === groupId)?.name; + } + + private getCollectionPermission( + collection: CollectionAdminView, + ): CollectionPermission | "NoAccess" { + const organization = this.allOrganizations.find((o) => o.id === collection.organizationId); + + if (collection.id == Unassigned && organization?.canEditUnassignedCiphers) { + return CollectionPermission.Edit; + } + + if (collection.assigned) { + return convertToPermission(collection); + } + + return "NoAccess"; + } } From c88c5bf1ef2a983f0a8c5589c2d5d83fec85b67d Mon Sep 17 00:00:00 2001 From: Oscar Hinton Date: Mon, 7 Oct 2024 13:20:50 +0200 Subject: [PATCH 03/13] [PM-11766] Introduce SDK client (#10974) Integrate the SDK into our other clients. --- apps/browser/config/base.json | 3 +- .../browser/src/background/main.background.ts | 15 +++ apps/browser/src/manifest.v3.json | 3 +- .../sdk/browser-sdk-client-factory.ts | 37 ++++++++ .../src/platform/services/sdk/fallback.ts | 8 ++ .../browser/src/platform/services/sdk/wasm.ts | 8 ++ .../src/popup/services/services.module.ts | 9 ++ apps/browser/webpack.config.js | 14 ++- apps/cli/config/base.json | 5 + apps/cli/config/config.js | 24 ++++- apps/cli/jest.config.js | 10 +- .../service-container/service-container.ts | 16 ++++ apps/cli/tsconfig.json | 2 +- apps/cli/webpack.config.js | 5 + apps/desktop/config/base.json | 6 +- .../src/app/services/services.module.ts | 9 ++ apps/desktop/src/index.html | 2 +- apps/desktop/webpack.renderer.js | 8 +- apps/web/config/base.json | 6 +- apps/web/jest.config.js | 22 +++-- apps/web/src/app/core/core.module.ts | 9 ++ .../app/platform/web-sdk-client-factory.ts | 42 ++++++++ apps/web/webpack.config.js | 8 +- bitwarden_license/bit-cli/jest.config.js | 10 +- bitwarden_license/bit-cli/tsconfig.json | 2 +- .../src/services/jslib-services.module.ts | 8 ++ libs/common/spec/jest-sdk-client-factory.ts | 9 ++ .../abstractions/sdk/sdk-client-factory.ts | 10 ++ .../platform/abstractions/sdk/sdk.service.ts | 8 ++ libs/common/src/platform/misc/flags.ts | 3 +- .../sdk/default-sdk-client-factory.ts | 19 ++++ .../services/sdk/default-sdk.service.ts | 95 +++++++++++++++++++ .../services/sdk/noop-sdk-client-factory.ts | 16 ++++ package-lock.json | 6 ++ package.json | 1 + 35 files changed, 424 insertions(+), 34 deletions(-) create mode 100644 apps/browser/src/platform/services/sdk/browser-sdk-client-factory.ts create mode 100644 apps/browser/src/platform/services/sdk/fallback.ts create mode 100644 apps/browser/src/platform/services/sdk/wasm.ts create mode 100644 apps/cli/config/base.json create mode 100644 apps/web/src/app/platform/web-sdk-client-factory.ts create mode 100644 libs/common/spec/jest-sdk-client-factory.ts create mode 100644 libs/common/src/platform/abstractions/sdk/sdk-client-factory.ts create mode 100644 libs/common/src/platform/abstractions/sdk/sdk.service.ts create mode 100644 libs/common/src/platform/services/sdk/default-sdk-client-factory.ts create mode 100644 libs/common/src/platform/services/sdk/default-sdk.service.ts create mode 100644 libs/common/src/platform/services/sdk/noop-sdk-client-factory.ts diff --git a/apps/browser/config/base.json b/apps/browser/config/base.json index 5113cd7d1b..9506bda0f0 100644 --- a/apps/browser/config/base.json +++ b/apps/browser/config/base.json @@ -2,6 +2,7 @@ "devFlags": {}, "flags": { "showPasswordless": true, - "accountSwitching": false + "accountSwitching": false, + "sdk": false } } diff --git a/apps/browser/src/background/main.background.ts b/apps/browser/src/background/main.background.ts index d3da7ba0ba..5875490ff0 100644 --- a/apps/browser/src/background/main.background.ts +++ b/apps/browser/src/background/main.background.ts @@ -90,6 +90,7 @@ import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/platfor import { KeyGenerationService as KeyGenerationServiceAbstraction } from "@bitwarden/common/platform/abstractions/key-generation.service"; import { LogService as LogServiceAbstraction } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from "@bitwarden/common/platform/abstractions/platform-utils.service"; +import { SdkService } from "@bitwarden/common/platform/abstractions/sdk/sdk.service"; import { StateService as StateServiceAbstraction } from "@bitwarden/common/platform/abstractions/state.service"; import { AbstractStorageService, @@ -122,6 +123,8 @@ import { FileUploadService } from "@bitwarden/common/platform/services/file-uplo import { KeyGenerationService } from "@bitwarden/common/platform/services/key-generation.service"; import { MigrationBuilderService } from "@bitwarden/common/platform/services/migration-builder.service"; import { MigrationRunner } from "@bitwarden/common/platform/services/migration-runner"; +import { DefaultSdkService } from "@bitwarden/common/platform/services/sdk/default-sdk.service"; +import { NoopSdkClientFactory } from "@bitwarden/common/platform/services/sdk/noop-sdk-client-factory"; import { StateService } from "@bitwarden/common/platform/services/state.service"; import { SystemService } from "@bitwarden/common/platform/services/system.service"; import { UserAutoUnlockKeyService } from "@bitwarden/common/platform/services/user-auto-unlock-key.service"; @@ -228,6 +231,7 @@ import AutofillService from "../autofill/services/autofill.service"; import { SafariApp } from "../browser/safariApp"; import { BackgroundBrowserBiometricsService } from "../key-management/biometrics/background-browser-biometrics.service"; import { BrowserApi } from "../platform/browser/browser-api"; +import { flagEnabled } from "../platform/flags"; import { UpdateBadge } from "../platform/listeners/update-badge"; /* eslint-disable no-restricted-imports */ import { ChromeMessageSender } from "../platform/messaging/chrome-message.sender"; @@ -245,6 +249,7 @@ import { LocalBackedSessionStorageService } from "../platform/services/local-bac import { BackgroundPlatformUtilsService } from "../platform/services/platform-utils/background-platform-utils.service"; import { BrowserPlatformUtilsService } from "../platform/services/platform-utils/browser-platform-utils.service"; import { PopupViewCacheBackgroundService } from "../platform/services/popup-view-cache-background.service"; +import { BrowserSdkClientFactory } from "../platform/services/sdk/browser-sdk-client-factory"; import { BackgroundTaskSchedulerService } from "../platform/services/task-scheduler/background-task-scheduler.service"; import { ForegroundTaskSchedulerService } from "../platform/services/task-scheduler/foreground-task-scheduler.service"; import { BackgroundMemoryStorageService } from "../platform/storage/background-memory-storage.service"; @@ -364,6 +369,7 @@ export default class MainBackground { syncServiceListener: SyncServiceListener; themeStateService: DefaultThemeStateService; autoSubmitLoginBackground: AutoSubmitLoginBackground; + sdkService: SdkService; onUpdatedRan: boolean; onReplacedRan: boolean; @@ -719,6 +725,15 @@ export default class MainBackground { this.stateProvider, ); + const sdkClientFactory = flagEnabled("sdk") + ? new BrowserSdkClientFactory() + : new NoopSdkClientFactory(); + this.sdkService = new DefaultSdkService( + sdkClientFactory, + this.environmentService, + this.platformUtilsService, + ); + this.passwordStrengthService = new PasswordStrengthService(); this.passwordGenerationService = legacyPasswordGenerationServiceFactory( diff --git a/apps/browser/src/manifest.v3.json b/apps/browser/src/manifest.v3.json index 5413ee5b63..762e5e01f8 100644 --- a/apps/browser/src/manifest.v3.json +++ b/apps/browser/src/manifest.v3.json @@ -39,8 +39,7 @@ } ], "background": { - "service_worker": "background.js", - "type": "module" + "service_worker": "background.js" }, "action": { "default_icon": { diff --git a/apps/browser/src/platform/services/sdk/browser-sdk-client-factory.ts b/apps/browser/src/platform/services/sdk/browser-sdk-client-factory.ts new file mode 100644 index 0000000000..2293a3b384 --- /dev/null +++ b/apps/browser/src/platform/services/sdk/browser-sdk-client-factory.ts @@ -0,0 +1,37 @@ +import { SdkClientFactory } from "@bitwarden/common/platform/abstractions/sdk/sdk-client-factory"; +import type { BitwardenClient } from "@bitwarden/sdk-internal"; + +// https://stackoverflow.com/a/47880734 +const supported = (() => { + try { + if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") { + const module = new WebAssembly.Module( + Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00), + ); + if (module instanceof WebAssembly.Module) { + return new WebAssembly.Instance(module) instanceof WebAssembly.Instance; + } + } + } catch (e) { + // ignore + } + return false; +})(); + +if (supported) { + // eslint-disable-next-line no-console + console.debug("WebAssembly is supported in this environment"); + import("./wasm"); +} else { + // eslint-disable-next-line no-console + console.debug("WebAssembly is not supported in this environment"); + import("./fallback"); +} + +export class BrowserSdkClientFactory implements SdkClientFactory { + async createSdkClient( + ...args: ConstructorParameters + ): Promise { + return Promise.resolve((globalThis as any).init_sdk(...args)); + } +} diff --git a/apps/browser/src/platform/services/sdk/fallback.ts b/apps/browser/src/platform/services/sdk/fallback.ts new file mode 100644 index 0000000000..82d292fc9e --- /dev/null +++ b/apps/browser/src/platform/services/sdk/fallback.ts @@ -0,0 +1,8 @@ +import * as sdk from "@bitwarden/sdk-internal"; +import * as wasm from "@bitwarden/sdk-internal/bitwarden_wasm_internal_bg.wasm.js"; + +(globalThis as any).init_sdk = (...args: ConstructorParameters) => { + (sdk as any).init(wasm); + + return new sdk.BitwardenClient(...args); +}; diff --git a/apps/browser/src/platform/services/sdk/wasm.ts b/apps/browser/src/platform/services/sdk/wasm.ts new file mode 100644 index 0000000000..1977a171e2 --- /dev/null +++ b/apps/browser/src/platform/services/sdk/wasm.ts @@ -0,0 +1,8 @@ +import * as sdk from "@bitwarden/sdk-internal"; +import * as wasm from "@bitwarden/sdk-internal/bitwarden_wasm_internal_bg.wasm"; + +(globalThis as any).init_sdk = (...args: ConstructorParameters) => { + (sdk as any).init(wasm); + + return new sdk.BitwardenClient(...args); +}; diff --git a/apps/browser/src/popup/services/services.module.ts b/apps/browser/src/popup/services/services.module.ts index 411eed380d..65bcd81072 100644 --- a/apps/browser/src/popup/services/services.module.ts +++ b/apps/browser/src/popup/services/services.module.ts @@ -58,6 +58,7 @@ import { KeyGenerationService } from "@bitwarden/common/platform/abstractions/ke import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService as MessagingServiceAbstraction } from "@bitwarden/common/platform/abstractions/messaging.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; +import { SdkClientFactory } from "@bitwarden/common/platform/abstractions/sdk/sdk-client-factory"; import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { AbstractStorageService, @@ -66,9 +67,11 @@ import { import { Message, MessageListener, MessageSender } from "@bitwarden/common/platform/messaging"; // eslint-disable-next-line no-restricted-imports -- Used for dependency injection import { SubjectMessageSender } from "@bitwarden/common/platform/messaging/internal"; +import { flagEnabled } from "@bitwarden/common/platform/misc/flags"; import { TaskSchedulerService } from "@bitwarden/common/platform/scheduling"; import { ConsoleLogService } from "@bitwarden/common/platform/services/console-log.service"; import { ContainerService } from "@bitwarden/common/platform/services/container.service"; +import { NoopSdkClientFactory } from "@bitwarden/common/platform/services/sdk/noop-sdk-client-factory"; import { StorageServiceProvider } from "@bitwarden/common/platform/services/storage-service.provider"; import { WebCryptoFunctionService } from "@bitwarden/common/platform/services/web-crypto-function.service"; import { @@ -114,6 +117,7 @@ import BrowserLocalStorageService from "../../platform/services/browser-local-st import { BrowserScriptInjectorService } from "../../platform/services/browser-script-injector.service"; import I18nService from "../../platform/services/i18n.service"; import { ForegroundPlatformUtilsService } from "../../platform/services/platform-utils/foreground-platform-utils.service"; +import { BrowserSdkClientFactory } from "../../platform/services/sdk/browser-sdk-client-factory"; import { ForegroundTaskSchedulerService } from "../../platform/services/task-scheduler/foreground-task-scheduler.service"; import { BrowserStorageServiceProvider } from "../../platform/storage/browser-storage-service.provider"; import { ForegroundMemoryStorageService } from "../../platform/storage/foreground-memory-storage.service"; @@ -572,6 +576,11 @@ const safeProviders: SafeProvider[] = [ useClass: ForegroundLockService, deps: [MessageSender, MessageListener], }), + safeProvider({ + provide: SdkClientFactory, + useClass: flagEnabled("sdk") ? BrowserSdkClientFactory : NoopSdkClientFactory, + deps: [], + }), ]; @NgModule({ diff --git a/apps/browser/webpack.config.js b/apps/browser/webpack.config.js index 7ac5a635b1..4309defd3a 100644 --- a/apps/browser/webpack.config.js +++ b/apps/browser/webpack.config.js @@ -122,7 +122,7 @@ const moduleRules = [ loader: "@ngtools/webpack", }, { - test: /\.wasm$/, + test: /argon2(-simd)?\.wasm$/, loader: "base64-loader", type: "javascript/auto", }, @@ -320,9 +320,12 @@ const mainConfig = { clean: true, }, module: { - noParse: /\.wasm$/, + noParse: /argon2(-simd)?\.wasm$/, rules: moduleRules, }, + experiments: { + asyncWebAssembly: true, + }, plugins: plugins, }; @@ -395,12 +398,15 @@ if (manifestVersion == 2) { loader: "ts-loader", }, { - test: /\.wasm$/, + test: /argon2(-simd)?\.wasm$/, loader: "base64-loader", type: "javascript/auto", }, ], - noParse: /\.wasm$/, + noParse: /argon2(-simd)?\.wasm$/, + }, + experiments: { + asyncWebAssembly: true, }, resolve: { extensions: [".ts", ".js"], diff --git a/apps/cli/config/base.json b/apps/cli/config/base.json new file mode 100644 index 0000000000..67f2323e94 --- /dev/null +++ b/apps/cli/config/base.json @@ -0,0 +1,5 @@ +{ + "flags": { + "sdk": false + } +} diff --git a/apps/cli/config/config.js b/apps/cli/config/config.js index 81e2d619fe..cff42ecf62 100644 --- a/apps/cli/config/config.js +++ b/apps/cli/config/config.js @@ -1,7 +1,27 @@ function load(envName) { + const base = require("./base.json"); + const env = loadConfig(envName); + const local = loadConfig("local"); + return { - ...loadConfig(envName), - ...loadConfig("local"), + ...base, + ...env, + ...local, + dev: { + ...base.dev, + ...env.dev, + ...local.dev, + }, + flags: { + ...base.flags, + ...env.flags, + ...local.flags, + }, + devFlags: { + ...base.devFlags, + ...env.devFlags, + ...local.devFlags, + }, }; } diff --git a/apps/cli/jest.config.js b/apps/cli/jest.config.js index 8765ccc8e4..e0a5b9ec9c 100644 --- a/apps/cli/jest.config.js +++ b/apps/cli/jest.config.js @@ -10,7 +10,11 @@ module.exports = { preset: "ts-jest", testEnvironment: "node", setupFilesAfterEnv: ["/test.setup.ts"], - moduleNameMapper: pathsToModuleNameMapper(compilerOptions?.paths || {}, { - prefix: "/", - }), + moduleNameMapper: { + "@bitwarden/common/platform/services/sdk/default-sdk-client-factory": + "/../../libs/common/spec/jest-sdk-client-factory", + ...pathsToModuleNameMapper(compilerOptions?.paths || {}, { + prefix: "/", + }), + }, }; diff --git a/apps/cli/src/service-container/service-container.ts b/apps/cli/src/service-container/service-container.ts index 280891edf3..95aa5f98b0 100644 --- a/apps/cli/src/service-container/service-container.ts +++ b/apps/cli/src/service-container/service-container.ts @@ -64,6 +64,7 @@ import { RegionConfig, } from "@bitwarden/common/platform/abstractions/environment.service"; import { KeyGenerationService as KeyGenerationServiceAbstraction } from "@bitwarden/common/platform/abstractions/key-generation.service"; +import { SdkService } from "@bitwarden/common/platform/abstractions/sdk/sdk.service"; import { KeySuffixOptions, LogLevelType } from "@bitwarden/common/platform/enums"; import { StateFactory } from "@bitwarden/common/platform/factories/state-factory"; import { MessageSender } from "@bitwarden/common/platform/messaging"; @@ -86,6 +87,9 @@ import { KeyGenerationService } from "@bitwarden/common/platform/services/key-ge import { MemoryStorageService } from "@bitwarden/common/platform/services/memory-storage.service"; import { MigrationBuilderService } from "@bitwarden/common/platform/services/migration-builder.service"; import { MigrationRunner } from "@bitwarden/common/platform/services/migration-runner"; +import { DefaultSdkClientFactory } from "@bitwarden/common/platform/services/sdk/default-sdk-client-factory"; +import { DefaultSdkService } from "@bitwarden/common/platform/services/sdk/default-sdk.service"; +import { NoopSdkClientFactory } from "@bitwarden/common/platform/services/sdk/noop-sdk-client-factory"; import { StateService } from "@bitwarden/common/platform/services/state.service"; import { StorageServiceProvider } from "@bitwarden/common/platform/services/storage-service.provider"; import { UserAutoUnlockKeyService } from "@bitwarden/common/platform/services/user-auto-unlock-key.service"; @@ -151,6 +155,7 @@ import { VaultExportServiceAbstraction, } from "@bitwarden/vault-export-core"; +import { flagEnabled } from "../platform/flags"; import { CliPlatformUtilsService } from "../platform/services/cli-platform-utils.service"; import { ConsoleLogService } from "../platform/services/console-log.service"; import { I18nService } from "../platform/services/i18n.service"; @@ -249,6 +254,7 @@ export class ServiceContainer { userAutoUnlockKeyService: UserAutoUnlockKeyService; kdfConfigService: KdfConfigServiceAbstraction; taskSchedulerService: TaskSchedulerService; + sdkService: SdkService; constructor() { let p = null; @@ -522,6 +528,16 @@ export class ServiceContainer { this.globalStateProvider, ); + const sdkClientFactory = flagEnabled("sdk") + ? new DefaultSdkClientFactory() + : new NoopSdkClientFactory(); + this.sdkService = new DefaultSdkService( + sdkClientFactory, + this.environmentService, + this.platformUtilsService, + customUserAgent, + ); + this.passwordStrengthService = new PasswordStrengthService(); this.passwordGenerationService = legacyPasswordGenerationServiceFactory( diff --git a/apps/cli/tsconfig.json b/apps/cli/tsconfig.json index eedf24179d..4cb450f9c6 100644 --- a/apps/cli/tsconfig.json +++ b/apps/cli/tsconfig.json @@ -3,7 +3,7 @@ "pretty": true, "moduleResolution": "node", "target": "ES2016", - "module": "es6", + "module": "ES2020", "noImplicitAny": true, "allowSyntheticDefaultImports": true, "emitDecoratorMetadata": true, diff --git a/apps/cli/webpack.config.js b/apps/cli/webpack.config.js index 2b9c53bac6..d5f66af73e 100644 --- a/apps/cli/webpack.config.js +++ b/apps/cli/webpack.config.js @@ -37,8 +37,10 @@ const plugins = [ contextRegExp: /node-fetch/, }), new webpack.EnvironmentPlugin({ + ENV: ENV, BWCLI_ENV: ENV, FLAGS: envConfig.flags, + DEV_FLAGS: envConfig.devFlags, }), new webpack.IgnorePlugin({ resourceRegExp: /canvas/, @@ -79,6 +81,9 @@ const webpackConfig = { allowlist: [/@bitwarden/], }), ], + experiments: { + asyncWebAssembly: true, + }, }; module.exports = webpackConfig; diff --git a/apps/desktop/config/base.json b/apps/desktop/config/base.json index 3c93018e65..5efcbc629c 100644 --- a/apps/desktop/config/base.json +++ b/apps/desktop/config/base.json @@ -1,4 +1,6 @@ { - "devFlags": {}, - "flags": {} + "flags": { + "sdk": false + }, + "devFlags": {} } diff --git a/apps/desktop/src/app/services/services.module.ts b/apps/desktop/src/app/services/services.module.ts index c6b73fbbbc..c9b434aa96 100644 --- a/apps/desktop/src/app/services/services.module.ts +++ b/apps/desktop/src/app/services/services.module.ts @@ -52,6 +52,7 @@ import { } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService as MessagingServiceAbstraction } from "@bitwarden/common/platform/abstractions/messaging.service"; import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from "@bitwarden/common/platform/abstractions/platform-utils.service"; +import { SdkClientFactory } from "@bitwarden/common/platform/abstractions/sdk/sdk-client-factory"; import { StateService as StateServiceAbstraction } from "@bitwarden/common/platform/abstractions/state.service"; import { AbstractStorageService } from "@bitwarden/common/platform/abstractions/storage.service"; import { SystemService as SystemServiceAbstraction } from "@bitwarden/common/platform/abstractions/system.service"; @@ -60,6 +61,8 @@ import { Message, MessageListener, MessageSender } from "@bitwarden/common/platf import { SubjectMessageSender } from "@bitwarden/common/platform/messaging/internal"; import { TaskSchedulerService } from "@bitwarden/common/platform/scheduling"; import { MemoryStorageService } from "@bitwarden/common/platform/services/memory-storage.service"; +import { DefaultSdkClientFactory } from "@bitwarden/common/platform/services/sdk/default-sdk-client-factory"; +import { NoopSdkClientFactory } from "@bitwarden/common/platform/services/sdk/noop-sdk-client-factory"; import { SystemService } from "@bitwarden/common/platform/services/system.service"; import { GlobalStateProvider, StateProvider } from "@bitwarden/common/platform/state"; // eslint-disable-next-line import/no-restricted-paths -- Implementation for memory storage @@ -73,6 +76,7 @@ import { BiometricStateService, BiometricsService } from "@bitwarden/key-managem import { DesktopAutofillSettingsService } from "../../autofill/services/desktop-autofill-settings.service"; import { ElectronBiometricsService } from "../../key-management/biometrics/electron-biometrics.service"; +import { flagEnabled } from "../../platform/flags"; import { DesktopSettingsService } from "../../platform/services/desktop-settings.service"; import { ElectronCryptoService } from "../../platform/services/electron-crypto.service"; import { ElectronLogRendererService } from "../../platform/services/electron-log.renderer.service"; @@ -302,6 +306,11 @@ const safeProviders: SafeProvider[] = [ InternalUserDecryptionOptionsServiceAbstraction, ], }), + safeProvider({ + provide: SdkClientFactory, + useClass: flagEnabled("sdk") ? DefaultSdkClientFactory : NoopSdkClientFactory, + deps: [], + }), ]; @NgModule({ diff --git a/apps/desktop/src/index.html b/apps/desktop/src/index.html index 6bac674bb5..37eb64adf3 100644 --- a/apps/desktop/src/index.html +++ b/apps/desktop/src/index.html @@ -4,7 +4,7 @@ diff --git a/apps/desktop/webpack.renderer.js b/apps/desktop/webpack.renderer.js index dc3cdf1fef..ac990689ae 100644 --- a/apps/desktop/webpack.renderer.js +++ b/apps/desktop/webpack.renderer.js @@ -42,7 +42,7 @@ const common = { type: "asset/resource", }, { - test: /\.wasm$/, + test: /argon2(-simd)?\.wasm$/, loader: "base64-loader", type: "javascript/auto", }, @@ -143,11 +143,15 @@ const renderer = { parser: { system: true }, }, { - test: /\.wasm$/, + test: /argon2(-simd)?\.wasm$/, loader: "base64-loader", type: "javascript/auto", }, ], + noParse: /argon2(-simd)?\.wasm$/, + }, + experiments: { + asyncWebAssembly: true, }, plugins: [ new AngularWebpackPlugin({ diff --git a/apps/web/config/base.json b/apps/web/config/base.json index 8eb8a31133..98f91360bc 100644 --- a/apps/web/config/base.json +++ b/apps/web/config/base.json @@ -11,6 +11,8 @@ "allowedHosts": "auto" }, "flags": { - "showPasswordless": false - } + "showPasswordless": false, + "sdk": false + }, + "devFlags": {} } diff --git a/apps/web/jest.config.js b/apps/web/jest.config.js index f121823ade..9b5d6fdc76 100644 --- a/apps/web/jest.config.js +++ b/apps/web/jest.config.js @@ -9,11 +9,19 @@ module.exports = { ...sharedConfig, preset: "jest-preset-angular", setupFilesAfterEnv: ["/test.setup.ts"], - moduleNameMapper: pathsToModuleNameMapper( - // lets us use @bitwarden/common/spec in web tests - { "@bitwarden/common/spec": ["../../libs/common/spec"], ...(compilerOptions?.paths ?? {}) }, - { - prefix: "/", - }, - ), + moduleNameMapper: { + // Replace ESM SDK with Node compatible SDK + "@bitwarden/common/platform/services/sdk/default-sdk-client-factory": + "/../../libs/common/spec/jest-sdk-client-factory", + ...pathsToModuleNameMapper( + { + // lets us use @bitwarden/common/spec in web tests + "@bitwarden/common/spec": ["../../libs/common/spec"], + ...(compilerOptions?.paths ?? {}), + }, + { + prefix: "/", + }, + ), + }, }; diff --git a/apps/web/src/app/core/core.module.ts b/apps/web/src/app/core/core.module.ts index ceff268217..217b228d32 100644 --- a/apps/web/src/app/core/core.module.ts +++ b/apps/web/src/app/core/core.module.ts @@ -51,6 +51,7 @@ import { FileDownloadService } from "@bitwarden/common/platform/abstractions/fil import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from "@bitwarden/common/platform/abstractions/platform-utils.service"; +import { SdkClientFactory } from "@bitwarden/common/platform/abstractions/sdk/sdk-client-factory"; import { AbstractStorageService } from "@bitwarden/common/platform/abstractions/storage.service"; import { ThemeType } from "@bitwarden/common/platform/enums"; import { AppIdService as DefaultAppIdService } from "@bitwarden/common/platform/services/app-id.service"; @@ -58,6 +59,7 @@ import { MemoryStorageService } from "@bitwarden/common/platform/services/memory // eslint-disable-next-line import/no-restricted-paths -- Implementation for memory storage import { MigrationBuilderService } from "@bitwarden/common/platform/services/migration-builder.service"; import { MigrationRunner } from "@bitwarden/common/platform/services/migration-runner"; +import { NoopSdkClientFactory } from "@bitwarden/common/platform/services/sdk/noop-sdk-client-factory"; import { StorageServiceProvider } from "@bitwarden/common/platform/services/storage-service.provider"; /* eslint-disable import/no-restricted-paths -- Implementation for memory storage */ import { GlobalStateProvider, StateProvider } from "@bitwarden/common/platform/state"; @@ -72,6 +74,7 @@ import { VaultTimeout, VaultTimeoutStringType } from "@bitwarden/common/types/va import { CollectionService } from "@bitwarden/common/vault/abstractions/collection.service"; import { BiometricsService } from "@bitwarden/key-management"; +import { flagEnabled } from "../../utils/flags"; import { PolicyListService } from "../admin-console/core/policy-list.service"; import { WebSetPasswordJitService, @@ -84,6 +87,7 @@ import { I18nService } from "../core/i18n.service"; import { WebBiometricsService } from "../key-management/web-biometric.service"; import { WebEnvironmentService } from "../platform/web-environment.service"; import { WebMigrationRunner } from "../platform/web-migration-runner"; +import { WebSdkClientFactory } from "../platform/web-sdk-client-factory"; import { WebStorageServiceProvider } from "../platform/web-storage-service.provider"; import { EventService } from "./event.service"; @@ -245,6 +249,11 @@ const safeProviders: SafeProvider[] = [ useClass: DefaultCollectionAdminService, deps: [ApiService, CryptoServiceAbstraction, EncryptService, CollectionService], }), + safeProvider({ + provide: SdkClientFactory, + useClass: flagEnabled("sdk") ? WebSdkClientFactory : NoopSdkClientFactory, + deps: [], + }), ]; @NgModule({ diff --git a/apps/web/src/app/platform/web-sdk-client-factory.ts b/apps/web/src/app/platform/web-sdk-client-factory.ts new file mode 100644 index 0000000000..2ebb2bcc10 --- /dev/null +++ b/apps/web/src/app/platform/web-sdk-client-factory.ts @@ -0,0 +1,42 @@ +import { SdkClientFactory } from "@bitwarden/common/platform/abstractions/sdk/sdk-client-factory"; +import * as sdk from "@bitwarden/sdk-internal"; + +/** + * SDK client factory with a js fallback for when WASM is not supported. + */ +export class WebSdkClientFactory implements SdkClientFactory { + async createSdkClient( + ...args: ConstructorParameters + ): Promise { + const module = await load(); + + (sdk as any).init(module); + + return Promise.resolve(new sdk.BitwardenClient(...args)); + } +} + +// https://stackoverflow.com/a/47880734 +const supported = (() => { + try { + if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") { + const module = new WebAssembly.Module( + Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00), + ); + if (module instanceof WebAssembly.Module) { + return new WebAssembly.Instance(module) instanceof WebAssembly.Instance; + } + } + } catch (e) { + // ignore + } + return false; +})(); + +async function load() { + if (supported) { + return await import("@bitwarden/sdk-internal/bitwarden_wasm_internal_bg.wasm"); + } else { + return await import("@bitwarden/sdk-internal/bitwarden_wasm_internal_bg.wasm.js"); + } +} diff --git a/apps/web/webpack.config.js b/apps/web/webpack.config.js index fee60264ea..df325015aa 100644 --- a/apps/web/webpack.config.js +++ b/apps/web/webpack.config.js @@ -78,7 +78,7 @@ const moduleRules = [ loader: "@ngtools/webpack", }, { - test: /\.wasm$/, + test: /argon2(-simd)?\.wasm$/, loader: "base64-loader", type: "javascript/auto", }, @@ -324,6 +324,7 @@ const webpackConfig = { mode: NODE_ENV, devtool: "source-map", devServer: devServer, + target: "web", entry: { "app/polyfills": "./src/polyfills.ts", "app/main": "./src/main.ts", @@ -383,9 +384,12 @@ const webpackConfig = { clean: true, }, module: { - noParse: /\.wasm$/, + noParse: /argon2(-simd)?\.wasm$/, rules: moduleRules, }, + experiments: { + asyncWebAssembly: true, + }, plugins: plugins, }; diff --git a/bitwarden_license/bit-cli/jest.config.js b/bitwarden_license/bit-cli/jest.config.js index 92be98cc56..30c9784c32 100644 --- a/bitwarden_license/bit-cli/jest.config.js +++ b/bitwarden_license/bit-cli/jest.config.js @@ -10,7 +10,11 @@ module.exports = { preset: "ts-jest", testEnvironment: "node", setupFilesAfterEnv: ["/../../apps/cli/test.setup.ts"], - moduleNameMapper: pathsToModuleNameMapper(compilerOptions?.paths || {}, { - prefix: "/", - }), + moduleNameMapper: { + "@bitwarden/common/platform/services/sdk/default-sdk-client-factory": + "/../../libs/common/spec/jest-sdk-client-factory", + ...pathsToModuleNameMapper(compilerOptions?.paths || {}, { + prefix: "/", + }), + }, }; diff --git a/bitwarden_license/bit-cli/tsconfig.json b/bitwarden_license/bit-cli/tsconfig.json index bb9986e6c9..9440a03375 100644 --- a/bitwarden_license/bit-cli/tsconfig.json +++ b/bitwarden_license/bit-cli/tsconfig.json @@ -3,7 +3,7 @@ "pretty": true, "moduleResolution": "node", "target": "ES2016", - "module": "es6", + "module": "ES2020", "noImplicitAny": true, "allowSyntheticDefaultImports": true, "emitDecoratorMetadata": true, diff --git a/libs/angular/src/services/jslib-services.module.ts b/libs/angular/src/services/jslib-services.module.ts index 934649ebfc..c8186e1e90 100644 --- a/libs/angular/src/services/jslib-services.module.ts +++ b/libs/angular/src/services/jslib-services.module.ts @@ -151,6 +151,8 @@ import { KeyGenerationService as KeyGenerationServiceAbstraction } from "@bitwar import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService as MessagingServiceAbstraction } from "@bitwarden/common/platform/abstractions/messaging.service"; import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from "@bitwarden/common/platform/abstractions/platform-utils.service"; +import { SdkClientFactory } from "@bitwarden/common/platform/abstractions/sdk/sdk-client-factory"; +import { SdkService } from "@bitwarden/common/platform/abstractions/sdk/sdk.service"; import { StateService as StateServiceAbstraction } from "@bitwarden/common/platform/abstractions/state.service"; import { AbstractStorageService } from "@bitwarden/common/platform/abstractions/storage.service"; import { ValidationService as ValidationServiceAbstraction } from "@bitwarden/common/platform/abstractions/validation.service"; @@ -179,6 +181,7 @@ import { KeyGenerationService } from "@bitwarden/common/platform/services/key-ge import { MigrationBuilderService } from "@bitwarden/common/platform/services/migration-builder.service"; import { MigrationRunner } from "@bitwarden/common/platform/services/migration-runner"; import { NoopNotificationsService } from "@bitwarden/common/platform/services/noop-notifications.service"; +import { DefaultSdkService } from "@bitwarden/common/platform/services/sdk/default-sdk.service"; import { StateService } from "@bitwarden/common/platform/services/state.service"; import { StorageServiceProvider } from "@bitwarden/common/platform/services/storage-service.provider"; import { UserAutoUnlockKeyService } from "@bitwarden/common/platform/services/user-auto-unlock-key.service"; @@ -1324,6 +1327,11 @@ const safeProviders: SafeProvider[] = [ useExisting: NoopViewCacheService, deps: [], }), + safeProvider({ + provide: SdkService, + useClass: DefaultSdkService, + deps: [SdkClientFactory, EnvironmentService, PlatformUtilsServiceAbstraction], + }), ]; @NgModule({ diff --git a/libs/common/spec/jest-sdk-client-factory.ts b/libs/common/spec/jest-sdk-client-factory.ts new file mode 100644 index 0000000000..ff120ccd78 --- /dev/null +++ b/libs/common/spec/jest-sdk-client-factory.ts @@ -0,0 +1,9 @@ +import { ClientSettings, LogLevel, BitwardenClient } from "@bitwarden/sdk-internal"; + +import { SdkClientFactory } from "../src/platform/abstractions/sdk/sdk-client-factory"; + +export class DefaultSdkClientFactory implements SdkClientFactory { + createSdkClient(settings?: ClientSettings, log_level?: LogLevel): Promise { + throw new Error("Method not implemented."); + } +} diff --git a/libs/common/src/platform/abstractions/sdk/sdk-client-factory.ts b/libs/common/src/platform/abstractions/sdk/sdk-client-factory.ts new file mode 100644 index 0000000000..d684561dac --- /dev/null +++ b/libs/common/src/platform/abstractions/sdk/sdk-client-factory.ts @@ -0,0 +1,10 @@ +import type { BitwardenClient } from "@bitwarden/sdk-internal"; + +/** + * Factory for creating SDK clients. + */ +export abstract class SdkClientFactory { + abstract createSdkClient( + ...args: ConstructorParameters + ): Promise; +} diff --git a/libs/common/src/platform/abstractions/sdk/sdk.service.ts b/libs/common/src/platform/abstractions/sdk/sdk.service.ts new file mode 100644 index 0000000000..5899856e5f --- /dev/null +++ b/libs/common/src/platform/abstractions/sdk/sdk.service.ts @@ -0,0 +1,8 @@ +import { Observable } from "rxjs"; + +import { BitwardenClient } from "@bitwarden/sdk-internal"; + +export abstract class SdkService { + client$: Observable; + supported$: Observable; +} diff --git a/libs/common/src/platform/misc/flags.ts b/libs/common/src/platform/misc/flags.ts index 3a30567681..b3269c8f4e 100644 --- a/libs/common/src/platform/misc/flags.ts +++ b/libs/common/src/platform/misc/flags.ts @@ -2,6 +2,7 @@ // eslint-disable-next-line @typescript-eslint/ban-types export type SharedFlags = { showPasswordless?: boolean; + sdk?: boolean; }; // required to avoid linting errors when there are no flags @@ -28,7 +29,7 @@ function getFlags(envFlags: string | T): T { * @returns The value of the flag */ export function flagEnabled(flag: keyof Flags): boolean { - const flags = getFlags(process.env.FLAGS); + const flags = getFlags(process.env.FLAGS) ?? ({} as Flags); return flags[flag] == null || !!flags[flag]; } diff --git a/libs/common/src/platform/services/sdk/default-sdk-client-factory.ts b/libs/common/src/platform/services/sdk/default-sdk-client-factory.ts new file mode 100644 index 0000000000..8e99af2efe --- /dev/null +++ b/libs/common/src/platform/services/sdk/default-sdk-client-factory.ts @@ -0,0 +1,19 @@ +import * as sdk from "@bitwarden/sdk-internal"; +import * as module from "@bitwarden/sdk-internal/bitwarden_wasm_internal_bg.wasm"; + +import { SdkClientFactory } from "../../abstractions/sdk/sdk-client-factory"; + +/** + * Directly imports the Bitwarden SDK and initializes it. + * + * **Warning**: This requires WASM support and will fail if the environment does not support it. + */ +export class DefaultSdkClientFactory implements SdkClientFactory { + async createSdkClient( + ...args: ConstructorParameters + ): Promise { + (sdk as any).init(module); + + return Promise.resolve(new sdk.BitwardenClient(...args)); + } +} diff --git a/libs/common/src/platform/services/sdk/default-sdk.service.ts b/libs/common/src/platform/services/sdk/default-sdk.service.ts new file mode 100644 index 0000000000..0240ebc94b --- /dev/null +++ b/libs/common/src/platform/services/sdk/default-sdk.service.ts @@ -0,0 +1,95 @@ +import { concatMap, shareReplay } from "rxjs"; + +import { LogLevel, DeviceType as SdkDeviceType } from "@bitwarden/sdk-internal"; + +import { DeviceType } from "../../../enums/device-type.enum"; +import { EnvironmentService } from "../../abstractions/environment.service"; +import { PlatformUtilsService } from "../../abstractions/platform-utils.service"; +import { SdkClientFactory } from "../../abstractions/sdk/sdk-client-factory"; +import { SdkService } from "../../abstractions/sdk/sdk.service"; + +export class DefaultSdkService implements SdkService { + client$ = this.environmentService.environment$.pipe( + concatMap(async (env) => { + const settings = { + apiUrl: env.getApiUrl(), + identityUrl: env.getIdentityUrl(), + deviceType: this.toDevice(this.platformUtilsService.getDevice()), + userAgent: this.userAgent ?? navigator.userAgent, + }; + + return await this.sdkClientFactory.createSdkClient(settings, LogLevel.Info); + }), + shareReplay({ refCount: true, bufferSize: 1 }), + ); + + supported$ = this.client$.pipe( + concatMap(async (client) => { + return client.echo("bitwarden wasm!") === "bitwarden wasm!"; + }), + ); + + constructor( + private sdkClientFactory: SdkClientFactory, + private environmentService: EnvironmentService, + private platformUtilsService: PlatformUtilsService, + private userAgent: string = null, + ) {} + + private toDevice(device: DeviceType): SdkDeviceType { + switch (device) { + case DeviceType.Android: + return "Android"; + case DeviceType.iOS: + return "iOS"; + case DeviceType.ChromeExtension: + return "ChromeExtension"; + case DeviceType.FirefoxExtension: + return "FirefoxExtension"; + case DeviceType.OperaExtension: + return "OperaExtension"; + case DeviceType.EdgeExtension: + return "EdgeExtension"; + case DeviceType.WindowsDesktop: + return "WindowsDesktop"; + case DeviceType.MacOsDesktop: + return "MacOsDesktop"; + case DeviceType.LinuxDesktop: + return "LinuxDesktop"; + case DeviceType.ChromeBrowser: + return "ChromeBrowser"; + case DeviceType.FirefoxBrowser: + return "FirefoxBrowser"; + case DeviceType.OperaBrowser: + return "OperaBrowser"; + case DeviceType.EdgeBrowser: + return "EdgeBrowser"; + case DeviceType.IEBrowser: + return "IEBrowser"; + case DeviceType.UnknownBrowser: + return "UnknownBrowser"; + case DeviceType.AndroidAmazon: + return "AndroidAmazon"; + case DeviceType.UWP: + return "UWP"; + case DeviceType.SafariBrowser: + return "SafariBrowser"; + case DeviceType.VivaldiBrowser: + return "VivaldiBrowser"; + case DeviceType.VivaldiExtension: + return "VivaldiExtension"; + case DeviceType.SafariExtension: + return "SafariExtension"; + case DeviceType.Server: + return "Server"; + case DeviceType.WindowsCLI: + return "WindowsCLI"; + case DeviceType.MacOsCLI: + return "MacOsCLI"; + case DeviceType.LinuxCLI: + return "LinuxCLI"; + default: + return "SDK"; + } + } +} diff --git a/libs/common/src/platform/services/sdk/noop-sdk-client-factory.ts b/libs/common/src/platform/services/sdk/noop-sdk-client-factory.ts new file mode 100644 index 0000000000..d7eab7e8dc --- /dev/null +++ b/libs/common/src/platform/services/sdk/noop-sdk-client-factory.ts @@ -0,0 +1,16 @@ +import type { BitwardenClient } from "@bitwarden/sdk-internal"; + +import { SdkClientFactory } from "../../abstractions/sdk/sdk-client-factory"; + +/** + * Noop SDK client factory. + * + * Used during SDK rollout to prevent bundling the SDK with some applications. + */ +export class NoopSdkClientFactory implements SdkClientFactory { + createSdkClient( + ...args: ConstructorParameters + ): Promise { + return Promise.reject(new Error("SDK not available")); + } +} diff --git a/package-lock.json b/package-lock.json index f5e233c232..7ef9cf23d9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,6 +24,7 @@ "@angular/platform-browser": "16.2.12", "@angular/platform-browser-dynamic": "16.2.12", "@angular/router": "16.2.12", + "@bitwarden/sdk-internal": "0.1.3", "@electron/fuses": "1.8.0", "@koa/multer": "3.0.2", "@koa/router": "12.0.1", @@ -4625,6 +4626,11 @@ "resolved": "libs/platform", "link": true }, + "node_modules/@bitwarden/sdk-internal": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/@bitwarden/sdk-internal/-/sdk-internal-0.1.3.tgz", + "integrity": "sha512-zk9DyYMjylVLdljeLn3OLBcD939Hg/qMNJ2FxbyjiSKtcOcgglXgYmbcS01NRFFfM9REbn+j+2fWbQo6N+8SHw==" + }, "node_modules/@bitwarden/vault": { "resolved": "libs/vault", "link": true diff --git a/package.json b/package.json index ed4e95c012..2926fd095f 100644 --- a/package.json +++ b/package.json @@ -157,6 +157,7 @@ "@angular/platform-browser": "16.2.12", "@angular/platform-browser-dynamic": "16.2.12", "@angular/router": "16.2.12", + "@bitwarden/sdk-internal": "0.1.3", "@electron/fuses": "1.8.0", "@koa/multer": "3.0.2", "@koa/router": "12.0.1", From 9ea9c3a932433ac44997df6da9f26855ae79546d Mon Sep 17 00:00:00 2001 From: Oscar Hinton Date: Mon, 7 Oct 2024 13:56:02 +0200 Subject: [PATCH 04/13] [PM-11290] Enable SDK (#11378) Follow up PR to #10974, flips the compile time flags to enabled and includes some debug logic to detect if users encounter issues with the WASM bundle in preparation for active consumption of the SDK. --- apps/browser/config/base.json | 2 +- .../browser/src/background/main.background.ts | 15 ++++++++++ .../sdk/browser-sdk-client-factory.ts | 5 ++++ apps/browser/src/popup/app.component.ts | 29 ++++++++++++++++-- apps/cli/config/base.json | 2 +- .../service-container/service-container.ts | 15 ++++++++++ apps/desktop/config/base.json | 2 +- apps/desktop/src/app/app.component.ts | 29 +++++++++++++++--- apps/web/config/base.json | 2 +- apps/web/src/app/app.component.ts | 30 +++++++++++++++++-- .../src/services/jslib-services.module.ts | 7 ++++- .../platform/abstractions/sdk/sdk.service.ts | 2 ++ .../services/sdk/default-sdk.service.ts | 18 ++++++++++- 13 files changed, 144 insertions(+), 14 deletions(-) diff --git a/apps/browser/config/base.json b/apps/browser/config/base.json index 9506bda0f0..91d4830924 100644 --- a/apps/browser/config/base.json +++ b/apps/browser/config/base.json @@ -3,6 +3,6 @@ "flags": { "showPasswordless": true, "accountSwitching": false, - "sdk": false + "sdk": true } } diff --git a/apps/browser/src/background/main.background.ts b/apps/browser/src/background/main.background.ts index 5875490ff0..ec1842e105 100644 --- a/apps/browser/src/background/main.background.ts +++ b/apps/browser/src/background/main.background.ts @@ -732,6 +732,7 @@ export default class MainBackground { sdkClientFactory, this.environmentService, this.platformUtilsService, + this.apiService, ); this.passwordStrengthService = new PasswordStrengthService(); @@ -1330,6 +1331,20 @@ export default class MainBackground { await this.initOverlayAndTabsBackground(); + if (flagEnabled("sdk")) { + // Warn if the SDK for some reason can't be initialized + let supported = false; + try { + supported = await firstValueFrom(this.sdkService.supported$); + } catch (e) { + // Do nothing. + } + + if (!supported) { + this.sdkService.failedToInitialize().catch(this.logService.error); + } + } + return new Promise((resolve) => { setTimeout(async () => { await this.refreshBadge(); diff --git a/apps/browser/src/platform/services/sdk/browser-sdk-client-factory.ts b/apps/browser/src/platform/services/sdk/browser-sdk-client-factory.ts index 2293a3b384..aa8bfe61c2 100644 --- a/apps/browser/src/platform/services/sdk/browser-sdk-client-factory.ts +++ b/apps/browser/src/platform/services/sdk/browser-sdk-client-factory.ts @@ -28,6 +28,11 @@ if (supported) { import("./fallback"); } +/** + * SDK client factory with a js fallback for when WASM is not supported. + * + * Works both in popup and service worker. + */ export class BrowserSdkClientFactory implements SdkClientFactory { async createSdkClient( ...args: ConstructorParameters diff --git a/apps/browser/src/popup/app.component.ts b/apps/browser/src/popup/app.component.ts index 12d5b109c2..113cd736c6 100644 --- a/apps/browser/src/popup/app.component.ts +++ b/apps/browser/src/popup/app.component.ts @@ -1,6 +1,7 @@ import { ChangeDetectorRef, Component, NgZone, OnDestroy, OnInit, inject } from "@angular/core"; +import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; import { NavigationEnd, Router, RouterOutlet } from "@angular/router"; -import { Subject, takeUntil, firstValueFrom, concatMap, filter, tap } from "rxjs"; +import { Subject, takeUntil, firstValueFrom, concatMap, filter, tap, catchError, of } from "rxjs"; import { LogoutReason } from "@bitwarden/auth/common"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; @@ -8,7 +9,9 @@ import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; import { AnimationControlService } from "@bitwarden/common/platform/abstractions/animation-control.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"; +import { SdkService } from "@bitwarden/common/platform/abstractions/sdk/sdk.service"; import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { MessageListener } from "@bitwarden/common/platform/messaging"; import { UserId } from "@bitwarden/common/types/guid"; @@ -20,6 +23,7 @@ import { ToastService, } from "@bitwarden/components"; +import { flagEnabled } from "../platform/flags"; import { PopupViewCacheService } from "../platform/popup/view-cache/popup-view-cache.service"; import { initPopupClosedListener } from "../platform/services/popup-view-cache-background.service"; import { BrowserSendStateService } from "../tools/popup/services/browser-send-state.service"; @@ -62,7 +66,28 @@ export class AppComponent implements OnInit, OnDestroy { private toastService: ToastService, private accountService: AccountService, private animationControlService: AnimationControlService, - ) {} + private logService: LogService, + private sdkService: SdkService, + ) { + if (flagEnabled("sdk")) { + // Warn if the SDK for some reason can't be initialized + this.sdkService.supported$ + .pipe( + takeUntilDestroyed(), + catchError(() => { + return of(false); + }), + ) + .subscribe((supported) => { + if (!supported) { + this.logService.debug("SDK is not supported"); + this.sdkService.failedToInitialize().catch(this.logService.error); + } else { + this.logService.debug("SDK is supported"); + } + }); + } + } async ngOnInit() { initPopupClosedListener(); diff --git a/apps/cli/config/base.json b/apps/cli/config/base.json index 67f2323e94..ccf867c0dc 100644 --- a/apps/cli/config/base.json +++ b/apps/cli/config/base.json @@ -1,5 +1,5 @@ { "flags": { - "sdk": false + "sdk": true } } diff --git a/apps/cli/src/service-container/service-container.ts b/apps/cli/src/service-container/service-container.ts index 95aa5f98b0..a249a4d3f3 100644 --- a/apps/cli/src/service-container/service-container.ts +++ b/apps/cli/src/service-container/service-container.ts @@ -535,6 +535,7 @@ export class ServiceContainer { sdkClientFactory, this.environmentService, this.platformUtilsService, + this.apiService, customUserAgent, ); @@ -846,5 +847,19 @@ export class ServiceContainer { } this.inited = true; + + if (flagEnabled("sdk")) { + // Warn if the SDK for some reason can't be initialized + let supported = false; + try { + supported = await firstValueFrom(this.sdkService.supported$); + } catch (e) { + // Do nothing. + } + + if (!supported) { + this.sdkService.failedToInitialize().catch(this.logService.error); + } + } } } diff --git a/apps/desktop/config/base.json b/apps/desktop/config/base.json index 5efcbc629c..5d045326d4 100644 --- a/apps/desktop/config/base.json +++ b/apps/desktop/config/base.json @@ -1,6 +1,6 @@ { "flags": { - "sdk": false + "sdk": true }, "devFlags": {} } diff --git a/apps/desktop/src/app/app.component.ts b/apps/desktop/src/app/app.component.ts index 9678f65723..61da12998d 100644 --- a/apps/desktop/src/app/app.component.ts +++ b/apps/desktop/src/app/app.component.ts @@ -8,8 +8,9 @@ import { ViewChild, ViewContainerRef, } from "@angular/core"; +import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; import { Router } from "@angular/router"; -import { filter, firstValueFrom, map, Subject, takeUntil, timeout } from "rxjs"; +import { catchError, filter, firstValueFrom, map, of, Subject, takeUntil, timeout } from "rxjs"; import { ModalRef } from "@bitwarden/angular/components/modal/modal.ref"; import { ModalService } from "@bitwarden/angular/services/modal.service"; @@ -21,7 +22,6 @@ import { SearchService } from "@bitwarden/common/abstractions/search.service"; import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service"; import { VaultTimeoutService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout.service"; import { InternalPolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; -import { ProviderService } from "@bitwarden/common/admin-console/abstractions/provider.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { KeyConnectorService } from "@bitwarden/common/auth/abstractions/key-connector.service"; @@ -38,6 +38,7 @@ import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.servic import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; +import { SdkService } from "@bitwarden/common/platform/abstractions/sdk/sdk.service"; import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { SystemService } from "@bitwarden/common/platform/abstractions/system.service"; import { clearCaches } from "@bitwarden/common/platform/misc/sequentialize"; @@ -56,6 +57,7 @@ import { BiometricStateService } from "@bitwarden/key-management"; import { DeleteAccountComponent } from "../auth/delete-account.component"; import { LoginApprovalComponent } from "../auth/login/login-approval.component"; import { MenuAccount, MenuUpdateRequest } from "../main/menu/menu.updater"; +import { flagEnabled } from "../platform/flags"; import { PremiumComponent } from "../vault/app/accounts/premium.component"; import { FolderAddEditComponent } from "../vault/app/vault/folder-add-edit.component"; @@ -150,9 +152,28 @@ export class AppComponent implements OnInit, OnDestroy { private dialogService: DialogService, private biometricStateService: BiometricStateService, private stateEventRunnerService: StateEventRunnerService, - private providerService: ProviderService, private accountService: AccountService, - ) {} + private sdkService: SdkService, + ) { + if (flagEnabled("sdk")) { + // Warn if the SDK for some reason can't be initialized + this.sdkService.supported$ + .pipe( + takeUntilDestroyed(), + catchError(() => { + return of(false); + }), + ) + .subscribe((supported) => { + if (!supported) { + this.logService.debug("SDK is not supported"); + this.sdkService.failedToInitialize().catch(this.logService.error); + } else { + this.logService.debug("SDK is supported"); + } + }); + } + } ngOnInit() { this.accountService.activeAccount$.pipe(takeUntil(this.destroy$)).subscribe((account) => { diff --git a/apps/web/config/base.json b/apps/web/config/base.json index 98f91360bc..cfaf604fb0 100644 --- a/apps/web/config/base.json +++ b/apps/web/config/base.json @@ -12,7 +12,7 @@ }, "flags": { "showPasswordless": false, - "sdk": false + "sdk": true }, "devFlags": {} } diff --git a/apps/web/src/app/app.component.ts b/apps/web/src/app/app.component.ts index 578bc9111c..7299c8ece2 100644 --- a/apps/web/src/app/app.component.ts +++ b/apps/web/src/app/app.component.ts @@ -1,8 +1,9 @@ import { DOCUMENT } from "@angular/common"; import { Component, Inject, NgZone, OnDestroy, OnInit } from "@angular/core"; +import { takeUntilDestroyed } from "@angular/core/rxjs-interop"; import { NavigationEnd, Router } from "@angular/router"; import * as jq from "jquery"; -import { Subject, filter, firstValueFrom, map, takeUntil, timeout } from "rxjs"; +import { Subject, filter, firstValueFrom, map, takeUntil, timeout, catchError, of } from "rxjs"; import { LogoutReason } from "@bitwarden/auth/common"; import { EventUploadService } from "@bitwarden/common/abstractions/event/event-upload.service"; @@ -19,7 +20,9 @@ import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broa import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.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"; +import { SdkService } from "@bitwarden/common/platform/abstractions/sdk/sdk.service"; import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { StateEventRunnerService } from "@bitwarden/common/platform/state"; import { SyncService } from "@bitwarden/common/platform/sync"; @@ -30,6 +33,8 @@ import { DialogService, ToastOptions, ToastService } from "@bitwarden/components import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; import { BiometricStateService } from "@bitwarden/key-management"; +import { flagEnabled } from "../utils/flags"; + import { PolicyListService } from "./admin-console/core/policy-list.service"; import { DisableSendPolicy, @@ -85,7 +90,28 @@ export class AppComponent implements OnDestroy, OnInit { private stateEventRunnerService: StateEventRunnerService, private organizationService: InternalOrganizationServiceAbstraction, private accountService: AccountService, - ) {} + private logService: LogService, + private sdkService: SdkService, + ) { + if (flagEnabled("sdk")) { + // Warn if the SDK for some reason can't be initialized + this.sdkService.supported$ + .pipe( + takeUntilDestroyed(), + catchError(() => { + return of(false); + }), + ) + .subscribe((supported) => { + if (!supported) { + this.logService.debug("SDK is not supported"); + this.sdkService.failedToInitialize().catch(this.logService.error); + } else { + this.logService.debug("SDK is supported"); + } + }); + } + } ngOnInit() { this.i18nService.locale$.pipe(takeUntil(this.destroy$)).subscribe((locale) => { diff --git a/libs/angular/src/services/jslib-services.module.ts b/libs/angular/src/services/jslib-services.module.ts index c8186e1e90..41b24a4a54 100644 --- a/libs/angular/src/services/jslib-services.module.ts +++ b/libs/angular/src/services/jslib-services.module.ts @@ -1330,7 +1330,12 @@ const safeProviders: SafeProvider[] = [ safeProvider({ provide: SdkService, useClass: DefaultSdkService, - deps: [SdkClientFactory, EnvironmentService, PlatformUtilsServiceAbstraction], + deps: [ + SdkClientFactory, + EnvironmentService, + PlatformUtilsServiceAbstraction, + ApiServiceAbstraction, + ], }), ]; diff --git a/libs/common/src/platform/abstractions/sdk/sdk.service.ts b/libs/common/src/platform/abstractions/sdk/sdk.service.ts index 5899856e5f..360f2e91a7 100644 --- a/libs/common/src/platform/abstractions/sdk/sdk.service.ts +++ b/libs/common/src/platform/abstractions/sdk/sdk.service.ts @@ -5,4 +5,6 @@ import { BitwardenClient } from "@bitwarden/sdk-internal"; export abstract class SdkService { client$: Observable; supported$: Observable; + + abstract failedToInitialize(): Promise; } diff --git a/libs/common/src/platform/services/sdk/default-sdk.service.ts b/libs/common/src/platform/services/sdk/default-sdk.service.ts index 0240ebc94b..d4a9cfeb7e 100644 --- a/libs/common/src/platform/services/sdk/default-sdk.service.ts +++ b/libs/common/src/platform/services/sdk/default-sdk.service.ts @@ -1,7 +1,8 @@ -import { concatMap, shareReplay } from "rxjs"; +import { concatMap, firstValueFrom, shareReplay } from "rxjs"; import { LogLevel, DeviceType as SdkDeviceType } from "@bitwarden/sdk-internal"; +import { ApiService } from "../../../abstractions/api.service"; import { DeviceType } from "../../../enums/device-type.enum"; import { EnvironmentService } from "../../abstractions/environment.service"; import { PlatformUtilsService } from "../../abstractions/platform-utils.service"; @@ -33,9 +34,24 @@ export class DefaultSdkService implements SdkService { private sdkClientFactory: SdkClientFactory, private environmentService: EnvironmentService, private platformUtilsService: PlatformUtilsService, + private apiService: ApiService, // Yes we shouldn't import ApiService, but it's temporary private userAgent: string = null, ) {} + async failedToInitialize(): Promise { + // Only log on cloud instances + if ( + this.platformUtilsService.isDev() || + !(await firstValueFrom(this.environmentService.environment$)).isCloud + ) { + return; + } + + return this.apiService.send("POST", "/wasm-debug", null, false, false, null, (headers) => { + headers.append("SDK-Version", "1.0.0"); + }); + } + private toDevice(device: DeviceType): SdkDeviceType { switch (device) { case DeviceType.Android: From a4123cb8bafe377c8847ebfd500c112ea96f1096 Mon Sep 17 00:00:00 2001 From: Shlomo Zalman Heigh Date: Mon, 7 Oct 2024 10:22:10 -0400 Subject: [PATCH 05/13] [PM-11497] If an org has only one collection, check it by default (#10806) Signed-off-by: Shlomo Zalman Heigh --- libs/angular/src/vault/components/add-edit.component.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libs/angular/src/vault/components/add-edit.component.ts b/libs/angular/src/vault/components/add-edit.component.ts index 960a226b1c..dc782e6e3a 100644 --- a/libs/angular/src/vault/components/add-edit.component.ts +++ b/libs/angular/src/vault/components/add-edit.component.ts @@ -605,6 +605,10 @@ export class AddEditComponent implements OnInit, OnDestroy { this.collections = this.writeableCollections?.filter( (c) => c.organizationId === this.cipher.organizationId, ); + // If there's only one collection, check it by default + if (this.collections.length === 1) { + (this.collections[0] as any).checked = true; + } const org = await this.organizationService.get(this.cipher.organizationId); if (org != null) { this.cipher.organizationUseTotp = org.useTotp; From 68f4c2e8797fea99fbe2fc40e11e832680b43359 Mon Sep 17 00:00:00 2001 From: Shane Melton Date: Mon, 7 Oct 2024 07:23:00 -0700 Subject: [PATCH 06/13] [PM-12389] Vault Item Dialog Fixes (#11374) * [PM-12389] Hide delete button when there is no cipher to delete * [PM-12389] Ensure decrypted collections and folders are available before building cipher form config * [PM-12389] Hide the delete button when cloning ciphers --- .../vault-item-dialog.component.html | 3 ++- .../vault-item-dialog.component.ts | 13 +++++++++++-- .../vault/abstractions/collection.service.ts | 1 + .../default-cipher-form-config.service.ts | 18 +++++++++++++++--- 4 files changed, 29 insertions(+), 6 deletions(-) diff --git a/apps/web/src/app/vault/components/vault-item-dialog/vault-item-dialog.component.html b/apps/web/src/app/vault/components/vault-item-dialog/vault-item-dialog.component.html index 521665496a..740264713c 100644 --- a/apps/web/src/app/vault/components/vault-item-dialog/vault-item-dialog.component.html +++ b/apps/web/src/app/vault/components/vault-item-dialog/vault-item-dialog.component.html @@ -65,7 +65,7 @@ > {{ "cancel" | i18n }} -
+
diff --git a/apps/web/src/app/vault/components/vault-item-dialog/vault-item-dialog.component.ts b/apps/web/src/app/vault/components/vault-item-dialog/vault-item-dialog.component.ts index d3d0703605..c1878e2dcb 100644 --- a/apps/web/src/app/vault/components/vault-item-dialog/vault-item-dialog.component.ts +++ b/apps/web/src/app/vault/components/vault-item-dialog/vault-item-dialog.component.ts @@ -179,6 +179,15 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy { return this.cipher?.edit ?? false; } + protected get showDelete() { + // Don't show the delete button when cloning a cipher + if (this.params.mode == "form" && this.formConfig.mode === "clone") { + return false; + } + // Never show the delete button for new ciphers + return this.cipher != null; + } + protected get showCipherView() { return this.cipher != undefined && (this.params.mode === "view" || this.loadingForm); } @@ -332,8 +341,8 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy { }; cancel = async () => { - // We're in View mode, or we don't have a cipher, close the dialog. - if (this.params.mode === "view" || this.cipher == null) { + // We're in View mode, we don't have a cipher, or we were cloning, close the dialog. + if (this.params.mode === "view" || this.cipher == null || this.formConfig.mode === "clone") { this.dialogRef.close(this._cipherModified ? VaultItemDialogResult.Saved : undefined); return; } diff --git a/libs/common/src/vault/abstractions/collection.service.ts b/libs/common/src/vault/abstractions/collection.service.ts index 81ae76729a..1f3e95a019 100644 --- a/libs/common/src/vault/abstractions/collection.service.ts +++ b/libs/common/src/vault/abstractions/collection.service.ts @@ -8,6 +8,7 @@ import { TreeNode } from "../models/domain/tree-node"; import { CollectionView } from "../models/view/collection.view"; export abstract class CollectionService { + encryptedCollections$: Observable; decryptedCollections$: Observable; clearActiveUserCache: () => Promise; diff --git a/libs/vault/src/cipher-form/services/default-cipher-form-config.service.ts b/libs/vault/src/cipher-form/services/default-cipher-form-config.service.ts index 4171f153ec..977cee8156 100644 --- a/libs/vault/src/cipher-form/services/default-cipher-form-config.service.ts +++ b/libs/vault/src/cipher-form/services/default-cipher-form-config.service.ts @@ -1,5 +1,5 @@ import { inject, Injectable } from "@angular/core"; -import { combineLatest, firstValueFrom, map } from "rxjs"; +import { combineLatest, filter, firstValueFrom, map, switchMap } from "rxjs"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; @@ -39,9 +39,21 @@ export class DefaultCipherFormConfigService implements CipherFormConfigService { await firstValueFrom( combineLatest([ this.organizations$, - this.collectionService.decryptedCollections$, + this.collectionService.encryptedCollections$.pipe( + switchMap((c) => + this.collectionService.decryptedCollections$.pipe( + filter((d) => d.length === c.length), // Ensure all collections have been decrypted + ), + ), + ), this.allowPersonalOwnership$, - this.folderService.folderViews$, + this.folderService.folders$.pipe( + switchMap((f) => + this.folderService.folderViews$.pipe( + filter((d) => d.length - 1 === f.length), // -1 for "No Folder" in folderViews$ + ), + ), + ), this.getCipher(cipherId), ]), ); From 359b6e02d99ce1cbcfcc99a42962869bddb0b92c Mon Sep 17 00:00:00 2001 From: Oleksii Holub <1935960+Tyrrrz@users.noreply.github.com> Date: Mon, 7 Oct 2024 17:55:17 +0300 Subject: [PATCH 07/13] PM-12102 | Fix LastPass importer not properly de-encrypting URLs (#11366) * PM-12102 | Fix LastPass importer not properly de-encrypting URLs * Reuse the original code for the unencrypted path * Add some comments --- .../importers/lastpass/access/services/parser.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/libs/importer/src/importers/lastpass/access/services/parser.ts b/libs/importer/src/importers/lastpass/access/services/parser.ts index 19ef55bc73..31efadd6c0 100644 --- a/libs/importer/src/importers/lastpass/access/services/parser.ts +++ b/libs/importer/src/importers/lastpass/access/services/parser.ts @@ -22,7 +22,7 @@ export class Parser { /* May return null when the chunk does not represent an account. All secure notes are ACCTs but not all of them store account information. - + TODO: Add a test for the folder case! TODO: Add a test case that covers secure note account! */ @@ -60,9 +60,17 @@ export class Parser { // 3: url step = 3; - let url = Utils.fromBufferToUtf8( - this.decodeHexLoose(Utils.fromBufferToUtf8(this.readItem(reader))), - ); + const urlEncoded = this.readItem(reader); + let url = + urlEncoded.length > 0 && urlEncoded[0] === 33 // 33 = '!' + ? // URL is encrypted + await this.cryptoUtils.decryptAes256PlainWithDefault( + urlEncoded, + encryptionKey, + placeholder, + ) + : // URL is not encrypted + Utils.fromBufferToUtf8(this.decodeHexLoose(Utils.fromBufferToUtf8(urlEncoded))); // Ignore "group" accounts. They have no credentials. if (url == "http://group") { From c98b4553f22b8e0e38af97e7690955a4c7a790d7 Mon Sep 17 00:00:00 2001 From: "bw-ghapp[bot]" <178206702+bw-ghapp[bot]@users.noreply.github.com> Date: Mon, 7 Oct 2024 15:06:39 +0000 Subject: [PATCH 08/13] Bumped client version(s) (#11439) Co-authored-by: bitwarden-devops-bot <106330231+bitwarden-devops-bot@users.noreply.github.com> --- apps/browser/package.json | 2 +- apps/browser/src/manifest.json | 2 +- apps/browser/src/manifest.v3.json | 2 +- apps/cli/package.json | 2 +- apps/desktop/package.json | 2 +- apps/desktop/src/package-lock.json | 12 ++---------- apps/desktop/src/package.json | 2 +- apps/web/package.json | 2 +- package-lock.json | 8 ++++---- 9 files changed, 13 insertions(+), 21 deletions(-) diff --git a/apps/browser/package.json b/apps/browser/package.json index 9d87869459..15caff9eff 100644 --- a/apps/browser/package.json +++ b/apps/browser/package.json @@ -1,6 +1,6 @@ { "name": "@bitwarden/browser", - "version": "2024.10.0", + "version": "2024.10.1", "scripts": { "build": "cross-env MANIFEST_VERSION=3 webpack", "build:mv2": "webpack", diff --git a/apps/browser/src/manifest.json b/apps/browser/src/manifest.json index 598c6ff028..850c5c4727 100644 --- a/apps/browser/src/manifest.json +++ b/apps/browser/src/manifest.json @@ -2,7 +2,7 @@ "manifest_version": 2, "name": "__MSG_extName__", "short_name": "__MSG_appName__", - "version": "2024.10.0", + "version": "2024.10.1", "description": "__MSG_extDesc__", "default_locale": "en", "author": "Bitwarden Inc.", diff --git a/apps/browser/src/manifest.v3.json b/apps/browser/src/manifest.v3.json index 762e5e01f8..0b89a36d70 100644 --- a/apps/browser/src/manifest.v3.json +++ b/apps/browser/src/manifest.v3.json @@ -3,7 +3,7 @@ "minimum_chrome_version": "102.0", "name": "__MSG_extName__", "short_name": "__MSG_appName__", - "version": "2024.10.0", + "version": "2024.10.1", "description": "__MSG_extDesc__", "default_locale": "en", "author": "Bitwarden Inc.", diff --git a/apps/cli/package.json b/apps/cli/package.json index 759fb14ba5..502e186d34 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,7 +1,7 @@ { "name": "@bitwarden/cli", "description": "A secure and free password manager for all of your devices.", - "version": "2024.9.1", + "version": "2024.10.0", "keywords": [ "bitwarden", "password", diff --git a/apps/desktop/package.json b/apps/desktop/package.json index fbf598327f..1014412c0d 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,7 +1,7 @@ { "name": "@bitwarden/desktop", "description": "A secure and free password manager for all of your devices.", - "version": "2024.9.2", + "version": "2024.10.0", "keywords": [ "bitwarden", "password", diff --git a/apps/desktop/src/package-lock.json b/apps/desktop/src/package-lock.json index acd5f97a3f..602f35872e 100644 --- a/apps/desktop/src/package-lock.json +++ b/apps/desktop/src/package-lock.json @@ -1,26 +1,18 @@ { "name": "@bitwarden/desktop", - "version": "2024.9.2", + "version": "2024.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@bitwarden/desktop", - "version": "2024.9.2", + "version": "2024.10.0", "license": "GPL-3.0", "dependencies": { "@bitwarden/desktop-napi": "file:../desktop_native/napi", "argon2": "0.40.1" } }, - "../desktop_native/napi": { - "name": "@bitwarden/desktop-napi", - "version": "0.1.0", - "license": "GPL-3.0", - "devDependencies": { - "@napi-rs/cli": "2.16.2" - } - }, "../desktop_native/napi": { "version": "0.1.0", "license": "GPL-3.0", diff --git a/apps/desktop/src/package.json b/apps/desktop/src/package.json index 29b3f8ed7d..c98d31f10a 100644 --- a/apps/desktop/src/package.json +++ b/apps/desktop/src/package.json @@ -2,7 +2,7 @@ "name": "@bitwarden/desktop", "productName": "Bitwarden", "description": "A secure and free password manager for all of your devices.", - "version": "2024.9.2", + "version": "2024.10.0", "author": "Bitwarden Inc. (https://bitwarden.com)", "homepage": "https://bitwarden.com", "license": "GPL-3.0", diff --git a/apps/web/package.json b/apps/web/package.json index bc7a96e239..dd737fb5b4 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@bitwarden/web-vault", - "version": "2024.10.0", + "version": "2024.10.1", "scripts": { "build:oss": "webpack", "build:bit": "webpack -c ../../bitwarden_license/bit-web/webpack.config.js", diff --git a/package-lock.json b/package-lock.json index 7ef9cf23d9..791976f907 100644 --- a/package-lock.json +++ b/package-lock.json @@ -194,11 +194,11 @@ }, "apps/browser": { "name": "@bitwarden/browser", - "version": "2024.10.0" + "version": "2024.10.1" }, "apps/cli": { "name": "@bitwarden/cli", - "version": "2024.9.1", + "version": "2024.10.0", "license": "SEE LICENSE IN LICENSE.txt", "dependencies": { "@koa/multer": "3.0.2", @@ -234,7 +234,7 @@ }, "apps/desktop": { "name": "@bitwarden/desktop", - "version": "2024.9.2", + "version": "2024.10.0", "hasInstallScript": true, "license": "GPL-3.0" }, @@ -248,7 +248,7 @@ }, "apps/web": { "name": "@bitwarden/web-vault", - "version": "2024.10.0" + "version": "2024.10.1" }, "libs/admin-console": { "name": "@bitwarden/admin-console", From 7098a243ca03d42f5994dfc863f652b8905b4c5b Mon Sep 17 00:00:00 2001 From: Jason Ng Date: Mon, 7 Oct 2024 11:15:00 -0400 Subject: [PATCH 09/13] [PM-10378] Unassigned Items Readonly After Edit Bug Fix (#11340) --- libs/common/src/vault/services/cipher.service.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libs/common/src/vault/services/cipher.service.ts b/libs/common/src/vault/services/cipher.service.ts index a06ca4d793..77e696b5cd 100644 --- a/libs/common/src/vault/services/cipher.service.ts +++ b/libs/common/src/vault/services/cipher.service.ts @@ -673,6 +673,8 @@ export class CipherService implements CipherServiceAbstraction { if (orgAdmin && cipher.organizationId != null) { const request = new CipherCreateRequest(cipher); response = await this.apiService.postCipherAdmin(request); + const data = new CipherData(response, cipher.collectionIds); + return new Cipher(data); } else if (cipher.collectionIds != null) { const request = new CipherCreateRequest(cipher); response = await this.apiService.postCipherCreate(request); @@ -697,6 +699,8 @@ export class CipherService implements CipherServiceAbstraction { if (orgAdmin && isNotClone) { const request = new CipherRequest(cipher); response = await this.apiService.putCipherAdmin(cipher.id, request); + const data = new CipherData(response, cipher.collectionIds); + return new Cipher(data, cipher.localData); } else if (cipher.edit) { const request = new CipherRequest(cipher); response = await this.apiService.putCipher(cipher.id, request); From a6db7e30861dff7803f053c4b91be721966b7f89 Mon Sep 17 00:00:00 2001 From: Nick Krantz <125900171+nick-livefront@users.noreply.github.com> Date: Mon, 7 Oct 2024 10:59:23 -0500 Subject: [PATCH 10/13] [PM-10426] Admin Console - Edit Modal (#11249) * add `hideFolderSelection` for admin console ciphers * hide folder form field when configuration has `hideFolderSelection` set to true * add `addCipherV2` method in the admin console vault * add browser refresh logic for add/edit form * add admin console implementation of `AdminConsoleCipherFormConfigService` * only allow edit dialog in admin console * remove duplicate check * refactor comments * initial integration of combined dialog * integrate add cipher with admin console vault * account for special admin console collection permissions * add `edit` variable to AC ciphers when the user has permissions * Move comment to JSDoc * pass full cipher to view component * validate edit access when opening view form * partial-edit not applicable for admin console * refactor hideIndividualFields to be more generic and hide favorite button * pass entire cipher into edit logic to match view logic * add null check for cipher when attempting to view * remove logic for personal ownership, not needed in AC --- ...console-cipher-form-config.service.spec.ts | 119 +++++++++++ ...dmin-console-cipher-form-config.service.ts | 99 ++++++++++ .../app/vault/org-vault/vault.component.ts | 186 +++++++++++++----- .../cipher-form-config.service.ts | 3 + .../item-details-section.component.html | 8 +- 5 files changed, 361 insertions(+), 54 deletions(-) create mode 100644 apps/web/src/app/vault/org-vault/services/admin-console-cipher-form-config.service.spec.ts create mode 100644 apps/web/src/app/vault/org-vault/services/admin-console-cipher-form-config.service.ts diff --git a/apps/web/src/app/vault/org-vault/services/admin-console-cipher-form-config.service.spec.ts b/apps/web/src/app/vault/org-vault/services/admin-console-cipher-form-config.service.spec.ts new file mode 100644 index 0000000000..f0624e6b2f --- /dev/null +++ b/apps/web/src/app/vault/org-vault/services/admin-console-cipher-form-config.service.spec.ts @@ -0,0 +1,119 @@ +import { TestBed } from "@angular/core/testing"; +import { BehaviorSubject } from "rxjs"; + +import { CollectionAdminService } from "@bitwarden/admin-console/common"; +import { ApiService } from "@bitwarden/common/abstractions/api.service"; +import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; +import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; +import { CipherId } from "@bitwarden/common/types/guid"; +import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; + +import { RoutedVaultFilterService } from "../../individual-vault/vault-filter/services/routed-vault-filter.service"; + +import { AdminConsoleCipherFormConfigService } from "./admin-console-cipher-form-config.service"; + +describe("AdminConsoleCipherFormConfigService", () => { + let adminConsoleConfigService: AdminConsoleCipherFormConfigService; + + const cipherId = "333-444-555" as CipherId; + const testOrg = { id: "333-44-55", name: "Test Org", canEditAllCiphers: false }; + const organization$ = new BehaviorSubject(testOrg as Organization); + const getCipherAdmin = jest.fn().mockResolvedValue(null); + const getCipher = jest.fn().mockResolvedValue(null); + + beforeEach(async () => { + getCipherAdmin.mockClear(); + getCipher.mockClear(); + getCipher.mockResolvedValue({ id: cipherId, name: "Test Cipher - (non-admin)" }); + getCipherAdmin.mockResolvedValue({ id: cipherId, name: "Test Cipher - (admin)" }); + + await TestBed.configureTestingModule({ + providers: [ + AdminConsoleCipherFormConfigService, + { provide: OrganizationService, useValue: { get$: () => organization$ } }, + { provide: CipherService, useValue: { get: getCipher } }, + { provide: CollectionAdminService, useValue: { getAll: () => Promise.resolve([]) } }, + { + provide: RoutedVaultFilterService, + useValue: { filter$: new BehaviorSubject({ organizationId: testOrg.id }) }, + }, + { provide: ApiService, useValue: { getCipherAdmin } }, + ], + }); + }); + + describe("buildConfig", () => { + it("sets individual attributes", async () => { + adminConsoleConfigService = TestBed.inject(AdminConsoleCipherFormConfigService); + + const { folders, hideIndividualVaultFields } = await adminConsoleConfigService.buildConfig( + "add", + cipherId, + ); + + expect(folders).toEqual([]); + expect(hideIndividualVaultFields).toBe(true); + }); + + it("sets mode based on passed mode", async () => { + adminConsoleConfigService = TestBed.inject(AdminConsoleCipherFormConfigService); + + const { mode } = await adminConsoleConfigService.buildConfig("edit", cipherId); + + expect(mode).toBe("edit"); + }); + + it("sets admin flag based on `canEditAllCiphers`", async () => { + // Disable edit all ciphers on org + testOrg.canEditAllCiphers = false; + adminConsoleConfigService = TestBed.inject(AdminConsoleCipherFormConfigService); + + let result = await adminConsoleConfigService.buildConfig("add", cipherId); + + expect(result.admin).toBe(false); + + // Enable edit all ciphers on org + testOrg.canEditAllCiphers = true; + result = await adminConsoleConfigService.buildConfig("add", cipherId); + + expect(result.admin).toBe(true); + }); + + it("sets `allowPersonalOwnership` to false", async () => { + adminConsoleConfigService = TestBed.inject(AdminConsoleCipherFormConfigService); + + const result = await adminConsoleConfigService.buildConfig("clone", cipherId); + + expect(result.allowPersonalOwnership).toBe(false); + }); + + describe("getCipher", () => { + it("retrieves the cipher from the cipher service", async () => { + testOrg.canEditAllCiphers = false; + + adminConsoleConfigService = TestBed.inject(AdminConsoleCipherFormConfigService); + + const result = await adminConsoleConfigService.buildConfig("clone", cipherId); + + expect(getCipher).toHaveBeenCalledWith(cipherId); + expect(result.originalCipher.name).toBe("Test Cipher - (non-admin)"); + + // Admin service not needed when cipher service can return the cipher + expect(getCipherAdmin).not.toHaveBeenCalled(); + }); + + it("retrieves the cipher from the admin service", async () => { + getCipher.mockResolvedValueOnce(null); + getCipherAdmin.mockResolvedValue({ id: cipherId, name: "Test Cipher - (admin)" }); + + adminConsoleConfigService = TestBed.inject(AdminConsoleCipherFormConfigService); + + await adminConsoleConfigService.buildConfig("add", cipherId); + + expect(getCipherAdmin).toHaveBeenCalledWith(cipherId); + + expect(getCipher).toHaveBeenCalledWith(cipherId); + }); + }); + }); +}); diff --git a/apps/web/src/app/vault/org-vault/services/admin-console-cipher-form-config.service.ts b/apps/web/src/app/vault/org-vault/services/admin-console-cipher-form-config.service.ts new file mode 100644 index 0000000000..fa5cbedfca --- /dev/null +++ b/apps/web/src/app/vault/org-vault/services/admin-console-cipher-form-config.service.ts @@ -0,0 +1,99 @@ +import { inject, Injectable } from "@angular/core"; +import { combineLatest, filter, firstValueFrom, map, switchMap } from "rxjs"; + +import { CollectionAdminService } from "@bitwarden/admin-console/common"; +import { ApiService } from "@bitwarden/common/abstractions/api.service"; +import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; +import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; +import { CipherId } from "@bitwarden/common/types/guid"; +import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; +import { CipherType } from "@bitwarden/common/vault/enums"; +import { CipherData } from "@bitwarden/common/vault/models/data/cipher.data"; +import { Cipher } from "@bitwarden/common/vault/models/domain/cipher"; + +import { + CipherFormConfig, + CipherFormConfigService, + CipherFormMode, +} from "../../../../../../../libs/vault/src/cipher-form/abstractions/cipher-form-config.service"; +import { RoutedVaultFilterService } from "../../individual-vault/vault-filter/services/routed-vault-filter.service"; + +/** Admin Console implementation of the `CipherFormConfigService`. */ +@Injectable() +export class AdminConsoleCipherFormConfigService implements CipherFormConfigService { + private organizationService: OrganizationService = inject(OrganizationService); + private cipherService: CipherService = inject(CipherService); + private routedVaultFilterService: RoutedVaultFilterService = inject(RoutedVaultFilterService); + private collectionAdminService: CollectionAdminService = inject(CollectionAdminService); + private apiService: ApiService = inject(ApiService); + + private organizationId$ = this.routedVaultFilterService.filter$.pipe( + map((filter) => filter.organizationId), + filter((filter) => filter !== undefined), + ); + + private organization$ = this.organizationId$.pipe( + switchMap((organizationId) => this.organizationService.get$(organizationId)), + ); + + private editableCollections$ = this.organization$.pipe( + switchMap(async (org) => { + const collections = await this.collectionAdminService.getAll(org.id); + // Users that can edit all ciphers can implicitly add to / edit within any collection + if (org.canEditAllCiphers) { + return collections; + } + // The user is only allowed to add/edit items to assigned collections that are not readonly + return collections.filter((c) => c.assigned && !c.readOnly); + }), + ); + + async buildConfig( + mode: CipherFormMode, + cipherId?: CipherId, + cipherType?: CipherType, + ): Promise { + const [organization, allCollections] = await firstValueFrom( + combineLatest([this.organization$, this.editableCollections$]), + ); + + const cipher = await this.getCipher(organization, cipherId); + + const collections = allCollections.filter( + (c) => c.organizationId === organization.id && c.assigned && !c.readOnly, + ); + + return { + mode, + cipherType: cipher?.type ?? cipherType ?? CipherType.Login, + admin: organization.canEditAllCiphers ?? false, + allowPersonalOwnership: false, + originalCipher: cipher, + collections, + organizations: [organization], // only a single org is in context at a time + folders: [], // folders not applicable in the admin console + hideIndividualVaultFields: true, + }; + } + + private async getCipher(organization: Organization, id?: CipherId): Promise { + if (id == null) { + return Promise.resolve(null); + } + + // Check to see if the user has direct access to the cipher + const cipherFromCipherService = await this.cipherService.get(id); + + // If the organization doesn't allow admin/owners to edit all ciphers return the cipher + if (!organization.canEditAllCiphers && cipherFromCipherService != null) { + return cipherFromCipherService; + } + + // Retrieve the cipher through the means of an admin + const cipherResponse = await this.apiService.getCipherAdmin(id); + cipherResponse.edit = true; + + const cipherData = new CipherData(cipherResponse); + return new Cipher(cipherData); + } +} diff --git a/apps/web/src/app/vault/org-vault/vault.component.ts b/apps/web/src/app/vault/org-vault/vault.component.ts index a52530dde1..9c8ff3f2ff 100644 --- a/apps/web/src/app/vault/org-vault/vault.component.ts +++ b/apps/web/src/app/vault/org-vault/vault.component.ts @@ -1,3 +1,4 @@ +import { DialogRef } from "@angular/cdk/dialog"; import { ChangeDetectorRef, Component, @@ -42,16 +43,17 @@ import { EventCollectionService } from "@bitwarden/common/abstractions/event/eve import { SearchService } from "@bitwarden/common/abstractions/search.service"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; -import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { EventType } from "@bitwarden/common/enums"; +import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; +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"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { SyncService } from "@bitwarden/common/platform/sync"; -import { OrganizationId } from "@bitwarden/common/types/guid"; +import { CipherId, CollectionId, OrganizationId } from "@bitwarden/common/types/guid"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { CollectionService } from "@bitwarden/common/vault/abstractions/collection.service"; import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service"; @@ -62,7 +64,12 @@ import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { CollectionView } from "@bitwarden/common/vault/models/view/collection.view"; import { ServiceUtils } from "@bitwarden/common/vault/service-utils"; import { DialogService, Icons, NoItemsModule, ToastService } from "@bitwarden/components"; -import { CollectionAssignmentResult, PasswordRepromptService } from "@bitwarden/vault"; +import { + CipherFormConfig, + CipherFormConfigService, + CollectionAssignmentResult, + PasswordRepromptService, +} from "@bitwarden/vault"; import { GroupService, GroupView } from "../../admin-console/organizations/core"; import { openEntityEventsDialog } from "../../admin-console/organizations/manage/entity-events.component"; @@ -75,6 +82,11 @@ import { CollectionDialogTabType, openCollectionDialog, } from "../components/collection-dialog"; +import { + VaultItemDialogComponent, + VaultItemDialogMode, + VaultItemDialogResult, +} from "../components/vault-item-dialog/vault-item-dialog.component"; import { VaultItemEvent } from "../components/vault-items/vault-item-event"; import { VaultItemsModule } from "../components/vault-items/vault-items.module"; import { @@ -89,12 +101,6 @@ import { All, RoutedVaultFilterModel, } from "../individual-vault/vault-filter/shared/models/routed-vault-filter.model"; -import { - openViewCipherDialog, - ViewCipherDialogCloseResult, - ViewCipherDialogResult, - ViewComponent, -} from "../individual-vault/view.component"; import { VaultHeaderComponent } from "../org-vault/vault-header/vault-header.component"; import { getNestedCollectionTree } from "../utils/collection-utils"; @@ -106,8 +112,8 @@ import { } from "./bulk-collections-dialog"; import { CollectionAccessRestrictedComponent } from "./collection-access-restricted.component"; import { openOrgVaultCollectionsDialog } from "./collections.component"; +import { AdminConsoleCipherFormConfigService } from "./services/admin-console-cipher-form-config.service"; import { VaultFilterModule } from "./vault-filter/vault-filter.module"; - const BroadcasterSubscriptionId = "OrgVaultComponent"; const SearchTextDebounceInterval = 200; @@ -127,9 +133,12 @@ enum AddAccessStatusType { VaultItemsModule, SharedModule, NoItemsModule, - ViewComponent, ], - providers: [RoutedVaultFilterService, RoutedVaultFilterBridgeService], + providers: [ + RoutedVaultFilterService, + RoutedVaultFilterBridgeService, + { provide: CipherFormConfigService, useClass: AdminConsoleCipherFormConfigService }, + ], }) export class VaultComponent implements OnInit, OnDestroy { protected Unassigned = Unassigned; @@ -174,6 +183,8 @@ export class VaultComponent implements OnInit, OnDestroy { private refresh$ = new BehaviorSubject(null); private destroy$ = new Subject(); protected addAccessStatus$ = new BehaviorSubject(0); + private extensionRefreshEnabled: boolean; + private vaultItemDialogRef?: DialogRef | undefined; constructor( private route: ActivatedRoute, @@ -203,10 +214,15 @@ export class VaultComponent implements OnInit, OnDestroy { private apiService: ApiService, private collectionService: CollectionService, private toastService: ToastService, - private accountService: AccountService, + private configService: ConfigService, + private cipherFormConfigService: CipherFormConfigService, ) {} async ngOnInit() { + this.extensionRefreshEnabled = await this.configService.getFeatureFlag( + FeatureFlag.ExtensionRefresh, + ); + this.trashCleanupWarning = this.i18nService.t( this.platformUtilsService.isSelfHost() ? "trashCleanupWarningSelfHosted" @@ -466,22 +482,27 @@ export class VaultComponent implements OnInit, OnDestroy { firstSetup$ .pipe( switchMap(() => this.route.queryParams), + // Only process the queryParams if the dialog is not open (only when extension refresh is enabled) + filter(() => this.vaultItemDialogRef == undefined || !this.extensionRefreshEnabled), withLatestFrom(allCipherMap$, allCollections$, organization$), - switchMap(async ([qParams, allCiphersMap, allCollections]) => { + switchMap(async ([qParams, allCiphersMap]) => { const cipherId = getCipherIdFromParams(qParams); if (!cipherId) { return; } const cipher = allCiphersMap[cipherId]; - const cipherCollections = allCollections.filter((c) => - cipher.collectionIds.includes(c.id), - ); if (cipher) { - if (qParams.action === "view") { - await this.viewCipher(cipher, cipherCollections); + let action = qParams.action; + // Default to "view" if extension refresh is enabled + if (action == null && this.extensionRefreshEnabled) { + action = "view"; + } + + if (action === "view") { + await this.viewCipherById(cipher); } else { - await this.editCipherId(cipherId); + await this.editCipherId(cipher, false); } } else { this.toastService.showToast({ @@ -730,12 +751,16 @@ export class VaultComponent implements OnInit, OnDestroy { } async addCipher(cipherType?: CipherType) { + if (this.extensionRefreshEnabled) { + return this.addCipherV2(cipherType); + } + let collections: CollectionView[] = []; // Admins limited to only adding items to collections they have access to. collections = await firstValueFrom(this.editableCollections$); - await this.editCipher(null, (comp) => { + await this.editCipher(null, false, (comp) => { comp.type = cipherType || this.activeFilter.cipherType; comp.collections = collections; if (this.activeFilter.collectionId) { @@ -744,20 +769,46 @@ export class VaultComponent implements OnInit, OnDestroy { }); } + /** Opens the Add/Edit Dialog. Only to be used when the BrowserExtension feature flag is active */ + async addCipherV2(cipherType?: CipherType) { + const cipherFormConfig = await this.cipherFormConfigService.buildConfig( + "add", + null, + cipherType, + ); + + const collectionId: CollectionId | undefined = this.activeFilter.collectionId as CollectionId; + + cipherFormConfig.initialValues = { + organizationId: this.organization.id as OrganizationId, + collectionIds: collectionId ? [collectionId] : [], + }; + + await this.openVaultItemDialog("form", cipherFormConfig); + } + + /** + * Edit the given cipher + * @param cipherView - The cipher to be edited + * @param cloneCipher - `true` when the cipher should be cloned. + * Used in place of the `additionalComponentParameters`, as + * the `editCipherIdV2` method has a differing implementation. + * @param defaultComponentParameters - A method that takes in an instance of + * the `AddEditComponent` to edit methods directly. + */ async editCipher( cipher: CipherView, + cloneCipher: boolean, additionalComponentParameters?: (comp: AddEditComponent) => void, ) { - return this.editCipherId(cipher?.id, additionalComponentParameters); + return this.editCipherId(cipher, cloneCipher, additionalComponentParameters); } async editCipherId( - cipherId: string, + cipher: CipherView, + cloneCipher: boolean, additionalComponentParameters?: (comp: AddEditComponent) => void, ) { - const cipher = await this.cipherService.get(cipherId); - // if cipher exists (cipher is null when new) and MP reprompt - // is on for this cipher, then show password reprompt if ( cipher && cipher.reprompt !== 0 && @@ -768,10 +819,15 @@ export class VaultComponent implements OnInit, OnDestroy { return; } + if (this.extensionRefreshEnabled) { + await this.editCipherIdV2(cipher, cloneCipher); + return; + } + const defaultComponentParameters = (comp: AddEditComponent) => { comp.organization = this.organization; comp.organizationId = this.organization.id; - comp.cipherId = cipherId; + comp.cipherId = cipher.id; comp.onSavedCipher.pipe(takeUntil(this.destroy$)).subscribe(() => { modal.close(); this.refresh(); @@ -807,46 +863,70 @@ export class VaultComponent implements OnInit, OnDestroy { } /** - * Takes a cipher and its assigned collections to opens dialog where it can be viewed. - * @param cipher - the cipher to view - * @param collections - the collections the cipher is assigned to + * Edit a cipher using the new AddEditCipherDialogV2 component. + * Only to be used behind the ExtensionRefresh feature flag. */ - async viewCipher(cipher: CipherView, collections: CollectionView[] = []) { + private async editCipherIdV2(cipher: CipherView, cloneCipher: boolean) { + const cipherFormConfig = await this.cipherFormConfigService.buildConfig( + cloneCipher ? "clone" : "edit", + cipher.id as CipherId, + ); + + await this.openVaultItemDialog("form", cipherFormConfig, cipher); + } + + /** Opens the view dialog for the given cipher unless password reprompt fails */ + async viewCipherById(cipher: CipherView) { if (!cipher) { - this.go({ cipherId: null, itemId: null }); return; } - if (cipher.reprompt !== 0 && !(await this.passwordRepromptService.showPasswordPrompt())) { - // didn't pass password prompt, so don't open the dialog - this.go({ cipherId: null, itemId: null }); + if ( + cipher && + cipher.reprompt !== 0 && + !(await this.passwordRepromptService.showPasswordPrompt()) + ) { + // Didn't pass password prompt, so don't open add / edit modal. + await this.go({ cipherId: null, itemId: null, action: null }); return; } - const dialogRef = openViewCipherDialog(this.dialogService, { - data: { - cipher: cipher, - collections: collections, - disableEdit: !cipher.edit && !this.organization.canEditAllCiphers, - }, + const cipherFormConfig = await this.cipherFormConfigService.buildConfig( + "edit", + cipher.id as CipherId, + cipher.type, + ); + + await this.openVaultItemDialog("view", cipherFormConfig, cipher); + } + + /** + * Open the combined view / edit dialog for a cipher. + */ + async openVaultItemDialog( + mode: VaultItemDialogMode, + formConfig: CipherFormConfig, + cipher?: CipherView, + ) { + const disableForm = cipher ? !cipher.edit && !this.organization.canEditAllCiphers : false; + // If the form is disabled, force the mode into `view` + const dialogMode = disableForm ? "view" : mode; + this.vaultItemDialogRef = VaultItemDialogComponent.open(this.dialogService, { + mode: dialogMode, + formConfig, + disableForm, }); - // Wait for the dialog to close. - const result: ViewCipherDialogCloseResult = await lastValueFrom(dialogRef.closed); - - // If the dialog was closed by clicking the edit button, navigate to open the edit dialog. - if (result?.action === ViewCipherDialogResult.Edited) { - this.go({ itemId: cipher.id, action: "edit" }); - return; - } + const result = await lastValueFrom(this.vaultItemDialogRef.closed); + this.vaultItemDialogRef = undefined; // If the dialog was closed by deleting the cipher, refresh the vault. - if (result?.action === ViewCipherDialogResult.Deleted) { + if (result === VaultItemDialogResult.Deleted || result === VaultItemDialogResult.Saved) { this.refresh(); } - // Clear the query params when the view dialog closes - this.go({ cipherId: null, itemId: null, action: null }); + // Clear the query params when the dialog closes + await this.go({ cipherId: null, itemId: null, action: null }); } async cloneCipher(cipher: CipherView) { @@ -867,7 +947,7 @@ export class VaultComponent implements OnInit, OnDestroy { // Admins limited to only adding items to collections they have access to. collections = await firstValueFrom(this.editableCollections$); - await this.editCipher(cipher, (comp) => { + await this.editCipher(cipher, true, (comp) => { comp.cloneMode = true; comp.collections = collections; comp.collectionIds = cipher.collectionIds; diff --git a/libs/vault/src/cipher-form/abstractions/cipher-form-config.service.ts b/libs/vault/src/cipher-form/abstractions/cipher-form-config.service.ts index 25c0e41124..28c18b3665 100644 --- a/libs/vault/src/cipher-form/abstractions/cipher-form-config.service.ts +++ b/libs/vault/src/cipher-form/abstractions/cipher-form-config.service.ts @@ -79,6 +79,9 @@ type BaseCipherFormConfig = { * List of organizations that the user can create ciphers for. */ organizations?: Organization[]; + + /** Hides the fields that are only applicable to individuals, useful in the Admin Console where folders aren't applicable */ + hideIndividualVaultFields?: true; }; /** diff --git a/libs/vault/src/cipher-form/components/item-details/item-details-section.component.html b/libs/vault/src/cipher-form/components/item-details/item-details-section.component.html index 26f7f7fd9e..6c6bd8a801 100644 --- a/libs/vault/src/cipher-form/components/item-details/item-details-section.component.html +++ b/libs/vault/src/cipher-form/components/item-details/item-details-section.component.html @@ -2,6 +2,7 @@

{{ "itemDetails" | i18n }}