/
KeyEntryStorage.ts
180 lines (156 loc) · 4.21 KB
/
KeyEntryStorage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import {
IKeyEntry,
IKeyEntryStorage,
IKeyEntryStorageConfig,
ISaveKeyEntryParams,
IUpdateKeyEntryParams,
} from './IKeyEntryStorage';
import { DefaultStorageAdapter } from '../adapters/DefaultStorageAdapter';
import { IStorageAdapter, IStorageAdapterConfig } from '../adapters/IStorageAdapter';
import { InvalidKeyEntryError, KeyEntryAlreadyExistsError, KeyEntryDoesNotExistError } from './errors';
const DEFAULTS: IStorageAdapterConfig = {
dir: '.virgil_key_entries',
name: 'VirgilKeyEntries'
};
const VALUE_KEY = 'value';
const CREATION_DATE_KEY = 'creationDate';
const MODIFICATION_DATE_KEY = 'modificationDate';
export { IKeyEntry, IKeyEntryStorage, IKeyEntryStorageConfig, ISaveKeyEntryParams, IUpdateKeyEntryParams };
/**
* Class responsible for persisting private key bytes with optional
* user-defined metadata.
*/
export class KeyEntryStorage implements IKeyEntryStorage {
private adapter: IStorageAdapter;
/**
* Initializes a new instance of `KeyEntryStorage`.
*
* @param {IKeyEntryStorageConfig} config - Instance configuration.
*/
constructor (config: IKeyEntryStorageConfig | string = {}) {
this.adapter = resolveAdapter(config);
}
/**
* @inheritDoc
*/
exists(name: string): Promise<boolean> {
validateName(name);
return this.adapter.exists(name);
}
/**
* @inheritDoc
*/
load(name: string): Promise<IKeyEntry | null> {
validateName(name);
return this.adapter.load(name).then(data => {
if (data == null) {
return null;
}
return deserializeKeyEntry(data);
});
}
/**
* @inheritDoc
*/
remove(name: string): Promise<boolean> {
validateName(name);
return this.adapter.remove(name);
}
/**
* @inheritDoc
*/
save({ name, value, meta }: ISaveKeyEntryParams): Promise<IKeyEntry> {
validateNameProperty(name);
validateValueProperty(value);
const keyEntry = {
name: name,
value: value,
meta: meta,
creationDate: new Date(),
modificationDate: new Date()
};
return this.adapter.store(name, serializeKeyEntry(keyEntry))
.then(() => keyEntry)
.catch(error => {
if (error && error.name === 'StorageEntryAlreadyExistsError') {
throw new KeyEntryAlreadyExistsError(name);
}
throw error;
});
}
/**
* @inheritDoc
*/
list (): Promise<IKeyEntry[]> {
return this.adapter.list()
.then(entries => entries.map(entry => deserializeKeyEntry(entry)));
}
/**
* @inheritDoc
*/
update ({ name, value, meta }: IUpdateKeyEntryParams): Promise<IKeyEntry> {
validateNameProperty(name);
if (!(value || meta)) {
throw new TypeError(
'Invalid argument. Either `value` or `meta` property is required.'
);
}
return this.adapter.load(name)
.then(data => {
if (data === null) {
throw new KeyEntryDoesNotExistError(name)
}
const entry = deserializeKeyEntry(data);
const updatedEntry = Object.assign(entry,{
value: value || entry.value,
meta: meta || entry.meta,
modificationDate: new Date()
});
return this.adapter.update(name, serializeKeyEntry(updatedEntry))
.then(() => updatedEntry);
});
}
/**
* @inheritDoc
*/
clear () {
return this.adapter.clear();
}
}
function serializeKeyEntry (keyEntry: IKeyEntry) {
return JSON.stringify(keyEntry);
}
function deserializeKeyEntry (data: string): IKeyEntry {
try {
return JSON.parse(
data,
(key, value) => {
if (key === CREATION_DATE_KEY || key === MODIFICATION_DATE_KEY) {
return new Date(value);
}
return value;
}
);
} catch (error) {
throw new InvalidKeyEntryError();
}
}
function resolveAdapter (config: IKeyEntryStorageConfig|string) {
if (typeof config === 'string') {
return new DefaultStorageAdapter({ dir: config, name: config });
}
const { adapter, ...rest } = config;
if (adapter != null) {
return adapter;
}
return new DefaultStorageAdapter({ ...DEFAULTS, ...rest });
}
const requiredArg = (name: string) => (value: any) => {
if (!value) throw new TypeError(`Argument '${name}' is required.`);
};
const requiredProp = (name: string) => (value: any) => {
if (!value) throw new TypeError(`Invalid argument. Property ${name} is required`)
};
const validateName = requiredArg('name');
const validateNameProperty = requiredProp('name');
const validateValueProperty = requiredProp('value');