forked from truevault-safe/truevault-js-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1470 lines (1326 loc) · 54.8 KB
/
index.js
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {version} from './package.json'
import nodeFetch from 'node-fetch';
import URI from 'urijs';
import base64 from 'base-64';
import nodeFormData from 'form-data';
import contentDisposition from 'content-disposition';
const tvFetch = typeof fetch !== "undefined" ? fetch : nodeFetch;
const tvFormData = typeof FormData !== "undefined" ? FormData : nodeFormData;
/**
* A client for the [TrueVault HTTP API](https://docs.truevault.com/).
*
* **Overview**
*
* The TrueVault JS SDK makes it easy to communicate with the TrueVault API from JavaScript web apps, nodejs servers,
* and lambda methods.
*
* ***JS Web example***
* ```js
* async function onLoginClicked() {
* var trueVaultClient = await TrueVault.login(TRUEVAULT_ACCOUNT_ID, username, password)
* localStorage.trueVaultAccessToken = trueVaultClient.accessToken;
* var userInfo = trueVaultClient.readCurrentUser();
* ...
* }
* ```
*
* **Error Handling**
*
* If any request fails, the method will throw an error. The thrown `Error` instance will have the following properties:
*
* - `message`: the message returned by the TrueVault API
* - `transaction_id`: a unique ID that can be used in support requests to [email protected] to help us resolve the error
* - `error`: the machine-readable error object returned by TrueVault.
*
* For more information on TrueVault API responses, see https://docs.truevault.com/overview#api-responses.
*
* **Authentication**
*
* If you already have an API key or access token, use the constructor. If you have a username and password, see
* `login()`. See https://docs.truevault.com/overview#authentication for more on authentication concepts in TrueVault.
*
* To authenticate, provide one of the following styles of objects based on how you wish to authenticate:
*
* - `{ apiKey: 'your API key' }`
* - `{ accessToken: 'your access token' }`
* - `{ httpBasic: 'http basic base64 string' }`
* - `null`, to indicate no authentication is to be provided to the server
*
* @param {object} authn Authentication info, or null if no authentication info is to be used.
* @param {string} host optional parameter specifying TV API host; defaults to https://api.truevault.com
*/
class TrueVaultClient {
constructor(authn, host) {
this._authHeader = null;
if (!authn) {
// no auth
this._authHeader = null;
} else if (typeof authn === 'object') {
if (authn.hasOwnProperty('apiKey')) {
this._authHeader = TrueVaultClient._makeHeaderForUsername(authn['apiKey'])
} else if (authn.hasOwnProperty('accessToken')) {
this._accessToken = authn['accessToken'];
this._authHeader = TrueVaultClient._makeHeaderForUsername(this.accessToken)
} else if (authn.hasOwnProperty('httpBasic')) {
this._authHeader = `Basic ${authn['httpBasic']}`;
}
} else {
throw new Error('Invalid authentication method provided');
}
this.host = host || 'https://api.truevault.com';
}
/**
* Returns the TrueVault access token that was supplied in the constructor/returned from the login call. Throws
* if the client was created without an access token (e. g. created with an API key).
* @returns {string}
*/
get accessToken() {
if (!this._accessToken) {
throw new Error('No access token set. This client may have been configured with an API key or a custom auth header');
}
return this._accessToken;
}
/**
* Returns the Authentication: header used for making requests (e. g. "Basic ABC123"). Useful if you need to make
* raw requests for some reason.
* @returns {*}
*/
get authHeader() {
return this._authHeader;
}
async performLegacyRequest(path, options) {
if (!!this.authHeader) {
if (!options) {
options = {};
}
if (!options.headers) {
options.headers = {};
}
options.headers.Authorization = this.authHeader;
}
const uri = URI(`${this.host}/${path}`)
.addQuery("_tv_sdk", version)
.toString();
const response = await tvFetch(uri, options);
const responseBody = await response.text();
let json;
try {
json = JSON.parse(responseBody);
} catch (e) {
throw new Error(`non-JSON response: ${responseBody}`);
}
if (json.result === 'error') {
const error = new Error(json.error.message);
error.error = json.error;
error.transaction_id = json.transaction_id;
throw error;
} else {
return json;
}
}
async performJSONRequest(path, options) {
if (!options) {
options = {};
}
if (!options.headers) {
options.headers = {};
}
options.headers['Content-Type'] = 'application/json';
return this.performLegacyRequest(path, options);
}
/**
* Performs a legacy (non-v2-JSON) request. By using XHR rather than fetch, it's able to supply progress
* information.
* @param method
* @param url
* @param formData
* @param progressCallback
* @param responseType
* @returns {Promise<XMLHTTPRequest>|Promise<Object>} A promise resolving to an XHR object for blobs, and the parsed JSON object for JSON
*/
performLegacyRequestWithProgress(method, url, formData, progressCallback, responseType) {
// We are using XMLHttpRequest here since fetch does not have a progress API
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
if (method.toLowerCase() === 'get') {
xhr.addEventListener('progress', progressCallback);
xhr.addEventListener('load', progressCallback);
} else {
xhr.upload.addEventListener('progress', progressCallback);
xhr.upload.addEventListener('load', progressCallback);
}
xhr.open(method, url);
xhr.setRequestHeader('Authorization', this.authHeader);
xhr.responseType = responseType;
xhr.onload = () => {
switch (responseType) {
case "json":
const responseJson = xhr.response;
if (responseJson.result === 'error') {
const error = new Error(responseJson.error.message);
error.error = responseJson.error;
reject(error);
} else {
resolve(responseJson);
}
break;
case "blob":
resolve(xhr);
break;
default:
throw new Error(`Unsupported responseType: ${responseType}`);
}
};
xhr.onerror = () => reject(Error('Network error'));
xhr.send(formData);
});
}
/**
* Useful when you want to create a client starting from a user's username and password as opposed to an API key
* or access token. The resulting TrueVaultClient has an accessToken property you can use to retrieve the raw
* TrueVault access token if needed (e. g. to save in localStorage).
* See https://docs.truevault.com/authentication#login-a-user.
* @param {string} accountId account id that the user belongs to.
* @param {string} username user's username.
* @param {string} password user's password.
* @param {string} [mfaCode] current MFA code, if user has MFA configured.
* @param {string} [host] host optional parameter specifying TV API host; defaults to https://api.truevault.com
* @param {Date} [notValidAfter] notValidAfter optional parameter specifying when the returned access token expires
* @returns {Promise.<TrueVaultClient>}
*/
static async login(accountId, username, password, mfaCode, host, notValidAfter) {
const accessToken = await TrueVaultClient.generateAccessToken(accountId, username, password, mfaCode, host, notValidAfter);
return new TrueVaultClient({'accessToken': accessToken}, host);
}
/**
* Log in with a username and password and return the resulting access token.
* See https://docs.truevault.com/authentication#login-a-user.
* @param {string} accountId account id that the user belongs to.
* @param {string} username user's username.
* @param {string} password user's password.
* @param {string} [mfaCode] current MFA code, if user has MFA configured.
* @param {string} [host] host optional parameter specifying TV API host; defaults to https://api.truevault.com
* @param {Date} [notValidAfter] notValidAfter optional parameter specifying when the returned access token expires
* @returns {Promise.<string>}
*/
static async generateAccessToken(accountId, username, password, mfaCode, host, notValidAfter) {
const formData = new tvFormData();
formData.append("account_id", accountId);
formData.append("username", username);
formData.append("password", password);
if (!!mfaCode) {
formData.append("mfa_code", mfaCode);
}
if (!!notValidAfter) {
formData.append("not_valid_after", notValidAfter.toISOString());
}
const tvClient = new TrueVaultClient(null, host);
const response = await tvClient.performLegacyRequest(`v1/auth/login`, {
method: 'POST',
body: formData
});
return response.user.access_token;
}
/**
* Log the authenticated user out, which deactivates its access token. See
* https://docs.truevault.com/authentication#logout-a-user.
* @returns {Promise.<Object>}
*/
async logout() {
const response = await this.performLegacyRequest(`v1/auth/logout`, {method: 'POST'});
this._authHeader = null;
return response.logout;
}
/**
* Get data about the authenticated user. See https://docs.truevault.com/authentication#verify-a-user.
* @param [full=true] Whether to include user attributes and groups
* @returns {Promise.<Object>}
*/
async readCurrentUser(full) {
if (full !== false) {
full = true;
}
const response = await this.performLegacyRequest(`v1/auth/me?full=${full}`);
const user = response.user;
if (user.attributes) {
user.attributes = JSON.parse(base64.decode(user.attributes));
}
return user;
}
/**
* Updates the currently authenticated user's attributes. See https://docs.truevault.com/authentication#verify-a-user.
* @param attributes
* @returns {Promise<Object>}
*/
async updateCurrentUser(attributes) {
const formData = new tvFormData();
formData.append("attributes", base64.encode(JSON.stringify(attributes)));
const response = await this.performLegacyRequest('v1/auth/me?full=true', {
method: 'PUT',
body: formData
});
const user = response.user;
if (user.attributes) {
user.attributes = JSON.parse(base64.decode(user.attributes));
}
return user;
}
/**
* List all users in the account. See https://docs.truevault.com/users#list-all-users.
* @param [full=false] Whether to return user attributes and group IDs
* @returns {Promise.<Array>}
*/
async listUsers(full) {
return this.listUsersWithStatus(null, full);
}
/**
* List all users in the account. See https://docs.truevault.com/users#list-all-users.
* @param [status=null] If ACTIVE, DEACTIVATED, PENDING, or LOCKED only returns users with that status
* @param [full=false] Whether to return user attributes and group IDs
* @returns {Promise.<Array>}
*/
async listUsersWithStatus(status, full) {
if (full !== true) {
full = false;
}
var path = `v1/users?full=${full}`;
if (status) {
path = `${path}&status=${status}`;
}
const response = await this.performLegacyRequest(path);
return response.users.map(user => {
if (user.attributes) {
user.attributes = JSON.parse(base64.decode(user.attributes));
}
return user;
});
}
/**
* Read a single user. See https://docs.truevault.com/users#read-a-user.
* @returns {Promise.<Object>}
*/
async readUser(userId) {
const users = await this.readUsers([userId]);
return users[0];
}
/**
* Reads multiple users. See https://docs.truevault.com/users#read-a-user.
* @returns {Promise.<Array>}
*/
async readUsers(userIds) {
const response = await this.performLegacyRequest(`v2/users/${userIds.join(',')}?full=true`);
return response.users;
}
/**
* Create a new user. See https://docs.truevault.com/users#create-a-user.
* @param {string} username new user's username.
* @param {string} password new user's password.
* @param {Object} [attributes] new user's attributes, if desired.
* @param {Array} [groupIds] add user to the given groups, if provided.
* @param {string} [status] the newly created user's status
* @returns {Promise.<Object>}
*/
async createUser(username, password, attributes, groupIds, status) {
const formData = new tvFormData();
formData.append("username", username);
formData.append("password", password);
if (attributes) {
formData.append("attributes", base64.encode(JSON.stringify(attributes)));
}
if (groupIds) {
formData.append("group_ids", groupIds.join(","));
}
if (status) {
formData.append("status", status);
}
const response = await this.performLegacyRequest('v1/users', {
method: 'POST',
body: formData
});
return response.user;
}
/**
* Update a user's attributes. See https://docs.truevault.com/users#update-a-user.
* @param {string} userId the user's userId
* @param {Object} attributes
* @returns {Promise.<Object>}
*/
async updateUserAttributes(userId, attributes) {
const formData = new tvFormData();
formData.append("attributes", base64.encode(JSON.stringify(attributes)));
const response = await this.performLegacyRequest(`v1/users/${userId}`, {
method: 'PUT',
body: formData
});
return response.user;
}
/**
* Update a user's status. See https://docs.truevault.com/users#update-a-user.
* @param {string} userId the user's userId
* @param {string} status
* @returns {Promise.<Object>}
*/
async updateUserStatus(userId, status) {
const formData = new tvFormData();
formData.append("status", status);
const response = await this.performLegacyRequest(`v1/users/${userId}`, {
method: 'PUT',
body: formData
});
return response.user;
}
/**
* Update a user's username. See https://docs.truevault.com/users#update-a-user.
* @param {string} userId the user id to change.
* @param {string} newUsername user's new username.
* @returns {Promise.<Object>}
*/
async updateUserUsername(userId, newUsername) {
const formData = new tvFormData();
formData.append("username", newUsername);
const response = await this.performLegacyRequest(`v1/users/${userId}`, {
method: 'PUT',
body: formData
});
return response.user;
}
/**
* Update a user's password. See https://docs.truevault.com/users#update-a-user.
* @param {string} userId the user id to change.
* @param {string} newPassword user's new password.
* @returns {Promise.<Object>}
*/
async updateUserPassword(userId, newPassword) {
const formData = new tvFormData();
formData.append("password", newPassword);
const response = await this.performLegacyRequest(`v1/users/${userId}`, {
method: 'PUT',
body: formData
});
return response.user;
}
/**
* Delete a user. See https://docs.truevault.com/users#delete-a-user
* @param {string} userId the user id to delete.
* @returns {Promise.<Object>}
*/
async deleteUser(userId) {
const response = await this.performLegacyRequest(`v1/users/${userId}`, {
method: 'DELETE',
});
return response.user;
}
/**
* Create an API key for a user. See https://docs.truevault.com/users#create-api-key-for-a-user.
* @param {string} userId user id.
* @returns {Promise.<string>}
*/
async createUserApiKey(userId) {
const response = await this.performLegacyRequest(`v1/users/${userId}/api_key`, {method: 'POST'});
return response.api_key;
}
/**
* Create an access token for a user. See https://docs.truevault.com/users#create-access-token-for-a-user.
* @param {string} userId user id.
* @param {Date} [notValidAfter] notValidAfter optional parameter specifying when the returned access token expires
* @returns {Promise.<string>}
*/
async createUserAccessToken(userId, notValidAfter) {
const formData = new tvFormData();
if (!!notValidAfter) {
formData.append("not_valid_after ", notValidAfter.toISOString());
}
const response = await this.performLegacyRequest(`v1/users/${userId}/access_token`, {method: 'POST', body: formData});
return response.user.access_token;
}
/**
* Start MFA enrollment for a user. See https://docs.truevault.com/users#start-mfa-enrollment-for-a-user.
* @param {string} userId user id.
* @param {string} issuer MFA issuer.
* @returns {Promise.<Object>}
*/
async startUserMfaEnrollment(userId, issuer) {
const result = await this.performJSONRequest(`v1/users/${userId}/mfa/start_enrollment`, {
method: 'POST',
body: JSON.stringify({issuer})
});
return result.mfa;
}
/**
* Finalize MFA enrollment for a user. See https://docs.truevault.com/users#finalize-mfa-enrollment-for-a-user.
* @param {string} userId user id.
* @param {string} mfaCode1 first MFA code.
* @param {string} mfaCode2 second MFA code.
* @returns {Promise.<undefined>}
*/
async finalizeMfaEnrollment(userId, mfaCode1, mfaCode2) {
await this.performJSONRequest(`v1/users/${userId}/mfa/finalize_enrollment`, {
method: 'POST',
body: JSON.stringify({mfa_code_1: mfaCode1, mfa_code_2: mfaCode2})
});
}
/**
* Unenroll a user from MFA. See #https://docs.truevault.com/users#unenroll-mfa-for-a-user.
* @param {string} userId user id.
* @param {string} mfaCode MFA code for user.
* @param {string} password user's password.
* @returns {Promise.<undefined>}
*/
async unenrollMfa(userId, mfaCode, password) {
await this.performJSONRequest(`v1/users/${userId}/mfa/unenroll`, {
method: 'POST',
body: JSON.stringify({mfa_code: mfaCode, password: password})
});
}
/**
* Create a new group. See https://docs.truevault.com/groups#create-a-group.
* @param {string} name group name.
* @param {Array} policy group policy. See https://docs.truevault.com/groups.
* @param {Array} [userIds] user ids to add to the group.
* @returns {Promise.<Object>}
*/
async createGroup(name, policy, userIds) {
const formData = new tvFormData();
formData.append("name", name);
formData.append("policy", base64.encode(JSON.stringify(policy)));
if (!!userIds) {
formData.append("user_ids", userIds.join(','));
}
const response = await this.performLegacyRequest('v1/groups', {
method: 'POST',
body: formData
});
return response.group;
}
/**
* Update an existing group's name and policy. See https://docs.truevault.com/groups#update-a-group.
* @param {string} groupId group id to update.
* @param {string} name group name.
* @param {Array} policy group policy. See https://docs.truevault.com/groups.
* @returns {Promise.<Object>}
*/
async updateGroup(groupId, name, policy) {
const formData = new tvFormData();
if (!!name) {
formData.append("name", name);
}
if (!!policy) {
formData.append("policy", base64.encode(JSON.stringify(policy)));
}
const response = await this.performLegacyRequest(`v1/groups/${groupId}`, {
method: 'PUT',
body: formData
});
return response.group;
}
/**
* Delete a group. See https://docs.truevault.com/groups#delete-a-group.
* @param {string} groupId group id to delete.
* @returns {Promise.<Object>}
*/
async deleteGroup(groupId) {
const response = await this.performLegacyRequest(`v1/groups/${groupId}`, {
method: 'DELETE'
});
return response.group;
}
/**
* List all groups. See https://docs.truevault.com/groups#list-all-groups.
* @returns {Promise.<Array>}
*/
async listGroups() {
const response = await this.performLegacyRequest(`v1/groups`);
return response.groups;
}
/**
* Gets a group, including user ids. See https://docs.truevault.com/groups#read-a-group.
* @param {string} groupId group id to get.
* @returns {Promise.<Object>}
*/
async readFullGroup(groupId) {
const response = await this.performLegacyRequest(`v1/groups/${groupId}?full=true`);
return response.group;
}
/**
* Add users to a group. See https://docs.truevault.com/groups#add-users-to-a-group.
* @param {string} groupId group to add to.
* @param {Array} userIds user ids to add to the group.
* @returns {Promise.<undefined>}
*/
async addUsersToGroup(groupId, userIds) {
await this.performJSONRequest(`v1/groups/${groupId}/membership`, {
method: 'POST',
body: JSON.stringify({user_ids: userIds})
});
}
/**
* Remove users from a group. See https://docs.truevault.com/groups#remove-users-from-a-group
* @param {string} groupId group to add to.
* @param {Array} userIds user ids to add to the group.
* @returns {Promise.<undefined>}
*/
async removeUsersFromGroup(groupId, userIds) {
await this.performJSONRequest(`v1/groups/${groupId}/membership/${userIds.join(',')}`, {
method: 'DELETE'
});
}
/**
* Add users to a group returning user ids. See https://docs.truevault.com/groups#update-a-group.
* @param {string} groupId group to add to.
* @param {Array} userIds user ids to add to the group.
* @returns {Promise.<Object>}
*/
async addUsersToGroupReturnUserIds(groupId, userIds) {
const formData = new tvFormData();
formData.append('operation', 'APPEND');
formData.append('user_ids', userIds.join(','));
const response = await this.performLegacyRequest(`v1/groups/${groupId}`, {
method: 'PUT',
body: formData
});
return response.group;
}
/**
* Remove users from a group. See https://docs.truevault.com/groups#update-a-group
* @param {string} groupId group to remove from.
* @param {Array} userIds user ids to remove from the group.
* @returns {Promise.<Object>}
*/
async removeUsersFromGroupReturnUserIds(groupId, userIds) {
const formData = new tvFormData();
formData.append('operation', 'REMOVE');
formData.append('user_ids', userIds.join(','));
const response = await this.performLegacyRequest(`v1/groups/${groupId}`, {
method: 'PUT',
body: formData
});
return response.group;
}
/**
* Perform a user search. See https://docs.truevault.com/documentsearch#search-users.
* @param {Object} searchOption search query. See https://docs.truevault.com/documentsearch#defining-search-options.
* @returns {Promise.<Object>}
*/
async searchUsers(searchOption) {
const formData = new tvFormData();
formData.append("search_option", base64.encode(JSON.stringify(searchOption)));
const response = await this.performLegacyRequest(`v1/users/search`, {
method: 'POST',
body: formData
});
const documents = response.data.documents.map(doc => {
if (doc.attributes) {
doc.attributes = JSON.parse(base64.decode(doc.attributes));
}
return doc;
});
return {
info: response.data.info,
documents
};
}
/**
* Lists all vaults. See https://docs.truevault.com/vaults#list-all-vaults.
* @param [page=1]
* @param [per_page=100]
* @returns {Promise<*>}
*/
async listVaults(page, per_page) {
if (typeof page !== "number") {
page = 1;
}
if (typeof per_page !== "number") {
per_page = 100
}
const response = await this.performLegacyRequest(`v1/vaults?page=${page}&per_page=${per_page}`);
return response.vaults;
}
/**
* Create a new vault. See https://docs.truevault.com/vaults#create-a-vault.
* @param {string} name the name of the new vault.
* @returns {Promise.<Object>}
*/
async createVault(name) {
const formData = new tvFormData();
formData.append("name", name);
const response = await this.performLegacyRequest('v1/vaults', {
method: 'POST',
body: formData
});
return response.vault;
}
/**
* Read a vault. See https://docs.truevault.com/vaults#read-a-vault
* @param vaultId
* @returns {Promise<Object>}
*/
async readVault(vaultId) {
const response = await this.performLegacyRequest(`v1/vaults/${vaultId}`);
return response.vault;
}
/**
* Update a vault. See https://docs.truevault.com/vaults#update-a-vault
* @param vaultId
* @param name
* @returns {Promise<Object>}
*/
async updateVault(vaultId, name) {
const formData = new tvFormData();
formData.append('name', name);
const response = await this.performLegacyRequest(`v1/vaults/${vaultId}`, {
method: 'PUT',
body: formData
});
return response.vault;
}
/**
* Delete a vault. See https://docs.truevault.com/vaults#delete-a-vault
* @param vaultId
* @returns {Promise<Object>}
*/
async deleteVault(vaultId) {
const response = await this.performLegacyRequest(`v1/vaults/${vaultId}`, {
method: 'DELETE'
});
return response.vault;
}
/**
* Create a new schema. See https://docs.truevault.com/schemas#create-a-schema.
* @param {string} vaultId the vault that should contain the schema.
* @param {string} name the name of the schema.
* @param {Array} fields field metadata for the schema. See https://docs.truevault.com/schemas.
* @returns {Promise.<Object>}
*/
async createSchema(vaultId, name, fields) {
const schemaDefinition = {name, fields};
const formData = new tvFormData();
formData.append("schema", base64.encode(JSON.stringify(schemaDefinition)));
const response = await this.performLegacyRequest(`v1/vaults/${vaultId}/schemas`, {
method: 'POST',
body: formData
});
return response.schema;
}
/**
* Create a new schema. See https://docs.truevault.com/schemas#update-a-schema
* @param {string} vaultId the vault that should contain the schema.
* @param {string} schemaId the schemathat should contain the schema.
* @param {string} name the name of the schema.
* @param {Array} fields field metadata for the schema. See https://docs.truevault.com/schemas.
* @returns {Promise.<Object>}
*/
async updateSchema(vaultId, schemaId, name, fields) {
const schemaDefinition = {name, fields};
const formData = new tvFormData();
formData.append("schema", base64.encode(JSON.stringify(schemaDefinition)));
const response = await this.performLegacyRequest(`v1/vaults/${vaultId}/schemas/${schemaId}`, {
method: 'PUT',
body: formData
});
return response.schema;
}
/**
* Read a schema. See https://docs.truevault.com/schemas#read-a-schema
* @param vaultId
* @param schemaId
* @returns {Promise<Object>}
*/
async readSchema(vaultId, schemaId) {
const response = await this.performLegacyRequest(`v1/vaults/${vaultId}/schemas/${schemaId}`);
return response.schema;
}
/**
* List all schemas in a vault. See https://docs.truevault.com/schemas#list-all-schemas
* @param vaultId
* @returns {Promise<Object>}
*/
async listSchemas(vaultId) {
const response = await this.performLegacyRequest(`v1/vaults/${vaultId}/schemas`);
return response.schemas;
}
/**
* Delete a schema. See https://docs.truevault.com/schemas#delete-a-schema
* @param vaultId
* @param schemaId
* @returns {Promise<undefined>}
*/
async deleteSchema(vaultId, schemaId) {
await this.performLegacyRequest(`v1/vaults/${vaultId}/schemas/${schemaId}`, {
method: 'DELETE'
});
}
/**
* Create the user schema. See https://docs.truevault.com/schemas#create-the-user-schema
* @param {string} accountId account id that the user schema belongs to.
* @param {string} name the name of the schema.
* @param {Array} fields field metadata for the schema. See https://docs.truevault.com/schemas.
* @returns {Promise.<Object>}
*/
async createUserSchema(accountId, name, fields) {
const schemaDefinition = {name, fields};
const formData = new tvFormData();
formData.append("schema", base64.encode(JSON.stringify(schemaDefinition)));
const response = await this.performLegacyRequest(`v1/accounts/${accountId}/user_schema`, {
method: 'POST',
body: formData
});
return response.user_schema;
}
/**
* Read the user schema. See https://docs.truevault.com/schemas#read-the-user-schema
* @param {string} accountId account id that the user schema belongs to.
* @returns {Promise.<Object>}
*/
async readUserSchema(accountId) {
const response = await this.performLegacyRequest(`v1/accounts/${accountId}/user_schema`, {
method: 'GET',
});
return response.user_schema;
}
/**
* Update the user schema. See https://docs.truevault.com/schemas#update-the-user-schema
* @param {string} accountId account id that the user schema belongs to.
* @param {string} name the name of the schema.
* @param {Array} fields field metadata for the schema. See https://docs.truevault.com/schemas.
* @returns {Promise.<Object>}
*/
async updateUserSchema(accountId, name, fields) {
const schemaDefinition = {name, fields};
const formData = new tvFormData();
formData.append("schema", base64.encode(JSON.stringify(schemaDefinition)));
const response = await this.performLegacyRequest(`v1/accounts/${accountId}/user_schema`, {
method: 'PUT',
body: formData
});
return response.user_schema;
}
/**
* Delete the user schema. See https://docs.truevault.com/schemas#delete-the-user-schema
* @param {string} accountId account id that the user schema belongs to.
* @returns {Promise.<Object>}
*/
async deleteUserSchema(accountId) {
const response = await this.performLegacyRequest(`v1/accounts/${accountId}/user_schema`, {
method: 'DELETE',
body: new tvFormData()
});
return response.user_schema;
}
/**
* Create a new document. See https://docs.truevault.com/documents#create-a-document.
* @param {string} vaultId vault to place the document in.
* @param {string|null} schemaId schema to associate with the document.
* @param {Object} document document contents.
* @param {string|null} [ownerId] the document's owner.
* @returns {Promise.<Object>}
*/
async createDocument(vaultId, schemaId, document, ownerId) {
const body = {document};
if (typeof schemaId === 'string') {
body.schema_id = schemaId;
}
if (typeof ownerId === 'string') {
body.owner_id = ownerId;
}
const response = await this.performJSONRequest(`v2/vaults/${vaultId}/documents`, {
method: 'POST',
body: JSON.stringify(body)
});
return response.document;
}
/**
* List documents in a vault. See https://docs.truevault.com/documents#list-all-documents.
* @param {string} vaultId vault to look in.
* @param {boolean} full include document contents in listing.
* @param {number} [page] which page to get, if pagination is needed.
* @param {number} [perPage] number of documents per page.
* @returns {Promise.<Object>}
*/
async listDocuments(vaultId, full, page, perPage) {
let url = `v1/vaults/${vaultId}/documents?`;
if (!!full) {
url += `&full=${full}`;
}
if (!!page) {
url += `&page=${page}`;
}
if (!!perPage) {
url += `&per_page=${perPage}`;
}
const response = await this.performLegacyRequest(url);
if (!!full) {
response.data.items = response.data.items.map(item => {
if (item.document) {
item.document = JSON.parse(base64.decode(item.document));
}
return item;
});
}
return response.data;
}
/**
* List documents in a schema. See https://docs.truevault.com/documents#list-all-documents-with-schema
* @param {string} vaultId vault to look in.
* @param {string} schemaId
* @param {boolean} [full] include document contents in listing.
* @param {number} [page] which page to get, if pagination is needed.
* @param {number} [perPage] number of documents per page.
* @returns {Promise.<Object>}
*/
async listDocumentsInSchema(vaultId, schemaId, full, page, perPage) {
let url = `v1/vaults/${vaultId}/schemas/${schemaId}/documents?`;
if (!!full) {
url += `&full=${full}`;
}
if (!!page) {
url += `&page=${page}`;
}
if (!!perPage) {
url += `&per_page=${perPage}`;
}
const response = await this.performLegacyRequest(url);
if (!!full) {
response.data.items = response.data.items.map(item => {
if (item.document) {
item.document = JSON.parse(base64.decode(item.document));
}
return item;
});
}
return response.data;
}
/**
* Get the contents of one or more documents. See https://docs.truevault.com/documents#read-a-document.
* @param {string} vaultId vault to look in.
* @param {Array} documentIds document ids to retrieve.
* @returns {Promise.<Array>}
*/
async getDocuments(vaultId, documentIds) {
let requestDocumentIds;
if (documentIds.length === 0) {
return [];
} else if (documentIds.length === 1) {
// Sending a single ID to the API will only return the document's contents. In order to
// retrieve a proper multiget response with `id` and `owner_id`, we need to send a
// request with two instances of the same document ID. We will then only return the
// first result from the response.