-
Notifications
You must be signed in to change notification settings - Fork 35
/
clienting.ts
491 lines (447 loc) · 13.5 KB
/
clienting.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
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
import { Agent, Controller } from './controller';
import { Tier } from '../core/salter';
import { Authenticater } from '../core/authing';
import { ExternalModule, KeyManager } from '../core/keeping';
import { Identifier } from './aiding';
import { Contacts, Challenges } from './contacting';
import { Oobis, Operations, KeyEvents, KeyStates } from './coring';
import { Credentials, Ipex, Registries, Schemas } from './credentialing';
import { Notifications } from './notifying';
import { Escrows } from './escrowing';
import { Groups } from './grouping';
import { Exchanges } from './exchanging';
const DEFAULT_BOOT_URL = 'http://localhost:3903';
class State {
agent: any | null;
controller: any | null;
ridx: number;
pidx: number;
constructor() {
this.agent = null;
this.controller = null;
this.pidx = 0;
this.ridx = 0;
}
}
/** SignifyClient */
export class SignifyClient {
public controller: Controller;
public url: string;
public bran: string;
public pidx: number;
public agent: Agent | null;
public authn: Authenticater | null;
public manager: KeyManager | null;
public tier: Tier;
public bootUrl: string;
public exteralModules: ExternalModule[];
/**
* SignifyClient constructor
* @param {string} url KERIA admin interface URL
* @param {string} bran Base64 21 char string that is used as base material for seed of the client AID
* @param {Tier} tier Security tier for generating keys of the client AID (high | mewdium | low)
* @param {string} bootUrl KERIA boot interface URL
* @param {ExternalModule[]} externalModules list of external modules to load
*/
constructor(
url: string,
bran: string,
tier: Tier = Tier.low,
bootUrl: string = DEFAULT_BOOT_URL,
externalModules: ExternalModule[] = []
) {
this.url = url;
if (bran.length < 21) {
throw Error('bran must be 21 characters');
}
this.bran = bran;
this.pidx = 0;
this.controller = new Controller(bran, tier);
this.authn = null;
this.agent = null;
this.manager = null;
this.tier = tier;
this.bootUrl = bootUrl;
this.exteralModules = externalModules;
}
get data() {
return [this.url, this.bran, this.pidx, this.authn];
}
/**
* Boot a KERIA agent
* @async
* @returns {Promise<Response>} A promise to the result of the boot
*/
async boot(): Promise<Response> {
const [evt, sign] = this.controller?.event ?? [];
const data = {
icp: evt.ked,
sig: sign.qb64,
stem: this.controller?.stem,
pidx: 1,
tier: this.controller?.tier,
};
return await fetch(this.bootUrl + '/boot', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
});
}
/**
* Get state of the agent and the client
* @async
* @returns {Promise<Response>} A promise to the state
*/
async state(): Promise<State> {
const caid = this.controller?.pre;
const res = await fetch(this.url + `/agent/${caid}`);
if (res.status == 404) {
throw new Error(`agent does not exist for controller ${caid}`);
}
const data = await res.json();
const state = new State();
state.agent = data.agent ?? {};
state.controller = data.controller ?? {};
state.ridx = data.ridx ?? 0;
state.pidx = data.pidx ?? 0;
return state;
}
/** Connect to a KERIA agent
* @async
*/
async connect() {
const state = await this.state();
this.pidx = state.pidx;
//Create controller representing the local client AID
this.controller = new Controller(
this.bran,
this.tier,
0,
state.controller
);
this.controller.ridx = state.ridx !== undefined ? state.ridx : 0;
// Create agent representing the AID of KERIA cloud agent
this.agent = new Agent(state.agent);
if (this.agent.anchor != this.controller.pre) {
throw Error(
'commitment to controller AID missing in agent inception event'
);
}
if (this.controller.serder.ked.s == 0) {
await this.approveDelegation();
}
this.manager = new KeyManager(
this.controller.salter,
this.exteralModules
);
this.authn = new Authenticater(
this.controller.signer,
this.agent.verfer!
);
}
/**
* Fetch a resource from the KERIA agent
* @async
* @param {string} path Path to the resource
* @param {string} method HTTP method
* @param {any} data Data to be sent in the body of the resource
* @param {Headers} [extraHeaders] Optional extra headers to be sent with the request
* @returns {Promise<Response>} A promise to the result of the fetch
*/
async fetch(
path: string,
method: string,
data: any,
extraHeaders?: Headers
): Promise<Response> {
const headers = new Headers();
let signed_headers = new Headers();
const final_headers = new Headers();
headers.set('Signify-Resource', this.controller.pre);
headers.set(
'Signify-Timestamp',
new Date().toISOString().replace('Z', '000+00:00')
);
headers.set('Content-Type', 'application/json');
const _body = method == 'GET' ? null : JSON.stringify(data);
if (_body !== null) {
headers.set('Content-Length', String(_body.length));
}
if (this.authn) {
signed_headers = this.authn.sign(
headers,
method,
path.split('?')[0]
);
} else {
throw new Error('client need to call connect first');
}
signed_headers.forEach((value, key) => {
final_headers.set(key, value);
});
if (extraHeaders !== undefined) {
extraHeaders.forEach((value, key) => {
final_headers.append(key, value);
});
}
const res = await fetch(this.url + path, {
method: method,
body: _body,
headers: final_headers,
});
if (!res.ok) {
const error = await res.text();
throw new Error(error);
}
const isSameAgent =
this.agent?.pre === res.headers.get('signify-resource');
if (!isSameAgent) {
throw new Error('message from a different remote agent');
}
const verification = this.authn.verify(
res.headers,
method,
path.split('?')[0]
);
if (verification) {
return res;
} else {
throw new Error('response verification failed');
}
}
/**
* Fetch a resource from from an external URL with headers signed by an AID
* @async
* @param {string} url URL of the resource
* @param {string} path Path to the resource
* @param {string} method HTTP method
* @param {any} data Data to be sent in the body of the resource
* @param {string} aidName Name or alias of the AID to be used for signing
* @returns {Promise<Response>} A promise to the result of the fetch
*/
async signedFetch(
url: string,
path: string,
method: string,
data: any,
aidName: string
): Promise<Response> {
const hab = await this.identifiers().get(aidName);
const keeper = this.manager!.get(hab);
const authenticator = new Authenticater(
keeper.signers[0],
keeper.signers[0].verfer
);
const headers = new Headers();
headers.set('Signify-Resource', hab.prefix);
headers.set(
'Signify-Timestamp',
new Date().toISOString().replace('Z', '000+00:00')
);
if (data !== null) {
headers.set('Content-Length', data.length);
} else {
headers.set('Content-Length', '0');
}
const signed_headers = authenticator.sign(
headers,
method,
path.split('?')[0]
);
let _body = null;
if (method != 'GET') {
if (data instanceof FormData) {
_body = data;
// do not set the content type, let the browser do it
// headers.set('Content-Type', 'multipart/form-data')
} else {
_body = JSON.stringify(data);
headers.set('Content-Type', 'application/json');
}
} else {
headers.set('Content-Type', 'application/json');
}
return await fetch(url + path, {
method: method,
body: _body,
headers: signed_headers,
});
}
/**
* Approve the delegation of the client AID to the KERIA agent
* @async
* @returns {Promise<Response>} A promise to the result of the approval
*/
async approveDelegation(): Promise<Response> {
const sigs = this.controller.approveDelegation(this.agent!);
const data = {
ixn: this.controller.serder.ked,
sigs: sigs,
};
return await fetch(
this.url + '/agent/' + this.controller.pre + '?type=ixn',
{
method: 'PUT',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
}
);
}
/**
* Save old client passcode in KERIA agent
* @async
* @param {string} passcode Passcode to be saved
* @returns {Promise<Response>} A promise to the result of the save
*/
async saveOldPasscode(passcode: string): Promise<Response> {
const caid = this.controller?.pre;
const body = { salt: passcode };
return await fetch(this.url + '/salt/' + caid, {
method: 'PUT',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
},
});
}
/**
* Delete a saved passcode from KERIA agent
* @async
* @returns {Promise<Response>} A promise to the result of the deletion
*/
async deletePasscode(): Promise<Response> {
const caid = this.controller?.pre;
return await fetch(this.url + '/salt/' + caid, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
});
}
/**
* Rotate the client AID
* @async
* @param {string} nbran Base64 21 char string that is used as base material for the new seed
* @param {Array<string>} aids List of managed AIDs to be rotated
* @returns {Promise<Response>} A promise to the result of the rotation
*/
async rotate(nbran: string, aids: string[]): Promise<Response> {
const data = this.controller.rotate(nbran, aids);
return await fetch(this.url + '/agent/' + this.controller.pre, {
method: 'PUT',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
},
});
}
/**
* Get identifiers resource
* @returns {Identifier}
*/
identifiers(): Identifier {
return new Identifier(this);
}
/**
* Get OOBIs resource
* @returns {Oobis}
*/
oobis(): Oobis {
return new Oobis(this);
}
/**
* Get operations resource
* @returns {Operations}
*/
operations(): Operations {
return new Operations(this);
}
/**
* Get keyEvents resource
* @returns {KeyEvents}
*/
keyEvents(): KeyEvents {
return new KeyEvents(this);
}
/**
* Get keyStates resource
* @returns {KeyStates}
*/
keyStates(): KeyStates {
return new KeyStates(this);
}
/**
* Get credentials resource
* @returns {Credentials}
*/
credentials(): Credentials {
return new Credentials(this);
}
/**
* Get IPEX resource
* @returns {Ipex}
*/
ipex(): Ipex {
return new Ipex(this);
}
/**
* Get registries resource
* @returns {Registries}
*/
registries(): Registries {
return new Registries(this);
}
/**
* Get schemas resource
* @returns {Schemas}
*/
schemas(): Schemas {
return new Schemas(this);
}
/**
* Get challenges resource
* @returns {Challenges}
*/
challenges(): Challenges {
return new Challenges(this);
}
/**
* Get contacts resource
* @returns {Contacts}
*/
contacts(): Contacts {
return new Contacts(this);
}
/**
* Get notifications resource
* @returns {Notifications}
*/
notifications(): Notifications {
return new Notifications(this);
}
/**
* Get escrows resource
* @returns {Escrows}
*/
escrows(): Escrows {
return new Escrows(this);
}
/**
* Get groups resource
* @returns {Groups}
*/
groups(): Groups {
return new Groups(this);
}
/**
* Get exchange resource
* @returns {Exchanges}
*/
exchanges(): Exchanges {
return new Exchanges(this);
}
}