1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-11-12 10:14:10 +01:00
bitwarden-browser/common/src/services/cipher.service.ts

1127 lines
43 KiB
TypeScript
Raw Normal View History

import { CipherType } from '../enums/cipherType';
2018-07-27 22:44:20 +02:00
import { FieldType } from '../enums/fieldType';
import { UriMatchType } from '../enums/uriMatchType';
2018-01-10 05:01:16 +01:00
import { CipherData } from '../models/data/cipherData';
2018-01-10 05:01:16 +01:00
2018-06-12 17:45:02 +02:00
import { Attachment } from '../models/domain/attachment';
import { Card } from '../models/domain/card';
import { Cipher } from '../models/domain/cipher';
import Domain from '../models/domain/domainBase';
import { EncArrayBuffer } from '../models/domain/encArrayBuffer';
import { EncString } from '../models/domain/encString';
import { Field } from '../models/domain/field';
import { Identity } from '../models/domain/identity';
import { Login } from '../models/domain/login';
import { LoginUri } from '../models/domain/loginUri';
2018-07-27 22:44:20 +02:00
import { Password } from '../models/domain/password';
import { SecureNote } from '../models/domain/secureNote';
import { SymmetricCryptoKey } from '../models/domain/symmetricCryptoKey';
2018-01-10 05:01:16 +01:00
import { AttachmentRequest } from '../models/request/attachmentRequest';
2018-06-12 23:12:27 +02:00
import { CipherBulkDeleteRequest } from '../models/request/cipherBulkDeleteRequest';
import { CipherBulkMoveRequest } from '../models/request/cipherBulkMoveRequest';
import { CipherBulkRestoreRequest } from '../models/request/cipherBulkRestoreRequest';
2018-06-13 06:02:15 +02:00
import { CipherBulkShareRequest } from '../models/request/cipherBulkShareRequest';
2018-06-12 19:07:06 +02:00
import { CipherCollectionsRequest } from '../models/request/cipherCollectionsRequest';
2018-10-19 15:14:11 +02:00
import { CipherCreateRequest } from '../models/request/cipherCreateRequest';
import { CipherRequest } from '../models/request/cipherRequest';
2018-06-12 23:12:27 +02:00
import { CipherShareRequest } from '../models/request/cipherShareRequest';
2018-01-10 05:01:16 +01:00
import { CipherResponse } from '../models/response/cipherResponse';
import { ErrorResponse } from '../models/response/errorResponse';
2018-01-10 05:01:16 +01:00
2018-06-12 17:45:02 +02:00
import { AttachmentView } from '../models/view/attachmentView';
import { CipherView } from '../models/view/cipherView';
import { FieldView } from '../models/view/fieldView';
2018-07-27 22:44:20 +02:00
import { PasswordHistoryView } from '../models/view/passwordHistoryView';
import { View } from '../models/view/view';
2018-01-24 17:33:15 +01:00
import { SortedCiphersCache } from '../models/domain/sortedCiphersCache';
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 { SearchService } from '../abstractions/search.service';
import { SettingsService } from '../abstractions/settings.service';
import { StorageService } from '../abstractions/storage.service';
import { UserService } from '../abstractions/user.service';
2018-04-23 19:03:47 +02:00
2019-01-09 17:59:11 +01:00
import { ConstantsService } from './constants.service';
import { sequentialize } from '../misc/sequentialize';
2018-04-23 19:03:47 +02:00
import { Utils } from '../misc/utils';
2018-01-10 05:01:16 +01:00
const Keys = {
ciphersPrefix: 'ciphers_',
localData: 'sitesLocalData',
neverDomains: 'neverDomains',
};
2018-12-07 21:41:43 +01:00
const DomainMatchBlacklist = new Map<string, Set<string>>([
['google.com', new Set(['script.google.com'])],
]);
2018-01-23 23:29:15 +01:00
export class CipherService implements CipherServiceAbstraction {
// tslint:disable-next-line
_decryptedCipherCache: CipherView[];
2018-01-10 05:01:16 +01:00
private sortedCiphersCache: SortedCiphersCache = new SortedCiphersCache(this.sortCiphersByLastUsed);
2018-01-10 05:01:16 +01:00
constructor(private cryptoService: CryptoService, private userService: UserService,
private settingsService: SettingsService, private apiService: ApiService,
private fileUploadService: FileUploadService, private storageService: StorageService,
private i18nService: I18nService, private searchService: () => SearchService) {
}
get decryptedCipherCache() {
return this._decryptedCipherCache;
}
set decryptedCipherCache(value: CipherView[]) {
this._decryptedCipherCache = value;
2018-08-13 20:28:10 +02:00
if (this.searchService != null) {
if (value == null) {
this.searchService().clearIndex();
} else {
this.searchService().indexCiphers();
}
}
2018-01-10 05:01:16 +01:00
}
clearCache(): void {
this.decryptedCipherCache = null;
this.sortedCiphersCache.clear();
2018-01-10 05:01:16 +01:00
}
async encrypt(model: CipherView, key?: SymmetricCryptoKey, originalCipher: Cipher = null): Promise<Cipher> {
2018-07-27 22:44:20 +02:00
// Adjust password history
if (model.id != null) {
if (originalCipher == null) {
originalCipher = await this.get(model.id);
}
if (originalCipher != null) {
const existingCipher = await originalCipher.decrypt();
2018-07-27 22:44:20 +02:00
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;
}
2018-07-27 22:44:20 +02:00
}
if (existingCipher.hasFields) {
const existingHiddenFields = existingCipher.fields.filter(f => f.type === FieldType.Hidden &&
f.name != null && f.name !== '' && f.value != null && f.value !== '');
2018-07-27 22:44:20 +02:00
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);
2019-04-16 03:15:35 +02:00
if (matchedField == null || matchedField.value !== ef.value) {
const ph = new PasswordHistoryView();
2018-07-27 22:44:20 +02:00
ph.password = ef.name + ': ' + ef.value;
ph.lastUsedDate = new Date();
model.passwordHistory.splice(0, 0, ph);
}
});
}
}
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
2018-07-27 23:30:51 +02:00
model.passwordHistory = model.passwordHistory.slice(0, 5);
2018-07-27 22:44:20 +02:00
}
}
2018-01-10 05:01:16 +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;
2021-04-29 13:31:21 +02:00
cipher.reprompt = model.reprompt;
2018-01-10 05:01:16 +01:00
2018-07-17 23:22:45 +02:00
if (key == null && cipher.organizationId != null) {
key = await this.cryptoService.getOrgKey(cipher.organizationId);
2018-09-10 14:22:10 +02:00
if (key == null) {
throw new Error('Cannot encrypt cipher for organization. No key.');
}
2018-07-17 23:22:45 +02:00
}
2018-01-10 05:01:16 +01:00
await Promise.all([
this.encryptObjProperty(model, cipher, {
name: null,
notes: null,
}, key),
2018-01-24 17:33:15 +01:00
this.encryptCipherData(cipher, model, key),
this.encryptFields(model.fields, key).then(fields => {
2018-01-10 05:01:16 +01:00
cipher.fields = fields;
}),
this.encryptPasswordHistories(model.passwordHistory, key).then(ph => {
2018-07-27 22:44:20 +02:00
cipher.passwordHistory = ph;
}),
this.encryptAttachments(model.attachments, key).then(attachments => {
2018-06-12 17:45:02 +02:00
cipher.attachments = attachments;
}),
2018-01-10 05:01:16 +01:00
]);
return cipher;
}
2018-06-12 17:45:02 +02:00
async encryptAttachments(attachmentsModel: AttachmentView[], key: SymmetricCryptoKey): Promise<Attachment[]> {
if (attachmentsModel == null || attachmentsModel.length === 0) {
return null;
}
const promises: Promise<any>[] = [];
2018-06-12 17:45:02 +02:00
const encAttachments: Attachment[] = [];
attachmentsModel.forEach(async model => {
2018-06-12 17:45:02 +02:00
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,
2018-11-14 02:43:45 +01:00
}, 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
encAttachments.push(attachment);
});
promises.push(promise);
});
await Promise.all(promises);
return encAttachments;
}
2018-01-24 17:33:15 +01:00
async encryptFields(fieldsModel: FieldView[], key: SymmetricCryptoKey): Promise<Field[]> {
2018-01-10 05:01:16 +01:00
if (!fieldsModel || !fieldsModel.length) {
return null;
}
const self = this;
const encFields: Field[] = [];
await fieldsModel.reduce((promise, field) => {
return promise.then(() => {
return self.encryptField(field, key);
}).then((encField: Field) => {
encFields.push(encField);
});
}, Promise.resolve());
return encFields;
}
2018-01-24 17:33:15 +01:00
async encryptField(fieldModel: FieldView, key: SymmetricCryptoKey): Promise<Field> {
2018-01-10 05:01:16 +01:00
const field = new Field();
field.type = fieldModel.type;
// normalize boolean type field values
if (fieldModel.type === FieldType.Boolean && fieldModel.value !== 'true') {
fieldModel.value = 'false';
}
2018-01-10 05:01:16 +01:00
await this.encryptObjProperty(fieldModel, field, {
name: null,
value: null,
}, key);
return field;
}
2018-07-27 22:44:20 +02:00
async encryptPasswordHistories(phModels: PasswordHistoryView[], key: SymmetricCryptoKey): Promise<Password[]> {
if (!phModels || !phModels.length) {
return null;
}
const self = this;
const encPhs: Password[] = [];
await phModels.reduce((promise, ph) => {
return promise.then(() => {
return self.encryptPasswordHistory(ph, key);
}).then((encPh: Password) => {
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;
}
2018-01-10 05:01:16 +01:00
async get(id: string): Promise<Cipher> {
const userId = await this.userService.getUserId();
const localData = await this.storageService.get<any>(Keys.localData);
const ciphers = await this.storageService.get<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
if (ciphers == null || !ciphers.hasOwnProperty(id)) {
return null;
}
return new Cipher(ciphers[id], false, localData ? localData[id] : null);
}
async getAll(): Promise<Cipher[]> {
const userId = await this.userService.getUserId();
const localData = await this.storageService.get<any>(Keys.localData);
const ciphers = await this.storageService.get<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
const response: Cipher[] = [];
for (const id in ciphers) {
if (ciphers.hasOwnProperty(id)) {
response.push(new Cipher(ciphers[id], false, localData ? localData[id] : null));
}
}
return response;
}
@sequentialize(() => 'getAllDecrypted')
2018-01-24 17:33:15 +01:00
async getAllDecrypted(): Promise<CipherView[]> {
2018-01-10 05:01:16 +01:00
if (this.decryptedCipherCache != null) {
const userId = await this.userService.getUserId();
if (this.searchService != null && (this.searchService().indexedEntityId ?? userId) !== userId)
{
await this.searchService().indexCiphers(userId, this.decryptedCipherCache);
}
2018-01-10 05:01:16 +01:00
return this.decryptedCipherCache;
}
2018-01-24 17:33:15 +01:00
const decCiphers: CipherView[] = [];
2018-06-13 23:14:26 +02:00
const hasKey = await this.cryptoService.hasKey();
if (!hasKey) {
2018-01-10 05:01:16 +01:00
throw new Error('No key.');
}
const promises: any[] = [];
2018-01-10 05:01:16 +01:00
const ciphers = await this.getAll();
ciphers.forEach(cipher => {
promises.push(cipher.decrypt().then(c => decCiphers.push(c)));
});
await Promise.all(promises);
2018-01-27 04:38:22 +01:00
decCiphers.sort(this.getLocaleSortingFunction());
2018-01-10 05:01:16 +01:00
this.decryptedCipherCache = decCiphers;
return this.decryptedCipherCache;
}
2018-01-24 17:33:15 +01:00
async getAllDecryptedForGrouping(groupingId: string, folder: boolean = true): Promise<CipherView[]> {
2018-01-10 05:01:16 +01:00
const ciphers = await this.getAllDecrypted();
return ciphers.filter(cipher => {
if (cipher.isDeleted) {
return false;
}
2018-01-10 05:01:16 +01:00
if (folder && cipher.folderId === groupingId) {
2018-01-24 17:33:15 +01:00
return true;
2018-01-10 05:01:16 +01:00
} else if (!folder && cipher.collectionIds != null && cipher.collectionIds.indexOf(groupingId) > -1) {
2018-01-24 17:33:15 +01:00
return true;
2018-01-10 05:01:16 +01:00
}
2018-01-24 17:33:15 +01:00
return false;
});
2018-01-10 05:01:16 +01:00
}
async getAllDecryptedForUrl(url: string, includeOtherTypes?: CipherType[],
defaultMatch: UriMatchType = null): Promise<CipherView[]> {
2019-04-16 03:15:35 +02:00
if (url == null && includeOtherTypes == null) {
2018-01-10 05:01:16 +01:00
return Promise.resolve([]);
}
2018-10-14 04:21:54 +02:00
const domain = Utils.getDomain(url);
2018-01-10 05:01:16 +01:00
const eqDomainsPromise = domain == null ? Promise.resolve([]) :
this.settingsService.getEquivalentDomains().then((eqDomains: any[][]) => {
let matches: any[] = [];
eqDomains.forEach(eqDomain => {
2018-01-10 05:01:16 +01:00
if (eqDomain.length && eqDomain.indexOf(domain) >= 0) {
matches = matches.concat(eqDomain);
}
});
if (!matches.length) {
matches.push(domain);
}
return matches;
});
const result = await Promise.all([eqDomainsPromise, this.getAllDecrypted()]);
const matchingDomains = result[0];
const ciphers = result[1];
2019-01-09 17:59:11 +01:00
if (defaultMatch == null) {
defaultMatch = await this.storageService.get<UriMatchType>(ConstantsService.defaultUriMatch);
if (defaultMatch == null) {
defaultMatch = UriMatchType.Domain;
}
2019-01-09 17:59:11 +01:00
}
return ciphers.filter(cipher => {
if (cipher.deletedDate != null) {
return false;
}
2019-04-16 03:15:35 +02:00
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;
}
2019-01-09 17:59:11 +01:00
const match = u.match == null ? defaultMatch : u.match;
switch (match) {
2018-03-02 19:50:26 +01:00
case UriMatchType.Domain:
if (domain != null && u.domain != null && matchingDomains.indexOf(u.domain) > -1) {
2018-12-07 21:41:43 +01:00
if (DomainMatchBlacklist.has(u.domain)) {
const domainUrlHost = Utils.getHost(url);
if (!DomainMatchBlacklist.get(u.domain).has(domainUrlHost)) {
return true;
}
} else {
return true;
}
}
2018-03-02 18:36:53 +01:00
break;
case UriMatchType.Host:
2018-04-23 19:03:47 +02:00
const urlHost = Utils.getHost(url);
if (urlHost != null && urlHost === Utils.getHost(u.uri)) {
return true;
}
2018-03-02 18:36:53 +01:00
break;
case UriMatchType.Exact:
if (url === u.uri) {
return true;
}
2018-03-02 18:36:53 +01:00
break;
case UriMatchType.StartsWith:
if (url.startsWith(u.uri)) {
return true;
}
2018-03-02 18:36:53 +01:00
break;
case UriMatchType.RegularExpression:
2018-05-31 05:19:12 +02:00
try {
const regex = new RegExp(u.uri, 'i');
if (regex.test(url)) {
return true;
}
} catch { }
2018-03-02 18:36:53 +01:00
break;
case UriMatchType.Never:
default:
break;
}
}
}
2018-01-10 05:01:16 +01:00
2018-01-24 17:33:15 +01:00
return false;
});
2018-12-14 19:55:44 +01:00
}
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 => {
2018-12-14 19:55:44 +01:00
const data = new CipherData(r);
const cipher = new Cipher(data);
promises.push(cipher.decrypt().then(c => decCiphers.push(c)));
2018-12-14 19:55:44 +01:00
});
await Promise.all(promises);
decCiphers.sort(this.getLocaleSortingFunction());
return decCiphers;
} else {
return [];
}
2018-01-10 05:01:16 +01:00
}
async getLastUsedForUrl(url: string, autofillOnPageLoad: boolean = false): Promise<CipherView> {
return this.getCipherForUrl(url, true, false, autofillOnPageLoad);
}
async getLastLaunchedForUrl(url: string, autofillOnPageLoad: boolean = false): Promise<CipherView> {
return this.getCipherForUrl(url, false, true, autofillOnPageLoad);
}
2018-01-10 05:01:16 +01:00
async getNextCipherForUrl(url: string): Promise<CipherView> {
return this.getCipherForUrl(url, false, false, false);
2018-01-10 05:01:16 +01:00
}
updateLastUsedIndexForUrl(url: string) {
this.sortedCiphersCache.updateLastUsedIndex(url);
}
2018-01-10 05:01:16 +01:00
async updateLastUsedDate(id: string): Promise<void> {
let ciphersLocalData = await this.storageService.get<any>(Keys.localData);
if (!ciphersLocalData) {
ciphersLocalData = {};
}
if (ciphersLocalData[id]) {
ciphersLocalData[id].lastUsedDate = new Date().getTime();
} else {
ciphersLocalData[id] = {
lastUsedDate: new Date().getTime(),
};
}
await this.storageService.save(Keys.localData, ciphersLocalData);
if (this.decryptedCipherCache == null) {
return;
}
for (let i = 0; i < this.decryptedCipherCache.length; i++) {
const cached = this.decryptedCipherCache[i];
if (cached.id === id) {
cached.localData = ciphersLocalData[id];
break;
}
}
}
async updateLastLaunchedDate(id: string): Promise<void> {
let ciphersLocalData = await this.storageService.get<any>(Keys.localData);
if (!ciphersLocalData) {
ciphersLocalData = {};
}
if (ciphersLocalData[id]) {
ciphersLocalData[id].lastLaunched = new Date().getTime();
} else {
ciphersLocalData[id] = {
lastUsedDate: new Date().getTime(),
};
}
await this.storageService.save(Keys.localData, ciphersLocalData);
if (this.decryptedCipherCache == null) {
return;
}
for (let i = 0; i < this.decryptedCipherCache.length; i++) {
const cached = this.decryptedCipherCache[i];
if (cached.id === id) {
cached.localData = ciphersLocalData[id];
break;
}
}
}
2018-01-10 05:01:16 +01:00
async saveNeverDomain(domain: string): Promise<void> {
if (domain == null) {
return;
}
let domains = await this.storageService.get<{ [id: string]: any; }>(Keys.neverDomains);
if (!domains) {
domains = {};
}
domains[domain] = null;
await this.storageService.save(Keys.neverDomains, domains);
}
async saveWithServer(cipher: Cipher): Promise<any> {
2018-01-10 05:01:16 +01:00
let response: CipherResponse;
if (cipher.id == null) {
if (cipher.collectionIds != null) {
const request = new CipherCreateRequest(cipher);
2018-10-19 15:14:11 +02:00
response = await this.apiService.postCipherCreate(request);
} else {
const request = new CipherRequest(cipher);
response = await this.apiService.postCipher(request);
}
2018-01-10 05:01:16 +01:00
cipher.id = response.id;
} else {
2018-10-19 15:14:11 +02:00
const request = new CipherRequest(cipher);
2018-01-10 05:01:16 +01:00
response = await this.apiService.putCipher(cipher.id, request);
}
const userId = await this.userService.getUserId();
const data = new CipherData(response, userId, cipher.collectionIds);
await this.upsert(data);
}
2018-06-13 06:02:15 +02:00
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));
}
});
}
await Promise.all(attachmentPromises);
2018-06-13 06:02:15 +02:00
cipher.organizationId = organizationId;
cipher.collectionIds = collectionIds;
const encCipher = await this.encrypt(cipher);
const request = new CipherShareRequest(encCipher);
2018-10-23 22:16:59 +02:00
const response = await this.apiService.putShareCipher(cipher.id, request);
2018-06-12 17:45:02 +02:00
const userId = await this.userService.getUserId();
2018-10-23 22:16:59 +02:00
const data = new CipherData(response, userId, collectionIds);
await this.upsert(data);
2018-06-13 06:02:15 +02:00
}
async shareManyWithServer(ciphers: CipherView[], organizationId: string, collectionIds: string[]): Promise<any> {
const promises: Promise<any>[] = [];
2018-06-13 06:02:15 +02:00
const encCiphers: Cipher[] = [];
for (const cipher of ciphers) {
cipher.organizationId = organizationId;
cipher.collectionIds = collectionIds;
promises.push(this.encrypt(cipher).then(c => {
2018-06-13 06:02:15 +02:00
encCiphers.push(c);
}));
}
await Promise.all(promises);
const request = new CipherBulkShareRequest(encCiphers, collectionIds);
await this.apiService.putShareCiphers(request);
const userId = await this.userService.getUserId();
await this.upsert(encCiphers.map(c => c.toCipherData(userId)));
2018-06-12 17:45:02 +02:00
}
2018-07-05 16:48:19 +02:00
saveAttachmentWithServer(cipher: Cipher, unencryptedFile: any, admin = false): Promise<Cipher> {
2018-01-10 05:01:16 +01:00
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsArrayBuffer(unencryptedFile);
reader.onload = async (evt: any) => {
try {
const cData = await this.saveAttachmentRawWithServer(cipher,
2018-07-05 16:48:19 +02:00
unencryptedFile.name, evt.target.result, admin);
resolve(cData);
2018-01-10 05:01:16 +01:00
} catch (e) {
reject(e);
2018-01-10 05:01:16 +01:00
}
};
reader.onerror = evt => {
2018-01-10 05:01:16 +01:00
reject('Error reading file.');
};
});
}
2018-07-05 16:48:19 +02:00
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);
2018-11-14 02:43:45 +01:00
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;
}
}
const userId = await this.userService.getUserId();
const cData = new CipherData(response, userId, cipher.collectionIds);
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) {
2018-05-31 15:07:56 +02:00
if (Utils.isNode && !Utils.isBrowser) {
fd.append('key', key.encryptedString);
fd.append('data', Buffer.from(encData.buffer) as any, {
2018-05-25 14:39:48 +02:00
filepath: encFileName.encryptedString,
contentType: 'application/octet-stream',
} as any);
} else {
throw e;
}
}
let response: CipherResponse;
try {
2018-07-05 16:48:19 +02:00
if (admin) {
response = await this.apiService.postCipherAttachmentAdminLegacy(cipherId, fd);
2018-07-05 16:48:19 +02:00
} else {
response = await this.apiService.postCipherAttachmentLegacy(cipherId, fd);
2018-07-05 16:48:19 +02:00
}
} catch (e) {
throw new Error((e as ErrorResponse).getSingleMessage());
}
return response;
}
2018-06-12 19:07:06 +02:00
async saveCollectionsWithServer(cipher: Cipher): Promise<any> {
const request = new CipherCollectionsRequest(cipher.collectionIds);
2018-07-05 16:48:19 +02:00
await this.apiService.putCipherCollections(cipher.id, request);
2018-06-12 19:07:06 +02:00
const userId = await this.userService.getUserId();
const data = cipher.toCipherData(userId);
await this.upsert(data);
}
2018-01-10 05:01:16 +01:00
async upsert(cipher: CipherData | CipherData[]): Promise<any> {
const userId = await this.userService.getUserId();
let ciphers = await this.storageService.get<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
if (ciphers == null) {
ciphers = {};
}
if (cipher instanceof CipherData) {
const c = cipher as CipherData;
ciphers[c.id] = c;
} else {
(cipher as CipherData[]).forEach(c => {
2018-01-10 05:01:16 +01:00
ciphers[c.id] = c;
});
}
await this.storageService.save(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
async replace(ciphers: { [id: string]: CipherData; }): Promise<any> {
const userId = await this.userService.getUserId();
await this.storageService.save(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
async clear(userId: string): Promise<any> {
await this.storageService.remove(Keys.ciphersPrefix + userId);
this.clearCache();
2018-01-10 05:01:16 +01:00
}
2018-06-12 23:12:27 +02:00
async moveManyWithServer(ids: string[], folderId: string): Promise<any> {
await this.apiService.putMoveCiphers(new CipherBulkMoveRequest(ids, folderId));
const userId = await this.userService.getUserId();
let ciphers = await this.storageService.get<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
if (ciphers == null) {
ciphers = {};
}
ids.forEach(id => {
2018-06-12 23:12:27 +02:00
if (ciphers.hasOwnProperty(id)) {
ciphers[id].folderId = folderId;
}
});
await this.storageService.save(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
2018-01-10 05:01:16 +01:00
async delete(id: string | string[]): Promise<any> {
const userId = await this.userService.getUserId();
const ciphers = await this.storageService.get<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
if (ciphers == null) {
return;
}
if (typeof id === 'string') {
2018-08-20 22:01:26 +02:00
if (ciphers[id] == null) {
return;
}
2018-01-10 05:01:16 +01:00
delete ciphers[id];
} else {
(id as string[]).forEach(i => {
2018-01-10 05:01:16 +01:00
delete ciphers[i];
});
}
await this.storageService.save(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
async deleteWithServer(id: string): Promise<any> {
await this.apiService.deleteCipher(id);
await this.delete(id);
}
2018-06-12 23:12:27 +02: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
async deleteAttachment(id: string, attachmentId: string): Promise<void> {
const userId = await this.userService.getUserId();
const ciphers = await this.storageService.get<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
if (ciphers == null || !ciphers.hasOwnProperty(id) || ciphers[id].attachments == null) {
return;
}
for (let i = 0; i < ciphers[id].attachments.length; i++) {
if (ciphers[id].attachments[i].id === attachmentId) {
ciphers[id].attachments.splice(i, 1);
}
}
await this.storageService.save(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
async deleteAttachmentWithServer(id: string, attachmentId: string): Promise<void> {
try {
await this.apiService.deleteCipherAttachment(id, attachmentId);
} catch (e) {
return Promise.reject((e as ErrorResponse).getSingleMessage());
}
await this.deleteAttachment(id, attachmentId);
}
2018-01-27 04:54:02 +01:00
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;
2019-04-17 05:32:02 +02:00
const bothNotNull = aLastUsed != null && bLastUsed != null;
if (bothNotNull && aLastUsed < bLastUsed) {
2018-01-27 04:54:02 +01:00
return 1;
}
if (aLastUsed != null && bLastUsed == null) {
return -1;
}
2019-04-17 05:32:02 +02:00
if (bothNotNull && aLastUsed > bLastUsed) {
2018-01-27 04:54:02 +01:00
return -1;
}
if (bLastUsed != null && aLastUsed == null) {
return 1;
}
return 0;
2018-01-10 05:01:16 +01:00
}
2018-01-27 04:54:02 +01:00
sortCiphersByLastUsedThenName(a: CipherView, b: CipherView): number {
const result = this.sortCiphersByLastUsed(a, b);
if (result !== 0) {
return result;
}
return this.getLocaleSortingFunction()(a, b);
2018-01-10 05:01:16 +01:00
}
2018-07-04 05:33:15 +02:00
getLocaleSortingFunction(): (a: CipherView, b: CipherView) => number {
return (a, b) => {
2018-01-27 04:54:02 +01:00
let aName = a.name;
let bName = b.name;
2018-03-20 00:42:38 +01:00
if (aName == null && bName != null) {
return -1;
}
if (aName != null && bName == null) {
return 1;
}
if (aName == null && bName == null) {
return 0;
}
2018-02-02 04:55:49 +01:00
const result = this.i18nService.collator ? this.i18nService.collator.compare(aName, bName) :
2018-01-27 04:54:02 +01:00
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 userId = await this.userService.getUserId();
const ciphers = await this.storageService.get<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
if (ciphers == null) {
return;
}
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);
}
await this.storageService.save(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
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 userId = await this.userService.getUserId();
const ciphers = await this.storageService.get<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
if (ciphers == null) {
return;
}
const clearDeletedDate = (c: { id: string, revisionDate: string; }) => {
if (ciphers[c.id] == null) {
return;
}
ciphers[c.id].deletedDate = null;
ciphers[c.id].revisionDate = c.revisionDate;
};
if (cipher.constructor.name === 'Array') {
(cipher as { id: string, revisionDate: string; }[]).forEach(clearDeletedDate);
} else {
clearDeletedDate(cipher as { id: string, revisionDate: string; });
}
await this.storageService.save(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
async restoreWithServer(id: string): Promise<any> {
const response = await this.apiService.putRestoreCipher(id);
await this.restore({ id: id, revisionDate: response.revisionDate });
}
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 });
}
await this.restore(restores);
}
2018-07-04 05:33:15 +02:00
// Helpers
private async shareAttachmentWithServer(attachmentView: AttachmentView, cipherId: string,
organizationId: string): Promise<any> {
const attachmentResponse = await this.apiService.nativeFetch(
2020-01-13 13:49:05 +01:00
new Request(attachmentView.url, { cache: 'no-store' }));
if (attachmentResponse.status !== 200) {
throw Error('Failed to download attachment: ' + attachmentResponse.status.toString());
}
const buf = await attachmentResponse.arrayBuffer();
const decBuf = await this.cryptoService.decryptFromBytes(buf, null);
const key = await this.cryptoService.getOrgKey(organizationId);
const encFileName = await this.cryptoService.encrypt(attachmentView.fileName, key);
2018-11-14 02:43:45 +01:00
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' });
2019-04-01 20:31:42 +02:00
fd.append('key', dataEncKey[1].encryptedString);
fd.append('data', blob, encFileName.encryptedString);
} catch (e) {
if (Utils.isNode && !Utils.isBrowser) {
2018-11-14 02:43:45 +01:00
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;
}
}
try {
await this.apiService.postShareCipherAttachment(cipherId, attachmentView.id, fd, organizationId);
} catch (e) {
throw new Error((e as ErrorResponse).getSingleMessage());
}
}
2018-01-24 17:33:15 +01:00
private async encryptObjProperty<V extends View, D extends Domain>(model: V, obj: D,
map: any, key: SymmetricCryptoKey): Promise<void> {
2018-01-10 05:01:16 +01:00
const promises = [];
const self = this;
for (const prop in map) {
if (!map.hasOwnProperty(prop)) {
continue;
}
// tslint:disable-next-line
(function (theProp, theObj) {
const p = Promise.resolve().then(() => {
2018-01-24 17:33:15 +01:00
const modelProp = (model as any)[(map[theProp] || theProp)];
2018-01-10 05:01:16 +01:00
if (modelProp && modelProp !== '') {
return self.cryptoService.encrypt(modelProp, key);
}
return null;
}).then((val: EncString) => {
2018-01-24 17:33:15 +01:00
(theObj as any)[theProp] = val;
2018-01-10 05:01:16 +01:00
});
promises.push(p);
})(prop, obj);
}
2018-01-24 17:33:15 +01:00
await Promise.all(promises);
2018-01-10 05:01:16 +01:00
}
2018-01-24 17:33:15 +01:00
private async encryptCipherData(cipher: Cipher, model: CipherView, key: SymmetricCryptoKey) {
2018-01-10 05:01:16 +01:00
switch (cipher.type) {
case CipherType.Login:
2018-01-24 19:27:32 +01:00
cipher.login = new Login();
cipher.login.passwordRevisionDate = model.login.passwordRevisionDate;
cipher.login.autofillOnPageLoad = model.login.autofillOnPageLoad;
2018-01-24 17:33:15 +01:00
await this.encryptObjProperty(model.login, cipher.login, {
2018-01-10 05:01:16 +01:00
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-24 17:33:15 +01:00
return;
2018-01-10 05:01:16 +01:00
case CipherType.SecureNote:
2018-01-24 19:27:32 +01:00
cipher.secureNote = new SecureNote();
cipher.secureNote.type = model.secureNote.type;
2018-01-24 17:33:15 +01:00
return;
2018-01-10 05:01:16 +01:00
case CipherType.Card:
2018-01-24 19:27:32 +01:00
cipher.card = new Card();
2018-01-24 17:33:15 +01:00
await this.encryptObjProperty(model.card, cipher.card, {
2018-01-10 05:01:16 +01:00
cardholderName: null,
brand: null,
number: null,
expMonth: null,
expYear: null,
code: null,
}, key);
2018-01-24 17:33:15 +01:00
return;
2018-01-10 05:01:16 +01:00
case CipherType.Identity:
2018-01-24 19:27:32 +01:00
cipher.identity = new Identity();
2018-01-24 17:33:15 +01:00
await this.encryptObjProperty(model.identity, cipher.identity, {
2018-01-10 05:01:16 +01:00
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);
2018-01-24 17:33:15 +01:00
return;
2018-01-10 05:01:16 +01:00
default:
throw new Error('Unknown cipher type.');
}
}
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.storageService.get(ConstantsService.autoFillOnPageLoadDefaultKey);
ciphers = ciphers.filter(cipher => cipher.login.autofillOnPageLoad ||
(cipher.login.autofillOnPageLoad == null && autofillOnPageLoadDefault !== false));
if (ciphers.length === 0) {
return null;
}
}
this.sortedCiphersCache.addCiphers(cacheKey, ciphers);
}
if (lastLaunched) {
return this.sortedCiphersCache.getLastLaunched(cacheKey);
} else if (lastUsed) {
return this.sortedCiphersCache.getLastUsed(cacheKey);
} else {
return this.sortedCiphersCache.getNext(cacheKey);
}
}
2018-01-10 05:01:16 +01:00
}