1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-12-29 17:38:04 +01:00

convert cipher service to ts

This commit is contained in:
Kyle Spearrin 2017-11-06 10:58:32 -05:00
parent 38e235302c
commit b05426f953
13 changed files with 543 additions and 23 deletions

View File

@ -1,7 +1,7 @@
// Service imports
import ApiService from './services/api.service';
import AppIdService from './services/appId.service';
import CipherService from './services/cipherService.js';
import CipherService from './services/cipher.service';
import ConstantsService from './services/constants.service';
import CryptoService from './services/crypto.service';
import EnvironmentService from './services/environment.service';
@ -99,8 +99,7 @@ var bg_isBackground = true,
window.bg_environmentService = bg_environmentService = new EnvironmentService(bg_apiService);
window.bg_userService = bg_userService = new UserService(bg_tokenService);
window.bg_settingsService = bg_settingsService = new SettingsService(bg_userService);
window.bg_cipherService = bg_cipherService = new CipherService(bg_cryptoService, bg_userService, bg_apiService, bg_settingsService, bg_utilsService,
bg_constantsService);
window.bg_cipherService = bg_cipherService = new CipherService(bg_cryptoService, bg_userService, bg_settingsService, bg_apiService);
window.bg_folderService = bg_folderService = new FolderService(bg_cryptoService, bg_userService, bg_i18nService, bg_apiService);
window.bg_lockService = bg_lockService = new LockService(bg_constantsService, bg_cryptoService, bg_folderService, bg_cipherService, bg_utilsService,
setIcon, refreshBadgeAndMenu);

View File

@ -1,3 +1,5 @@
import { CipherType } from '../../enums/cipherType.enum';
import { AttachmentData } from './attachmentData';
import { CardData } from './cardData';
import { FieldData } from './fieldData';
@ -16,7 +18,7 @@ class CipherData {
organizationUseTotp: boolean;
favorite: boolean;
revisionDate: string;
type: number; // TODO: enum
type: CipherType;
sizeName: string;
name: string;
notes: string;
@ -41,32 +43,31 @@ class CipherData {
this.name = response.data.Name;
this.notes = response.data.Notes;
const constantsService = chrome.extension.getBackgroundPage().bg_constantsService; // TODO: enum
switch (this.type) {
case constantsService.cipherType.login:
case CipherType.Login:
this.login = new LoginData(response.data);
break;
case constantsService.cipherType.secureNote:
case CipherType.SecureNote:
this.secureNote = new SecureNoteData(response.data);
break;
case constantsService.cipherType.card:
case CipherType.Card:
this.card = new CardData(response.data);
break;
case constantsService.cipherType.identity:
case CipherType.Identity:
this.identity = new IdentityData(response.data);
break;
default:
break;
}
if (response.data.Fields) {
if (response.data.Fields != null) {
this.fields = [];
for (const field of response.data.Fields) {
this.fields.push(new FieldData(field));
}
}
if (response.attachments) {
if (response.attachments != null) {
this.attachments = [];
for (const attachment of response.attachments) {
this.attachments.push(new AttachmentData(attachment));

View File

@ -33,7 +33,7 @@ class Attachment extends Domain {
url: this.url,
};
return this.decryptObj(model, this, {
return this.decryptObj(model, {
fileName: null,
}, orgId);
}

View File

@ -28,7 +28,7 @@ class Card extends Domain {
}
decrypt(orgId: string): Promise<any> {
return this.decryptObj({}, this, {
return this.decryptObj({}, {
cardholderName: null,
brand: null,
number: null,

View File

@ -103,7 +103,7 @@ class Cipher extends Domain {
fields: null as any[],
};
await this.decryptObj(model, this, {
await this.decryptObj(model, {
name: null,
notes: null,
}, this.organizationId);

View File

@ -16,8 +16,10 @@ export default abstract class Domain {
}
}
protected async decryptObj(model: any, self: any, map: any, orgId: string) {
protected async decryptObj(model: any, map: any, orgId: string) {
const promises = [];
const self: any = this;
for (const prop in map) {
if (!map.hasOwnProperty(prop)) {
continue;
@ -33,7 +35,6 @@ export default abstract class Domain {
return null;
}).then((val: any) => {
model[theProp] = val;
return;
});
promises.push(p);
})(prop);

View File

@ -28,7 +28,7 @@ class Field extends Domain {
type: this.type,
};
return this.decryptObj(model, this, {
return this.decryptObj(model, {
name: null,
value: null,
}, orgId);

View File

@ -24,7 +24,7 @@ class Folder extends Domain {
id: this.id,
};
return this.decryptObj(model, this, {
return this.decryptObj(model, {
name: null,
}, null);
}

View File

@ -52,7 +52,7 @@ class Identity extends Domain {
}
decrypt(orgId: string): Promise<any> {
return this.decryptObj({}, this, {
return this.decryptObj({}, {
title: null,
firstName: null,
middleName: null,

View File

@ -24,7 +24,7 @@ class Login extends Domain {
}
decrypt(orgId: string): Promise<any> {
return this.decryptObj({}, this, {
return this.decryptObj({}, {
uri: null,
username: null,
password: null,

View File

@ -10,7 +10,7 @@ class CipherResponse {
organizationUseTotp: boolean;
data: any;
revisionDate: string;
attachments: AttachmentResponse[] = [];
attachments: AttachmentResponse[];
constructor(response: any) {
this.id = response.Id;
@ -23,7 +23,8 @@ class CipherResponse {
this.data = response.Data;
this.revisionDate = response.RevisionDate;
if (response.Attachments) {
if (response.Attachments != null) {
this.attachments = [];
for (const attachment of response.Attachments) {
this.attachments.push(new AttachmentResponse(attachment));
}

View File

@ -43,7 +43,7 @@ angular
}
}
if (model.login.totp && (cipherObj.organizationUseTotp || tokenService.getPremium())) {
if (model.login && model.login.totp && (cipherObj.organizationUseTotp || tokenService.getPremium())) {
totpUpdateCode();
totpTick();

View File

@ -0,0 +1,518 @@
import { CipherType } from '../enums/cipherType.enum';
import { Cipher } from '../models/domain/cipher';
import { CipherString } from '../models/domain/cipherString';
import { Field } from '../models/domain/field';
import SymmetricCryptoKey from '../models/domain/symmetricCryptoKey';
import { CipherData } from '../models/data/cipherData';
import { CipherRequest } from '../models/request/cipherRequest';
import { CipherResponse } from '../models/response/cipherResponse';
import { ErrorResponse } from '../models/response/errorResponse';
import ApiService from './api.service';
import ConstantsService from './constants.service';
import CryptoService from './crypto.service';
import SettingsService from './settings.service';
import UserService from './user.service';
import UtilsService from './utils.service';
const Keys = {
ciphersPrefix: 'ciphers_',
localData: 'sitesLocalData',
neverDomains: 'neverDomains',
};
export default class CipherService {
static sortCiphersByLastUsed(a: any, b: any): 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;
if (aLastUsed != null && bLastUsed != null && aLastUsed < bLastUsed) {
return 1;
}
if (aLastUsed != null && bLastUsed == null) {
return -1;
}
if (bLastUsed != null && aLastUsed != null && aLastUsed > bLastUsed) {
return -1;
}
if (bLastUsed != null && aLastUsed == null) {
return 1;
}
return 0;
}
static sortCiphersByLastUsedThenName(a: any, b: any): number {
const result = CipherService.sortCiphersByLastUsed(a, b);
if (result !== 0) {
return result;
}
const nameA = (a.name + '_' + a.username).toUpperCase();
const nameB = (b.name + '_' + b.username).toUpperCase();
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
return 0;
}
decryptedCipherCache: any[];
constructor(private cryptoService: CryptoService, private userService: UserService,
private settingsService: SettingsService, private apiService: ApiService) {
}
clearCache(): void {
this.decryptedCipherCache = null;
}
async encrypt(model: any): Promise<Cipher> {
const cipher = new Cipher();
cipher.id = model.id;
cipher.folderId = model.folderId;
cipher.favorite = model.favorite;
cipher.organizationId = model.organizationId;
cipher.type = model.type;
const key = await this.cryptoService.getOrgKey(cipher.organizationId);
await Promise.all([
this.encryptObjProperty(model, cipher, {
name: null,
notes: null,
}, key),
this.encryptCipherData(model, cipher, key),
this.encryptFields(model.fields, key).then((fields) => {
cipher.fields = fields;
}),
]);
return cipher;
}
async encryptFields(fieldsModel: any[], key: SymmetricCryptoKey): Promise<Field[]> {
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;
}
async encryptField(fieldModel: any, key: SymmetricCryptoKey): Promise<Field> {
const field = new Field();
field.type = fieldModel.type;
await this.encryptObjProperty(fieldModel, field, {
name: null,
value: null,
}, key);
return field;
}
async get(id: string): Promise<Cipher> {
const userId = await this.userService.getUserId();
const localData = await UtilsService.getObjFromStorage<any>(Keys.localData);
const ciphers = await UtilsService.getObjFromStorage<{ [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 UtilsService.getObjFromStorage<any>(Keys.localData);
const ciphers = await UtilsService.getObjFromStorage<{ [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;
}
async getAllDecrypted(): Promise<any[]> {
if (this.decryptedCipherCache != null) {
return this.decryptedCipherCache;
}
const decCiphers: any[] = [];
const key = await this.cryptoService.getKey();
if (key == null) {
throw new Error('No key.');
}
const promises = [];
const ciphers = await this.getAll();
for (const cipher of ciphers) {
promises.push(cipher.decrypt().then((c: any) => {
decCiphers.push(c);
}));
}
await Promise.all(promises);
this.decryptedCipherCache = decCiphers;
return this.decryptedCipherCache;
}
async getAllDecryptedForFolder(folderId: string): Promise<any[]> {
const ciphers = await this.getAllDecrypted();
const ciphersToReturn = [];
for (const cipher of ciphers) {
if (cipher.folderId === folderId) {
ciphersToReturn.push(cipher);
}
}
return ciphersToReturn;
}
async getAllDecryptedForDomain(domain: string, includeOtherTypes?: any[]): Promise<any[]> {
if (domain == null && !includeOtherTypes) {
return Promise.resolve([]);
}
const eqDomainsPromise = domain == null ? Promise.resolve([]) :
this.settingsService.getEquivalentDomains().then((eqDomains: any[][]) => {
let matches: any[] = [];
for (const eqDomain of eqDomains) {
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];
const ciphersToReturn = [];
for (const cipher of ciphers) {
if (domain && cipher.type === CipherType.Login && cipher.login.domain &&
matchingDomains.indexOf(cipher.login.domain) > -1) {
ciphersToReturn.push(cipher);
} else if (includeOtherTypes && includeOtherTypes.indexOf(cipher.type) > -1) {
ciphersToReturn.push(cipher);
}
}
return ciphersToReturn;
}
async getLastUsedForDomain(domain: string): Promise<any> {
const ciphers = await this.getAllDecryptedForDomain(domain);
if (ciphers.length === 0) {
throw new Error('No ciphers.');
}
const sortedCiphers = ciphers.sort(CipherService.sortCiphersByLastUsed);
return sortedCiphers[0];
}
async updateLastUsedDate(id: string): Promise<void> {
let ciphersLocalData = await UtilsService.getObjFromStorage<any>(Keys.localData);
if (!ciphersLocalData) {
ciphersLocalData = {};
}
if (ciphersLocalData[id]) {
ciphersLocalData[id].lastUsedDate = new Date().getTime();
} else {
ciphersLocalData[id] = {
lastUsedDate: new Date().getTime(),
};
}
await UtilsService.saveObjToStorage(Keys.localData, ciphersLocalData);
if (this.decryptedCipherCache == null) {
return;
}
for (const cached of this.decryptedCipherCache) {
if (cached.id === id) {
cached.localData = ciphersLocalData[id];
break;
}
}
}
async saveNeverDomain(domain: string): Promise<void> {
if (domain == null) {
return;
}
let domains = await UtilsService.getObjFromStorage<{ [id: string]: any; }>(Keys.neverDomains);
if (!domains) {
domains = {};
}
domains[domain] = null;
await UtilsService.saveObjToStorage(Keys.neverDomains, domains);
}
async saveWithServer(cipher: Cipher): Promise<any> {
const request = new CipherRequest(cipher);
let response: CipherResponse;
if (cipher.id == null) {
response = await this.apiService.postCipher(request);
cipher.id = response.id;
} else {
response = await this.apiService.putCipher(cipher.id, request);
}
const userId = await this.userService.getUserId();
const data = new CipherData(response, userId);
await this.upsert(data);
}
saveAttachmentWithServer(cipher: Cipher, unencryptedFile: any): Promise<any> {
const self = this;
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsArrayBuffer(unencryptedFile);
reader.onload = async (evt: any) => {
const key = await self.cryptoService.getOrgKey(cipher.organizationId);
const encFileName = await self.cryptoService.encrypt(unencryptedFile.name, key);
const encData = await self.cryptoService.encryptToBytes(evt.target.result, key);
const fd = new FormData();
const blob = new Blob([encData], { type: 'application/octet-stream' });
fd.append('data', blob, encFileName.encryptedString);
const response = await self.apiService.postCipherAttachment(cipher.id, fd);
// TODO: handle error response
const userId = await self.userService.getUserId();
const data = new CipherData(response, userId);
this.upsert(data);
resolve(new Cipher(data));
};
reader.onerror = (evt) => {
reject('Error reading file.');
};
});
}
async upsert(cipher: CipherData | CipherData[]): Promise<any> {
const userId = await this.userService.getUserId();
let ciphers = await UtilsService.getObjFromStorage<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
if (ciphers == null) {
ciphers = {};
}
if (cipher instanceof CipherData) {
const c = cipher as CipherData;
ciphers[c.id] = c;
} else {
for (const c of (cipher as CipherData[])) {
ciphers[c.id] = c;
}
}
await UtilsService.saveObjToStorage(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
async replace(ciphers: CipherData[]): Promise<any> {
const userId = await this.userService.getUserId();
await UtilsService.saveObjToStorage(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
async clear(userId: string): Promise<any> {
await UtilsService.removeFromStorage(Keys.ciphersPrefix + userId);
this.decryptedCipherCache = null;
}
async delete(id: string | string[]): Promise<any> {
const userId = await this.userService.getUserId();
const ciphers = await UtilsService.getObjFromStorage<{ [id: string]: CipherData; }>(
Keys.ciphersPrefix + userId);
if (ciphers == null) {
return;
}
if (typeof id === 'string') {
const i = id as string;
delete ciphers[id];
} else {
for (const i of (id as string[])) {
delete ciphers[i];
}
}
await UtilsService.saveObjToStorage(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
async deleteWithServer(id: string): Promise<any> {
await this.apiService.deleteCipher(id);
await this.delete(id);
}
async deleteAttachment(id: string, attachmentId: string): Promise<void> {
const userId = await this.userService.getUserId();
const ciphers = await UtilsService.getObjFromStorage<{ [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 UtilsService.saveObjToStorage(Keys.ciphersPrefix + userId, ciphers);
this.decryptedCipherCache = null;
}
async deleteAttachmentWithServer(id: string, attachmentId: string): Promise<void> {
await this.apiService.deleteCipherAttachment(id, attachmentId);
await this.deleteAttachment(id, attachmentId);
// TODO: handle error
}
// TODO: remove in favor of static refs
sortCiphersByLastUsed(a: any, b: any): number {
return CipherService.sortCiphersByLastUsed(a, b);
}
sortCiphersByLastUsedThenName(a: any, b: any): number {
return CipherService.sortCiphersByLastUsedThenName(a, b);
}
// Helpers
private encryptObjProperty(model: any, obj: any, map: any, key: SymmetricCryptoKey): Promise<void[]> {
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(() => {
const modelProp = model[(map[theProp] || theProp)];
if (modelProp && modelProp !== '') {
return self.cryptoService.encrypt(modelProp, key);
}
return null;
}).then((val: CipherString) => {
theObj[theProp] = val;
});
promises.push(p);
})(prop, obj);
}
return Promise.all(promises);
}
private encryptCipherData(cipher: Cipher, model: any, key: SymmetricCryptoKey): Promise<any> {
switch (cipher.type) {
case CipherType.Login:
model.login = {};
return this.encryptObjProperty(cipher.login, model.login, {
uri: null,
username: null,
password: null,
totp: null,
}, key);
case CipherType.SecureNote:
model.secureNote = {
type: cipher.secureNote.type,
};
return Promise.resolve();
case CipherType.Card:
model.card = {};
return this.encryptObjProperty(cipher.card, model.card, {
cardholderName: null,
brand: null,
number: null,
expMonth: null,
expYear: null,
code: null,
}, key);
case CipherType.Identity:
model.identity = {};
return this.encryptObjProperty(cipher.identity, model.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);
default:
throw new Error('Unknown cipher type.');
}
}
private handleErrorMessage(error: ErrorResponse, reject: Function): void {
if (error.validationErrors) {
for (const key in error.validationErrors) {
if (!error.validationErrors.hasOwnProperty(key)) {
continue;
}
if (error.validationErrors[key].length) {
reject(error.validationErrors[key][0]);
return;
}
}
}
reject(error.message);
return;
}
}