1
0
mirror of https://github.com/bitwarden/browser.git synced 2024-11-30 13:03:53 +01:00

convert domain models to jslib

This commit is contained in:
Kyle Spearrin 2018-01-08 15:23:36 -05:00
parent 5d39030e05
commit e68f7a1141
26 changed files with 90 additions and 884 deletions

View File

@ -1,7 +1,5 @@
import { Abstractions, Enums, Services } from '@bitwarden/jslib'; import { Abstractions, Enums, Services } from '@bitwarden/jslib';
import { Cipher } from '../models/domain/cipher';
import BrowserApi from '../browser/browserApi'; import BrowserApi from '../browser/browserApi';
import CommandsBackground from './commands.background'; import CommandsBackground from './commands.background';

View File

@ -1,43 +0,0 @@
import { Data } from '@bitwarden/jslib';
import { CipherString } from './cipherString';
import Domain from './domain';
class Attachment extends Domain {
id: string;
url: string;
size: number;
sizeName: string;
fileName: CipherString;
constructor(obj?: Data.Attachment, alreadyEncrypted: boolean = false) {
super();
if (obj == null) {
return;
}
this.size = obj.size;
this.buildDomainModel(this, obj, {
id: null,
url: null,
sizeName: null,
fileName: null,
}, alreadyEncrypted, ['id', 'url', 'sizeName']);
}
decrypt(orgId: string): Promise<any> {
const model = {
id: this.id,
size: this.size,
sizeName: this.sizeName,
url: this.url,
};
return this.decryptObj(model, {
fileName: null,
}, orgId);
}
}
export { Attachment };
(window as any).Attachment = Attachment;

View File

@ -1,43 +0,0 @@
import { Data } from '@bitwarden/jslib';
import { CipherString } from './cipherString';
import Domain from './domain';
class Card extends Domain {
cardholderName: CipherString;
brand: CipherString;
number: CipherString;
expMonth: CipherString;
expYear: CipherString;
code: CipherString;
constructor(obj?: Data.Card, alreadyEncrypted: boolean = false) {
super();
if (obj == null) {
return;
}
this.buildDomainModel(this, obj, {
cardholderName: null,
brand: null,
number: null,
expMonth: null,
expYear: null,
code: null,
}, alreadyEncrypted, []);
}
decrypt(orgId: string): Promise<any> {
return this.decryptObj({}, {
cardholderName: null,
brand: null,
number: null,
expMonth: null,
expYear: null,
code: null,
}, orgId);
}
}
export { Card };
(window as any).Card = Card;

View File

@ -1,188 +0,0 @@
import { Abstractions, Enums, Data } from '@bitwarden/jslib';
import { Attachment } from './attachment';
import { Card } from './card';
import { CipherString } from './cipherString';
import Domain from './domain';
import { Field } from './field';
import { Identity } from './identity';
import { Login } from './login';
import { SecureNote } from './secureNote';
class Cipher extends Domain {
id: string;
organizationId: string;
folderId: string;
name: CipherString;
notes: CipherString;
type: Enums.CipherType;
favorite: boolean;
organizationUseTotp: boolean;
edit: boolean;
localData: any;
login: Login;
identity: Identity;
card: Card;
secureNote: SecureNote;
attachments: Attachment[];
fields: Field[];
collectionIds: string[];
constructor(obj?: Data.Cipher, alreadyEncrypted: boolean = false, localData: any = null) {
super();
if (obj == null) {
return;
}
this.buildDomainModel(this, obj, {
id: null,
organizationId: null,
folderId: null,
name: null,
notes: null,
}, alreadyEncrypted, ['id', 'organizationId', 'folderId']);
this.type = obj.type;
this.favorite = obj.favorite;
this.organizationUseTotp = obj.organizationUseTotp;
this.edit = obj.edit;
this.collectionIds = obj.collectionIds;
this.localData = localData;
switch (this.type) {
case Enums.CipherType.Login:
this.login = new Login(obj.login, alreadyEncrypted);
break;
case Enums.CipherType.SecureNote:
this.secureNote = new SecureNote(obj.secureNote, alreadyEncrypted);
break;
case Enums.CipherType.Card:
this.card = new Card(obj.card, alreadyEncrypted);
break;
case Enums.CipherType.Identity:
this.identity = new Identity(obj.identity, alreadyEncrypted);
break;
default:
break;
}
if (obj.attachments != null) {
this.attachments = [];
obj.attachments.forEach((attachment) => {
this.attachments.push(new Attachment(attachment, alreadyEncrypted));
});
} else {
this.attachments = null;
}
if (obj.fields != null) {
this.fields = [];
obj.fields.forEach((field) => {
this.fields.push(new Field(field, alreadyEncrypted));
});
} else {
this.fields = null;
}
}
async decrypt(): Promise<any> {
const model = {
id: this.id,
organizationId: this.organizationId,
folderId: this.folderId,
favorite: this.favorite,
type: this.type,
localData: this.localData,
login: null as any,
card: null as any,
identity: null as any,
secureNote: null as any,
subTitle: null as string,
attachments: null as any[],
fields: null as any[],
collectionIds: this.collectionIds,
};
await this.decryptObj(model, {
name: null,
notes: null,
}, this.organizationId);
switch (this.type) {
case Enums.CipherType.Login:
model.login = await this.login.decrypt(this.organizationId);
model.subTitle = model.login.username;
if (model.login.uri) {
const containerService = (window as any).BitwardenContainerService;
if (containerService) {
const platformUtilsService: Abstractions.PlatformUtilsService =
containerService.getPlatformUtilsService();
model.login.domain = platformUtilsService.getDomain(model.login.uri);
} else {
throw new Error('window.BitwardenContainerService not initialized.');
}
}
break;
case Enums.CipherType.SecureNote:
model.secureNote = await this.secureNote.decrypt(this.organizationId);
model.subTitle = null;
break;
case Enums.CipherType.Card:
model.card = await this.card.decrypt(this.organizationId);
model.subTitle = model.card.brand;
if (model.card.number && model.card.number.length >= 4) {
if (model.subTitle !== '') {
model.subTitle += ', ';
}
model.subTitle += ('*' + model.card.number.substr(model.card.number.length - 4));
}
break;
case Enums.CipherType.Identity:
model.identity = await this.identity.decrypt(this.organizationId);
model.subTitle = '';
if (model.identity.firstName) {
model.subTitle = model.identity.firstName;
}
if (model.identity.lastName) {
if (model.subTitle !== '') {
model.subTitle += ' ';
}
model.subTitle += model.identity.lastName;
}
break;
default:
break;
}
const orgId = this.organizationId;
if (this.attachments != null && this.attachments.length > 0) {
const attachments: any[] = [];
await this.attachments.reduce((promise, attachment) => {
return promise.then(() => {
return attachment.decrypt(orgId);
}).then((decAttachment) => {
attachments.push(decAttachment);
});
}, Promise.resolve());
model.attachments = attachments;
}
if (this.fields != null && this.fields.length > 0) {
const fields: any[] = [];
await this.fields.reduce((promise, field) => {
return promise.then(() => {
return field.decrypt(orgId);
}).then((decField) => {
fields.push(decField);
});
}, Promise.resolve());
model.fields = fields;
}
return model;
}
}
export { Cipher };
(window as any).Cipher = Cipher;

View File

@ -1,116 +0,0 @@
import { Enums } from '@bitwarden/jslib';
import { CryptoService } from '../../services/abstractions/crypto.service';
class CipherString {
encryptedString?: string;
encryptionType?: Enums.EncryptionType;
decryptedValue?: string;
cipherText?: string;
initializationVector?: string;
mac?: string;
constructor(encryptedStringOrType: string | Enums.EncryptionType, ct?: string, iv?: string, mac?: string) {
if (ct != null) {
// ct and header
const encType = encryptedStringOrType as Enums.EncryptionType;
this.encryptedString = encType + '.' + ct;
// iv
if (iv != null) {
this.encryptedString += ('|' + iv);
}
// mac
if (mac != null) {
this.encryptedString += ('|' + mac);
}
this.encryptionType = encType;
this.cipherText = ct;
this.initializationVector = iv;
this.mac = mac;
return;
}
this.encryptedString = encryptedStringOrType as string;
if (!this.encryptedString) {
return;
}
const headerPieces = this.encryptedString.split('.');
let encPieces: string[] = null;
if (headerPieces.length === 2) {
try {
this.encryptionType = parseInt(headerPieces[0], null);
encPieces = headerPieces[1].split('|');
} catch (e) {
return;
}
} else {
encPieces = this.encryptedString.split('|');
this.encryptionType = encPieces.length === 3 ? Enums.EncryptionType.AesCbc128_HmacSha256_B64 :
Enums.EncryptionType.AesCbc256_B64;
}
switch (this.encryptionType) {
case Enums.EncryptionType.AesCbc128_HmacSha256_B64:
case Enums.EncryptionType.AesCbc256_HmacSha256_B64:
if (encPieces.length !== 3) {
return;
}
this.initializationVector = encPieces[0];
this.cipherText = encPieces[1];
this.mac = encPieces[2];
break;
case Enums.EncryptionType.AesCbc256_B64:
if (encPieces.length !== 2) {
return;
}
this.initializationVector = encPieces[0];
this.cipherText = encPieces[1];
break;
case Enums.EncryptionType.Rsa2048_OaepSha256_B64:
case Enums.EncryptionType.Rsa2048_OaepSha1_B64:
if (encPieces.length !== 1) {
return;
}
this.cipherText = encPieces[0];
break;
default:
return;
}
}
decrypt(orgId: string): Promise<string> {
if (this.decryptedValue) {
return Promise.resolve(this.decryptedValue);
}
let cryptoService: CryptoService;
const containerService = (window as any).BitwardenContainerService;
if (containerService) {
cryptoService = containerService.getCryptoService();
} else {
throw new Error('window.BitwardenContainerService not initialized.');
}
return cryptoService.getOrgKey(orgId).then((orgKey: any) => {
return cryptoService.decrypt(this, orgKey);
}).then((decValue: any) => {
this.decryptedValue = decValue;
return this.decryptedValue;
}).catch(() => {
this.decryptedValue = '[error: cannot decrypt]';
return this.decryptedValue;
});
}
}
export { CipherString };
(window as any).CipherString = CipherString;

View File

@ -1,37 +0,0 @@
import { Data } from '@bitwarden/jslib';
import { CipherString } from './cipherString';
import Domain from './domain';
class Collection extends Domain {
id: string;
organizationId: string;
name: CipherString;
constructor(obj?: Data.Collection, alreadyEncrypted: boolean = false) {
super();
if (obj == null) {
return;
}
this.buildDomainModel(this, obj, {
id: null,
organizationId: null,
name: null,
}, alreadyEncrypted, ['id', 'organizationId']);
}
decrypt(): Promise<any> {
const model = {
id: this.id,
organizationId: this.organizationId,
};
return this.decryptObj(model, {
name: null,
}, this.organizationId);
}
}
export { Collection };
(window as any).Collection = Collection;

View File

@ -1,46 +0,0 @@
import { CipherString } from '../domain/cipherString';
export default abstract class Domain {
protected buildDomainModel(model: any, obj: any, map: any, alreadyEncrypted: boolean, notEncList: any[] = []) {
for (const prop in map) {
if (!map.hasOwnProperty(prop)) {
continue;
}
const objProp = obj[(map[prop] || prop)];
if (alreadyEncrypted === true || notEncList.indexOf(prop) > -1) {
model[prop] = objProp ? objProp : null;
} else {
model[prop] = objProp ? new CipherString(objProp) : null;
}
}
}
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;
}
// tslint:disable-next-line
(function (theProp) {
const p = Promise.resolve().then(() => {
const mapProp = map[theProp] || theProp;
if (self[mapProp]) {
return self[mapProp].decrypt(orgId);
}
return null;
}).then((val: any) => {
model[theProp] = val;
});
promises.push(p);
})(prop);
}
await Promise.all(promises);
return model;
}
}

View File

@ -1,8 +0,0 @@
import SymmetricCryptoKey from './symmetricCryptoKey';
export default class EncryptedObject {
iv: Uint8Array;
ct: Uint8Array;
mac: Uint8Array;
key: SymmetricCryptoKey;
}

View File

@ -1,5 +0,0 @@
export default class EnvironmentUrls {
base: string;
api: string;
identity: string;
}

View File

@ -1,37 +0,0 @@
import { Enums, Data } from '@bitwarden/jslib';
import { CipherString } from './cipherString';
import Domain from './domain';
class Field extends Domain {
name: CipherString;
vault: CipherString;
type: Enums.FieldType;
constructor(obj?: Data.Field, alreadyEncrypted: boolean = false) {
super();
if (obj == null) {
return;
}
this.type = obj.type;
this.buildDomainModel(this, obj, {
name: null,
value: null,
}, alreadyEncrypted, []);
}
decrypt(orgId: string): Promise<any> {
const model = {
type: this.type,
};
return this.decryptObj(model, {
name: null,
value: null,
}, orgId);
}
}
export { Field };
(window as any).Field = Field;

View File

@ -1,79 +0,0 @@
import { Data } from '@bitwarden/jslib';
import { CipherString } from './cipherString';
import Domain from './domain';
class Identity extends Domain {
title: CipherString;
firstName: CipherString;
middleName: CipherString;
lastName: CipherString;
address1: CipherString;
address2: CipherString;
address3: CipherString;
city: CipherString;
state: CipherString;
postalCode: CipherString;
country: CipherString;
company: CipherString;
email: CipherString;
phone: CipherString;
ssn: CipherString;
username: CipherString;
passportNumber: CipherString;
licenseNumber: CipherString;
constructor(obj?: Data.Identity, alreadyEncrypted: boolean = false) {
super();
if (obj == null) {
return;
}
this.buildDomainModel(this, obj, {
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,
}, alreadyEncrypted, []);
}
decrypt(orgId: string): Promise<any> {
return this.decryptObj({}, {
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,
}, orgId);
}
}
export { Identity };
(window as any).Identity = Identity;

View File

@ -1,37 +0,0 @@
import { Data } from '@bitwarden/jslib';
import { CipherString } from './cipherString';
import Domain from './domain';
class Login extends Domain {
uri: CipherString;
username: CipherString;
password: CipherString;
totp: CipherString;
constructor(obj?: Data.Login, alreadyEncrypted: boolean = false) {
super();
if (obj == null) {
return;
}
this.buildDomainModel(this, obj, {
uri: null,
username: null,
password: null,
totp: null,
}, alreadyEncrypted, []);
}
decrypt(orgId: string): Promise<any> {
return this.decryptObj({}, {
uri: null,
username: null,
password: null,
totp: null,
}, orgId);
}
}
export { Login };
(window as any).Login = Login;

View File

@ -1,9 +0,0 @@
export default class PasswordHistory {
password: string;
date: number;
constructor(password: string, date: number) {
this.password = password;
this.date = date;
}
}

View File

@ -1,25 +0,0 @@
import { Enums, Data } from '@bitwarden/jslib';
import Domain from './domain';
class SecureNote extends Domain {
type: Enums.SecureNoteType;
constructor(obj?: Data.SecureNote, alreadyEncrypted: boolean = false) {
super();
if (obj == null) {
return;
}
this.type = obj.type;
}
decrypt(orgId: string): any {
return {
type: this.type,
};
}
}
export { SecureNote };
(window as any).SecureNote = SecureNote;

View File

@ -1,78 +0,0 @@
import * as forge from 'node-forge';
import { Enums, Services } from '@bitwarden/jslib';
import SymmetricCryptoKeyBuffers from './symmetricCryptoKeyBuffers';
export default class SymmetricCryptoKey {
key: string;
keyB64: string;
encKey: string;
macKey: string;
encType: Enums.EncryptionType;
keyBuf: SymmetricCryptoKeyBuffers;
constructor(keyBytes: string, b64KeyBytes?: boolean, encType?: Enums.EncryptionType) {
if (b64KeyBytes) {
keyBytes = forge.util.decode64(keyBytes);
}
if (!keyBytes) {
throw new Error('Must provide keyBytes');
}
const buffer = (forge as any).util.createBuffer(keyBytes);
if (!buffer || buffer.length() === 0) {
throw new Error('Couldn\'t make buffer');
}
const bufferLength: number = buffer.length();
if (encType == null) {
if (bufferLength === 32) {
encType = Enums.EncryptionType.AesCbc256_B64;
} else if (bufferLength === 64) {
encType = Enums.EncryptionType.AesCbc256_HmacSha256_B64;
} else {
throw new Error('Unable to determine encType.');
}
}
this.key = keyBytes;
this.keyB64 = forge.util.encode64(keyBytes);
this.encType = encType;
if (encType === Enums.EncryptionType.AesCbc256_B64 && bufferLength === 32) {
this.encKey = keyBytes;
this.macKey = null;
} else if (encType === Enums.EncryptionType.AesCbc128_HmacSha256_B64 && bufferLength === 32) {
this.encKey = buffer.getBytes(16); // first half
this.macKey = buffer.getBytes(16); // second half
} else if (encType === Enums.EncryptionType.AesCbc256_HmacSha256_B64 && bufferLength === 64) {
this.encKey = buffer.getBytes(32); // first half
this.macKey = buffer.getBytes(32); // second half
} else {
throw new Error('Unsupported encType/key length.');
}
}
getBuffers() {
if (this.keyBuf) {
return this.keyBuf;
}
const key = Services.UtilsService.fromB64ToArray(this.keyB64);
const keys = new SymmetricCryptoKeyBuffers(key.buffer);
if (this.macKey) {
keys.encKey = key.slice(0, key.length / 2).buffer;
keys.macKey = key.slice(key.length / 2).buffer;
} else {
keys.encKey = key.buffer;
keys.macKey = null;
}
this.keyBuf = keys;
return this.keyBuf;
}
}

View File

@ -1,9 +0,0 @@
export default class SymmetricCryptoKeyBuffers {
key: ArrayBuffer;
encKey?: ArrayBuffer;
macKey?: ArrayBuffer;
constructor(key: ArrayBuffer) {
this.key = key;
}
}

View File

@ -30,16 +30,6 @@ import GlobalModule from './global/global.module';
import SettingsModule from './settings/settings.module'; import SettingsModule from './settings/settings.module';
// Model imports // Model imports
import { Attachment } from '../../models/domain/attachment';
import { Card } from '../../models/domain/card';
import { Cipher } from '../../models/domain/cipher';
import { Field } from '../../models/domain/field';
import { Identity } from '../../models/domain/identity';
import { Login } from '../../models/domain/login';
import { SecureNote } from '../../models/domain/secureNote';
import { CipherString } from '../../models/domain/cipherString';
import { Data, Domain, Request, Response } from '@bitwarden/jslib'; import { Data, Domain, Request, Response } from '@bitwarden/jslib';
angular angular

View File

@ -1,10 +1,10 @@
import * as template from './password-generator-history.component.html'; import * as template from './password-generator-history.component.html';
import PasswordHistory from '../../../models/domain/passwordHistory'; import { Domain } from '@bitwarden/jslib';
export class PasswordGeneratorHistoryController { export class PasswordGeneratorHistoryController {
$transition$: any; $transition$: any;
history: PasswordHistory[]; history: Domain.PasswordHistory[];
editState: any; editState: any;
addState: any; addState: any;
i18n: any; i18n: any;

View File

@ -1,28 +1,27 @@
import { CipherString } from '../../models/domain/cipherString'; import { Domain, Response } from '@bitwarden/jslib';
import SymmetricCryptoKey from '../../models/domain/symmetricCryptoKey';
import { Response } from '@bitwarden/jslib';
export interface CryptoService { export interface CryptoService {
setKey(key: SymmetricCryptoKey): Promise<any>; setKey(key: Domain.SymmetricCryptoKey): Promise<any>;
setKeyHash(keyHash: string): Promise<{}>; setKeyHash(keyHash: string): Promise<{}>;
setEncKey(encKey: string): Promise<{}>; setEncKey(encKey: string): Promise<{}>;
setEncPrivateKey(encPrivateKey: string): Promise<{}>; setEncPrivateKey(encPrivateKey: string): Promise<{}>;
setOrgKeys(orgs: Response.ProfileOrganization[]): Promise<{}>; setOrgKeys(orgs: Response.ProfileOrganization[]): Promise<{}>;
getKey(): Promise<SymmetricCryptoKey>; getKey(): Promise<Domain.SymmetricCryptoKey>;
getKeyHash(): Promise<string>; getKeyHash(): Promise<string>;
getEncKey(): Promise<SymmetricCryptoKey>; getEncKey(): Promise<Domain.SymmetricCryptoKey>;
getPrivateKey(): Promise<ArrayBuffer>; getPrivateKey(): Promise<ArrayBuffer>;
getOrgKeys(): Promise<Map<string, SymmetricCryptoKey>>; getOrgKeys(): Promise<Map<string, Domain.SymmetricCryptoKey>>;
getOrgKey(orgId: string): Promise<SymmetricCryptoKey>; getOrgKey(orgId: string): Promise<Domain.SymmetricCryptoKey>;
clearKeys(): Promise<any>; clearKeys(): Promise<any>;
toggleKey(): Promise<any>; toggleKey(): Promise<any>;
makeKey(password: string, salt: string): SymmetricCryptoKey; makeKey(password: string, salt: string): Domain.SymmetricCryptoKey;
hashPassword(password: string, key: SymmetricCryptoKey): Promise<string>; hashPassword(password: string, key: Domain.SymmetricCryptoKey): Promise<string>;
makeEncKey(key: SymmetricCryptoKey): Promise<CipherString>; makeEncKey(key: Domain.SymmetricCryptoKey): Promise<Domain.CipherString>;
encrypt(plainValue: string | Uint8Array, key?: SymmetricCryptoKey, plainValueEncoding?: string): Promise<CipherString>; encrypt(plainValue: string | Uint8Array, key?: Domain.SymmetricCryptoKey,
encryptToBytes(plainValue: ArrayBuffer, key?: SymmetricCryptoKey): Promise<ArrayBuffer>; plainValueEncoding?: string): Promise<Domain.CipherString>;
decrypt(cipherString: CipherString, key?: SymmetricCryptoKey, outputEncoding?: string): Promise<string>; encryptToBytes(plainValue: ArrayBuffer, key?: Domain.SymmetricCryptoKey): Promise<ArrayBuffer>;
decryptFromBytes(encBuf: ArrayBuffer, key: SymmetricCryptoKey): Promise<ArrayBuffer>; decrypt(cipherString: Domain.CipherString, key?: Domain.SymmetricCryptoKey,
outputEncoding?: string): Promise<string>;
decryptFromBytes(encBuf: ArrayBuffer, key: Domain.SymmetricCryptoKey): Promise<ArrayBuffer>;
rsaDecrypt(encValue: string): Promise<string>; rsaDecrypt(encValue: string): Promise<string>;
} }

View File

@ -2,9 +2,7 @@ import AppIdService from './appId.service';
import ConstantsService from './constants.service'; import ConstantsService from './constants.service';
import TokenService from './token.service'; import TokenService from './token.service';
import { Abstractions, Request as Req, Response as Res } from '@bitwarden/jslib'; import { Abstractions, Domain, Request as Req, Response as Res } from '@bitwarden/jslib';
import EnvironmentUrls from '../models/domain/environmentUrls';
export default class ApiService { export default class ApiService {
urlsSet: boolean = false; urlsSet: boolean = false;
@ -19,7 +17,7 @@ export default class ApiService {
this.deviceType = platformUtilsService.getDevice().toString(); this.deviceType = platformUtilsService.getDevice().toString();
} }
setUrls(urls: EnvironmentUrls) { setUrls(urls: Domain.EnvironmentUrls) {
this.urlsSet = true; this.urlsSet = true;
if (urls.base != null) { if (urls.base != null) {

View File

@ -1,9 +1,4 @@
import { Abstractions, Data, Enums, Request, Response } from '@bitwarden/jslib'; import { Abstractions, Data, Domain, Enums, Request, Response } from '@bitwarden/jslib';
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 ApiService from './api.service'; import ApiService from './api.service';
import ConstantsService from './constants.service'; import ConstantsService from './constants.service';
@ -69,8 +64,8 @@ export default class CipherService {
this.decryptedCipherCache = null; this.decryptedCipherCache = null;
} }
async encrypt(model: any): Promise<Cipher> { async encrypt(model: any): Promise<Domain.Cipher> {
const cipher = new Cipher(); const cipher = new Domain.Cipher();
cipher.id = model.id; cipher.id = model.id;
cipher.folderId = model.folderId; cipher.folderId = model.folderId;
cipher.favorite = model.favorite; cipher.favorite = model.favorite;
@ -93,17 +88,17 @@ export default class CipherService {
return cipher; return cipher;
} }
async encryptFields(fieldsModel: any[], key: SymmetricCryptoKey): Promise<Field[]> { async encryptFields(fieldsModel: any[], key: Domain.SymmetricCryptoKey): Promise<Domain.Field[]> {
if (!fieldsModel || !fieldsModel.length) { if (!fieldsModel || !fieldsModel.length) {
return null; return null;
} }
const self = this; const self = this;
const encFields: Field[] = []; const encFields: Domain.Field[] = [];
await fieldsModel.reduce((promise, field) => { await fieldsModel.reduce((promise, field) => {
return promise.then(() => { return promise.then(() => {
return self.encryptField(field, key); return self.encryptField(field, key);
}).then((encField: Field) => { }).then((encField: Domain.Field) => {
encFields.push(encField); encFields.push(encField);
}); });
}, Promise.resolve()); }, Promise.resolve());
@ -111,8 +106,8 @@ export default class CipherService {
return encFields; return encFields;
} }
async encryptField(fieldModel: any, key: SymmetricCryptoKey): Promise<Field> { async encryptField(fieldModel: any, key: Domain.SymmetricCryptoKey): Promise<Domain.Field> {
const field = new Field(); const field = new Domain.Field();
field.type = fieldModel.type; field.type = fieldModel.type;
await this.encryptObjProperty(fieldModel, field, { await this.encryptObjProperty(fieldModel, field, {
@ -123,7 +118,7 @@ export default class CipherService {
return field; return field;
} }
async get(id: string): Promise<Cipher> { async get(id: string): Promise<Domain.Cipher> {
const userId = await this.userService.getUserId(); const userId = await this.userService.getUserId();
const localData = await this.storageService.get<any>(Keys.localData); const localData = await this.storageService.get<any>(Keys.localData);
const ciphers = await this.storageService.get<{ [id: string]: Data.Cipher; }>( const ciphers = await this.storageService.get<{ [id: string]: Data.Cipher; }>(
@ -132,18 +127,18 @@ export default class CipherService {
return null; return null;
} }
return new Cipher(ciphers[id], false, localData ? localData[id] : null); return new Domain.Cipher(ciphers[id], false, localData ? localData[id] : null);
} }
async getAll(): Promise<Cipher[]> { async getAll(): Promise<Domain.Cipher[]> {
const userId = await this.userService.getUserId(); const userId = await this.userService.getUserId();
const localData = await this.storageService.get<any>(Keys.localData); const localData = await this.storageService.get<any>(Keys.localData);
const ciphers = await this.storageService.get<{ [id: string]: Data.Cipher; }>( const ciphers = await this.storageService.get<{ [id: string]: Data.Cipher; }>(
Keys.ciphersPrefix + userId); Keys.ciphersPrefix + userId);
const response: Cipher[] = []; const response: Domain.Cipher[] = [];
for (const id in ciphers) { for (const id in ciphers) {
if (ciphers.hasOwnProperty(id)) { if (ciphers.hasOwnProperty(id)) {
response.push(new Cipher(ciphers[id], false, localData ? localData[id] : null)); response.push(new Domain.Cipher(ciphers[id], false, localData ? localData[id] : null));
} }
} }
return response; return response;
@ -278,7 +273,7 @@ export default class CipherService {
await this.storageService.save(Keys.neverDomains, domains); await this.storageService.save(Keys.neverDomains, domains);
} }
async saveWithServer(cipher: Cipher): Promise<any> { async saveWithServer(cipher: Domain.Cipher): Promise<any> {
const request = new Request.Cipher(cipher); const request = new Request.Cipher(cipher);
let response: Response.Cipher; let response: Response.Cipher;
@ -294,7 +289,7 @@ export default class CipherService {
await this.upsert(data); await this.upsert(data);
} }
saveAttachmentWithServer(cipher: Cipher, unencryptedFile: any): Promise<any> { saveAttachmentWithServer(cipher: Domain.Cipher, unencryptedFile: any): Promise<any> {
const self = this; const self = this;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -321,7 +316,7 @@ export default class CipherService {
const userId = await self.userService.getUserId(); const userId = await self.userService.getUserId();
const data = new Data.Cipher(response, userId, cipher.collectionIds); const data = new Data.Cipher(response, userId, cipher.collectionIds);
this.upsert(data); this.upsert(data);
resolve(new Cipher(data)); resolve(new Domain.Cipher(data));
}; };
@ -427,7 +422,7 @@ export default class CipherService {
// Helpers // Helpers
private encryptObjProperty(model: any, obj: any, map: any, key: SymmetricCryptoKey): Promise<void[]> { private encryptObjProperty(model: any, obj: any, map: any, key: Domain.SymmetricCryptoKey): Promise<void[]> {
const promises = []; const promises = [];
const self = this; const self = this;
@ -444,7 +439,7 @@ export default class CipherService {
return self.cryptoService.encrypt(modelProp, key); return self.cryptoService.encrypt(modelProp, key);
} }
return null; return null;
}).then((val: CipherString) => { }).then((val: Domain.CipherString) => {
theObj[theProp] = val; theObj[theProp] = val;
}); });
promises.push(p); promises.push(p);
@ -454,7 +449,7 @@ export default class CipherService {
return Promise.all(promises); return Promise.all(promises);
} }
private encryptCipherData(cipher: Cipher, model: any, key: SymmetricCryptoKey): Promise<any> { private encryptCipherData(cipher: Domain.Cipher, model: any, key: Domain.SymmetricCryptoKey): Promise<any> {
switch (cipher.type) { switch (cipher.type) {
case Enums.CipherType.Login: case Enums.CipherType.Login:
model.login = {}; model.login = {};

View File

@ -1,10 +1,7 @@
import { CipherString } from '../models/domain/cipherString';
import { Collection } from '../models/domain/collection';
import CryptoService from './crypto.service'; import CryptoService from './crypto.service';
import UserService from './user.service'; import UserService from './user.service';
import { Abstractions, Data } from '@bitwarden/jslib'; import { Abstractions, Data, Domain } from '@bitwarden/jslib';
const Keys = { const Keys = {
collectionsPrefix: 'collections_', collectionsPrefix: 'collections_',
@ -21,7 +18,7 @@ export default class CollectionService {
this.decryptedCollectionCache = null; this.decryptedCollectionCache = null;
} }
async get(id: string): Promise<Collection> { async get(id: string): Promise<Domain.Collection> {
const userId = await this.userService.getUserId(); const userId = await this.userService.getUserId();
const collections = await this.storageService.get<{ [id: string]: Data.Collection; }>( const collections = await this.storageService.get<{ [id: string]: Data.Collection; }>(
Keys.collectionsPrefix + userId); Keys.collectionsPrefix + userId);
@ -29,17 +26,17 @@ export default class CollectionService {
return null; return null;
} }
return new Collection(collections[id]); return new Domain.Collection(collections[id]);
} }
async getAll(): Promise<Collection[]> { async getAll(): Promise<Domain.Collection[]> {
const userId = await this.userService.getUserId(); const userId = await this.userService.getUserId();
const collections = await this.storageService.get<{ [id: string]: Data.Collection; }>( const collections = await this.storageService.get<{ [id: string]: Data.Collection; }>(
Keys.collectionsPrefix + userId); Keys.collectionsPrefix + userId);
const response: Collection[] = []; const response: Domain.Collection[] = [];
for (const id in collections) { for (const id in collections) {
if (collections.hasOwnProperty(id)) { if (collections.hasOwnProperty(id)) {
response.push(new Collection(collections[id])); response.push(new Domain.Collection(collections[id]));
} }
} }
return response; return response;

View File

@ -1,10 +1,6 @@
import * as forge from 'node-forge'; import * as forge from 'node-forge';
import { Abstractions, Enums, Response, Services } from '@bitwarden/jslib'; import { Abstractions, Domain, Enums, Response, Services } from '@bitwarden/jslib';
import { CipherString } from '../models/domain/cipherString';
import EncryptedObject from '../models/domain/encryptedObject';
import SymmetricCryptoKey from '../models/domain/symmetricCryptoKey';
import ConstantsService from './constants.service'; import ConstantsService from './constants.service';
@ -31,18 +27,18 @@ const Crypto = window.crypto;
const Subtle = Crypto.subtle; const Subtle = Crypto.subtle;
export default class CryptoService implements CryptoServiceInterface { export default class CryptoService implements CryptoServiceInterface {
private key: SymmetricCryptoKey; private key: Domain.SymmetricCryptoKey;
private encKey: SymmetricCryptoKey; private encKey: Domain.SymmetricCryptoKey;
private legacyEtmKey: SymmetricCryptoKey; private legacyEtmKey: Domain.SymmetricCryptoKey;
private keyHash: string; private keyHash: string;
private privateKey: ArrayBuffer; private privateKey: ArrayBuffer;
private orgKeys: Map<string, SymmetricCryptoKey>; private orgKeys: Map<string, Domain.SymmetricCryptoKey>;
constructor(private storageService: Abstractions.StorageService, constructor(private storageService: Abstractions.StorageService,
private secureStorageService: Abstractions.StorageService) { private secureStorageService: Abstractions.StorageService) {
} }
async setKey(key: SymmetricCryptoKey): Promise<any> { async setKey(key: Domain.SymmetricCryptoKey): Promise<any> {
this.key = key; this.key = key;
const option = await this.storageService.get<number>(ConstantsService.lockOptionKey); const option = await this.storageService.get<number>(ConstantsService.lockOptionKey);
@ -85,7 +81,7 @@ export default class CryptoService implements CryptoServiceInterface {
return this.storageService.save(Keys.encOrgKeys, orgKeys); return this.storageService.save(Keys.encOrgKeys, orgKeys);
} }
async getKey(): Promise<SymmetricCryptoKey> { async getKey(): Promise<Domain.SymmetricCryptoKey> {
if (this.key != null) { if (this.key != null) {
return this.key; return this.key;
} }
@ -97,7 +93,7 @@ export default class CryptoService implements CryptoServiceInterface {
const key = await this.secureStorageService.get<string>(Keys.key); const key = await this.secureStorageService.get<string>(Keys.key);
if (key) { if (key) {
this.key = new SymmetricCryptoKey(key, true); this.key = new Domain.SymmetricCryptoKey(key, true);
} }
return key == null ? null : this.key; return key == null ? null : this.key;
@ -111,7 +107,7 @@ export default class CryptoService implements CryptoServiceInterface {
return this.storageService.get<string>(Keys.keyHash); return this.storageService.get<string>(Keys.keyHash);
} }
async getEncKey(): Promise<SymmetricCryptoKey> { async getEncKey(): Promise<Domain.SymmetricCryptoKey> {
if (this.encKey != null) { if (this.encKey != null) {
return this.encKey; return this.encKey;
} }
@ -126,12 +122,12 @@ export default class CryptoService implements CryptoServiceInterface {
return null; return null;
} }
const decEncKey = await this.decrypt(new CipherString(encKey), key, 'raw'); const decEncKey = await this.decrypt(new Domain.CipherString(encKey), key, 'raw');
if (decEncKey == null) { if (decEncKey == null) {
return null; return null;
} }
this.encKey = new SymmetricCryptoKey(decEncKey); this.encKey = new Domain.SymmetricCryptoKey(decEncKey);
return this.encKey; return this.encKey;
} }
@ -145,13 +141,13 @@ export default class CryptoService implements CryptoServiceInterface {
return null; return null;
} }
const privateKey = await this.decrypt(new CipherString(encPrivateKey), null, 'raw'); const privateKey = await this.decrypt(new Domain.CipherString(encPrivateKey), null, 'raw');
const privateKeyB64 = forge.util.encode64(privateKey); const privateKeyB64 = forge.util.encode64(privateKey);
this.privateKey = Services.UtilsService.fromB64ToArray(privateKeyB64).buffer; this.privateKey = Services.UtilsService.fromB64ToArray(privateKeyB64).buffer;
return this.privateKey; return this.privateKey;
} }
async getOrgKeys(): Promise<Map<string, SymmetricCryptoKey>> { async getOrgKeys(): Promise<Map<string, Domain.SymmetricCryptoKey>> {
if (this.orgKeys != null && this.orgKeys.size > 0) { if (this.orgKeys != null && this.orgKeys.size > 0) {
return this.orgKeys; return this.orgKeys;
} }
@ -162,7 +158,7 @@ export default class CryptoService implements CryptoServiceInterface {
return null; return null;
} }
const orgKeys: Map<string, SymmetricCryptoKey> = new Map<string, SymmetricCryptoKey>(); const orgKeys: Map<string, Domain.SymmetricCryptoKey> = new Map<string, Domain.SymmetricCryptoKey>();
let setKey = false; let setKey = false;
for (const orgId in encOrgKeys) { for (const orgId in encOrgKeys) {
@ -171,7 +167,7 @@ export default class CryptoService implements CryptoServiceInterface {
} }
const decValueB64 = await this.rsaDecrypt(encOrgKeys[orgId]); const decValueB64 = await this.rsaDecrypt(encOrgKeys[orgId]);
orgKeys.set(orgId, new SymmetricCryptoKey(decValueB64, true)); orgKeys.set(orgId, new Domain.SymmetricCryptoKey(decValueB64, true));
setKey = true; setKey = true;
} }
@ -182,7 +178,7 @@ export default class CryptoService implements CryptoServiceInterface {
return this.orgKeys; return this.orgKeys;
} }
async getOrgKey(orgId: string): Promise<SymmetricCryptoKey> { async getOrgKey(orgId: string): Promise<Domain.SymmetricCryptoKey> {
if (orgId == null) { if (orgId == null) {
return null; return null;
} }
@ -252,13 +248,13 @@ export default class CryptoService implements CryptoServiceInterface {
await this.setKey(key); await this.setKey(key);
} }
makeKey(password: string, salt: string): SymmetricCryptoKey { makeKey(password: string, salt: string): Domain.SymmetricCryptoKey {
const keyBytes: string = (forge as any).pbkdf2(forge.util.encodeUtf8(password), forge.util.encodeUtf8(salt), const keyBytes: string = (forge as any).pbkdf2(forge.util.encodeUtf8(password), forge.util.encodeUtf8(salt),
5000, 256 / 8, 'sha256'); 5000, 256 / 8, 'sha256');
return new SymmetricCryptoKey(keyBytes); return new Domain.SymmetricCryptoKey(keyBytes);
} }
async hashPassword(password: string, key: SymmetricCryptoKey): Promise<string> { async hashPassword(password: string, key: Domain.SymmetricCryptoKey): Promise<string> {
const storedKey = await this.getKey(); const storedKey = await this.getKey();
key = key || storedKey; key = key || storedKey;
if (!password || !key) { if (!password || !key) {
@ -269,14 +265,14 @@ export default class CryptoService implements CryptoServiceInterface {
return forge.util.encode64(hashBits); return forge.util.encode64(hashBits);
} }
makeEncKey(key: SymmetricCryptoKey): Promise<CipherString> { makeEncKey(key: Domain.SymmetricCryptoKey): Promise<Domain.CipherString> {
const bytes = new Uint8Array(512 / 8); const bytes = new Uint8Array(512 / 8);
Crypto.getRandomValues(bytes); Crypto.getRandomValues(bytes);
return this.encrypt(bytes, key, 'raw'); return this.encrypt(bytes, key, 'raw');
} }
async encrypt(plainValue: string | Uint8Array, key?: SymmetricCryptoKey, async encrypt(plainValue: string | Uint8Array, key?: Domain.SymmetricCryptoKey,
plainValueEncoding: string = 'utf8'): Promise<CipherString> { plainValueEncoding: string = 'utf8'): Promise<Domain.CipherString> {
if (!plainValue) { if (!plainValue) {
return Promise.resolve(null); return Promise.resolve(null);
} }
@ -292,10 +288,10 @@ export default class CryptoService implements CryptoServiceInterface {
const iv = Services.UtilsService.fromBufferToB64(encValue.iv.buffer); const iv = Services.UtilsService.fromBufferToB64(encValue.iv.buffer);
const ct = Services.UtilsService.fromBufferToB64(encValue.ct.buffer); const ct = Services.UtilsService.fromBufferToB64(encValue.ct.buffer);
const mac = encValue.mac ? Services.UtilsService.fromBufferToB64(encValue.mac.buffer) : null; const mac = encValue.mac ? Services.UtilsService.fromBufferToB64(encValue.mac.buffer) : null;
return new CipherString(encValue.key.encType, iv, ct, mac); return new Domain.CipherString(encValue.key.encType, iv, ct, mac);
} }
async encryptToBytes(plainValue: ArrayBuffer, key?: SymmetricCryptoKey): Promise<ArrayBuffer> { async encryptToBytes(plainValue: ArrayBuffer, key?: Domain.SymmetricCryptoKey): Promise<ArrayBuffer> {
const encValue = await this.aesEncrypt(plainValue, key); const encValue = await this.aesEncrypt(plainValue, key);
let macLen = 0; let macLen = 0;
if (encValue.mac) { if (encValue.mac) {
@ -313,7 +309,7 @@ export default class CryptoService implements CryptoServiceInterface {
return encBytes.buffer; return encBytes.buffer;
} }
async decrypt(cipherString: CipherString, key?: SymmetricCryptoKey, async decrypt(cipherString: Domain.CipherString, key?: Domain.SymmetricCryptoKey,
outputEncoding: string = 'utf8'): Promise<string> { outputEncoding: string = 'utf8'): Promise<string> {
const ivBytes: string = forge.util.decode64(cipherString.initializationVector); const ivBytes: string = forge.util.decode64(cipherString.initializationVector);
const ctBytes: string = forge.util.decode64(cipherString.cipherText); const ctBytes: string = forge.util.decode64(cipherString.cipherText);
@ -330,7 +326,7 @@ export default class CryptoService implements CryptoServiceInterface {
} }
} }
async decryptFromBytes(encBuf: ArrayBuffer, key: SymmetricCryptoKey): Promise<ArrayBuffer> { async decryptFromBytes(encBuf: ArrayBuffer, key: Domain.SymmetricCryptoKey): Promise<ArrayBuffer> {
if (!encBuf) { if (!encBuf) {
throw new Error('no encBuf.'); throw new Error('no encBuf.');
} }
@ -448,8 +444,8 @@ export default class CryptoService implements CryptoServiceInterface {
// Helpers // Helpers
private async aesEncrypt(plainValue: ArrayBuffer, key: SymmetricCryptoKey): Promise<EncryptedObject> { private async aesEncrypt(plainValue: ArrayBuffer, key: Domain.SymmetricCryptoKey): Promise<Domain.EncryptedObject> {
const obj = new EncryptedObject(); const obj = new Domain.EncryptedObject();
obj.key = await this.getKeyForEncryption(key); obj.key = await this.getKeyForEncryption(key);
const keyBuf = obj.key.getBuffers(); const keyBuf = obj.key.getBuffers();
@ -472,7 +468,7 @@ export default class CryptoService implements CryptoServiceInterface {
} }
private async aesDecrypt(encType: Enums.EncryptionType, ctBytes: string, ivBytes: string, macBytes: string, private async aesDecrypt(encType: Enums.EncryptionType, ctBytes: string, ivBytes: string, macBytes: string,
key: SymmetricCryptoKey): Promise<any> { key: Domain.SymmetricCryptoKey): Promise<any> {
const keyForEnc = await this.getKeyForEncryption(key); const keyForEnc = await this.getKeyForEncryption(key);
const theKey = this.resolveLegacyKey(encType, keyForEnc); const theKey = this.resolveLegacyKey(encType, keyForEnc);
@ -501,7 +497,7 @@ export default class CryptoService implements CryptoServiceInterface {
} }
private async aesDecryptWC(encType: Enums.EncryptionType, ctBuf: ArrayBuffer, ivBuf: ArrayBuffer, private async aesDecryptWC(encType: Enums.EncryptionType, ctBuf: ArrayBuffer, ivBuf: ArrayBuffer,
macBuf: ArrayBuffer, key: SymmetricCryptoKey): Promise<ArrayBuffer> { macBuf: ArrayBuffer, key: Domain.SymmetricCryptoKey): Promise<ArrayBuffer> {
const theKey = await this.getKeyForEncryption(key); const theKey = await this.getKeyForEncryption(key);
const keyBuf = theKey.getBuffers(); const keyBuf = theKey.getBuffers();
const encKey = await Subtle.importKey('raw', keyBuf.encKey, AesAlgorithm, false, ['decrypt']); const encKey = await Subtle.importKey('raw', keyBuf.encKey, AesAlgorithm, false, ['decrypt']);
@ -577,7 +573,7 @@ export default class CryptoService implements CryptoServiceInterface {
return true; return true;
} }
private async getKeyForEncryption(key?: SymmetricCryptoKey): Promise<SymmetricCryptoKey> { private async getKeyForEncryption(key?: Domain.SymmetricCryptoKey): Promise<Domain.SymmetricCryptoKey> {
if (key) { if (key) {
return key; return key;
} }
@ -586,12 +582,12 @@ export default class CryptoService implements CryptoServiceInterface {
return encKey || (await this.getKey()); return encKey || (await this.getKey());
} }
private resolveLegacyKey(encType: Enums.EncryptionType, key: SymmetricCryptoKey): SymmetricCryptoKey { private resolveLegacyKey(encType: Enums.EncryptionType, key: Domain.SymmetricCryptoKey): Domain.SymmetricCryptoKey {
if (encType === Enums.EncryptionType.AesCbc128_HmacSha256_B64 && if (encType === Enums.EncryptionType.AesCbc128_HmacSha256_B64 &&
key.encType === Enums.EncryptionType.AesCbc256_B64) { key.encType === Enums.EncryptionType.AesCbc256_B64) {
// Old encrypt-then-mac scheme, make a new key // Old encrypt-then-mac scheme, make a new key
this.legacyEtmKey = this.legacyEtmKey || this.legacyEtmKey = this.legacyEtmKey ||
new SymmetricCryptoKey(key.key, false, Enums.EncryptionType.AesCbc128_HmacSha256_B64); new Domain.SymmetricCryptoKey(key.key, false, Enums.EncryptionType.AesCbc128_HmacSha256_B64);
return this.legacyEtmKey; return this.legacyEtmKey;
} }

View File

@ -1,9 +1,7 @@
import ApiService from './api.service'; import ApiService from './api.service';
import ConstantsService from './constants.service'; import ConstantsService from './constants.service';
import { Abstractions } from '@bitwarden/jslib'; import { Abstractions, Domain } from '@bitwarden/jslib';
import EnvironmentUrls from '../models/domain/environmentUrls';
export default class EnvironmentService { export default class EnvironmentService {
baseUrl: string; baseUrl: string;
@ -25,7 +23,7 @@ export default class EnvironmentService {
webVault: null, webVault: null,
}; };
const envUrls = new EnvironmentUrls(); const envUrls = new Domain.EnvironmentUrls();
if (urls.base) { if (urls.base) {
this.baseUrl = envUrls.base = urls.base; this.baseUrl = envUrls.base = urls.base;
@ -61,7 +59,7 @@ export default class EnvironmentService {
this.identityUrl = urls.identity; this.identityUrl = urls.identity;
this.iconsUrl = urls.icons; this.iconsUrl = urls.icons;
const envUrls = new EnvironmentUrls(); const envUrls = new Domain.EnvironmentUrls();
if (this.baseUrl) { if (this.baseUrl) {
envUrls.base = this.baseUrl; envUrls.base = this.baseUrl;
} else { } else {

View File

@ -1,5 +1,3 @@
import { CipherString } from '../models/domain/cipherString';
import ApiService from './api.service'; import ApiService from './api.service';
import CryptoService from './crypto.service'; import CryptoService from './crypto.service';
import UserService from './user.service'; import UserService from './user.service';

View File

@ -1,9 +1,6 @@
import { CipherString } from '../models/domain/cipherString';
import PasswordHistory from '../models/domain/passwordHistory';
import CryptoService from './crypto.service'; import CryptoService from './crypto.service';
import { Abstractions, Services } from '@bitwarden/jslib'; import { Abstractions, Domain, Services } from '@bitwarden/jslib';
const DefaultOptions = { const DefaultOptions = {
length: 14, length: 14,
@ -144,10 +141,10 @@ export default class PasswordGenerationService {
} }
optionsCache: any; optionsCache: any;
history: PasswordHistory[] = []; history: Domain.PasswordHistory[] = [];
constructor(private cryptoService: CryptoService, private storageService: Abstractions.StorageService) { constructor(private cryptoService: CryptoService, private storageService: Abstractions.StorageService) {
storageService.get<PasswordHistory[]>(Keys.history).then((encrypted) => { storageService.get<Domain.PasswordHistory[]>(Keys.history).then((encrypted) => {
return this.decryptHistory(encrypted); return this.decryptHistory(encrypted);
}).then((history) => { }).then((history) => {
this.history = history; this.history = history;
@ -177,7 +174,7 @@ export default class PasswordGenerationService {
} }
getHistory() { getHistory() {
return this.history || new Array<PasswordHistory>(); return this.history || new Array<Domain.PasswordHistory>();
} }
async addHistory(password: string): Promise<any> { async addHistory(password: string): Promise<any> {
@ -186,7 +183,7 @@ export default class PasswordGenerationService {
return; return;
} }
this.history.push(new PasswordHistory(password, Date.now())); this.history.push(new Domain.PasswordHistory(password, Date.now()));
// Remove old items. // Remove old items.
if (this.history.length > MaxPasswordsInHistory) { if (this.history.length > MaxPasswordsInHistory) {
@ -202,27 +199,27 @@ export default class PasswordGenerationService {
return await this.storageService.remove(Keys.history); return await this.storageService.remove(Keys.history);
} }
private async encryptHistory(): Promise<PasswordHistory[]> { private async encryptHistory(): Promise<Domain.PasswordHistory[]> {
if (this.history == null || this.history.length === 0) { if (this.history == null || this.history.length === 0) {
return Promise.resolve([]); return Promise.resolve([]);
} }
const promises = this.history.map(async (item) => { const promises = this.history.map(async (item) => {
const encrypted = await this.cryptoService.encrypt(item.password); const encrypted = await this.cryptoService.encrypt(item.password);
return new PasswordHistory(encrypted.encryptedString, item.date); return new Domain.PasswordHistory(encrypted.encryptedString, item.date);
}); });
return await Promise.all(promises); return await Promise.all(promises);
} }
private async decryptHistory(history: PasswordHistory[]): Promise<PasswordHistory[]> { private async decryptHistory(history: Domain.PasswordHistory[]): Promise<Domain.PasswordHistory[]> {
if (history == null || history.length === 0) { if (history == null || history.length === 0) {
return Promise.resolve([]); return Promise.resolve([]);
} }
const promises = history.map(async (item) => { const promises = history.map(async (item) => {
const decrypted = await this.cryptoService.decrypt(new CipherString(item.password)); const decrypted = await this.cryptoService.decrypt(new Domain.CipherString(item.password));
return new PasswordHistory(decrypted, item.date); return new Domain.PasswordHistory(decrypted, item.date);
}); });
return await Promise.all(promises); return await Promise.all(promises);