1
0
mirror of https://github.com/bitwarden/browser synced 2026-02-28 02:23:25 +00:00

Merge remote-tracking branch 'origin' into auth/pm-19877/notification-processing

This commit is contained in:
Patrick Pimentel
2025-07-23 10:20:48 -04:00
558 changed files with 22610 additions and 5035 deletions

View File

@@ -1,6 +1,7 @@
import { EncryptionContext } from "@bitwarden/common/vault/abstractions/cipher.service";
import { CipherListView } from "@bitwarden/sdk-internal";
import { UserId } from "../../types/guid";
import { UserId, OrganizationId } from "../../types/guid";
import { Cipher } from "../models/domain/cipher";
import { AttachmentView } from "../models/view/attachment.view";
import { CipherView } from "../models/view/cipher.view";
@@ -9,6 +10,28 @@ import { CipherView } from "../models/view/cipher.view";
* Service responsible for encrypting and decrypting ciphers.
*/
export abstract class CipherEncryptionService {
/**
* Encrypts a cipher using the SDK for the given userId.
* @param model The cipher view to encrypt
* @param userId The user ID to initialize the SDK client with
*
* @returns A promise that resolves to the encryption context, or undefined if encryption fails
*/
abstract encrypt(model: CipherView, userId: UserId): Promise<EncryptionContext | undefined>;
/**
* Move the cipher to the specified organization by re-encrypting its keys with the organization's key.
* The cipher.organizationId will be updated to the new organizationId.
* @param model The cipher view to move to the organization
* @param organizationId The ID of the organization to move the cipher to
* @param userId The user ID to initialize the SDK client with
*/
abstract moveToOrganization(
model: CipherView,
organizationId: OrganizationId,
userId: UserId,
): Promise<EncryptionContext | undefined>;
/**
* Decrypts a cipher using the SDK for the given userId.
*

View File

@@ -1,10 +1,9 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { Observable } from "rxjs";
// This import has been flagged as unallowed for this class. It may be involved in a circular dependency loop.
// eslint-disable-next-line no-restricted-imports
import { UserKeyRotationDataProvider } from "@bitwarden/key-management";
import { CipherListView } from "@bitwarden/sdk-internal";
import { UriMatchStrategySetting } from "../../models/domain/domain-service";
import { SymmetricCryptoKey } from "../../platform/models/domain/symmetric-crypto-key";
@@ -20,6 +19,7 @@ import { AttachmentView } from "../models/view/attachment.view";
import { CipherView } from "../models/view/cipher.view";
import { FieldView } from "../models/view/field.view";
import { AddEditCipherInfo } from "../types/add-edit-cipher-info";
import { CipherViewLike } from "../utils/cipher-view-like-utils";
export type EncryptionContext = {
cipher: Cipher;
@@ -29,6 +29,7 @@ export type EncryptionContext = {
export abstract class CipherService implements UserKeyRotationDataProvider<CipherWithIdRequest> {
abstract cipherViews$(userId: UserId): Observable<CipherView[]>;
abstract cipherListViews$(userId: UserId): Observable<CipherListView[] | CipherView[]>;
abstract ciphers$(userId: UserId): Observable<Record<CipherId, CipherData>>;
abstract localData$(userId: UserId): Observable<Record<CipherId, LocalData>>;
/**
@@ -65,12 +66,12 @@ export abstract class CipherService implements UserKeyRotationDataProvider<Ciphe
includeOtherTypes?: CipherType[],
defaultMatch?: UriMatchStrategySetting,
): Promise<CipherView[]>;
abstract filterCiphersForUrl(
ciphers: CipherView[],
abstract filterCiphersForUrl<C extends CipherViewLike = CipherView>(
ciphers: C[],
url: string,
includeOtherTypes?: CipherType[],
defaultMatch?: UriMatchStrategySetting,
): Promise<CipherView[]>;
): Promise<C[]>;
abstract getAllFromApiForOrganization(organizationId: string): Promise<CipherView[]>;
/**
* Gets ciphers belonging to the specified organization that the user has explicit collection level access to.
@@ -117,11 +118,21 @@ export abstract class CipherService implements UserKeyRotationDataProvider<Ciphe
orgAdmin?: boolean,
isNotClone?: boolean,
): Promise<Cipher>;
/**
* Move a cipher to an organization by re-encrypting its keys with the organization's key.
* @param cipher The cipher to move
* @param organizationId The Id of the organization to move the cipher to
* @param collectionIds The collection Ids to assign the cipher to in the organization
* @param userId The Id of the user performing the operation
* @param originalCipher Optional original cipher that will be used to compare/update password history
*/
abstract shareWithServer(
cipher: CipherView,
organizationId: string,
collectionIds: string[],
userId: UserId,
originalCipher?: Cipher,
): Promise<Cipher>;
abstract shareManyWithServer(
ciphers: CipherView[],
@@ -198,9 +209,9 @@ export abstract class CipherService implements UserKeyRotationDataProvider<Ciphe
userId: UserId,
admin: boolean,
): Promise<CipherData>;
abstract sortCiphersByLastUsed(a: CipherView, b: CipherView): number;
abstract sortCiphersByLastUsedThenName(a: CipherView, b: CipherView): number;
abstract getLocaleSortingFunction(): (a: CipherView, b: CipherView) => number;
abstract sortCiphersByLastUsed(a: CipherViewLike, b: CipherViewLike): number;
abstract sortCiphersByLastUsedThenName(a: CipherViewLike, b: CipherViewLike): number;
abstract getLocaleSortingFunction(): (a: CipherViewLike, b: CipherViewLike) => number;
abstract softDelete(id: string | string[], userId: UserId): Promise<any>;
abstract softDeleteWithServer(id: string, userId: UserId, asAdmin?: boolean): Promise<any>;
abstract softDeleteManyWithServer(ids: string[], userId: UserId, asAdmin?: boolean): Promise<any>;
@@ -251,4 +262,10 @@ export abstract class CipherService implements UserKeyRotationDataProvider<Ciphe
response: Response,
userId: UserId,
): Promise<Uint8Array | null>;
/**
* Decrypts the full `CipherView` for a given `CipherViewLike`.
* When a `CipherView` instance is passed, it returns it as is.
*/
abstract getFullCipherView(c: CipherViewLike): Promise<CipherView>;
}

View File

@@ -1,5 +1,3 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { EncString } from "../../../key-management/crypto/models/enc-string";
import { EncArrayBuffer } from "../../../platform/models/domain/enc-array-buffer";
import { SymmetricCryptoKey } from "../../../platform/models/domain/symmetric-crypto-key";
@@ -7,11 +5,11 @@ import { Cipher } from "../../models/domain/cipher";
import { CipherResponse } from "../../models/response/cipher.response";
export abstract class CipherFileUploadService {
upload: (
abstract upload(
cipher: Cipher,
encFileName: EncString,
encData: EncArrayBuffer,
admin: boolean,
dataEncKey: [SymmetricCryptoKey, EncString],
) => Promise<CipherResponse>;
): Promise<CipherResponse>;
}

View File

@@ -1,14 +1,11 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { UserId } from "../../../types/guid";
import { FolderData } from "../../models/data/folder.data";
import { Folder } from "../../models/domain/folder";
import { FolderResponse } from "../../models/response/folder.response";
export class FolderApiServiceAbstraction {
save: (folder: Folder, userId: UserId) => Promise<FolderData>;
delete: (id: string, userId: UserId) => Promise<any>;
get: (id: string) => Promise<FolderResponse>;
deleteAll: (userId: UserId) => Promise<void>;
export abstract class FolderApiServiceAbstraction {
abstract save(folder: Folder, userId: UserId): Promise<FolderData>;
abstract delete(id: string, userId: UserId): Promise<any>;
abstract get(id: string): Promise<FolderResponse>;
abstract deleteAll(userId: UserId): Promise<void>;
}

View File

@@ -1,5 +1,3 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { Observable } from "rxjs";
// This import has been flagged as unallowed for this class. It may be involved in a circular dependency loop.
@@ -15,27 +13,27 @@ import { FolderWithIdRequest } from "../../models/request/folder-with-id.request
import { FolderView } from "../../models/view/folder.view";
export abstract class FolderService implements UserKeyRotationDataProvider<FolderWithIdRequest> {
folders$: (userId: UserId) => Observable<Folder[]>;
folderViews$: (userId: UserId) => Observable<FolderView[]>;
abstract folders$(userId: UserId): Observable<Folder[]>;
abstract folderViews$(userId: UserId): Observable<FolderView[]>;
clearDecryptedFolderState: (userId: UserId) => Promise<void>;
encrypt: (model: FolderView, key: SymmetricCryptoKey) => Promise<Folder>;
get: (id: string, userId: UserId) => Promise<Folder>;
getDecrypted$: (id: string, userId: UserId) => Observable<FolderView | undefined>;
abstract clearDecryptedFolderState(userId: UserId): Promise<void>;
abstract encrypt(model: FolderView, key: SymmetricCryptoKey): Promise<Folder>;
abstract get(id: string, userId: UserId): Promise<Folder>;
abstract getDecrypted$(id: string, userId: UserId): Observable<FolderView | undefined>;
/**
* @deprecated Use firstValueFrom(folders$) directly instead
* @param userId The user id
* @returns Promise of folders array
*/
getAllFromState: (userId: UserId) => Promise<Folder[]>;
abstract getAllFromState(userId: UserId): Promise<Folder[]>;
/**
* @deprecated Only use in CLI!
*/
getFromState: (id: string, userId: UserId) => Promise<Folder>;
abstract getFromState(id: string, userId: UserId): Promise<Folder>;
/**
* @deprecated Only use in CLI!
*/
getAllDecryptedFromState: (userId: UserId) => Promise<FolderView[]>;
abstract getAllDecryptedFromState(userId: UserId): Promise<FolderView[]>;
/**
* Returns user folders re-encrypted with the new user key.
* @param originalUserKey the original user key
@@ -44,16 +42,16 @@ export abstract class FolderService implements UserKeyRotationDataProvider<Folde
* @throws Error if new user key is null
* @returns a list of user folders that have been re-encrypted with the new user key
*/
getRotatedData: (
abstract getRotatedData(
originalUserKey: UserKey,
newUserKey: UserKey,
userId: UserId,
) => Promise<FolderWithIdRequest[]>;
): Promise<FolderWithIdRequest[]>;
}
export abstract class InternalFolderService extends FolderService {
upsert: (folder: FolderData | FolderData[], userId: UserId) => Promise<void>;
replace: (folders: { [id: string]: FolderData }, userId: UserId) => Promise<void>;
clear: (userId: UserId) => Promise<void>;
delete: (id: string | string[], userId: UserId) => Promise<any>;
abstract upsert(folder: FolderData | FolderData[], userId: UserId): Promise<void>;
abstract replace(folders: { [id: string]: FolderData }, userId: UserId): Promise<void>;
abstract clear(userId: UserId): Promise<void>;
abstract delete(id: string | string[], userId: UserId): Promise<any>;
}

View File

@@ -1,27 +1,30 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { Observable } from "rxjs";
import { SendView } from "../../tools/send/models/view/send.view";
import { IndexedEntityId, UserId } from "../../types/guid";
import { CipherView } from "../models/view/cipher.view";
import { CipherViewLike } from "../utils/cipher-view-like-utils";
export abstract class SearchService {
indexedEntityId$: (userId: UserId) => Observable<IndexedEntityId | null>;
abstract indexedEntityId$(userId: UserId): Observable<IndexedEntityId | null>;
clearIndex: (userId: UserId) => Promise<void>;
isSearchable: (userId: UserId, query: string) => Promise<boolean>;
indexCiphers: (
abstract clearIndex(userId: UserId): Promise<void>;
abstract isSearchable(userId: UserId, query: string): Promise<boolean>;
abstract indexCiphers(
userId: UserId,
ciphersToIndex: CipherView[],
indexedEntityGuid?: string,
) => Promise<void>;
searchCiphers: (
): Promise<void>;
abstract searchCiphers<C extends CipherViewLike>(
userId: UserId,
query: string,
filter?: ((cipher: CipherView) => boolean) | ((cipher: CipherView) => boolean)[],
ciphers?: CipherView[],
) => Promise<CipherView[]>;
searchCiphersBasic: (ciphers: CipherView[], query: string, deleted?: boolean) => CipherView[];
searchSends: (sends: SendView[], query: string) => SendView[];
filter?: ((cipher: C) => boolean) | ((cipher: C) => boolean)[],
ciphers?: C[],
): Promise<C[]>;
abstract searchCiphersBasic<C extends CipherViewLike>(
ciphers: C[],
query: string,
deleted?: boolean,
): C[];
abstract searchSends(sends: SendView[], query: string): SendView[];
}

View File

@@ -1,5 +1,3 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { Observable } from "rxjs";
/**
* Service for managing vault settings.
@@ -9,42 +7,40 @@ export abstract class VaultSettingsService {
* An observable monitoring the state of the enable passkeys setting.
* The observable updates when the setting changes.
*/
enablePasskeys$: Observable<boolean>;
abstract enablePasskeys$: Observable<boolean>;
/**
* An observable monitoring the state of the show cards on the current tab.
*/
showCardsCurrentTab$: Observable<boolean>;
abstract showCardsCurrentTab$: Observable<boolean>;
/**
* An observable monitoring the state of the show identities on the current tab.
*/
showIdentitiesCurrentTab$: Observable<boolean>;
/**
abstract showIdentitiesCurrentTab$: Observable<boolean>;
/**
* An observable monitoring the state of the click items on the Vault view
* for Autofill suggestions.
*/
clickItemsToAutofillVaultView$: Observable<boolean>;
/**
abstract clickItemsToAutofillVaultView$: Observable<boolean>;
/**
* Saves the enable passkeys setting to disk.
* @param value The new value for the passkeys setting.
*/
setEnablePasskeys: (value: boolean) => Promise<void>;
abstract setEnablePasskeys(value: boolean): Promise<void>;
/**
* Saves the show cards on tab page setting to disk.
* @param value The new value for the show cards on tab page setting.
*/
setShowCardsCurrentTab: (value: boolean) => Promise<void>;
abstract setShowCardsCurrentTab(value: boolean): Promise<void>;
/**
* Saves the show identities on tab page setting to disk.
* @param value The new value for the show identities on tab page setting.
*/
setShowIdentitiesCurrentTab: (value: boolean) => Promise<void>;
abstract setShowIdentitiesCurrentTab(value: boolean): Promise<void>;
/**
* Saves the click items on vault View for Autofill suggestions to disk.
* @param value The new value for the click items on vault View for
* Autofill suggestions setting.
*/
setClickItemsToAutofillVaultView: (value: boolean) => Promise<void>;
abstract setClickItemsToAutofillVaultView(value: boolean): Promise<void>;
}

View File

@@ -1,6 +1,6 @@
import { Utils } from "../../platform/misc/utils";
import { CipherType } from "../enums/cipher-type";
import { CipherView } from "../models/view/cipher.view";
import { CipherViewLike, CipherViewLikeUtils } from "../utils/cipher-view-like-utils";
export interface CipherIconDetails {
imageEnabled: boolean;
@@ -14,7 +14,7 @@ export interface CipherIconDetails {
export function buildCipherIcon(
iconsServerUrl: string | null,
cipher: CipherView,
cipher: CipherViewLike,
showFavicon: boolean,
): CipherIconDetails {
let icon: string = "bwi-globe";
@@ -36,12 +36,16 @@ export function buildCipherIcon(
showFavicon = false;
}
switch (cipher.type) {
const cipherType = CipherViewLikeUtils.getType(cipher);
const uri = CipherViewLikeUtils.uri(cipher);
const card = CipherViewLikeUtils.getCard(cipher);
switch (cipherType) {
case CipherType.Login:
icon = "bwi-globe";
if (cipher.login.uri) {
let hostnameUri = cipher.login.uri;
if (uri) {
let hostnameUri = uri;
let isWebsite = false;
if (hostnameUri.indexOf("androidapp://") === 0) {
@@ -84,8 +88,8 @@ export function buildCipherIcon(
break;
case CipherType.Card:
icon = "bwi-credit-card";
if (showFavicon && cipher.card.brand in cardIcons) {
icon = `credit-card-icon ${cardIcons[cipher.card.brand]}`;
if (showFavicon && card?.brand && card.brand in cardIcons) {
icon = `credit-card-icon ${cardIcons[card.brand]}`;
}
break;
case CipherType.Identity:

View File

@@ -4,7 +4,7 @@ import { CipherPermissions as SdkCipherPermissions } from "@bitwarden/sdk-intern
import { BaseResponse } from "../../../models/response/base.response";
export class CipherPermissionsApi extends BaseResponse {
export class CipherPermissionsApi extends BaseResponse implements SdkCipherPermissions {
delete: boolean = false;
restore: boolean = false;
@@ -35,4 +35,11 @@ export class CipherPermissionsApi extends BaseResponse {
return permissions;
}
/**
* Converts the CipherPermissionsApi to an SdkCipherPermissions
*/
toSdkCipherPermissions(): SdkCipherPermissions {
return this;
}
}

View File

@@ -1,4 +1,45 @@
import {
LocalDataView as SdkLocalDataView,
LocalData as SdkLocalData,
} from "@bitwarden/sdk-internal";
export type LocalData = {
lastUsedDate?: number;
lastLaunched?: number;
};
/**
* Convert the SdkLocalDataView to LocalData
* @param localData
*/
export function fromSdkLocalData(
localData: SdkLocalDataView | SdkLocalData | undefined,
): LocalData | undefined {
if (localData == null) {
return undefined;
}
return {
lastUsedDate: localData.lastUsedDate ? new Date(localData.lastUsedDate).getTime() : undefined,
lastLaunched: localData.lastLaunched ? new Date(localData.lastLaunched).getTime() : undefined,
};
}
/**
* Convert the LocalData to SdkLocalData
* @param localData
*/
export function toSdkLocalData(
localData: LocalData | undefined,
): (SdkLocalDataView & SdkLocalData) | undefined {
if (localData == null) {
return undefined;
}
return {
lastUsedDate: localData.lastUsedDate
? new Date(localData.lastUsedDate).toISOString()
: undefined,
lastLaunched: localData.lastLaunched
? new Date(localData.lastLaunched).toISOString()
: undefined,
};
}

View File

@@ -93,6 +93,7 @@ describe("Attachment", () => {
sizeName: "1.1 KB",
fileName: "fileName",
key: expect.any(SymmetricCryptoKey),
encryptedKey: attachment.key,
});
});

View File

@@ -56,6 +56,7 @@ export class Attachment extends Domain {
if (this.key != null) {
view.key = await this.decryptAttachmentKey(orgId, encKey);
view.encryptedKey = this.key; // Keep the encrypted key for the view
}
return view;
@@ -131,4 +132,24 @@ export class Attachment extends Domain {
key: this.key?.toJSON(),
};
}
/**
* Maps an SDK Attachment object to an Attachment
* @param obj - The SDK attachment object
*/
static fromSdkAttachment(obj: SdkAttachment): Attachment | undefined {
if (!obj) {
return undefined;
}
const attachment = new Attachment();
attachment.id = obj.id;
attachment.url = obj.url;
attachment.size = obj.size;
attachment.sizeName = obj.sizeName;
attachment.fileName = EncString.fromJSON(obj.fileName);
attachment.key = EncString.fromJSON(obj.key);
return attachment;
}
}

View File

@@ -103,4 +103,24 @@ export class Card extends Domain {
code: this.code?.toJSON(),
};
}
/**
* Maps an SDK Card object to a Card
* @param obj - The SDK Card object
*/
static fromSdkCard(obj: SdkCard): Card | undefined {
if (obj == null) {
return undefined;
}
const card = new Card();
card.cardholderName = EncString.fromJSON(obj.cardholderName);
card.brand = EncString.fromJSON(obj.brand);
card.number = EncString.fromJSON(obj.number);
card.expMonth = EncString.fromJSON(obj.expMonth);
card.expYear = EncString.fromJSON(obj.expYear);
card.code = EncString.fromJSON(obj.code);
return card;
}
}

View File

@@ -10,6 +10,7 @@ import {
UriMatchType,
CipherRepromptType as SdkCipherRepromptType,
LoginLinkedIdType,
Cipher as SdkCipher,
} from "@bitwarden/sdk-internal";
import { makeStaticByteArray, mockEnc, mockFromJson } from "../../../../spec/utils";
@@ -206,7 +207,7 @@ describe("Cipher DTO", () => {
it("Convert", () => {
const cipher = new Cipher(cipherData);
expect(cipher).toEqual({
expect(cipher).toMatchObject({
initializerKey: InitializerKey.Cipher,
id: "id",
organizationId: "orgId",
@@ -339,9 +340,9 @@ describe("Cipher DTO", () => {
edit: true,
viewPassword: true,
login: loginView,
attachments: null,
fields: null,
passwordHistory: null,
attachments: [],
fields: [],
passwordHistory: [],
collectionIds: undefined,
revisionDate: new Date("2022-01-31T12:00:00.000Z"),
creationDate: new Date("2022-01-01T12:00:00.000Z"),
@@ -462,9 +463,9 @@ describe("Cipher DTO", () => {
edit: true,
viewPassword: true,
secureNote: { type: 0 },
attachments: null,
fields: null,
passwordHistory: null,
attachments: [],
fields: [],
passwordHistory: [],
collectionIds: undefined,
revisionDate: new Date("2022-01-31T12:00:00.000Z"),
creationDate: new Date("2022-01-01T12:00:00.000Z"),
@@ -603,9 +604,9 @@ describe("Cipher DTO", () => {
edit: true,
viewPassword: true,
card: cardView,
attachments: null,
fields: null,
passwordHistory: null,
attachments: [],
fields: [],
passwordHistory: [],
collectionIds: undefined,
revisionDate: new Date("2022-01-31T12:00:00.000Z"),
creationDate: new Date("2022-01-01T12:00:00.000Z"),
@@ -768,9 +769,9 @@ describe("Cipher DTO", () => {
edit: true,
viewPassword: true,
identity: identityView,
attachments: null,
fields: null,
passwordHistory: null,
attachments: [],
fields: [],
passwordHistory: [],
collectionIds: undefined,
revisionDate: new Date("2022-01-31T12:00:00.000Z"),
creationDate: new Date("2022-01-01T12:00:00.000Z"),
@@ -1001,6 +1002,167 @@ describe("Cipher DTO", () => {
revisionDate: "2022-01-31T12:00:00.000Z",
});
});
it("should map from SDK Cipher", () => {
jest.restoreAllMocks();
const sdkCipher: SdkCipher = {
id: "id",
organizationId: "orgId",
folderId: "folderId",
collectionIds: [],
key: "EncryptedString",
name: "EncryptedString",
notes: "EncryptedString",
type: SdkCipherType.Login,
login: {
username: "EncryptedString",
password: "EncryptedString",
passwordRevisionDate: "2022-01-31T12:00:00.000Z",
uris: [
{
uri: "EncryptedString",
uriChecksum: "EncryptedString",
match: UriMatchType.Domain,
},
],
totp: "EncryptedString",
autofillOnPageLoad: false,
fido2Credentials: undefined,
},
identity: undefined,
card: undefined,
secureNote: undefined,
sshKey: undefined,
favorite: false,
reprompt: SdkCipherRepromptType.None,
organizationUseTotp: true,
edit: true,
permissions: new CipherPermissionsApi(),
viewPassword: true,
localData: {
lastUsedDate: "2025-04-15T12:00:00.000Z",
lastLaunched: "2025-04-15T12:00:00.000Z",
},
attachments: [
{
id: "a1",
url: "url",
size: "1100",
sizeName: "1.1 KB",
fileName: "file",
key: "EncKey",
},
{
id: "a2",
url: "url",
size: "1100",
sizeName: "1.1 KB",
fileName: "file",
key: "EncKey",
},
],
fields: [
{
name: "EncryptedString",
value: "EncryptedString",
type: FieldType.Linked,
linkedId: LoginLinkedIdType.Username,
},
{
name: "EncryptedString",
value: "EncryptedString",
type: FieldType.Linked,
linkedId: LoginLinkedIdType.Password,
},
],
passwordHistory: [
{
password: "EncryptedString",
lastUsedDate: "2022-01-31T12:00:00.000Z",
},
],
creationDate: "2022-01-01T12:00:00.000Z",
deletedDate: undefined,
revisionDate: "2022-01-31T12:00:00.000Z",
};
const lastUsedDate = new Date("2025-04-15T12:00:00.000Z").getTime();
const lastLaunched = new Date("2025-04-15T12:00:00.000Z").getTime();
const cipherData: CipherData = {
id: "id",
organizationId: "orgId",
folderId: "folderId",
edit: true,
permissions: new CipherPermissionsApi(),
collectionIds: [],
viewPassword: true,
organizationUseTotp: true,
favorite: false,
revisionDate: "2022-01-31T12:00:00.000Z",
type: CipherType.Login,
name: "EncryptedString",
notes: "EncryptedString",
creationDate: "2022-01-01T12:00:00.000Z",
deletedDate: null,
reprompt: CipherRepromptType.None,
key: "EncryptedString",
login: {
uris: [
{
uri: "EncryptedString",
uriChecksum: "EncryptedString",
match: UriMatchStrategy.Domain,
},
],
username: "EncryptedString",
password: "EncryptedString",
passwordRevisionDate: "2022-01-31T12:00:00.000Z",
totp: "EncryptedString",
autofillOnPageLoad: false,
},
passwordHistory: [
{ password: "EncryptedString", lastUsedDate: "2022-01-31T12:00:00.000Z" },
],
attachments: [
{
id: "a1",
url: "url",
size: "1100",
sizeName: "1.1 KB",
fileName: "file",
key: "EncKey",
},
{
id: "a2",
url: "url",
size: "1100",
sizeName: "1.1 KB",
fileName: "file",
key: "EncKey",
},
],
fields: [
{
name: "EncryptedString",
value: "EncryptedString",
type: FieldType.Linked,
linkedId: LoginLinkedId.Username,
},
{
name: "EncryptedString",
value: "EncryptedString",
type: FieldType.Linked,
linkedId: LoginLinkedId.Password,
},
],
};
const expectedCipher = new Cipher(cipherData, { lastUsedDate, lastLaunched });
const cipher = Cipher.fromSdkCipher(sdkCipher);
expect(cipher).toEqual(expectedCipher);
});
});
});

View File

@@ -2,6 +2,7 @@
// @ts-strict-ignore
import { Jsonify } from "type-fest";
import { uuidToString } from "@bitwarden/common/platform/abstractions/sdk/sdk.service";
import { Cipher as SdkCipher } from "@bitwarden/sdk-internal";
import { EncString } from "../../../key-management/crypto/models/enc-string";
@@ -14,7 +15,7 @@ import { CipherRepromptType } from "../../enums/cipher-reprompt-type";
import { CipherType } from "../../enums/cipher-type";
import { CipherPermissionsApi } from "../api/cipher-permissions.api";
import { CipherData } from "../data/cipher.data";
import { LocalData } from "../data/local.data";
import { LocalData, fromSdkLocalData, toSdkLocalData } from "../data/local.data";
import { AttachmentView } from "../view/attachment.view";
import { CipherView } from "../view/cipher.view";
import { FieldView } from "../view/field.view";
@@ -361,16 +362,7 @@ export class Cipher extends Domain implements Decryptable<CipherView> {
}
: undefined,
viewPassword: this.viewPassword ?? true,
localData: this.localData
? {
lastUsedDate: this.localData.lastUsedDate
? new Date(this.localData.lastUsedDate).toISOString()
: undefined,
lastLaunched: this.localData.lastLaunched
? new Date(this.localData.lastLaunched).toISOString()
: undefined,
}
: undefined,
localData: toSdkLocalData(this.localData),
attachments: this.attachments?.map((a) => a.toSdkAttachment()),
fields: this.fields?.map((f) => f.toSdkField()),
passwordHistory: this.passwordHistory?.map((ph) => ph.toSdkPasswordHistory()),
@@ -408,4 +400,50 @@ export class Cipher extends Domain implements Decryptable<CipherView> {
return sdkCipher;
}
/**
* Maps an SDK Cipher object to a Cipher
* @param sdkCipher - The SDK Cipher object
*/
static fromSdkCipher(sdkCipher: SdkCipher | null): Cipher | undefined {
if (sdkCipher == null) {
return undefined;
}
const cipher = new Cipher();
cipher.id = sdkCipher.id ? uuidToString(sdkCipher.id) : undefined;
cipher.organizationId = sdkCipher.organizationId
? uuidToString(sdkCipher.organizationId)
: undefined;
cipher.folderId = sdkCipher.folderId ? uuidToString(sdkCipher.folderId) : undefined;
cipher.collectionIds = sdkCipher.collectionIds ? sdkCipher.collectionIds.map(uuidToString) : [];
cipher.key = EncString.fromJSON(sdkCipher.key);
cipher.name = EncString.fromJSON(sdkCipher.name);
cipher.notes = EncString.fromJSON(sdkCipher.notes);
cipher.type = sdkCipher.type;
cipher.favorite = sdkCipher.favorite;
cipher.organizationUseTotp = sdkCipher.organizationUseTotp;
cipher.edit = sdkCipher.edit;
cipher.permissions = CipherPermissionsApi.fromSdkCipherPermissions(sdkCipher.permissions);
cipher.viewPassword = sdkCipher.viewPassword;
cipher.localData = fromSdkLocalData(sdkCipher.localData);
cipher.attachments = sdkCipher.attachments?.map((a) => Attachment.fromSdkAttachment(a)) ?? [];
cipher.fields = sdkCipher.fields?.map((f) => Field.fromSdkField(f)) ?? [];
cipher.passwordHistory =
sdkCipher.passwordHistory?.map((ph) => Password.fromSdkPasswordHistory(ph)) ?? [];
cipher.creationDate = new Date(sdkCipher.creationDate);
cipher.revisionDate = new Date(sdkCipher.revisionDate);
cipher.deletedDate = sdkCipher.deletedDate ? new Date(sdkCipher.deletedDate) : null;
cipher.reprompt = sdkCipher.reprompt;
// Cipher type specific properties
cipher.login = Login.fromSdkLogin(sdkCipher.login);
cipher.secureNote = SecureNote.fromSdkSecureNote(sdkCipher.secureNote);
cipher.card = Card.fromSdkCard(sdkCipher.card);
cipher.identity = Identity.fromSdkIdentity(sdkCipher.identity);
cipher.sshKey = SshKey.fromSdkSshKey(sdkCipher.sshKey);
return cipher;
}
}

View File

@@ -173,4 +173,32 @@ export class Fido2Credential extends Domain {
creationDate: this.creationDate.toISOString(),
};
}
/**
* Maps an SDK Fido2Credential object to a Fido2Credential
* @param obj - The SDK Fido2Credential object
*/
static fromSdkFido2Credential(obj: SdkFido2Credential): Fido2Credential | undefined {
if (!obj) {
return undefined;
}
const credential = new Fido2Credential();
credential.credentialId = EncString.fromJSON(obj.credentialId);
credential.keyType = EncString.fromJSON(obj.keyType);
credential.keyAlgorithm = EncString.fromJSON(obj.keyAlgorithm);
credential.keyCurve = EncString.fromJSON(obj.keyCurve);
credential.keyValue = EncString.fromJSON(obj.keyValue);
credential.rpId = EncString.fromJSON(obj.rpId);
credential.userHandle = EncString.fromJSON(obj.userHandle);
credential.userName = EncString.fromJSON(obj.userName);
credential.counter = EncString.fromJSON(obj.counter);
credential.rpName = EncString.fromJSON(obj.rpName);
credential.userDisplayName = EncString.fromJSON(obj.userDisplayName);
credential.discoverable = EncString.fromJSON(obj.discoverable);
credential.creationDate = new Date(obj.creationDate);
return credential;
}
}

View File

@@ -1,6 +1,14 @@
import {
Field as SdkField,
FieldType,
LoginLinkedIdType,
CardLinkedIdType,
IdentityLinkedIdType,
} from "@bitwarden/sdk-internal";
import { mockEnc, mockFromJson } from "../../../../spec";
import { EncryptedString, EncString } from "../../../key-management/crypto/models/enc-string";
import { CardLinkedId, FieldType, IdentityLinkedId, LoginLinkedId } from "../../enums";
import { CardLinkedId, IdentityLinkedId, LoginLinkedId } from "../../enums";
import { FieldData } from "../../models/data/field.data";
import { Field } from "../../models/domain/field";
@@ -103,5 +111,34 @@ describe("Field", () => {
identityField.linkedId = IdentityLinkedId.LicenseNumber;
expect(identityField.toSdkField().linkedId).toBe(415);
});
it("should map from SDK Field", () => {
// Test Login LinkedId
const loginField: SdkField = {
name: undefined,
value: undefined,
type: FieldType.Linked,
linkedId: LoginLinkedIdType.Username,
};
expect(Field.fromSdkField(loginField)!.linkedId).toBe(100);
// Test Card LinkedId
const cardField: SdkField = {
name: undefined,
value: undefined,
type: FieldType.Linked,
linkedId: CardLinkedIdType.Number,
};
expect(Field.fromSdkField(cardField)!.linkedId).toBe(305);
// Test Identity LinkedId
const identityFieldSdkField: SdkField = {
name: undefined,
value: undefined,
type: FieldType.Linked,
linkedId: IdentityLinkedIdType.LicenseNumber,
};
expect(Field.fromSdkField(identityFieldSdkField)!.linkedId).toBe(415);
});
});
});

View File

@@ -90,4 +90,22 @@ export class Field extends Domain {
linkedId: this.linkedId as unknown as SdkLinkedIdType,
};
}
/**
* Maps SDK Field to Field
* @param obj The SDK Field object to map
*/
static fromSdkField(obj: SdkField): Field | undefined {
if (!obj) {
return undefined;
}
const field = new Field();
field.name = EncString.fromJSON(obj.name);
field.value = EncString.fromJSON(obj.value);
field.type = obj.type;
field.linkedId = obj.linkedId;
return field;
}
}

View File

@@ -195,4 +195,36 @@ export class Identity extends Domain {
licenseNumber: this.licenseNumber?.toJSON(),
};
}
/**
* Maps an SDK Identity object to an Identity
* @param obj - The SDK Identity object
*/
static fromSdkIdentity(obj: SdkIdentity): Identity | undefined {
if (obj == null) {
return undefined;
}
const identity = new Identity();
identity.title = EncString.fromJSON(obj.title);
identity.firstName = EncString.fromJSON(obj.firstName);
identity.middleName = EncString.fromJSON(obj.middleName);
identity.lastName = EncString.fromJSON(obj.lastName);
identity.address1 = EncString.fromJSON(obj.address1);
identity.address2 = EncString.fromJSON(obj.address2);
identity.address3 = EncString.fromJSON(obj.address3);
identity.city = EncString.fromJSON(obj.city);
identity.state = EncString.fromJSON(obj.state);
identity.postalCode = EncString.fromJSON(obj.postalCode);
identity.country = EncString.fromJSON(obj.country);
identity.company = EncString.fromJSON(obj.company);
identity.email = EncString.fromJSON(obj.email);
identity.phone = EncString.fromJSON(obj.phone);
identity.ssn = EncString.fromJSON(obj.ssn);
identity.username = EncString.fromJSON(obj.username);
identity.passportNumber = EncString.fromJSON(obj.passportNumber);
identity.licenseNumber = EncString.fromJSON(obj.licenseNumber);
return identity;
}
}

View File

@@ -102,4 +102,17 @@ export class LoginUri extends Domain {
match: this.match,
};
}
static fromSdkLoginUri(obj: SdkLoginUri): LoginUri | undefined {
if (obj == null) {
return undefined;
}
const view = new LoginUri();
view.uri = EncString.fromJSON(obj.uri);
view.uriChecksum = obj.uriChecksum ? EncString.fromJSON(obj.uriChecksum) : undefined;
view.match = obj.match;
return view;
}
}

View File

@@ -163,4 +163,31 @@ export class Login extends Domain {
fido2Credentials: this.fido2Credentials?.map((f) => f.toSdkFido2Credential()),
};
}
/**
* Maps an SDK Login object to a Login
* @param obj - The SDK Login object
*/
static fromSdkLogin(obj: SdkLogin): Login | undefined {
if (!obj) {
return undefined;
}
const login = new Login();
login.uris =
obj.uris?.filter((u) => u.uri != null).map((uri) => LoginUri.fromSdkLoginUri(uri)) ?? [];
login.username = EncString.fromJSON(obj.username);
login.password = EncString.fromJSON(obj.password);
login.passwordRevisionDate = obj.passwordRevisionDate
? new Date(obj.passwordRevisionDate)
: undefined;
login.totp = EncString.fromJSON(obj.totp);
login.autofillOnPageLoad = obj.autofillOnPageLoad ?? false;
login.fido2Credentials = obj.fido2Credentials?.map((f) =>
Fido2Credential.fromSdkFido2Credential(f),
);
return login;
}
}

View File

@@ -71,4 +71,20 @@ export class Password extends Domain {
lastUsedDate: this.lastUsedDate.toISOString(),
};
}
/**
* Maps an SDK PasswordHistory object to a Password
* @param obj - The SDK PasswordHistory object
*/
static fromSdkPasswordHistory(obj: PasswordHistory): Password | undefined {
if (!obj) {
return undefined;
}
const passwordHistory = new Password();
passwordHistory.password = EncString.fromJSON(obj.password);
passwordHistory.lastUsedDate = new Date(obj.lastUsedDate);
return passwordHistory;
}
}

View File

@@ -54,4 +54,19 @@ export class SecureNote extends Domain {
type: this.type,
};
}
/**
* Maps an SDK SecureNote object to a SecureNote
* @param obj - The SDK SecureNote object
*/
static fromSdkSecureNote(obj: SdkSecureNote): SecureNote | undefined {
if (obj == null) {
return undefined;
}
const secureNote = new SecureNote();
secureNote.type = obj.type;
return secureNote;
}
}

View File

@@ -85,4 +85,21 @@ export class SshKey extends Domain {
fingerprint: this.keyFingerprint.toJSON(),
};
}
/**
* Maps an SDK SshKey object to a SshKey
* @param obj - The SDK SshKey object
*/
static fromSdkSshKey(obj: SdkSshKey): SshKey | undefined {
if (obj == null) {
return undefined;
}
const sshKey = new SshKey();
sshKey.privateKey = EncString.fromJSON(obj.privateKey);
sshKey.publicKey = EncString.fromJSON(obj.publicKey);
sshKey.keyFingerprint = EncString.fromJSON(obj.fingerprint);
return sshKey;
}
}

View File

@@ -16,6 +16,6 @@ export class TreeNode<T extends ITreeNodeObject> {
}
export interface ITreeNodeObject {
id: string;
name: string;
id: string | undefined;
name: string | undefined;
}

View File

@@ -10,7 +10,7 @@ import { linkedFieldOption } from "../../linked-field-option.decorator";
import { ItemView } from "./item.view";
export class CardView extends ItemView {
export class CardView extends ItemView implements SdkCardView {
@linkedFieldOption(LinkedId.CardholderName, { sortPosition: 0 })
cardholderName: string = null;
@linkedFieldOption(LinkedId.ExpMonth, { sortPosition: 3, i18nKey: "expirationMonth" })
@@ -168,4 +168,12 @@ export class CardView extends ItemView {
return cardView;
}
/**
* Converts the CardView to an SDK CardView.
* The view implements the SdkView so we can safely return `this`
*/
toSdkCardView(): SdkCardView {
return this;
}
}

View File

@@ -1,3 +1,7 @@
import { Jsonify } from "type-fest";
import { EncString } from "@bitwarden/common/key-management/crypto/models/enc-string";
import { CipherPermissionsApi } from "@bitwarden/common/vault/models/api/cipher-permissions.api";
import {
CipherView as SdkCipherView,
CipherType as SdkCipherType,
@@ -85,6 +89,25 @@ describe("CipherView", () => {
expect(actual).toMatchObject(expected);
});
it("handle both string and object inputs for the cipher key", () => {
const cipherKeyString = "cipherKeyString";
const cipherKeyObject = new EncString("cipherKeyObject");
// Test with string input
let actual = CipherView.fromJSON({
key: cipherKeyString,
});
expect(actual.key).toBeInstanceOf(EncString);
expect(actual.key?.toJSON()).toBe(cipherKeyString);
// Test with object input (which can happen when cipher view is stored in an InMemory state provider)
actual = CipherView.fromJSON({
key: cipherKeyObject,
} as Jsonify<CipherView>);
expect(actual.key).toBeInstanceOf(EncString);
expect(actual.key?.toJSON()).toBe(cipherKeyObject.toJSON());
});
});
describe("fromSdkCipherView", () => {
@@ -196,11 +219,80 @@ describe("CipherView", () => {
__fromSdk: true,
},
],
passwordHistory: null,
passwordHistory: [],
creationDate: new Date("2022-01-01T12:00:00.000Z"),
revisionDate: new Date("2022-01-02T12:00:00.000Z"),
deletedDate: null,
});
});
});
describe("toSdkCipherView", () => {
it("maps properties correctly", () => {
const cipherView = new CipherView();
cipherView.id = "0a54d80c-14aa-4ef8-8c3a-7ea99ce5b602";
cipherView.organizationId = "000f2a6e-da5e-4726-87ed-1c5c77322c3c";
cipherView.folderId = "41b22db4-8e2a-4ed2-b568-f1186c72922f";
cipherView.collectionIds = ["b0473506-3c3c-4260-a734-dfaaf833ab6f"];
cipherView.key = new EncString("some-key");
cipherView.name = "name";
cipherView.notes = "notes";
cipherView.type = CipherType.Login;
cipherView.favorite = true;
cipherView.edit = true;
cipherView.viewPassword = false;
cipherView.reprompt = CipherRepromptType.None;
cipherView.organizationUseTotp = false;
cipherView.localData = {
lastLaunched: new Date("2022-01-01T12:00:00.000Z").getTime(),
lastUsedDate: new Date("2022-01-02T12:00:00.000Z").getTime(),
};
cipherView.permissions = new CipherPermissionsApi();
cipherView.permissions.restore = true;
cipherView.permissions.delete = true;
cipherView.attachments = [];
cipherView.fields = [];
cipherView.passwordHistory = [];
cipherView.login = new LoginView();
cipherView.revisionDate = new Date("2022-01-02T12:00:00.000Z");
cipherView.creationDate = new Date("2022-01-02T12:00:00.000Z");
const sdkCipherView = cipherView.toSdkCipherView();
expect(sdkCipherView).toMatchObject({
id: "0a54d80c-14aa-4ef8-8c3a-7ea99ce5b602",
organizationId: "000f2a6e-da5e-4726-87ed-1c5c77322c3c",
folderId: "41b22db4-8e2a-4ed2-b568-f1186c72922f",
collectionIds: ["b0473506-3c3c-4260-a734-dfaaf833ab6f"],
key: "some-key",
name: "name",
notes: "notes",
type: SdkCipherType.Login,
favorite: true,
edit: true,
viewPassword: false,
reprompt: SdkCipherRepromptType.None,
organizationUseTotp: false,
localData: {
lastLaunched: "2022-01-01T12:00:00.000Z",
lastUsedDate: "2022-01-02T12:00:00.000Z",
},
permissions: {
restore: true,
delete: true,
},
deletedDate: undefined,
creationDate: "2022-01-02T12:00:00.000Z",
revisionDate: "2022-01-02T12:00:00.000Z",
attachments: [],
passwordHistory: [],
login: undefined,
identity: undefined,
card: undefined,
secureNote: undefined,
sshKey: undefined,
fields: [],
} as SdkCipherView);
});
});
});

View File

@@ -1,5 +1,7 @@
// FIXME: Update this file to be type safe and remove this and next line
// @ts-strict-ignore
import { EncString } from "@bitwarden/common/key-management/crypto/models/enc-string";
import { uuidToString, asUuid } from "@bitwarden/common/platform/abstractions/sdk/sdk.service";
import { CipherView as SdkCipherView } from "@bitwarden/sdk-internal";
import { View } from "../../../models/view/view";
@@ -9,7 +11,7 @@ import { DeepJsonify } from "../../../types/deep-jsonify";
import { CipherType, LinkedIdType } from "../../enums";
import { CipherRepromptType } from "../../enums/cipher-reprompt-type";
import { CipherPermissionsApi } from "../api/cipher-permissions.api";
import { LocalData } from "../data/local.data";
import { LocalData, toSdkLocalData, fromSdkLocalData } from "../data/local.data";
import { Cipher } from "../domain/cipher";
import { AttachmentView } from "./attachment.view";
@@ -41,14 +43,17 @@ export class CipherView implements View, InitializerMetadata {
card = new CardView();
secureNote = new SecureNoteView();
sshKey = new SshKeyView();
attachments: AttachmentView[] = null;
fields: FieldView[] = null;
passwordHistory: PasswordHistoryView[] = null;
attachments: AttachmentView[] = [];
fields: FieldView[] = [];
passwordHistory: PasswordHistoryView[] = [];
collectionIds: string[] = null;
revisionDate: Date = null;
creationDate: Date = null;
deletedDate: Date = null;
reprompt: CipherRepromptType = CipherRepromptType.None;
// We need a copy of the encrypted key so we can pass it to
// the SdkCipherView during encryption
key?: EncString;
/**
* Flag to indicate if the cipher decryption failed.
@@ -76,6 +81,7 @@ export class CipherView implements View, InitializerMetadata {
this.deletedDate = c.deletedDate;
// Old locally stored ciphers might have reprompt == null. If so set it to None.
this.reprompt = c.reprompt ?? CipherRepromptType.None;
this.key = c.key;
}
private get item() {
@@ -194,6 +200,18 @@ export class CipherView implements View, InitializerMetadata {
const attachments = obj.attachments?.map((a: any) => AttachmentView.fromJSON(a));
const fields = obj.fields?.map((f: any) => FieldView.fromJSON(f));
const passwordHistory = obj.passwordHistory?.map((ph: any) => PasswordHistoryView.fromJSON(ph));
const permissions = CipherPermissionsApi.fromJSON(obj.permissions);
let key: EncString | undefined;
if (obj.key != null) {
if (typeof obj.key === "string") {
// If the key is a string, we need to parse it as EncString
key = EncString.fromJSON(obj.key);
} else if ((obj.key as any) instanceof EncString) {
// If the key is already an EncString instance, we can use it directly
key = obj.key;
}
}
Object.assign(view, obj, {
creationDate: creationDate,
@@ -202,6 +220,8 @@ export class CipherView implements View, InitializerMetadata {
attachments: attachments,
fields: fields,
passwordHistory: passwordHistory,
permissions: permissions,
key: key,
});
switch (obj.type) {
@@ -236,9 +256,9 @@ export class CipherView implements View, InitializerMetadata {
}
const cipherView = new CipherView();
cipherView.id = obj.id ?? null;
cipherView.organizationId = obj.organizationId ?? null;
cipherView.folderId = obj.folderId ?? null;
cipherView.id = uuidToString(obj.id) ?? null;
cipherView.organizationId = uuidToString(obj.organizationId) ?? null;
cipherView.folderId = uuidToString(obj.folderId) ?? null;
cipherView.name = obj.name;
cipherView.notes = obj.notes ?? null;
cipherView.type = obj.type;
@@ -247,26 +267,18 @@ export class CipherView implements View, InitializerMetadata {
cipherView.permissions = CipherPermissionsApi.fromSdkCipherPermissions(obj.permissions);
cipherView.edit = obj.edit;
cipherView.viewPassword = obj.viewPassword;
cipherView.localData = obj.localData
? {
lastUsedDate: obj.localData.lastUsedDate
? new Date(obj.localData.lastUsedDate).getTime()
: undefined,
lastLaunched: obj.localData.lastLaunched
? new Date(obj.localData.lastLaunched).getTime()
: undefined,
}
: undefined;
cipherView.localData = fromSdkLocalData(obj.localData);
cipherView.attachments =
obj.attachments?.map((a) => AttachmentView.fromSdkAttachmentView(a)) ?? null;
cipherView.fields = obj.fields?.map((f) => FieldView.fromSdkFieldView(f)) ?? null;
obj.attachments?.map((a) => AttachmentView.fromSdkAttachmentView(a)) ?? [];
cipherView.fields = obj.fields?.map((f) => FieldView.fromSdkFieldView(f)) ?? [];
cipherView.passwordHistory =
obj.passwordHistory?.map((ph) => PasswordHistoryView.fromSdkPasswordHistoryView(ph)) ?? null;
cipherView.collectionIds = obj.collectionIds ?? null;
obj.passwordHistory?.map((ph) => PasswordHistoryView.fromSdkPasswordHistoryView(ph)) ?? [];
cipherView.collectionIds = obj.collectionIds?.map((i) => uuidToString(i)) ?? [];
cipherView.revisionDate = obj.revisionDate == null ? null : new Date(obj.revisionDate);
cipherView.creationDate = obj.creationDate == null ? null : new Date(obj.creationDate);
cipherView.deletedDate = obj.deletedDate == null ? null : new Date(obj.deletedDate);
cipherView.reprompt = obj.reprompt ?? CipherRepromptType.None;
cipherView.key = EncString.fromJSON(obj.key);
switch (obj.type) {
case CipherType.Card:
@@ -290,4 +302,66 @@ export class CipherView implements View, InitializerMetadata {
return cipherView;
}
/**
* Maps CipherView to SdkCipherView
*
* @returns {SdkCipherView} The SDK cipher view object
*/
toSdkCipherView(): SdkCipherView {
const sdkCipherView: SdkCipherView = {
id: this.id ? asUuid(this.id) : undefined,
organizationId: this.organizationId ? asUuid(this.organizationId) : undefined,
folderId: this.folderId ? asUuid(this.folderId) : undefined,
name: this.name ?? "",
notes: this.notes,
type: this.type ?? CipherType.Login,
favorite: this.favorite,
organizationUseTotp: this.organizationUseTotp,
permissions: this.permissions?.toSdkCipherPermissions(),
edit: this.edit,
viewPassword: this.viewPassword,
localData: toSdkLocalData(this.localData),
attachments: this.attachments?.map((a) => a.toSdkAttachmentView()),
fields: this.fields?.map((f) => f.toSdkFieldView()),
passwordHistory: this.passwordHistory?.map((ph) => ph.toSdkPasswordHistoryView()),
collectionIds: this.collectionIds?.map((i) => i) ?? [],
// Revision and creation dates are non-nullable in SDKCipherView
revisionDate: (this.revisionDate ?? new Date()).toISOString(),
creationDate: (this.creationDate ?? new Date()).toISOString(),
deletedDate: this.deletedDate?.toISOString(),
reprompt: this.reprompt ?? CipherRepromptType.None,
key: this.key?.toJSON(),
// Cipher type specific properties are set in the switch statement below
// CipherView initializes each with default constructors (undefined values)
// The SDK does not expect those undefined values and will throw exceptions
login: undefined,
card: undefined,
identity: undefined,
secureNote: undefined,
sshKey: undefined,
};
switch (this.type) {
case CipherType.Card:
sdkCipherView.card = this.card.toSdkCardView();
break;
case CipherType.Identity:
sdkCipherView.identity = this.identity.toSdkIdentityView();
break;
case CipherType.Login:
sdkCipherView.login = this.login.toSdkLoginView();
break;
case CipherType.SecureNote:
sdkCipherView.secureNote = this.secureNote.toSdkSecureNoteView();
break;
case CipherType.SshKey:
sdkCipherView.sshKey = this.sshKey.toSdkSshKeyView();
break;
default:
break;
}
return sdkCipherView;
}
}

View File

@@ -2,7 +2,10 @@
// @ts-strict-ignore
import { Jsonify } from "type-fest";
import { Fido2CredentialView as SdkFido2CredentialView } from "@bitwarden/sdk-internal";
import {
Fido2CredentialView as SdkFido2CredentialView,
Fido2CredentialFullView,
} from "@bitwarden/sdk-internal";
import { ItemView } from "./item.view";
@@ -56,4 +59,22 @@ export class Fido2CredentialView extends ItemView {
return view;
}
toSdkFido2CredentialFullView(): Fido2CredentialFullView {
return {
credentialId: this.credentialId,
keyType: this.keyType,
keyAlgorithm: this.keyAlgorithm,
keyCurve: this.keyCurve,
keyValue: this.keyValue,
rpId: this.rpId,
userHandle: this.userHandle,
userName: this.userName,
counter: this.counter.toString(),
rpName: this.rpName,
userDisplayName: this.userDisplayName,
discoverable: this.discoverable ? "true" : "false",
creationDate: this.creationDate?.toISOString(),
};
}
}

View File

@@ -2,7 +2,7 @@
// @ts-strict-ignore
import { Jsonify } from "type-fest";
import { FieldView as SdkFieldView } from "@bitwarden/sdk-internal";
import { FieldView as SdkFieldView, FieldType as SdkFieldType } from "@bitwarden/sdk-internal";
import { View } from "../../../models/view/view";
import { FieldType, LinkedIdType } from "../../enums";
@@ -50,4 +50,16 @@ export class FieldView implements View {
return view;
}
/**
* Converts the FieldView to an SDK FieldView.
*/
toSdkFieldView(): SdkFieldView {
return {
name: this.name ?? undefined,
value: this.value ?? undefined,
type: this.type ?? SdkFieldType.Text,
linkedId: this.linkedId ?? undefined,
};
}
}

View File

@@ -10,7 +10,7 @@ import { linkedFieldOption } from "../../linked-field-option.decorator";
import { ItemView } from "./item.view";
export class IdentityView extends ItemView {
export class IdentityView extends ItemView implements SdkIdentityView {
@linkedFieldOption(LinkedId.Title, { sortPosition: 0 })
title: string = null;
@linkedFieldOption(LinkedId.MiddleName, { sortPosition: 2 })
@@ -192,4 +192,12 @@ export class IdentityView extends ItemView {
return identityView;
}
/**
* Converts the IdentityView to an SDK IdentityView.
* The view implements the SdkView so we can safely return `this`
*/
toSdkIdentityView(): SdkIdentityView {
return this;
}
}

View File

@@ -129,6 +129,15 @@ export class LoginUriView implements View {
return view;
}
/** Converts a LoginUriView object to an SDK LoginUriView object. */
toSdkLoginUriView(): SdkLoginUriView {
return {
uri: this.uri ?? undefined,
match: this.match ?? undefined,
uriChecksum: undefined, // SDK handles uri checksum generation internally
};
}
matchesUri(
targetUri: string,
equivalentDomains: Set<string>,

View File

@@ -124,10 +124,30 @@ export class LoginView extends ItemView {
obj.passwordRevisionDate == null ? null : new Date(obj.passwordRevisionDate);
loginView.totp = obj.totp ?? null;
loginView.autofillOnPageLoad = obj.autofillOnPageLoad ?? null;
loginView.uris = obj.uris?.map((uri) => LoginUriView.fromSdkLoginUriView(uri)) || [];
loginView.uris =
obj.uris
?.filter((uri) => uri.uri != null && uri.uri !== "")
.map((uri) => LoginUriView.fromSdkLoginUriView(uri)) || [];
// FIDO2 credentials are not decrypted here, they remain encrypted
loginView.fido2Credentials = null;
return loginView;
}
/**
* Converts the LoginView to an SDK LoginView.
*
* Note: FIDO2 credentials remain encrypted in the SDK view so they are not included here.
*/
toSdkLoginView(): SdkLoginView {
return {
username: this.username,
password: this.password,
passwordRevisionDate: this.passwordRevisionDate?.toISOString(),
totp: this.totp,
autofillOnPageLoad: this.autofillOnPageLoad ?? undefined,
uris: this.uris?.map((uri) => uri.toSdkLoginUriView()),
fido2Credentials: undefined, // FIDO2 credentials are handled separately and remain encrypted
};
}
}

View File

@@ -33,4 +33,17 @@ describe("PasswordHistoryView", () => {
});
});
});
describe("toSdkPasswordHistoryView", () => {
it("should return a SdkPasswordHistoryView", () => {
const passwordHistoryView = new PasswordHistoryView();
passwordHistoryView.password = "password";
passwordHistoryView.lastUsedDate = new Date("2023-10-01T00:00:00.000Z");
expect(passwordHistoryView.toSdkPasswordHistoryView()).toMatchObject({
password: "password",
lastUsedDate: "2023-10-01T00:00:00.000Z",
});
});
});
});

View File

@@ -41,4 +41,14 @@ export class PasswordHistoryView implements View {
return view;
}
/**
* Converts the PasswordHistoryView to an SDK PasswordHistoryView.
*/
toSdkPasswordHistoryView(): SdkPasswordHistoryView {
return {
password: this.password ?? "",
lastUsedDate: this.lastUsedDate.toISOString(),
};
}
}

View File

@@ -9,7 +9,7 @@ import { SecureNote } from "../domain/secure-note";
import { ItemView } from "./item.view";
export class SecureNoteView extends ItemView {
export class SecureNoteView extends ItemView implements SdkSecureNoteView {
type: SecureNoteType = null;
constructor(n?: SecureNote) {
@@ -42,4 +42,12 @@ export class SecureNoteView extends ItemView {
return secureNoteView;
}
/**
* Converts the SecureNoteView to an SDK SecureNoteView.
* The view implements the SdkView so we can safely return `this`
*/
toSdkSecureNoteView(): SdkSecureNoteView {
return this;
}
}

View File

@@ -63,4 +63,15 @@ export class SshKeyView extends ItemView {
return sshKeyView;
}
/**
* Converts the SshKeyView to an SDK SshKeyView.
*/
toSdkSshKeyView(): SdkSshKeyView {
return {
privateKey: this.privateKey,
publicKey: this.publicKey,
fingerprint: this.keyFingerprint,
};
}
}

View File

@@ -8,13 +8,7 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv
import { CollectionId } from "@bitwarden/common/types/guid";
import { getUserId } from "../../auth/services/account.service";
import { Cipher } from "../models/domain/cipher";
import { CipherView } from "../models/view/cipher.view";
/**
* Represents either a cipher or a cipher view.
*/
type CipherLike = Cipher | CipherView;
import { CipherLike } from "../types/cipher-like";
/**
* Service for managing user cipher authorization.
@@ -95,7 +89,7 @@ export class DefaultCipherAuthorizationService implements CipherAuthorizationSer
}
}
return cipher.permissions.delete;
return !!cipher.permissions?.delete;
}),
);
}
@@ -118,7 +112,7 @@ export class DefaultCipherAuthorizationService implements CipherAuthorizationSer
}
}
return cipher.permissions.restore;
return !!cipher.permissions?.restore;
}),
);
}

View File

@@ -1,7 +1,9 @@
import { mock } from "jest-mock-extended";
import { BehaviorSubject, map, of } from "rxjs";
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { CipherResponse } from "@bitwarden/common/vault/models/response/cipher.response";
// This import has been flagged as unallowed for this class. It may be involved in a circular dependency loop.
// eslint-disable-next-line no-restricted-imports
import { CipherDecryptionKeys, KeyService } from "@bitwarden/key-management";
@@ -23,7 +25,7 @@ import { Utils } from "../../platform/misc/utils";
import { EncArrayBuffer } from "../../platform/models/domain/enc-array-buffer";
import { SymmetricCryptoKey } from "../../platform/models/domain/symmetric-crypto-key";
import { ContainerService } from "../../platform/services/container.service";
import { CipherId, UserId } from "../../types/guid";
import { CipherId, UserId, OrganizationId, CollectionId } from "../../types/guid";
import { CipherKey, OrgKey, UserKey } from "../../types/key";
import { CipherEncryptionService } from "../abstractions/cipher-encryption.service";
import { EncryptionContext } from "../abstractions/cipher.service";
@@ -108,6 +110,7 @@ describe("Cipher Service", () => {
const cipherEncryptionService = mock<CipherEncryptionService>();
const userId = "TestUserId" as UserId;
const orgId = "4ff8c0b2-1d3e-4f8c-9b2d-1d3e4f8c0b2" as OrganizationId;
let cipherService: CipherService;
let encryptionContext: EncryptionContext;
@@ -155,7 +158,9 @@ describe("Cipher Service", () => {
);
configService.checkServerMeetsVersionRequirement$.mockReturnValue(of(false));
configService.getFeatureFlag.mockResolvedValue(false);
configService.getFeatureFlag
.calledWith(FeatureFlag.CipherKeyEncryption)
.mockResolvedValue(false);
const spy = jest.spyOn(cipherFileUploadService, "upload");
@@ -270,6 +275,55 @@ describe("Cipher Service", () => {
jest.spyOn(cipherService as any, "getAutofillOnPageLoadDefault").mockResolvedValue(true);
});
it("should call encrypt method of CipherEncryptionService when feature flag is true", async () => {
configService.getFeatureFlag
.calledWith(FeatureFlag.PM22136_SdkCipherEncryption)
.mockResolvedValue(true);
cipherEncryptionService.encrypt.mockResolvedValue(encryptionContext);
const result = await cipherService.encrypt(cipherView, userId);
expect(result).toEqual(encryptionContext);
expect(cipherEncryptionService.encrypt).toHaveBeenCalledWith(cipherView, userId);
});
it("should call legacy encrypt when feature flag is false", async () => {
configService.getFeatureFlag
.calledWith(FeatureFlag.PM22136_SdkCipherEncryption)
.mockResolvedValue(false);
jest.spyOn(cipherService as any, "encryptCipher").mockResolvedValue(encryptionContext.cipher);
const result = await cipherService.encrypt(cipherView, userId);
expect(result).toEqual(encryptionContext);
expect(cipherEncryptionService.encrypt).not.toHaveBeenCalled();
});
it("should call legacy encrypt when keys are provided", async () => {
configService.getFeatureFlag
.calledWith(FeatureFlag.PM22136_SdkCipherEncryption)
.mockResolvedValue(true);
jest.spyOn(cipherService as any, "encryptCipher").mockResolvedValue(encryptionContext.cipher);
const encryptKey = new SymmetricCryptoKey(new Uint8Array(32));
const decryptKey = new SymmetricCryptoKey(new Uint8Array(32));
let result = await cipherService.encrypt(cipherView, userId, encryptKey);
expect(result).toEqual(encryptionContext);
expect(cipherEncryptionService.encrypt).not.toHaveBeenCalled();
result = await cipherService.encrypt(cipherView, userId, undefined, decryptKey);
expect(result).toEqual(encryptionContext);
expect(cipherEncryptionService.encrypt).not.toHaveBeenCalled();
result = await cipherService.encrypt(cipherView, userId, encryptKey, decryptKey);
expect(result).toEqual(encryptionContext);
expect(cipherEncryptionService.encrypt).not.toHaveBeenCalled();
});
it("should return the encrypting user id", async () => {
keyService.getOrgKey.mockReturnValue(
Promise.resolve<any>(new SymmetricCryptoKey(new Uint8Array(32)) as OrgKey),
@@ -310,7 +364,9 @@ describe("Cipher Service", () => {
});
it("is null when feature flag is false", async () => {
configService.getFeatureFlag.mockResolvedValue(false);
configService.getFeatureFlag
.calledWith(FeatureFlag.CipherKeyEncryption)
.mockResolvedValue(false);
const { cipher } = await cipherService.encrypt(cipherView, userId);
expect(cipher.key).toBeNull();
@@ -318,7 +374,9 @@ describe("Cipher Service", () => {
describe("when feature flag is true", () => {
beforeEach(() => {
configService.getFeatureFlag.mockResolvedValue(true);
configService.getFeatureFlag
.calledWith(FeatureFlag.CipherKeyEncryption)
.mockResolvedValue(true);
});
it("is null when the cipher is not viewPassword", async () => {
@@ -348,7 +406,9 @@ describe("Cipher Service", () => {
});
it("is not called when feature flag is false", async () => {
configService.getFeatureFlag.mockResolvedValue(false);
configService.getFeatureFlag
.calledWith(FeatureFlag.CipherKeyEncryption)
.mockResolvedValue(false);
await cipherService.encrypt(cipherView, userId);
@@ -357,7 +417,9 @@ describe("Cipher Service", () => {
describe("when feature flag is true", () => {
beforeEach(() => {
configService.getFeatureFlag.mockResolvedValue(true);
configService.getFeatureFlag
.calledWith(FeatureFlag.CipherKeyEncryption)
.mockResolvedValue(true);
});
it("is called when cipher viewPassword is true", async () => {
@@ -401,7 +463,9 @@ describe("Cipher Service", () => {
let encryptedKey: EncString;
beforeEach(() => {
configService.getFeatureFlag.mockResolvedValue(true);
configService.getFeatureFlag
.calledWith(FeatureFlag.CipherKeyEncryption)
.mockResolvedValue(true);
configService.checkServerMeetsVersionRequirement$.mockReturnValue(of(true));
searchService.indexedEntityId$.mockReturnValue(of(null));
@@ -474,7 +538,9 @@ describe("Cipher Service", () => {
describe("decrypt", () => {
it("should call decrypt method of CipherEncryptionService when feature flag is true", async () => {
configService.getFeatureFlag.mockResolvedValue(true);
configService.getFeatureFlag
.calledWith(FeatureFlag.PM19941MigrateCipherDomainToSdk)
.mockResolvedValue(true);
cipherEncryptionService.decrypt.mockResolvedValue(new CipherView(encryptionContext.cipher));
const result = await cipherService.decrypt(encryptionContext.cipher, userId);
@@ -488,7 +554,9 @@ describe("Cipher Service", () => {
it("should call legacy decrypt when feature flag is false", async () => {
const mockUserKey = new SymmetricCryptoKey(new Uint8Array(32)) as UserKey;
configService.getFeatureFlag.mockResolvedValue(false);
configService.getFeatureFlag
.calledWith(FeatureFlag.PM19941MigrateCipherDomainToSdk)
.mockResolvedValue(false);
cipherService.getKeyForCipherKeyDecryption = jest.fn().mockResolvedValue(mockUserKey);
encryptService.decryptToBytes.mockResolvedValue(new Uint8Array(32));
jest
@@ -509,7 +577,9 @@ describe("Cipher Service", () => {
it("should use SDK when feature flag is enabled", async () => {
const cipher = new Cipher(cipherData);
const attachment = new AttachmentView(cipher.attachments![0]);
configService.getFeatureFlag.mockResolvedValue(true);
configService.getFeatureFlag
.calledWith(FeatureFlag.PM19941MigrateCipherDomainToSdk)
.mockResolvedValue(true);
jest.spyOn(cipherService, "ciphers$").mockReturnValue(of({ [cipher.id]: cipherData }));
cipherEncryptionService.decryptAttachmentContent.mockResolvedValue(mockDecryptedContent);
@@ -534,7 +604,9 @@ describe("Cipher Service", () => {
});
it("should use legacy decryption when feature flag is enabled", async () => {
configService.getFeatureFlag.mockResolvedValue(false);
configService.getFeatureFlag
.calledWith(FeatureFlag.PM19941MigrateCipherDomainToSdk)
.mockResolvedValue(false);
const cipher = new Cipher(cipherData);
const attachment = new AttachmentView(cipher.attachments![0]);
attachment.key = makeSymmetricCryptoKey(64);
@@ -557,4 +629,77 @@ describe("Cipher Service", () => {
expect(encryptService.decryptFileData).toHaveBeenCalledWith(mockEncBuf, attachment.key);
});
});
describe("shareWithServer()", () => {
it("should use cipherEncryptionService to move the cipher when feature flag enabled", async () => {
configService.getFeatureFlag
.calledWith(FeatureFlag.PM22136_SdkCipherEncryption)
.mockResolvedValue(true);
apiService.putShareCipher.mockResolvedValue(new CipherResponse(cipherData));
const expectedCipher = new Cipher(cipherData);
expectedCipher.organizationId = orgId;
const cipherView = new CipherView(expectedCipher);
const collectionIds = ["collection1", "collection2"] as CollectionId[];
cipherView.organizationId = undefined; // Ensure organizationId is undefined for this test
cipherEncryptionService.moveToOrganization.mockResolvedValue({
cipher: expectedCipher,
encryptedFor: userId,
});
await cipherService.shareWithServer(cipherView, orgId, collectionIds, userId);
// Expect SDK usage
expect(cipherEncryptionService.moveToOrganization).toHaveBeenCalledWith(
cipherView,
orgId,
userId,
);
// Expect collectionIds to be assigned
expect(apiService.putShareCipher).toHaveBeenCalledWith(
cipherView.id,
expect.objectContaining({
cipher: expect.objectContaining({ organizationId: orgId }),
collectionIds: collectionIds,
}),
);
});
it("should use legacy encryption when feature flag disabled", async () => {
configService.getFeatureFlag
.calledWith(FeatureFlag.PM22136_SdkCipherEncryption)
.mockResolvedValue(false);
apiService.putShareCipher.mockResolvedValue(new CipherResponse(cipherData));
const expectedCipher = new Cipher(cipherData);
expectedCipher.organizationId = orgId;
const cipherView = new CipherView(expectedCipher);
const collectionIds = ["collection1", "collection2"] as CollectionId[];
cipherView.organizationId = undefined; // Ensure organizationId is undefined for this test
const oldEncryptSharedSpy = jest
.spyOn(cipherService as any, "encryptSharedCipher")
.mockResolvedValue({
cipher: expectedCipher,
encryptedFor: userId,
});
await cipherService.shareWithServer(cipherView, orgId, collectionIds, userId);
// Expect no SDK usage
expect(cipherEncryptionService.moveToOrganization).not.toHaveBeenCalled();
expect(oldEncryptSharedSpy).toHaveBeenCalledWith(
expect.objectContaining({
organizationId: orgId,
collectionIds: collectionIds,
} as unknown as CipherView),
userId,
);
});
});
});

View File

@@ -71,6 +71,7 @@ import { CipherView } from "../models/view/cipher.view";
import { FieldView } from "../models/view/field.view";
import { PasswordHistoryView } from "../models/view/password-history.view";
import { AddEditCipherInfo } from "../types/add-edit-cipher-info";
import { CipherViewLike, CipherViewLikeUtils } from "../utils/cipher-view-like-utils";
import {
ADD_EDIT_CIPHER_INFO_KEY,
@@ -123,6 +124,43 @@ export class CipherService implements CipherServiceAbstraction {
return this.encryptedCiphersState(userId).state$.pipe(map((ciphers) => ciphers ?? {}));
}
/**
* Observable that emits an array of decrypted ciphers for given userId.
* This observable will not emit until the encrypted ciphers have either been loaded from state or after sync.
*
* This uses the SDK for decryption, when the `PM22134SdkCipherListView` feature flag is disabled the full `cipherViews$` observable will be emitted.
* Usage of the {@link CipherViewLike} type is recommended to ensure both `CipherView` and `CipherListView` are supported.
*/
cipherListViews$ = perUserCache$((userId: UserId) => {
return this.configService.getFeatureFlag$(FeatureFlag.PM22134SdkCipherListView).pipe(
switchMap((useSdk) => {
if (!useSdk) {
return this.cipherViews$(userId);
}
return combineLatest([
this.encryptedCiphersState(userId).state$,
this.localData$(userId),
this.keyService.cipherDecryptionKeys$(userId, true),
]).pipe(
filter(([cipherDataState, _, keys]) => cipherDataState != null && keys != null),
map(([cipherDataState, localData]) =>
Object.values(cipherDataState).map(
(cipherData) => new Cipher(cipherData, localData?.[cipherData.id as CipherId]),
),
),
switchMap(async (ciphers) => {
// TODO: remove this once failed decrypted ciphers are handled in the SDK
await this.setFailedDecryptedCiphers([], userId);
return this.cipherEncryptionService
.decryptMany(ciphers, userId)
.then((ciphers) => ciphers.sort(this.getLocaleSortingFunction()));
}),
);
}),
);
});
/**
* Observable that emits an array of decrypted ciphers for the active user.
* This observable will not emit until the encrypted ciphers have either been loaded from state or after sync.
@@ -193,13 +231,14 @@ export class CipherService implements CipherServiceAbstraction {
this.clearCipherViewsForUser$.next(userId);
}
async encrypt(
model: CipherView,
userId: UserId,
keyForCipherEncryption?: SymmetricCryptoKey,
keyForCipherKeyDecryption?: SymmetricCryptoKey,
originalCipher: Cipher = null,
): Promise<EncryptionContext> {
/**
* Adjusts the cipher history for the given model by updating its history properties based on the original cipher.
* @param model The cipher model to adjust.
* @param userId The acting userId
* @param originalCipher The original cipher to compare against. If not provided, it will be fetched from the store.
* @private
*/
private async adjustCipherHistory(model: CipherView, userId: UserId, originalCipher?: Cipher) {
if (model.id != null) {
if (originalCipher == null) {
originalCipher = await this.get(model.id, userId);
@@ -209,6 +248,25 @@ export class CipherService implements CipherServiceAbstraction {
}
this.adjustPasswordHistoryLength(model);
}
}
async encrypt(
model: CipherView,
userId: UserId,
keyForCipherEncryption?: SymmetricCryptoKey,
keyForCipherKeyDecryption?: SymmetricCryptoKey,
originalCipher: Cipher = null,
): Promise<EncryptionContext> {
await this.adjustCipherHistory(model, userId, originalCipher);
const sdkEncryptionEnabled =
(await this.configService.getFeatureFlag(FeatureFlag.PM22136_SdkCipherEncryption)) &&
keyForCipherEncryption == null && // PM-23085 - SDK encryption does not currently support custom keys (e.g. key rotation)
keyForCipherKeyDecryption == null; // PM-23348 - Or has explicit methods for re-encrypting ciphers with different keys (e.g. move to org)
if (sdkEncryptionEnabled) {
return await this.cipherEncryptionService.encrypt(model, userId);
}
const cipher = new Cipher();
cipher.id = model.id;
@@ -543,18 +601,23 @@ export class CipherService implements CipherServiceAbstraction {
filter((c) => c != null),
switchMap(
async (ciphers) =>
await this.filterCiphersForUrl(ciphers, url, includeOtherTypes, defaultMatch),
await this.filterCiphersForUrl<CipherView>(
ciphers,
url,
includeOtherTypes,
defaultMatch,
),
),
),
);
}
async filterCiphersForUrl(
ciphers: CipherView[],
async filterCiphersForUrl<C extends CipherViewLike>(
ciphers: C[],
url: string,
includeOtherTypes?: CipherType[],
defaultMatch: UriMatchStrategySetting = null,
): Promise<CipherView[]> {
): Promise<C[]> {
if (url == null && includeOtherTypes == null) {
return [];
}
@@ -565,22 +628,20 @@ export class CipherService implements CipherServiceAbstraction {
defaultMatch ??= await firstValueFrom(this.domainSettingsService.defaultUriMatchStrategy$);
return ciphers.filter((cipher) => {
const cipherIsLogin = cipher.type === CipherType.Login && cipher.login !== null;
const type = CipherViewLikeUtils.getType(cipher);
const login = CipherViewLikeUtils.getLogin(cipher);
const cipherIsLogin = login !== null;
if (cipher.deletedDate !== null) {
if (CipherViewLikeUtils.isDeleted(cipher)) {
return false;
}
if (
Array.isArray(includeOtherTypes) &&
includeOtherTypes.includes(cipher.type) &&
!cipherIsLogin
) {
if (Array.isArray(includeOtherTypes) && includeOtherTypes.includes(type) && !cipherIsLogin) {
return true;
}
if (cipherIsLogin) {
return cipher.login.matchesUri(url, equivalentDomains, defaultMatch);
return CipherViewLikeUtils.matchesUri(cipher, url, equivalentDomains, defaultMatch);
}
return false;
@@ -813,22 +874,48 @@ export class CipherService implements CipherServiceAbstraction {
organizationId: string,
collectionIds: string[],
userId: UserId,
originalCipher?: Cipher,
): Promise<Cipher> {
const attachmentPromises: Promise<any>[] = [];
if (cipher.attachments != null) {
cipher.attachments.forEach((attachment) => {
if (attachment.key == null) {
attachmentPromises.push(
this.shareAttachmentWithServer(attachment, cipher.id, organizationId),
);
}
});
}
await Promise.all(attachmentPromises);
const sdkCipherEncryptionEnabled = await this.configService.getFeatureFlag(
FeatureFlag.PM22136_SdkCipherEncryption,
);
await this.adjustCipherHistory(cipher, userId, originalCipher);
let encCipher: EncryptionContext;
if (sdkCipherEncryptionEnabled) {
// The SDK does not expect the cipher to already have an organizationId. It will result in the wrong
// cipher encryption key being used during the move to organization operation.
if (cipher.organizationId != null) {
throw new Error("Cipher is already associated with an organization.");
}
encCipher = await this.cipherEncryptionService.moveToOrganization(
cipher,
organizationId as OrganizationId,
userId,
);
encCipher.cipher.collectionIds = collectionIds;
} else {
// This old attachment logic is safe to remove after it is replaced in PM-22750; which will require fixing
// the attachment before sharing.
const attachmentPromises: Promise<any>[] = [];
if (cipher.attachments != null) {
cipher.attachments.forEach((attachment) => {
if (attachment.key == null) {
attachmentPromises.push(
this.shareAttachmentWithServer(attachment, cipher.id, organizationId),
);
}
});
}
await Promise.all(attachmentPromises);
cipher.organizationId = organizationId;
cipher.collectionIds = collectionIds;
encCipher = await this.encryptSharedCipher(cipher, userId);
}
cipher.organizationId = organizationId;
cipher.collectionIds = collectionIds;
const encCipher = await this.encryptSharedCipher(cipher, userId);
const request = new CipherShareRequest(encCipher);
const response = await this.apiService.putShareCipher(cipher.id, request);
const data = new CipherData(response, collectionIds);
@@ -842,16 +929,36 @@ export class CipherService implements CipherServiceAbstraction {
collectionIds: string[],
userId: UserId,
) {
const sdkCipherEncryptionEnabled = await this.configService.getFeatureFlag(
FeatureFlag.PM22136_SdkCipherEncryption,
);
const promises: Promise<any>[] = [];
const encCiphers: Cipher[] = [];
for (const cipher of ciphers) {
cipher.organizationId = organizationId;
cipher.collectionIds = collectionIds;
promises.push(
this.encryptSharedCipher(cipher, userId).then((c) => {
encCiphers.push(c.cipher);
}),
);
if (sdkCipherEncryptionEnabled) {
// The SDK does not expect the cipher to already have an organizationId. It will result in the wrong
// cipher encryption key being used during the move to organization operation.
if (cipher.organizationId != null) {
throw new Error("Cipher is already associated with an organization.");
}
promises.push(
this.cipherEncryptionService
.moveToOrganization(cipher, organizationId as OrganizationId, userId)
.then((encCipher) => {
encCipher.cipher.collectionIds = collectionIds;
encCiphers.push(encCipher.cipher);
}),
);
} else {
cipher.organizationId = organizationId;
cipher.collectionIds = collectionIds;
promises.push(
this.encryptSharedCipher(cipher, userId).then((c) => {
encCiphers.push(c.cipher);
}),
);
}
}
await Promise.all(promises);
const request = new CipherBulkShareRequest(encCiphers, collectionIds, userId);
@@ -1173,7 +1280,7 @@ export class CipherService implements CipherServiceAbstraction {
return await this.deleteAttachment(id, cipherData.revisionDate, attachmentId, userId);
}
sortCiphersByLastUsed(a: CipherView, b: CipherView): number {
sortCiphersByLastUsed(a: CipherViewLike, b: CipherViewLike): number {
const aLastUsed =
a.localData && a.localData.lastUsedDate ? (a.localData.lastUsedDate as number) : null;
const bLastUsed =
@@ -1197,7 +1304,7 @@ export class CipherService implements CipherServiceAbstraction {
return 0;
}
sortCiphersByLastUsedThenName(a: CipherView, b: CipherView): number {
sortCiphersByLastUsedThenName(a: CipherViewLike, b: CipherViewLike): number {
const result = this.sortCiphersByLastUsed(a, b);
if (result !== 0) {
return result;
@@ -1206,7 +1313,7 @@ export class CipherService implements CipherServiceAbstraction {
return this.getLocaleSortingFunction()(a, b);
}
getLocaleSortingFunction(): (a: CipherView, b: CipherView) => number {
getLocaleSortingFunction(): (a: CipherViewLike, b: CipherViewLike) => number {
return (a, b) => {
let aName = a.name;
let bName = b.name;
@@ -1225,16 +1332,22 @@ export class CipherService implements CipherServiceAbstraction {
? this.i18nService.collator.compare(aName, bName)
: aName.localeCompare(bName);
if (result !== 0 || a.type !== CipherType.Login || b.type !== CipherType.Login) {
const aType = CipherViewLikeUtils.getType(a);
const bType = CipherViewLikeUtils.getType(b);
if (result !== 0 || aType !== CipherType.Login || bType !== CipherType.Login) {
return result;
}
if (a.login.username != null) {
aName += a.login.username;
const aLogin = CipherViewLikeUtils.getLogin(a);
const bLogin = CipherViewLikeUtils.getLogin(b);
if (aLogin.username != null) {
aName += aLogin.username;
}
if (b.login.username != null) {
bName += b.login.username;
if (bLogin.username != null) {
bName += bLogin.username;
}
return this.i18nService.collator
@@ -1902,4 +2015,17 @@ export class CipherService implements CipherServiceAbstraction {
return decryptedViews.sort(this.getLocaleSortingFunction());
}
/** Fetches the full `CipherView` when a `CipherListView` is passed. */
async getFullCipherView(c: CipherViewLike): Promise<CipherView> {
if (CipherViewLikeUtils.isCipherListView(c)) {
const activeUserId = await firstValueFrom(
this.accountService.activeAccount$.pipe(map((a) => a?.id)),
);
const cipher = await this.get(c.id!, activeUserId);
return this.decrypt(cipher, activeUserId);
}
return Promise.resolve(c);
}
}

View File

@@ -1,20 +1,22 @@
import { mock } from "jest-mock-extended";
import { of } from "rxjs";
import { Fido2Credential } from "@bitwarden/common/vault/models/domain/fido2-credential";
import {
Fido2Credential,
Fido2Credential as SdkFido2Credential,
Cipher as SdkCipher,
CipherType as SdkCipherType,
CipherView as SdkCipherView,
CipherListView,
AttachmentView as SdkAttachmentView,
Fido2CredentialFullView,
} from "@bitwarden/sdk-internal";
import { mockEnc } from "../../../spec";
import { UriMatchStrategy } from "../../models/domain/domain-service";
import { LogService } from "../../platform/abstractions/log.service";
import { SdkService } from "../../platform/abstractions/sdk/sdk.service";
import { UserId } from "../../types/guid";
import { UserId, CipherId, OrganizationId } from "../../types/guid";
import { CipherRepromptType, CipherType } from "../enums";
import { CipherPermissionsApi } from "../models/api/cipher-permissions.api";
import { CipherData } from "../models/data/cipher.data";
@@ -25,10 +27,15 @@ import { Fido2CredentialView } from "../models/view/fido2-credential.view";
import { DefaultCipherEncryptionService } from "./default-cipher-encryption.service";
const cipherId = "bdc4ef23-1116-477e-ae73-247854af58cb" as CipherId;
const orgId = "c5e9654f-6cc5-44c4-8e09-3d323522668c" as OrganizationId;
const folderId = "a3e9654f-6cc5-44c4-8e09-3d323522668c";
const userId = "59fbbb44-8cc8-4279-ab40-afc5f68704f4" as UserId;
const cipherData: CipherData = {
id: "id",
organizationId: "orgId",
folderId: "folderId",
id: cipherId,
organizationId: orgId,
folderId: folderId,
edit: true,
viewPassword: true,
organizationUseTotp: true,
@@ -78,13 +85,17 @@ describe("DefaultCipherEncryptionService", () => {
const sdkService = mock<SdkService>();
const logService = mock<LogService>();
let sdkCipherView: SdkCipherView;
let sdkCipher: SdkCipher;
const mockSdkClient = {
vault: jest.fn().mockReturnValue({
ciphers: jest.fn().mockReturnValue({
encrypt: jest.fn(),
set_fido2_credentials: jest.fn(),
decrypt: jest.fn(),
decrypt_list: jest.fn(),
decrypt_fido2_credentials: jest.fn(),
move_to_organization: jest.fn(),
}),
attachments: jest.fn().mockReturnValue({
decrypt_buffer: jest.fn(),
@@ -99,21 +110,25 @@ describe("DefaultCipherEncryptionService", () => {
take: jest.fn().mockReturnValue(mockRef),
};
const userId = "user-id" as UserId;
let cipherObj: Cipher;
let cipherViewObj: CipherView;
beforeEach(() => {
sdkService.userClient$ = jest.fn((userId: UserId) => of(mockSdk)) as any;
cipherEncryptionService = new DefaultCipherEncryptionService(sdkService, logService);
cipherObj = new Cipher(cipherData);
cipherViewObj = new CipherView(cipherObj);
jest.spyOn(cipherObj, "toSdkCipher").mockImplementation(() => {
return { id: cipherData.id } as SdkCipher;
});
jest.spyOn(cipherViewObj, "toSdkCipherView").mockImplementation(() => {
return { id: cipherData.id } as SdkCipherView;
});
sdkCipherView = {
id: "test-id",
id: cipherId as string,
type: SdkCipherType.Login,
name: "test-name",
login: {
@@ -121,16 +136,211 @@ describe("DefaultCipherEncryptionService", () => {
password: "test-password",
},
} as SdkCipherView;
sdkCipher = {
id: cipherId,
type: SdkCipherType.Login,
name: "encrypted-name",
login: {
username: "encrypted-username",
password: "encrypted-password",
},
} as unknown as SdkCipher;
});
afterEach(() => {
jest.clearAllMocks();
});
describe("encrypt", () => {
it("should encrypt a cipher successfully", async () => {
const expectedCipher: Cipher = {
id: cipherId as string,
type: CipherType.Login,
name: "encrypted-name",
login: {
username: "encrypted-username",
password: "encrypted-password",
},
} as unknown as Cipher;
mockSdkClient.vault().ciphers().encrypt.mockReturnValue({
cipher: sdkCipher,
encryptedFor: userId,
});
jest.spyOn(Cipher, "fromSdkCipher").mockReturnValue(expectedCipher);
const result = await cipherEncryptionService.encrypt(cipherViewObj, userId);
expect(result).toBeDefined();
expect(result!.cipher).toEqual(expectedCipher);
expect(result!.encryptedFor).toBe(userId);
expect(cipherViewObj.toSdkCipherView).toHaveBeenCalled();
expect(mockSdkClient.vault().ciphers().encrypt).toHaveBeenCalledWith({ id: cipherData.id });
});
it("should encrypt FIDO2 credentials if present", async () => {
const fidoCredentialView = new Fido2CredentialView();
fidoCredentialView.credentialId = "credentialId";
cipherViewObj.login.fido2Credentials = [fidoCredentialView];
jest.spyOn(fidoCredentialView, "toSdkFido2CredentialFullView").mockImplementation(
() =>
({
credentialId: "credentialId",
}) as Fido2CredentialFullView,
);
jest.spyOn(cipherViewObj, "toSdkCipherView").mockImplementation(
() =>
({
id: cipherId as string,
login: {
fido2Credentials: undefined,
},
}) as unknown as SdkCipherView,
);
mockSdkClient
.vault()
.ciphers()
.set_fido2_credentials.mockReturnValue({
id: cipherId as string,
login: {
fido2Credentials: [
{
credentialId: "encrypted-credentialId",
},
],
},
});
mockSdkClient.vault().ciphers().encrypt.mockReturnValue({
cipher: sdkCipher,
encryptedFor: userId,
});
cipherObj.login!.fido2Credentials = [
{ credentialId: "encrypted-credentialId" } as unknown as Fido2Credential,
];
jest.spyOn(Cipher, "fromSdkCipher").mockReturnValue(cipherObj);
const result = await cipherEncryptionService.encrypt(cipherViewObj, userId);
expect(result).toBeDefined();
expect(result!.cipher.login!.fido2Credentials).toHaveLength(1);
// Ensure set_fido2_credentials was called with correct parameters
expect(mockSdkClient.vault().ciphers().set_fido2_credentials).toHaveBeenCalledWith(
expect.objectContaining({ id: cipherId }),
[{ credentialId: "credentialId" }],
);
// Encrypted fido2 credential should be in the cipher passed to encrypt
expect(mockSdkClient.vault().ciphers().encrypt).toHaveBeenCalledWith(
expect.objectContaining({
id: cipherId,
login: { fido2Credentials: [{ credentialId: "encrypted-credentialId" }] },
}),
);
});
});
describe("moveToOrganization", () => {
it("should call the sdk method to move a cipher to an organization", async () => {
const expectedCipher: Cipher = {
id: cipherId as string,
type: CipherType.Login,
name: "encrypted-name",
organizationId: orgId,
login: {
username: "encrypted-username",
password: "encrypted-password",
},
} as unknown as Cipher;
mockSdkClient.vault().ciphers().move_to_organization.mockReturnValue({
id: cipherId,
organizationId: orgId,
});
mockSdkClient.vault().ciphers().encrypt.mockReturnValue({
cipher: sdkCipher,
encryptedFor: userId,
});
jest.spyOn(Cipher, "fromSdkCipher").mockReturnValue(expectedCipher);
const result = await cipherEncryptionService.moveToOrganization(cipherViewObj, orgId, userId);
expect(result).toBeDefined();
expect(result!.cipher).toEqual(expectedCipher);
expect(result!.encryptedFor).toBe(userId);
expect(cipherViewObj.toSdkCipherView).toHaveBeenCalled();
expect(mockSdkClient.vault().ciphers().move_to_organization).toHaveBeenCalledWith(
{ id: cipherData.id },
orgId,
);
});
it("should re-encrypt any fido2 credentials when moving to an organization", async () => {
const mockSdkCredentialView = {
username: "username",
} as unknown as Fido2CredentialFullView;
const mockCredentialView = mock<Fido2CredentialView>();
mockCredentialView.toSdkFido2CredentialFullView.mockReturnValue(mockSdkCredentialView);
cipherViewObj.login.fido2Credentials = [mockCredentialView];
const expectedCipher: Cipher = {
id: cipherId as string,
type: CipherType.Login,
name: "encrypted-name",
organizationId: orgId,
login: {
username: "encrypted-username",
password: "encrypted-password",
fido2Credentials: [{ username: "encrypted-username" }],
},
} as unknown as Cipher;
mockSdkClient
.vault()
.ciphers()
.set_fido2_credentials.mockReturnValue({
id: cipherId as string,
login: {
fido2Credentials: [mockSdkCredentialView],
},
} as SdkCipherView);
mockSdkClient.vault().ciphers().move_to_organization.mockReturnValue({
id: cipherId,
organizationId: orgId,
});
mockSdkClient.vault().ciphers().encrypt.mockReturnValue({
cipher: sdkCipher,
encryptedFor: userId,
});
jest.spyOn(Cipher, "fromSdkCipher").mockReturnValue(expectedCipher);
const result = await cipherEncryptionService.moveToOrganization(cipherViewObj, orgId, userId);
expect(result).toBeDefined();
expect(result!.cipher).toEqual(expectedCipher);
expect(result!.encryptedFor).toBe(userId);
expect(cipherViewObj.toSdkCipherView).toHaveBeenCalled();
expect(mockSdkClient.vault().ciphers().set_fido2_credentials).toHaveBeenCalledWith(
expect.objectContaining({ id: cipherId }),
expect.arrayContaining([mockSdkCredentialView]),
);
expect(mockSdkClient.vault().ciphers().move_to_organization).toHaveBeenCalledWith(
{ id: cipherData.id, login: { fido2Credentials: [mockSdkCredentialView] } },
orgId,
);
});
});
describe("decrypt", () => {
it("should decrypt a cipher successfully", async () => {
const expectedCipherView: CipherView = {
id: "test-id",
id: cipherId as string,
type: CipherType.Login,
name: "test-name",
login: {
@@ -168,12 +378,12 @@ describe("DefaultCipherEncryptionService", () => {
discoverable: mockEnc("true"),
creationDate: new Date("2023-01-01T12:00:00.000Z"),
},
] as unknown as Fido2Credential[];
] as unknown as SdkFido2Credential[];
sdkCipherView.login!.fido2Credentials = fido2Credentials;
const expectedCipherView: CipherView = {
id: "test-id",
id: cipherId,
type: CipherType.Login,
name: "test-name",
login: {
@@ -228,13 +438,15 @@ describe("DefaultCipherEncryptionService", () => {
it("should decrypt multiple ciphers successfully", async () => {
const ciphers = [new Cipher(cipherData), new Cipher(cipherData)];
const cipherId2 = "bdc4ef23-2222-477e-ae73-247854af58cb" as CipherId;
const expectedViews = [
{
id: "test-id-1",
id: cipherId as string,
name: "test-name-1",
} as CipherView,
{
id: "test-id-2",
id: cipherId2 as string,
name: "test-name-2",
} as CipherView,
];
@@ -242,8 +454,11 @@ describe("DefaultCipherEncryptionService", () => {
mockSdkClient
.vault()
.ciphers()
.decrypt.mockReturnValueOnce({ id: "test-id-1", name: "test-name-1" } as SdkCipherView)
.mockReturnValueOnce({ id: "test-id-2", name: "test-name-2" } as SdkCipherView);
.decrypt.mockReturnValueOnce({
id: cipherId,
name: "test-name-1",
} as unknown as SdkCipherView)
.mockReturnValueOnce({ id: cipherId2, name: "test-name-2" } as unknown as SdkCipherView);
jest
.spyOn(CipherView, "fromSdkCipherView")

View File

@@ -1,10 +1,15 @@
import { EMPTY, catchError, firstValueFrom, map } from "rxjs";
import { CipherListView } from "@bitwarden/sdk-internal";
import { EncryptionContext } from "@bitwarden/common/vault/abstractions/cipher.service";
import {
CipherListView,
BitwardenClient,
CipherView as SdkCipherView,
} from "@bitwarden/sdk-internal";
import { LogService } from "../../platform/abstractions/log.service";
import { SdkService } from "../../platform/abstractions/sdk/sdk.service";
import { UserId } from "../../types/guid";
import { SdkService, asUuid } from "../../platform/abstractions/sdk/sdk.service";
import { UserId, OrganizationId } from "../../types/guid";
import { CipherEncryptionService } from "../abstractions/cipher-encryption.service";
import { CipherType } from "../enums";
import { Cipher } from "../models/domain/cipher";
@@ -18,6 +23,67 @@ export class DefaultCipherEncryptionService implements CipherEncryptionService {
private logService: LogService,
) {}
async encrypt(model: CipherView, userId: UserId): Promise<EncryptionContext | undefined> {
return firstValueFrom(
this.sdkService.userClient$(userId).pipe(
map((sdk) => {
if (!sdk) {
throw new Error("SDK not available");
}
using ref = sdk.take();
const sdkCipherView = this.toSdkCipherView(model, ref.value);
const encryptionContext = ref.value.vault().ciphers().encrypt(sdkCipherView);
return {
cipher: Cipher.fromSdkCipher(encryptionContext.cipher)!,
encryptedFor: asUuid<UserId>(encryptionContext.encryptedFor),
};
}),
catchError((error: unknown) => {
this.logService.error(`Failed to encrypt cipher: ${error}`);
return EMPTY;
}),
),
);
}
async moveToOrganization(
model: CipherView,
organizationId: OrganizationId,
userId: UserId,
): Promise<EncryptionContext | undefined> {
return firstValueFrom(
this.sdkService.userClient$(userId).pipe(
map((sdk) => {
if (!sdk) {
throw new Error("SDK not available");
}
using ref = sdk.take();
const sdkCipherView = this.toSdkCipherView(model, ref.value);
const movedCipherView = ref.value
.vault()
.ciphers()
.move_to_organization(sdkCipherView, asUuid(organizationId));
const encryptionContext = ref.value.vault().ciphers().encrypt(movedCipherView);
return {
cipher: Cipher.fromSdkCipher(encryptionContext.cipher)!,
encryptedFor: asUuid<UserId>(encryptionContext.encryptedFor),
};
}),
catchError((error: unknown) => {
this.logService.error(`Failed to move cipher to organization: ${error}`);
return EMPTY;
}),
),
);
}
async decrypt(cipher: Cipher, userId: UserId): Promise<CipherView> {
return firstValueFrom(
this.sdkService.userClient$(userId).pipe(
@@ -51,11 +117,8 @@ export class DefaultCipherEncryptionService implements CipherEncryptionService {
clientCipherView.login.fido2Credentials = fido2CredentialViews
.map((f) => {
const view = Fido2CredentialView.fromSdkFido2CredentialView(f)!;
return {
...view,
keyValue: decryptedKeyValue,
};
view.keyValue = decryptedKeyValue;
return view;
})
.filter((view): view is Fido2CredentialView => view !== undefined);
}
@@ -104,10 +167,8 @@ export class DefaultCipherEncryptionService implements CipherEncryptionService {
clientCipherView.login.fido2Credentials = fido2CredentialViews
.map((f) => {
const view = Fido2CredentialView.fromSdkFido2CredentialView(f)!;
return {
...view,
keyValue: decryptedKeyValue,
};
view.keyValue = decryptedKeyValue;
return view;
})
.filter((view): view is Fido2CredentialView => view !== undefined);
}
@@ -187,4 +248,25 @@ export class DefaultCipherEncryptionService implements CipherEncryptionService {
),
);
}
/**
* Helper method to convert a CipherView model to an SDK CipherView. Has special handling for Fido2 credentials
* that need to be encrypted before being sent to the SDK.
* @param model The CipherView model to convert
* @param sdk An instance of SDK client
* @private
*/
private toSdkCipherView(model: CipherView, sdk: BitwardenClient): SdkCipherView {
let sdkCipherView = model.toSdkCipherView();
if (model.type === CipherType.Login && model.login?.hasFido2Credentials) {
// Encrypt Fido2 credentials separately
const fido2Credentials = model.login.fido2Credentials?.map((f) =>
f.toSdkFido2CredentialFullView(),
);
sdkCipherView = sdk.vault().ciphers().set_fido2_credentials(sdkCipherView, fido2Credentials);
}
return sdkCipherView;
}
}

View File

@@ -9,17 +9,15 @@ import { getUserId } from "@bitwarden/common/auth/services/account.service";
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service";
import { CipherType } from "@bitwarden/common/vault/enums";
import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view";
import { Cipher } from "../models/domain/cipher";
import { CipherLike } from "../types/cipher-like";
import { CipherViewLikeUtils } from "../utils/cipher-view-like-utils";
export type RestrictedCipherType = {
cipherType: CipherType;
allowViewOrgIds: string[];
};
type CipherLike = Cipher | CipherView;
export class RestrictedItemTypesService {
/**
* Emits an array of RestrictedCipherType objects:
@@ -94,7 +92,9 @@ export class RestrictedItemTypesService {
* - Otherwise → restricted
*/
isCipherRestricted(cipher: CipherLike, restrictedTypes: RestrictedCipherType[]): boolean {
const restriction = restrictedTypes.find((r) => r.cipherType === cipher.type);
const restriction = restrictedTypes.find(
(r) => r.cipherType === CipherViewLikeUtils.getType(cipher),
);
// If cipher type is not restricted by any organization, allow it
if (!restriction) {

View File

@@ -19,6 +19,7 @@ import { SearchService as SearchServiceAbstraction } from "../abstractions/searc
import { FieldType } from "../enums";
import { CipherType } from "../enums/cipher-type";
import { CipherView } from "../models/view/cipher.view";
import { CipherViewLike, CipherViewLikeUtils } from "../utils/cipher-view-like-utils";
export type SerializedLunrIndex = {
version: string;
@@ -197,13 +198,13 @@ export class SearchService implements SearchServiceAbstraction {
]);
}
async searchCiphers(
async searchCiphers<C extends CipherViewLike>(
userId: UserId,
query: string,
filter: ((cipher: CipherView) => boolean) | ((cipher: CipherView) => boolean)[] = null,
ciphers: CipherView[],
): Promise<CipherView[]> {
const results: CipherView[] = [];
filter: ((cipher: C) => boolean) | ((cipher: C) => boolean)[] = null,
ciphers: C[],
): Promise<C[]> {
const results: C[] = [];
if (query != null) {
query = SearchService.normalizeSearchQuery(query.trim().toLowerCase());
}
@@ -218,7 +219,7 @@ export class SearchService implements SearchServiceAbstraction {
if (filter != null && Array.isArray(filter) && filter.length > 0) {
ciphers = ciphers.filter((c) => filter.every((f) => f == null || f(c)));
} else if (filter != null) {
ciphers = ciphers.filter(filter as (cipher: CipherView) => boolean);
ciphers = ciphers.filter(filter as (cipher: C) => boolean);
}
if (!(await this.isSearchable(userId, query))) {
@@ -238,7 +239,7 @@ export class SearchService implements SearchServiceAbstraction {
return this.searchCiphersBasic(ciphers, query);
}
const ciphersMap = new Map<string, CipherView>();
const ciphersMap = new Map<string, C>();
ciphers.forEach((c) => ciphersMap.set(c.id, c));
let searchResults: lunr.Index.Result[] = null;
@@ -272,10 +273,10 @@ export class SearchService implements SearchServiceAbstraction {
return results;
}
searchCiphersBasic(ciphers: CipherView[], query: string, deleted = false) {
searchCiphersBasic<C extends CipherViewLike>(ciphers: C[], query: string, deleted = false) {
query = SearchService.normalizeSearchQuery(query.trim().toLowerCase());
return ciphers.filter((c) => {
if (deleted !== c.isDeleted) {
if (deleted !== CipherViewLikeUtils.isDeleted(c)) {
return false;
}
if (c.name != null && c.name.toLowerCase().indexOf(query) > -1) {
@@ -284,13 +285,17 @@ export class SearchService implements SearchServiceAbstraction {
if (query.length >= 8 && c.id.startsWith(query)) {
return true;
}
if (c.subTitle != null && c.subTitle.toLowerCase().indexOf(query) > -1) {
const subtitle = CipherViewLikeUtils.subtitle(c);
if (subtitle != null && subtitle.toLowerCase().indexOf(query) > -1) {
return true;
}
const login = CipherViewLikeUtils.getLogin(c);
if (
c.login &&
c.login.hasUris &&
c.login.uris.some((loginUri) => loginUri?.uri?.toLowerCase().indexOf(query) > -1)
login &&
login.uris.length &&
login.uris.some((loginUri) => loginUri?.uri?.toLowerCase().indexOf(query) > -1)
) {
return true;
}

View File

@@ -0,0 +1,9 @@
import { Cipher } from "../models/domain/cipher";
import { CipherViewLike } from "../utils/cipher-view-like-utils";
/**
* Represents either a Cipher, CipherView or CipherListView.
*
* {@link CipherViewLikeUtils} provides logic to perform operations on each type.
*/
export type CipherLike = Cipher | CipherViewLike;

View File

@@ -0,0 +1,624 @@
import { CipherListView } from "@bitwarden/sdk-internal";
import { CipherType } from "../enums";
import { Attachment } from "../models/domain/attachment";
import { AttachmentView } from "../models/view/attachment.view";
import { CipherView } from "../models/view/cipher.view";
import { Fido2CredentialView } from "../models/view/fido2-credential.view";
import { IdentityView } from "../models/view/identity.view";
import { LoginUriView } from "../models/view/login-uri.view";
import { LoginView } from "../models/view/login.view";
import { CipherViewLikeUtils } from "./cipher-view-like-utils";
describe("CipherViewLikeUtils", () => {
const createCipherView = (type: CipherType = CipherType.Login): CipherView => {
const cipherView = new CipherView();
// Always set a type to avoid issues within `CipherViewLikeUtils`
cipherView.type = type;
return cipherView;
};
describe("isCipherListView", () => {
it("returns true when the cipher is a CipherListView", () => {
const cipherListViewLogin = {
type: {
login: {},
},
} as CipherListView;
const cipherListViewSshKey = {
type: "sshKey",
} as CipherListView;
expect(CipherViewLikeUtils.isCipherListView(cipherListViewLogin)).toBe(true);
expect(CipherViewLikeUtils.isCipherListView(cipherListViewSshKey)).toBe(true);
});
it("returns false when the cipher is not a CipherListView", () => {
const cipherView = createCipherView();
cipherView.type = CipherType.SecureNote;
expect(CipherViewLikeUtils.isCipherListView(cipherView)).toBe(false);
});
});
describe("getLogin", () => {
it("returns null when the cipher is not a login", () => {
const cipherView = createCipherView(CipherType.SecureNote);
expect(CipherViewLikeUtils.getLogin(cipherView)).toBeNull();
expect(CipherViewLikeUtils.getLogin({ type: "identity" } as CipherListView)).toBeNull();
});
describe("CipherView", () => {
it("returns the login object", () => {
const cipherView = createCipherView(CipherType.Login);
expect(CipherViewLikeUtils.getLogin(cipherView)).toEqual(cipherView.login);
});
});
describe("CipherListView", () => {
it("returns the login object", () => {
const cipherListView = {
type: {
login: {
username: "testuser",
hasFido2: false,
},
},
} as CipherListView;
expect(CipherViewLikeUtils.getLogin(cipherListView)).toEqual(
(cipherListView.type as any).login,
);
});
});
});
describe("getCard", () => {
it("returns null when the cipher is not a card", () => {
const cipherView = createCipherView(CipherType.SecureNote);
expect(CipherViewLikeUtils.getCard(cipherView)).toBeNull();
expect(CipherViewLikeUtils.getCard({ type: "identity" } as CipherListView)).toBeNull();
});
describe("CipherView", () => {
it("returns the card object", () => {
const cipherView = createCipherView(CipherType.Card);
expect(CipherViewLikeUtils.getCard(cipherView)).toEqual(cipherView.card);
});
});
describe("CipherListView", () => {
it("returns the card object", () => {
const cipherListView = {
type: {
card: {
brand: "Visa",
},
},
} as CipherListView;
expect(CipherViewLikeUtils.getCard(cipherListView)).toEqual(
(cipherListView.type as any).card,
);
});
});
});
describe("isDeleted", () => {
it("returns true when the cipher is deleted", () => {
const cipherListView = { deletedDate: "2024-02-02", type: "identity" } as CipherListView;
const cipherView = createCipherView();
cipherView.deletedDate = new Date();
expect(CipherViewLikeUtils.isDeleted(cipherListView)).toBe(true);
expect(CipherViewLikeUtils.isDeleted(cipherView)).toBe(true);
});
it("returns false when the cipher is not deleted", () => {
const cipherListView = { deletedDate: undefined, type: "identity" } as CipherListView;
const cipherView = createCipherView();
expect(CipherViewLikeUtils.isDeleted(cipherListView)).toBe(false);
expect(CipherViewLikeUtils.isDeleted(cipherView)).toBe(false);
});
});
describe("canAssignToCollections", () => {
describe("CipherView", () => {
let cipherView: CipherView;
beforeEach(() => {
cipherView = createCipherView();
});
it("returns true when the cipher is not assigned to an organization", () => {
expect(CipherViewLikeUtils.canAssignToCollections(cipherView)).toBe(true);
});
it("returns false when the cipher is assigned to an organization and cannot be edited", () => {
cipherView.organizationId = "org-id";
cipherView.edit = false;
cipherView.viewPassword = false;
expect(CipherViewLikeUtils.canAssignToCollections(cipherView)).toBe(false);
});
it("returns true when the cipher is assigned to an organization and can be edited", () => {
cipherView.organizationId = "org-id";
cipherView.edit = true;
cipherView.viewPassword = true;
expect(CipherViewLikeUtils.canAssignToCollections(cipherView)).toBe(true);
});
});
describe("CipherListView", () => {
let cipherListView: CipherListView;
beforeEach(() => {
cipherListView = {
organizationId: undefined,
edit: false,
viewPassword: false,
type: { login: {} },
} as CipherListView;
});
it("returns true when the cipher is not assigned to an organization", () => {
expect(CipherViewLikeUtils.canAssignToCollections(cipherListView)).toBe(true);
});
it("returns false when the cipher is assigned to an organization and cannot be edited", () => {
cipherListView.organizationId = "org-id";
expect(CipherViewLikeUtils.canAssignToCollections(cipherListView)).toBe(false);
});
it("returns true when the cipher is assigned to an organization and can be edited", () => {
cipherListView.organizationId = "org-id";
cipherListView.edit = true;
cipherListView.viewPassword = true;
expect(CipherViewLikeUtils.canAssignToCollections(cipherListView)).toBe(true);
});
});
});
describe("getType", () => {
describe("CipherView", () => {
it("returns the type of the cipher", () => {
const cipherView = createCipherView();
cipherView.type = CipherType.Login;
expect(CipherViewLikeUtils.getType(cipherView)).toBe(CipherType.Login);
cipherView.type = CipherType.SecureNote;
expect(CipherViewLikeUtils.getType(cipherView)).toBe(CipherType.SecureNote);
cipherView.type = CipherType.SshKey;
expect(CipherViewLikeUtils.getType(cipherView)).toBe(CipherType.SshKey);
cipherView.type = CipherType.Identity;
expect(CipherViewLikeUtils.getType(cipherView)).toBe(CipherType.Identity);
cipherView.type = CipherType.Card;
expect(CipherViewLikeUtils.getType(cipherView)).toBe(CipherType.Card);
});
});
describe("CipherListView", () => {
it("converts the `CipherViewListType` to `CipherType`", () => {
const cipherListView = {
type: { login: {} },
} as CipherListView;
expect(CipherViewLikeUtils.getType(cipherListView)).toBe(CipherType.Login);
cipherListView.type = { card: { brand: "Visa" } };
expect(CipherViewLikeUtils.getType(cipherListView)).toBe(CipherType.Card);
cipherListView.type = "sshKey";
expect(CipherViewLikeUtils.getType(cipherListView)).toBe(CipherType.SshKey);
cipherListView.type = "identity";
expect(CipherViewLikeUtils.getType(cipherListView)).toBe(CipherType.Identity);
cipherListView.type = "secureNote";
expect(CipherViewLikeUtils.getType(cipherListView)).toBe(CipherType.SecureNote);
});
});
});
describe("subtitle", () => {
describe("CipherView", () => {
it("returns the subtitle of the cipher", () => {
const cipherView = createCipherView();
cipherView.login = new LoginView();
cipherView.login.username = "Test Username";
expect(CipherViewLikeUtils.subtitle(cipherView)).toBe("Test Username");
});
});
describe("CipherListView", () => {
it("returns the subtitle of the cipher", () => {
const cipherListView = {
subtitle: "Test Subtitle",
type: "identity",
} as CipherListView;
expect(CipherViewLikeUtils.subtitle(cipherListView)).toBe("Test Subtitle");
});
});
});
describe("hasAttachments", () => {
describe("CipherView", () => {
it("returns true when the cipher has attachments", () => {
const cipherView = createCipherView();
cipherView.attachments = [new AttachmentView({ id: "1" } as Attachment)];
expect(CipherViewLikeUtils.hasAttachments(cipherView)).toBe(true);
});
it("returns false when the cipher has no attachments", () => {
const cipherView = new CipherView();
(cipherView.attachments as any) = null;
expect(CipherViewLikeUtils.hasAttachments(cipherView)).toBe(false);
});
});
describe("CipherListView", () => {
it("returns true when there are attachments", () => {
const cipherListView = { attachments: 1, type: "secureNote" } as CipherListView;
expect(CipherViewLikeUtils.hasAttachments(cipherListView)).toBe(true);
});
it("returns false when there are no attachments", () => {
const cipherListView = { attachments: 0, type: "secureNote" } as CipherListView;
expect(CipherViewLikeUtils.hasAttachments(cipherListView)).toBe(false);
});
});
});
describe("canLaunch", () => {
it("returns false when the cipher is not a login", () => {
const cipherView = createCipherView(CipherType.SecureNote);
expect(CipherViewLikeUtils.canLaunch(cipherView)).toBe(false);
expect(CipherViewLikeUtils.canLaunch({ type: "identity" } as CipherListView)).toBe(false);
});
describe("CipherView", () => {
it("returns true when the login has URIs that can be launched", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
cipherView.login.uris = [{ uri: "https://example.com" } as LoginUriView];
expect(CipherViewLikeUtils.canLaunch(cipherView)).toBe(true);
});
it("returns true when the uri does not have a protocol", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
const uriView = new LoginUriView();
uriView.uri = "bitwarden.com";
cipherView.login.uris = [uriView];
expect(CipherViewLikeUtils.canLaunch(cipherView)).toBe(true);
});
it("returns false when the login has no URIs", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
expect(CipherViewLikeUtils.canLaunch(cipherView)).toBe(false);
});
});
describe("CipherListView", () => {
it("returns true when the login has URIs that can be launched", () => {
const cipherListView = {
type: { login: { uris: [{ uri: "https://example.com" }] } },
} as CipherListView;
expect(CipherViewLikeUtils.canLaunch(cipherListView)).toBe(true);
});
it("returns true when the uri does not have a protocol", () => {
const cipherListView = {
type: { login: { uris: [{ uri: "bitwarden.com" }] } },
} as CipherListView;
expect(CipherViewLikeUtils.canLaunch(cipherListView)).toBe(true);
});
it("returns false when the login has no URIs", () => {
const cipherListView = { type: { login: {} } } as CipherListView;
expect(CipherViewLikeUtils.canLaunch(cipherListView)).toBe(false);
});
});
});
describe("getLaunchUri", () => {
it("returns undefined when the cipher is not a login", () => {
const cipherView = createCipherView(CipherType.SecureNote);
expect(CipherViewLikeUtils.getLaunchUri(cipherView)).toBeUndefined();
expect(
CipherViewLikeUtils.getLaunchUri({ type: "identity" } as CipherListView),
).toBeUndefined();
});
describe("CipherView", () => {
it("returns the first launch-able URI", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
cipherView.login.uris = [
{ uri: "" } as LoginUriView,
{ uri: "https://example.com" } as LoginUriView,
{ uri: "https://another.com" } as LoginUriView,
];
expect(CipherViewLikeUtils.getLaunchUri(cipherView)).toBe("https://example.com");
});
it("returns undefined when there are no URIs", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
expect(CipherViewLikeUtils.getLaunchUri(cipherView)).toBeUndefined();
});
it("appends protocol when there are none", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
const uriView = new LoginUriView();
uriView.uri = "bitwarden.com";
cipherView.login.uris = [uriView];
expect(CipherViewLikeUtils.getLaunchUri(cipherView)).toBe("http://bitwarden.com");
});
});
describe("CipherListView", () => {
it("returns the first launch-able URI", () => {
const cipherListView = {
type: { login: { uris: [{ uri: "" }, { uri: "https://example.com" }] } },
} as CipherListView;
expect(CipherViewLikeUtils.getLaunchUri(cipherListView)).toBe("https://example.com");
});
it("returns undefined when there are no URIs", () => {
const cipherListView = { type: { login: {} } } as CipherListView;
expect(CipherViewLikeUtils.getLaunchUri(cipherListView)).toBeUndefined();
});
});
});
describe("matchesUri", () => {
const emptySet = new Set<string>();
it("returns false when the cipher is not a login", () => {
const cipherView = createCipherView(CipherType.SecureNote);
expect(CipherViewLikeUtils.matchesUri(cipherView, "https://example.com", emptySet)).toBe(
false,
);
});
describe("CipherView", () => {
it("returns true when the URI matches", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
const uri = new LoginUriView();
uri.uri = "https://example.com";
cipherView.login.uris = [uri];
expect(CipherViewLikeUtils.matchesUri(cipherView, "https://example.com", emptySet)).toBe(
true,
);
});
it("returns false when the URI does not match", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
const uri = new LoginUriView();
uri.uri = "https://www.bitwarden.com";
cipherView.login.uris = [uri];
expect(
CipherViewLikeUtils.matchesUri(cipherView, "https://www.another.com", emptySet),
).toBe(false);
});
});
describe("CipherListView", () => {
it("returns true when the URI matches", () => {
const cipherListView = {
type: { login: { uris: [{ uri: "https://example.com" }] } },
} as CipherListView;
expect(
CipherViewLikeUtils.matchesUri(cipherListView, "https://example.com", emptySet),
).toBe(true);
});
it("returns false when the URI does not match", () => {
const cipherListView = {
type: { login: { uris: [{ uri: "https://bitwarden.com" }] } },
} as CipherListView;
expect(
CipherViewLikeUtils.matchesUri(cipherListView, "https://another.com", emptySet),
).toBe(false);
});
});
});
describe("hasCopyableValue", () => {
describe("CipherView", () => {
it("returns true for login fields", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
cipherView.login.username = "testuser";
cipherView.login.password = "testpass";
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "username")).toBe(true);
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "password")).toBe(true);
});
it("returns true for card fields", () => {
const cipherView = createCipherView(CipherType.Card);
cipherView.card = { number: "1234-5678-9012-3456", code: "123" } as any;
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "cardNumber")).toBe(true);
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "securityCode")).toBe(true);
});
it("returns true for identity fields", () => {
const cipherView = createCipherView(CipherType.Identity);
cipherView.identity = new IdentityView();
cipherView.identity.email = "example@bitwarden.com";
cipherView.identity.phone = "123-456-7890";
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "email")).toBe(true);
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "phone")).toBe(true);
});
it("returns false when values are not populated", () => {
const cipherView = createCipherView(CipherType.Login);
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "email")).toBe(false);
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "password")).toBe(false);
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "securityCode")).toBe(false);
expect(CipherViewLikeUtils.hasCopyableValue(cipherView, "username")).toBe(false);
});
});
describe("CipherListView", () => {
it("returns true for copyable fields in a login cipher", () => {
const cipherListView = {
type: { login: { username: "testuser" } },
copyableFields: ["LoginUsername", "LoginPassword"],
} as CipherListView;
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "username")).toBe(true);
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "password")).toBe(true);
});
it("returns true for copyable fields in a card cipher", () => {
const cipherListView = {
type: { card: { brand: "MasterCard" } },
copyableFields: ["CardNumber", "CardSecurityCode"],
} as CipherListView;
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "cardNumber")).toBe(true);
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "securityCode")).toBe(true);
});
it("returns true for copyable fields in an sshKey ciphers", () => {
const cipherListView = {
type: "sshKey",
copyableFields: ["SshKey"],
} as CipherListView;
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "privateKey")).toBe(true);
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "publicKey")).toBe(true);
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "keyFingerprint")).toBe(true);
});
it("returns true for copyable fields in an identity cipher", () => {
const cipherListView = {
type: "identity",
copyableFields: ["IdentityUsername", "IdentityEmail", "IdentityPhone"],
} as CipherListView;
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "username")).toBe(true);
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "email")).toBe(true);
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "phone")).toBe(true);
});
it("returns false for when missing a field", () => {
const cipherListView = {
type: { login: {} },
copyableFields: ["LoginUsername"],
} as CipherListView;
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "password")).toBe(false);
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "phone")).toBe(false);
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "address")).toBe(false);
expect(CipherViewLikeUtils.hasCopyableValue(cipherListView, "publicKey")).toBe(false);
});
});
});
describe("hasFido2Credentials", () => {
describe("CipherView", () => {
it("returns true when the login has FIDO2 credentials", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
cipherView.login.fido2Credentials = [new Fido2CredentialView()];
expect(CipherViewLikeUtils.hasFido2Credentials(cipherView)).toBe(true);
});
it("returns false when the login has no FIDO2 credentials", () => {
const cipherView = createCipherView(CipherType.Login);
cipherView.login = new LoginView();
expect(CipherViewLikeUtils.hasFido2Credentials(cipherView)).toBe(false);
});
});
describe("CipherListView", () => {
it("returns true when the login has FIDO2 credentials", () => {
const cipherListView = {
type: { login: { fido2Credentials: [{ credentialId: "fido2-1" }] } },
} as CipherListView;
expect(CipherViewLikeUtils.hasFido2Credentials(cipherListView)).toBe(true);
});
it("returns false when the login has no FIDO2 credentials", () => {
const cipherListView = { type: { login: {} } } as CipherListView;
expect(CipherViewLikeUtils.hasFido2Credentials(cipherListView)).toBe(false);
});
});
});
describe("decryptionFailure", () => {
it("returns true when the cipher has a decryption failure", () => {
const cipherView = createCipherView();
cipherView.decryptionFailure = true;
expect(CipherViewLikeUtils.decryptionFailure(cipherView)).toBe(true);
});
it("returns false when the cipher does not have a decryption failure", () => {
const cipherView = createCipherView();
cipherView.decryptionFailure = false;
expect(CipherViewLikeUtils.decryptionFailure(cipherView)).toBe(false);
});
it("returns false when the cipher is a CipherListView without decryptionFailure", () => {
const cipherListView = { type: "secureNote" } as CipherListView;
expect(CipherViewLikeUtils.decryptionFailure(cipherListView)).toBe(false);
});
});
});

View File

@@ -0,0 +1,301 @@
import {
UriMatchStrategy,
UriMatchStrategySetting,
} from "@bitwarden/common/models/domain/domain-service";
import {
CardListView,
CipherListView,
CopyableCipherFields,
LoginListView,
LoginUriView as LoginListUriView,
} from "@bitwarden/sdk-internal";
import { CipherType } from "../enums";
import { Cipher } from "../models/domain/cipher";
import { CardView } from "../models/view/card.view";
import { CipherView } from "../models/view/cipher.view";
import { LoginUriView } from "../models/view/login-uri.view";
import { LoginView } from "../models/view/login.view";
/**
* Type union of {@link CipherView} and {@link CipherListView}.
*/
export type CipherViewLike = CipherView | CipherListView;
/**
* Utility class for working with ciphers that can be either a {@link CipherView} or a {@link CipherListView}.
*/
export class CipherViewLikeUtils {
/** @returns true when the given cipher is an instance of {@link CipherListView}. */
static isCipherListView = (cipher: CipherViewLike | Cipher): cipher is CipherListView => {
return typeof cipher.type === "object" || typeof cipher.type === "string";
};
/** @returns The login object from the input cipher. If the cipher is not of type Login, returns null. */
static getLogin = (cipher: CipherViewLike): LoginListView | LoginView | null => {
if (this.isCipherListView(cipher)) {
if (typeof cipher.type !== "object") {
return null;
}
return "login" in cipher.type ? cipher.type.login : null;
}
return cipher.type === CipherType.Login ? cipher.login : null;
};
/** @returns The first URI for a login cipher. If the cipher is not of type Login or has no associated URIs, returns null. */
static uri = (cipher: CipherViewLike) => {
const login = this.getLogin(cipher);
if (!login) {
return null;
}
if ("uri" in login) {
return login.uri;
}
return login.uris?.length ? login.uris[0].uri : null;
};
/** @returns The login object from the input cipher. If the cipher is not of type Login, returns null. */
static getCard = (cipher: CipherViewLike): CardListView | CardView | null => {
if (this.isCipherListView(cipher)) {
if (typeof cipher.type !== "object") {
return null;
}
return "card" in cipher.type ? cipher.type.card : null;
}
return cipher.type === CipherType.Card ? cipher.card : null;
};
/** @returns `true` when the cipher has been deleted, `false` otherwise. */
static isDeleted = (cipher: CipherViewLike): boolean => {
if (this.isCipherListView(cipher)) {
return !!cipher.deletedDate;
}
return cipher.isDeleted;
};
/** @returns `true` when the user can assign the cipher to a collection, `false` otherwise. */
static canAssignToCollections = (cipher: CipherViewLike): boolean => {
if (this.isCipherListView(cipher)) {
if (!cipher.organizationId) {
return true;
}
return cipher.edit && cipher.viewPassword;
}
return cipher.canAssignToCollections;
};
/**
* Returns the type of the cipher.
* For consistency, when the given cipher is a {@link CipherListView} the {@link CipherType} equivalent will be returned.
*/
static getType = (cipher: CipherViewLike | Cipher): CipherType => {
if (!this.isCipherListView(cipher)) {
return cipher.type;
}
// CipherListViewType is a string, so we need to map it to CipherType.
switch (true) {
case cipher.type === "secureNote":
return CipherType.SecureNote;
case cipher.type === "sshKey":
return CipherType.SshKey;
case cipher.type === "identity":
return CipherType.Identity;
case typeof cipher.type === "object" && "card" in cipher.type:
return CipherType.Card;
case typeof cipher.type === "object" && "login" in cipher.type:
return CipherType.Login;
default:
throw new Error(`Unknown cipher type: ${cipher.type}`);
}
};
/** @returns The subtitle of the cipher. */
static subtitle = (cipher: CipherViewLike): string | undefined => {
if (!this.isCipherListView(cipher)) {
return cipher.subTitle;
}
return cipher.subtitle;
};
/** @returns `true` when the cipher has attachments, false otherwise. */
static hasAttachments = (cipher: CipherViewLike): boolean => {
if (this.isCipherListView(cipher)) {
return typeof cipher.attachments === "number" && cipher.attachments > 0;
}
return cipher.hasAttachments;
};
/**
* @returns `true` when one of the URIs for the cipher can be launched.
* When a non-login cipher is passed, it will return false.
*/
static canLaunch = (cipher: CipherViewLike): boolean => {
const login = this.getLogin(cipher);
if (!login) {
return false;
}
return !!login.uris?.map((u) => toLoginUriView(u)).some((uri) => uri.canLaunch);
};
/**
* @returns The first launch-able URI for the cipher.
* When a non-login cipher is passed or none of the URLs, it will return undefined.
*/
static getLaunchUri = (cipher: CipherViewLike): string | undefined => {
const login = this.getLogin(cipher);
if (!login) {
return undefined;
}
return login.uris?.map((u) => toLoginUriView(u)).find((uri) => uri.canLaunch)?.launchUri;
};
/**
* @returns `true` when the `targetUri` matches for any URI on the cipher.
* Uses the existing logic from `LoginView.matchesUri` for both `CipherView` and `CipherListView`
*/
static matchesUri = (
cipher: CipherViewLike,
targetUri: string,
equivalentDomains: Set<string>,
defaultUriMatch: UriMatchStrategySetting = UriMatchStrategy.Domain,
): boolean => {
if (CipherViewLikeUtils.getType(cipher) !== CipherType.Login) {
return false;
}
if (!this.isCipherListView(cipher)) {
return cipher.login.matchesUri(targetUri, equivalentDomains, defaultUriMatch);
}
const login = this.getLogin(cipher);
if (!login?.uris?.length) {
return false;
}
const loginUriViews = login.uris
.filter((u) => !!u.uri)
.map((u) => {
const view = new LoginUriView();
view.match = u.match ?? defaultUriMatch;
view.uri = u.uri!; // above `filter` ensures `u.uri` is not null or undefined
return view;
});
return loginUriViews.some((uriView) =>
uriView.matchesUri(targetUri, equivalentDomains, defaultUriMatch),
);
};
/** @returns true when the `copyField` is populated on the given cipher. */
static hasCopyableValue = (cipher: CipherViewLike, copyField: string): boolean => {
// `CipherListView` instances do not contain the values to be copied, but rather a list of copyable fields.
// When the copy action is performed on a `CipherListView`, the full cipher will need to be decrypted.
if (this.isCipherListView(cipher)) {
let _copyField = copyField;
if (_copyField === "username" && this.getType(cipher) === CipherType.Login) {
_copyField = "usernameLogin";
} else if (_copyField === "username" && this.getType(cipher) === CipherType.Identity) {
_copyField = "usernameIdentity";
}
return cipher.copyableFields.includes(copyActionToCopyableFieldMap[_copyField]);
}
// When the full cipher is available, check the specific field
switch (copyField) {
case "username":
return !!cipher.login?.username || !!cipher.identity?.username;
case "password":
return !!cipher.login?.password;
case "totp":
return !!cipher.login?.totp;
case "cardNumber":
return !!cipher.card?.number;
case "securityCode":
return !!cipher.card?.code;
case "email":
return !!cipher.identity?.email;
case "phone":
return !!cipher.identity?.phone;
case "address":
return !!cipher.identity?.fullAddressForCopy;
case "secureNote":
return !!cipher.notes;
case "privateKey":
return !!cipher.sshKey?.privateKey;
case "publicKey":
return !!cipher.sshKey?.publicKey;
case "keyFingerprint":
return !!cipher.sshKey?.keyFingerprint;
default:
return false;
}
};
/** @returns true when the cipher has fido2 credentials */
static hasFido2Credentials = (cipher: CipherViewLike): boolean => {
const login = this.getLogin(cipher);
return !!login?.fido2Credentials?.length;
};
/**
* Returns the `decryptionFailure` property from the cipher when available.
* TODO: https://bitwarden.atlassian.net/browse/PM-22515 - alter for `CipherListView` if needed
*/
static decryptionFailure = (cipher: CipherViewLike): boolean => {
return "decryptionFailure" in cipher ? cipher.decryptionFailure : false;
};
}
/**
* Mapping between the generic copy actions and the specific fields in a `CipherViewLike`.
*/
const copyActionToCopyableFieldMap: Record<string, CopyableCipherFields> = {
usernameLogin: "LoginUsername",
password: "LoginPassword",
totp: "LoginTotp",
cardNumber: "CardNumber",
securityCode: "CardSecurityCode",
usernameIdentity: "IdentityUsername",
email: "IdentityEmail",
phone: "IdentityPhone",
address: "IdentityAddress",
secureNote: "SecureNotes",
privateKey: "SshKey",
publicKey: "SshKey",
keyFingerprint: "SshKey",
};
/** Converts a `LoginListUriView` to a `LoginUriView`. */
const toLoginUriView = (uri: LoginListUriView | LoginUriView): LoginUriView => {
if (uri instanceof LoginUriView) {
return uri;
}
const loginUriView = new LoginUriView();
if (uri.match) {
loginUriView.match = uri.match;
}
if (uri.uri) {
loginUriView.uri = uri.uri;
}
return loginUriView;
};