-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmediator_client.dart
More file actions
272 lines (231 loc) · 8.5 KB
/
mediator_client.dart
File metadata and controls
272 lines (231 loc) · 8.5 KB
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
import 'dart:async';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:didcomm/didcomm.dart';
import 'package:didcomm/src/did_resolver_manager.dart';
import 'package:didcomm/src/extensions/verification_method_list_extention.dart';
import 'package:dio/dio.dart';
import 'package:ssi/ssi.dart';
import 'package:uuid/uuid.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/status.dart' as status;
import '../../didcomm.dart';
import '../common/did_document_service_type.dart';
import '../extensions/extensions.dart';
/// Client for interacting with a DIDComm mediator, supporting message sending, inbox management,
/// and real-time message delivery via WebSockets.
class MediatorClient {
/// The DID Document of the mediator.
final DidDocument mediatorDidDocument;
/// The key pair used for encryption and signing.
final KeyPair keyPair;
/// The key ID used for encryption.
final String didKeyId;
/// The signer used for signing messages.
final DidSigner signer;
/// Options for forwarding messages to the mediator.
final ForwardMessageOptions forwardMessageOptions;
/// Options for WebSocket connections.
final WebSocketOptions webSocketOptions;
final Dio _dio;
late final IOWebSocketChannel? _channel;
/// Creates a [MediatorClient] instance.
///
/// [mediatorDidDocument] - The mediator's DID Document.
/// [keyPair] - The key pair for encryption/signing.
/// [didKeyId] - The key ID for encryption.
/// [signer] - The signer for signing messages.
/// [forwardMessageOptions] - Options for forwarding messages (default: const ForwardMessageOptions()).
/// [webSocketOptions] - Options for WebSocket/live delivery (default: const WebSocketOptions()).
MediatorClient({
required this.mediatorDidDocument,
required this.keyPair,
required this.didKeyId,
required this.signer,
this.forwardMessageOptions = const ForwardMessageOptions(),
this.webSocketOptions = const WebSocketOptions(),
}) : _dio = mediatorDidDocument.toDio(
mediatorServiceType: DidDocumentServiceType.didCommMessaging,
);
/// Creates a [MediatorClient] from a mediator DID Document URI.
///
/// [didDocumentUrl] - The URI of the mediator's DID Document.
/// [keyPair] - The key pair for encryption/signing.
/// [didKeyId] - The key ID for encryption.
/// [signer] - The signer for signing messages.
static Future<MediatorClient> fromMediatorDidDocumentUri(
Uri didDocumentUrl, {
required KeyPair keyPair,
required String didKeyId,
required DidSigner signer,
}) async {
return MediatorClient(
mediatorDidDocument: await DidResolverManager.resolve(
didDocumentUrl.toString(),
),
keyPair: keyPair,
didKeyId: didKeyId,
signer: signer,
);
}
/// Sends a [ForwardMessage] to the mediator.
///
/// [message] - The message to send.
/// [accessToken] - Optional bearer token for authentication.
///
/// Returns the packed [DidcommMessage] that was sent.
Future<DidcommMessage> sendMessage(
ForwardMessage message, {
String? accessToken,
}) async {
final messageToSend = await _packMessage(
message,
messageOptions: forwardMessageOptions,
);
final headers =
accessToken != null ? {'Authorization': 'Bearer $accessToken'} : null;
await _dio.post<Map<String, dynamic>>(
'/inbound',
data: messageToSend,
options: Options(headers: headers),
);
return messageToSend;
}
/// Lists message IDs in the inbox for the current actor.
///
/// [accessToken] - Optional bearer token for authentication.
///
/// Returns a list of message IDs as strings.
Future<List<String>> listInboxMessageIds({String? accessToken}) async {
final actorDidDocument = await _getActorDidDocument();
final headers =
accessToken != null ? {'Authorization': 'Bearer $accessToken'} : null;
final response = await _dio.get<Map<String, dynamic>>(
'/list/${sha256.convert(utf8.encode(actorDidDocument.id)).toString()}/inbox',
options: Options(headers: headers),
);
return (response.data!['data'] as List<dynamic>)
.map((item) => (item as Map<String, dynamic>)['msg_id'] as String)
.toList();
}
/// Receives messages from the mediator by message IDs.
///
/// [messageIds] - The list of message IDs to fetch.
/// [deleteOnMediator] - Whether to delete messages from the mediator after fetching (default: true).
/// [accessToken] - Optional bearer token for authentication.
///
/// Returns a list of message.
Future<List<Map<String, dynamic>>> receiveMessages({
required List<String> messageIds,
bool deleteOnMediator = true,
String? accessToken,
}) async {
// TODO: create exception to wrap errors
final headers =
accessToken != null ? {'Authorization': 'Bearer $accessToken'} : null;
final response = await _dio.post<Map<String, dynamic>>(
'/outbound',
data: {'message_ids': messageIds, 'delete': deleteOnMediator},
options: Options(headers: headers),
);
final data = response.data!['data'] as Map<String, dynamic>;
return (data['success'] as List<dynamic>)
.map(
(item) => jsonDecode((item as Map<String, dynamic>)['msg'] as String)
as Map<String, dynamic>,
)
.toList();
}
/// Listens for incoming messages from the mediator via WebSocket.
///
/// [onMessage] - Callback for each received message.
/// [onError] - Optional callback for errors.
/// [onDone] - Optional callback when the stream is closed.
/// [cancelOnError] - Whether to cancel on error.
/// [accessToken] - Optional bearer token for authentication.
///
/// Returns a [StreamSubscription] for the WebSocket stream.
Future<StreamSubscription> listenForIncomingMessages(
void Function(Map<String, dynamic>) onMessage, {
Function? onError,
void Function()? onDone,
bool? cancelOnError,
String? accessToken,
}) async {
_channel = mediatorDidDocument.toWebSocketChannel(accessToken: accessToken);
await _channel!.ready;
final subscription = _channel.stream.listen(
(data) => onMessage(jsonDecode(data as String) as Map<String, dynamic>),
onError: onError,
onDone: onDone,
cancelOnError: cancelOnError,
);
final actorDidDocument = await _getActorDidDocument();
if (webSocketOptions.statusRequestMessageOptions.shouldSend) {
final setupRequestMessage = StatusRequestMessage(
id: const Uuid().v4(),
to: [mediatorDidDocument.id],
from: actorDidDocument.id,
recipientDid: actorDidDocument.id,
);
_sendMessageToChannel(
await _packMessage(
setupRequestMessage,
messageOptions: webSocketOptions.statusRequestMessageOptions,
),
);
}
if (webSocketOptions.liveDeliveryChangeMessageOptions.shouldSend) {
final liveDeliveryChangeMessage = LiveDeliveryChangeMessage(
id: const Uuid().v4(),
to: [mediatorDidDocument.id],
from: actorDidDocument.id,
liveDelivery: true,
);
_sendMessageToChannel(
await _packMessage(
liveDeliveryChangeMessage,
messageOptions: webSocketOptions.liveDeliveryChangeMessageOptions,
),
);
}
return subscription;
}
/// Disconnects the WebSocket channel if connected.
Future<void> disconnect() async {
if (_channel != null) {
await _channel.sink.close(status.normalClosure);
}
}
Future<DidDocument> _getActorDidDocument() async {
return DidKey.generateDocument(keyPair.publicKey);
}
Future<DidcommMessage> _packMessage(
PlainTextMessage message, {
required MessageOptions messageOptions,
}) async {
DidcommMessage messageToSend = message;
if (messageOptions.shouldSign) {
messageToSend = await SignedMessage.pack(message, signer: signer);
}
if (messageOptions.shouldEncrypt) {
messageToSend = await EncryptedMessage.pack(
messageToSend,
keyPair: keyPair,
didKeyId: didKeyId,
recipientDidDocuments: [mediatorDidDocument],
keyWrappingAlgorithm: messageOptions.keyWrappingAlgorithm,
encryptionAlgorithm: messageOptions.encryptionAlgorithm,
);
}
return messageToSend;
}
void _sendMessageToChannel(DidcommMessage message) {
if (_channel == null) {
throw Exception(
'WebSockets connection has not configured yet. Call listenForIncomingMessages first.',
);
}
_channel.sink.add(jsonEncode(message));
}
}