-
Notifications
You must be signed in to change notification settings - Fork 129
/
didcomm.ts
753 lines (686 loc) · 26.4 KB
/
didcomm.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
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
import {
IAgentContext,
IResolver,
IMessage,
IDIDManager,
IKeyManager,
IMessageHandler,
IAgentPlugin,
IIdentifier,
} from '@veramo/core-types'
import {
createAnonDecrypter,
createAuthDecrypter,
Decrypter,
decryptJWE,
JWE,
ECDH,
createAnonEncrypter,
createJWE,
createAuthEncrypter,
Encrypter,
verifyJWS,
} from 'did-jwt'
import { DIDDocument, parse as parseDidUrl, ServiceEndpoint, VerificationMethod, Service } from 'did-resolver'
import schema from "./plugin.schema.json" assert { type: 'json' }
import { v4 as uuidv4 } from 'uuid'
import * as u8a from 'uint8arrays'
import {
createEcdhWrapper,
extractSenderEncryptionKey,
extractManagedRecipients,
mapRecipientsToLocalKeys,
} from './utils.js'
import {
decodeJoseBlob,
dereferenceDidKeys,
encodeJoseBlob,
isDefined,
mapIdentifierKeysToDoc,
resolveDidOrThrow,
_ExtendedIKey,
_NormalizedVerificationMethod,
} from '@veramo/utils'
import Debug from 'debug'
import { IDIDComm } from './types/IDIDComm.js'
import { DIDCommHttpTransport, IDIDCommTransport } from './transports/transports.js'
import {
DIDCommMessageMediaType,
DIDCommMessagePacking,
IDIDCommMessage,
IDIDCommOptions,
IPackedDIDCommMessage,
IUnpackedDIDCommMessage,
} from './types/message-types.js'
import {
_DIDCommEncryptedMessage,
_DIDCommPlainMessage,
_DIDCommSignedMessage,
_FlattenedJWS,
_GenericJWS,
} from './types/utility-types.js'
const debug = Debug('veramo:did-comm:action-handler')
/**
* @deprecated Please use {@link IDIDComm.sendDIDCommMessage} instead. This will be removed in Veramo 4.0.
* Input arguments for {@link IDIDComm.sendMessageDIDCommAlpha1}
*
* @beta This API may change without a BREAKING CHANGE notice.
*/
export interface ISendMessageDIDCommAlpha1Args {
url?: string
save?: boolean
data: {
id?: string
from: string
to: string
type: string
body: object | string
}
headers?: Record<string, string>
}
// interface arguments
/**
* The input to the {@link DIDComm.unpackDIDCommMessage} method.
*
* @beta This API may change without a BREAKING CHANGE notice.
*/
export type IUnpackDIDCommMessageArgs = IPackedDIDCommMessage
/**
* The input to the {@link DIDComm.packDIDCommMessage} method.
* When `packing` is `authcrypt` or `jws`, a `keyRef` MUST be provided.
*
* @beta This API may change without a BREAKING CHANGE notice.
*/
export interface IPackDIDCommMessageArgs {
message: IDIDCommMessage
packing: DIDCommMessagePacking
keyRef?: string
options?: IDIDCommOptions
}
/**
* The input to the {@link DIDComm.sendDIDCommMessage} method.
* The provided `messageId` will be used in the emitted
* event to allow event/message correlation.
*
* @beta This API may change without a BREAKING CHANGE notice.
*/
export interface ISendDIDCommMessageArgs {
packedMessage: IPackedDIDCommMessage
messageId: string
returnTransportId?: string
recipientDidUrl: string
}
/**
* DID Comm plugin for {@link @veramo/core#Agent}
*
* This plugin provides a method of creating an encrypted message according to the initial
* {@link https://github.com/decentralized-identifier/DIDComm-js | DIDComm-js} implementation.
*
* @remarks Be advised that this spec is still not final and that this protocol may need to change.
*
* @beta This API may change without a BREAKING CHANGE notice.
*/
export class DIDComm implements IAgentPlugin {
readonly transports: IDIDCommTransport[]
/** Plugin methods */
readonly methods: IDIDComm
readonly schema = schema.IDIDComm
/**
* Constructor that takes a list of {@link IDIDCommTransport} objects.
* @param transports - A list of {@link IDIDCommTransport} objects. Defaults to
* {@link @veramo/did-comm#DIDCommHttpTransport | DIDCommHttpTransport}
*/
constructor(transports: IDIDCommTransport[] = [new DIDCommHttpTransport()]) {
this.transports = transports
this.methods = {
sendMessageDIDCommAlpha1: this.sendMessageDIDCommAlpha1.bind(this),
getDIDCommMessageMediaType: this.getDidCommMessageMediaType.bind(this),
unpackDIDCommMessage: this.unpackDIDCommMessage.bind(this),
packDIDCommMessage: this.packDIDCommMessage.bind(this),
sendDIDCommMessage: this.sendDIDCommMessage.bind(this),
}
}
/** {@inheritdoc IDIDComm.packDIDCommMessage} */
async packDIDCommMessage(
args: IPackDIDCommMessageArgs,
context: IAgentContext<IDIDManager & IKeyManager & IResolver>,
): Promise<IPackedDIDCommMessage> {
switch (args.packing) {
case 'authcrypt': // intentionally omitting break
case 'anoncrypt':
return this.packDIDCommMessageJWE(args, context)
case 'none':
const message = {
...args.message,
typ: DIDCommMessageMediaType.PLAIN,
}
return { message: JSON.stringify(message) }
case 'jws':
return this.packDIDCommMessageJWS(args, context)
default:
throw new Error(`not_implemented: packing messages as ${args.packing} is not supported yet`)
}
}
private async packDIDCommMessageJWS(
args: IPackDIDCommMessageArgs,
context: IAgentContext<IDIDManager & IKeyManager & IResolver>,
): Promise<IPackedDIDCommMessage> {
const message = args.message
let keyRef: string | undefined = args.keyRef
let kid: string
// check that the message has from field that is managed
let managedSender: IIdentifier | undefined
try {
managedSender = await context.agent.didManagerGet({ did: message.from || '' })
} catch (e) {
debug(`message.from(${message.from}) is not managed by this agent`)
}
if (!message.from || !isDefined(managedSender)) {
throw new Error('invalid_argument: `from` field must be a DID managed by this agent')
}
// obtain sender signing key(s) from authentication section
const senderKeys = await mapIdentifierKeysToDoc(managedSender, 'authentication', context)
// try to find a managed signing key that matches keyRef
let signingKey = null
if (isDefined(keyRef)) {
signingKey = senderKeys.find((key) => key.kid === keyRef || key.meta.verificationMethod.id === keyRef)
}
// otherwise use the first available one.
signingKey = signingKey ? signingKey : senderKeys[0]
if (!signingKey) {
throw new Error(`key_not_found: could not locate a suitable signing key for ${message.from}`)
} else {
kid = signingKey.meta.verificationMethod.id
}
let alg: string
if (signingKey.type === 'Ed25519') {
alg = 'EdDSA'
} else if (signingKey.type === 'Secp256k1') {
alg = 'ES256K'
} else {
throw new Error(
`not_supported: key of type ${signingKey.type} is not supported for JWS didcomm message`,
)
}
// construct the protected header with alg, typ and kid
const headerObj = { alg, kid, typ: DIDCommMessageMediaType.SIGNED }
const header = encodeJoseBlob(headerObj)
const payload = encodeJoseBlob(args.message)
// construct signing input and obtain signature
const signingInput = header + '.' + payload
const signature: string = await context.agent.keyManagerSign({
data: signingInput,
encoding: 'utf-8',
keyRef: signingKey.kid,
algorithm: alg,
})
// create flattened JWS
const packedMessage = {
protected: header,
payload,
signature,
}
// serialize flattened JWS JSON and return
return { message: JSON.stringify(packedMessage) }
}
private async packDIDCommMessageJWE(
args: IPackDIDCommMessageArgs,
context: IAgentContext<IDIDManager & IKeyManager & IResolver>,
): Promise<IPackedDIDCommMessage> {
// 1. check if args.packing requires authentication and map sender key to skid
let senderECDH: ECDH | null = null
let keyRef: string | undefined = args.keyRef
let protectedHeader: {
skid?: string
typ: string
} = {
typ: DIDCommMessageMediaType.ENCRYPTED,
}
if (args.packing === 'authcrypt') {
// TODO: what to do about from_prior?
if (!args?.message?.from) {
throw new Error(
`invalid_argument: cannot create authenticated did-comm message without a 'from' field`,
)
}
// 1.1 check that args.message.from is a managed DID
const sender: IIdentifier = await context.agent.didManagerGet({ did: args?.message?.from })
// 1.2 match key agreement keys from DID to managed keys
const senderKeys: _ExtendedIKey[] = await mapIdentifierKeysToDoc(sender, 'keyAgreement', context)
// try to find a sender key by keyRef, otherwise pick the first one
let senderKey
if (isDefined(keyRef)) {
senderKey = senderKeys.find((key) => key.kid === keyRef || key.meta.verificationMethod.id === keyRef)
}
senderKey = senderKey || senderKeys[0]
// 1.3 use kid from DID doc(skid) + local IKey to bundle a sender key
if (senderKey) {
senderECDH = createEcdhWrapper(senderKey.kid, context)
protectedHeader = { ...protectedHeader, skid: senderKey.meta.verificationMethod.id }
} else {
throw new Error(`key_not_found: could not map an agent key to an skid for ${args?.message?.from}`)
}
}
// 2: compute recipients
interface IRecipient {
kid: string
publicKeyBytes: Uint8Array
}
let recipients: IRecipient[] = []
async function computeRecipients(to: string): Promise<IRecipient[]> {
// 2.1 resolve DID for "to"
const didDocument: DIDDocument = await resolveDidOrThrow(to, context)
// 2.2 extract all recipient key agreement keys and normalize them
const keyAgreementKeys: _NormalizedVerificationMethod[] = (
await dereferenceDidKeys(didDocument, 'keyAgreement', context)
)
.filter((k) => k.publicKeyHex?.length! > 0)
.filter((k) => (args.options?.recipientKids ? args.options?.recipientKids.includes(k.id) : true))
if (keyAgreementKeys.length === 0) {
throw new Error(`key_not_found: no key agreement keys found for recipient ${to}`)
}
// 2.3 get public key bytes and key IDs for supported recipient keys
const tempRecipients = keyAgreementKeys
.map((pk) => ({ kid: pk.id, publicKeyBytes: u8a.fromString(pk.publicKeyHex!, 'base16') }))
.filter(isDefined)
if (tempRecipients.length === 0) {
throw new Error(`not_supported: no compatible key agreement keys found for recipient ${to}`)
}
return tempRecipients
}
// add primary recipient
recipients.push(...(await computeRecipients(args.message.to)))
// add bcc recipients (optional)
for (const to of args.options?.bcc || []) {
recipients.push(...(await computeRecipients(to)))
}
// 3. create Encrypter for each recipient
const encrypters: Encrypter[] = recipients
.map((recipient) => {
if (args.packing === 'authcrypt') {
return createAuthEncrypter(recipient.publicKeyBytes, <ECDH>senderECDH, { kid: recipient.kid })
} else {
return createAnonEncrypter(recipient.publicKeyBytes, { kid: recipient.kid })
}
})
.filter(isDefined)
if (encrypters.length === 0) {
throw new Error(
`not_supported: could not create suitable encryption for recipient ${args?.message?.to}`,
)
}
// 4. createJWE
const messageBytes = u8a.fromString(JSON.stringify(args.message), 'utf-8')
const jwe = await createJWE(messageBytes, encrypters, protectedHeader)
const message = JSON.stringify(jwe)
return { message }
}
/** {@inheritdoc IDIDComm.getDIDCommMessageMediaType} */
async getDidCommMessageMediaType({ message }: IPackedDIDCommMessage): Promise<DIDCommMessageMediaType> {
try {
const { mediaType } = this.decodeMessageAndMediaType(message)
return mediaType
} catch (e) {
debug(`Could not parse message as DIDComm v2 message: ${e}`)
throw e
}
}
/** {@inheritdoc IDIDComm.unpackDIDCommMessage} */
async unpackDIDCommMessage(
args: IUnpackDIDCommMessageArgs,
context: IAgentContext<IDIDManager & IKeyManager & IResolver & IMessageHandler>,
): Promise<IUnpackedDIDCommMessage> {
const { msgObj, mediaType } = this.decodeMessageAndMediaType(args.message)
if (mediaType === DIDCommMessageMediaType.SIGNED) {
return this.unpackDIDCommMessageJWS(msgObj as _DIDCommSignedMessage, context)
} else if (mediaType === DIDCommMessageMediaType.PLAIN) {
return { message: <IDIDCommMessage>msgObj, metaData: { packing: 'none' } }
} else if (mediaType === DIDCommMessageMediaType.ENCRYPTED) {
return this.unpackDIDCommMessageJWE({ jwe: msgObj as JWE }, context)
} else {
throw Error('not_supported: ' + mediaType)
}
}
private async unpackDIDCommMessageJWS(
jws: _DIDCommSignedMessage,
context: IAgentContext<IDIDManager & IKeyManager & IResolver>,
): Promise<IUnpackedDIDCommMessage> {
// TODO: currently only supporting one signature
const signatureEncoded: string = isDefined((<_FlattenedJWS>jws).signature)
? (<_FlattenedJWS>jws).signature
: (<_GenericJWS>jws).signatures[0]?.signature
const headerEncoded = isDefined((<_FlattenedJWS>jws).protected)
? (<_FlattenedJWS>jws).protected
: (<_GenericJWS>jws).signatures[0]?.protected
if (!isDefined(headerEncoded) || !isDefined(signatureEncoded)) {
throw new Error('invalid_argument: could not interpret message as JWS')
}
const message = <IDIDCommMessage>decodeJoseBlob(jws.payload)
const header = decodeJoseBlob(headerEncoded)
const sender = parseDidUrl(header.kid)?.did
if (!isDefined(sender) || sender !== message.from) {
throw new Error('invalid_jws: sender is not a DID or does not match the `kid`')
}
const senderDoc = await resolveDidOrThrow(sender, context)
const senderKey = (await context.agent.getDIDComponentById({
didDocument: senderDoc,
didUrl: header.kid,
section: 'authentication',
})) as VerificationMethod
const verifiedSenderKey = verifyJWS(`${headerEncoded}.${jws.payload}.${signatureEncoded}`, senderKey)
if (isDefined(verifiedSenderKey)) {
return { message, metaData: { packing: 'jws' } }
} else {
throw new Error('invalid_jws: sender `kid` could not be validated as the signer of the message')
}
}
private async unpackDIDCommMessageJWE(
{ jwe }: { jwe: JWE },
context: IAgentContext<IDIDManager & IKeyManager & IResolver>,
): Promise<IUnpackedDIDCommMessage> {
// 0 resolve skid to DID doc
// - find skid in DID doc and convert to 'X25519' byte array (if type matches)
let senderKeyBytes: Uint8Array | null = await extractSenderEncryptionKey(jwe, context)
// 1. check whether kid is one of my DID URIs
// - get recipient DID URIs
// - extract DIDs from recipient DID URIs
// - match DIDs against locally managed DIDs
let managedRecipients = await extractManagedRecipients(jwe, context)
// 2. get internal IKey instance for each recipient.kid
// - resolve locally managed DIDs that match recipients
// - filter to the keyAgreementKeys that match the recipient.kid
// - match identifier.keys.publicKeyHex to (verificationMethod.publicKey*)
// - return a list of `IKey`
const localKeys = await mapRecipientsToLocalKeys(managedRecipients, context)
// 3. for each recipient
// if isAuthcrypted? (if senderKey != null)
// - construct auth decrypter
// else
// - construct anon decrypter
for (const localKey of localKeys) {
let packing: string
let decrypter: Decrypter
const recipientECDH: ECDH = createEcdhWrapper(localKey.localKeyRef, context)
// TODO: here's where more algorithms should be supported
if (senderKeyBytes && localKey.recipient?.header?.alg?.includes('ECDH-1PU')) {
decrypter = createAuthDecrypter(recipientECDH, senderKeyBytes)
packing = 'authcrypt'
} else {
decrypter = createAnonDecrypter(recipientECDH)
packing = 'anoncrypt'
}
// 4. decryptJWE(jwe, decrypter)
try {
const decryptedBytes = await decryptJWE(jwe, decrypter)
const decryptedMsg = u8a.toString(decryptedBytes, 'utf-8')
const message = JSON.parse(decryptedMsg)
return { message, metaData: { packing } } as IUnpackedDIDCommMessage
} catch (e) {
debug(
`unable to decrypt DIDComm msg using ${localKey.localKeyRef} (${localKey.recipient.header.kid})`,
)
}
}
throw new Error('unable to decrypt DIDComm message with any of the locally managed keys')
}
private decodeMessageAndMediaType(message: string): {
msgObj: _DIDCommPlainMessage | _DIDCommSignedMessage | _DIDCommEncryptedMessage
mediaType: DIDCommMessageMediaType
} {
let msgObj
if (typeof message === 'string') {
try {
msgObj = JSON.parse(message)
} catch (e) {
throw new Error('invalid_argument: unable to parse message as JSON')
// TODO: try to interpret as compact serialized JWS / JWM?
}
} else {
msgObj = message
}
let mediaType: DIDCommMessageMediaType | null = null
if ((<_DIDCommPlainMessage>msgObj).typ === DIDCommMessageMediaType.PLAIN) {
mediaType = DIDCommMessageMediaType.PLAIN
} else if ((<_FlattenedJWS | _DIDCommEncryptedMessage>msgObj).protected) {
const protectedHeader = decodeJoseBlob(msgObj.protected)
if (protectedHeader.typ === DIDCommMessageMediaType.SIGNED) {
mediaType = DIDCommMessageMediaType.SIGNED
} else if (protectedHeader.typ === DIDCommMessageMediaType.ENCRYPTED) {
mediaType = DIDCommMessageMediaType.ENCRYPTED
} else {
throw new Error('invalid_argument: unable to determine message type')
}
} else if ((<_GenericJWS>msgObj).signatures) {
mediaType = DIDCommMessageMediaType.SIGNED
} else {
throw new Error('invalid_argument: unable to determine message type')
}
return { msgObj, mediaType }
}
private findPreferredDIDCommService(services: Service[]) {
// FIXME: TODO: get preferred service endpoint according to configuration; now defaulting to first service
return services[0]
}
private async wrapDIDCommForwardMessage(
recipientDidUrl: string,
messageId: string,
packedMessageToForward: IPackedDIDCommMessage,
routingKey: string,
context: IAgentContext<IDIDManager & IKeyManager & IResolver>,
): Promise<IPackedDIDCommMessage> {
const splitKey = routingKey.split('#')
const shouldUseSpecificKid = splitKey.length > 1
const mediatorDidUrl = splitKey[0]
// 1. Create forward message
const forwardMessage: IDIDCommMessage = {
id: uuidv4(),
type: 'https://didcomm.org/routing/2.0/forward',
to: mediatorDidUrl,
body: {
next: recipientDidUrl,
},
attachments: [
{
media_type: DIDCommMessageMediaType.ENCRYPTED,
data: {
json: JSON.parse(packedMessageToForward.message),
},
},
],
}
context.agent.emit('DIDCommV2Message-forwarded', {
messageId,
next: recipientDidUrl,
routingKey: routingKey,
})
// 2. Pack message for routingKey with anoncrypt
if (shouldUseSpecificKid) {
return this.packDIDCommMessageJWE(
{ message: forwardMessage, packing: 'anoncrypt', options: { recipientKids: [routingKey] } },
context,
)
} else {
return this.packDIDCommMessageJWE({ message: forwardMessage, packing: 'anoncrypt' }, context)
}
}
/** {@inheritdoc IDIDComm.sendDIDCommMessage} */
async sendDIDCommMessage(
args: ISendDIDCommMessageArgs,
context: IAgentContext<IDIDManager & IKeyManager & IResolver>,
): Promise<string> {
const { packedMessage, returnTransportId, recipientDidUrl, messageId } = args
if (returnTransportId) {
// FIXME: TODO: check if previous message was ok with reusing transport?
// if so, retrieve transport from transport manager
//transport = this.findDIDCommTransport(returnTransportId)
throw new Error(`not_supported: return routes not supported yet`)
}
const didDoc = await resolveDidOrThrow(recipientDidUrl, context)
const services = didDoc.service?.filter(
(service: any) => service.type === 'DIDCommMessaging',
// FIXME: TODO: only send the message if the service section either explicitly supports
// `didcomm/v2`, or no `accept` property is present.
)
if (!services || services.length === 0) {
throw new Error(
`not_found: could not find DIDComm Messaging service in DID document for '${recipientDidUrl}'`,
)
}
const service = this.findPreferredDIDCommService(services)
if (!service) {
throw new Error(
`not_found: could not find preferred DIDComm Messaging service in DID document for '${recipientDidUrl}'`,
)
}
// serviceEndpoint can be a string, a ServiceEndpoint object, or an array of strings or ServiceEndpoint objects
let routingKeys: string[] = []
let serviceEndpointUrl = ''
if (typeof service.serviceEndpoint === 'string') {
serviceEndpointUrl = service.serviceEndpoint
} else if ((service.serviceEndpoint as any).uri) {
serviceEndpointUrl = (service.serviceEndpoint as any).uri
} else if (Array.isArray(service.serviceEndpoint) && service.serviceEndpoint.length > 0) {
if (typeof service.serviceEndpoint[0] === 'string') {
serviceEndpointUrl = service.serviceEndpoint[0]
} else if (service.serviceEndpoint[0].uri) {
serviceEndpointUrl = service.serviceEndpoint[0].uri
}
}
if (typeof service.serviceEndpoint !== 'string') {
if (
Array.isArray(service.serviceEndpoint) &&
service.serviceEndpoint.length > 0 &&
service.serviceEndpoint[0].routingKeys
) {
routingKeys = service.serviceEndpoint[0].routingKeys
} else if (service.serviceEndpoint.routingKeys) {
routingKeys = service.serviceEndpoint.routingKeys
}
}
if (routingKeys.length > 0) {
// routingKeys found, wrap forward messages
let wrappedMessage: IPackedDIDCommMessage = packedMessage
for (let i = routingKeys.length - 1; i >= 0; i--) {
const recipient = i >= routingKeys.length - 1 ? recipientDidUrl : routingKeys[i + 1].split('#')[0]
wrappedMessage = await this.wrapDIDCommForwardMessage(
recipient,
messageId,
wrappedMessage,
routingKeys[i],
context,
)
}
packedMessage.message = wrappedMessage.message
}
// Check for DID as URI
let isServiceEndpointDid = false
try {
await resolveDidOrThrow(serviceEndpointUrl, context)
isServiceEndpointDid = true
} catch (e) {}
if (isServiceEndpointDid) {
// Final wrapping and send to mediator DID
const recipient =
routingKeys.length > 0 ? routingKeys[routingKeys.length - 1].split('#')[0] : recipientDidUrl
const wrappedMessage = await this.wrapDIDCommForwardMessage(
recipient,
messageId,
packedMessage,
serviceEndpointUrl,
context,
)
return this.sendDIDCommMessage(
{ packedMessage: wrappedMessage, recipientDidUrl: serviceEndpointUrl, messageId },
context,
)
}
const transports = this.transports.filter(
(t) => t.isServiceSupported(service) && (!returnTransportId || t.id === returnTransportId),
)
if (!transports || transports.length < 1) {
throw new Error('not_found: no transport type found for service: ' + JSON.stringify(service))
}
// TODO: better strategy for selecting the transport if multiple transports apply
const transport = transports[0]
let response
try {
response = await transport.send(service, packedMessage.message)
if (response.error) {
throw new Error(
`Error when sending DIDComm message through transport with id: '${transport.id}': ${response.error}`,
)
}
} catch (e) {
throw new Error(`Cannot send DIDComm message through transport with id: '${transport.id}': ${e}`)
}
context.agent.emit('DIDCommV2Message-sent', messageId)
if (response.returnMessage) {
// Handle return message
await context.agent.handleMessage({
raw: response.returnMessage,
})
}
return transport.id
}
/** {@inheritdoc IDIDComm.sendMessageDIDCommAlpha1} */
async sendMessageDIDCommAlpha1(
args: ISendMessageDIDCommAlpha1Args,
context: IAgentContext<IDIDManager & IKeyManager & IResolver & IMessageHandler>,
): Promise<IMessage> {
const { data, url, headers, save = true } = args
debug('Resolving didDoc')
const didDoc = (await context.agent.resolveDid({ didUrl: data.to })).didDocument
let serviceEndpoint
if (url) {
serviceEndpoint = url
} else {
const service = didDoc && didDoc.service && didDoc.service.find((item) => item.type == 'Messaging')
serviceEndpoint = service?.serviceEndpoint
}
if (serviceEndpoint) {
try {
data.id = data.id || uuidv4()
let postPayload = JSON.stringify(data)
try {
const identifier = await context.agent.didManagerGet({ did: data.from })
const key = identifier.keys.find((k) => k.type === 'Ed25519')
if (!key) throw Error('No encryption key')
const publicKey = didDoc?.publicKey?.find((item) => item.type == 'Ed25519VerificationKey2018')
if (!publicKey?.publicKeyHex) throw Error('Recipient does not have encryption publicKey')
postPayload = await context.agent.keyManagerEncryptJWE({
kid: key.kid,
to: {
type: 'Ed25519',
publicKeyHex: publicKey?.publicKeyHex,
kid: publicKey?.publicKeyHex,
},
data: postPayload,
})
debug('Encrypted:', postPayload)
} catch (e) {
}
debug('Sending to %s', serviceEndpoint)
const endpointUri = (typeof serviceEndpoint === 'string') ? serviceEndpoint : serviceEndpoint.uri
const res = await fetch(endpointUri, {
method: 'POST',
body: postPayload,
headers,
})
debug('Status', res.status, res.statusText)
if (res.status == 200) {
return await context.agent.handleMessage({
raw: JSON.stringify(data),
metaData: [{ type: 'DIDComm-sent' }],
save,
})
}
return Promise.reject(new Error('Message not sent'))
} catch (e) {
return Promise.reject(e)
}
} else {
debug('No Messaging service in didDoc')
return Promise.reject(new Error('No service endpoint'))
}
}
}