forked from IBM-Blockchain-Identity/openssi-websdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsdk.js
1878 lines (1669 loc) · 74.8 KB
/
sdk.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
/**
© Copyright IBM Corp. 2019, 2019
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const async = require('async');
const fetch = require('node-fetch');
const URL = require('url').URL;
const https = require('https');
const http = require('http');
const jsonPrint = function (o) {
if (typeof o === 'string') return o;
return JSON.stringify(o, 2, ' ');
};
const LOG_LEVELS = Object.freeze([
'trace',
'debug',
'info',
'warn',
'error',
'fatal',
'disabled'
]);
/**
* A simple logging mechanism for the SDK.
*/
class Logger {
/**
* Creates a Logger with the given logging level that will prefix messages with the given name.
* @param {'trace'|'debug'|'info'|'warn'|'error'|'fatal'} log_level The desired logging level.
* @param {string} name The prefix for the log messages.
*/
constructor (log_level, name) {
if (!name || typeof name !== 'string')
throw new TypeError(`Invalid logger name: ${name}`);
if (LOG_LEVELS.indexOf(log_level) < 0)
throw new TypeError(`Invalid log level: ${log_level}`);
this.name = name;
this.level = log_level;
}
setLogLevel (level) {
if (LOG_LEVELS.indexOf(level) < 0)
throw new Error(`Invalid log level: ${level}`);
this.level = level;
}
trace (message) {
const valid_levels = LOG_LEVELS.slice(LOG_LEVELS.indexOf(this.level), LOG_LEVELS.length);
if (valid_levels.indexOf('trace') >= 0)
console.log(make_message(message, 'trace', this.name));
}
debug (message) {
const valid_levels = LOG_LEVELS.slice(LOG_LEVELS.indexOf(this.level), LOG_LEVELS.length);
if (valid_levels.indexOf('debug') >= 0)
console.log(make_message(message, 'debug', this.name));
}
info (message) {
const valid_levels = LOG_LEVELS.slice(LOG_LEVELS.indexOf(this.level), LOG_LEVELS.length);
if (valid_levels.indexOf('info') >= 0)
console.log(make_message(message, 'info', this.name));
}
warn (message) {
const valid_levels = LOG_LEVELS.slice(LOG_LEVELS.indexOf(this.level), LOG_LEVELS.length);
if (valid_levels.indexOf('warn') >= 0)
console.log(make_message(message, 'warn', this.name));
}
error (message) {
const valid_levels = LOG_LEVELS.slice(LOG_LEVELS.indexOf(this.level), LOG_LEVELS.length);
if (valid_levels.indexOf('error') >= 0)
console.log(make_message(message, 'error', this.name));
}
fatal (message) {
const valid_levels = LOG_LEVELS.slice(LOG_LEVELS.indexOf(this.level), LOG_LEVELS.length);
if (valid_levels.indexOf('fatal') >= 0)
console.log(make_message(message, 'fatal', this.name));
}
}
function make_message (message, level, name) {
return `${new Date().toISOString()} [${name}] ${level}: ${message}`;
}
class Agent {
/**
* Constructs an Agent instance for a user
*
* @param {string} account_url The Agent endpoint url
* @param {string} agent_name User name for Agent endpoint
* @param {string} agent_password Password for Agent endpoint
* @param {string} friendly_name The human readable name of the user
* @param {string} log_level Logging level for Agent debugging
*/
constructor (account_url, agent_name, agent_password, friendly_name, log_level) {
this.setUrl(account_url);
this.setUserPassword(agent_name, agent_password);
this.setUserName(friendly_name);
this.logger = new Logger(log_level || 'disabled', `agent/${this.user}`);
}
/**
* Set url of Agent
*
* @param {string} url The new URL for the Agency.
* @returns {void}
*/
setUrl (url) {
this.url = url;
}
/**
* Set user and password for user's Agent
*
* @param {string} user A TI Agent identity.
* @param {string} pw The password for the Agency identity.
* @returns {void}
*/
setUserPassword (user, pw) {
this.user = user;
this.pw = pw;
this.authHeader = 'Basic ' + Buffer.from(user + ':' + pw).toString('base64');
}
/**
* Set human readable user name that is displayed in connection, credential or proof UI
*
* @param {string} name The human readable name of the user
* @returns {void}
*/
setUserName (name) {
this.name = name;
}
/**
* Enable logging for the agent by setting a logging level.
*
* @param {'trace'|'debug'|'info'|'warn'|'error'|'fatal'} log_level The desired logging level.
* @returns {void}
*/
setLoggingLevel (log_level) {
this.logger.setLogLevel(log_level);
}
//---------------------------------------------------------------------------------
// IDENTITIES
//---------------------------------------------------------------------------------
/**
* A URL associated with a cloud agent account.
* @typedef {string} AccountURL
*/
/**
* The name of an agent. Generally only useful if you also know the {@link AccountURL}. Ex. admin, gov-dmv, thrift, etc.
* @typedef {string} AgentName
*/
/**
* The URL needed to connect to an agent. Combines the {@link AgentName} and {@link AccountURL}.
* @typedef {string} AgentURL
*/
/**
* Represents an agent on a given cloud agent account.
* @typedef {object} AgentInfo
* @property {AgentName} name The name of the agent.
* @property {AgentURL} url The connection url for the agent.
* @property {string|null} role The role of the agent. TRUST_ANCHORs are allowed to publish credential schemas and
* definitions.
* @property {Verkey} verkey The public key for the agent.
* @property {DID} did The DID for the agent.
* @property {string} creation_time A datetime string for when the agent was created.
* @property {number} expiration A timestamp, in milliseconds, for when the agent's password expires.
* @property {object} metrics Metrics about the agent, such as incoming connections, etc.
*/
/**
* Get this agent's {@link AgentInfo}.
*
* @return {Promise<AgentInfo>} A promise that resolves with information about the agent.
*/
async getIdentity () {
this.logger.info(`Getting agent info for ${this.user}`);
const r = await this.request('info');
this.logger.debug('User = '+jsonPrint(r));
return r;
}
/**
* Create a {@link AgentInfo} on the account. If self_registration is disabled, you have to create an agent with
* some password, and then change that password as the agent that was created. This function attempts to handle
* both self-registration and non-self-registration scenarios.
*
* @param {string} account_admin_agent_name The admin agent on this agent's account. Only needed if create is true.
* @param {string} account_admin_agent_password The admin agent's password.
* @return {Promise<AgentInfo>} A promise that resolves with information about the agent that was created.
*/
async createIdentity (account_admin_agent_name, account_admin_agent_password) {
if (!account_admin_agent_name || typeof account_admin_agent_name !== 'string')
throw new TypeError('Account\'s admin agent name was not provided');
if (!account_admin_agent_password || typeof account_admin_agent_password !== 'string')
throw new TypeError('Invalid admin agent password');
const admin_auth = 'Basic ' + Buffer.from(account_admin_agent_name + ':' + account_admin_agent_password).toString('base64');
this.logger.info('Determining if self-registration is enabled on the agent');
const settings = await this.request('settings', {
'headers': {'Authorization': admin_auth},
});
if (settings && settings.self_registration) {
this.logger.info('Self registration is enabled. Don\'t need to change the password');
this.logger.info(`Creating agent: ${this.user}`);
const r = await this.request('identities', {
'headers': {'Authorization': admin_auth},
'method': 'POST',
'body': JSON.stringify({'name': this.user, 'password': this.pw})
});
this.logger.debug('Result from createIdentity: '+jsonPrint(r));
return r;
} else {
this.logger.info('Self-registration is disabled');
this.logger.info(`Creating agent: ${this.user}`);
try {
const r = await this.request('identities', {
'headers': {'Authorization': admin_auth},
'method': 'POST',
'body': JSON.stringify({'name': this.user, 'password': this.pw + '1'})
});
this.logger.debug('Result from creating identity: '+jsonPrint(r));
this.logger.info(`Changing ${this.user}'s password`);
} catch (error) {
this.logger.error(`Failed to create identity: ${error}`);
if (error.code === 504) {
this.logger.warn('Giving the agent a little more time to finish...');
await new Promise((resolve, reject) => {
setTimeout(resolve, 20000);
});
} else {
throw error;
}
}
const my_auth = 'Basic ' + Buffer.from(this.user + ':' + this.pw).toString('base64');
this.logger.info(`Setting ${this.user}'s password`);
const r = await this.request(`identities/${this.user}/password`, {
'headers': {'Authorization': my_auth},
'method': 'POST',
'body': JSON.stringify({password_old: this.pw + '1', password_new: this.pw})
});
this.logger.info(`Set ${this.user}'s password`);
return r;
}
}
/**
* Set this agent's role to TRUST_ANCHOR on the ledger, giving the agent the ability to publish schemas and
* credential definitions, which are needed to issue credentials.
*
* @param {string} account_admin_agent_name The admin agent on this agent's account. Only needed if create is true.
* @param {string} account_admin_agent_password The admin agent's password.
* @param {string} [seed] A valid trustee seed. Allows this agent to generate the NYM transaction as the network's trustee.
* @returns {Promise<AgentInfo>} A promise that resolves with the updated agent information.
*/
async onboardAsTrustAnchor (account_admin_agent_name, account_admin_agent_password, seed) {
if (seed && typeof seed !== 'string')
throw new TypeError('Invalid seed for onboarding as a Trust Anchor');
const body = {
role: 'TRUST_ANCHOR'
};
if (seed) body.seed = seed;
this.logger.info(`Registering ${this.user} as a Trust Anchor`);
const auth = 'Basic ' + Buffer.from(account_admin_agent_name + ':' + account_admin_agent_password).toString('base64');
const r1 = await this.request('identities/' + this.user, {
'headers': {'Authorization': auth},
'method': 'PATCH',
'body': JSON.stringify(body)
});
this.logger.info(`Registered ${this.user} as a Trust Anchor`);
this.logger.debug('Result from onboardAsTrustAnchor: '+jsonPrint(r1));
return r1;
}
/**
* Get all listeners
*
* @returns {object[]} Array of listener objects
*/
async getListeners () {
const r = await this.request('listeners');
this.logger.debug('Result from getListeners: '+jsonPrint(r));
return r;
}
/**
* Delete listener
*
* @param {string} id The ID of a listener
* @returns {object} The delete response from Agency
*/
async deleteListener (id) {
const r = await this.request('listeners/' + id, {
'method': 'DELETE'
});
this.logger.debug('Result from deleteListener: '+jsonPrint(r));
return r;
}
/**
* Get all devices
*
* @returns {object[]} Array of device objects
*/
async getDevices () {
const r = await this.request('devices');
this.logger.debug('Result from getDevices: '+jsonPrint(r));
return r;
}
/**
* Delete device
*
* @param {string} id The ID of a device
* @returns {object} The delete response from Agency
*/
async deleteDevice (id) {
const r = await this.request('devices/' + id, {
'method': 'DELETE'
});
this.logger.debug('Result from deleteDevice: '+jsonPrint(r));
return r;
}
//*********************************************************************************
// CREDENTIAL SCHEMAS
//*********************************************************************************
/**
* The identifier for a {@link CredentialSchema} on both the agent and the public ledger. If you're curious, the
* ID is composed of the schema publisher's {@link DID}, a transaction type, the schema name, and the schema version.
* Ex. "R4PbDKCjZTWFh1vBc5Zaxc:2:Thrift Account:1.0"
* @typedef {string} CredentialSchemaID
*/
/**
* A CredentialSchema represents a list of attributes that a credential based on the schema can contain.
* {
* "attr_names": [
* "first_name",
* "last_name"
* ],
* "id": "R4PbDKCjZTWFh1vBc5Zaxc:2:Thrift Account:1.0",
* "name": "Thrift Account",
* "namever": "Thrift Account:1.0",
* "version": "1.0"
* }
* @typedef {object} CredentialSchema
* @property {CredentialSchemaID} id The ID of the schema.
* @property {string} name The name of the schema.
* @property {string} version A tuple representing the schema version (1.0, 1.1.2, etc.).
* @property {string} namever The name and version joined with a ':'.
* @property {string[]} attr_names The list of attributes that a credential based on the schema can have.
*/
/**
* Creates a {@link CredentialSchema}, meaning the schema is published on the ledger.
*
* @param {string} name The name of the schema.
* @param {string} version A tuple representing the schema version (1.0, 1.1.2, etc.)
* @param {string[]} attributes The list of attributes credentials based on this schema must have.
* @return {Promise<CredentialSchema>} A promise that resolves with the new schema record.
*/
async createCredentialSchema (name, version, attributes) {
if (!name || typeof name !== 'string')
throw new Error('Cannot create a credential schema without a name');
if (!version || typeof version !== 'string')
throw new Error('Cannot create a credential schema without a version');
if (!attributes.length || typeof attributes[0] !== 'string')
throw new Error('Cannot create a credential schema without attributes');
this.logger.info(`Creating credential schema ${name} ${version}`);
this.logger.debug(`Credential schema ${name} ${version} attributes: ${jsonPrint(attributes)}`);
const r = await this.request('credential_schemas', {
'method': 'POST',
'body': JSON.stringify({'name':name, 'version':version, 'attrs':attributes})
});
this.logger.info(`Published credential schema ${r.id}`);
this.logger.debug('Result from createCredentialSchema: '+jsonPrint(r));
return r;
}
/**
* Get a {@link CredentialSchema} record.
*
* @param {CredentialSchemaID} id The ID of the schema
* @return {Promise<CredentialSchema>} A promise that resolves with the schema object, or null if not found
*/
async getCredentialSchema (id) {
if (!id || typeof id !== 'string')
throw new TypeError('Must provide an ID to lookup a credential schema');
this.logger.info(`Getting credential schema ${id}`);
const r = await this.request(`credential_schemas/${id}`);
this.logger.info(`Got credential schema ${r.id}`);
this.logger.debug('Result from getCredentialSchema: '+jsonPrint(r));
return r;
}
/**
* An object listing [BSON query parameters]{@link https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {@link CredentialSchema}. The fields below are just examples to give you an idea;
* there are other queries you can make.
* {
* name: 'My Schema',
* version: { $ne: '1.0' }
* }
* @typedef {object} CredentialSchemaQueryParams
* @property {string} [id] The ID of the schema
* @property {string} [name] The name of the schema
*/
/**
* A set of parameters that cause the agent to collect a set of responses from other agents that it has connections
* to. It's a list of {@link Connection} property names and values. For example,
* {
* property1: true,
* property2: 'prop2'
* }
* causes this agent to look for connections with property1=true. It will send propagate the request to each
* relevant connection. The agents receiving the request will look for connections with property2=prop2 custom and
* recursively propagate the request along those connections, etc.
* @typedef {object} QueryRoute
* @property {boolean} [trustedVerifier] Propagates the request to connections with trusted verifiers.
* @property {boolean} [trustedIssuer] Propagates the request to connections with trusted issuers.
*/
/**
* @typedef {object} AgentResponse
* @property {DID} did The pairwise DID for the remote agent.
* @property {AgentName} name The agent name for the remote agent.
* @property {object} results The list of {@link CredentialSchemas} or {@link CredentialDefinitions} found by the
* remote agent.
* @property {number} results.count The number of results found by the remote agent.
* @property {CredentialSchema[]|CredentialDefinition[]}
*/
/**
* @typedef {object} RouteResponse
* @property {AgentResponse[]} agents A list of agent responses containing
*/
/**
* Get a list of all {@link CredentialSchema}s published by your agent, if no parameters are specified, or a list of
* credential schemas matching the search parameters. You can use the `route` parameter to direct the request to
* other agents.
*
* @param {CredentialSchemaQueryParams} [opts] An optional filter for the schemas that are returned.
* @param {QueryRoute} [route] A list of parameters used to proxy the request to other agents.
* @return {Promise<CredentialSchema[]>} A promise that resolves with a list of credential schemas.
*/
async getCredentialSchemas (opts, route) {
let query = '';
if (opts) {
if (typeof opts !== 'object')
throw new TypeError('Invalid query parameters');
query = `?filter=${JSON.stringify(opts)}`;
}
if (route) {
if (typeof route !== 'object')
throw new TypeError('Invalid route parameters');
let routeparams = 'route=';
for (const key in route) {
routeparams += `${key}:${route[key]},`;
}
query = query ? `${query}&${routeparams}` : `?${routeparams}`;
}
this.logger.info('Getting credential schemas');
this.logger.debug(`Getting credential schemas that match: ${query}`);
let r = await this.request(`credential_schemas${query}`);
if (r.items) r = r.items;
this.logger.info(`Got ${r.length} credential schemas`);
this.logger.debug('Result from getCredentialSchemas: '+jsonPrint(r));
return r;
}
//*********************************************************************************
// CREDENTIAL DEFINITIONS
//*********************************************************************************
/**
* Resolves to a published credential definition on the ledger. Consists of a DID, a transaction type (3 means a
* credential definition in Hyperledger Indy), CL, a transaction number, and a tag.
* Ex. 'JeU3p99QCt3p5tjZJyPwUK:3:CL:357:TAG1'
* @typedef {string} CredentialDefinitionID
*/
/**
* When an issuer wants to issue credentials based on a certain schema, they have to publish a credential definition
* on the ledger for that schema.
* @typedef {object} CredentialDefinition
* @property {object} data The cryptographic content of the credential definition. Good at filling up logs.
* @property {CredentialDefinitionID} id The ID of the credential definition on both the agent and the ledger.
* @property {CredentialSchemaID} schema_id The credential schema this credential definition pertains to.
* @property {string} schema_name The name of the credential schema.
* @property {string} version The version of the credential schema.
*/
/**
* Create a {@link CredentialDefinition}
* @param {CredentialSchemaID} schemaId The ledger ID for the schema.
* @return {Promise<CredentialDefinition>} The created credential definition.
*/
async createCredentialDefinition (schemaId) {
if (!schemaId || typeof schemaId !== 'string')
throw new TypeError('Must provide a credential schema ID to create a credential definition');
this.logger.info(`Creating credential definition for schema ${schemaId}`);
const r = await this.request('credential_definitions', {
'method': 'POST',
'body': JSON.stringify({'schema_id':schemaId})
});
this.logger.info(`Created credential definition for schema ${schemaId}`);
this.logger.debug('Result from createCredentialDefinition: '+jsonPrint(r));
return r;
}
/**
* Get a {@link CredentialDefinition}.
* @param {CredentialDefinitionID} id The credential definition ID.
* @returns {Promise<CredentialDefinition>} A promise that resolves with the credential definition.
*/
async getCredentialDefinition (id) {
if (!id || typeof id !== 'string')
throw new TypeError('Invalid credential definition ID');
this.logger.info(`Getting credential definition ${id}`);
const r = await this.request(`credential_definitions/${id}`);
this.logger.info(`Got credential definition ${r.id}`);
this.logger.debug(`Result from getCredentialDefinition: ${jsonPrint(r)}`);
return r;
}
/**
* An object listing [BSON query parameters]{@link https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {@link CredentialDefinition}. The fields below are just examples to give you an idea;
* there are other queries you can make.
* {
* schema_name: 'My Schema',
* version: { $ne: '1.0' }
* }
* @typedef {object} CredentialDefinitionQueryParams
* @property {string} [id] The ID of the credential definition
* @property {string} [schema_name] The name of the schema for the credential definition
*/
/**
* Get a list of {@link CredentialDefinition}s matching the given parameters, or all of them, if no parameters are
* given.
*
* @param {CredentialDefinitionQueryParams} [opts] Credential definition search parameters.
* @param {QueryRoute} [route] A list of parameters used to proxy the request to other agents.
* @return {Promise<CredentialDefinition[]>} A promise that resolves with a list of credential definitions.
*/
async getCredentialDefinitions (opts, route) {
let query = '';
if (opts) {
if (typeof opts !== 'object')
throw new TypeError('Invalid query parameters');
query = `?filter=${JSON.stringify(opts)}`;
}
if (route) {
if (typeof route !== 'object')
throw new TypeError('Invalid route parameters');
let routeparams = 'route=';
for (const key in route) {
routeparams += `${key}:${route[key]},`;
}
query = query ? `${query}&${routeparams}` : `?${routeparams}`;
}
this.logger.info('Getting credential definitions');
this.logger.debug(`Getting credential definitions that match: ${query}`);
let r = await this.request(`credential_definitions${query}`);
if (r.items) r = r.items;
this.logger.info(`Got ${r.length} credential definitions`);
this.logger.debug('Result from getCredentialDefinitions: '+jsonPrint(r));
return r;
}
//*********************************************************************************
// PROOF SCHEMAS
//*********************************************************************************
/**
* Criteria which must be true pertaining to an attribute or predicate in a {@link ProofSchema}. There is a logical
* AND between keys inside a Restriction and a logical OR between the Restrictions in a list. For example, consider
* the following restrictions field:
*
* 'restrictions': [{'schema_name': 'myschema', 'schema_version': '1.0'}, {'cred_def_id': 'XXX'}]
*
* This can be read as (schema_name == 'myschema' AND schema_version == '1.0') OR cred_def_id == 'XXX'. The list of
* possible restrictions:
*
* @typedef {object} Restriction
* @property {CredentialSchemaID} [schema_id] The DID of a credential schema.
* @property {DID} [schema_issuer_did] The DID of the schema issuer.
* @property {string} [schema_name] The name of the schema.
* @property {string} [schema_version] The value of the schema.
* @property {DID} [issuer_did] The DID of the issuer of the credential.
* @property {CredentialDefinitionID} [cred_def_id] The credential definition ID.
*/
/**
* A requirement in a {@link ProofSchema} that asks a prover not to provide a value for something, but to prove
* something _about_ a value, such as a value being greater than some limit. You could, for example, ask someone to
* prove that they're older than 21 with the following predicate:
* {
* name: 'age',
* p_type: '>',
* p_value: 21,
* restrictions: [{'cred_def_id': '<credential_definition_id>'}]
* }
* @typedef {object} ProofSchemaPredicate
* @property {string} name The name of the attribute.
* @property {string} p_type The type of the predicate. Defines an operation like ">" to check the attribute value.
* @property {number} p_value The value of the predicate. Define the boundary for the operation.
* @property {Restriction[]} restrictions A list of {@link Restriction}s to limit what credentials can supply the
* attribute for the predicate.
*/
/**
* Describes a request attribute in a proof request. If you don't specify any restrictions on the attribute, then
* the attribute is 'self attested', meaning the prover can put whatever they want in for that field.
* @typedef {object} ProofSchemaAttribute
* @property {Restriction[]} [restrictions] A list of {@link Restriction}s on to limit what credentials can supply
* the attribute.
*/
/**
* An object describing the contents of a proof request, which is basically a prepared query for a list of verified
* or self attested attributes and predicates from a prover. An example:
* {
* 'name': 'proof-schema1',
* 'version': '1.0',
* 'requested_attributes': {
* 'attr1_referent': {
* 'name': 'attr1',
* 'restrictions': [{'schema_name': 'cred_schema1', 'schema_version': '1.0'}]
* },
* 'attr2_referent': {
* 'name': 'attr2',
* 'restrictions': [{'cred_def_id': '<credential_definition_id>'}]
* },
* 'self_attested_attr1_referent': {
* 'name': 'self-attested-attr1'
* },
* },
* 'requested_predicates': {
* 'predicate1_referent': {
* 'name': 'attr3',
* 'p_type': '>',
* 'p_value': 5,
* 'restrictions': [{'cred_def_id': '<credential_definition_id>'}]
* }
* }
* }
* @typedef {object} ProofSchema
* @property {string} id The ID of the proof schema.
* @property {string} name The name of the proof schema. Ex. "proof_of_employment".
* @property {string} version The version of the proof schema. Ex. "1.0", "1.0.0", etc.
* @property {object<ProofSchemaAttribute>} requested_attributes A list of attributes to be provided by credentials
* @property {object<ProofSchemaPredicate>} requested_predicates A list of predicates to be included in the proof
*/
/**
* Create a {@link ProofSchema}.
* @param {string} name The name of the schema.
* @param {string} version The version of the schema.
* @param {object<ProofSchemaAttribute>} [requestedAttributes] A list of requested attributes.
* @param {object<ProofSchemaPredicate>} [requestedPredicates] A list of requested predicates.
* @returns {Promise<ProofSchema>} A promise that resolves with the created proof schema.
*/
async createProofSchema (name, version, requestedAttributes, requestedPredicates) {
if (!name || typeof name !== 'string')
throw new TypeError('Invalid name for proof schema');
if (!version || typeof version !== 'string')
throw new TypeError('Invalid version for proof schema');
if (requestedAttributes && typeof requestedAttributes !== 'object')
throw new TypeError('Invalid requested attributes list for proof schema');
if (requestedPredicates && typeof requestedPredicates !== 'object')
throw new TypeError('Invalid requested predicates list for proof schema');
const body = {
name: name,
version: version,
requested_attributes: requestedAttributes ? requestedAttributes : {},
requested_predicates: requestedPredicates ? requestedPredicates : {}
};
this.logger.info(`Creating proof schema ${name} ${version}`);
this.logger.debug(`Attributes: ${jsonPrint(requestedAttributes)}\nPredicates: ${jsonPrint(requestedPredicates)}`);
const r = await this.request('proof_schemas', {
'method': 'POST',
'body': JSON.stringify(body)
});
this.logger.info(`Created proof schema ${r.id}`);
this.logger.debug('Result from verifierCreateProofSchema: '+jsonPrint(r));
return r;
}
/**
* An object listing [BSON query parameters]{@link https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {@link ProofSchema}. The fields below are just examples to give you an idea;
* there are other queries you can make.
* {
* name: 'My Schema',
* version: { $ne: '1.0' }
* }
* @typedef {object} ProofSchemaQueryParams
* @property {string} [name] The name of the proof schema
* @property {string} [version] The version of the proof schema
*/
/**
* Gets a list of {@link ProofSchema}s matching the query parameters, if any are given, or all proof schemas on the agent.
* @param {ProofSchemaQueryParams} [opts] Query parameters.
* @returns {Promise<ProofSchema[]>} A promise that resolves with a list of proof schemas
*/
async verifierGetProofSchemas (opts) {
let query = '';
if (opts) {
if (typeof opts !== 'object')
throw new TypeError('Invalid query parameters');
query = `?filter=${JSON.stringify(opts)}`;
}
this.logger.info('Getting proof schemas');
this.logger.info(`Getting proof schemas that match: ${query}`);
let r = await this.request(`proof_schemas${query}`);
this.logger.info(`r: ${JSON.stringify(r)}`);
if (r.items) r = r.items;
this.logger.info(`Got ${r.length} proof schemas`);
this.logger.debug('Result from getProofSchemas: '+jsonPrint(r));
return r;
}
/**
* Get a {@link ProofSchema}
*
* @param {string} id The proof schema ID.
* @return {Promise<ProofSchema>} A promise that resolves with the proof schema object.
*/
async verifierGetProofSchema (id) {
if (!id || typeof id !== 'string')
throw new TypeError('Must provide an ID to get a proof schema');
this.logger.info(`Getting proof schema ${id}`);
const r = await this.request(`proof_schemas/${id}`);
this.logger.info(`Got proof schema ${id}`);
this.logger.debug('Result from verifierGetProofSchema: '+jsonPrint(r));
return r;
}
//*********************************************************************************
// CONNECTIONS
//*********************************************************************************
/**
* A unique identifier use in communication on the Hyperledger Indy ledger. They represent users, agents, issuers, verifiers, etc.
* @typedef {string} DID
*/
/**
* A publicly shared key associated with a DID. The DID owner proves ownership of the DID using the private/signing key associated with this verkey.
* @typedef {string} Verkey
*/
/**
* A string representing image data. Generally used to store icons for decorating {@link Connection}s, {@link Credential}s,
* and {@link Verification}s.
* Ex. 'data:image/png;base64,iVBOR....'
* @typedef {string} ImageData
*/
/**
* Information about an agent involved in a {@link Connection}.
*
* @typedef {object} ConnectionAgent
* @property {AgentName} name The agent name.
* @property {string} role The agent's role on the ledger. Can be 'TRUST_ANCHOR' or 'NONE'.
* @property {AgentURL} url The agent url.
* @property {object} pairwise Identifying information dedicated to this specific connection.
* @property {DID} pairwise.did The pairwise connection DID.
* @property {Verkey} pairwise.verkey The pairwise verkey.
* @property {object} public Identifying information that has been published to the ledger.
* @property {DID} public.did A public DID.
* @property {Verkey} public.verkey A public verkey.
*/
/**
* Represents the state of a {@link Connection}.
* @typedef {'inbound_offer'|'outbound_offer'|'connected'|'rejected'} ConnectionState
*/
/**
* Connections represent a channel for communication between two agents.
*
* @typedef {object} Connection
* @property {string} id A unique identifier for this connection.
* @property {object} properties Properties of the connection. Generally used to sort or decorate connections.
* @property {ImageData} [properties.icon] An icon to display when someone views the connection.
* @property {string} [properties.name] A friendly name to display when someone views the connection.
* @property {string} role This agent's role in the connection. Can be 'offerer' or 'offeree'.
* @property {ConnectionState} state The state of the connection.
* @property {ConnectionAgent} [local] Information about this agent's role in the connection. Only present if this
* agent has accepted or initiated the connection.
* @property {ConnectionAgent} [remote] Information about the other agent's role in this connection. Only present if
* that agent accepted or initiated the connection.
*/
/**
* Gets a {@link Connection}.
* @param {string} id The ID for a connection.
* @return {Promise<Connection>} A promise that resolves with the given connection, or rejects if something went wrong.
*/
async getConnection (id) {
if (!id || typeof id !== 'string')
throw new TypeError('Connection ID must be a string');
this.logger.info(`Getting connection ${id}`);
const r = await this.request(`connections/${id}`);
this.logger.info(`Got connection ${r.id}`);
this.logger.debug('Result from getConnection: '+jsonPrint(r));
return r;
}
/**
* Delete a {@link Connection}.
*
* @param {string} id The ID of an existing connection.
* @returns {Promise<void>} A promise that resolves when the connection is deleted.
*/
async deleteConnection (id) {
if (!id || typeof id !== 'string')
throw new TypeError('Connection ID was not provided');
this.logger.info(`Deleting connection ${id}`);
const r = await this.request('connections/' + id, {
method: 'DELETE'
});
this.logger.info(`Deleted connection ${id}`);
this.logger.debug('Result from deleteConnection: '+jsonPrint(r));
}
/**
* An object listing [BSON query parameters]{@link https://docs.mongodb.com/manual/reference/operator/query/} that
* correspond to the fields in a {@link Connection} object. The keys listed below are simply examples to give you
* the idea; there are others.
* @typedef {object} ConnectionQueryParams
* @property {ConnectionState} [state] The connection state we're searching for.
* @property {AgentName} [remote.name] The name of the remote agent to match against.
* @property {DID} [remote.pairwise.did] The remote pairwise DID to match.
* {
* state: { $ne: 'inbound_offer' },
* 'remote.pairwise.did': 'A4DXofjbeC97WZAHU5MVGK'
* }
*/
/**
* Returns a list of {@link Connection}s. If query parameters are provided, only connections matching those parameters will
* be returned. If none are specified, all of the agent's connections will be returned.
* @param {ConnectionQueryParams} [opts] Connections search parameters.
* @return {Promise<Connection[]>} A list of all connections or only those matching the query parameters.
*/
async getConnections (opts) {
let query = '';
if (opts) {
if (typeof opts !== 'object')
throw new TypeError('Invalid query parameters');
query = `?filter=${JSON.stringify(opts)}`;
}
this.logger.info('Getting connections');
this.logger.debug(`getConnections query: ${query}`);
let r = await this.request(`connections${query}`);
if (r.items) r = r.items;
this.logger.info(`Got ${r.length} connections`);
this.logger.debug(`Result from getConnections for query '${query}': ${jsonPrint(r)}`);
return r;
}
/**
* Describes the recipient of a {@link Connection}. You must specify either the name of an agent in your agent's
* same account, or the full {@link AgentURL} to a remote agent.
* @typedef {object} ConnectionRecipient
* @property {AgentURL} [url] The full {@link AgentURL} for the other agent.
* @property {AgentName} [name] The name of an agent in your account.
*/
/**
* {@link Connection}s, {@link Credential}s, and {@link Verification}s can all be extended by adding additional
* properties during their creation. For example, setting an icon in the properties of a connection could cause
* that connection to be displayed with an icon when a user views it in their agent UI. The properties listed below
* are merely examples to demonstrate what these properties could be used for.
* @typedef {object} Properties
* @property {ImageData} [properties.icon] An image to display when someone views the connection.
* @property {string} [properties.name] A friendly name to display for the issuer when the connection is viewed.
* @property {string} [properties.time] A timestamp used to sort the connection in a list.
*/
/**
* Create a {@link Connection}. If recipient information is provided, the agent will attempt to contact the
* recipient agent and create an inbound connection offer on that agent. Otherwise, the connection offer is only
* created on this agent, and the returned object must be passed to the intended recipient agent out-of-band in
* order to establish the connection.
*
* @param {ConnectionRecipient} [to] The recipient agent.
* @param {Properties} [properties] Optional metadata to add to the connection offer.
* @return {Promise<Connection>} The connection offer, or the active {@link Connection} if one is already established.
*/
async createConnection (to, properties) {
if (properties && typeof properties !== 'object')
throw new TypeError('Invalid properties for credential offer');
// Create the connection offer with optional metadata
const body = {
properties: properties ? properties : {}
};
if (!body.properties.type) body.properties.type = 'child';
// Add an optional friendly name to the request
if (this.name && !body.properties.name) body.properties.name = this.name;
// It's useful to timestamp offers so you can sort them by most recent
if (!body.properties.time) body.properties.time = (new Date()).toISOString();
if (to) {
if (!to.url && !to.name)
throw new TypeError('Must specify an agent name or agent url to send a connection offer');
if (to.url && to.name)
throw new TypeError('Must specify only an agent name or an agent url for a connection, not both');
if (to.url && typeof to.url !== 'string')
throw new TypeError('Invalid agent url for connection offer');
if (to.name && typeof to.name !== 'string')
throw new TypeError('Invalid agent name for connection offer');
// Return any active connections
let search;
if (to.url)
search = {
'remote.url': to.url
};
else
search = {
'remote.name': to.name
};
const incoming_connections = [], offered_connections = [];
this.logger.info(`Checking for existing connections to ${JSON.stringify(to)}`);
const all_remote_connections = await this.getConnections(search);
for (const index in all_remote_connections) {