From 1f850363463ad7bfb730d83449817a2c250b5b60 Mon Sep 17 00:00:00 2001 From: Thomas Rittson <31796059+eliykat@users.noreply.github.com> Date: Tue, 1 Oct 2024 07:13:26 +1000 Subject: [PATCH 01/15] [PM-3478] Refactor OrganizationUser api (#10949) * User and Group collection dialogs - don't fetch additional associations from the api * Refactor to use user mini-details endpoint --- .../service-container/service-container.ts | 7 +++- .../manage/entity-events.component.ts | 2 +- .../organizations/manage/events.component.ts | 4 +- .../manage/group-add-edit.component.ts | 2 +- .../collection-dialog.component.ts | 42 +++++++++++-------- .../bulk-collections-dialog.component.ts | 2 +- .../app/vault/org-vault/vault.component.ts | 14 ------- .../organization-user-api.service.ts | 15 ++++++- .../models/responses/index.ts | 1 + .../organization-user-mini.response.ts | 24 +++++++++++ .../default-organization-user-api.service.ts | 31 +++++++++++++- .../src/services/jslib-services.module.ts | 2 +- libs/common/src/enums/feature-flag.enum.ts | 2 + 13 files changed, 107 insertions(+), 41 deletions(-) create mode 100644 libs/admin-console/src/common/organization-user/models/responses/organization-user-mini.response.ts diff --git a/apps/cli/src/service-container/service-container.ts b/apps/cli/src/service-container/service-container.ts index 6f19081a736..2149b74f614 100644 --- a/apps/cli/src/service-container/service-container.ts +++ b/apps/cli/src/service-container/service-container.ts @@ -498,8 +498,6 @@ export class ServiceContainer { this.providerService = new ProviderService(this.stateProvider); - this.organizationUserApiService = new DefaultOrganizationUserApiService(this.apiService); - this.policyApiService = new PolicyApiService(this.policyService, this.apiService); this.keyConnectorService = new KeyConnectorService( @@ -778,6 +776,11 @@ export class ServiceContainer { this.organizationApiService = new OrganizationApiService(this.apiService, this.syncService); this.providerApiService = new ProviderApiService(this.apiService); + + this.organizationUserApiService = new DefaultOrganizationUserApiService( + this.apiService, + this.configService, + ); } async logout() { diff --git a/apps/web/src/app/admin-console/organizations/manage/entity-events.component.ts b/apps/web/src/app/admin-console/organizations/manage/entity-events.component.ts index 79ada2b7a53..2caf2e76b72 100644 --- a/apps/web/src/app/admin-console/organizations/manage/entity-events.component.ts +++ b/apps/web/src/app/admin-console/organizations/manage/entity-events.component.ts @@ -78,7 +78,7 @@ export class EntityEventsComponent implements OnInit { async load() { try { if (this.showUser) { - const response = await this.organizationUserApiService.getAllUsers( + const response = await this.organizationUserApiService.getAllMiniUserDetails( this.params.organizationId, ); response.data.forEach((u) => { diff --git a/apps/web/src/app/admin-console/organizations/manage/events.component.ts b/apps/web/src/app/admin-console/organizations/manage/events.component.ts index 574335125e6..ef9d5c32d90 100644 --- a/apps/web/src/app/admin-console/organizations/manage/events.component.ts +++ b/apps/web/src/app/admin-console/organizations/manage/events.component.ts @@ -83,7 +83,9 @@ export class EventsComponent extends BaseEventsComponent implements OnInit, OnDe } async load() { - const response = await this.organizationUserApiService.getAllUsers(this.organizationId); + const response = await this.organizationUserApiService.getAllMiniUserDetails( + this.organizationId, + ); response.data.forEach((u) => { const name = this.userNamePipe.transform(u); this.orgUsersUserIdMap.set(u.userId, { name: name, email: u.email }); diff --git a/apps/web/src/app/admin-console/organizations/manage/group-add-edit.component.ts b/apps/web/src/app/admin-console/organizations/manage/group-add-edit.component.ts index 36489e0ab1d..cdbc049111d 100644 --- a/apps/web/src/app/admin-console/organizations/manage/group-add-edit.component.ts +++ b/apps/web/src/app/admin-console/organizations/manage/group-add-edit.component.ts @@ -131,7 +131,7 @@ export class GroupAddEditComponent implements OnInit, OnDestroy { ); private get orgMembers$(): Observable> { - return from(this.organizationUserApiService.getAllUsers(this.organizationId)).pipe( + return from(this.organizationUserApiService.getAllMiniUserDetails(this.organizationId)).pipe( map((response) => response.data.map((m) => ({ id: m.id, diff --git a/apps/web/src/app/vault/components/collection-dialog/collection-dialog.component.ts b/apps/web/src/app/vault/components/collection-dialog/collection-dialog.component.ts index 9dc8a3c0df1..5c46a7a0296 100644 --- a/apps/web/src/app/vault/components/collection-dialog/collection-dialog.component.ts +++ b/apps/web/src/app/vault/components/collection-dialog/collection-dialog.component.ts @@ -15,7 +15,7 @@ import { first } from "rxjs/operators"; import { OrganizationUserApiService, - OrganizationUserUserDetailsResponse, + OrganizationUserUserMiniResponse, } from "@bitwarden/admin-console/common"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; @@ -156,15 +156,23 @@ export class CollectionDialogComponent implements OnInit, OnDestroy { organization: organization$, collections: this.collectionAdminService.getAll(orgId), groups: groups$, - // Collection(s) needed to map readonlypermission for (potential) access selector disabled state - users: this.organizationUserApiService.getAllUsers(orgId, { includeCollections: true }), + users: this.organizationUserApiService.getAllMiniUserDetails(orgId), }) .pipe(takeUntil(this.formGroup.controls.selectedOrg.valueChanges), takeUntil(this.destroy$)) .subscribe(({ organization, collections: allCollections, groups, users }) => { this.organization = organization; + + if (this.params.collectionId) { + this.collection = allCollections.find((c) => c.id === this.collectionId); + + if (!this.collection) { + throw new Error("Could not find collection to edit."); + } + } + this.accessItems = [].concat( - groups.map((group) => mapGroupToAccessItemView(group, this.collectionId)), - users.data.map((user) => mapUserToAccessItemView(user, this.collectionId)), + groups.map((group) => mapGroupToAccessItemView(group, this.collection)), + users.data.map((user) => mapUserToAccessItemView(user, this.collection)), ); // Force change detection to update the access selector's items @@ -174,15 +182,10 @@ export class CollectionDialogComponent implements OnInit, OnDestroy { ? allCollections.filter((c) => c.manage) : allCollections; - if (this.params.collectionId) { - this.collection = allCollections.find((c) => c.id === this.collectionId); + if (this.collection) { // Ensure we don't allow nesting the current collection within itself this.nestOptions = this.nestOptions.filter((c) => c.id !== this.collectionId); - if (!this.collection) { - throw new Error("Could not find collection to edit."); - } - // Parse the name to find its parent name const { name, parent: parentName } = parseName(this.collection); @@ -423,7 +426,10 @@ function validateCanManagePermission(control: AbstractControl) { * @param collectionId Current collection being viewed/edited * @returns AccessItemView customized to set a readonlyPermission to be displayed if the access selector is in a disabled state */ -function mapGroupToAccessItemView(group: GroupView, collectionId: string): AccessItemView { +function mapGroupToAccessItemView( + group: GroupView, + collection: CollectionAdminView, +): AccessItemView { return { id: group.id, type: AccessItemType.Group, @@ -431,8 +437,8 @@ function mapGroupToAccessItemView(group: GroupView, collectionId: string): Acces labelName: group.name, readonly: false, readonlyPermission: - collectionId != null - ? convertToPermission(group.collections.find((gc) => gc.id == collectionId)) + collection != null + ? convertToPermission(collection.groups.find((g) => g.id === group.id)) : undefined, }; } @@ -444,8 +450,8 @@ function mapGroupToAccessItemView(group: GroupView, collectionId: string): Acces * @returns AccessItemView customized to set a readonlyPermission to be displayed if the access selector is in a disabled state */ function mapUserToAccessItemView( - user: OrganizationUserUserDetailsResponse, - collectionId: string, + user: OrganizationUserUserMiniResponse, + collection: CollectionAdminView, ): AccessItemView { return { id: user.id, @@ -457,9 +463,9 @@ function mapUserToAccessItemView( status: user.status, readonly: false, readonlyPermission: - collectionId != null + collection != null ? convertToPermission( - new CollectionAccessSelectionView(user.collections.find((uc) => uc.id == collectionId)), + new CollectionAccessSelectionView(collection.users.find((u) => u.id === user.id)), ) : undefined, }; diff --git a/apps/web/src/app/vault/org-vault/bulk-collections-dialog/bulk-collections-dialog.component.ts b/apps/web/src/app/vault/org-vault/bulk-collections-dialog/bulk-collections-dialog.component.ts index 76e90097d19..c4b0d8bc2a2 100644 --- a/apps/web/src/app/vault/org-vault/bulk-collections-dialog/bulk-collections-dialog.component.ts +++ b/apps/web/src/app/vault/org-vault/bulk-collections-dialog/bulk-collections-dialog.component.ts @@ -79,7 +79,7 @@ export class BulkCollectionsDialogComponent implements OnDestroy { combineLatest([ organization$, groups$, - this.organizationUserApiService.getAllUsers(this.params.organizationId), + this.organizationUserApiService.getAllMiniUserDetails(this.params.organizationId), ]) .pipe(takeUntil(this.destroy$)) .subscribe(([organization, groups, users]) => { 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 2976bfc8c2f..3120b54ed38 100644 --- a/apps/web/src/app/vault/org-vault/vault.component.ts +++ b/apps/web/src/app/vault/org-vault/vault.component.ts @@ -30,10 +30,6 @@ import { withLatestFrom, } from "rxjs/operators"; -import { - OrganizationUserApiService, - OrganizationUserUserDetailsResponse, -} from "@bitwarden/admin-console/common"; import { SearchPipe } from "@bitwarden/angular/pipes/search.pipe"; import { ModalService } from "@bitwarden/angular/services/modal.service"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; @@ -168,8 +164,6 @@ export class VaultComponent implements OnInit, OnDestroy { protected editableCollections$: Observable; protected allCollectionsWithoutUnassigned$: Observable; - protected orgRevokedUsers: OrganizationUserUserDetailsResponse[]; - protected get hideVaultFilters(): boolean { return this.organization?.isProviderUser && !this.organization?.isMember; } @@ -206,7 +200,6 @@ export class VaultComponent implements OnInit, OnDestroy { private totpService: TotpService, private apiService: ApiService, private collectionService: CollectionService, - private organizationUserApiService: OrganizationUserApiService, private toastService: ToastService, private accountService: AccountService, ) {} @@ -358,13 +351,6 @@ export class VaultComponent implements OnInit, OnDestroy { shareReplay({ refCount: true, bufferSize: 1 }), ); - // This will be passed into the usersCanManage call - this.orgRevokedUsers = ( - await this.organizationUserApiService.getAllUsers(await firstValueFrom(organizationId$)) - ).data.filter((user: OrganizationUserUserDetailsResponse) => { - return user.status === -1; - }); - const collections$ = combineLatest([ nestedCollections$, filter$, diff --git a/libs/admin-console/src/common/organization-user/abstractions/organization-user-api.service.ts b/libs/admin-console/src/common/organization-user/abstractions/organization-user-api.service.ts index ea5d2185ee2..ff7f9c5df6c 100644 --- a/libs/admin-console/src/common/organization-user/abstractions/organization-user-api.service.ts +++ b/libs/admin-console/src/common/organization-user/abstractions/organization-user-api.service.ts @@ -16,6 +16,7 @@ import { OrganizationUserDetailsResponse, OrganizationUserResetPasswordDetailsResponse, OrganizationUserUserDetailsResponse, + OrganizationUserUserMiniResponse, } from "../models/responses"; /** @@ -44,7 +45,9 @@ export abstract class OrganizationUserApiService { abstract getOrganizationUserGroups(organizationId: string, id: string): Promise; /** - * Retrieve a list of all users that belong to the specified organization + * Retrieve full details of all users that belong to the specified organization. + * This is only accessible to privileged users, if you need a simple listing of basic details, use + * {@link getAllMiniUserDetails}. * @param organizationId - Identifier for the organization * @param options - Options for the request */ @@ -56,6 +59,16 @@ export abstract class OrganizationUserApiService { }, ): Promise>; + /** + * Retrieve a list of all users that belong to the specified organization, with basic information only. + * This is suitable for lists of names/emails etc. throughout the app and can be accessed by most users. + * @param organizationId - Identifier for the organization + * @param options - Options for the request + */ + abstract getAllMiniUserDetails( + organizationId: string, + ): Promise>; + /** * Retrieve reset password details for the specified organization user * @param organizationId - Identifier for the user's organization diff --git a/libs/admin-console/src/common/organization-user/models/responses/index.ts b/libs/admin-console/src/common/organization-user/models/responses/index.ts index 29c82fb18b3..aa0a968f71a 100644 --- a/libs/admin-console/src/common/organization-user/models/responses/index.ts +++ b/libs/admin-console/src/common/organization-user/models/responses/index.ts @@ -1,3 +1,4 @@ export * from "./organization-user.response"; export * from "./organization-user-bulk.response"; export * from "./organization-user-bulk-public-key.response"; +export * from "./organization-user-mini.response"; diff --git a/libs/admin-console/src/common/organization-user/models/responses/organization-user-mini.response.ts b/libs/admin-console/src/common/organization-user/models/responses/organization-user-mini.response.ts new file mode 100644 index 00000000000..6ca1bace401 --- /dev/null +++ b/libs/admin-console/src/common/organization-user/models/responses/organization-user-mini.response.ts @@ -0,0 +1,24 @@ +import { + OrganizationUserStatusType, + OrganizationUserType, +} from "@bitwarden/common/admin-console/enums"; +import { BaseResponse } from "@bitwarden/common/models/response/base.response"; + +export class OrganizationUserUserMiniResponse extends BaseResponse { + id: string; + userId: string; + email: string; + name: string; + type: OrganizationUserType; + status: OrganizationUserStatusType; + + constructor(response: any) { + super(response); + this.id = this.getResponseProperty("Id"); + this.userId = this.getResponseProperty("UserId"); + this.email = this.getResponseProperty("Email"); + this.name = this.getResponseProperty("Name"); + this.type = this.getResponseProperty("Type"); + this.status = this.getResponseProperty("Status"); + } +} diff --git a/libs/admin-console/src/common/organization-user/services/default-organization-user-api.service.ts b/libs/admin-console/src/common/organization-user/services/default-organization-user-api.service.ts index 40824550d44..a6438b8b5ff 100644 --- a/libs/admin-console/src/common/organization-user/services/default-organization-user-api.service.ts +++ b/libs/admin-console/src/common/organization-user/services/default-organization-user-api.service.ts @@ -1,5 +1,9 @@ +import { firstValueFrom } from "rxjs"; + import { ApiService } from "@bitwarden/common/abstractions/api.service"; +import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; +import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { OrganizationUserApiService } from "../abstractions"; import { @@ -19,10 +23,14 @@ import { OrganizationUserDetailsResponse, OrganizationUserResetPasswordDetailsResponse, OrganizationUserUserDetailsResponse, + OrganizationUserUserMiniResponse, } from "../models/responses"; export class DefaultOrganizationUserApiService implements OrganizationUserApiService { - constructor(private apiService: ApiService) {} + constructor( + private apiService: ApiService, + private configService: ConfigService, + ) {} async getOrganizationUser( organizationId: string, @@ -84,6 +92,27 @@ export class DefaultOrganizationUserApiService implements OrganizationUserApiSer return new ListResponse(r, OrganizationUserUserDetailsResponse); } + async getAllMiniUserDetails( + organizationId: string, + ): Promise> { + const apiEnabled = await firstValueFrom( + this.configService.getFeatureFlag$(FeatureFlag.Pm3478RefactorOrganizationUserApi), + ); + if (!apiEnabled) { + // Keep using the old api until this feature flag is enabled + return this.getAllUsers(organizationId); + } + + const r = await this.apiService.send( + "GET", + `/organizations/${organizationId}/users/mini-details`, + null, + true, + true, + ); + return new ListResponse(r, OrganizationUserUserMiniResponse); + } + async getOrganizationUserResetPasswordDetails( organizationId: string, id: string, diff --git a/libs/angular/src/services/jslib-services.module.ts b/libs/angular/src/services/jslib-services.module.ts index 1ebaf343066..0cc6e74d5b0 100644 --- a/libs/angular/src/services/jslib-services.module.ts +++ b/libs/angular/src/services/jslib-services.module.ts @@ -952,7 +952,7 @@ const safeProviders: SafeProvider[] = [ safeProvider({ provide: OrganizationUserApiService, useClass: DefaultOrganizationUserApiService, - deps: [ApiServiceAbstraction], + deps: [ApiServiceAbstraction, ConfigService], }), safeProvider({ provide: PasswordResetEnrollmentServiceAbstraction, diff --git a/libs/common/src/enums/feature-flag.enum.ts b/libs/common/src/enums/feature-flag.enum.ts index 505fe33e82a..2b7d2bea334 100644 --- a/libs/common/src/enums/feature-flag.enum.ts +++ b/libs/common/src/enums/feature-flag.enum.ts @@ -34,6 +34,7 @@ export enum FeatureFlag { AC2476_DeprecateStripeSourcesAPI = "AC-2476-deprecate-stripe-sources-api", CipherKeyEncryption = "cipher-key-encryption", PM11901_RefactorSelfHostingLicenseUploader = "PM-11901-refactor-self-hosting-license-uploader", + Pm3478RefactorOrganizationUserApi = "pm-3478-refactor-organizationuser-api", } export type AllowedFeatureFlagTypes = boolean | number | string; @@ -78,6 +79,7 @@ export const DefaultFeatureFlagValue = { [FeatureFlag.AC2476_DeprecateStripeSourcesAPI]: FALSE, [FeatureFlag.CipherKeyEncryption]: FALSE, [FeatureFlag.PM11901_RefactorSelfHostingLicenseUploader]: FALSE, + [FeatureFlag.Pm3478RefactorOrganizationUserApi]: FALSE, } satisfies Record; export type DefaultFeatureFlagValueType = typeof DefaultFeatureFlagValue; From 9a9b41a5da287ae2911614c5a866a4d248d1dcb8 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Mon, 30 Sep 2024 23:18:05 +0200 Subject: [PATCH 02/15] [deps] Tools: Update jsdom to v25 (#10742) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- apps/cli/package.json | 2 +- package-lock.json | 26 +++++++++++++++++++------- package.json | 2 +- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/apps/cli/package.json b/apps/cli/package.json index c5a28316cfd..ac0e171b94f 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -66,7 +66,7 @@ "form-data": "4.0.0", "https-proxy-agent": "7.0.5", "inquirer": "8.2.6", - "jsdom": "24.1.3", + "jsdom": "25.0.1", "jszip": "3.10.1", "koa": "2.15.0", "koa-bodyparser": "4.4.1", diff --git a/package-lock.json b/package-lock.json index 4163ead080d..218e5f53a1f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -43,7 +43,7 @@ "https-proxy-agent": "7.0.5", "inquirer": "8.2.6", "jquery": "3.7.1", - "jsdom": "24.1.3", + "jsdom": "25.0.1", "jszip": "3.10.1", "koa": "2.15.0", "koa-bodyparser": "4.4.1", @@ -209,7 +209,7 @@ "form-data": "4.0.0", "https-proxy-agent": "7.0.5", "inquirer": "8.2.6", - "jsdom": "24.1.3", + "jsdom": "25.0.1", "jszip": "3.10.1", "koa": "2.15.0", "koa-bodyparser": "4.4.1", @@ -24701,12 +24701,12 @@ } }, "node_modules/jsdom": { - "version": "24.1.3", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-24.1.3.tgz", - "integrity": "sha512-MyL55p3Ut3cXbeBEG7Hcv0mVM8pp8PBNWxRqchZnSfAiES1v1mRnMeFfaHWIPULpwsYfvO+ZmMZz5tGCnjzDUQ==", + "version": "25.0.1", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-25.0.1.tgz", + "integrity": "sha512-8i7LzZj7BF8uplX+ZyOlIz86V6TAsSs+np6m1kpW9u0JWi4z/1t+FzcK1aek+ybTnAC4KhBL4uXCNT0wcUIeCw==", "license": "MIT", "dependencies": { - "cssstyle": "^4.0.1", + "cssstyle": "^4.1.0", "data-urls": "^5.0.0", "decimal.js": "^10.4.3", "form-data": "^4.0.0", @@ -24719,7 +24719,7 @@ "rrweb-cssom": "^0.7.1", "saxes": "^6.0.0", "symbol-tree": "^3.2.4", - "tough-cookie": "^4.1.4", + "tough-cookie": "^5.0.0", "w3c-xmlserializer": "^5.0.0", "webidl-conversions": "^7.0.0", "whatwg-encoding": "^3.1.1", @@ -24765,6 +24765,18 @@ "node": ">= 14" } }, + "node_modules/jsdom/node_modules/tough-cookie": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.0.0.tgz", + "integrity": "sha512-FRKsF7cz96xIIeMZ82ehjC3xW2E+O2+v11udrDYewUbszngYhsGa8z6YUMMzO9QJZzzyd0nGGXnML/TReX6W8Q==", + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^6.1.32" + }, + "engines": { + "node": ">=16" + } + }, "node_modules/jsesc": { "version": "2.5.2", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", diff --git a/package.json b/package.json index 8b8f3ed70a4..b9304f0aa87 100644 --- a/package.json +++ b/package.json @@ -176,7 +176,7 @@ "https-proxy-agent": "7.0.5", "inquirer": "8.2.6", "jquery": "3.7.1", - "jsdom": "24.1.3", + "jsdom": "25.0.1", "jszip": "3.10.1", "koa": "2.15.0", "koa-bodyparser": "4.4.1", From 0ae672fc0cc7a3b98f9a03973db9d5b12f9cefd9 Mon Sep 17 00:00:00 2001 From: Alec Rippberger <127791530+alec-livefront@users.noreply.github.com> Date: Mon, 30 Sep 2024 21:46:36 -0500 Subject: [PATCH 03/15] Add missing translation strings. (#11274) --- apps/web/src/locales/en/messages.json | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/apps/web/src/locales/en/messages.json b/apps/web/src/locales/en/messages.json index 63dbd6ff9ce..8e847dfb63e 100644 --- a/apps/web/src/locales/en/messages.json +++ b/apps/web/src/locales/en/messages.json @@ -6591,6 +6591,18 @@ } } }, + "singleFieldNeedsAttention": { + "message": "1 field needs your attention." + }, + "multipleFieldsNeedAttention": { + "message": "$COUNT$ fields need your attention.", + "placeholders": { + "count": { + "content": "$1", + "example": "2" + } + } + }, "duoHealthCheckResultsInNullAuthUrlError": { "message": "Error connecting with the Duo service. Use a different two-step login method or contact Duo for assistance." }, From 5a1583cb0a42b001dfcf0803776045984d86d608 Mon Sep 17 00:00:00 2001 From: Jordan Aasen <166539328+jaasen-livefront@users.noreply.github.com> Date: Tue, 1 Oct 2024 02:36:34 -0700 Subject: [PATCH 04/15] [PM-12732] - fix new send button (#11266) * fix new send button * simplify logic. use static class name where possible --- apps/browser/src/tools/popup/send-v2/send-v2.component.html | 6 +++++- .../src/new-send-dropdown/new-send-dropdown.component.html | 4 ++-- .../src/new-send-dropdown/new-send-dropdown.component.ts | 4 +++- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/apps/browser/src/tools/popup/send-v2/send-v2.component.html b/apps/browser/src/tools/popup/send-v2/send-v2.component.html index 23582f19115..0baa43a4b56 100644 --- a/apps/browser/src/tools/popup/send-v2/send-v2.component.html +++ b/apps/browser/src/tools/popup/send-v2/send-v2.component.html @@ -23,7 +23,11 @@ {{ "sendsNoItemsTitle" | i18n }} {{ "sendsNoItemsMessage" | i18n }} - + diff --git a/libs/tools/send/send-ui/src/new-send-dropdown/new-send-dropdown.component.html b/libs/tools/send/send-ui/src/new-send-dropdown/new-send-dropdown.component.html index f1f0363c999..75334b68ef9 100644 --- a/libs/tools/send/send-ui/src/new-send-dropdown/new-send-dropdown.component.html +++ b/libs/tools/send/send-ui/src/new-send-dropdown/new-send-dropdown.component.html @@ -1,6 +1,6 @@ diff --git a/libs/tools/send/send-ui/src/new-send-dropdown/new-send-dropdown.component.ts b/libs/tools/send/send-ui/src/new-send-dropdown/new-send-dropdown.component.ts index 620dc77c995..7dbe184d981 100644 --- a/libs/tools/send/send-ui/src/new-send-dropdown/new-send-dropdown.component.ts +++ b/libs/tools/send/send-ui/src/new-send-dropdown/new-send-dropdown.component.ts @@ -1,5 +1,5 @@ import { CommonModule } from "@angular/common"; -import { Component, OnInit } from "@angular/core"; +import { Component, Input, OnInit } from "@angular/core"; import { Router, RouterLink } from "@angular/router"; import { firstValueFrom } from "rxjs"; @@ -15,6 +15,8 @@ import { BadgeModule, ButtonModule, MenuModule } from "@bitwarden/components"; imports: [JslibModule, CommonModule, ButtonModule, RouterLink, MenuModule, BadgeModule], }) export class NewSendDropdownComponent implements OnInit { + @Input() hideIcon: boolean = false; + sendType = SendType; hasNoPremium = false; From 3059662482652b229accf3341863a53f4b0e7dda Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 1 Oct 2024 12:43:19 +0200 Subject: [PATCH 05/15] [deps] Tools: Update @electron/notarize to v2.5.0 (#11323) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: Daniel James Smith <2670567+djsmith85@users.noreply.github.com> --- package-lock.json | 8 ++++---- package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/package-lock.json b/package-lock.json index 218e5f53a1f..d760d36e573 100644 --- a/package-lock.json +++ b/package-lock.json @@ -82,7 +82,7 @@ "@babel/core": "7.24.9", "@babel/preset-env": "7.24.8", "@compodoc/compodoc": "1.1.25", - "@electron/notarize": "2.4.0", + "@electron/notarize": "2.5.0", "@electron/rebuild": "3.6.0", "@ngtools/webpack": "16.2.14", "@storybook/addon-a11y": "8.2.9", @@ -5194,9 +5194,9 @@ } }, "node_modules/@electron/notarize": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-2.4.0.tgz", - "integrity": "sha512-ArHnRPIJJGrmV+uWNQSINAht+cM4gAo3uA3WFI54bYF93mzmD15gzhPQ0Dd+v/fkMhnRiiIO8NNkGdn87Vsy0g==", + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@electron/notarize/-/notarize-2.5.0.tgz", + "integrity": "sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index b9304f0aa87..b1e69fca494 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,7 @@ "@babel/core": "7.24.9", "@babel/preset-env": "7.24.8", "@compodoc/compodoc": "1.1.25", - "@electron/notarize": "2.4.0", + "@electron/notarize": "2.5.0", "@electron/rebuild": "3.6.0", "@ngtools/webpack": "16.2.14", "@storybook/addon-a11y": "8.2.9", From 0846c2c822eec75eb68fa2a705fef725b25a2153 Mon Sep 17 00:00:00 2001 From: Andreas Coroiu Date: Tue, 1 Oct 2024 13:39:36 +0200 Subject: [PATCH 06/15] [PM-11780] Resolve TypeScript 5.3 compile error --- ...rowser-api.register-content-scripts-polyfill.ts | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/apps/browser/src/platform/browser/browser-api.register-content-scripts-polyfill.ts b/apps/browser/src/platform/browser/browser-api.register-content-scripts-polyfill.ts index 8a20f3e9997..b0dc60ed126 100644 --- a/apps/browser/src/platform/browser/browser-api.register-content-scripts-polyfill.ts +++ b/apps/browser/src/platform/browser/browser-api.register-content-scripts-polyfill.ts @@ -43,17 +43,23 @@ function buildRegisterContentScriptsPolyfill() { function NestedProxy(target: T): T { return new Proxy(target, { get(target, prop) { - if (!target[prop as keyof T]) { + const propertyValue = target[prop as keyof T]; + + if (!propertyValue) { return; } - if (typeof target[prop as keyof T] !== "function") { - return NestedProxy(target[prop as keyof T]); + if (typeof propertyValue === "object") { + return NestedProxy(propertyValue); + } + + if (typeof propertyValue !== "function") { + return propertyValue; } return (...arguments_: any[]) => new Promise((resolve, reject) => { - target[prop as keyof T](...arguments_, (result: any) => { + propertyValue(...arguments_, (result: any) => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { From 7108a34ac017c0259185452c6a72535d60e4ad53 Mon Sep 17 00:00:00 2001 From: Cesar Gonzalez Date: Tue, 1 Oct 2024 07:27:07 -0500 Subject: [PATCH 07/15] [PM-12619] Passkey script cleanup process triggers breaking behavior in websites (#11304) --- .../content/fido2-page-script-append.mv2.spec.ts | 15 --------------- .../fido2/content/fido2-page-script-append.mv2.ts | 5 ----- .../content/fido2-page-script-delay-append.mv2.ts | 5 ----- 3 files changed, 25 deletions(-) diff --git a/apps/browser/src/autofill/fido2/content/fido2-page-script-append.mv2.spec.ts b/apps/browser/src/autofill/fido2/content/fido2-page-script-append.mv2.spec.ts index f5f8dd770c7..6b9b41b5aac 100644 --- a/apps/browser/src/autofill/fido2/content/fido2-page-script-append.mv2.spec.ts +++ b/apps/browser/src/autofill/fido2/content/fido2-page-script-append.mv2.spec.ts @@ -57,19 +57,4 @@ describe("FIDO2 page-script for manifest v2", () => { ); expect(createdScriptElement.src).toBe(`chrome-extension://id/${Fido2ContentScript.PageScript}`); }); - - it("removes the appended `page-script.js` file after the script has triggered a load event", () => { - createdScriptElement = document.createElement("script"); - jest.spyOn(window.document, "createElement").mockImplementation((element) => { - return createdScriptElement; - }); - - require("./fido2-page-script-append.mv2"); - - jest.spyOn(createdScriptElement, "remove"); - createdScriptElement.dispatchEvent(new Event("load")); - jest.runAllTimers(); - - expect(createdScriptElement.remove).toHaveBeenCalled(); - }); }); diff --git a/apps/browser/src/autofill/fido2/content/fido2-page-script-append.mv2.ts b/apps/browser/src/autofill/fido2/content/fido2-page-script-append.mv2.ts index e5280c088bc..dd5f33dffb0 100644 --- a/apps/browser/src/autofill/fido2/content/fido2-page-script-append.mv2.ts +++ b/apps/browser/src/autofill/fido2/content/fido2-page-script-append.mv2.ts @@ -9,13 +9,8 @@ const script = globalContext.document.createElement("script"); script.src = chrome.runtime.getURL("content/fido2-page-script.js"); - script.addEventListener("load", removeScriptOnLoad); const scriptInsertionPoint = globalContext.document.head || globalContext.document.documentElement; scriptInsertionPoint.prepend(script); - - function removeScriptOnLoad() { - globalThis.setTimeout(() => script?.remove(), 5000); - } })(globalThis); diff --git a/apps/browser/src/autofill/fido2/content/fido2-page-script-delay-append.mv2.ts b/apps/browser/src/autofill/fido2/content/fido2-page-script-delay-append.mv2.ts index c75a37c1b65..2ada31fdfe2 100644 --- a/apps/browser/src/autofill/fido2/content/fido2-page-script-delay-append.mv2.ts +++ b/apps/browser/src/autofill/fido2/content/fido2-page-script-delay-append.mv2.ts @@ -9,7 +9,6 @@ const script = globalContext.document.createElement("script"); script.src = chrome.runtime.getURL("content/fido2-page-script.js"); - script.addEventListener("load", removeScriptOnLoad); // We are ensuring that the script injection is delayed in the event that we are loading // within an iframe element. This prevents an issue with web mail clients that load content @@ -29,8 +28,4 @@ globalContext.document.head || globalContext.document.documentElement; scriptInsertionPoint.prepend(script); } - - function removeScriptOnLoad() { - globalThis.setTimeout(() => script?.remove(), 5000); - } })(globalThis); From 2b78ac5151d39c5243a706c9974c40ba16077452 Mon Sep 17 00:00:00 2001 From: Alex Morask <144709477+amorask-bitwarden@users.noreply.github.com> Date: Tue, 1 Oct 2024 08:45:01 -0400 Subject: [PATCH 08/15] Show subscription status as active for premium if incomplete and within 15 seconds of creation (#11334) --- .../user-subscription.component.html | 2 +- .../individual/user-subscription.component.ts | 29 ++++++++++++++----- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/apps/web/src/app/billing/individual/user-subscription.component.html b/apps/web/src/app/billing/individual/user-subscription.component.html index 3430bddc134..eeb64ffe77d 100644 --- a/apps/web/src/app/billing/individual/user-subscription.component.html +++ b/apps/web/src/app/billing/individual/user-subscription.component.html @@ -42,7 +42,7 @@
{{ "status" | i18n }}
- {{ (subscription && subscription.status) || "-" }} + {{ (subscription && subscriptionStatus) || "-" }} {{ "pendingCancellation" | i18n }} diff --git a/apps/web/src/app/billing/individual/user-subscription.component.ts b/apps/web/src/app/billing/individual/user-subscription.component.ts index cca17f6b9cc..e04b7c8b019 100644 --- a/apps/web/src/app/billing/individual/user-subscription.component.ts +++ b/apps/web/src/app/billing/individual/user-subscription.component.ts @@ -35,8 +35,6 @@ import { UpdateLicenseDialogResult } from "../shared/update-license-types"; export class UserSubscriptionComponent implements OnInit { loading = false; firstLoaded = false; - adjustStorageAdd = true; - showUpdateLicense = false; sub: SubscriptionResponse; selfHosted = false; cloudWebVaultUrl: string; @@ -65,7 +63,7 @@ export class UserSubscriptionComponent implements OnInit { private toastService: ToastService, private configService: ConfigService, ) { - this.selfHosted = platformUtilsService.isSelfHost(); + this.selfHosted = this.platformUtilsService.isSelfHost(); } async ngOnInit() { @@ -216,11 +214,28 @@ export class UserSubscriptionComponent implements OnInit { : 0; } - get storageProgressWidth() { - return this.storagePercentage < 5 ? 5 : 0; - } - get title(): string { return this.i18nService.t(this.selfHosted ? "subscription" : "premiumMembership"); } + + get subscriptionStatus(): string | null { + if (!this.subscription) { + return null; + } else { + /* + Premium users who sign up with PayPal will have their subscription activated by a webhook. + This is an arbitrary 15-second grace period where we show their subscription as active rather than + incomplete while we wait for our webhook to process the `invoice.created` event. + */ + if (this.subscription.status === "incomplete") { + const periodStartMS = new Date(this.subscription.periodStartDate).getTime(); + const nowMS = new Date().getTime(); + return nowMS - periodStartMS <= 15000 + ? this.i18nService.t("active") + : this.subscription.status; + } + + return this.subscription.status; + } + } } From 9aeb4124048bcefe105c036bfd9d348b1a83ec99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Garc=C3=ADa?= Date: Tue, 1 Oct 2024 16:28:56 +0200 Subject: [PATCH 09/15] [PM-7646][PM-5506] Rust IPC changes: Episode 2 (#11122) * Revert "[PM-7646][PM-5506] Revert IPC changes (#10946)" This reverts commit ed4d481e4d26d3349506407ea113da2238a4ab16. * Ensure tmp dir gets created on MacOS * Remove client reconnections * Improve client error handling and process exiting --- .github/workflows/build-desktop.yml | 45 +-- apps/desktop/desktop_native/.gitignore | 1 + apps/desktop/desktop_native/Cargo.lock | 260 +++++++++++++++++- apps/desktop/desktop_native/Cargo.toml | 2 +- apps/desktop/desktop_native/build.js | 68 +++++ apps/desktop/desktop_native/core/Cargo.toml | 37 ++- .../desktop_native/core/src/ipc/client.rs | 70 +++++ .../desktop_native/core/src/ipc/mod.rs | 66 +++++ .../desktop_native/core/src/ipc/server.rs | 232 ++++++++++++++++ apps/desktop/desktop_native/core/src/lib.rs | 6 + apps/desktop/desktop_native/napi/Cargo.toml | 6 +- apps/desktop/desktop_native/napi/build.js | 24 -- apps/desktop/desktop_native/napi/index.d.ts | 30 ++ apps/desktop/desktop_native/napi/index.js | 8 +- apps/desktop/desktop_native/napi/package.json | 4 +- apps/desktop/desktop_native/napi/src/lib.rs | 100 +++++++ apps/desktop/desktop_native/proxy/Cargo.toml | 19 ++ apps/desktop/desktop_native/proxy/src/main.rs | 159 +++++++++++ apps/desktop/electron-builder.json | 21 +- apps/desktop/package.json | 2 +- .../entitlements.desktop_proxy.plist | 12 + apps/desktop/resources/entitlements.mas.plist | 4 + .../resources/info.desktop_proxy.plist | 8 + apps/desktop/resources/native-messaging.bat | 7 - apps/desktop/scripts/after-pack.js | 138 +++++++++- apps/desktop/src/entry.ts | 42 +-- apps/desktop/src/main.ts | 15 +- .../desktop/src/main/native-messaging.main.ts | 97 ++++--- apps/desktop/src/proxy/ipc.ts | 78 ------ .../src/proxy/native-messaging-proxy.ts | 23 -- apps/desktop/src/proxy/nativemessage.ts | 95 ------- package-lock.json | 28 ++ package.json | 1 + 33 files changed, 1357 insertions(+), 351 deletions(-) create mode 100644 apps/desktop/desktop_native/build.js create mode 100644 apps/desktop/desktop_native/core/src/ipc/client.rs create mode 100644 apps/desktop/desktop_native/core/src/ipc/mod.rs create mode 100644 apps/desktop/desktop_native/core/src/ipc/server.rs delete mode 100644 apps/desktop/desktop_native/napi/build.js create mode 100644 apps/desktop/desktop_native/proxy/Cargo.toml create mode 100644 apps/desktop/desktop_native/proxy/src/main.rs create mode 100644 apps/desktop/resources/entitlements.desktop_proxy.plist create mode 100644 apps/desktop/resources/info.desktop_proxy.plist delete mode 100644 apps/desktop/resources/native-messaging.bat delete mode 100644 apps/desktop/src/proxy/ipc.ts delete mode 100644 apps/desktop/src/proxy/native-messaging-proxy.ts delete mode 100644 apps/desktop/src/proxy/nativemessage.ts diff --git a/.github/workflows/build-desktop.yml b/.github/workflows/build-desktop.yml index 17748fa6a08..5022184bd05 100644 --- a/.github/workflows/build-desktop.yml +++ b/.github/workflows/build-desktop.yml @@ -174,20 +174,21 @@ jobs: with: path: | apps/desktop/desktop_native/napi/*.node + apps/desktop/desktop_native/dist/* ${{ env.RUNNER_TEMP }}/.cargo/registry ${{ env.RUNNER_TEMP }}/.cargo/git key: rust-${{ runner.os }}-${{ hashFiles('apps/desktop/desktop_native/**/*') }} - name: Build Native Module if: steps.cache.outputs.cache-hit != 'true' - working-directory: apps/desktop/desktop_native/napi + working-directory: apps/desktop/desktop_native env: PKG_CONFIG_ALLOW_CROSS: true PKG_CONFIG_ALL_STATIC: true TARGET: musl run: | rustup target add x86_64-unknown-linux-musl - npm run build:cross-platform + node build.js cross-platform - name: Build application run: npm run dist:lin @@ -301,13 +302,15 @@ jobs: uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 id: cache with: - path: apps/desktop/desktop_native/napi/*.node + path: | + apps/desktop/desktop_native/napi/*.node + apps/desktop/desktop_native/dist/* key: rust-${{ runner.os }}-${{ hashFiles('apps/desktop/desktop_native/**/*') }} - name: Build Native Module if: steps.cache.outputs.cache-hit != 'true' - working-directory: apps/desktop/desktop_native/napi - run: npm run build:cross-platform + working-directory: apps/desktop/desktop_native + run: node build.js cross-platform - name: Build & Sign (dev) env: @@ -584,13 +587,15 @@ jobs: uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 id: cache with: - path: apps/desktop/desktop_native/napi/*.node + path: | + apps/desktop/desktop_native/napi/*.node + apps/desktop/desktop_native/dist/* key: rust-${{ runner.os }}-${{ hashFiles('apps/desktop/desktop_native/**/*') }} - name: Build Native Module if: steps.cache.outputs.cache-hit != 'true' - working-directory: apps/desktop/desktop_native/napi - run: npm run build:cross-platform + working-directory: apps/desktop/desktop_native + run: node build.js cross-platform - name: Build application (dev) run: npm run build @@ -748,13 +753,15 @@ jobs: uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 id: cache with: - path: apps/desktop/desktop_native/napi/*.node + path: | + apps/desktop/desktop_native/napi/*.node + apps/desktop/desktop_native/dist/* key: rust-${{ runner.os }}-${{ hashFiles('apps/desktop/desktop_native/**/*') }} - name: Build Native Module if: steps.cache.outputs.cache-hit != 'true' - working-directory: apps/desktop/desktop_native/napi - run: npm run build:cross-platform + working-directory: apps/desktop/desktop_native + run: node build.js cross-platform - name: Build if: steps.build-cache.outputs.cache-hit != 'true' @@ -972,13 +979,15 @@ jobs: uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 id: cache with: - path: apps/desktop/desktop_native/napi/*.node + path: | + apps/desktop/desktop_native/napi/*.node + apps/desktop/desktop_native/dist/* key: rust-${{ runner.os }}-${{ hashFiles('apps/desktop/desktop_native/**/*') }} - name: Build Native Module if: steps.cache.outputs.cache-hit != 'true' - working-directory: apps/desktop/desktop_native/napi - run: npm run build:cross-platform + working-directory: apps/desktop/desktop_native + run: node build.js cross-platform - name: Build if: steps.build-cache.outputs.cache-hit != 'true' @@ -1205,13 +1214,15 @@ jobs: uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.2 id: cache with: - path: apps/desktop/desktop_native/napi/*.node + path: | + apps/desktop/desktop_native/napi/*.node + apps/desktop/desktop_native/dist/* key: rust-${{ runner.os }}-${{ hashFiles('apps/desktop/desktop_native/**/*') }} - name: Build Native Module if: steps.cache.outputs.cache-hit != 'true' - working-directory: apps/desktop/desktop_native/napi - run: npm run build:cross-platform + working-directory: apps/desktop/desktop_native + run: node build.js cross-platform - name: Build if: steps.build-cache.outputs.cache-hit != 'true' diff --git a/apps/desktop/desktop_native/.gitignore b/apps/desktop/desktop_native/.gitignore index 96e7a71e1b0..1cfa7dafc20 100644 --- a/apps/desktop/desktop_native/.gitignore +++ b/apps/desktop/desktop_native/.gitignore @@ -4,3 +4,4 @@ index.node **/.DS_Store npm-debug.log* *.node +dist diff --git a/apps/desktop/desktop_native/Cargo.lock b/apps/desktop/desktop_native/Cargo.lock index c01e68f804b..ed6f2420b66 100644 --- a/apps/desktop/desktop_native/Cargo.lock +++ b/apps/desktop/desktop_native/Cargo.lock @@ -304,9 +304,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.1.23" +version = "1.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3bbb537bb4a30b90362caddba8f360c0a56bc13d3a5570028e7197204cb54a17" +checksum = "812acba72f0a070b003d3697490d2b55b837230ae7c6c6497f05cc2ddbb8d938" dependencies = [ "shlex", ] @@ -481,6 +481,15 @@ dependencies = [ "syn", ] +[[package]] +name = "deranged" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", +] + [[package]] name = "derive-new" version = "0.6.0" @@ -502,10 +511,14 @@ dependencies = [ "base64", "cbc", "core-foundation", + "dirs", + "futures", "gio", + "interprocess", "keytar", "libc", "libsecret", + "log", "rand", "retry", "scopeguard", @@ -514,6 +527,7 @@ dependencies = [ "sha2", "thiserror", "tokio", + "tokio-util", "typenum", "widestring", "windows", @@ -530,6 +544,22 @@ dependencies = [ "napi", "napi-build", "napi-derive", + "tokio", + "tokio-util", +] + +[[package]] +name = "desktop_proxy" +version = "0.0.0" +dependencies = [ + "anyhow", + "desktop_core", + "embed_plist", + "futures", + "log", + "simplelog", + "tokio", + "tokio-util", ] [[package]] @@ -542,6 +572,27 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.48.0", +] + [[package]] name = "dlib" version = "0.5.2" @@ -551,12 +602,24 @@ dependencies = [ "libloading", ] +[[package]] +name = "doctest-file" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac81fa3e28d21450aa4d2ac065992ba96a1d7303efbce51a95f4fd175b67562" + [[package]] name = "downcast-rs" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" +[[package]] +name = "embed_plist" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" + [[package]] name = "endi" version = "1.1.0" @@ -645,6 +708,21 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "futures" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "645c6916888f6cb6350d2550b80fb63e734897a8498abe35cfb732b6487804b0" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.30" @@ -652,6 +730,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -719,6 +798,7 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ + "futures-channel", "futures-core", "futures-io", "futures-macro", @@ -913,6 +993,27 @@ dependencies = [ "generic-array", ] +[[package]] +name = "interprocess" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f4e4a06d42fab3e85ab1b419ad32b09eab58b901d40c57935ff92db3287a13" +dependencies = [ + "doctest-file", + "futures-core", + "libc", + "recvmsg", + "tokio", + "widestring", + "windows-sys 0.52.0", +] + +[[package]] +name = "itoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" + [[package]] name = "keytar" version = "0.1.6" @@ -950,6 +1051,16 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "libredox" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" +dependencies = [ + "bitflags", + "libc", +] + [[package]] name = "libsecret" version = "0.5.0" @@ -1038,10 +1149,21 @@ dependencies = [ ] [[package]] -name = "napi" -version = "2.16.6" +name = "mio" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dfc300228808a0e6aea5a58115c82889240bcf8dab16fc25ad675b33e454b368" +checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.48.0", +] + +[[package]] +name = "napi" +version = "2.16.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633e41b2b983cf7983134f0c50986ca524d0caf38a2c6fc893ea3fa2e26abb0c" dependencies = [ "bitflags", "ctor", @@ -1059,9 +1181,9 @@ checksum = "e1c0f5d67ee408a4685b61f5ab7e58605c8ae3f2b4189f0127d804ff13d5560a" [[package]] name = "napi-derive" -version = "2.16.5" +version = "2.16.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0e034ddf6155192cf83f267ede763fe6c164dfa9971585436b16173718d94c4" +checksum = "70a8a778fd367b13c64232e58632514b795514ece491ce136d96e976d34a3eb8" dependencies = [ "cfg-if", "convert_case", @@ -1130,6 +1252,12 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + [[package]] name = "num_cpus" version = "1.16.0" @@ -1140,6 +1268,15 @@ dependencies = [ "libc", ] +[[package]] +name = "num_threads" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9" +dependencies = [ + "libc", +] + [[package]] name = "objc-sys" version = "0.3.5" @@ -1257,6 +1394,12 @@ dependencies = [ "portable-atomic", ] +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "ordered-stream" version = "0.2.0" @@ -1366,6 +1509,12 @@ version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cc9c68a3f6da06753e9335d63e27f6b9754dd1920d941135b7ea8224f141adb2" +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "ppv-lite86" version = "0.2.20" @@ -1441,6 +1590,12 @@ dependencies = [ "getrandom", ] +[[package]] +name = "recvmsg" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3edd4d5d42c92f0a659926464d4cce56b562761267ecf0f469d85b7de384175" + [[package]] name = "redox_syscall" version = "0.5.7" @@ -1450,6 +1605,17 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom", + "libredox", + "thiserror", +] + [[package]] name = "regex" version = "1.11.0" @@ -1631,6 +1797,17 @@ dependencies = [ "libc", ] +[[package]] +name = "simplelog" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16257adbfaef1ee58b1363bdc0664c9b8e1e30aed86049635fb5f147d065a9c0" +dependencies = [ + "log", + "termcolor", + "time", +] + [[package]] name = "slab" version = "0.4.9" @@ -1646,6 +1823,16 @@ version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" +[[package]] +name = "socket2" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + [[package]] name = "static_assertions" version = "1.1.0" @@ -1724,6 +1911,39 @@ dependencies = [ "syn", ] +[[package]] +name = "time" +version = "0.3.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" +dependencies = [ + "deranged", + "itoa", + "libc", + "num-conv", + "num_threads", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" + +[[package]] +name = "time-macros" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tokio" version = "1.38.0" @@ -1732,9 +1952,13 @@ checksum = "ba4f4a02a7a80d6f274636f0aa95c7e383b912d41fe721a31f29e29698585a4a" dependencies = [ "backtrace", "bytes", + "libc", + "mio", "num_cpus", "pin-project-lite", + "socket2", "tokio-macros", + "windows-sys 0.48.0", ] [[package]] @@ -1748,6 +1972,19 @@ dependencies = [ "syn", ] +[[package]] +name = "tokio-util" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cf6b47b3771c49ac75ad09a6162f53ad4b8088b76ac60e8ec1455b31a189fe1" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + [[package]] name = "toml" version = "0.8.19" @@ -2043,6 +2280,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows-sys" version = "0.52.0" diff --git a/apps/desktop/desktop_native/Cargo.toml b/apps/desktop/desktop_native/Cargo.toml index c6b77473b2a..6525b38162d 100644 --- a/apps/desktop/desktop_native/Cargo.toml +++ b/apps/desktop/desktop_native/Cargo.toml @@ -1,3 +1,3 @@ [workspace] resolver = "2" -members = ["napi", "core"] +members = ["napi", "core", "proxy"] diff --git a/apps/desktop/desktop_native/build.js b/apps/desktop/desktop_native/build.js new file mode 100644 index 00000000000..f2f012bf088 --- /dev/null +++ b/apps/desktop/desktop_native/build.js @@ -0,0 +1,68 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +const child_process = require("child_process"); +const fs = require("fs"); +const path = require("path"); +const process = require("process"); + +let crossPlatform = process.argv.length > 2 && process.argv[2] === "cross-platform"; + +function buildNapiModule(target, release = true) { + const targetArg = target ? `--target ${target}` : ""; + const releaseArg = release ? "--release" : ""; + return child_process.execSync(`npm run build -- ${releaseArg} ${targetArg}`, { stdio: 'inherit', cwd: path.join(__dirname, "napi") }); +} + +function buildProxyBin(target, release = true) { + const targetArg = target ? `--target ${target}` : ""; + const releaseArg = release ? "--release" : ""; + return child_process.execSync(`cargo build --bin desktop_proxy ${releaseArg} ${targetArg}`, {stdio: 'inherit', cwd: path.join(__dirname, "proxy")}); +} + +if (!crossPlatform) { + console.log("Building native modules in debug mode for the native architecture"); + buildNapiModule(false, false); + buildProxyBin(false, false); + return; +} + +// Note that targets contains pairs of [rust target, node arch] +// We do this to move the output binaries to a location that can +// be easily accessed from electron-builder using ${os} and ${arch} +let targets = []; +switch (process.platform) { + case "win32": + targets = [ + ["i686-pc-windows-msvc", 'ia32'], + ["x86_64-pc-windows-msvc", 'x64'], + ["aarch64-pc-windows-msvc", 'arm64'] + ]; + break; + + case "darwin": + targets = [ + ["x86_64-apple-darwin", 'x64'], + ["aarch64-apple-darwin", 'arm64'] + ]; + break; + + default: + targets = [ + ['x86_64-unknown-linux-musl', 'x64'] + ]; + + process.env["PKG_CONFIG_ALLOW_CROSS"] = "1"; + process.env["PKG_CONFIG_ALL_STATIC"] = "1"; + break; +} + +console.log("Cross building native modules for the targets: ", targets.map(([target, _]) => target).join(", ")); + +fs.mkdirSync(path.join(__dirname, "dist"), { recursive: true }); + +targets.forEach(([target, nodeArch]) => { + buildNapiModule(target); + buildProxyBin(target); + + const ext = process.platform === "win32" ? ".exe" : ""; + fs.copyFileSync(path.join(__dirname, "target", target, "release", `desktop_proxy${ext}`), path.join(__dirname, "dist", `desktop_proxy.${process.platform}-${nodeArch}${ext}`)); +}); diff --git a/apps/desktop/desktop_native/core/Cargo.toml b/apps/desktop/desktop_native/core/Cargo.toml index 108d6124dae..03f0ef6d696 100644 --- a/apps/desktop/desktop_native/core/Cargo.toml +++ b/apps/desktop/desktop_native/core/Cargo.toml @@ -6,9 +6,21 @@ version = "0.0.0" publish = false [features] -default = [] +default = ["sys"] manual_test = [] +sys = [ + "dep:widestring", + "dep:windows", + "dep:core-foundation", + "dep:security-framework", + "dep:security-framework-sys", + "dep:gio", + "dep:libsecret", + "dep:zbus", + "dep:zbus_polkit", +] + [dependencies] aes = "=0.8.4" anyhow = "=1.0.86" @@ -17,17 +29,22 @@ arboard = { version = "=3.4.1", default-features = false, features = [ ] } base64 = "=0.22.1" cbc = { version = "=0.1.2", features = ["alloc"] } +dirs = "=5.0.1" +futures = "=0.3.30" +interprocess = { version = "=2.2.1", features = ["tokio"] } libc = "=0.2.155" +log = "=0.4.22" rand = "=0.8.5" retry = "=2.0.0" scopeguard = "=1.2.0" sha2 = "=0.10.8" thiserror = "=1.0.61" tokio = { version = "=1.38.0", features = ["io-util", "sync", "macros"] } +tokio-util = "=0.7.11" typenum = "=1.17.0" [target.'cfg(windows)'.dependencies] -widestring = "=1.1.0" +widestring = { version = "=1.1.0", optional = true } windows = { version = "=0.57.0", features = [ "Foundation", "Security_Credentials_UI", @@ -38,18 +55,18 @@ windows = { version = "=0.57.0", features = [ "Win32_System_WinRT", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging", -] } +], optional = true } [target.'cfg(windows)'.dev-dependencies] keytar = "=0.1.6" [target.'cfg(target_os = "macos")'.dependencies] -core-foundation = "=0.9.4" -security-framework = "=2.11.0" -security-framework-sys = "=2.11.0" +core-foundation = { version = "=0.9.4", optional = true } +security-framework = { version = "=2.11.0", optional = true } +security-framework-sys = { version = "=2.11.0", optional = true } [target.'cfg(target_os = "linux")'.dependencies] -gio = "=0.19.5" -libsecret = "=0.5.0" -zbus = "=4.3.1" -zbus_polkit = "=4.0.0" +gio = { version = "=0.19.5", optional = true } +libsecret = { version = "=0.5.0", optional = true } +zbus = { version = "=4.3.1", optional = true } +zbus_polkit = { version = "=4.0.0", optional = true } diff --git a/apps/desktop/desktop_native/core/src/ipc/client.rs b/apps/desktop/desktop_native/core/src/ipc/client.rs new file mode 100644 index 00000000000..7eff8a10974 --- /dev/null +++ b/apps/desktop/desktop_native/core/src/ipc/client.rs @@ -0,0 +1,70 @@ +use std::path::PathBuf; + +use interprocess::local_socket::{ + tokio::{prelude::*, Stream}, + GenericFilePath, ToFsName, +}; +use log::{error, info}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +use crate::ipc::NATIVE_MESSAGING_BUFFER_SIZE; + +pub async fn connect( + path: PathBuf, + send: tokio::sync::mpsc::Sender, + mut recv: tokio::sync::mpsc::Receiver, +) -> Result<(), Box> { + info!("Attempting to connect to {}", path.display()); + + let name = path.as_os_str().to_fs_name::()?; + let mut conn = Stream::connect(name).await?; + + info!("Connected to {}", path.display()); + + // This `connected` and the latter `disconnected` messages are the only ones that + // are sent from the Rust IPC code and not just forwarded from the desktop app. + // As it's only two, we hardcode the JSON values to avoid pulling in a JSON library. + send.send("{\"command\":\"connected\"}".to_owned()).await?; + + let mut buffer = vec![0; NATIVE_MESSAGING_BUFFER_SIZE]; + + // Listen to IPC messages + loop { + tokio::select! { + // Forward messages to the IPC server + msg = recv.recv() => { + match msg { + Some(msg) => { + conn.write_all(msg.as_bytes()).await?; + } + None => { + info!("Client channel closed"); + break; + }, + } + }, + + // Forward messages from the IPC server + res = conn.read(&mut buffer[..]) => { + match res { + Err(e) => { + error!("Error reading from IPC server: {e}"); + break; + } + Ok(0) => { + info!("Connection closed"); + break; + } + Ok(n) => { + let message = String::from_utf8_lossy(&buffer[..n]).to_string(); + send.send(message).await?; + } + } + } + } + } + + let _ = send.send("{\"command\":\"disconnected\"}".to_owned()).await; + + Ok(()) +} diff --git a/apps/desktop/desktop_native/core/src/ipc/mod.rs b/apps/desktop/desktop_native/core/src/ipc/mod.rs new file mode 100644 index 00000000000..c7ac1a43404 --- /dev/null +++ b/apps/desktop/desktop_native/core/src/ipc/mod.rs @@ -0,0 +1,66 @@ +pub mod client; +pub mod server; + +/// The maximum size of a message that can be sent over IPC. +/// According to the documentation, the maximum size sent to the browser is 1MB. +/// While the maximum size sent from the browser to the native messaging host is 4GB. +/// +/// Currently we are setting the maximum both ways to be 1MB. +/// +/// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging#app_side +/// https://developer.chrome.com/docs/extensions/develop/concepts/native-messaging#native-messaging-host-protocol +pub const NATIVE_MESSAGING_BUFFER_SIZE: usize = 1024 * 1024; + +/// The maximum number of messages that can be buffered in a channel. +/// This number is more or less arbitrary and can be adjusted as needed, +/// but ideally the messages should be processed as quickly as possible. +pub const MESSAGE_CHANNEL_BUFFER: usize = 32; + +/// Resolve the path to the IPC socket. +pub fn path(name: &str) -> std::path::PathBuf { + #[cfg(target_os = "windows")] + { + // Use a unique IPC pipe //./pipe/xxxxxxxxxxxxxxxxx.app.bitwarden per user. + // Hashing prevents problems with reserved characters and file length limitations. + use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine}; + use sha2::Digest; + let home = dirs::home_dir().unwrap(); + let hash = sha2::Sha256::digest(home.as_os_str().as_encoded_bytes()); + let hash_b64 = URL_SAFE_NO_PAD.encode(hash.as_slice()); + + format!(r"\\.\pipe\{hash_b64}.app.{name}").into() + } + + #[cfg(target_os = "macos")] + { + let mut home = dirs::home_dir().unwrap(); + + // When running in an unsandboxed environment, path is: /Users// + // While running sandboxed, it's different: /Users//Library/Containers/com.bitwarden.desktop/Data + // + // We want to use App Groups in /Users//Library/Group Containers/LTZ2PFU5D6.com.bitwarden.desktop, + // so we need to remove all the components after the user. + // Note that we subtract 3 because the root directory is counted as a component (/, Users, ). + let num_components = home.components().count(); + for _ in 0..num_components - 3 { + home.pop(); + } + + let tmp = home.join("Library/Group Containers/LTZ2PFU5D6.com.bitwarden.desktop/tmp"); + + // The tmp directory might not exist, so create it + let _ = std::fs::create_dir_all(&tmp); + tmp.join(format!("app.{name}")) + } + + #[cfg(target_os = "linux")] + { + // On Linux, we use the user's cache directory. + let home = dirs::cache_dir().unwrap(); + let path_dir = home.join("com.bitwarden.desktop"); + + // The chache directory might not exist, so create it + let _ = std::fs::create_dir_all(&path_dir); + path_dir.join(format!("app.{name}")) + } +} diff --git a/apps/desktop/desktop_native/core/src/ipc/server.rs b/apps/desktop/desktop_native/core/src/ipc/server.rs new file mode 100644 index 00000000000..053b4322203 --- /dev/null +++ b/apps/desktop/desktop_native/core/src/ipc/server.rs @@ -0,0 +1,232 @@ +use std::{error::Error, path::Path, vec}; + +use futures::TryFutureExt; + +use anyhow::Result; +use interprocess::local_socket::{tokio::prelude::*, GenericFilePath, ListenerOptions}; +use log::{error, info}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, + sync::{broadcast, mpsc}, +}; +use tokio_util::sync::CancellationToken; + +use super::{MESSAGE_CHANNEL_BUFFER, NATIVE_MESSAGING_BUFFER_SIZE}; + +#[derive(Debug)] +pub struct Message { + pub client_id: u32, + pub kind: MessageType, + // This value should be Some for MessageType::Message and None for the rest + pub message: Option, +} + +#[derive(Debug)] +pub enum MessageType { + Connected, + Disconnected, + Message, +} + +pub struct Server { + cancel_token: CancellationToken, + server_to_clients_send: broadcast::Sender, +} + +impl Server { + /// Create and start the IPC server without blocking. + /// + /// # Parameters + /// + /// - `name`: The endpoint name to listen on. This name uniquely identifies the IPC connection and must be the same for both the server and client. + /// - `client_to_server_send`: This [`mpsc::Sender`] will receive all the [`Message`]'s that the clients send to this server. + pub fn start( + path: &Path, + client_to_server_send: mpsc::Sender, + ) -> Result> { + // If the unix socket file already exists, we get an error when trying to bind to it. So we remove it first. + // Any processes that were using the old socket should remain connected to it but any new connections will use the new socket. + if !cfg!(windows) { + let _ = std::fs::remove_file(path); + } + + let name = path.as_os_str().to_fs_name::()?; + let opts = ListenerOptions::new().name(name); + let listener = opts.create_tokio()?; + + // This broadcast channel is used for sending messages to all connected clients, and so the sender + // will be stored in the server while the receiver will be cloned and passed to each client handler. + let (server_to_clients_send, server_to_clients_recv) = + broadcast::channel::(MESSAGE_CHANNEL_BUFFER); + + // This cancellation token allows us to cleanly stop the server and all the spawned + // tasks without having to wait on all the pending tasks finalizing first + let cancel_token = CancellationToken::new(); + + // Create the server and start listening for incoming connections + // in a separate task to avoid blocking the current task + let server = Server { + cancel_token: cancel_token.clone(), + server_to_clients_send, + }; + tokio::spawn(listen_incoming( + listener, + client_to_server_send, + server_to_clients_recv, + cancel_token, + )); + + Ok(server) + } + + /// Send a message over the IPC server to all the connected clients + /// + /// # Returns + /// + /// The number of clients that the message was sent to. Note that the number of messages + /// sent may be less than the number of connected clients if some clients disconnect while + /// the message is being sent. + pub fn send(&self, message: String) -> Result { + let sent = self.server_to_clients_send.send(message)?; + Ok(sent) + } + + /// Stop the IPC server. + pub fn stop(&self) { + self.cancel_token.cancel(); + } +} + +impl Drop for Server { + fn drop(&mut self) { + self.stop(); + } +} + +async fn listen_incoming( + listener: LocalSocketListener, + client_to_server_send: mpsc::Sender, + server_to_clients_recv: broadcast::Receiver, + cancel_token: CancellationToken, +) { + // We use a simple incrementing ID for each client + let mut next_client_id = 1_u32; + + loop { + tokio::select! { + _ = cancel_token.cancelled() => { + info!("IPC server cancelled."); + break; + }, + + // A new client connection has been established + msg = listener.accept() => { + match msg { + Ok(client_stream) => { + let client_id = next_client_id; + next_client_id += 1; + + let future = handle_connection( + client_stream, + client_to_server_send.clone(), + // We resubscribe to the receiver here so this task can have it's own copy + // Note that this copy will only receive messages sent after this point, + // but that is okay, realistically we don't want any messages before we get a chance + // to send the connected message to the client, which is done inside [`handle_connection`] + server_to_clients_recv.resubscribe(), + cancel_token.clone(), + client_id + ); + tokio::spawn(future.map_err(|e| { + error!("Error handling connection: {}", e) + })); + }, + Err(e) => { + error!("Error accepting connection: {}", e); + break; + }, + } + } + } + } +} + +async fn handle_connection( + mut client_stream: impl AsyncRead + AsyncWrite + Unpin, + client_to_server_send: mpsc::Sender, + mut server_to_clients_recv: broadcast::Receiver, + cancel_token: CancellationToken, + client_id: u32, +) -> Result<(), Box> { + client_to_server_send + .send(Message { + client_id, + kind: MessageType::Connected, + message: None, + }) + .await?; + + let mut buf = vec![0u8; NATIVE_MESSAGING_BUFFER_SIZE]; + + loop { + tokio::select! { + _ = cancel_token.cancelled() => { + info!("Client {client_id} cancelled."); + break; + }, + + // Forward messages to the IPC clients + msg = server_to_clients_recv.recv() => { + match msg { + Ok(msg) => { + client_stream.write_all(msg.as_bytes()).await?; + }, + Err(e) => { + info!("Error reading message: {}", e); + break; + } + } + }, + + // Forwards messages from the IPC clients to the server + // Note that we also send connect and disconnect events so that + // the server can keep track of multiple clients + result = client_stream.read(&mut buf) => { + match result { + Err(e) => { + info!("Error reading from client {client_id}: {e}"); + + client_to_server_send.send(Message { + client_id, + kind: MessageType::Disconnected, + message: None, + }).await?; + break; + }, + Ok(0) => { + info!("Client {client_id} disconnected."); + + client_to_server_send.send(Message { + client_id, + kind: MessageType::Disconnected, + message: None, + }).await?; + break; + }, + Ok(size) => { + let msg = std::str::from_utf8(&buf[..size])?; + + client_to_server_send.send(Message { + client_id, + kind: MessageType::Message, + message: Some(msg.to_string()), + }).await?; + }, + + } + } + } + } + + Ok(()) +} diff --git a/apps/desktop/desktop_native/core/src/lib.rs b/apps/desktop/desktop_native/core/src/lib.rs index d23a285b4ac..3132c56f7f8 100644 --- a/apps/desktop/desktop_native/core/src/lib.rs +++ b/apps/desktop/desktop_native/core/src/lib.rs @@ -1,7 +1,13 @@ +#[cfg(feature = "sys")] pub mod biometric; +#[cfg(feature = "sys")] pub mod clipboard; pub mod crypto; pub mod error; +pub mod ipc; +#[cfg(feature = "sys")] pub mod password; +#[cfg(feature = "sys")] pub mod process_isolation; +#[cfg(feature = "sys")] pub mod powermonitor; diff --git a/apps/desktop/desktop_native/napi/Cargo.toml b/apps/desktop/desktop_native/napi/Cargo.toml index 942ccdba212..6fb710b0671 100644 --- a/apps/desktop/desktop_native/napi/Cargo.toml +++ b/apps/desktop/desktop_native/napi/Cargo.toml @@ -16,8 +16,10 @@ manual_test = [] [dependencies] anyhow = "=1.0.86" desktop_core = { path = "../core" } -napi = { version = "=2.16.6", features = ["async"] } -napi-derive = "=2.16.5" +napi = { version = "=2.16.7", features = ["async"] } +napi-derive = "=2.16.6" +tokio = { version = "1.38.0" } +tokio-util = "0.7.11" [build-dependencies] napi-build = "=2.1.3" diff --git a/apps/desktop/desktop_native/napi/build.js b/apps/desktop/desktop_native/napi/build.js deleted file mode 100644 index 6c92dbad1b6..00000000000 --- a/apps/desktop/desktop_native/napi/build.js +++ /dev/null @@ -1,24 +0,0 @@ -/* eslint-disable @typescript-eslint/no-var-requires */ -const child_process = require("child_process"); -const process = require("process"); - -let targets = []; -switch (process.platform) { - case "win32": - targets = ["i686-pc-windows-msvc", "x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc"]; - break; - - case "darwin": - targets = ["x86_64-apple-darwin", "aarch64-apple-darwin"]; - break; - - default: - targets = ['x86_64-unknown-linux-musl']; - process.env["PKG_CONFIG_ALLOW_CROSS"] = "1"; - process.env["PKG_CONFIG_ALL_STATIC"] = "1"; - break; -} - -targets.forEach(target => { - child_process.execSync(`npm run build -- --target ${target}`, {stdio: 'inherit'}); -}); diff --git a/apps/desktop/desktop_native/napi/index.d.ts b/apps/desktop/desktop_native/napi/index.d.ts index deaf6b8e57f..fe4ab59fd8e 100644 --- a/apps/desktop/desktop_native/napi/index.d.ts +++ b/apps/desktop/desktop_native/napi/index.d.ts @@ -51,3 +51,33 @@ export namespace powermonitors { export function onLock(callback: (err: Error | null, ) => any): Promise export function isLockMonitorAvailable(): Promise } +export namespace ipc { + export interface IpcMessage { + clientId: number + kind: IpcMessageType + message?: string + } + export const enum IpcMessageType { + Connected = 0, + Disconnected = 1, + Message = 2 + } + export class IpcServer { + /** + * Create and start the IPC server without blocking. + * + * @param name The endpoint name to listen on. This name uniquely identifies the IPC connection and must be the same for both the server and client. + * @param callback This function will be called whenever a message is received from a client. + */ + static listen(name: string, callback: (error: null | Error, message: IpcMessage) => void): Promise + /** Stop the IPC server. */ + stop(): void + /** + * Send a message over the IPC server to all the connected clients + * + * @return The number of clients that the message was sent to. Note that the number of messages + * actually received may be less, as some clients could disconnect before receiving the message. + */ + send(message: string): number + } +} diff --git a/apps/desktop/desktop_native/napi/index.js b/apps/desktop/desktop_native/napi/index.js index 680f1302b9a..a0cfee8e1a0 100644 --- a/apps/desktop/desktop_native/napi/index.js +++ b/apps/desktop/desktop_native/napi/index.js @@ -206,10 +206,4 @@ if (!nativeBinding) { throw new Error(`Failed to load native binding`) } -const { passwords, biometrics, clipboards, processisolations, powermonitors } = nativeBinding - -module.exports.passwords = passwords -module.exports.biometrics = biometrics -module.exports.clipboards = clipboards -module.exports.processisolations = processisolations -module.exports.powermonitors = powermonitors +module.exports = nativeBinding diff --git a/apps/desktop/desktop_native/napi/package.json b/apps/desktop/desktop_native/napi/package.json index 70e472b3952..9f098c4965d 100644 --- a/apps/desktop/desktop_native/napi/package.json +++ b/apps/desktop/desktop_native/napi/package.json @@ -3,9 +3,7 @@ "version": "0.1.0", "description": "", "scripts": { - "build": "napi build --release --platform --js false", - "build:debug": "napi build --platform --js false", - "build:cross-platform": "node build.js", + "build": "napi build --platform --js false", "test": "cargo test" }, "author": "", diff --git a/apps/desktop/desktop_native/napi/src/lib.rs b/apps/desktop/desktop_native/napi/src/lib.rs index dfdc316d259..838eb651244 100644 --- a/apps/desktop/desktop_native/napi/src/lib.rs +++ b/apps/desktop/desktop_native/napi/src/lib.rs @@ -189,3 +189,103 @@ pub mod powermonitors { } } + +#[napi] +pub mod ipc { + use desktop_core::ipc::server::{Message, MessageType}; + use napi::threadsafe_function::{ + ErrorStrategy, ThreadsafeFunction, ThreadsafeFunctionCallMode, + }; + + #[napi(object)] + pub struct IpcMessage { + pub client_id: u32, + pub kind: IpcMessageType, + pub message: Option, + } + + impl From for IpcMessage { + fn from(message: Message) -> Self { + IpcMessage { + client_id: message.client_id, + kind: message.kind.into(), + message: message.message, + } + } + } + + #[napi] + pub enum IpcMessageType { + Connected, + Disconnected, + Message, + } + + impl From for IpcMessageType { + fn from(message_type: MessageType) -> Self { + match message_type { + MessageType::Connected => IpcMessageType::Connected, + MessageType::Disconnected => IpcMessageType::Disconnected, + MessageType::Message => IpcMessageType::Message, + } + } + } + + #[napi] + pub struct IpcServer { + server: desktop_core::ipc::server::Server, + } + + #[napi] + impl IpcServer { + /// Create and start the IPC server without blocking. + /// + /// @param name The endpoint name to listen on. This name uniquely identifies the IPC connection and must be the same for both the server and client. + /// @param callback This function will be called whenever a message is received from a client. + #[napi(factory)] + pub async fn listen( + name: String, + #[napi(ts_arg_type = "(error: null | Error, message: IpcMessage) => void")] + callback: ThreadsafeFunction, + ) -> napi::Result { + let (send, mut recv) = tokio::sync::mpsc::channel::(32); + tokio::spawn(async move { + while let Some(message) = recv.recv().await { + callback.call(Ok(message.into()), ThreadsafeFunctionCallMode::NonBlocking); + } + }); + + let path = desktop_core::ipc::path(&name); + + let server = desktop_core::ipc::server::Server::start(&path, send).map_err(|e| { + napi::Error::from_reason(format!( + "Error listening to server - Path: {path:?} - Error: {e} - {e:?}" + )) + })?; + + Ok(IpcServer { server }) + } + + /// Stop the IPC server. + #[napi] + pub fn stop(&self) -> napi::Result<()> { + self.server.stop(); + Ok(()) + } + + /// Send a message over the IPC server to all the connected clients + /// + /// @return The number of clients that the message was sent to. Note that the number of messages + /// actually received may be less, as some clients could disconnect before receiving the message. + #[napi] + pub fn send(&self, message: String) -> napi::Result { + self.server + .send(message) + .map_err(|e| { + napi::Error::from_reason(format!("Error sending message - Error: {e} - {e:?}")) + }) + // NAPI doesn't support u64 or usize, so we need to convert to u32 + .map(|u| u32::try_from(u).unwrap_or_default()) + } + } +} diff --git a/apps/desktop/desktop_native/proxy/Cargo.toml b/apps/desktop/desktop_native/proxy/Cargo.toml new file mode 100644 index 00000000000..681c34c8eab --- /dev/null +++ b/apps/desktop/desktop_native/proxy/Cargo.toml @@ -0,0 +1,19 @@ +[package] +edition = "2021" +exclude = ["index.node"] +license = "GPL-3.0" +name = "desktop_proxy" +version = "0.0.0" +publish = false + +[dependencies] +anyhow = "=1.0.86" +desktop_core = { path = "../core", default-features = false } +futures = "0.3.30" +log = "0.4.21" +simplelog = "0.12.2" +tokio = { version = "1.38.0", features = ["io-std", "io-util", "macros", "rt"] } +tokio-util = { version = "0.7.11", features = ["codec"] } + +[target.'cfg(target_os = "macos")'.dependencies] +embed_plist = "1.2.2" diff --git a/apps/desktop/desktop_native/proxy/src/main.rs b/apps/desktop/desktop_native/proxy/src/main.rs new file mode 100644 index 00000000000..7d3b4ecfca7 --- /dev/null +++ b/apps/desktop/desktop_native/proxy/src/main.rs @@ -0,0 +1,159 @@ +use std::path::Path; + +use desktop_core::ipc::{MESSAGE_CHANNEL_BUFFER, NATIVE_MESSAGING_BUFFER_SIZE}; +use futures::{FutureExt, SinkExt, StreamExt}; +use log::*; +use tokio_util::codec::LengthDelimitedCodec; + +#[cfg(target_os = "macos")] +embed_plist::embed_info_plist!("../../../resources/info.desktop_proxy.plist"); + +fn init_logging(log_path: &Path, level: log::LevelFilter) { + use simplelog::{ColorChoice, CombinedLogger, Config, SharedLogger, TermLogger, TerminalMode}; + + let config = Config::default(); + + let mut loggers: Vec> = Vec::new(); + loggers.push(TermLogger::new( + level, + config.clone(), + TerminalMode::Stderr, + ColorChoice::Auto, + )); + + match std::fs::File::create(log_path) { + Ok(file) => { + loggers.push(simplelog::WriteLogger::new(level, config, file)); + } + Err(e) => { + eprintln!("Can't create file: {}", e); + } + } + + if let Err(e) = CombinedLogger::init(loggers) { + eprintln!("Failed to initialize logger: {}", e); + } +} + +/// Bitwarden IPC Proxy. +/// +/// This proxy allows browser extensions to communicate with a desktop application using Native +/// Messaging. This method allows an extension to send and receive messages through the use of +/// stdin/stdout streams. +/// +/// However, this also requires the browser to start the process in order for the communication to +/// occur. To overcome this limitation, we implement Inter-Process Communication (IPC) to establish +/// a stable communication channel between the proxy and the running desktop application. +/// +/// Browser extension <-[native messaging]-> proxy <-[ipc]-> desktop +/// +#[tokio::main(flavor = "current_thread")] +async fn main() { + let sock_path = desktop_core::ipc::path("bitwarden"); + + let log_path = { + let mut path = sock_path.clone(); + path.set_extension("bitwarden.log"); + path + }; + + init_logging(&log_path, LevelFilter::Info); + + info!("Starting Bitwarden IPC Proxy."); + + // Different browsers send different arguments when the app starts: + // + // Firefox: + // - The complete path to the app manifest. (in the form `/Users//Library/.../Mozilla/NativeMessagingHosts/com.8bit.bitwarden.json`) + // - (in Firefox 55+) the ID (as given in the manifest.json) of the add-on that started it (in the form `{[UUID]}`). + // + // Chrome on Windows: + // - Origin of the extension that started it (in the form `chrome-extension://[ID]`). + // - Handle to the Chrome native window that started the app. + // + // Chrome on Linux and Mac: + // - Origin of the extension that started it (in the form `chrome-extension://[ID]`). + + let args: Vec<_> = std::env::args().skip(1).collect(); + info!("Process args: {:?}", args); + + // Setup two channels, one for sending messages to the desktop application (`out`) and one for receiving messages from the desktop application (`in`) + let (in_send, in_recv) = tokio::sync::mpsc::channel(MESSAGE_CHANNEL_BUFFER); + let (out_send, mut out_recv) = tokio::sync::mpsc::channel(MESSAGE_CHANNEL_BUFFER); + + let mut handle = tokio::spawn( + desktop_core::ipc::client::connect(sock_path, out_send, in_recv) + .map(|r| r.map_err(|e| e.to_string())), + ); + + // Create a new codec for reading and writing messages from stdin/stdout. + let mut stdin = LengthDelimitedCodec::builder() + .max_frame_length(NATIVE_MESSAGING_BUFFER_SIZE) + .native_endian() + .new_read(tokio::io::stdin()); + let mut stdout = LengthDelimitedCodec::builder() + .max_frame_length(NATIVE_MESSAGING_BUFFER_SIZE) + .native_endian() + .new_write(tokio::io::stdout()); + + loop { + tokio::select! { + // This forces tokio to poll the futures in the order that they are written. + // We want the spawn handle to be evaluated first so that we can get any error + // results before we get the channel closed message. + biased; + + // IPC client has finished, so we should exit as well. + res = &mut handle => { + match res { + Ok(Ok(())) => { + info!("IPC client finished successfully."); + std::process::exit(0); + } + Ok(Err(e)) => { + error!("IPC client connection error: {}", e); + std::process::exit(1); + } + Err(e) => { + error!("IPC client spawn error: {}", e); + std::process::exit(1); + } + } + } + + // Receive messages from IPC and print to STDOUT. + msg = out_recv.recv() => { + match msg { + Some(msg) => { + debug!("OUT: {}", msg); + stdout.send(msg.into()).await.unwrap(); + } + None => { + info!("Channel closed, exiting."); + std::process::exit(0); + } + } + }, + + // Listen to stdin and send messages to ipc processor. + msg = stdin.next() => { + match msg { + Some(Ok(msg)) => { + let m = String::from_utf8(msg.to_vec()).unwrap(); + debug!("IN: {}", m); + in_send.send(m).await.unwrap(); + } + Some(Err(e)) => { + error!("Error parsing input: {}", e); + std::process::exit(1); + } + None => { + info!("Received EOF, exiting."); + std::process::exit(0); + } + } + } + + } + } +} diff --git a/apps/desktop/electron-builder.json b/apps/desktop/electron-builder.json index 09783f26f49..be30e063c1a 100644 --- a/apps/desktop/electron-builder.json +++ b/apps/desktop/electron-builder.json @@ -73,6 +73,13 @@ "CFBundleDevelopmentRegion": "en" }, "singleArchFiles": "node_modules/@bitwarden/desktop-napi/desktop_napi.darwin-*.node", + "extraFiles": [ + { + "from": "desktop_native/dist/desktop_proxy.${platform}-${arch}", + "to": "MacOS/desktop_proxy" + } + ], + "signIgnore": ["MacOS/desktop_proxy"], "target": ["dmg", "zip"] }, "win": { @@ -84,16 +91,24 @@ "from": "../../node_modules/regedit/vbs", "to": "regedit/vbs", "filter": ["**/*"] - }, + } + ], + "extraFiles": [ { - "from": "resources/native-messaging.bat", - "to": "native-messaging.bat" + "from": "desktop_native/dist/desktop_proxy.${platform}-${arch}.exe", + "to": "desktop_proxy.exe" } ] }, "linux": { "category": "Utility", "synopsis": "A secure and free password manager for all of your devices.", + "extraFiles": [ + { + "from": "desktop_native/dist/desktop_proxy.${platform}-${arch}", + "to": "desktop_proxy" + } + ], "target": ["deb", "freebsd", "rpm", "AppImage", "snap"], "desktop": { "Name": "Bitwarden", diff --git a/apps/desktop/package.json b/apps/desktop/package.json index c50e7ccbac4..fbf598327f4 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -18,7 +18,7 @@ "scripts": { "postinstall": "electron-rebuild", "start": "cross-env ELECTRON_IS_DEV=0 ELECTRON_NO_UPDATER=1 electron ./build", - "build-native": "cd desktop_native/napi && npm run build", + "build-native": "cd desktop_native && node build.js", "build": "concurrently -n Main,Rend,Prel -c yellow,cyan \"npm run build:main\" \"npm run build:renderer\" \"npm run build:preload\"", "build:dev": "concurrently -n Main,Rend -c yellow,cyan \"npm run build:main:dev\" \"npm run build:renderer:dev\"", "build:preload": "cross-env NODE_ENV=production webpack --config webpack.preload.js", diff --git a/apps/desktop/resources/entitlements.desktop_proxy.plist b/apps/desktop/resources/entitlements.desktop_proxy.plist new file mode 100644 index 00000000000..d5c7b8a2cc8 --- /dev/null +++ b/apps/desktop/resources/entitlements.desktop_proxy.plist @@ -0,0 +1,12 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.application-groups + + LTZ2PFU5D6.com.bitwarden.desktop + + + diff --git a/apps/desktop/resources/entitlements.mas.plist b/apps/desktop/resources/entitlements.mas.plist index 5bfeba83a61..d42ade962c3 100644 --- a/apps/desktop/resources/entitlements.mas.plist +++ b/apps/desktop/resources/entitlements.mas.plist @@ -8,6 +8,10 @@ LTZ2PFU5D6 com.apple.security.app-sandbox + com.apple.security.application-groups + + LTZ2PFU5D6.com.bitwarden.desktop + com.apple.security.network.client com.apple.security.files.user-selected.read-write diff --git a/apps/desktop/resources/info.desktop_proxy.plist b/apps/desktop/resources/info.desktop_proxy.plist new file mode 100644 index 00000000000..d3c30e3e0eb --- /dev/null +++ b/apps/desktop/resources/info.desktop_proxy.plist @@ -0,0 +1,8 @@ + + + + + CFBundleIdentifier + com.bitwarden.desktop + + diff --git a/apps/desktop/resources/native-messaging.bat b/apps/desktop/resources/native-messaging.bat deleted file mode 100644 index 45519250dd6..00000000000 --- a/apps/desktop/resources/native-messaging.bat +++ /dev/null @@ -1,7 +0,0 @@ -@echo off -:: Helper script for starting the Native Messaging Proxy on Windows. - -cd ../ -set ELECTRON_RUN_AS_NODE=1 -set ELECTRON_NO_ATTACH_CONSOLE=1 -Bitwarden.exe resources/app.asar %* diff --git a/apps/desktop/scripts/after-pack.js b/apps/desktop/scripts/after-pack.js index e128397e615..08cff76e858 100644 --- a/apps/desktop/scripts/after-pack.js +++ b/apps/desktop/scripts/after-pack.js @@ -1,14 +1,22 @@ /* eslint-disable @typescript-eslint/no-var-requires, no-console */ require("dotenv").config(); +const child_process = require("child_process"); const path = require("path"); +const { flipFuses, FuseVersion, FuseV1Options } = require("@electron/fuses"); +const builder = require("electron-builder"); const fse = require("fs-extra"); exports.default = run; async function run(context) { console.log("## After pack"); - console.log(context); + // console.log(context); + + if (context.packager.platform.nodeName !== "darwin" || context.arch === builder.Arch.universal) { + await addElectronFuses(context); + } + if (context.electronPlatformName === "linux") { console.log("Creating memory-protection wrapper script"); const appOutDir = context.appOutDir; @@ -23,4 +31,132 @@ async function run(context) { fse.chmodSync(wrapperBin, "755"); console.log("Copied memory-protection wrapper script"); } + + if (["darwin", "mas"].includes(context.electronPlatformName)) { + const is_mas = context.electronPlatformName === "mas"; + const is_mas_dev = context.targets.some((e) => e.name === "mas-dev"); + + let id; + + // Only use the Bitwarden Identities on CI + if (process.env.GITHUB_ACTIONS === "true") { + if (is_mas) { + id = is_mas_dev + ? "E7C9978F6FBCE0553429185C405E61F5380BE8EB" + : "3rd Party Mac Developer Application: Bitwarden Inc"; + } else { + id = "Developer ID Application: 8bit Solutions LLC"; + } + // Locally, use the first valid code signing identity, unless CSC_NAME is set + } else if (process.env.CSC_NAME) { + id = process.env.CSC_NAME; + } else { + const identities = getIdentities(); + if (identities.length === 0) { + throw new Error("No valid identities found"); + } + id = identities[0].id; + } + + console.log(`Signing proxy binary before the main bundle, using identity '${id}'`); + + const appName = context.packager.appInfo.productFilename; + const appPath = `${context.appOutDir}/${appName}.app`; + const proxyPath = path.join(appPath, "Contents", "MacOS", "desktop_proxy"); + + const packageId = "com.bitwarden.desktop"; + const entitlementsName = "entitlements.desktop_proxy.plist"; + const entitlementsPath = path.join(__dirname, "..", "resources", entitlementsName); + child_process.execSync( + `codesign -s '${id}' -i ${packageId} -f --timestamp --options runtime --entitlements ${entitlementsPath} ${proxyPath}`, + ); + } +} + +// Partially based on electron-builder code: +// https://github.com/electron-userland/electron-builder/blob/master/packages/app-builder-lib/src/macPackager.ts +// https://github.com/electron-userland/electron-builder/blob/master/packages/app-builder-lib/src/codeSign/macCodeSign.ts + +const appleCertificatePrefixes = [ + "Developer ID Application:", + // "Developer ID Installer:", + // "3rd Party Mac Developer Application:", + // "3rd Party Mac Developer Installer:", + "Apple Development:", +]; + +function getIdentities() { + const ids = child_process + .execSync("/usr/bin/security find-identity -v -p codesigning") + .toString(); + + return ids + .split("\n") + .filter((line) => { + for (const prefix of appleCertificatePrefixes) { + if (line.includes(prefix)) { + return true; + } + } + return false; + }) + .map((line) => { + const split = line.trim().split(" "); + const id = split[1]; + const name = split.slice(2).join(" ").replace(/"/g, ""); + return { id, name }; + }); +} + +/** + * @param {import("electron-builder").AfterPackContext} context + */ +async function addElectronFuses(context) { + const platform = context.packager.platform.nodeName; + + const ext = { + darwin: ".app", + win32: ".exe", + linux: "", + }[platform]; + + const IS_LINUX = platform === "linux"; + const executableName = IS_LINUX + ? context.packager.appInfo.productFilename.toLowerCase().replace("-dev", "").replace(" ", "-") + : context.packager.appInfo.productFilename; // .toLowerCase() to accomodate Linux file named `name` but productFileName is `Name` -- Replaces '-dev' because on Linux the executable name is `name` even for the DEV builds + + const electronBinaryPath = path.join(context.appOutDir, `${executableName}${ext}`); + + console.log("## Adding fuses to the electron binary", electronBinaryPath); + + await flipFuses(electronBinaryPath, { + version: FuseVersion.V1, + strictlyRequireAllFuses: true, + resetAdHocDarwinSignature: platform === "darwin" && context.arch === builder.Arch.universal, + + // List of fuses and their default values is available at: + // https://www.electronjs.org/docs/latest/tutorial/fuses + + [FuseV1Options.RunAsNode]: false, + [FuseV1Options.EnableCookieEncryption]: true, + [FuseV1Options.EnableNodeOptionsEnvironmentVariable]: false, + [FuseV1Options.EnableNodeCliInspectArguments]: false, + + // Currently, asar integrity is only implemented for macOS and Windows + // https://www.electronjs.org/docs/latest/tutorial/asar-integrity + // On macOS, it works by default, but on Windows it requires the + // asarIntegrity feature of electron-builder v25, currently in alpha + // https://github.com/electron-userland/electron-builder/releases/tag/v25.0.0-alpha.10 + [FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: platform === "darwin", + + [FuseV1Options.OnlyLoadAppFromAsar]: true, + + // App refuses to open when enabled + [FuseV1Options.LoadBrowserProcessSpecificV8Snapshot]: false, + + // To disable this, we should stop using the file:// protocol to load the app bundle + // This can be done by defining a custom app:// protocol and loading the bundle from there, + // but then any requests to the server will be blocked by CORS policy + [FuseV1Options.GrantFileProtocolExtraPrivileges]: true, + }); } diff --git a/apps/desktop/src/entry.ts b/apps/desktop/src/entry.ts index 78fe51e8b9e..3bb84461363 100644 --- a/apps/desktop/src/entry.ts +++ b/apps/desktop/src/entry.ts @@ -1,31 +1,33 @@ -import { NativeMessagingProxy } from "./proxy/native-messaging-proxy"; +import { spawn } from "child_process"; +import * as path from "path"; -// We need to import the other dependencies using `require` since `import` will -// generate `Error: Cannot find module 'electron'`. The cause of this error is -// due to native messaging setting the ELECTRON_RUN_AS_NODE env flag on windows -// which removes the electron module. This flag is needed for stdin/out to work -// properly on Windows. +import { app } from "electron"; if ( + process.platform === "darwin" && process.argv.some((arg) => arg.indexOf("chrome-extension://") !== -1 || arg.indexOf("{") !== -1) ) { - if (process.platform === "darwin") { - // eslint-disable-next-line - const app = require("electron").app; + // If we're on MacOS, we need to support DuckDuckGo's IPC communication, + // which for the moment is launching the Bitwarden process. + // Ideally the browser would instead startup the desktop_proxy process + // when available, but for now we'll just launch it here. - app.on("ready", () => { - app.dock.hide(); - }); - } - - process.stdout.on("error", (e) => { - if (e.code === "EPIPE") { - process.exit(0); - } + app.on("ready", () => { + app.dock.hide(); }); - const proxy = new NativeMessagingProxy(); - proxy.run(); + const proc = spawn(path.join(process.execPath, "..", "desktop_proxy"), process.argv.slice(1), { + cwd: process.cwd(), + stdio: "inherit", + shell: false, + }); + + proc.on("exit", () => { + process.exit(0); + }); + proc.on("error", () => { + process.exit(1); + }); } else { // eslint-disable-next-line const Main = require("./main").Main; diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index cf680c3bd96..723b410f19b 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -227,6 +227,7 @@ export class Main { this.windowMain, app.getPath("userData"), app.getPath("exe"), + app.getAppPath(), ); this.desktopAutofillSettingsService = new DesktopAutofillSettingsService(stateProvider); @@ -273,13 +274,21 @@ export class Main { if (browserIntegrationEnabled || ddgIntegrationEnabled) { // Re-register the native messaging host integrations on startup, in case they are not present if (browserIntegrationEnabled) { - this.nativeMessagingMain.generateManifests().catch(this.logService.error); + this.nativeMessagingMain + .generateManifests() + .catch((err) => this.logService.error("Error while generating manifests", err)); } if (ddgIntegrationEnabled) { - this.nativeMessagingMain.generateDdgManifests().catch(this.logService.error); + this.nativeMessagingMain + .generateDdgManifests() + .catch((err) => this.logService.error("Error while generating DDG manifests", err)); } - this.nativeMessagingMain.listen(); + this.nativeMessagingMain + .listen() + .catch((err) => + this.logService.error("Error while starting native message listener", err), + ); } app.removeAsDefaultProtocolClient("bitwarden"); diff --git a/apps/desktop/src/main/native-messaging.main.ts b/apps/desktop/src/main/native-messaging.main.ts index 8c8404578b6..036f35e61c8 100644 --- a/apps/desktop/src/main/native-messaging.main.ts +++ b/apps/desktop/src/main/native-messaging.main.ts @@ -1,34 +1,34 @@ import { existsSync, promises as fs } from "fs"; -import { Socket } from "net"; import { homedir, userInfo } from "os"; import * as path from "path"; import * as util from "util"; import { ipcMain } from "electron"; -import * as ipc from "node-ipc"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { ipc } from "@bitwarden/desktop-napi"; -import { getIpcSocketRoot } from "../proxy/ipc"; +import { isDev } from "../utils"; import { WindowMain } from "./window.main"; export class NativeMessagingMain { - private connected: Socket[] = []; - private socket: any; + private ipcServer: ipc.IpcServer | null; + private connected: number[] = []; constructor( private logService: LogService, private windowMain: WindowMain, private userPath: string, private exePath: string, + private appPath: string, ) { ipcMain.handle( "nativeMessaging.manifests", async (_event: any, options: { create: boolean }) => { if (options.create) { - this.listen(); try { + await this.listen(); await this.generateManifests(); } catch (e) { this.logService.error("Error generating manifests: " + e); @@ -51,8 +51,8 @@ export class NativeMessagingMain { "nativeMessaging.ddgManifests", async (_event: any, options: { create: boolean }) => { if (options.create) { - this.listen(); try { + await this.listen(); await this.generateDdgManifests(); } catch (e) { this.logService.error("Error generating duckduckgo manifests: " + e); @@ -72,56 +72,46 @@ export class NativeMessagingMain { ); } - listen() { - ipc.config.id = "bitwarden"; - ipc.config.retry = 1500; - const ipcSocketRoot = getIpcSocketRoot(); - if (ipcSocketRoot != null) { - ipc.config.socketRoot = ipcSocketRoot; + async listen() { + if (this.ipcServer) { + this.ipcServer.stop(); } - ipc.serve(() => { - ipc.server.on("message", (data: any, socket: any) => { - this.socket = socket; - this.windowMain.win.webContents.send("nativeMessaging", data); - }); - - ipcMain.on("nativeMessagingReply", (event, msg) => { - if (this.socket != null && msg != null) { - this.send(msg, this.socket); + this.ipcServer = await ipc.IpcServer.listen("bitwarden", (error, msg) => { + switch (msg.kind) { + case ipc.IpcMessageType.Connected: { + this.connected.push(msg.clientId); + this.logService.info("Native messaging client " + msg.clientId + " has connected"); + break; } - }); + case ipc.IpcMessageType.Disconnected: { + const index = this.connected.indexOf(msg.clientId); + if (index > -1) { + this.connected.splice(index, 1); + } - ipc.server.on("connect", (socket: Socket) => { - this.connected.push(socket); - }); - - ipc.server.on("socket.disconnected", (socket, destroyedSocketID) => { - const index = this.connected.indexOf(socket); - if (index > -1) { - this.connected.splice(index, 1); + this.logService.info("Native messaging client " + msg.clientId + " has disconnected"); + break; } - - this.socket = null; - ipc.log("client " + destroyedSocketID + " has disconnected!"); - }); + case ipc.IpcMessageType.Message: + this.windowMain.win.webContents.send("nativeMessaging", JSON.parse(msg.message)); + break; + } }); - ipc.server.start(); - } - - stop() { - ipc.server.stop(); - // Kill all existing connections - this.connected.forEach((socket) => { - if (!socket.destroyed) { - socket.destroy(); + ipcMain.on("nativeMessagingReply", (event, msg) => { + if (msg != null) { + this.send(msg); } }); } - send(message: object, socket: any) { - ipc.server.emit(socket, "message", message); + stop() { + this.ipcServer?.stop(); + } + + send(message: object) { + this.ipcServer?.send(JSON.stringify(message)); } async generateManifests() { @@ -331,11 +321,20 @@ export class NativeMessagingMain { } private binaryPath() { - if (process.platform === "win32") { - return path.join(path.dirname(this.exePath), "resources", "native-messaging.bat"); + const ext = process.platform === "win32" ? ".exe" : ""; + + if (isDev()) { + return path.join( + this.appPath, + "..", + "desktop_native", + "target", + "debug", + `desktop_proxy${ext}`, + ); } - return this.exePath; + return path.join(path.dirname(this.exePath), `desktop_proxy${ext}`); } private getRegeditInstance() { diff --git a/apps/desktop/src/proxy/ipc.ts b/apps/desktop/src/proxy/ipc.ts deleted file mode 100644 index 0160d6bf294..00000000000 --- a/apps/desktop/src/proxy/ipc.ts +++ /dev/null @@ -1,78 +0,0 @@ -/* eslint-disable no-console */ -import { createHash } from "crypto"; -import { existsSync, mkdirSync } from "fs"; -import { homedir } from "os"; -import { join as path_join } from "path"; - -import * as ipc from "node-ipc"; - -export function getIpcSocketRoot(): string | null { - let socketRoot = null; - - switch (process.platform) { - case "darwin": { - const ipcSocketRootDir = path_join(homedir(), "tmp"); - if (!existsSync(ipcSocketRootDir)) { - mkdirSync(ipcSocketRootDir); - } - socketRoot = ipcSocketRootDir + "/"; - break; - } - case "win32": { - // Let node-ipc use a unique IPC pipe //./pipe/xxxxxxxxxxxxxxxxx.app.bitwarden per user. - // Hashing prevents problems with reserved characters and file length limitations. - socketRoot = createHash("sha1").update(homedir()).digest("hex") + "."; - } - } - return socketRoot; -} - -ipc.config.id = "proxy"; -ipc.config.retry = 1500; -ipc.config.logger = console.warn; // Stdout is used for native messaging -const ipcSocketRoot = getIpcSocketRoot(); -if (ipcSocketRoot != null) { - ipc.config.socketRoot = ipcSocketRoot; -} - -export default class IPC { - onMessage: (message: object) => void; - - private connected = false; - - connect() { - ipc.connectTo("bitwarden", () => { - ipc.of.bitwarden.on("connect", () => { - this.connected = true; - console.error("## connected to bitwarden desktop ##"); - - // Notify browser extension, connection is established to desktop application. - this.onMessage({ command: "connected" }); - }); - - ipc.of.bitwarden.on("disconnect", () => { - this.connected = false; - console.error("disconnected from world"); - - // Notify browser extension, no connection to desktop application. - this.onMessage({ command: "disconnected" }); - }); - - ipc.of.bitwarden.on("message", (message: any) => { - this.onMessage(message); - }); - - ipc.of.bitwarden.on("error", (err: any) => { - console.error("error", err); - }); - }); - } - - isConnected(): boolean { - return this.connected; - } - - send(json: object) { - ipc.of.bitwarden.emit("message", json); - } -} diff --git a/apps/desktop/src/proxy/native-messaging-proxy.ts b/apps/desktop/src/proxy/native-messaging-proxy.ts deleted file mode 100644 index f1b54a82014..00000000000 --- a/apps/desktop/src/proxy/native-messaging-proxy.ts +++ /dev/null @@ -1,23 +0,0 @@ -import IPC from "./ipc"; -import NativeMessage from "./nativemessage"; - -// Proxy is a lightweight application which provides bi-directional communication -// between the browser extension and a running desktop application. -// -// Browser extension <-[native messaging]-> proxy <-[ipc]-> desktop -export class NativeMessagingProxy { - private ipc: IPC; - private nativeMessage: NativeMessage; - - constructor() { - this.ipc = new IPC(); - this.nativeMessage = new NativeMessage(this.ipc); - } - - run() { - this.ipc.connect(); - this.nativeMessage.listen(); - - this.ipc.onMessage = this.nativeMessage.send; - } -} diff --git a/apps/desktop/src/proxy/nativemessage.ts b/apps/desktop/src/proxy/nativemessage.ts deleted file mode 100644 index f7a32296f84..00000000000 --- a/apps/desktop/src/proxy/nativemessage.ts +++ /dev/null @@ -1,95 +0,0 @@ -/* eslint-disable no-console */ -import IPC from "./ipc"; - -// Mostly based on the example from MDN, -// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging -export default class NativeMessage { - ipc: IPC; - - constructor(ipc: IPC) { - this.ipc = ipc; - } - - send(message: object) { - const messageBuffer = Buffer.from(JSON.stringify(message)); - - const headerBuffer = Buffer.alloc(4); - headerBuffer.writeUInt32LE(messageBuffer.length, 0); - - process.stdout.write(Buffer.concat([headerBuffer, messageBuffer])); - } - - listen() { - let payloadSize: number = null; - - // A queue to store the chunks as we read them from stdin. - // This queue can be flushed when `payloadSize` data has been read - const chunks: any = []; - - // Only read the size once for each payload - const sizeHasBeenRead = () => Boolean(payloadSize); - - // All the data has been read, reset everything for the next message - const flushChunksQueue = () => { - payloadSize = null; - chunks.splice(0); - }; - - const processData = () => { - // Create one big buffer with all all the chunks - const stringData = Buffer.concat(chunks); - console.error(stringData); - - // The browser will emit the size as a header of the payload, - // if it hasn't been read yet, do it. - // The next time we'll need to read the payload size is when all of the data - // of the current payload has been read (ie. data.length >= payloadSize + 4) - if (!sizeHasBeenRead()) { - try { - payloadSize = stringData.readUInt32LE(0); - } catch (e) { - console.error(e); - return; - } - } - - // If the data we have read so far is >= to the size advertised in the header, - // it means we have all of the data sent. - // We add 4 here because that's the size of the bytes that old the payloadSize - if (stringData.length >= payloadSize + 4) { - // Remove the header - const contentWithoutSize = stringData.slice(4, payloadSize + 4).toString(); - - // Reset the read size and the queued chunks - flushChunksQueue(); - - const json = JSON.parse(contentWithoutSize); - - // Forward to desktop application - this.ipc.send(json); - } - }; - - process.stdin.on("readable", () => { - // A temporary variable holding the nodejs.Buffer of each - // chunk of data read off stdin - let chunk = null; - - // Read all of the available data - // tslint:disable-next-line:no-conditional-assignment - while ((chunk = process.stdin.read()) !== null) { - chunks.push(chunk); - } - - try { - processData(); - } catch (e) { - console.error(e); - } - }); - - process.stdin.on("end", () => { - process.exit(0); - }); - } -} diff --git a/package-lock.json b/package-lock.json index d760d36e573..c2571510a9b 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", + "@electron/fuses": "1.8.0", "@koa/multer": "3.0.2", "@koa/router": "12.0.1", "@microsoft/signalr": "8.0.7", @@ -5126,6 +5127,33 @@ "node": "*" } }, + "node_modules/@electron/fuses": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@electron/fuses/-/fuses-1.8.0.tgz", + "integrity": "sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==", + "dependencies": { + "chalk": "^4.1.1", + "fs-extra": "^9.0.1", + "minimist": "^1.2.5" + }, + "bin": { + "electron-fuses": "dist/bin.js" + } + }, + "node_modules/@electron/fuses/node_modules/fs-extra": { + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", + "dependencies": { + "at-least-node": "^1.0.0", + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/@electron/get": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/@electron/get/-/get-2.0.3.tgz", diff --git a/package.json b/package.json index b1e69fca494..d2a42da8592 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", + "@electron/fuses": "1.8.0", "@koa/multer": "3.0.2", "@koa/router": "12.0.1", "@microsoft/signalr": "8.0.7", From 6e7c83305e85ca1f0fc1ee78fff39174628a9653 Mon Sep 17 00:00:00 2001 From: Jordan Aasen <166539328+jaasen-livefront@users.noreply.github.com> Date: Tue, 1 Oct 2024 07:35:39 -0700 Subject: [PATCH 10/15] [PM-12990]- center align footer buttons (#11342) * center align footer buttons * fix popup-tab-navigation layout --- .../platform/popup/layout/popup-tab-navigation.component.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/browser/src/platform/popup/layout/popup-tab-navigation.component.html b/apps/browser/src/platform/popup/layout/popup-tab-navigation.component.html index a0ff252c6c2..972a60d31ad 100644 --- a/apps/browser/src/platform/popup/layout/popup-tab-navigation.component.html +++ b/apps/browser/src/platform/popup/layout/popup-tab-navigation.component.html @@ -6,7 +6,7 @@ - + - {{ cipher.subTitle }} - + From 256c6aef5ca48be1ee0dbf27f8333b0b3c5138ba Mon Sep 17 00:00:00 2001 From: Alex Yao <33379584+alexyao2015@users.noreply.github.com> Date: Tue, 1 Oct 2024 12:40:28 -0500 Subject: [PATCH 14/15] native-messaging: Add chromium support (#11230) --- apps/desktop/src/main/native-messaging.main.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/apps/desktop/src/main/native-messaging.main.ts b/apps/desktop/src/main/native-messaging.main.ts index 036f35e61c8..ec57ecdf7bb 100644 --- a/apps/desktop/src/main/native-messaging.main.ts +++ b/apps/desktop/src/main/native-messaging.main.ts @@ -201,6 +201,13 @@ export class NativeMessagingMain { chromeJson, ); } + + if (existsSync(`${this.homedir()}/.config/chromium/`)) { + await this.writeManifest( + `${this.homedir()}/.config/chromium/NativeMessagingHosts/com.8bit.bitwarden.json`, + chromeJson, + ); + } break; default: break; From ab5a02f4830ae5f9d1b5c7f6767b40ffabb92820 Mon Sep 17 00:00:00 2001 From: Jordan Aasen <166539328+jaasen-livefront@users.noreply.github.com> Date: Tue, 1 Oct 2024 11:46:10 -0700 Subject: [PATCH 15/15] [PM-12774] - don't display filters when no sends are available (#11298) * don't display filters when no sends are available * move logic down. add conditional class * fix logic for send filters --- apps/browser/src/tools/popup/send-v2/send-v2.component.html | 2 +- libs/tools/send/send-ui/src/services/send-items.service.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/browser/src/tools/popup/send-v2/send-v2.component.html b/apps/browser/src/tools/popup/send-v2/send-v2.component.html index 0baa43a4b56..23cc692a598 100644 --- a/apps/browser/src/tools/popup/send-v2/send-v2.component.html +++ b/apps/browser/src/tools/popup/send-v2/send-v2.component.html @@ -10,7 +10,7 @@ {{ "sendDisabledWarning" | i18n }} - + diff --git a/libs/tools/send/send-ui/src/services/send-items.service.ts b/libs/tools/send/send-ui/src/services/send-items.service.ts index 66ad5b67864..6cef663f891 100644 --- a/libs/tools/send/send-ui/src/services/send-items.service.ts +++ b/libs/tools/send/send-ui/src/services/send-items.service.ts @@ -83,7 +83,7 @@ export class SendItemsService { ); /** - * Observable that indicates whether the user's vault is empty. + * Observable that indicates whether the user's send list is empty. */ emptyList$: Observable = this._sendList$.pipe(map((sends) => !sends.length));