2022-08-30 16:19:09 +02:00
|
|
|
import { firstValueFrom } from "rxjs";
|
|
|
|
|
2022-02-22 15:39:11 +01:00
|
|
|
import { ApiService } from "../abstractions/api.service";
|
|
|
|
import { CipherService as CipherServiceAbstraction } from "../abstractions/cipher.service";
|
|
|
|
import { CryptoService } from "../abstractions/crypto.service";
|
|
|
|
import { FileUploadService } from "../abstractions/fileUpload.service";
|
|
|
|
import { I18nService } from "../abstractions/i18n.service";
|
|
|
|
import { LogService } from "../abstractions/log.service";
|
|
|
|
import { SearchService } from "../abstractions/search.service";
|
|
|
|
import { SettingsService } from "../abstractions/settings.service";
|
|
|
|
import { StateService } from "../abstractions/state.service";
|
2021-12-16 13:36:21 +01:00
|
|
|
import { CipherType } from "../enums/cipherType";
|
|
|
|
import { FieldType } from "../enums/fieldType";
|
|
|
|
import { UriMatchType } from "../enums/uriMatchType";
|
2022-02-22 15:39:11 +01:00
|
|
|
import { sequentialize } from "../misc/sequentialize";
|
|
|
|
import { Utils } from "../misc/utils";
|
2022-10-14 18:25:50 +02:00
|
|
|
import { CipherData } from "../models/data/cipher.data";
|
2022-08-30 16:19:09 +02:00
|
|
|
import { AccountSettingsSettings } from "../models/domain/account";
|
2021-12-16 13:36:21 +01:00
|
|
|
import { Attachment } from "../models/domain/attachment";
|
|
|
|
import { Card } from "../models/domain/card";
|
|
|
|
import { Cipher } from "../models/domain/cipher";
|
2022-10-14 18:25:50 +02:00
|
|
|
import Domain from "../models/domain/domain-base";
|
|
|
|
import { EncArrayBuffer } from "../models/domain/enc-array-buffer";
|
|
|
|
import { EncString } from "../models/domain/enc-string";
|
2021-12-16 13:36:21 +01:00
|
|
|
import { Field } from "../models/domain/field";
|
|
|
|
import { Identity } from "../models/domain/identity";
|
|
|
|
import { Login } from "../models/domain/login";
|
2022-10-14 18:25:50 +02:00
|
|
|
import { LoginUri } from "../models/domain/login-uri";
|
2021-12-16 13:36:21 +01:00
|
|
|
import { Password } from "../models/domain/password";
|
2022-10-14 18:25:50 +02:00
|
|
|
import { SecureNote } from "../models/domain/secure-note";
|
|
|
|
import { SortedCiphersCache } from "../models/domain/sorted-ciphers-cache";
|
|
|
|
import { SymmetricCryptoKey } from "../models/domain/symmetric-crypto-key";
|
2022-10-18 19:01:42 +02:00
|
|
|
import { AttachmentRequest } from "../models/request/attachment.request";
|
|
|
|
import { CipherBulkDeleteRequest } from "../models/request/cipher-bulk-delete.request";
|
|
|
|
import { CipherBulkMoveRequest } from "../models/request/cipher-bulk-move.request";
|
|
|
|
import { CipherBulkRestoreRequest } from "../models/request/cipher-bulk-restore.request";
|
|
|
|
import { CipherBulkShareRequest } from "../models/request/cipher-bulk-share.request";
|
|
|
|
import { CipherCollectionsRequest } from "../models/request/cipher-collections.request";
|
|
|
|
import { CipherCreateRequest } from "../models/request/cipher-create.request";
|
|
|
|
import { CipherShareRequest } from "../models/request/cipher-share.request";
|
|
|
|
import { CipherRequest } from "../models/request/cipher.request";
|
|
|
|
import { CipherResponse } from "../models/response/cipher.response";
|
|
|
|
import { ErrorResponse } from "../models/response/error.response";
|
2022-10-14 18:25:50 +02:00
|
|
|
import { AttachmentView } from "../models/view/attachment.view";
|
|
|
|
import { CipherView } from "../models/view/cipher.view";
|
|
|
|
import { FieldView } from "../models/view/field.view";
|
|
|
|
import { PasswordHistoryView } from "../models/view/password-history.view";
|
2021-12-16 13:36:21 +01:00
|
|
|
import { View } from "../models/view/view";
|
|
|
|
|
2018-12-07 21:41:43 +01:00
|
|
|
const DomainMatchBlacklist = new Map<string, Set<string>>([
|
2021-12-16 13:36:21 +01:00
|
|
|
["google.com", new Set(["script.google.com"])],
|
2018-12-07 21:41:43 +01:00
|
|
|
]);
|
|
|
|
|
2018-01-23 23:29:15 +01:00
|
|
|
export class CipherService implements CipherServiceAbstraction {
|
2021-12-16 13:36:21 +01:00
|
|
|
private sortedCiphersCache: SortedCiphersCache = new SortedCiphersCache(
|
|
|
|
this.sortCiphersByLastUsed
|
|
|
|
);
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
private cryptoService: CryptoService,
|
|
|
|
private settingsService: SettingsService,
|
|
|
|
private apiService: ApiService,
|
|
|
|
private fileUploadService: FileUploadService,
|
|
|
|
private i18nService: I18nService,
|
|
|
|
private searchService: () => SearchService,
|
|
|
|
private logService: LogService,
|
|
|
|
private stateService: StateService
|
|
|
|
) {}
|
|
|
|
|
|
|
|
async getDecryptedCipherCache(): Promise<CipherView[]> {
|
|
|
|
const decryptedCiphers = await this.stateService.getDecryptedCiphers();
|
|
|
|
return decryptedCiphers;
|
|
|
|
}
|
|
|
|
|
|
|
|
async setDecryptedCipherCache(value: CipherView[]) {
|
|
|
|
await this.stateService.setDecryptedCiphers(value);
|
|
|
|
if (this.searchService != null) {
|
|
|
|
if (value == null) {
|
|
|
|
this.searchService().clearIndex();
|
|
|
|
} else {
|
|
|
|
this.searchService().indexCiphers();
|
|
|
|
}
|
2018-08-13 15:42:52 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
async clearCache(userId?: string): Promise<void> {
|
|
|
|
await this.clearDecryptedCiphersState(userId);
|
|
|
|
}
|
|
|
|
|
|
|
|
async encrypt(
|
|
|
|
model: CipherView,
|
|
|
|
key?: SymmetricCryptoKey,
|
|
|
|
originalCipher: Cipher = null
|
|
|
|
): Promise<Cipher> {
|
|
|
|
// Adjust password history
|
|
|
|
if (model.id != null) {
|
|
|
|
if (originalCipher == null) {
|
|
|
|
originalCipher = await this.get(model.id);
|
|
|
|
}
|
|
|
|
if (originalCipher != null) {
|
|
|
|
const existingCipher = await originalCipher.decrypt();
|
|
|
|
model.passwordHistory = existingCipher.passwordHistory || [];
|
|
|
|
if (model.type === CipherType.Login && existingCipher.type === CipherType.Login) {
|
|
|
|
if (
|
|
|
|
existingCipher.login.password != null &&
|
|
|
|
existingCipher.login.password !== "" &&
|
|
|
|
existingCipher.login.password !== model.login.password
|
|
|
|
) {
|
|
|
|
const ph = new PasswordHistoryView();
|
|
|
|
ph.password = existingCipher.login.password;
|
|
|
|
ph.lastUsedDate = model.login.passwordRevisionDate = new Date();
|
|
|
|
model.passwordHistory.splice(0, 0, ph);
|
|
|
|
} else {
|
|
|
|
model.login.passwordRevisionDate = existingCipher.login.passwordRevisionDate;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (existingCipher.hasFields) {
|
|
|
|
const existingHiddenFields = existingCipher.fields.filter(
|
|
|
|
(f) =>
|
|
|
|
f.type === FieldType.Hidden &&
|
|
|
|
f.name != null &&
|
|
|
|
f.name !== "" &&
|
|
|
|
f.value != null &&
|
|
|
|
f.value !== ""
|
|
|
|
);
|
|
|
|
const hiddenFields =
|
|
|
|
model.fields == null
|
|
|
|
? []
|
|
|
|
: model.fields.filter(
|
|
|
|
(f) => f.type === FieldType.Hidden && f.name != null && f.name !== ""
|
|
|
|
);
|
|
|
|
existingHiddenFields.forEach((ef) => {
|
|
|
|
const matchedField = hiddenFields.find((f) => f.name === ef.name);
|
|
|
|
if (matchedField == null || matchedField.value !== ef.value) {
|
|
|
|
const ph = new PasswordHistoryView();
|
|
|
|
ph.password = ef.name + ": " + ef.value;
|
|
|
|
ph.lastUsedDate = new Date();
|
|
|
|
model.passwordHistory.splice(0, 0, ph);
|
2018-08-13 20:28:10 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
});
|
2018-08-13 15:42:52 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
if (model.passwordHistory != null && model.passwordHistory.length === 0) {
|
|
|
|
model.passwordHistory = null;
|
|
|
|
} else if (model.passwordHistory != null && model.passwordHistory.length > 5) {
|
|
|
|
// only save last 5 history
|
|
|
|
model.passwordHistory = model.passwordHistory.slice(0, 5);
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const cipher = new Cipher();
|
|
|
|
cipher.id = model.id;
|
|
|
|
cipher.folderId = model.folderId;
|
|
|
|
cipher.favorite = model.favorite;
|
|
|
|
cipher.organizationId = model.organizationId;
|
|
|
|
cipher.type = model.type;
|
|
|
|
cipher.collectionIds = model.collectionIds;
|
|
|
|
cipher.revisionDate = model.revisionDate;
|
|
|
|
cipher.reprompt = model.reprompt;
|
|
|
|
|
|
|
|
if (key == null && cipher.organizationId != null) {
|
|
|
|
key = await this.cryptoService.getOrgKey(cipher.organizationId);
|
|
|
|
if (key == null) {
|
|
|
|
throw new Error("Cannot encrypt cipher for organization. No key.");
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
await Promise.all([
|
|
|
|
this.encryptObjProperty(
|
|
|
|
model,
|
|
|
|
cipher,
|
|
|
|
{
|
|
|
|
name: null,
|
|
|
|
notes: null,
|
|
|
|
},
|
|
|
|
key
|
|
|
|
),
|
|
|
|
this.encryptCipherData(cipher, model, key),
|
|
|
|
this.encryptFields(model.fields, key).then((fields) => {
|
|
|
|
cipher.fields = fields;
|
|
|
|
}),
|
|
|
|
this.encryptPasswordHistories(model.passwordHistory, key).then((ph) => {
|
|
|
|
cipher.passwordHistory = ph;
|
|
|
|
}),
|
|
|
|
this.encryptAttachments(model.attachments, key).then((attachments) => {
|
|
|
|
cipher.attachments = attachments;
|
|
|
|
}),
|
|
|
|
]);
|
|
|
|
|
|
|
|
return cipher;
|
|
|
|
}
|
|
|
|
|
|
|
|
async encryptAttachments(
|
|
|
|
attachmentsModel: AttachmentView[],
|
|
|
|
key: SymmetricCryptoKey
|
|
|
|
): Promise<Attachment[]> {
|
|
|
|
if (attachmentsModel == null || attachmentsModel.length === 0) {
|
|
|
|
return null;
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const promises: Promise<any>[] = [];
|
|
|
|
const encAttachments: Attachment[] = [];
|
|
|
|
attachmentsModel.forEach(async (model) => {
|
|
|
|
const attachment = new Attachment();
|
|
|
|
attachment.id = model.id;
|
|
|
|
attachment.size = model.size;
|
|
|
|
attachment.sizeName = model.sizeName;
|
|
|
|
attachment.url = model.url;
|
|
|
|
const promise = this.encryptObjProperty(
|
|
|
|
model,
|
|
|
|
attachment,
|
|
|
|
{
|
|
|
|
fileName: null,
|
|
|
|
},
|
|
|
|
key
|
|
|
|
).then(async () => {
|
|
|
|
if (model.key != null) {
|
|
|
|
attachment.key = await this.cryptoService.encrypt(model.key.key, key);
|
2018-06-12 17:45:02 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
encAttachments.push(attachment);
|
|
|
|
});
|
|
|
|
promises.push(promise);
|
|
|
|
});
|
|
|
|
|
|
|
|
await Promise.all(promises);
|
|
|
|
return encAttachments;
|
|
|
|
}
|
|
|
|
|
|
|
|
async encryptFields(fieldsModel: FieldView[], key: SymmetricCryptoKey): Promise<Field[]> {
|
|
|
|
if (!fieldsModel || !fieldsModel.length) {
|
|
|
|
return null;
|
2018-06-12 17:45:02 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const self = this;
|
|
|
|
const encFields: Field[] = [];
|
|
|
|
await fieldsModel.reduce(async (promise, field) => {
|
|
|
|
await promise;
|
|
|
|
const encField = await self.encryptField(field, key);
|
|
|
|
encFields.push(encField);
|
|
|
|
}, Promise.resolve());
|
|
|
|
|
|
|
|
return encFields;
|
|
|
|
}
|
|
|
|
|
|
|
|
async encryptField(fieldModel: FieldView, key: SymmetricCryptoKey): Promise<Field> {
|
|
|
|
const field = new Field();
|
|
|
|
field.type = fieldModel.type;
|
|
|
|
field.linkedId = fieldModel.linkedId;
|
|
|
|
// normalize boolean type field values
|
|
|
|
if (fieldModel.type === FieldType.Boolean && fieldModel.value !== "true") {
|
|
|
|
fieldModel.value = "false";
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.encryptObjProperty(
|
|
|
|
fieldModel,
|
|
|
|
field,
|
|
|
|
{
|
|
|
|
name: null,
|
|
|
|
value: null,
|
|
|
|
},
|
|
|
|
key
|
|
|
|
);
|
|
|
|
|
|
|
|
return field;
|
|
|
|
}
|
|
|
|
|
|
|
|
async encryptPasswordHistories(
|
|
|
|
phModels: PasswordHistoryView[],
|
|
|
|
key: SymmetricCryptoKey
|
|
|
|
): Promise<Password[]> {
|
|
|
|
if (!phModels || !phModels.length) {
|
|
|
|
return null;
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const self = this;
|
|
|
|
const encPhs: Password[] = [];
|
|
|
|
await phModels.reduce(async (promise, ph) => {
|
|
|
|
await promise;
|
|
|
|
const encPh = await self.encryptPasswordHistory(ph, key);
|
|
|
|
encPhs.push(encPh);
|
|
|
|
}, Promise.resolve());
|
|
|
|
|
|
|
|
return encPhs;
|
|
|
|
}
|
|
|
|
|
|
|
|
async encryptPasswordHistory(
|
|
|
|
phModel: PasswordHistoryView,
|
|
|
|
key: SymmetricCryptoKey
|
|
|
|
): Promise<Password> {
|
|
|
|
const ph = new Password();
|
|
|
|
ph.lastUsedDate = phModel.lastUsedDate;
|
|
|
|
|
|
|
|
await this.encryptObjProperty(
|
|
|
|
phModel,
|
|
|
|
ph,
|
|
|
|
{
|
|
|
|
password: null,
|
|
|
|
},
|
|
|
|
key
|
|
|
|
);
|
|
|
|
|
|
|
|
return ph;
|
|
|
|
}
|
|
|
|
|
|
|
|
async get(id: string): Promise<Cipher> {
|
|
|
|
const ciphers = await this.stateService.getEncryptedCiphers();
|
2022-02-22 15:39:11 +01:00
|
|
|
// eslint-disable-next-line
|
2021-12-16 13:36:21 +01:00
|
|
|
if (ciphers == null || !ciphers.hasOwnProperty(id)) {
|
|
|
|
return null;
|
2018-07-27 22:44:20 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const localData = await this.stateService.getLocalData();
|
2022-04-16 17:00:48 +02:00
|
|
|
return new Cipher(ciphers[id], localData ? localData[id] : null);
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
async getAll(): Promise<Cipher[]> {
|
|
|
|
const localData = await this.stateService.getLocalData();
|
|
|
|
const ciphers = await this.stateService.getEncryptedCiphers();
|
|
|
|
const response: Cipher[] = [];
|
|
|
|
for (const id in ciphers) {
|
2022-02-22 15:39:11 +01:00
|
|
|
// eslint-disable-next-line
|
2021-12-16 13:36:21 +01:00
|
|
|
if (ciphers.hasOwnProperty(id)) {
|
2022-04-16 17:00:48 +02:00
|
|
|
response.push(new Cipher(ciphers[id], localData ? localData[id] : null));
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
@sequentialize(() => "getAllDecrypted")
|
|
|
|
async getAllDecrypted(): Promise<CipherView[]> {
|
|
|
|
const userId = await this.stateService.getUserId();
|
|
|
|
if ((await this.getDecryptedCipherCache()) != null) {
|
|
|
|
if (
|
|
|
|
this.searchService != null &&
|
|
|
|
(this.searchService().indexedEntityId ?? userId) !== userId
|
|
|
|
) {
|
|
|
|
await this.searchService().indexCiphers(userId, await this.getDecryptedCipherCache());
|
|
|
|
}
|
|
|
|
return await this.getDecryptedCipherCache();
|
2018-07-27 22:44:20 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const decCiphers: CipherView[] = [];
|
|
|
|
const hasKey = await this.cryptoService.hasKey();
|
|
|
|
if (!hasKey) {
|
|
|
|
throw new Error("No key.");
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2022-08-10 03:30:26 +02:00
|
|
|
const promises: Promise<number>[] = [];
|
2021-12-16 13:36:21 +01:00
|
|
|
const ciphers = await this.getAll();
|
|
|
|
ciphers.forEach(async (cipher) => {
|
|
|
|
promises.push(cipher.decrypt().then((c) => decCiphers.push(c)));
|
|
|
|
});
|
|
|
|
|
|
|
|
await Promise.all(promises);
|
|
|
|
decCiphers.sort(this.getLocaleSortingFunction());
|
2022-01-20 22:25:04 +01:00
|
|
|
await this.setDecryptedCipherCache(decCiphers);
|
2021-12-16 13:36:21 +01:00
|
|
|
return decCiphers;
|
|
|
|
}
|
|
|
|
|
2022-02-22 15:39:11 +01:00
|
|
|
async getAllDecryptedForGrouping(groupingId: string, folder = true): Promise<CipherView[]> {
|
2021-12-16 13:36:21 +01:00
|
|
|
const ciphers = await this.getAllDecrypted();
|
|
|
|
|
|
|
|
return ciphers.filter((cipher) => {
|
|
|
|
if (cipher.isDeleted) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if (folder && cipher.folderId === groupingId) {
|
|
|
|
return true;
|
|
|
|
} else if (
|
|
|
|
!folder &&
|
|
|
|
cipher.collectionIds != null &&
|
|
|
|
cipher.collectionIds.indexOf(groupingId) > -1
|
|
|
|
) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async getAllDecryptedForUrl(
|
|
|
|
url: string,
|
|
|
|
includeOtherTypes?: CipherType[],
|
|
|
|
defaultMatch: UriMatchType = null
|
|
|
|
): Promise<CipherView[]> {
|
|
|
|
if (url == null && includeOtherTypes == null) {
|
|
|
|
return Promise.resolve([]);
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const domain = Utils.getDomain(url);
|
|
|
|
const eqDomainsPromise =
|
|
|
|
domain == null
|
|
|
|
? Promise.resolve([])
|
2022-08-30 16:19:09 +02:00
|
|
|
: firstValueFrom(this.settingsService.settings$).then(
|
|
|
|
(settings: AccountSettingsSettings) => {
|
|
|
|
let matches: any[] = [];
|
2022-09-22 14:51:14 +02:00
|
|
|
settings.equivalentDomains?.forEach((eqDomain: any) => {
|
2022-08-30 16:19:09 +02:00
|
|
|
if (eqDomain.length && eqDomain.indexOf(domain) >= 0) {
|
|
|
|
matches = matches.concat(eqDomain);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!matches.length) {
|
|
|
|
matches.push(domain);
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
2022-08-30 16:19:09 +02:00
|
|
|
return matches;
|
2021-04-22 21:53:45 +02:00
|
|
|
}
|
2022-08-30 16:19:09 +02:00
|
|
|
);
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const result = await Promise.all([eqDomainsPromise, this.getAllDecrypted()]);
|
|
|
|
const matchingDomains = result[0];
|
|
|
|
const ciphers = result[1];
|
2018-07-23 20:24:27 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
if (defaultMatch == null) {
|
|
|
|
defaultMatch = await this.stateService.getDefaultUriMatch();
|
|
|
|
if (defaultMatch == null) {
|
|
|
|
defaultMatch = UriMatchType.Domain;
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
return ciphers.filter((cipher) => {
|
|
|
|
if (cipher.deletedDate != null) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if (includeOtherTypes != null && includeOtherTypes.indexOf(cipher.type) > -1) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (url != null && cipher.type === CipherType.Login && cipher.login.uris != null) {
|
|
|
|
for (let i = 0; i < cipher.login.uris.length; i++) {
|
|
|
|
const u = cipher.login.uris[i];
|
|
|
|
if (u.uri == null) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
const match = u.match == null ? defaultMatch : u.match;
|
|
|
|
switch (match) {
|
|
|
|
case UriMatchType.Domain:
|
|
|
|
if (domain != null && u.domain != null && matchingDomains.indexOf(u.domain) > -1) {
|
|
|
|
if (DomainMatchBlacklist.has(u.domain)) {
|
|
|
|
const domainUrlHost = Utils.getHost(url);
|
|
|
|
if (!DomainMatchBlacklist.get(u.domain).has(domainUrlHost)) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
break;
|
2022-02-22 15:39:11 +01:00
|
|
|
case UriMatchType.Host: {
|
2021-12-16 13:36:21 +01:00
|
|
|
const urlHost = Utils.getHost(url);
|
|
|
|
if (urlHost != null && urlHost === Utils.getHost(u.uri)) {
|
2018-01-24 17:33:15 +01:00
|
|
|
return true;
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
break;
|
2022-02-22 15:39:11 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
case UriMatchType.Exact:
|
|
|
|
if (url === u.uri) {
|
2018-01-24 17:33:15 +01:00
|
|
|
return true;
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
case UriMatchType.StartsWith:
|
|
|
|
if (url.startsWith(u.uri)) {
|
2018-03-02 18:03:03 +01:00
|
|
|
return true;
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
break;
|
|
|
|
case UriMatchType.RegularExpression:
|
|
|
|
try {
|
|
|
|
const regex = new RegExp(u.uri, "i");
|
|
|
|
if (regex.test(url)) {
|
|
|
|
return true;
|
2018-03-02 18:03:03 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
} catch (e) {
|
|
|
|
this.logService.error(e);
|
|
|
|
}
|
|
|
|
break;
|
|
|
|
case UriMatchType.Never:
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
2018-12-14 19:55:44 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async getAllFromApiForOrganization(organizationId: string): Promise<CipherView[]> {
|
|
|
|
const ciphers = await this.apiService.getCiphersOrganization(organizationId);
|
|
|
|
if (ciphers != null && ciphers.data != null && ciphers.data.length) {
|
|
|
|
const decCiphers: CipherView[] = [];
|
|
|
|
const promises: any[] = [];
|
|
|
|
ciphers.data.forEach((r) => {
|
|
|
|
const data = new CipherData(r);
|
|
|
|
const cipher = new Cipher(data);
|
|
|
|
promises.push(cipher.decrypt().then((c) => decCiphers.push(c)));
|
|
|
|
});
|
|
|
|
await Promise.all(promises);
|
|
|
|
decCiphers.sort(this.getLocaleSortingFunction());
|
|
|
|
return decCiphers;
|
|
|
|
} else {
|
|
|
|
return [];
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
2022-02-22 15:39:11 +01:00
|
|
|
async getLastUsedForUrl(url: string, autofillOnPageLoad = false): Promise<CipherView> {
|
2021-12-16 13:36:21 +01:00
|
|
|
return this.getCipherForUrl(url, true, false, autofillOnPageLoad);
|
|
|
|
}
|
|
|
|
|
2022-02-22 15:39:11 +01:00
|
|
|
async getLastLaunchedForUrl(url: string, autofillOnPageLoad = false): Promise<CipherView> {
|
2021-12-16 13:36:21 +01:00
|
|
|
return this.getCipherForUrl(url, false, true, autofillOnPageLoad);
|
|
|
|
}
|
|
|
|
|
|
|
|
async getNextCipherForUrl(url: string): Promise<CipherView> {
|
|
|
|
return this.getCipherForUrl(url, false, false, false);
|
|
|
|
}
|
|
|
|
|
|
|
|
updateLastUsedIndexForUrl(url: string) {
|
|
|
|
this.sortedCiphersCache.updateLastUsedIndex(url);
|
|
|
|
}
|
|
|
|
|
|
|
|
async updateLastUsedDate(id: string): Promise<void> {
|
|
|
|
let ciphersLocalData = await this.stateService.getLocalData();
|
|
|
|
if (!ciphersLocalData) {
|
|
|
|
ciphersLocalData = {};
|
2020-09-23 18:41:25 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
if (ciphersLocalData[id]) {
|
|
|
|
ciphersLocalData[id].lastUsedDate = new Date().getTime();
|
|
|
|
} else {
|
|
|
|
ciphersLocalData[id] = {
|
|
|
|
lastUsedDate: new Date().getTime(),
|
|
|
|
};
|
2020-08-12 21:59:59 +02:00
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.stateService.setLocalData(ciphersLocalData);
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const decryptedCipherCache = await this.stateService.getDecryptedCiphers();
|
|
|
|
if (!decryptedCipherCache) {
|
|
|
|
return;
|
2020-10-09 13:30:55 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
for (let i = 0; i < decryptedCipherCache.length; i++) {
|
|
|
|
const cached = decryptedCipherCache[i];
|
|
|
|
if (cached.id === id) {
|
|
|
|
cached.localData = ciphersLocalData[id];
|
|
|
|
break;
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.stateService.setDecryptedCiphers(decryptedCipherCache);
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async updateLastLaunchedDate(id: string): Promise<void> {
|
|
|
|
let ciphersLocalData = await this.stateService.getLocalData();
|
|
|
|
if (!ciphersLocalData) {
|
|
|
|
ciphersLocalData = {};
|
2020-09-23 18:41:25 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
if (ciphersLocalData[id]) {
|
|
|
|
ciphersLocalData[id].lastLaunched = new Date().getTime();
|
|
|
|
} else {
|
|
|
|
ciphersLocalData[id] = {
|
|
|
|
lastUsedDate: new Date().getTime(),
|
|
|
|
};
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.stateService.setLocalData(ciphersLocalData);
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const decryptedCipherCache = await this.stateService.getDecryptedCiphers();
|
|
|
|
if (!decryptedCipherCache) {
|
|
|
|
return;
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
for (let i = 0; i < decryptedCipherCache.length; i++) {
|
|
|
|
const cached = decryptedCipherCache[i];
|
|
|
|
if (cached.id === id) {
|
|
|
|
cached.localData = ciphersLocalData[id];
|
|
|
|
break;
|
|
|
|
}
|
2018-06-13 06:02:15 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.stateService.setDecryptedCiphers(decryptedCipherCache);
|
|
|
|
}
|
2018-06-13 06:02:15 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async saveNeverDomain(domain: string): Promise<void> {
|
|
|
|
if (domain == null) {
|
|
|
|
return;
|
2018-06-12 17:45:02 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
let domains = await this.stateService.getNeverDomains();
|
|
|
|
if (!domains) {
|
|
|
|
domains = {};
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
domains[domain] = null;
|
|
|
|
await this.stateService.setNeverDomains(domains);
|
|
|
|
}
|
|
|
|
|
|
|
|
async saveWithServer(cipher: Cipher): Promise<any> {
|
|
|
|
let response: CipherResponse;
|
|
|
|
if (cipher.id == null) {
|
|
|
|
if (cipher.collectionIds != null) {
|
|
|
|
const request = new CipherCreateRequest(cipher);
|
|
|
|
response = await this.apiService.postCipherCreate(request);
|
|
|
|
} else {
|
|
|
|
const request = new CipherRequest(cipher);
|
|
|
|
response = await this.apiService.postCipher(request);
|
|
|
|
}
|
|
|
|
cipher.id = response.id;
|
|
|
|
} else {
|
|
|
|
const request = new CipherRequest(cipher);
|
|
|
|
response = await this.apiService.putCipher(cipher.id, request);
|
2021-03-26 22:57:07 +01:00
|
|
|
}
|
|
|
|
|
2022-04-20 15:59:51 +02:00
|
|
|
const data = new CipherData(response, cipher.collectionIds);
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.upsert(data);
|
|
|
|
}
|
|
|
|
|
|
|
|
async shareWithServer(
|
|
|
|
cipher: CipherView,
|
|
|
|
organizationId: string,
|
|
|
|
collectionIds: string[]
|
|
|
|
): Promise<any> {
|
|
|
|
const attachmentPromises: Promise<any>[] = [];
|
|
|
|
if (cipher.attachments != null) {
|
|
|
|
cipher.attachments.forEach((attachment) => {
|
|
|
|
if (attachment.key == null) {
|
|
|
|
attachmentPromises.push(
|
|
|
|
this.shareAttachmentWithServer(attachment, cipher.id, organizationId)
|
|
|
|
);
|
2018-05-17 21:35:02 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
});
|
|
|
|
}
|
|
|
|
await Promise.all(attachmentPromises);
|
|
|
|
|
|
|
|
cipher.organizationId = organizationId;
|
|
|
|
cipher.collectionIds = collectionIds;
|
|
|
|
const encCipher = await this.encrypt(cipher);
|
|
|
|
const request = new CipherShareRequest(encCipher);
|
|
|
|
const response = await this.apiService.putShareCipher(cipher.id, request);
|
2022-04-20 15:59:51 +02:00
|
|
|
const data = new CipherData(response, collectionIds);
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.upsert(data);
|
|
|
|
}
|
|
|
|
|
|
|
|
async shareManyWithServer(
|
|
|
|
ciphers: CipherView[],
|
|
|
|
organizationId: string,
|
|
|
|
collectionIds: string[]
|
|
|
|
): Promise<any> {
|
|
|
|
const promises: Promise<any>[] = [];
|
|
|
|
const encCiphers: Cipher[] = [];
|
|
|
|
for (const cipher of ciphers) {
|
|
|
|
cipher.organizationId = organizationId;
|
|
|
|
cipher.collectionIds = collectionIds;
|
|
|
|
promises.push(
|
|
|
|
this.encrypt(cipher).then((c) => {
|
|
|
|
encCiphers.push(c);
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
await Promise.all(promises);
|
|
|
|
const request = new CipherBulkShareRequest(encCiphers, collectionIds);
|
2022-03-02 14:11:34 +01:00
|
|
|
try {
|
|
|
|
await this.apiService.putShareCiphers(request);
|
|
|
|
} catch (e) {
|
|
|
|
for (const cipher of ciphers) {
|
|
|
|
cipher.organizationId = null;
|
|
|
|
cipher.collectionIds = null;
|
|
|
|
}
|
|
|
|
throw e;
|
|
|
|
}
|
2022-04-20 15:59:51 +02:00
|
|
|
await this.upsert(encCiphers.map((c) => c.toCipherData()));
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
saveAttachmentWithServer(cipher: Cipher, unencryptedFile: any, admin = false): Promise<Cipher> {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
const reader = new FileReader();
|
|
|
|
reader.readAsArrayBuffer(unencryptedFile);
|
|
|
|
reader.onload = async (evt: any) => {
|
2018-05-17 21:35:02 +02:00
|
|
|
try {
|
2021-12-16 13:36:21 +01:00
|
|
|
const cData = await this.saveAttachmentRawWithServer(
|
|
|
|
cipher,
|
|
|
|
unencryptedFile.name,
|
|
|
|
evt.target.result,
|
|
|
|
admin
|
|
|
|
);
|
|
|
|
resolve(cData);
|
2018-05-17 21:35:02 +02:00
|
|
|
} catch (e) {
|
2021-12-16 13:36:21 +01:00
|
|
|
reject(e);
|
2018-05-17 21:35:02 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
};
|
2022-02-22 15:39:11 +01:00
|
|
|
reader.onerror = () => {
|
2021-12-16 13:36:21 +01:00
|
|
|
reject("Error reading file.");
|
|
|
|
};
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async saveAttachmentRawWithServer(
|
|
|
|
cipher: Cipher,
|
|
|
|
filename: string,
|
|
|
|
data: ArrayBuffer,
|
|
|
|
admin = false
|
|
|
|
): Promise<Cipher> {
|
|
|
|
const key = await this.cryptoService.getOrgKey(cipher.organizationId);
|
|
|
|
const encFileName = await this.cryptoService.encrypt(filename, key);
|
|
|
|
|
|
|
|
const dataEncKey = await this.cryptoService.makeEncKey(key);
|
|
|
|
const encData = await this.cryptoService.encryptToBytes(data, dataEncKey[0]);
|
|
|
|
|
|
|
|
const request: AttachmentRequest = {
|
|
|
|
key: dataEncKey[1].encryptedString,
|
|
|
|
fileName: encFileName.encryptedString,
|
|
|
|
fileSize: encData.buffer.byteLength,
|
|
|
|
adminRequest: admin,
|
|
|
|
};
|
|
|
|
|
|
|
|
let response: CipherResponse;
|
|
|
|
try {
|
|
|
|
const uploadDataResponse = await this.apiService.postCipherAttachment(cipher.id, request);
|
|
|
|
response = admin ? uploadDataResponse.cipherMiniResponse : uploadDataResponse.cipherResponse;
|
|
|
|
await this.fileUploadService.uploadCipherAttachment(
|
|
|
|
admin,
|
|
|
|
uploadDataResponse,
|
|
|
|
encFileName,
|
|
|
|
encData
|
|
|
|
);
|
|
|
|
} catch (e) {
|
|
|
|
if (
|
|
|
|
(e instanceof ErrorResponse && (e as ErrorResponse).statusCode === 404) ||
|
|
|
|
(e as ErrorResponse).statusCode === 405
|
|
|
|
) {
|
|
|
|
response = await this.legacyServerAttachmentFileUpload(
|
|
|
|
admin,
|
|
|
|
cipher.id,
|
|
|
|
encFileName,
|
|
|
|
encData,
|
|
|
|
dataEncKey[1]
|
|
|
|
);
|
|
|
|
} else if (e instanceof ErrorResponse) {
|
|
|
|
throw new Error((e as ErrorResponse).getSingleMessage());
|
|
|
|
} else {
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
}
|
2018-05-17 21:35:02 +02:00
|
|
|
|
2022-04-20 15:59:51 +02:00
|
|
|
const cData = new CipherData(response, cipher.collectionIds);
|
2021-12-16 13:36:21 +01:00
|
|
|
if (!admin) {
|
|
|
|
await this.upsert(cData);
|
|
|
|
}
|
|
|
|
return new Cipher(cData);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @deprecated Mar 25 2021: This method has been deprecated in favor of direct uploads.
|
|
|
|
* This method still exists for backward compatibility with old server versions.
|
|
|
|
*/
|
|
|
|
async legacyServerAttachmentFileUpload(
|
|
|
|
admin: boolean,
|
|
|
|
cipherId: string,
|
|
|
|
encFileName: EncString,
|
|
|
|
encData: EncArrayBuffer,
|
|
|
|
key: EncString
|
|
|
|
) {
|
|
|
|
const fd = new FormData();
|
|
|
|
try {
|
|
|
|
const blob = new Blob([encData.buffer], { type: "application/octet-stream" });
|
|
|
|
fd.append("key", key.encryptedString);
|
|
|
|
fd.append("data", blob, encFileName.encryptedString);
|
|
|
|
} catch (e) {
|
|
|
|
if (Utils.isNode && !Utils.isBrowser) {
|
|
|
|
fd.append("key", key.encryptedString);
|
|
|
|
fd.append(
|
|
|
|
"data",
|
|
|
|
Buffer.from(encData.buffer) as any,
|
|
|
|
{
|
|
|
|
filepath: encFileName.encryptedString,
|
|
|
|
contentType: "application/octet-stream",
|
|
|
|
} as any
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
throw e;
|
|
|
|
}
|
2018-05-17 21:35:02 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
let response: CipherResponse;
|
|
|
|
try {
|
|
|
|
if (admin) {
|
|
|
|
response = await this.apiService.postCipherAttachmentAdminLegacy(cipherId, fd);
|
|
|
|
} else {
|
|
|
|
response = await this.apiService.postCipherAttachmentLegacy(cipherId, fd);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
throw new Error((e as ErrorResponse).getSingleMessage());
|
2018-06-12 19:07:06 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
return response;
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async saveCollectionsWithServer(cipher: Cipher): Promise<any> {
|
|
|
|
const request = new CipherCollectionsRequest(cipher.collectionIds);
|
|
|
|
await this.apiService.putCipherCollections(cipher.id, request);
|
2022-04-20 15:59:51 +02:00
|
|
|
const data = cipher.toCipherData();
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.upsert(data);
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async upsert(cipher: CipherData | CipherData[]): Promise<any> {
|
|
|
|
let ciphers = await this.stateService.getEncryptedCiphers();
|
|
|
|
if (ciphers == null) {
|
|
|
|
ciphers = {};
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
if (cipher instanceof CipherData) {
|
|
|
|
const c = cipher as CipherData;
|
|
|
|
ciphers[c.id] = c;
|
|
|
|
} else {
|
|
|
|
(cipher as CipherData[]).forEach((c) => {
|
|
|
|
ciphers[c.id] = c;
|
|
|
|
});
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.replace(ciphers);
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async replace(ciphers: { [id: string]: CipherData }): Promise<any> {
|
|
|
|
await this.clearDecryptedCiphersState();
|
|
|
|
await this.stateService.setEncryptedCiphers(ciphers);
|
|
|
|
}
|
2018-06-12 23:12:27 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async clear(userId?: string): Promise<any> {
|
|
|
|
await this.clearEncryptedCiphersState(userId);
|
|
|
|
await this.clearCache(userId);
|
|
|
|
}
|
2018-06-12 23:12:27 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async moveManyWithServer(ids: string[], folderId: string): Promise<any> {
|
|
|
|
await this.apiService.putMoveCiphers(new CipherBulkMoveRequest(ids, folderId));
|
2018-06-12 23:12:27 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
let ciphers = await this.stateService.getEncryptedCiphers();
|
|
|
|
if (ciphers == null) {
|
|
|
|
ciphers = {};
|
2018-06-12 23:12:27 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
ids.forEach((id) => {
|
2022-02-22 15:39:11 +01:00
|
|
|
// eslint-disable-next-line
|
2021-12-16 13:36:21 +01:00
|
|
|
if (ciphers.hasOwnProperty(id)) {
|
|
|
|
ciphers[id].folderId = folderId;
|
|
|
|
}
|
|
|
|
});
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.clearCache();
|
|
|
|
await this.stateService.setEncryptedCiphers(ciphers);
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async delete(id: string | string[]): Promise<any> {
|
|
|
|
const ciphers = await this.stateService.getEncryptedCiphers();
|
|
|
|
if (ciphers == null) {
|
|
|
|
return;
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
if (typeof id === "string") {
|
|
|
|
if (ciphers[id] == null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
delete ciphers[id];
|
|
|
|
} else {
|
|
|
|
(id as string[]).forEach((i) => {
|
|
|
|
delete ciphers[i];
|
|
|
|
});
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.clearCache();
|
|
|
|
await this.stateService.setEncryptedCiphers(ciphers);
|
|
|
|
}
|
2018-06-12 23:12:27 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async deleteWithServer(id: string): Promise<any> {
|
|
|
|
await this.apiService.deleteCipher(id);
|
|
|
|
await this.delete(id);
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async deleteManyWithServer(ids: string[]): Promise<any> {
|
|
|
|
await this.apiService.deleteManyCiphers(new CipherBulkDeleteRequest(ids));
|
|
|
|
await this.delete(ids);
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async deleteAttachment(id: string, attachmentId: string): Promise<void> {
|
|
|
|
const ciphers = await this.stateService.getEncryptedCiphers();
|
2018-01-10 05:01:16 +01:00
|
|
|
|
2022-02-22 15:39:11 +01:00
|
|
|
// eslint-disable-next-line
|
2021-12-16 13:36:21 +01:00
|
|
|
if (ciphers == null || !ciphers.hasOwnProperty(id) || ciphers[id].attachments == null) {
|
|
|
|
return;
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
for (let i = 0; i < ciphers[id].attachments.length; i++) {
|
|
|
|
if (ciphers[id].attachments[i].id === attachmentId) {
|
|
|
|
ciphers[id].attachments.splice(i, 1);
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.clearCache();
|
|
|
|
await this.stateService.setEncryptedCiphers(ciphers);
|
|
|
|
}
|
2018-01-27 04:54:02 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async deleteAttachmentWithServer(id: string, attachmentId: string): Promise<void> {
|
|
|
|
try {
|
|
|
|
await this.apiService.deleteCipherAttachment(id, attachmentId);
|
|
|
|
} catch (e) {
|
|
|
|
return Promise.reject((e as ErrorResponse).getSingleMessage());
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.deleteAttachment(id, attachmentId);
|
|
|
|
}
|
|
|
|
|
|
|
|
sortCiphersByLastUsed(a: CipherView, b: CipherView): number {
|
|
|
|
const aLastUsed =
|
|
|
|
a.localData && a.localData.lastUsedDate ? (a.localData.lastUsedDate as number) : null;
|
|
|
|
const bLastUsed =
|
|
|
|
b.localData && b.localData.lastUsedDate ? (b.localData.lastUsedDate as number) : null;
|
|
|
|
|
|
|
|
const bothNotNull = aLastUsed != null && bLastUsed != null;
|
|
|
|
if (bothNotNull && aLastUsed < bLastUsed) {
|
|
|
|
return 1;
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
if (aLastUsed != null && bLastUsed == null) {
|
|
|
|
return -1;
|
2018-01-27 04:16:35 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
if (bothNotNull && aLastUsed > bLastUsed) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
if (bLastUsed != null && aLastUsed == null) {
|
|
|
|
return 1;
|
|
|
|
}
|
2020-04-03 22:32:15 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
return 0;
|
|
|
|
}
|
2020-04-03 22:32:15 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
sortCiphersByLastUsedThenName(a: CipherView, b: CipherView): number {
|
|
|
|
const result = this.sortCiphersByLastUsed(a, b);
|
|
|
|
if (result !== 0) {
|
|
|
|
return result;
|
2020-04-03 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
return this.getLocaleSortingFunction()(a, b);
|
|
|
|
}
|
|
|
|
|
|
|
|
getLocaleSortingFunction(): (a: CipherView, b: CipherView) => number {
|
|
|
|
return (a, b) => {
|
|
|
|
let aName = a.name;
|
|
|
|
let bName = b.name;
|
|
|
|
|
|
|
|
if (aName == null && bName != null) {
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
if (aName != null && bName == null) {
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
if (aName == null && bName == null) {
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
const result = this.i18nService.collator
|
|
|
|
? this.i18nService.collator.compare(aName, bName)
|
|
|
|
: aName.localeCompare(bName);
|
|
|
|
|
|
|
|
if (result !== 0 || a.type !== CipherType.Login || b.type !== CipherType.Login) {
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (a.login.username != null) {
|
|
|
|
aName += a.login.username;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (b.login.username != null) {
|
|
|
|
bName += b.login.username;
|
|
|
|
}
|
|
|
|
|
|
|
|
return this.i18nService.collator
|
|
|
|
? this.i18nService.collator.compare(aName, bName)
|
|
|
|
: aName.localeCompare(bName);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
async softDelete(id: string | string[]): Promise<any> {
|
|
|
|
const ciphers = await this.stateService.getEncryptedCiphers();
|
|
|
|
if (ciphers == null) {
|
|
|
|
return;
|
2020-04-03 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const setDeletedDate = (cipherId: string) => {
|
|
|
|
if (ciphers[cipherId] == null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
ciphers[cipherId].deletedDate = new Date().toISOString();
|
|
|
|
};
|
|
|
|
|
|
|
|
if (typeof id === "string") {
|
|
|
|
setDeletedDate(id);
|
|
|
|
} else {
|
|
|
|
(id as string[]).forEach(setDeletedDate);
|
2020-04-03 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.clearCache();
|
|
|
|
await this.stateService.setEncryptedCiphers(ciphers);
|
|
|
|
}
|
|
|
|
|
|
|
|
async softDeleteWithServer(id: string): Promise<any> {
|
|
|
|
await this.apiService.putDeleteCipher(id);
|
|
|
|
await this.softDelete(id);
|
|
|
|
}
|
|
|
|
|
|
|
|
async softDeleteManyWithServer(ids: string[]): Promise<any> {
|
|
|
|
await this.apiService.putDeleteManyCiphers(new CipherBulkDeleteRequest(ids));
|
|
|
|
await this.softDelete(ids);
|
|
|
|
}
|
|
|
|
|
|
|
|
async restore(
|
|
|
|
cipher: { id: string; revisionDate: string } | { id: string; revisionDate: string }[]
|
|
|
|
) {
|
|
|
|
const ciphers = await this.stateService.getEncryptedCiphers();
|
|
|
|
if (ciphers == null) {
|
|
|
|
return;
|
|
|
|
}
|
2020-04-03 22:32:15 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
const clearDeletedDate = (c: { id: string; revisionDate: string }) => {
|
|
|
|
if (ciphers[c.id] == null) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
ciphers[c.id].deletedDate = null;
|
|
|
|
ciphers[c.id].revisionDate = c.revisionDate;
|
|
|
|
};
|
|
|
|
|
2022-03-15 02:12:31 +01:00
|
|
|
if (cipher.constructor.name === Array.name) {
|
2021-12-16 13:36:21 +01:00
|
|
|
(cipher as { id: string; revisionDate: string }[]).forEach(clearDeletedDate);
|
|
|
|
} else {
|
|
|
|
clearDeletedDate(cipher as { id: string; revisionDate: string });
|
|
|
|
}
|
2020-04-03 22:32:15 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.clearCache();
|
|
|
|
await this.stateService.setEncryptedCiphers(ciphers);
|
|
|
|
}
|
2021-01-08 15:53:41 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async restoreWithServer(id: string): Promise<any> {
|
|
|
|
const response = await this.apiService.putRestoreCipher(id);
|
|
|
|
await this.restore({ id: id, revisionDate: response.revisionDate });
|
|
|
|
}
|
2020-04-03 22:32:15 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
async restoreManyWithServer(ids: string[]): Promise<any> {
|
|
|
|
const response = await this.apiService.putRestoreManyCiphers(new CipherBulkRestoreRequest(ids));
|
|
|
|
const restores: { id: string; revisionDate: string }[] = [];
|
|
|
|
for (const cipher of response.data) {
|
|
|
|
restores.push({ id: cipher.id, revisionDate: cipher.revisionDate });
|
2020-04-03 22:32:15 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
await this.restore(restores);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Helpers
|
|
|
|
|
|
|
|
private async shareAttachmentWithServer(
|
|
|
|
attachmentView: AttachmentView,
|
|
|
|
cipherId: string,
|
|
|
|
organizationId: string
|
|
|
|
): Promise<any> {
|
|
|
|
const attachmentResponse = await this.apiService.nativeFetch(
|
|
|
|
new Request(attachmentView.url, { cache: "no-store" })
|
|
|
|
);
|
|
|
|
if (attachmentResponse.status !== 200) {
|
|
|
|
throw Error("Failed to download attachment: " + attachmentResponse.status.toString());
|
2020-04-03 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
2022-07-26 03:40:32 +02:00
|
|
|
const encBuf = await EncArrayBuffer.fromResponse(attachmentResponse);
|
|
|
|
const decBuf = await this.cryptoService.decryptFromBytes(encBuf, null);
|
2021-12-16 13:36:21 +01:00
|
|
|
const key = await this.cryptoService.getOrgKey(organizationId);
|
|
|
|
const encFileName = await this.cryptoService.encrypt(attachmentView.fileName, key);
|
|
|
|
|
|
|
|
const dataEncKey = await this.cryptoService.makeEncKey(key);
|
|
|
|
const encData = await this.cryptoService.encryptToBytes(decBuf, dataEncKey[0]);
|
|
|
|
|
|
|
|
const fd = new FormData();
|
|
|
|
try {
|
|
|
|
const blob = new Blob([encData.buffer], { type: "application/octet-stream" });
|
|
|
|
fd.append("key", dataEncKey[1].encryptedString);
|
|
|
|
fd.append("data", blob, encFileName.encryptedString);
|
|
|
|
} catch (e) {
|
|
|
|
if (Utils.isNode && !Utils.isBrowser) {
|
|
|
|
fd.append("key", dataEncKey[1].encryptedString);
|
|
|
|
fd.append(
|
|
|
|
"data",
|
|
|
|
Buffer.from(encData.buffer) as any,
|
|
|
|
{
|
|
|
|
filepath: encFileName.encryptedString,
|
|
|
|
contentType: "application/octet-stream",
|
|
|
|
} as any
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
throw e;
|
|
|
|
}
|
2020-04-03 22:32:15 +02:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
try {
|
|
|
|
await this.apiService.postShareCipherAttachment(
|
|
|
|
cipherId,
|
|
|
|
attachmentView.id,
|
|
|
|
fd,
|
|
|
|
organizationId
|
|
|
|
);
|
|
|
|
} catch (e) {
|
|
|
|
throw new Error((e as ErrorResponse).getSingleMessage());
|
2018-10-24 04:10:08 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private async encryptObjProperty<V extends View, D extends Domain>(
|
|
|
|
model: V,
|
|
|
|
obj: D,
|
|
|
|
map: any,
|
|
|
|
key: SymmetricCryptoKey
|
|
|
|
): Promise<void> {
|
|
|
|
const promises = [];
|
|
|
|
const self = this;
|
|
|
|
|
|
|
|
for (const prop in map) {
|
2022-02-22 15:39:11 +01:00
|
|
|
// eslint-disable-next-line
|
2021-12-16 13:36:21 +01:00
|
|
|
if (!map.hasOwnProperty(prop)) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
(function (theProp, theObj) {
|
|
|
|
const p = Promise.resolve()
|
|
|
|
.then(() => {
|
|
|
|
const modelProp = (model as any)[map[theProp] || theProp];
|
|
|
|
if (modelProp && modelProp !== "") {
|
|
|
|
return self.cryptoService.encrypt(modelProp, key);
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
return null;
|
|
|
|
})
|
|
|
|
.then((val: EncString) => {
|
|
|
|
(theObj as any)[theProp] = val;
|
|
|
|
});
|
|
|
|
promises.push(p);
|
|
|
|
})(prop, obj);
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
await Promise.all(promises);
|
|
|
|
}
|
|
|
|
|
|
|
|
private async encryptCipherData(cipher: Cipher, model: CipherView, key: SymmetricCryptoKey) {
|
|
|
|
switch (cipher.type) {
|
|
|
|
case CipherType.Login:
|
|
|
|
cipher.login = new Login();
|
|
|
|
cipher.login.passwordRevisionDate = model.login.passwordRevisionDate;
|
|
|
|
cipher.login.autofillOnPageLoad = model.login.autofillOnPageLoad;
|
|
|
|
await this.encryptObjProperty(
|
|
|
|
model.login,
|
|
|
|
cipher.login,
|
|
|
|
{
|
|
|
|
username: null,
|
|
|
|
password: null,
|
|
|
|
totp: null,
|
|
|
|
},
|
|
|
|
key
|
|
|
|
);
|
|
|
|
|
|
|
|
if (model.login.uris != null) {
|
|
|
|
cipher.login.uris = [];
|
|
|
|
for (let i = 0; i < model.login.uris.length; i++) {
|
|
|
|
const loginUri = new LoginUri();
|
|
|
|
loginUri.match = model.login.uris[i].match;
|
|
|
|
await this.encryptObjProperty(
|
|
|
|
model.login.uris[i],
|
|
|
|
loginUri,
|
|
|
|
{
|
|
|
|
uri: null,
|
|
|
|
},
|
|
|
|
key
|
|
|
|
);
|
|
|
|
cipher.login.uris.push(loginUri);
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
return;
|
|
|
|
case CipherType.SecureNote:
|
|
|
|
cipher.secureNote = new SecureNote();
|
|
|
|
cipher.secureNote.type = model.secureNote.type;
|
|
|
|
return;
|
|
|
|
case CipherType.Card:
|
|
|
|
cipher.card = new Card();
|
|
|
|
await this.encryptObjProperty(
|
|
|
|
model.card,
|
|
|
|
cipher.card,
|
|
|
|
{
|
|
|
|
cardholderName: null,
|
|
|
|
brand: null,
|
|
|
|
number: null,
|
|
|
|
expMonth: null,
|
|
|
|
expYear: null,
|
|
|
|
code: null,
|
|
|
|
},
|
|
|
|
key
|
|
|
|
);
|
|
|
|
return;
|
|
|
|
case CipherType.Identity:
|
|
|
|
cipher.identity = new Identity();
|
|
|
|
await this.encryptObjProperty(
|
|
|
|
model.identity,
|
|
|
|
cipher.identity,
|
|
|
|
{
|
|
|
|
title: null,
|
|
|
|
firstName: null,
|
|
|
|
middleName: null,
|
|
|
|
lastName: null,
|
|
|
|
address1: null,
|
|
|
|
address2: null,
|
|
|
|
address3: null,
|
|
|
|
city: null,
|
|
|
|
state: null,
|
|
|
|
postalCode: null,
|
|
|
|
country: null,
|
|
|
|
company: null,
|
|
|
|
email: null,
|
|
|
|
phone: null,
|
|
|
|
ssn: null,
|
|
|
|
username: null,
|
|
|
|
passportNumber: null,
|
|
|
|
licenseNumber: null,
|
|
|
|
},
|
|
|
|
key
|
|
|
|
);
|
|
|
|
return;
|
|
|
|
default:
|
|
|
|
throw new Error("Unknown cipher type.");
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private async getCipherForUrl(
|
|
|
|
url: string,
|
|
|
|
lastUsed: boolean,
|
|
|
|
lastLaunched: boolean,
|
|
|
|
autofillOnPageLoad: boolean
|
|
|
|
): Promise<CipherView> {
|
|
|
|
const cacheKey = autofillOnPageLoad ? "autofillOnPageLoad-" + url : url;
|
|
|
|
|
|
|
|
if (!this.sortedCiphersCache.isCached(cacheKey)) {
|
|
|
|
let ciphers = await this.getAllDecryptedForUrl(url);
|
|
|
|
if (!ciphers) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (autofillOnPageLoad) {
|
|
|
|
const autofillOnPageLoadDefault = await this.stateService.getAutoFillOnPageLoadDefault();
|
|
|
|
ciphers = ciphers.filter(
|
|
|
|
(cipher) =>
|
|
|
|
cipher.login.autofillOnPageLoad ||
|
|
|
|
(cipher.login.autofillOnPageLoad == null && autofillOnPageLoadDefault !== false)
|
|
|
|
);
|
|
|
|
if (ciphers.length === 0) {
|
|
|
|
return null;
|
2020-08-12 21:59:59 +02:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
2020-08-12 21:59:59 +02:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
this.sortedCiphersCache.addCiphers(cacheKey, ciphers);
|
2020-08-12 21:59:59 +02:00
|
|
|
}
|
[Account Switching] [Feature] Allow clients to store data for more than one user (#491)
* [refactor] Extract, rename, and expand StorageServiceOptions
* Pulled StorageServiceOptions into its own file
* Renamed StorageServiceOptions to StorageOptions
* Pulled KeySuffixOpptions into its own file
* Converted KeySuffixOptions into an enum from a union type
* [refactor] Expand StateService into a full coverage storage proxy
* Expand StateService to allow it to manage all data points of the application state regardless of memory.
* Expand StateService to allow for storing and managing multiple accounts
* [refactor] Create helper services for managing organization and provider state data
* [refactor] Implement StateService across service layer
* Remove service level variables used for in memory data storage and replaced with calls to StateService
* Remove direct calls to StorageService in favor of using StateService as a proxy
* [feature] Implement account switching capable services across components and processes
* Replace calls to StorageService and deprecated services with calls to a StateService
* [chore] Remove unused services
Several services are no longer in use because of the expanded state service. These have simply been removed.
* [bug] Add loginRedirect to the account model
* [bug] Add awaits to newly async calls in TokenService
* [bug] Add several missing awaits
* [bug] Add state service handlers for AutoConfirmFingerprint
* [bug] Move TwoFactorToken to global state
* Update unauth-guard.service.ts
Add back return true
* [refactor] Slim down the boilerplate needed to manage options on StateService calls
* [bug] Allow the lock message handler to manipulate a specific acount
* [bug] Add missing await to auth guard
* [bug] Adjust state scope of several biometric data points
* [bug] Ensure vault locking logic can operate over non-active accounts
* [style] Fix lint complaints
* [bug] Move disableFavicon to global state
* [refactor] Remove an unecassary parameter from a StorageOptions instance
* [bug] Ensure HtmlStorageService paths are accounted for in StateService
* [feature] Add a server url helper to the account model for the account switcher
* [refactor] Remove some unused getters from the account model
* [bug] Ensure locking and logging out can function over any user
* Fix account getting set to null in getAccountFromDisk
* [bug] Ensure lock component is always working with the latest active account in state
* [chore] Update recent KeyConnector changes to use stateService
* [style] Fix lint complaints
* [chore] Resolve TokenService merge issues from KeyConnector
* [bug] Add missing service arguement
* [bug] Correct several default storage option types
* [bug] Check for the right key in hasEncKey
* [bug] Add enableFullWidth to the account model
* [style] Fix lint complaints
* [review] Revist remember email
* [refactor] Remove RememberEmail from state
* setDisableFavicon to correct storage location
* [bug] Convert vault lock loop returns into continues to not skip secondary accounts
* [review] Sorted state service methods
* [bug] Correct neverDomains type on the account model
* [review] Rename stateService.purge to stateService.clean
* [review] [refactor] Extract lock refresh logic to a load function
* [review] [refactor] Extract some timeout logic to dedicated functions
* [review] [refactor] Move AuthenticationStatus to a dedicated file
* [review] [refactor] Rename Globals to GlobalState
* [style] Fix lint complaints
* [review] Remove unused global state property for decodedToken
* [review] [bug] Adjust state scope for OrganizationInvitation
* [review] [bug] Put back the homepage variable in lock guard
* [review] Un-try-catch the window creation function
* Revert "[review] [bug] Adjust state scope for OrganizationInvitation"
This reverts commit caa4574a65d9d0c3573a7529ed2221764fd55497.
* [bug] Change || to && in recent vault timeout refactor
* [bug] Keep up with entire state in storage instead of just accounts and globals
Not having access to the last active user was creating issues across clients when restarting the process.
For example: when refreshing the page on web we no longer maintain an understanding of who is logged in.
To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals.
This allows for more flexible saving, like saving activeUserId as a top level storage item.
* [style] Fix lint complaints
* Revert "[bug] Keep up with entire state in storage instead of just accounts and globals"
This reverts commit e8970725be472386358c1e2f06f53663c4979e0e.
* [bug] Initialize GlobalState by default
* [bug] Only get key hash from storage
* [bug] Remove settings storage location overrides
* [bug] Only save accessToken to storage
* [refactor] Remove unecassary argements from electron crypto state calls
* [bug] Ensure keys and tokens load and save to the right locations for web
* [style] Fix lint complaints
* [bug] Remove keySuffix storage option and split uses into unique methods
The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state.
This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly.
* [bug] Add default vault timeouts to new accounts
* [bug] Save appId as a top level storage item
* [bug] Add missing await to timeout logic
* [bug] Adjust state scope for everBeenUnlocked
* [bug] Clear access tokens when loading account state from disk
* [bug] Adjust theme to be a global state item
* [bug] Adjust null checking for window in state
* [bug] Correct getGlobals not pulling from the stored state item
* [bug] Null check in memory account before claiming it has a userId
* [bug] Scaffold secure storage service when building storage objects on init
* [bug] Adjusted state scope of event collection
* [bug] Adjusted state scope of vault timeout and action
* [bug] Grab account from normal storage if secure storage is requested but does not exist
* [bug] Create a State if one is requested from memory before it exists
* [bug] Ensure all storage locations are cleared on state clean
* [style] Fix lint complaints
* [bug] Remove uneeded clearing of access token
* [bug] Reset tokens when toggling
* [refactor] Split up the Account model
Until this point the account model has been very flat, holding many kinds of data.
In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale,
the Account model has been divided into logical chunks.
* [bug] Correct the serverUrl helpers return
* Fix sends always coming back as empty in browser
* Get settings properly (I think)
* [bug] Fix lint error
* [bug] Add missing await to identity token refresh
This was causing weird behavior in web that was creating a lot of 429s
* [bug] Scaffold memory storage for web
Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in.
Namely, encrypted data that was recently synced had nowhere to save to and was lost.
* [bug] Implement better null handling in a few places for retrieving state
* [bug] Update correct storage locations on account removal
* [bug] Added missing awaits to lock component
* [bug] Reload lock component on account switching vs. account update
* [bug] Store master keys correctly
* [bug] Move some biometrics storage items to global state
* [feature] Add platform helper isMac()
* [refactor] Comment emphasis and call order refresh
* [refactor] Remove unecassary using
* [bug] Relocate authenticationStatus check logic to component
* [bug] Stop not clearing everything on state clean
* [style] Fix lint complaints
* [bug] Correct mismatched uses of encrypted and decrypted pin states
* Add browser specific state classes and methods
* lint fixes
* [bug] Migrate existing persistant data to new schema
* [style] Fix lint complaints
* [bug] Dont clear settings on state clean
* [bug] Maintain the right storage items on logout
* [chore] resolve issues from merge
* [bug] Resolve settings clearing on lock
* [chore] Added a comment
* [review] fromatting for code review
* Revert browser state items
Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com>
Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
2021-12-13 17:15:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
if (lastLaunched) {
|
|
|
|
return this.sortedCiphersCache.getLastLaunched(cacheKey);
|
|
|
|
} else if (lastUsed) {
|
|
|
|
return this.sortedCiphersCache.getLastUsed(cacheKey);
|
|
|
|
} else {
|
|
|
|
return this.sortedCiphersCache.getNext(cacheKey);
|
[Account Switching] [Feature] Allow clients to store data for more than one user (#491)
* [refactor] Extract, rename, and expand StorageServiceOptions
* Pulled StorageServiceOptions into its own file
* Renamed StorageServiceOptions to StorageOptions
* Pulled KeySuffixOpptions into its own file
* Converted KeySuffixOptions into an enum from a union type
* [refactor] Expand StateService into a full coverage storage proxy
* Expand StateService to allow it to manage all data points of the application state regardless of memory.
* Expand StateService to allow for storing and managing multiple accounts
* [refactor] Create helper services for managing organization and provider state data
* [refactor] Implement StateService across service layer
* Remove service level variables used for in memory data storage and replaced with calls to StateService
* Remove direct calls to StorageService in favor of using StateService as a proxy
* [feature] Implement account switching capable services across components and processes
* Replace calls to StorageService and deprecated services with calls to a StateService
* [chore] Remove unused services
Several services are no longer in use because of the expanded state service. These have simply been removed.
* [bug] Add loginRedirect to the account model
* [bug] Add awaits to newly async calls in TokenService
* [bug] Add several missing awaits
* [bug] Add state service handlers for AutoConfirmFingerprint
* [bug] Move TwoFactorToken to global state
* Update unauth-guard.service.ts
Add back return true
* [refactor] Slim down the boilerplate needed to manage options on StateService calls
* [bug] Allow the lock message handler to manipulate a specific acount
* [bug] Add missing await to auth guard
* [bug] Adjust state scope of several biometric data points
* [bug] Ensure vault locking logic can operate over non-active accounts
* [style] Fix lint complaints
* [bug] Move disableFavicon to global state
* [refactor] Remove an unecassary parameter from a StorageOptions instance
* [bug] Ensure HtmlStorageService paths are accounted for in StateService
* [feature] Add a server url helper to the account model for the account switcher
* [refactor] Remove some unused getters from the account model
* [bug] Ensure locking and logging out can function over any user
* Fix account getting set to null in getAccountFromDisk
* [bug] Ensure lock component is always working with the latest active account in state
* [chore] Update recent KeyConnector changes to use stateService
* [style] Fix lint complaints
* [chore] Resolve TokenService merge issues from KeyConnector
* [bug] Add missing service arguement
* [bug] Correct several default storage option types
* [bug] Check for the right key in hasEncKey
* [bug] Add enableFullWidth to the account model
* [style] Fix lint complaints
* [review] Revist remember email
* [refactor] Remove RememberEmail from state
* setDisableFavicon to correct storage location
* [bug] Convert vault lock loop returns into continues to not skip secondary accounts
* [review] Sorted state service methods
* [bug] Correct neverDomains type on the account model
* [review] Rename stateService.purge to stateService.clean
* [review] [refactor] Extract lock refresh logic to a load function
* [review] [refactor] Extract some timeout logic to dedicated functions
* [review] [refactor] Move AuthenticationStatus to a dedicated file
* [review] [refactor] Rename Globals to GlobalState
* [style] Fix lint complaints
* [review] Remove unused global state property for decodedToken
* [review] [bug] Adjust state scope for OrganizationInvitation
* [review] [bug] Put back the homepage variable in lock guard
* [review] Un-try-catch the window creation function
* Revert "[review] [bug] Adjust state scope for OrganizationInvitation"
This reverts commit caa4574a65d9d0c3573a7529ed2221764fd55497.
* [bug] Change || to && in recent vault timeout refactor
* [bug] Keep up with entire state in storage instead of just accounts and globals
Not having access to the last active user was creating issues across clients when restarting the process.
For example: when refreshing the page on web we no longer maintain an understanding of who is logged in.
To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals.
This allows for more flexible saving, like saving activeUserId as a top level storage item.
* [style] Fix lint complaints
* Revert "[bug] Keep up with entire state in storage instead of just accounts and globals"
This reverts commit e8970725be472386358c1e2f06f53663c4979e0e.
* [bug] Initialize GlobalState by default
* [bug] Only get key hash from storage
* [bug] Remove settings storage location overrides
* [bug] Only save accessToken to storage
* [refactor] Remove unecassary argements from electron crypto state calls
* [bug] Ensure keys and tokens load and save to the right locations for web
* [style] Fix lint complaints
* [bug] Remove keySuffix storage option and split uses into unique methods
The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state.
This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly.
* [bug] Add default vault timeouts to new accounts
* [bug] Save appId as a top level storage item
* [bug] Add missing await to timeout logic
* [bug] Adjust state scope for everBeenUnlocked
* [bug] Clear access tokens when loading account state from disk
* [bug] Adjust theme to be a global state item
* [bug] Adjust null checking for window in state
* [bug] Correct getGlobals not pulling from the stored state item
* [bug] Null check in memory account before claiming it has a userId
* [bug] Scaffold secure storage service when building storage objects on init
* [bug] Adjusted state scope of event collection
* [bug] Adjusted state scope of vault timeout and action
* [bug] Grab account from normal storage if secure storage is requested but does not exist
* [bug] Create a State if one is requested from memory before it exists
* [bug] Ensure all storage locations are cleared on state clean
* [style] Fix lint complaints
* [bug] Remove uneeded clearing of access token
* [bug] Reset tokens when toggling
* [refactor] Split up the Account model
Until this point the account model has been very flat, holding many kinds of data.
In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale,
the Account model has been divided into logical chunks.
* [bug] Correct the serverUrl helpers return
* Fix sends always coming back as empty in browser
* Get settings properly (I think)
* [bug] Fix lint error
* [bug] Add missing await to identity token refresh
This was causing weird behavior in web that was creating a lot of 429s
* [bug] Scaffold memory storage for web
Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in.
Namely, encrypted data that was recently synced had nowhere to save to and was lost.
* [bug] Implement better null handling in a few places for retrieving state
* [bug] Update correct storage locations on account removal
* [bug] Added missing awaits to lock component
* [bug] Reload lock component on account switching vs. account update
* [bug] Store master keys correctly
* [bug] Move some biometrics storage items to global state
* [feature] Add platform helper isMac()
* [refactor] Comment emphasis and call order refresh
* [refactor] Remove unecassary using
* [bug] Relocate authenticationStatus check logic to component
* [bug] Stop not clearing everything on state clean
* [style] Fix lint complaints
* [bug] Correct mismatched uses of encrypted and decrypted pin states
* Add browser specific state classes and methods
* lint fixes
* [bug] Migrate existing persistant data to new schema
* [style] Fix lint complaints
* [bug] Dont clear settings on state clean
* [bug] Maintain the right storage items on logout
* [chore] resolve issues from merge
* [bug] Resolve settings clearing on lock
* [chore] Added a comment
* [review] fromatting for code review
* Revert browser state items
Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com>
Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
2021-12-13 17:15:16 +01:00
|
|
|
}
|
2021-12-16 13:36:21 +01:00
|
|
|
}
|
[Account Switching] [Feature] Allow clients to store data for more than one user (#491)
* [refactor] Extract, rename, and expand StorageServiceOptions
* Pulled StorageServiceOptions into its own file
* Renamed StorageServiceOptions to StorageOptions
* Pulled KeySuffixOpptions into its own file
* Converted KeySuffixOptions into an enum from a union type
* [refactor] Expand StateService into a full coverage storage proxy
* Expand StateService to allow it to manage all data points of the application state regardless of memory.
* Expand StateService to allow for storing and managing multiple accounts
* [refactor] Create helper services for managing organization and provider state data
* [refactor] Implement StateService across service layer
* Remove service level variables used for in memory data storage and replaced with calls to StateService
* Remove direct calls to StorageService in favor of using StateService as a proxy
* [feature] Implement account switching capable services across components and processes
* Replace calls to StorageService and deprecated services with calls to a StateService
* [chore] Remove unused services
Several services are no longer in use because of the expanded state service. These have simply been removed.
* [bug] Add loginRedirect to the account model
* [bug] Add awaits to newly async calls in TokenService
* [bug] Add several missing awaits
* [bug] Add state service handlers for AutoConfirmFingerprint
* [bug] Move TwoFactorToken to global state
* Update unauth-guard.service.ts
Add back return true
* [refactor] Slim down the boilerplate needed to manage options on StateService calls
* [bug] Allow the lock message handler to manipulate a specific acount
* [bug] Add missing await to auth guard
* [bug] Adjust state scope of several biometric data points
* [bug] Ensure vault locking logic can operate over non-active accounts
* [style] Fix lint complaints
* [bug] Move disableFavicon to global state
* [refactor] Remove an unecassary parameter from a StorageOptions instance
* [bug] Ensure HtmlStorageService paths are accounted for in StateService
* [feature] Add a server url helper to the account model for the account switcher
* [refactor] Remove some unused getters from the account model
* [bug] Ensure locking and logging out can function over any user
* Fix account getting set to null in getAccountFromDisk
* [bug] Ensure lock component is always working with the latest active account in state
* [chore] Update recent KeyConnector changes to use stateService
* [style] Fix lint complaints
* [chore] Resolve TokenService merge issues from KeyConnector
* [bug] Add missing service arguement
* [bug] Correct several default storage option types
* [bug] Check for the right key in hasEncKey
* [bug] Add enableFullWidth to the account model
* [style] Fix lint complaints
* [review] Revist remember email
* [refactor] Remove RememberEmail from state
* setDisableFavicon to correct storage location
* [bug] Convert vault lock loop returns into continues to not skip secondary accounts
* [review] Sorted state service methods
* [bug] Correct neverDomains type on the account model
* [review] Rename stateService.purge to stateService.clean
* [review] [refactor] Extract lock refresh logic to a load function
* [review] [refactor] Extract some timeout logic to dedicated functions
* [review] [refactor] Move AuthenticationStatus to a dedicated file
* [review] [refactor] Rename Globals to GlobalState
* [style] Fix lint complaints
* [review] Remove unused global state property for decodedToken
* [review] [bug] Adjust state scope for OrganizationInvitation
* [review] [bug] Put back the homepage variable in lock guard
* [review] Un-try-catch the window creation function
* Revert "[review] [bug] Adjust state scope for OrganizationInvitation"
This reverts commit caa4574a65d9d0c3573a7529ed2221764fd55497.
* [bug] Change || to && in recent vault timeout refactor
* [bug] Keep up with entire state in storage instead of just accounts and globals
Not having access to the last active user was creating issues across clients when restarting the process.
For example: when refreshing the page on web we no longer maintain an understanding of who is logged in.
To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals.
This allows for more flexible saving, like saving activeUserId as a top level storage item.
* [style] Fix lint complaints
* Revert "[bug] Keep up with entire state in storage instead of just accounts and globals"
This reverts commit e8970725be472386358c1e2f06f53663c4979e0e.
* [bug] Initialize GlobalState by default
* [bug] Only get key hash from storage
* [bug] Remove settings storage location overrides
* [bug] Only save accessToken to storage
* [refactor] Remove unecassary argements from electron crypto state calls
* [bug] Ensure keys and tokens load and save to the right locations for web
* [style] Fix lint complaints
* [bug] Remove keySuffix storage option and split uses into unique methods
The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state.
This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly.
* [bug] Add default vault timeouts to new accounts
* [bug] Save appId as a top level storage item
* [bug] Add missing await to timeout logic
* [bug] Adjust state scope for everBeenUnlocked
* [bug] Clear access tokens when loading account state from disk
* [bug] Adjust theme to be a global state item
* [bug] Adjust null checking for window in state
* [bug] Correct getGlobals not pulling from the stored state item
* [bug] Null check in memory account before claiming it has a userId
* [bug] Scaffold secure storage service when building storage objects on init
* [bug] Adjusted state scope of event collection
* [bug] Adjusted state scope of vault timeout and action
* [bug] Grab account from normal storage if secure storage is requested but does not exist
* [bug] Create a State if one is requested from memory before it exists
* [bug] Ensure all storage locations are cleared on state clean
* [style] Fix lint complaints
* [bug] Remove uneeded clearing of access token
* [bug] Reset tokens when toggling
* [refactor] Split up the Account model
Until this point the account model has been very flat, holding many kinds of data.
In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale,
the Account model has been divided into logical chunks.
* [bug] Correct the serverUrl helpers return
* Fix sends always coming back as empty in browser
* Get settings properly (I think)
* [bug] Fix lint error
* [bug] Add missing await to identity token refresh
This was causing weird behavior in web that was creating a lot of 429s
* [bug] Scaffold memory storage for web
Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in.
Namely, encrypted data that was recently synced had nowhere to save to and was lost.
* [bug] Implement better null handling in a few places for retrieving state
* [bug] Update correct storage locations on account removal
* [bug] Added missing awaits to lock component
* [bug] Reload lock component on account switching vs. account update
* [bug] Store master keys correctly
* [bug] Move some biometrics storage items to global state
* [feature] Add platform helper isMac()
* [refactor] Comment emphasis and call order refresh
* [refactor] Remove unecassary using
* [bug] Relocate authenticationStatus check logic to component
* [bug] Stop not clearing everything on state clean
* [style] Fix lint complaints
* [bug] Correct mismatched uses of encrypted and decrypted pin states
* Add browser specific state classes and methods
* lint fixes
* [bug] Migrate existing persistant data to new schema
* [style] Fix lint complaints
* [bug] Dont clear settings on state clean
* [bug] Maintain the right storage items on logout
* [chore] resolve issues from merge
* [bug] Resolve settings clearing on lock
* [chore] Added a comment
* [review] fromatting for code review
* Revert browser state items
Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com>
Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
2021-12-13 17:15:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
private async clearEncryptedCiphersState(userId?: string) {
|
|
|
|
await this.stateService.setEncryptedCiphers(null, { userId: userId });
|
|
|
|
}
|
[Account Switching] [Feature] Allow clients to store data for more than one user (#491)
* [refactor] Extract, rename, and expand StorageServiceOptions
* Pulled StorageServiceOptions into its own file
* Renamed StorageServiceOptions to StorageOptions
* Pulled KeySuffixOpptions into its own file
* Converted KeySuffixOptions into an enum from a union type
* [refactor] Expand StateService into a full coverage storage proxy
* Expand StateService to allow it to manage all data points of the application state regardless of memory.
* Expand StateService to allow for storing and managing multiple accounts
* [refactor] Create helper services for managing organization and provider state data
* [refactor] Implement StateService across service layer
* Remove service level variables used for in memory data storage and replaced with calls to StateService
* Remove direct calls to StorageService in favor of using StateService as a proxy
* [feature] Implement account switching capable services across components and processes
* Replace calls to StorageService and deprecated services with calls to a StateService
* [chore] Remove unused services
Several services are no longer in use because of the expanded state service. These have simply been removed.
* [bug] Add loginRedirect to the account model
* [bug] Add awaits to newly async calls in TokenService
* [bug] Add several missing awaits
* [bug] Add state service handlers for AutoConfirmFingerprint
* [bug] Move TwoFactorToken to global state
* Update unauth-guard.service.ts
Add back return true
* [refactor] Slim down the boilerplate needed to manage options on StateService calls
* [bug] Allow the lock message handler to manipulate a specific acount
* [bug] Add missing await to auth guard
* [bug] Adjust state scope of several biometric data points
* [bug] Ensure vault locking logic can operate over non-active accounts
* [style] Fix lint complaints
* [bug] Move disableFavicon to global state
* [refactor] Remove an unecassary parameter from a StorageOptions instance
* [bug] Ensure HtmlStorageService paths are accounted for in StateService
* [feature] Add a server url helper to the account model for the account switcher
* [refactor] Remove some unused getters from the account model
* [bug] Ensure locking and logging out can function over any user
* Fix account getting set to null in getAccountFromDisk
* [bug] Ensure lock component is always working with the latest active account in state
* [chore] Update recent KeyConnector changes to use stateService
* [style] Fix lint complaints
* [chore] Resolve TokenService merge issues from KeyConnector
* [bug] Add missing service arguement
* [bug] Correct several default storage option types
* [bug] Check for the right key in hasEncKey
* [bug] Add enableFullWidth to the account model
* [style] Fix lint complaints
* [review] Revist remember email
* [refactor] Remove RememberEmail from state
* setDisableFavicon to correct storage location
* [bug] Convert vault lock loop returns into continues to not skip secondary accounts
* [review] Sorted state service methods
* [bug] Correct neverDomains type on the account model
* [review] Rename stateService.purge to stateService.clean
* [review] [refactor] Extract lock refresh logic to a load function
* [review] [refactor] Extract some timeout logic to dedicated functions
* [review] [refactor] Move AuthenticationStatus to a dedicated file
* [review] [refactor] Rename Globals to GlobalState
* [style] Fix lint complaints
* [review] Remove unused global state property for decodedToken
* [review] [bug] Adjust state scope for OrganizationInvitation
* [review] [bug] Put back the homepage variable in lock guard
* [review] Un-try-catch the window creation function
* Revert "[review] [bug] Adjust state scope for OrganizationInvitation"
This reverts commit caa4574a65d9d0c3573a7529ed2221764fd55497.
* [bug] Change || to && in recent vault timeout refactor
* [bug] Keep up with entire state in storage instead of just accounts and globals
Not having access to the last active user was creating issues across clients when restarting the process.
For example: when refreshing the page on web we no longer maintain an understanding of who is logged in.
To resolve this I converted all storage save operations to get and save an entire state object, instead of specifying accounts and globals.
This allows for more flexible saving, like saving activeUserId as a top level storage item.
* [style] Fix lint complaints
* Revert "[bug] Keep up with entire state in storage instead of just accounts and globals"
This reverts commit e8970725be472386358c1e2f06f53663c4979e0e.
* [bug] Initialize GlobalState by default
* [bug] Only get key hash from storage
* [bug] Remove settings storage location overrides
* [bug] Only save accessToken to storage
* [refactor] Remove unecassary argements from electron crypto state calls
* [bug] Ensure keys and tokens load and save to the right locations for web
* [style] Fix lint complaints
* [bug] Remove keySuffix storage option and split uses into unique methods
The keySuffix options don't work with saving serialized json as a storage object - use cases simply overwrite each other in state.
This commit breaks Auto and Biometric keys into distinct storage items and adjusts logic accordingly.
* [bug] Add default vault timeouts to new accounts
* [bug] Save appId as a top level storage item
* [bug] Add missing await to timeout logic
* [bug] Adjust state scope for everBeenUnlocked
* [bug] Clear access tokens when loading account state from disk
* [bug] Adjust theme to be a global state item
* [bug] Adjust null checking for window in state
* [bug] Correct getGlobals not pulling from the stored state item
* [bug] Null check in memory account before claiming it has a userId
* [bug] Scaffold secure storage service when building storage objects on init
* [bug] Adjusted state scope of event collection
* [bug] Adjusted state scope of vault timeout and action
* [bug] Grab account from normal storage if secure storage is requested but does not exist
* [bug] Create a State if one is requested from memory before it exists
* [bug] Ensure all storage locations are cleared on state clean
* [style] Fix lint complaints
* [bug] Remove uneeded clearing of access token
* [bug] Reset tokens when toggling
* [refactor] Split up the Account model
Until this point the account model has been very flat, holding many kinds of data.
In order to be able to prune data at appropriate times, for example clearing keys at logout without clearing QoL settings like locale,
the Account model has been divided into logical chunks.
* [bug] Correct the serverUrl helpers return
* Fix sends always coming back as empty in browser
* Get settings properly (I think)
* [bug] Fix lint error
* [bug] Add missing await to identity token refresh
This was causing weird behavior in web that was creating a lot of 429s
* [bug] Scaffold memory storage for web
Not properly creating storage objects on signin was creating weird behavior when logging out, locking, and logging back in.
Namely, encrypted data that was recently synced had nowhere to save to and was lost.
* [bug] Implement better null handling in a few places for retrieving state
* [bug] Update correct storage locations on account removal
* [bug] Added missing awaits to lock component
* [bug] Reload lock component on account switching vs. account update
* [bug] Store master keys correctly
* [bug] Move some biometrics storage items to global state
* [feature] Add platform helper isMac()
* [refactor] Comment emphasis and call order refresh
* [refactor] Remove unecassary using
* [bug] Relocate authenticationStatus check logic to component
* [bug] Stop not clearing everything on state clean
* [style] Fix lint complaints
* [bug] Correct mismatched uses of encrypted and decrypted pin states
* Add browser specific state classes and methods
* lint fixes
* [bug] Migrate existing persistant data to new schema
* [style] Fix lint complaints
* [bug] Dont clear settings on state clean
* [bug] Maintain the right storage items on logout
* [chore] resolve issues from merge
* [bug] Resolve settings clearing on lock
* [chore] Added a comment
* [review] fromatting for code review
* Revert browser state items
Co-authored-by: Robyn MacCallum <nickersthecat@gmail.com>
Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com>
2021-12-13 17:15:16 +01:00
|
|
|
|
2021-12-16 13:36:21 +01:00
|
|
|
private async clearDecryptedCiphersState(userId?: string) {
|
|
|
|
await this.stateService.setDecryptedCiphers(null, { userId: userId });
|
|
|
|
this.clearSortedCiphers();
|
|
|
|
}
|
|
|
|
|
|
|
|
private clearSortedCiphers() {
|
|
|
|
this.sortedCiphersCache.clear();
|
|
|
|
}
|
2018-01-10 05:01:16 +01:00
|
|
|
}
|