-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathMessages.ts
302 lines (274 loc) · 9.04 KB
/
Messages.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
import {
DeliveryServiceProfileKeys,
normalizeEnsName,
UserProfile,
} from '@dm3-org/dm3-lib-profile';
import { ethers } from 'ethers';
import { stringify } from '@dm3-org/dm3-lib-shared';
import {
decryptAsymmetric,
encryptAsymmetric,
EncryptedPayload,
KeyPair,
sign,
} from '@dm3-org/dm3-lib-crypto';
import {
DeliveryInformation,
EncryptionEnvelop,
getEnvelopSize,
Postmark,
} from '@dm3-org/dm3-lib-messaging';
import { logDebug, sha256 } from '@dm3-org/dm3-lib-shared';
import { NotificationBroker } from './notifications';
import {
GetNotificationChannels,
NotificationChannel,
NotificationType,
} from './notifications/types';
import { checkToken, Session } from './Session';
import { isSpam } from './spam-filter';
import { SpamFilterRules } from './spam-filter/SpamFilterRules';
export interface Acknoledgment {
contactAddress: string;
messageDeliveryServiceTimestamp: number;
}
export interface MessageSubmission {
token: string;
envelop: EncryptionEnvelop;
}
export function getConversationId(ensNameA: string, ensNameB: string): string {
return [normalizeEnsName(ensNameA), normalizeEnsName(ensNameB)]
.sort()
.join();
}
// fetch new messages
export async function getMessages(
loadMessages: (
conversationId: string,
offset: number,
size: number,
) => Promise<EncryptionEnvelop[]>,
encryptionKeyPair: KeyPair,
ensName: string,
contactEnsName: string,
) {
const account = normalizeEnsName(ensName);
const contact = normalizeEnsName(contactEnsName);
const conversationId = getConversationId(contact, account);
const receivedMessages: EncryptionEnvelop[] = await loadMessages(
conversationId,
0,
50,
);
const envelopContainers = await Promise.all(
receivedMessages.map(async (envelop) => ({
to: normalizeEnsName(
JSON.parse(JSON.stringify(envelop.metadata.deliveryInformation))
.to,
),
envelop,
})),
);
return envelopContainers
.filter((envelopContainer) => envelopContainer.to === account)
.map((envelopContainer) => envelopContainer.envelop);
}
/**
* Handles an incomming message.
* Either stores the message or sends it directly to the receiver if a socketId is provided
* In order to be considered valid a incoming message has to meet the following criterias
* 1. The message size must be lower than the sizeLimit specified by the deliveryService {@see messageIsToLarge}
* 2. The DeliveryServiceToken used by the sender has to be valid
* 3. The receiver has to have a session at the deliveryService
* 4. The message must pass every {@see SpamFilterRule} the receiver declared
*/
export async function incomingMessage(
{ envelop, token }: { envelop: EncryptionEnvelop; token: string },
signingKeyPair: KeyPair,
encryptionKeyPair: KeyPair,
sizeLimit: number,
dsNotificationChannels: NotificationChannel[],
getSession: (
accountAddress: string,
) => Promise<(Session & { spamFilterRules: SpamFilterRules }) | null>,
storeNewMessage: (
conversationId: string,
envelop: EncryptionEnvelop,
) => Promise<void>,
send: (socketId: string, envelop: EncryptionEnvelop) => void,
provider: ethers.providers.JsonRpcProvider,
getIdEnsName: (name: string) => Promise<string>,
getUsersNotificationChannels: GetNotificationChannels,
): Promise<void> {
logDebug({
text: 'incomingMessage',
token,
});
//Checks the size of the incoming message
if (messageIsToLarge(envelop, sizeLimit)) {
throw Error('Message is too large');
}
//Decryptes the encrypted DeliveryInformation with the KeyPair of the deliveryService
const deliveryInformation: DeliveryInformation =
await decryptDeliveryInformation(envelop, encryptionKeyPair);
logDebug({ text: 'incomingMessage', deliveryInformation });
const conversationId = getConversationId(
await getIdEnsName(deliveryInformation.from),
await getIdEnsName(deliveryInformation.to),
);
logDebug({ text: 'incomingMessage', conversationId, deliveryInformation });
//Checks if the sender is authenticated
const tokenIsValid = await checkToken(
provider,
getSession,
deliveryInformation.from,
token,
);
if (!tokenIsValid) {
//Token is invalid
logDebug({
text: 'incomingMessage token invalid',
});
throw Error('Token check failed');
}
//Retrives the session of the receiver
const receiverSession = await getSession(deliveryInformation.to);
if (!receiverSession) {
logDebug({
text: 'incomingMessage unknown session',
});
throw Error('unknown session');
}
logDebug({
text: 'incomingMessage',
conversationId,
deliveryInformation,
receiverSession,
});
//Checkes if the message is spam
if (await isSpam(provider, receiverSession, deliveryInformation)) {
logDebug({
text: 'incomingMessage is spam',
});
throw Error('Message does not match spam criteria');
}
const receiverEncryptionKey =
receiverSession.signedUserProfile.profile.publicEncryptionKey;
const envelopWithPostmark: EncryptionEnvelop = {
...envelop,
metadata: {
...envelop.metadata,
//Alwaays store the encrypted metadata
deliveryInformation,
},
postmark: stringify(
await addPostmark(
envelop,
receiverEncryptionKey,
signingKeyPair.privateKey,
),
),
};
logDebug({
text: 'incomingMessage',
conversationId,
envelopWithPostmark,
});
if (process.env.DISABLE_MSG_BUFFER !== 'true') {
logDebug({ text: 'storeNewMessage', conversationId });
await storeNewMessage(conversationId, envelopWithPostmark);
} else {
logDebug({ text: 'skip storeNewMessage', conversationId });
}
//If there is currently a webSocket connection open to the receiver, the message will be directly send.
if (receiverSession.socketId) {
//Client is already connect to the delivery service and the message can be dispatched
send(receiverSession.socketId, envelopWithPostmark);
logDebug({
text: 'WS send to socketId ',
receiverSessionSocketId: receiverSession.socketId,
});
//If not we're notifing the user that there is a new message waiting for them
} else {
const { sendNotification } = NotificationBroker(
dsNotificationChannels,
NotificationType.NEW_MESSAGE,
);
await sendNotification(
deliveryInformation,
getUsersNotificationChannels,
);
}
}
function messageIsToLarge(
envelop: EncryptionEnvelop,
sizeLimit: number,
): boolean {
return getEnvelopSize(envelop) > sizeLimit;
}
export async function handleIncomingMessage(
encryptedEnvelop: EncryptionEnvelop,
deliveryServiceKeys: DeliveryServiceProfileKeys,
receiverProfile: UserProfile,
): Promise<{
encryptedEnvelop: Required<EncryptionEnvelop>;
decryptedDeliveryInformation: DeliveryInformation;
}> {
const postmark = await addPostmark(
encryptedEnvelop,
receiverProfile.publicEncryptionKey,
deliveryServiceKeys.signingKeyPair.privateKey,
);
return {
encryptedEnvelop: {
...encryptedEnvelop,
postmark: stringify(postmark),
},
decryptedDeliveryInformation: await decryptDeliveryInformation(
encryptedEnvelop,
deliveryServiceKeys.encryptionKeyPair,
),
};
}
async function addPostmark(
{ message }: EncryptionEnvelop,
receiverEncryptionKey: string,
deliveryServiceSigningKey: string,
): Promise<EncryptedPayload> {
const postmarkWithoutSig: Omit<Postmark, 'signature'> = {
messageHash: ethers.utils.hashMessage(stringify(message)),
incommingTimestamp: new Date().getTime(),
};
const signature = await signPostmark(
postmarkWithoutSig,
deliveryServiceSigningKey,
);
//Encrypte the signed Postmark and return the ciphertext
const { ciphertext, nonce, ephemPublicKey } = await encryptAsymmetric(
receiverEncryptionKey,
stringify({ ...postmarkWithoutSig, signature })!,
);
return {
nonce,
ciphertext,
ephemPublicKey,
};
}
export async function decryptDeliveryInformation(
encryptedEnvelop: EncryptionEnvelop,
encryptionKeyPair: KeyPair,
): Promise<DeliveryInformation> {
return JSON.parse(
await decryptAsymmetric(
encryptionKeyPair,
JSON.parse(encryptedEnvelop.metadata.deliveryInformation as string),
),
);
}
function signPostmark(
p: Omit<Postmark, 'signature'>,
signingKey: string,
): Promise<string> {
const postmarkHash = sha256(stringify(p));
return sign(signingKey, postmarkHash);
}