@waku/message-encryption 0.0.4 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,96 +1,19 @@
1
- import { DecoderV0, MessageV0, proto } from "@waku/core/lib/waku_message/version_0";
2
- import type { DecodedMessage, Decoder, Encoder, Message, ProtoMessage } from "@waku/interfaces";
3
- import { generatePrivateKey, generateSymmetricKey, getPublicKey } from "./crypto.js";
1
+ import { DecodedMessage as DecodedMessageV0, proto } from "@waku/core/lib/message/version_0";
2
+ import type { IDecodedMessage } from "@waku/interfaces";
3
+ import { generatePrivateKey, generateSymmetricKey, getPublicKey } from "./crypto/index.js";
4
+ export declare const OneMillion: bigint;
4
5
  export { generatePrivateKey, generateSymmetricKey, getPublicKey };
6
+ export * as ecies from "./ecies.js";
7
+ export * as symmetric from "./symmetric.js";
5
8
  export declare const Version = 1;
6
9
  export declare type Signature = {
7
10
  signature: Uint8Array;
8
11
  publicKey: Uint8Array | undefined;
9
12
  };
10
- export declare class MessageV1 extends MessageV0 implements DecodedMessage {
13
+ export declare class DecodedMessage extends DecodedMessageV0 implements IDecodedMessage {
11
14
  signature?: Uint8Array | undefined;
12
15
  signaturePublicKey?: Uint8Array | undefined;
13
16
  private readonly _decodedPayload;
14
17
  constructor(proto: proto.WakuMessage, decodedPayload: Uint8Array, signature?: Uint8Array | undefined, signaturePublicKey?: Uint8Array | undefined);
15
18
  get payload(): Uint8Array;
16
19
  }
17
- export declare class AsymEncoder implements Encoder {
18
- contentTopic: string;
19
- private publicKey;
20
- private sigPrivKey?;
21
- ephemeral: boolean;
22
- constructor(contentTopic: string, publicKey: Uint8Array, sigPrivKey?: Uint8Array | undefined, ephemeral?: boolean);
23
- toWire(message: Partial<Message>): Promise<Uint8Array | undefined>;
24
- toProtoObj(message: Partial<Message>): Promise<ProtoMessage | undefined>;
25
- }
26
- export declare class SymEncoder implements Encoder {
27
- contentTopic: string;
28
- private symKey;
29
- private sigPrivKey?;
30
- ephemeral: boolean;
31
- constructor(contentTopic: string, symKey: Uint8Array, sigPrivKey?: Uint8Array | undefined, ephemeral?: boolean);
32
- toWire(message: Partial<Message>): Promise<Uint8Array | undefined>;
33
- toProtoObj(message: Partial<Message>): Promise<ProtoMessage | undefined>;
34
- }
35
- export declare class AsymDecoder extends DecoderV0 implements Decoder<MessageV1> {
36
- private privateKey;
37
- constructor(contentTopic: string, privateKey: Uint8Array);
38
- fromProtoObj(protoMessage: ProtoMessage): Promise<MessageV1 | undefined>;
39
- }
40
- export declare class SymDecoder extends DecoderV0 implements Decoder<MessageV1> {
41
- private symKey;
42
- constructor(contentTopic: string, symKey: Uint8Array);
43
- fromProtoObj(protoMessage: ProtoMessage): Promise<MessageV1 | undefined>;
44
- }
45
- /**
46
- * Proceed with Asymmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
47
- * The data MUST be flags | payload-length | payload | [signature].
48
- * The returned result can be set to `WakuMessage.payload`.
49
- *
50
- * @internal
51
- */
52
- export declare function encryptAsymmetric(data: Uint8Array, publicKey: Uint8Array | string): Promise<Uint8Array>;
53
- /**
54
- * Proceed with Asymmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
55
- * The returned data is expected to be `flags | payload-length | payload | [signature]`.
56
- *
57
- * @internal
58
- */
59
- export declare function decryptAsymmetric(payload: Uint8Array, privKey: Uint8Array): Promise<Uint8Array>;
60
- /**
61
- * Proceed with Symmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
62
- *
63
- * @param data The data to encrypt, expected to be `flags | payload-length | payload | [signature]`.
64
- * @param key The key to use for encryption.
65
- * @returns The decrypted data, `cipherText | tag | iv` and can be set to `WakuMessage.payload`.
66
- *
67
- * @internal
68
- */
69
- export declare function encryptSymmetric(data: Uint8Array, key: Uint8Array | string): Promise<Uint8Array>;
70
- /**
71
- * Proceed with Symmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
72
- *
73
- * @param payload The cipher data, it is expected to be `cipherText | tag | iv`.
74
- * @param key The key to use for decryption.
75
- * @returns The decrypted data, expected to be `flags | payload-length | payload | [signature]`.
76
- *
77
- * @internal
78
- */
79
- export declare function decryptSymmetric(payload: Uint8Array, key: Uint8Array | string): Promise<Uint8Array>;
80
- /**
81
- * Prepare the payload pre-encryption.
82
- *
83
- * @internal
84
- * @returns The encoded payload, ready for encryption using {@link encryptAsymmetric}
85
- * or {@link encryptSymmetric}.
86
- */
87
- export declare function preCipher(messagePayload: Uint8Array, sigPrivKey?: Uint8Array): Promise<Uint8Array>;
88
- /**
89
- * Decode a decrypted payload.
90
- *
91
- * @internal
92
- */
93
- export declare function postCipher(message: Uint8Array): {
94
- payload: Uint8Array;
95
- sig?: Signature;
96
- } | undefined;
package/dist/index.js CHANGED
@@ -1,21 +1,11 @@
1
- import * as secp from "@noble/secp256k1";
2
- import { concat, hexToBytes } from "@waku/byte-utils";
3
- import { DecoderV0, MessageV0, proto, } from "@waku/core/lib/waku_message/version_0";
4
- import debug from "debug";
5
- import { Symmetric } from "./constants.js";
6
- import { generatePrivateKey, generateSymmetricKey, getPublicKey, keccak256, randomBytes, sign, } from "./crypto.js";
7
- import * as ecies from "./ecies.js";
8
- import * as symmetric from "./symmetric.js";
9
- const log = debug("waku:message:version-1");
10
- const FlagsLength = 1;
11
- const FlagMask = 3; // 0011
12
- const IsSignedMask = 4; // 0100
13
- const PaddingTarget = 256;
14
- const SignatureLength = 65;
15
- const OneMillion = BigInt(1000000);
1
+ import { DecodedMessage as DecodedMessageV0, } from "@waku/core/lib/message/version_0";
2
+ import { generatePrivateKey, generateSymmetricKey, getPublicKey, } from "./crypto/index.js";
3
+ export const OneMillion = BigInt(1000000);
16
4
  export { generatePrivateKey, generateSymmetricKey, getPublicKey };
5
+ export * as ecies from "./ecies.js";
6
+ export * as symmetric from "./symmetric.js";
17
7
  export const Version = 1;
18
- export class MessageV1 extends MessageV0 {
8
+ export class DecodedMessage extends DecodedMessageV0 {
19
9
  constructor(proto, decodedPayload, signature, signaturePublicKey) {
20
10
  super(proto);
21
11
  this.signature = signature;
@@ -26,304 +16,4 @@ export class MessageV1 extends MessageV0 {
26
16
  return this._decodedPayload;
27
17
  }
28
18
  }
29
- export class AsymEncoder {
30
- constructor(contentTopic, publicKey, sigPrivKey, ephemeral = false) {
31
- this.contentTopic = contentTopic;
32
- this.publicKey = publicKey;
33
- this.sigPrivKey = sigPrivKey;
34
- this.ephemeral = ephemeral;
35
- }
36
- async toWire(message) {
37
- const protoMessage = await this.toProtoObj(message);
38
- if (!protoMessage)
39
- return;
40
- return proto.WakuMessage.encode(protoMessage);
41
- }
42
- async toProtoObj(message) {
43
- const timestamp = message.timestamp ?? new Date();
44
- if (!message.payload) {
45
- log("No payload to encrypt, skipping: ", message);
46
- return;
47
- }
48
- const preparedPayload = await preCipher(message.payload, this.sigPrivKey);
49
- const payload = await encryptAsymmetric(preparedPayload, this.publicKey);
50
- return {
51
- payload,
52
- version: Version,
53
- contentTopic: this.contentTopic,
54
- timestamp: BigInt(timestamp.valueOf()) * OneMillion,
55
- rateLimitProof: message.rateLimitProof,
56
- ephemeral: this.ephemeral,
57
- };
58
- }
59
- }
60
- export class SymEncoder {
61
- constructor(contentTopic, symKey, sigPrivKey, ephemeral = false) {
62
- this.contentTopic = contentTopic;
63
- this.symKey = symKey;
64
- this.sigPrivKey = sigPrivKey;
65
- this.ephemeral = ephemeral;
66
- }
67
- async toWire(message) {
68
- const protoMessage = await this.toProtoObj(message);
69
- if (!protoMessage)
70
- return;
71
- return proto.WakuMessage.encode(protoMessage);
72
- }
73
- async toProtoObj(message) {
74
- const timestamp = message.timestamp ?? new Date();
75
- if (!message.payload) {
76
- log("No payload to encrypt, skipping: ", message);
77
- return;
78
- }
79
- const preparedPayload = await preCipher(message.payload, this.sigPrivKey);
80
- const payload = await encryptSymmetric(preparedPayload, this.symKey);
81
- return {
82
- payload,
83
- version: Version,
84
- contentTopic: this.contentTopic,
85
- timestamp: BigInt(timestamp.valueOf()) * OneMillion,
86
- rateLimitProof: message.rateLimitProof,
87
- ephemeral: this.ephemeral,
88
- };
89
- }
90
- }
91
- export class AsymDecoder extends DecoderV0 {
92
- constructor(contentTopic, privateKey) {
93
- super(contentTopic);
94
- this.privateKey = privateKey;
95
- }
96
- async fromProtoObj(protoMessage) {
97
- const cipherPayload = protoMessage.payload;
98
- if (protoMessage.version !== Version) {
99
- log("Failed to decrypt due to incorrect version, expected:", Version, ", actual:", protoMessage.version);
100
- return;
101
- }
102
- let payload;
103
- if (!cipherPayload) {
104
- log(`No payload to decrypt for contentTopic ${this.contentTopic}`);
105
- return;
106
- }
107
- try {
108
- payload = await decryptAsymmetric(cipherPayload, this.privateKey);
109
- }
110
- catch (e) {
111
- log(`Failed to decrypt message using asymmetric decryption for contentTopic: ${this.contentTopic}`, e);
112
- return;
113
- }
114
- if (!payload) {
115
- log(`Failed to decrypt payload for contentTopic ${this.contentTopic}`);
116
- return;
117
- }
118
- const res = await postCipher(payload);
119
- if (!res) {
120
- log(`Failed to decode payload for contentTopic ${this.contentTopic}`);
121
- return;
122
- }
123
- log("Message decrypted", protoMessage);
124
- return new MessageV1(protoMessage, res.payload, res.sig?.signature, res.sig?.publicKey);
125
- }
126
- }
127
- export class SymDecoder extends DecoderV0 {
128
- constructor(contentTopic, symKey) {
129
- super(contentTopic);
130
- this.symKey = symKey;
131
- }
132
- async fromProtoObj(protoMessage) {
133
- const cipherPayload = protoMessage.payload;
134
- if (protoMessage.version !== Version) {
135
- log("Failed to decrypt due to incorrect version, expected:", Version, ", actual:", protoMessage.version);
136
- return;
137
- }
138
- let payload;
139
- if (!cipherPayload) {
140
- log(`No payload to decrypt for contentTopic ${this.contentTopic}`);
141
- return;
142
- }
143
- try {
144
- payload = await decryptSymmetric(cipherPayload, this.symKey);
145
- }
146
- catch (e) {
147
- log(`Failed to decrypt message using asymmetric decryption for contentTopic: ${this.contentTopic}`, e);
148
- return;
149
- }
150
- if (!payload) {
151
- log(`Failed to decrypt payload for contentTopic ${this.contentTopic}`);
152
- return;
153
- }
154
- const res = await postCipher(payload);
155
- if (!res) {
156
- log(`Failed to decode payload for contentTopic ${this.contentTopic}`);
157
- return;
158
- }
159
- log("Message decrypted", protoMessage);
160
- return new MessageV1(protoMessage, res.payload, res.sig?.signature, res.sig?.publicKey);
161
- }
162
- }
163
- function getSizeOfPayloadSizeField(message) {
164
- const messageDataView = new DataView(message.buffer);
165
- return messageDataView.getUint8(0) & FlagMask;
166
- }
167
- function getPayloadSize(message, sizeOfPayloadSizeField) {
168
- let payloadSizeBytes = message.slice(1, 1 + sizeOfPayloadSizeField);
169
- // int 32 == 4 bytes
170
- if (sizeOfPayloadSizeField < 4) {
171
- // If less than 4 bytes pad right (Little Endian).
172
- payloadSizeBytes = concat([payloadSizeBytes, new Uint8Array(4 - sizeOfPayloadSizeField)], 4);
173
- }
174
- const payloadSizeDataView = new DataView(payloadSizeBytes.buffer);
175
- return payloadSizeDataView.getInt32(0, true);
176
- }
177
- function isMessageSigned(message) {
178
- const messageDataView = new DataView(message.buffer);
179
- return (messageDataView.getUint8(0) & IsSignedMask) == IsSignedMask;
180
- }
181
- /**
182
- * Proceed with Asymmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
183
- * The data MUST be flags | payload-length | payload | [signature].
184
- * The returned result can be set to `WakuMessage.payload`.
185
- *
186
- * @internal
187
- */
188
- export async function encryptAsymmetric(data, publicKey) {
189
- return ecies.encrypt(hexToBytes(publicKey), data);
190
- }
191
- /**
192
- * Proceed with Asymmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
193
- * The returned data is expected to be `flags | payload-length | payload | [signature]`.
194
- *
195
- * @internal
196
- */
197
- export async function decryptAsymmetric(payload, privKey) {
198
- return ecies.decrypt(privKey, payload);
199
- }
200
- /**
201
- * Proceed with Symmetric encryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
202
- *
203
- * @param data The data to encrypt, expected to be `flags | payload-length | payload | [signature]`.
204
- * @param key The key to use for encryption.
205
- * @returns The decrypted data, `cipherText | tag | iv` and can be set to `WakuMessage.payload`.
206
- *
207
- * @internal
208
- */
209
- export async function encryptSymmetric(data, key) {
210
- const iv = symmetric.generateIv();
211
- // Returns `cipher | tag`
212
- const cipher = await symmetric.encrypt(iv, hexToBytes(key), data);
213
- return concat([cipher, iv]);
214
- }
215
- /**
216
- * Proceed with Symmetric decryption of the data as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
217
- *
218
- * @param payload The cipher data, it is expected to be `cipherText | tag | iv`.
219
- * @param key The key to use for decryption.
220
- * @returns The decrypted data, expected to be `flags | payload-length | payload | [signature]`.
221
- *
222
- * @internal
223
- */
224
- export async function decryptSymmetric(payload, key) {
225
- const ivStart = payload.length - Symmetric.ivSize;
226
- const cipher = payload.slice(0, ivStart);
227
- const iv = payload.slice(ivStart);
228
- return symmetric.decrypt(iv, hexToBytes(key), cipher);
229
- }
230
- /**
231
- * Computes the flags & auxiliary-field as per [26/WAKU-PAYLOAD](https://rfc.vac.dev/spec/26/).
232
- */
233
- function addPayloadSizeField(msg, payload) {
234
- const fieldSize = computeSizeOfPayloadSizeField(payload);
235
- let field = new Uint8Array(4);
236
- const fieldDataView = new DataView(field.buffer);
237
- fieldDataView.setUint32(0, payload.length, true);
238
- field = field.slice(0, fieldSize);
239
- msg = concat([msg, field]);
240
- msg[0] |= fieldSize;
241
- return msg;
242
- }
243
- /**
244
- * Returns the size of the auxiliary-field which in turns contains the payload size
245
- */
246
- function computeSizeOfPayloadSizeField(payload) {
247
- let s = 1;
248
- for (let i = payload.length; i >= 256; i /= 256) {
249
- s++;
250
- }
251
- return s;
252
- }
253
- function validateDataIntegrity(value, expectedSize) {
254
- if (value.length !== expectedSize) {
255
- return false;
256
- }
257
- return expectedSize <= 3 || value.findIndex((i) => i !== 0) !== -1;
258
- }
259
- function getSignature(message) {
260
- return message.slice(message.length - SignatureLength, message.length);
261
- }
262
- function getHash(message, isSigned) {
263
- if (isSigned) {
264
- return keccak256(message.slice(0, message.length - SignatureLength));
265
- }
266
- return keccak256(message);
267
- }
268
- function ecRecoverPubKey(messageHash, signature) {
269
- const recoveryDataView = new DataView(signature.slice(64).buffer);
270
- const recovery = recoveryDataView.getUint8(0);
271
- const _signature = secp.Signature.fromCompact(signature.slice(0, 64));
272
- return secp.recoverPublicKey(messageHash, _signature, recovery, false);
273
- }
274
- /**
275
- * Prepare the payload pre-encryption.
276
- *
277
- * @internal
278
- * @returns The encoded payload, ready for encryption using {@link encryptAsymmetric}
279
- * or {@link encryptSymmetric}.
280
- */
281
- export async function preCipher(messagePayload, sigPrivKey) {
282
- let envelope = new Uint8Array([0]); // No flags
283
- envelope = addPayloadSizeField(envelope, messagePayload);
284
- envelope = concat([envelope, messagePayload]);
285
- // Calculate padding:
286
- let rawSize = FlagsLength +
287
- computeSizeOfPayloadSizeField(messagePayload) +
288
- messagePayload.length;
289
- if (sigPrivKey) {
290
- rawSize += SignatureLength;
291
- }
292
- const remainder = rawSize % PaddingTarget;
293
- const paddingSize = PaddingTarget - remainder;
294
- const pad = randomBytes(paddingSize);
295
- if (!validateDataIntegrity(pad, paddingSize)) {
296
- throw new Error("failed to generate random padding of size " + paddingSize);
297
- }
298
- envelope = concat([envelope, pad]);
299
- if (sigPrivKey) {
300
- envelope[0] |= IsSignedMask;
301
- const hash = keccak256(envelope);
302
- const bytesSignature = await sign(hash, sigPrivKey);
303
- envelope = concat([envelope, bytesSignature]);
304
- }
305
- return envelope;
306
- }
307
- /**
308
- * Decode a decrypted payload.
309
- *
310
- * @internal
311
- */
312
- export function postCipher(message) {
313
- const sizeOfPayloadSizeField = getSizeOfPayloadSizeField(message);
314
- if (sizeOfPayloadSizeField === 0)
315
- return;
316
- const payloadSize = getPayloadSize(message, sizeOfPayloadSizeField);
317
- const payloadStart = 1 + sizeOfPayloadSizeField;
318
- const payload = message.slice(payloadStart, payloadStart + payloadSize);
319
- const isSigned = isMessageSigned(message);
320
- let sig;
321
- if (isSigned) {
322
- const signature = getSignature(message);
323
- const hash = getHash(message, isSigned);
324
- const publicKey = ecRecoverPubKey(hash, signature);
325
- sig = { signature, publicKey };
326
- }
327
- return { payload, sig };
328
- }
329
19
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EACL,SAAS,EACT,SAAS,EACT,KAAK,GACN,MAAM,uCAAuC,CAAC;AAQ/C,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EACL,kBAAkB,EAClB,oBAAoB,EACpB,YAAY,EACZ,SAAS,EACT,WAAW,EACX,IAAI,GACL,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAC;AAE5C,MAAM,GAAG,GAAG,KAAK,CAAC,wBAAwB,CAAC,CAAC;AAE5C,MAAM,WAAW,GAAG,CAAC,CAAC;AACtB,MAAM,QAAQ,GAAG,CAAC,CAAC,CAAC,OAAO;AAC3B,MAAM,YAAY,GAAG,CAAC,CAAC,CAAC,OAAO;AAC/B,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,UAAU,GAAG,MAAM,CAAC,OAAS,CAAC,CAAC;AAErC,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,YAAY,EAAE,CAAC;AAElE,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,CAAC;AAOzB,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B,EAAE,oBAAoB,EAAE,YAAY,EAAE,CAAC;AAElE,OAAO,KAAK,KAAK,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,SAAS,MAAM,gBAAgB,CAAC;AAE5C,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,CAAC;AAOzB,MAAM,OAAO,cACX,SAAQ,gBAAgB;IAKxB,YACE,KAAwB,EACxB,cAA0B,EACnB,SAAsB,EACtB,kBAA+B;QAEtC,KAAK,CAAC,KAAK,CAAC,CAAC;QAHN,cAAS,GAAT,SAAS,CAAa;QACtB,uBAAkB,GAAlB,kBAAkB,CAAa;QAGtC,IAAI,CAAC,eAAe,GAAG,cAAc,CAAC;IACxC,CAAC;IAED,IAAI,OAAO;QACT,OAAO,IAAI,CAAC,eAAe,CAAC;IAC9B,CAAC;CACF"}
@@ -1,3 +1,51 @@
1
- export declare function encrypt(iv: Uint8Array, key: Uint8Array, clearText: Uint8Array): Promise<Uint8Array>;
2
- export declare function decrypt(iv: Uint8Array, key: Uint8Array, cipherText: Uint8Array): Promise<Uint8Array>;
3
- export declare function generateIv(): Uint8Array;
1
+ import { Decoder as DecoderV0 } from "@waku/core/lib/message/version_0";
2
+ import type { IDecoder, IEncoder, IMessage, IProtoMessage } from "@waku/interfaces";
3
+ import { DecodedMessage, generateSymmetricKey } from "./index.js";
4
+ export { DecodedMessage, generateSymmetricKey };
5
+ declare class Encoder implements IEncoder {
6
+ contentTopic: string;
7
+ private symKey;
8
+ private sigPrivKey?;
9
+ ephemeral: boolean;
10
+ constructor(contentTopic: string, symKey: Uint8Array, sigPrivKey?: Uint8Array | undefined, ephemeral?: boolean);
11
+ toWire(message: IMessage): Promise<Uint8Array | undefined>;
12
+ toProtoObj(message: IMessage): Promise<IProtoMessage | undefined>;
13
+ }
14
+ /**
15
+ * Creates an encoder that encrypts messages using symmetric encryption for the
16
+ * given key, as defined in [26/WAKU2-PAYLOAD](https://rfc.vac.dev/spec/26/).
17
+ *
18
+ * An encoder is used to encode messages in the [`14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)
19
+ * format to be sent over the Waku network. The resulting encoder can then be
20
+ * pass to { @link @waku/interfaces.LightPush.push } or
21
+ * { @link @waku/interfaces.Relay.send } to automatically encrypt
22
+ * and encode outgoing messages.
23
+ *
24
+ * The payload can optionally be signed with the given private key as defined
25
+ * in [26/WAKU2-PAYLOAD](https://rfc.vac.dev/spec/26/).
26
+ *
27
+ * @param contentTopic The content topic to set on outgoing messages.
28
+ * @param symKey The symmetric key to encrypt the payload with.
29
+ * @param sigPrivKey An optional private key to used to sign the payload before encryption.
30
+ * @param ephemeral An optional flag to mark message as ephemeral, ie, not to be stored by Waku Store nodes.
31
+ */
32
+ export declare function createEncoder(contentTopic: string, symKey: Uint8Array, sigPrivKey?: Uint8Array, ephemeral?: boolean): Encoder;
33
+ declare class Decoder extends DecoderV0 implements IDecoder<DecodedMessage> {
34
+ private symKey;
35
+ constructor(contentTopic: string, symKey: Uint8Array);
36
+ fromProtoObj(protoMessage: IProtoMessage): Promise<DecodedMessage | undefined>;
37
+ }
38
+ /**
39
+ * Creates a decoder that decrypts messages using symmetric encryption, using
40
+ * the given key as defined in [26/WAKU2-PAYLOAD](https://rfc.vac.dev/spec/26/).
41
+ *
42
+ * A decoder is used to decode messages from the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)
43
+ * format when received from the Waku network. The resulting decoder can then be
44
+ * pass to { @link @waku/interfaces.Filter.subscribe } or
45
+ * { @link @waku/interfaces.Relay.subscribe } to automatically decrypt and
46
+ * decode incoming messages.
47
+ *
48
+ * @param contentTopic The resulting decoder will only decode messages with this content topic.
49
+ * @param symKey The symmetric key used to decrypt the message.
50
+ */
51
+ export declare function createDecoder(contentTopic: string, symKey: Uint8Array): Decoder;
package/dist/symmetric.js CHANGED
@@ -1,18 +1,111 @@
1
- import { Symmetric } from "./constants.js";
2
- import { getSubtle, randomBytes } from "./crypto.js";
3
- export async function encrypt(iv, key, clearText) {
4
- return getSubtle()
5
- .importKey("raw", key, Symmetric.algorithm, false, ["encrypt"])
6
- .then((cryptoKey) => getSubtle().encrypt({ iv, ...Symmetric.algorithm }, cryptoKey, clearText))
7
- .then((cipher) => new Uint8Array(cipher));
1
+ import { Decoder as DecoderV0, proto } from "@waku/core/lib/message/version_0";
2
+ import debug from "debug";
3
+ import { decryptSymmetric, encryptSymmetric, postCipher, preCipher, } from "./waku_payload.js";
4
+ import { DecodedMessage, generateSymmetricKey, OneMillion, Version, } from "./index.js";
5
+ export { DecodedMessage, generateSymmetricKey };
6
+ const log = debug("waku:message-encryption:symmetric");
7
+ class Encoder {
8
+ constructor(contentTopic, symKey, sigPrivKey, ephemeral = false) {
9
+ this.contentTopic = contentTopic;
10
+ this.symKey = symKey;
11
+ this.sigPrivKey = sigPrivKey;
12
+ this.ephemeral = ephemeral;
13
+ }
14
+ async toWire(message) {
15
+ const protoMessage = await this.toProtoObj(message);
16
+ if (!protoMessage)
17
+ return;
18
+ return proto.WakuMessage.encode(protoMessage);
19
+ }
20
+ async toProtoObj(message) {
21
+ const timestamp = message.timestamp ?? new Date();
22
+ if (!message.payload) {
23
+ log("No payload to encrypt, skipping: ", message);
24
+ return;
25
+ }
26
+ const preparedPayload = await preCipher(message.payload, this.sigPrivKey);
27
+ const payload = await encryptSymmetric(preparedPayload, this.symKey);
28
+ return {
29
+ payload,
30
+ version: Version,
31
+ contentTopic: this.contentTopic,
32
+ timestamp: BigInt(timestamp.valueOf()) * OneMillion,
33
+ rateLimitProof: message.rateLimitProof,
34
+ ephemeral: this.ephemeral,
35
+ };
36
+ }
8
37
  }
9
- export async function decrypt(iv, key, cipherText) {
10
- return getSubtle()
11
- .importKey("raw", key, Symmetric.algorithm, false, ["decrypt"])
12
- .then((cryptoKey) => getSubtle().decrypt({ iv, ...Symmetric.algorithm }, cryptoKey, cipherText))
13
- .then((clear) => new Uint8Array(clear));
38
+ /**
39
+ * Creates an encoder that encrypts messages using symmetric encryption for the
40
+ * given key, as defined in [26/WAKU2-PAYLOAD](https://rfc.vac.dev/spec/26/).
41
+ *
42
+ * An encoder is used to encode messages in the [`14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)
43
+ * format to be sent over the Waku network. The resulting encoder can then be
44
+ * pass to { @link @waku/interfaces.LightPush.push } or
45
+ * { @link @waku/interfaces.Relay.send } to automatically encrypt
46
+ * and encode outgoing messages.
47
+ *
48
+ * The payload can optionally be signed with the given private key as defined
49
+ * in [26/WAKU2-PAYLOAD](https://rfc.vac.dev/spec/26/).
50
+ *
51
+ * @param contentTopic The content topic to set on outgoing messages.
52
+ * @param symKey The symmetric key to encrypt the payload with.
53
+ * @param sigPrivKey An optional private key to used to sign the payload before encryption.
54
+ * @param ephemeral An optional flag to mark message as ephemeral, ie, not to be stored by Waku Store nodes.
55
+ */
56
+ export function createEncoder(contentTopic, symKey, sigPrivKey, ephemeral = false) {
57
+ return new Encoder(contentTopic, symKey, sigPrivKey, ephemeral);
14
58
  }
15
- export function generateIv() {
16
- return randomBytes(Symmetric.ivSize);
59
+ class Decoder extends DecoderV0 {
60
+ constructor(contentTopic, symKey) {
61
+ super(contentTopic);
62
+ this.symKey = symKey;
63
+ }
64
+ async fromProtoObj(protoMessage) {
65
+ const cipherPayload = protoMessage.payload;
66
+ if (protoMessage.version !== Version) {
67
+ log("Failed to decrypt due to incorrect version, expected:", Version, ", actual:", protoMessage.version);
68
+ return;
69
+ }
70
+ let payload;
71
+ if (!cipherPayload) {
72
+ log(`No payload to decrypt for contentTopic ${this.contentTopic}`);
73
+ return;
74
+ }
75
+ try {
76
+ payload = await decryptSymmetric(cipherPayload, this.symKey);
77
+ }
78
+ catch (e) {
79
+ log(`Failed to decrypt message using asymmetric decryption for contentTopic: ${this.contentTopic}`, e);
80
+ return;
81
+ }
82
+ if (!payload) {
83
+ log(`Failed to decrypt payload for contentTopic ${this.contentTopic}`);
84
+ return;
85
+ }
86
+ const res = await postCipher(payload);
87
+ if (!res) {
88
+ log(`Failed to decode payload for contentTopic ${this.contentTopic}`);
89
+ return;
90
+ }
91
+ log("Message decrypted", protoMessage);
92
+ return new DecodedMessage(protoMessage, res.payload, res.sig?.signature, res.sig?.publicKey);
93
+ }
94
+ }
95
+ /**
96
+ * Creates a decoder that decrypts messages using symmetric encryption, using
97
+ * the given key as defined in [26/WAKU2-PAYLOAD](https://rfc.vac.dev/spec/26/).
98
+ *
99
+ * A decoder is used to decode messages from the [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/)
100
+ * format when received from the Waku network. The resulting decoder can then be
101
+ * pass to { @link @waku/interfaces.Filter.subscribe } or
102
+ * { @link @waku/interfaces.Relay.subscribe } to automatically decrypt and
103
+ * decode incoming messages.
104
+ *
105
+ * @param contentTopic The resulting decoder will only decode messages with this content topic.
106
+ * @param symKey The symmetric key used to decrypt the message.
107
+ */
108
+ export function createDecoder(contentTopic, symKey) {
109
+ return new Decoder(contentTopic, symKey);
17
110
  }
18
111
  //# sourceMappingURL=symmetric.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"symmetric.js","sourceRoot":"","sources":["../src/symmetric.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAErD,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,EAAc,EACd,GAAe,EACf,SAAqB;IAErB,OAAO,SAAS,EAAE;SACf,SAAS,CAAC,KAAK,EAAE,GAAG,EAAE,SAAS,CAAC,SAAS,EAAE,KAAK,EAAE,CAAC,SAAS,CAAC,CAAC;SAC9D,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAClB,SAAS,EAAE,CAAC,OAAO,CAAC,EAAE,EAAE,EAAE,GAAG,SAAS,CAAC,SAAS,EAAE,EAAE,SAAS,EAAE,SAAS,CAAC,CAC1E;SACA,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,IAAI,UAAU,CAAC,MAAM,CAAC,CAA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