dignity.js 0.1.0

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.
@@ -0,0 +1,3585 @@
1
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
+ var __commonJS = (cb, mod) => function __require() {
3
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4
+ };
5
+
6
+ // src/utils/event-emitter.js
7
+ var require_event_emitter = __commonJS({
8
+ "src/utils/event-emitter.js"(exports2, module2) {
9
+ var EventEmitter = class {
10
+ constructor() {
11
+ this.handlers = /* @__PURE__ */ new Map();
12
+ }
13
+ on(eventName, handler) {
14
+ if (!this.handlers.has(eventName)) {
15
+ this.handlers.set(eventName, /* @__PURE__ */ new Set());
16
+ }
17
+ this.handlers.get(eventName).add(handler);
18
+ }
19
+ off(eventName, handler) {
20
+ const eventHandlers = this.handlers.get(eventName);
21
+ if (!eventHandlers) {
22
+ return;
23
+ }
24
+ eventHandlers.delete(handler);
25
+ if (eventHandlers.size === 0) {
26
+ this.handlers.delete(eventName);
27
+ }
28
+ }
29
+ emit(eventName, payload) {
30
+ const eventHandlers = this.handlers.get(eventName);
31
+ if (!eventHandlers) {
32
+ return;
33
+ }
34
+ for (const handler of eventHandlers) {
35
+ handler(payload);
36
+ }
37
+ }
38
+ };
39
+ module2.exports = EventEmitter;
40
+ }
41
+ });
42
+
43
+ // node_modules/tweetnacl/nacl-fast.js
44
+ var require_nacl_fast = __commonJS({
45
+ "node_modules/tweetnacl/nacl-fast.js"(exports2, module2) {
46
+ (function(nacl) {
47
+ "use strict";
48
+ var gf = function(init) {
49
+ var i, r = new Float64Array(16);
50
+ if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
51
+ return r;
52
+ };
53
+ var randombytes = function() {
54
+ throw new Error("no PRNG");
55
+ };
56
+ var _0 = new Uint8Array(16);
57
+ var _9 = new Uint8Array(32);
58
+ _9[0] = 9;
59
+ var gf0 = gf(), gf1 = gf([1]), _121665 = gf([56129, 1]), D = gf([30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995]), D2 = gf([61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222]), X = gf([54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553]), Y = gf([26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214]), I = gf([41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139]);
60
+ function ts64(x, i, h, l) {
61
+ x[i] = h >> 24 & 255;
62
+ x[i + 1] = h >> 16 & 255;
63
+ x[i + 2] = h >> 8 & 255;
64
+ x[i + 3] = h & 255;
65
+ x[i + 4] = l >> 24 & 255;
66
+ x[i + 5] = l >> 16 & 255;
67
+ x[i + 6] = l >> 8 & 255;
68
+ x[i + 7] = l & 255;
69
+ }
70
+ function vn(x, xi, y, yi, n) {
71
+ var i, d = 0;
72
+ for (i = 0; i < n; i++) d |= x[xi + i] ^ y[yi + i];
73
+ return (1 & d - 1 >>> 8) - 1;
74
+ }
75
+ function crypto_verify_16(x, xi, y, yi) {
76
+ return vn(x, xi, y, yi, 16);
77
+ }
78
+ function crypto_verify_32(x, xi, y, yi) {
79
+ return vn(x, xi, y, yi, 32);
80
+ }
81
+ function core_salsa20(o, p, k, c) {
82
+ var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24;
83
+ var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u;
84
+ for (var i = 0; i < 20; i += 2) {
85
+ u = x0 + x12 | 0;
86
+ x4 ^= u << 7 | u >>> 32 - 7;
87
+ u = x4 + x0 | 0;
88
+ x8 ^= u << 9 | u >>> 32 - 9;
89
+ u = x8 + x4 | 0;
90
+ x12 ^= u << 13 | u >>> 32 - 13;
91
+ u = x12 + x8 | 0;
92
+ x0 ^= u << 18 | u >>> 32 - 18;
93
+ u = x5 + x1 | 0;
94
+ x9 ^= u << 7 | u >>> 32 - 7;
95
+ u = x9 + x5 | 0;
96
+ x13 ^= u << 9 | u >>> 32 - 9;
97
+ u = x13 + x9 | 0;
98
+ x1 ^= u << 13 | u >>> 32 - 13;
99
+ u = x1 + x13 | 0;
100
+ x5 ^= u << 18 | u >>> 32 - 18;
101
+ u = x10 + x6 | 0;
102
+ x14 ^= u << 7 | u >>> 32 - 7;
103
+ u = x14 + x10 | 0;
104
+ x2 ^= u << 9 | u >>> 32 - 9;
105
+ u = x2 + x14 | 0;
106
+ x6 ^= u << 13 | u >>> 32 - 13;
107
+ u = x6 + x2 | 0;
108
+ x10 ^= u << 18 | u >>> 32 - 18;
109
+ u = x15 + x11 | 0;
110
+ x3 ^= u << 7 | u >>> 32 - 7;
111
+ u = x3 + x15 | 0;
112
+ x7 ^= u << 9 | u >>> 32 - 9;
113
+ u = x7 + x3 | 0;
114
+ x11 ^= u << 13 | u >>> 32 - 13;
115
+ u = x11 + x7 | 0;
116
+ x15 ^= u << 18 | u >>> 32 - 18;
117
+ u = x0 + x3 | 0;
118
+ x1 ^= u << 7 | u >>> 32 - 7;
119
+ u = x1 + x0 | 0;
120
+ x2 ^= u << 9 | u >>> 32 - 9;
121
+ u = x2 + x1 | 0;
122
+ x3 ^= u << 13 | u >>> 32 - 13;
123
+ u = x3 + x2 | 0;
124
+ x0 ^= u << 18 | u >>> 32 - 18;
125
+ u = x5 + x4 | 0;
126
+ x6 ^= u << 7 | u >>> 32 - 7;
127
+ u = x6 + x5 | 0;
128
+ x7 ^= u << 9 | u >>> 32 - 9;
129
+ u = x7 + x6 | 0;
130
+ x4 ^= u << 13 | u >>> 32 - 13;
131
+ u = x4 + x7 | 0;
132
+ x5 ^= u << 18 | u >>> 32 - 18;
133
+ u = x10 + x9 | 0;
134
+ x11 ^= u << 7 | u >>> 32 - 7;
135
+ u = x11 + x10 | 0;
136
+ x8 ^= u << 9 | u >>> 32 - 9;
137
+ u = x8 + x11 | 0;
138
+ x9 ^= u << 13 | u >>> 32 - 13;
139
+ u = x9 + x8 | 0;
140
+ x10 ^= u << 18 | u >>> 32 - 18;
141
+ u = x15 + x14 | 0;
142
+ x12 ^= u << 7 | u >>> 32 - 7;
143
+ u = x12 + x15 | 0;
144
+ x13 ^= u << 9 | u >>> 32 - 9;
145
+ u = x13 + x12 | 0;
146
+ x14 ^= u << 13 | u >>> 32 - 13;
147
+ u = x14 + x13 | 0;
148
+ x15 ^= u << 18 | u >>> 32 - 18;
149
+ }
150
+ x0 = x0 + j0 | 0;
151
+ x1 = x1 + j1 | 0;
152
+ x2 = x2 + j2 | 0;
153
+ x3 = x3 + j3 | 0;
154
+ x4 = x4 + j4 | 0;
155
+ x5 = x5 + j5 | 0;
156
+ x6 = x6 + j6 | 0;
157
+ x7 = x7 + j7 | 0;
158
+ x8 = x8 + j8 | 0;
159
+ x9 = x9 + j9 | 0;
160
+ x10 = x10 + j10 | 0;
161
+ x11 = x11 + j11 | 0;
162
+ x12 = x12 + j12 | 0;
163
+ x13 = x13 + j13 | 0;
164
+ x14 = x14 + j14 | 0;
165
+ x15 = x15 + j15 | 0;
166
+ o[0] = x0 >>> 0 & 255;
167
+ o[1] = x0 >>> 8 & 255;
168
+ o[2] = x0 >>> 16 & 255;
169
+ o[3] = x0 >>> 24 & 255;
170
+ o[4] = x1 >>> 0 & 255;
171
+ o[5] = x1 >>> 8 & 255;
172
+ o[6] = x1 >>> 16 & 255;
173
+ o[7] = x1 >>> 24 & 255;
174
+ o[8] = x2 >>> 0 & 255;
175
+ o[9] = x2 >>> 8 & 255;
176
+ o[10] = x2 >>> 16 & 255;
177
+ o[11] = x2 >>> 24 & 255;
178
+ o[12] = x3 >>> 0 & 255;
179
+ o[13] = x3 >>> 8 & 255;
180
+ o[14] = x3 >>> 16 & 255;
181
+ o[15] = x3 >>> 24 & 255;
182
+ o[16] = x4 >>> 0 & 255;
183
+ o[17] = x4 >>> 8 & 255;
184
+ o[18] = x4 >>> 16 & 255;
185
+ o[19] = x4 >>> 24 & 255;
186
+ o[20] = x5 >>> 0 & 255;
187
+ o[21] = x5 >>> 8 & 255;
188
+ o[22] = x5 >>> 16 & 255;
189
+ o[23] = x5 >>> 24 & 255;
190
+ o[24] = x6 >>> 0 & 255;
191
+ o[25] = x6 >>> 8 & 255;
192
+ o[26] = x6 >>> 16 & 255;
193
+ o[27] = x6 >>> 24 & 255;
194
+ o[28] = x7 >>> 0 & 255;
195
+ o[29] = x7 >>> 8 & 255;
196
+ o[30] = x7 >>> 16 & 255;
197
+ o[31] = x7 >>> 24 & 255;
198
+ o[32] = x8 >>> 0 & 255;
199
+ o[33] = x8 >>> 8 & 255;
200
+ o[34] = x8 >>> 16 & 255;
201
+ o[35] = x8 >>> 24 & 255;
202
+ o[36] = x9 >>> 0 & 255;
203
+ o[37] = x9 >>> 8 & 255;
204
+ o[38] = x9 >>> 16 & 255;
205
+ o[39] = x9 >>> 24 & 255;
206
+ o[40] = x10 >>> 0 & 255;
207
+ o[41] = x10 >>> 8 & 255;
208
+ o[42] = x10 >>> 16 & 255;
209
+ o[43] = x10 >>> 24 & 255;
210
+ o[44] = x11 >>> 0 & 255;
211
+ o[45] = x11 >>> 8 & 255;
212
+ o[46] = x11 >>> 16 & 255;
213
+ o[47] = x11 >>> 24 & 255;
214
+ o[48] = x12 >>> 0 & 255;
215
+ o[49] = x12 >>> 8 & 255;
216
+ o[50] = x12 >>> 16 & 255;
217
+ o[51] = x12 >>> 24 & 255;
218
+ o[52] = x13 >>> 0 & 255;
219
+ o[53] = x13 >>> 8 & 255;
220
+ o[54] = x13 >>> 16 & 255;
221
+ o[55] = x13 >>> 24 & 255;
222
+ o[56] = x14 >>> 0 & 255;
223
+ o[57] = x14 >>> 8 & 255;
224
+ o[58] = x14 >>> 16 & 255;
225
+ o[59] = x14 >>> 24 & 255;
226
+ o[60] = x15 >>> 0 & 255;
227
+ o[61] = x15 >>> 8 & 255;
228
+ o[62] = x15 >>> 16 & 255;
229
+ o[63] = x15 >>> 24 & 255;
230
+ }
231
+ function core_hsalsa20(o, p, k, c) {
232
+ var j0 = c[0] & 255 | (c[1] & 255) << 8 | (c[2] & 255) << 16 | (c[3] & 255) << 24, j1 = k[0] & 255 | (k[1] & 255) << 8 | (k[2] & 255) << 16 | (k[3] & 255) << 24, j2 = k[4] & 255 | (k[5] & 255) << 8 | (k[6] & 255) << 16 | (k[7] & 255) << 24, j3 = k[8] & 255 | (k[9] & 255) << 8 | (k[10] & 255) << 16 | (k[11] & 255) << 24, j4 = k[12] & 255 | (k[13] & 255) << 8 | (k[14] & 255) << 16 | (k[15] & 255) << 24, j5 = c[4] & 255 | (c[5] & 255) << 8 | (c[6] & 255) << 16 | (c[7] & 255) << 24, j6 = p[0] & 255 | (p[1] & 255) << 8 | (p[2] & 255) << 16 | (p[3] & 255) << 24, j7 = p[4] & 255 | (p[5] & 255) << 8 | (p[6] & 255) << 16 | (p[7] & 255) << 24, j8 = p[8] & 255 | (p[9] & 255) << 8 | (p[10] & 255) << 16 | (p[11] & 255) << 24, j9 = p[12] & 255 | (p[13] & 255) << 8 | (p[14] & 255) << 16 | (p[15] & 255) << 24, j10 = c[8] & 255 | (c[9] & 255) << 8 | (c[10] & 255) << 16 | (c[11] & 255) << 24, j11 = k[16] & 255 | (k[17] & 255) << 8 | (k[18] & 255) << 16 | (k[19] & 255) << 24, j12 = k[20] & 255 | (k[21] & 255) << 8 | (k[22] & 255) << 16 | (k[23] & 255) << 24, j13 = k[24] & 255 | (k[25] & 255) << 8 | (k[26] & 255) << 16 | (k[27] & 255) << 24, j14 = k[28] & 255 | (k[29] & 255) << 8 | (k[30] & 255) << 16 | (k[31] & 255) << 24, j15 = c[12] & 255 | (c[13] & 255) << 8 | (c[14] & 255) << 16 | (c[15] & 255) << 24;
233
+ var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u;
234
+ for (var i = 0; i < 20; i += 2) {
235
+ u = x0 + x12 | 0;
236
+ x4 ^= u << 7 | u >>> 32 - 7;
237
+ u = x4 + x0 | 0;
238
+ x8 ^= u << 9 | u >>> 32 - 9;
239
+ u = x8 + x4 | 0;
240
+ x12 ^= u << 13 | u >>> 32 - 13;
241
+ u = x12 + x8 | 0;
242
+ x0 ^= u << 18 | u >>> 32 - 18;
243
+ u = x5 + x1 | 0;
244
+ x9 ^= u << 7 | u >>> 32 - 7;
245
+ u = x9 + x5 | 0;
246
+ x13 ^= u << 9 | u >>> 32 - 9;
247
+ u = x13 + x9 | 0;
248
+ x1 ^= u << 13 | u >>> 32 - 13;
249
+ u = x1 + x13 | 0;
250
+ x5 ^= u << 18 | u >>> 32 - 18;
251
+ u = x10 + x6 | 0;
252
+ x14 ^= u << 7 | u >>> 32 - 7;
253
+ u = x14 + x10 | 0;
254
+ x2 ^= u << 9 | u >>> 32 - 9;
255
+ u = x2 + x14 | 0;
256
+ x6 ^= u << 13 | u >>> 32 - 13;
257
+ u = x6 + x2 | 0;
258
+ x10 ^= u << 18 | u >>> 32 - 18;
259
+ u = x15 + x11 | 0;
260
+ x3 ^= u << 7 | u >>> 32 - 7;
261
+ u = x3 + x15 | 0;
262
+ x7 ^= u << 9 | u >>> 32 - 9;
263
+ u = x7 + x3 | 0;
264
+ x11 ^= u << 13 | u >>> 32 - 13;
265
+ u = x11 + x7 | 0;
266
+ x15 ^= u << 18 | u >>> 32 - 18;
267
+ u = x0 + x3 | 0;
268
+ x1 ^= u << 7 | u >>> 32 - 7;
269
+ u = x1 + x0 | 0;
270
+ x2 ^= u << 9 | u >>> 32 - 9;
271
+ u = x2 + x1 | 0;
272
+ x3 ^= u << 13 | u >>> 32 - 13;
273
+ u = x3 + x2 | 0;
274
+ x0 ^= u << 18 | u >>> 32 - 18;
275
+ u = x5 + x4 | 0;
276
+ x6 ^= u << 7 | u >>> 32 - 7;
277
+ u = x6 + x5 | 0;
278
+ x7 ^= u << 9 | u >>> 32 - 9;
279
+ u = x7 + x6 | 0;
280
+ x4 ^= u << 13 | u >>> 32 - 13;
281
+ u = x4 + x7 | 0;
282
+ x5 ^= u << 18 | u >>> 32 - 18;
283
+ u = x10 + x9 | 0;
284
+ x11 ^= u << 7 | u >>> 32 - 7;
285
+ u = x11 + x10 | 0;
286
+ x8 ^= u << 9 | u >>> 32 - 9;
287
+ u = x8 + x11 | 0;
288
+ x9 ^= u << 13 | u >>> 32 - 13;
289
+ u = x9 + x8 | 0;
290
+ x10 ^= u << 18 | u >>> 32 - 18;
291
+ u = x15 + x14 | 0;
292
+ x12 ^= u << 7 | u >>> 32 - 7;
293
+ u = x12 + x15 | 0;
294
+ x13 ^= u << 9 | u >>> 32 - 9;
295
+ u = x13 + x12 | 0;
296
+ x14 ^= u << 13 | u >>> 32 - 13;
297
+ u = x14 + x13 | 0;
298
+ x15 ^= u << 18 | u >>> 32 - 18;
299
+ }
300
+ o[0] = x0 >>> 0 & 255;
301
+ o[1] = x0 >>> 8 & 255;
302
+ o[2] = x0 >>> 16 & 255;
303
+ o[3] = x0 >>> 24 & 255;
304
+ o[4] = x5 >>> 0 & 255;
305
+ o[5] = x5 >>> 8 & 255;
306
+ o[6] = x5 >>> 16 & 255;
307
+ o[7] = x5 >>> 24 & 255;
308
+ o[8] = x10 >>> 0 & 255;
309
+ o[9] = x10 >>> 8 & 255;
310
+ o[10] = x10 >>> 16 & 255;
311
+ o[11] = x10 >>> 24 & 255;
312
+ o[12] = x15 >>> 0 & 255;
313
+ o[13] = x15 >>> 8 & 255;
314
+ o[14] = x15 >>> 16 & 255;
315
+ o[15] = x15 >>> 24 & 255;
316
+ o[16] = x6 >>> 0 & 255;
317
+ o[17] = x6 >>> 8 & 255;
318
+ o[18] = x6 >>> 16 & 255;
319
+ o[19] = x6 >>> 24 & 255;
320
+ o[20] = x7 >>> 0 & 255;
321
+ o[21] = x7 >>> 8 & 255;
322
+ o[22] = x7 >>> 16 & 255;
323
+ o[23] = x7 >>> 24 & 255;
324
+ o[24] = x8 >>> 0 & 255;
325
+ o[25] = x8 >>> 8 & 255;
326
+ o[26] = x8 >>> 16 & 255;
327
+ o[27] = x8 >>> 24 & 255;
328
+ o[28] = x9 >>> 0 & 255;
329
+ o[29] = x9 >>> 8 & 255;
330
+ o[30] = x9 >>> 16 & 255;
331
+ o[31] = x9 >>> 24 & 255;
332
+ }
333
+ function crypto_core_salsa20(out, inp, k, c) {
334
+ core_salsa20(out, inp, k, c);
335
+ }
336
+ function crypto_core_hsalsa20(out, inp, k, c) {
337
+ core_hsalsa20(out, inp, k, c);
338
+ }
339
+ var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
340
+ function crypto_stream_salsa20_xor(c, cpos, m, mpos, b, n, k) {
341
+ var z = new Uint8Array(16), x = new Uint8Array(64);
342
+ var u, i;
343
+ for (i = 0; i < 16; i++) z[i] = 0;
344
+ for (i = 0; i < 8; i++) z[i] = n[i];
345
+ while (b >= 64) {
346
+ crypto_core_salsa20(x, z, k, sigma);
347
+ for (i = 0; i < 64; i++) c[cpos + i] = m[mpos + i] ^ x[i];
348
+ u = 1;
349
+ for (i = 8; i < 16; i++) {
350
+ u = u + (z[i] & 255) | 0;
351
+ z[i] = u & 255;
352
+ u >>>= 8;
353
+ }
354
+ b -= 64;
355
+ cpos += 64;
356
+ mpos += 64;
357
+ }
358
+ if (b > 0) {
359
+ crypto_core_salsa20(x, z, k, sigma);
360
+ for (i = 0; i < b; i++) c[cpos + i] = m[mpos + i] ^ x[i];
361
+ }
362
+ return 0;
363
+ }
364
+ function crypto_stream_salsa20(c, cpos, b, n, k) {
365
+ var z = new Uint8Array(16), x = new Uint8Array(64);
366
+ var u, i;
367
+ for (i = 0; i < 16; i++) z[i] = 0;
368
+ for (i = 0; i < 8; i++) z[i] = n[i];
369
+ while (b >= 64) {
370
+ crypto_core_salsa20(x, z, k, sigma);
371
+ for (i = 0; i < 64; i++) c[cpos + i] = x[i];
372
+ u = 1;
373
+ for (i = 8; i < 16; i++) {
374
+ u = u + (z[i] & 255) | 0;
375
+ z[i] = u & 255;
376
+ u >>>= 8;
377
+ }
378
+ b -= 64;
379
+ cpos += 64;
380
+ }
381
+ if (b > 0) {
382
+ crypto_core_salsa20(x, z, k, sigma);
383
+ for (i = 0; i < b; i++) c[cpos + i] = x[i];
384
+ }
385
+ return 0;
386
+ }
387
+ function crypto_stream(c, cpos, d, n, k) {
388
+ var s = new Uint8Array(32);
389
+ crypto_core_hsalsa20(s, n, k, sigma);
390
+ var sn = new Uint8Array(8);
391
+ for (var i = 0; i < 8; i++) sn[i] = n[i + 16];
392
+ return crypto_stream_salsa20(c, cpos, d, sn, s);
393
+ }
394
+ function crypto_stream_xor(c, cpos, m, mpos, d, n, k) {
395
+ var s = new Uint8Array(32);
396
+ crypto_core_hsalsa20(s, n, k, sigma);
397
+ var sn = new Uint8Array(8);
398
+ for (var i = 0; i < 8; i++) sn[i] = n[i + 16];
399
+ return crypto_stream_salsa20_xor(c, cpos, m, mpos, d, sn, s);
400
+ }
401
+ var poly1305 = function(key) {
402
+ this.buffer = new Uint8Array(16);
403
+ this.r = new Uint16Array(10);
404
+ this.h = new Uint16Array(10);
405
+ this.pad = new Uint16Array(8);
406
+ this.leftover = 0;
407
+ this.fin = 0;
408
+ var t0, t1, t2, t3, t4, t5, t6, t7;
409
+ t0 = key[0] & 255 | (key[1] & 255) << 8;
410
+ this.r[0] = t0 & 8191;
411
+ t1 = key[2] & 255 | (key[3] & 255) << 8;
412
+ this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
413
+ t2 = key[4] & 255 | (key[5] & 255) << 8;
414
+ this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
415
+ t3 = key[6] & 255 | (key[7] & 255) << 8;
416
+ this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
417
+ t4 = key[8] & 255 | (key[9] & 255) << 8;
418
+ this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
419
+ this.r[5] = t4 >>> 1 & 8190;
420
+ t5 = key[10] & 255 | (key[11] & 255) << 8;
421
+ this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
422
+ t6 = key[12] & 255 | (key[13] & 255) << 8;
423
+ this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
424
+ t7 = key[14] & 255 | (key[15] & 255) << 8;
425
+ this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
426
+ this.r[9] = t7 >>> 5 & 127;
427
+ this.pad[0] = key[16] & 255 | (key[17] & 255) << 8;
428
+ this.pad[1] = key[18] & 255 | (key[19] & 255) << 8;
429
+ this.pad[2] = key[20] & 255 | (key[21] & 255) << 8;
430
+ this.pad[3] = key[22] & 255 | (key[23] & 255) << 8;
431
+ this.pad[4] = key[24] & 255 | (key[25] & 255) << 8;
432
+ this.pad[5] = key[26] & 255 | (key[27] & 255) << 8;
433
+ this.pad[6] = key[28] & 255 | (key[29] & 255) << 8;
434
+ this.pad[7] = key[30] & 255 | (key[31] & 255) << 8;
435
+ };
436
+ poly1305.prototype.blocks = function(m, mpos, bytes) {
437
+ var hibit = this.fin ? 0 : 1 << 11;
438
+ var t0, t1, t2, t3, t4, t5, t6, t7, c;
439
+ var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
440
+ var h0 = this.h[0], h1 = this.h[1], h2 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9];
441
+ var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9];
442
+ while (bytes >= 16) {
443
+ t0 = m[mpos + 0] & 255 | (m[mpos + 1] & 255) << 8;
444
+ h0 += t0 & 8191;
445
+ t1 = m[mpos + 2] & 255 | (m[mpos + 3] & 255) << 8;
446
+ h1 += (t0 >>> 13 | t1 << 3) & 8191;
447
+ t2 = m[mpos + 4] & 255 | (m[mpos + 5] & 255) << 8;
448
+ h2 += (t1 >>> 10 | t2 << 6) & 8191;
449
+ t3 = m[mpos + 6] & 255 | (m[mpos + 7] & 255) << 8;
450
+ h3 += (t2 >>> 7 | t3 << 9) & 8191;
451
+ t4 = m[mpos + 8] & 255 | (m[mpos + 9] & 255) << 8;
452
+ h4 += (t3 >>> 4 | t4 << 12) & 8191;
453
+ h5 += t4 >>> 1 & 8191;
454
+ t5 = m[mpos + 10] & 255 | (m[mpos + 11] & 255) << 8;
455
+ h6 += (t4 >>> 14 | t5 << 2) & 8191;
456
+ t6 = m[mpos + 12] & 255 | (m[mpos + 13] & 255) << 8;
457
+ h7 += (t5 >>> 11 | t6 << 5) & 8191;
458
+ t7 = m[mpos + 14] & 255 | (m[mpos + 15] & 255) << 8;
459
+ h8 += (t6 >>> 8 | t7 << 8) & 8191;
460
+ h9 += t7 >>> 5 | hibit;
461
+ c = 0;
462
+ d0 = c;
463
+ d0 += h0 * r0;
464
+ d0 += h1 * (5 * r9);
465
+ d0 += h2 * (5 * r8);
466
+ d0 += h3 * (5 * r7);
467
+ d0 += h4 * (5 * r6);
468
+ c = d0 >>> 13;
469
+ d0 &= 8191;
470
+ d0 += h5 * (5 * r5);
471
+ d0 += h6 * (5 * r4);
472
+ d0 += h7 * (5 * r3);
473
+ d0 += h8 * (5 * r2);
474
+ d0 += h9 * (5 * r1);
475
+ c += d0 >>> 13;
476
+ d0 &= 8191;
477
+ d1 = c;
478
+ d1 += h0 * r1;
479
+ d1 += h1 * r0;
480
+ d1 += h2 * (5 * r9);
481
+ d1 += h3 * (5 * r8);
482
+ d1 += h4 * (5 * r7);
483
+ c = d1 >>> 13;
484
+ d1 &= 8191;
485
+ d1 += h5 * (5 * r6);
486
+ d1 += h6 * (5 * r5);
487
+ d1 += h7 * (5 * r4);
488
+ d1 += h8 * (5 * r3);
489
+ d1 += h9 * (5 * r2);
490
+ c += d1 >>> 13;
491
+ d1 &= 8191;
492
+ d2 = c;
493
+ d2 += h0 * r2;
494
+ d2 += h1 * r1;
495
+ d2 += h2 * r0;
496
+ d2 += h3 * (5 * r9);
497
+ d2 += h4 * (5 * r8);
498
+ c = d2 >>> 13;
499
+ d2 &= 8191;
500
+ d2 += h5 * (5 * r7);
501
+ d2 += h6 * (5 * r6);
502
+ d2 += h7 * (5 * r5);
503
+ d2 += h8 * (5 * r4);
504
+ d2 += h9 * (5 * r3);
505
+ c += d2 >>> 13;
506
+ d2 &= 8191;
507
+ d3 = c;
508
+ d3 += h0 * r3;
509
+ d3 += h1 * r2;
510
+ d3 += h2 * r1;
511
+ d3 += h3 * r0;
512
+ d3 += h4 * (5 * r9);
513
+ c = d3 >>> 13;
514
+ d3 &= 8191;
515
+ d3 += h5 * (5 * r8);
516
+ d3 += h6 * (5 * r7);
517
+ d3 += h7 * (5 * r6);
518
+ d3 += h8 * (5 * r5);
519
+ d3 += h9 * (5 * r4);
520
+ c += d3 >>> 13;
521
+ d3 &= 8191;
522
+ d4 = c;
523
+ d4 += h0 * r4;
524
+ d4 += h1 * r3;
525
+ d4 += h2 * r2;
526
+ d4 += h3 * r1;
527
+ d4 += h4 * r0;
528
+ c = d4 >>> 13;
529
+ d4 &= 8191;
530
+ d4 += h5 * (5 * r9);
531
+ d4 += h6 * (5 * r8);
532
+ d4 += h7 * (5 * r7);
533
+ d4 += h8 * (5 * r6);
534
+ d4 += h9 * (5 * r5);
535
+ c += d4 >>> 13;
536
+ d4 &= 8191;
537
+ d5 = c;
538
+ d5 += h0 * r5;
539
+ d5 += h1 * r4;
540
+ d5 += h2 * r3;
541
+ d5 += h3 * r2;
542
+ d5 += h4 * r1;
543
+ c = d5 >>> 13;
544
+ d5 &= 8191;
545
+ d5 += h5 * r0;
546
+ d5 += h6 * (5 * r9);
547
+ d5 += h7 * (5 * r8);
548
+ d5 += h8 * (5 * r7);
549
+ d5 += h9 * (5 * r6);
550
+ c += d5 >>> 13;
551
+ d5 &= 8191;
552
+ d6 = c;
553
+ d6 += h0 * r6;
554
+ d6 += h1 * r5;
555
+ d6 += h2 * r4;
556
+ d6 += h3 * r3;
557
+ d6 += h4 * r2;
558
+ c = d6 >>> 13;
559
+ d6 &= 8191;
560
+ d6 += h5 * r1;
561
+ d6 += h6 * r0;
562
+ d6 += h7 * (5 * r9);
563
+ d6 += h8 * (5 * r8);
564
+ d6 += h9 * (5 * r7);
565
+ c += d6 >>> 13;
566
+ d6 &= 8191;
567
+ d7 = c;
568
+ d7 += h0 * r7;
569
+ d7 += h1 * r6;
570
+ d7 += h2 * r5;
571
+ d7 += h3 * r4;
572
+ d7 += h4 * r3;
573
+ c = d7 >>> 13;
574
+ d7 &= 8191;
575
+ d7 += h5 * r2;
576
+ d7 += h6 * r1;
577
+ d7 += h7 * r0;
578
+ d7 += h8 * (5 * r9);
579
+ d7 += h9 * (5 * r8);
580
+ c += d7 >>> 13;
581
+ d7 &= 8191;
582
+ d8 = c;
583
+ d8 += h0 * r8;
584
+ d8 += h1 * r7;
585
+ d8 += h2 * r6;
586
+ d8 += h3 * r5;
587
+ d8 += h4 * r4;
588
+ c = d8 >>> 13;
589
+ d8 &= 8191;
590
+ d8 += h5 * r3;
591
+ d8 += h6 * r2;
592
+ d8 += h7 * r1;
593
+ d8 += h8 * r0;
594
+ d8 += h9 * (5 * r9);
595
+ c += d8 >>> 13;
596
+ d8 &= 8191;
597
+ d9 = c;
598
+ d9 += h0 * r9;
599
+ d9 += h1 * r8;
600
+ d9 += h2 * r7;
601
+ d9 += h3 * r6;
602
+ d9 += h4 * r5;
603
+ c = d9 >>> 13;
604
+ d9 &= 8191;
605
+ d9 += h5 * r4;
606
+ d9 += h6 * r3;
607
+ d9 += h7 * r2;
608
+ d9 += h8 * r1;
609
+ d9 += h9 * r0;
610
+ c += d9 >>> 13;
611
+ d9 &= 8191;
612
+ c = (c << 2) + c | 0;
613
+ c = c + d0 | 0;
614
+ d0 = c & 8191;
615
+ c = c >>> 13;
616
+ d1 += c;
617
+ h0 = d0;
618
+ h1 = d1;
619
+ h2 = d2;
620
+ h3 = d3;
621
+ h4 = d4;
622
+ h5 = d5;
623
+ h6 = d6;
624
+ h7 = d7;
625
+ h8 = d8;
626
+ h9 = d9;
627
+ mpos += 16;
628
+ bytes -= 16;
629
+ }
630
+ this.h[0] = h0;
631
+ this.h[1] = h1;
632
+ this.h[2] = h2;
633
+ this.h[3] = h3;
634
+ this.h[4] = h4;
635
+ this.h[5] = h5;
636
+ this.h[6] = h6;
637
+ this.h[7] = h7;
638
+ this.h[8] = h8;
639
+ this.h[9] = h9;
640
+ };
641
+ poly1305.prototype.finish = function(mac, macpos) {
642
+ var g = new Uint16Array(10);
643
+ var c, mask, f, i;
644
+ if (this.leftover) {
645
+ i = this.leftover;
646
+ this.buffer[i++] = 1;
647
+ for (; i < 16; i++) this.buffer[i] = 0;
648
+ this.fin = 1;
649
+ this.blocks(this.buffer, 0, 16);
650
+ }
651
+ c = this.h[1] >>> 13;
652
+ this.h[1] &= 8191;
653
+ for (i = 2; i < 10; i++) {
654
+ this.h[i] += c;
655
+ c = this.h[i] >>> 13;
656
+ this.h[i] &= 8191;
657
+ }
658
+ this.h[0] += c * 5;
659
+ c = this.h[0] >>> 13;
660
+ this.h[0] &= 8191;
661
+ this.h[1] += c;
662
+ c = this.h[1] >>> 13;
663
+ this.h[1] &= 8191;
664
+ this.h[2] += c;
665
+ g[0] = this.h[0] + 5;
666
+ c = g[0] >>> 13;
667
+ g[0] &= 8191;
668
+ for (i = 1; i < 10; i++) {
669
+ g[i] = this.h[i] + c;
670
+ c = g[i] >>> 13;
671
+ g[i] &= 8191;
672
+ }
673
+ g[9] -= 1 << 13;
674
+ mask = (c ^ 1) - 1;
675
+ for (i = 0; i < 10; i++) g[i] &= mask;
676
+ mask = ~mask;
677
+ for (i = 0; i < 10; i++) this.h[i] = this.h[i] & mask | g[i];
678
+ this.h[0] = (this.h[0] | this.h[1] << 13) & 65535;
679
+ this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535;
680
+ this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535;
681
+ this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 65535;
682
+ this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 65535;
683
+ this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 65535;
684
+ this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 65535;
685
+ this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 65535;
686
+ f = this.h[0] + this.pad[0];
687
+ this.h[0] = f & 65535;
688
+ for (i = 1; i < 8; i++) {
689
+ f = (this.h[i] + this.pad[i] | 0) + (f >>> 16) | 0;
690
+ this.h[i] = f & 65535;
691
+ }
692
+ mac[macpos + 0] = this.h[0] >>> 0 & 255;
693
+ mac[macpos + 1] = this.h[0] >>> 8 & 255;
694
+ mac[macpos + 2] = this.h[1] >>> 0 & 255;
695
+ mac[macpos + 3] = this.h[1] >>> 8 & 255;
696
+ mac[macpos + 4] = this.h[2] >>> 0 & 255;
697
+ mac[macpos + 5] = this.h[2] >>> 8 & 255;
698
+ mac[macpos + 6] = this.h[3] >>> 0 & 255;
699
+ mac[macpos + 7] = this.h[3] >>> 8 & 255;
700
+ mac[macpos + 8] = this.h[4] >>> 0 & 255;
701
+ mac[macpos + 9] = this.h[4] >>> 8 & 255;
702
+ mac[macpos + 10] = this.h[5] >>> 0 & 255;
703
+ mac[macpos + 11] = this.h[5] >>> 8 & 255;
704
+ mac[macpos + 12] = this.h[6] >>> 0 & 255;
705
+ mac[macpos + 13] = this.h[6] >>> 8 & 255;
706
+ mac[macpos + 14] = this.h[7] >>> 0 & 255;
707
+ mac[macpos + 15] = this.h[7] >>> 8 & 255;
708
+ };
709
+ poly1305.prototype.update = function(m, mpos, bytes) {
710
+ var i, want;
711
+ if (this.leftover) {
712
+ want = 16 - this.leftover;
713
+ if (want > bytes)
714
+ want = bytes;
715
+ for (i = 0; i < want; i++)
716
+ this.buffer[this.leftover + i] = m[mpos + i];
717
+ bytes -= want;
718
+ mpos += want;
719
+ this.leftover += want;
720
+ if (this.leftover < 16)
721
+ return;
722
+ this.blocks(this.buffer, 0, 16);
723
+ this.leftover = 0;
724
+ }
725
+ if (bytes >= 16) {
726
+ want = bytes - bytes % 16;
727
+ this.blocks(m, mpos, want);
728
+ mpos += want;
729
+ bytes -= want;
730
+ }
731
+ if (bytes) {
732
+ for (i = 0; i < bytes; i++)
733
+ this.buffer[this.leftover + i] = m[mpos + i];
734
+ this.leftover += bytes;
735
+ }
736
+ };
737
+ function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
738
+ var s = new poly1305(k);
739
+ s.update(m, mpos, n);
740
+ s.finish(out, outpos);
741
+ return 0;
742
+ }
743
+ function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
744
+ var x = new Uint8Array(16);
745
+ crypto_onetimeauth(x, 0, m, mpos, n, k);
746
+ return crypto_verify_16(h, hpos, x, 0);
747
+ }
748
+ function crypto_secretbox(c, m, d, n, k) {
749
+ var i;
750
+ if (d < 32) return -1;
751
+ crypto_stream_xor(c, 0, m, 0, d, n, k);
752
+ crypto_onetimeauth(c, 16, c, 32, d - 32, c);
753
+ for (i = 0; i < 16; i++) c[i] = 0;
754
+ return 0;
755
+ }
756
+ function crypto_secretbox_open(m, c, d, n, k) {
757
+ var i;
758
+ var x = new Uint8Array(32);
759
+ if (d < 32) return -1;
760
+ crypto_stream(x, 0, 32, n, k);
761
+ if (crypto_onetimeauth_verify(c, 16, c, 32, d - 32, x) !== 0) return -1;
762
+ crypto_stream_xor(m, 0, c, 0, d, n, k);
763
+ for (i = 0; i < 32; i++) m[i] = 0;
764
+ return 0;
765
+ }
766
+ function set25519(r, a) {
767
+ var i;
768
+ for (i = 0; i < 16; i++) r[i] = a[i] | 0;
769
+ }
770
+ function car25519(o) {
771
+ var i, v, c = 1;
772
+ for (i = 0; i < 16; i++) {
773
+ v = o[i] + c + 65535;
774
+ c = Math.floor(v / 65536);
775
+ o[i] = v - c * 65536;
776
+ }
777
+ o[0] += c - 1 + 37 * (c - 1);
778
+ }
779
+ function sel25519(p, q, b) {
780
+ var t, c = ~(b - 1);
781
+ for (var i = 0; i < 16; i++) {
782
+ t = c & (p[i] ^ q[i]);
783
+ p[i] ^= t;
784
+ q[i] ^= t;
785
+ }
786
+ }
787
+ function pack25519(o, n) {
788
+ var i, j, b;
789
+ var m = gf(), t = gf();
790
+ for (i = 0; i < 16; i++) t[i] = n[i];
791
+ car25519(t);
792
+ car25519(t);
793
+ car25519(t);
794
+ for (j = 0; j < 2; j++) {
795
+ m[0] = t[0] - 65517;
796
+ for (i = 1; i < 15; i++) {
797
+ m[i] = t[i] - 65535 - (m[i - 1] >> 16 & 1);
798
+ m[i - 1] &= 65535;
799
+ }
800
+ m[15] = t[15] - 32767 - (m[14] >> 16 & 1);
801
+ b = m[15] >> 16 & 1;
802
+ m[14] &= 65535;
803
+ sel25519(t, m, 1 - b);
804
+ }
805
+ for (i = 0; i < 16; i++) {
806
+ o[2 * i] = t[i] & 255;
807
+ o[2 * i + 1] = t[i] >> 8;
808
+ }
809
+ }
810
+ function neq25519(a, b) {
811
+ var c = new Uint8Array(32), d = new Uint8Array(32);
812
+ pack25519(c, a);
813
+ pack25519(d, b);
814
+ return crypto_verify_32(c, 0, d, 0);
815
+ }
816
+ function par25519(a) {
817
+ var d = new Uint8Array(32);
818
+ pack25519(d, a);
819
+ return d[0] & 1;
820
+ }
821
+ function unpack25519(o, n) {
822
+ var i;
823
+ for (i = 0; i < 16; i++) o[i] = n[2 * i] + (n[2 * i + 1] << 8);
824
+ o[15] &= 32767;
825
+ }
826
+ function A(o, a, b) {
827
+ for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
828
+ }
829
+ function Z(o, a, b) {
830
+ for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
831
+ }
832
+ function M(o, a, b) {
833
+ var v, c, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11], b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
834
+ v = a[0];
835
+ t0 += v * b0;
836
+ t1 += v * b1;
837
+ t2 += v * b2;
838
+ t3 += v * b3;
839
+ t4 += v * b4;
840
+ t5 += v * b5;
841
+ t6 += v * b6;
842
+ t7 += v * b7;
843
+ t8 += v * b8;
844
+ t9 += v * b9;
845
+ t10 += v * b10;
846
+ t11 += v * b11;
847
+ t12 += v * b12;
848
+ t13 += v * b13;
849
+ t14 += v * b14;
850
+ t15 += v * b15;
851
+ v = a[1];
852
+ t1 += v * b0;
853
+ t2 += v * b1;
854
+ t3 += v * b2;
855
+ t4 += v * b3;
856
+ t5 += v * b4;
857
+ t6 += v * b5;
858
+ t7 += v * b6;
859
+ t8 += v * b7;
860
+ t9 += v * b8;
861
+ t10 += v * b9;
862
+ t11 += v * b10;
863
+ t12 += v * b11;
864
+ t13 += v * b12;
865
+ t14 += v * b13;
866
+ t15 += v * b14;
867
+ t16 += v * b15;
868
+ v = a[2];
869
+ t2 += v * b0;
870
+ t3 += v * b1;
871
+ t4 += v * b2;
872
+ t5 += v * b3;
873
+ t6 += v * b4;
874
+ t7 += v * b5;
875
+ t8 += v * b6;
876
+ t9 += v * b7;
877
+ t10 += v * b8;
878
+ t11 += v * b9;
879
+ t12 += v * b10;
880
+ t13 += v * b11;
881
+ t14 += v * b12;
882
+ t15 += v * b13;
883
+ t16 += v * b14;
884
+ t17 += v * b15;
885
+ v = a[3];
886
+ t3 += v * b0;
887
+ t4 += v * b1;
888
+ t5 += v * b2;
889
+ t6 += v * b3;
890
+ t7 += v * b4;
891
+ t8 += v * b5;
892
+ t9 += v * b6;
893
+ t10 += v * b7;
894
+ t11 += v * b8;
895
+ t12 += v * b9;
896
+ t13 += v * b10;
897
+ t14 += v * b11;
898
+ t15 += v * b12;
899
+ t16 += v * b13;
900
+ t17 += v * b14;
901
+ t18 += v * b15;
902
+ v = a[4];
903
+ t4 += v * b0;
904
+ t5 += v * b1;
905
+ t6 += v * b2;
906
+ t7 += v * b3;
907
+ t8 += v * b4;
908
+ t9 += v * b5;
909
+ t10 += v * b6;
910
+ t11 += v * b7;
911
+ t12 += v * b8;
912
+ t13 += v * b9;
913
+ t14 += v * b10;
914
+ t15 += v * b11;
915
+ t16 += v * b12;
916
+ t17 += v * b13;
917
+ t18 += v * b14;
918
+ t19 += v * b15;
919
+ v = a[5];
920
+ t5 += v * b0;
921
+ t6 += v * b1;
922
+ t7 += v * b2;
923
+ t8 += v * b3;
924
+ t9 += v * b4;
925
+ t10 += v * b5;
926
+ t11 += v * b6;
927
+ t12 += v * b7;
928
+ t13 += v * b8;
929
+ t14 += v * b9;
930
+ t15 += v * b10;
931
+ t16 += v * b11;
932
+ t17 += v * b12;
933
+ t18 += v * b13;
934
+ t19 += v * b14;
935
+ t20 += v * b15;
936
+ v = a[6];
937
+ t6 += v * b0;
938
+ t7 += v * b1;
939
+ t8 += v * b2;
940
+ t9 += v * b3;
941
+ t10 += v * b4;
942
+ t11 += v * b5;
943
+ t12 += v * b6;
944
+ t13 += v * b7;
945
+ t14 += v * b8;
946
+ t15 += v * b9;
947
+ t16 += v * b10;
948
+ t17 += v * b11;
949
+ t18 += v * b12;
950
+ t19 += v * b13;
951
+ t20 += v * b14;
952
+ t21 += v * b15;
953
+ v = a[7];
954
+ t7 += v * b0;
955
+ t8 += v * b1;
956
+ t9 += v * b2;
957
+ t10 += v * b3;
958
+ t11 += v * b4;
959
+ t12 += v * b5;
960
+ t13 += v * b6;
961
+ t14 += v * b7;
962
+ t15 += v * b8;
963
+ t16 += v * b9;
964
+ t17 += v * b10;
965
+ t18 += v * b11;
966
+ t19 += v * b12;
967
+ t20 += v * b13;
968
+ t21 += v * b14;
969
+ t22 += v * b15;
970
+ v = a[8];
971
+ t8 += v * b0;
972
+ t9 += v * b1;
973
+ t10 += v * b2;
974
+ t11 += v * b3;
975
+ t12 += v * b4;
976
+ t13 += v * b5;
977
+ t14 += v * b6;
978
+ t15 += v * b7;
979
+ t16 += v * b8;
980
+ t17 += v * b9;
981
+ t18 += v * b10;
982
+ t19 += v * b11;
983
+ t20 += v * b12;
984
+ t21 += v * b13;
985
+ t22 += v * b14;
986
+ t23 += v * b15;
987
+ v = a[9];
988
+ t9 += v * b0;
989
+ t10 += v * b1;
990
+ t11 += v * b2;
991
+ t12 += v * b3;
992
+ t13 += v * b4;
993
+ t14 += v * b5;
994
+ t15 += v * b6;
995
+ t16 += v * b7;
996
+ t17 += v * b8;
997
+ t18 += v * b9;
998
+ t19 += v * b10;
999
+ t20 += v * b11;
1000
+ t21 += v * b12;
1001
+ t22 += v * b13;
1002
+ t23 += v * b14;
1003
+ t24 += v * b15;
1004
+ v = a[10];
1005
+ t10 += v * b0;
1006
+ t11 += v * b1;
1007
+ t12 += v * b2;
1008
+ t13 += v * b3;
1009
+ t14 += v * b4;
1010
+ t15 += v * b5;
1011
+ t16 += v * b6;
1012
+ t17 += v * b7;
1013
+ t18 += v * b8;
1014
+ t19 += v * b9;
1015
+ t20 += v * b10;
1016
+ t21 += v * b11;
1017
+ t22 += v * b12;
1018
+ t23 += v * b13;
1019
+ t24 += v * b14;
1020
+ t25 += v * b15;
1021
+ v = a[11];
1022
+ t11 += v * b0;
1023
+ t12 += v * b1;
1024
+ t13 += v * b2;
1025
+ t14 += v * b3;
1026
+ t15 += v * b4;
1027
+ t16 += v * b5;
1028
+ t17 += v * b6;
1029
+ t18 += v * b7;
1030
+ t19 += v * b8;
1031
+ t20 += v * b9;
1032
+ t21 += v * b10;
1033
+ t22 += v * b11;
1034
+ t23 += v * b12;
1035
+ t24 += v * b13;
1036
+ t25 += v * b14;
1037
+ t26 += v * b15;
1038
+ v = a[12];
1039
+ t12 += v * b0;
1040
+ t13 += v * b1;
1041
+ t14 += v * b2;
1042
+ t15 += v * b3;
1043
+ t16 += v * b4;
1044
+ t17 += v * b5;
1045
+ t18 += v * b6;
1046
+ t19 += v * b7;
1047
+ t20 += v * b8;
1048
+ t21 += v * b9;
1049
+ t22 += v * b10;
1050
+ t23 += v * b11;
1051
+ t24 += v * b12;
1052
+ t25 += v * b13;
1053
+ t26 += v * b14;
1054
+ t27 += v * b15;
1055
+ v = a[13];
1056
+ t13 += v * b0;
1057
+ t14 += v * b1;
1058
+ t15 += v * b2;
1059
+ t16 += v * b3;
1060
+ t17 += v * b4;
1061
+ t18 += v * b5;
1062
+ t19 += v * b6;
1063
+ t20 += v * b7;
1064
+ t21 += v * b8;
1065
+ t22 += v * b9;
1066
+ t23 += v * b10;
1067
+ t24 += v * b11;
1068
+ t25 += v * b12;
1069
+ t26 += v * b13;
1070
+ t27 += v * b14;
1071
+ t28 += v * b15;
1072
+ v = a[14];
1073
+ t14 += v * b0;
1074
+ t15 += v * b1;
1075
+ t16 += v * b2;
1076
+ t17 += v * b3;
1077
+ t18 += v * b4;
1078
+ t19 += v * b5;
1079
+ t20 += v * b6;
1080
+ t21 += v * b7;
1081
+ t22 += v * b8;
1082
+ t23 += v * b9;
1083
+ t24 += v * b10;
1084
+ t25 += v * b11;
1085
+ t26 += v * b12;
1086
+ t27 += v * b13;
1087
+ t28 += v * b14;
1088
+ t29 += v * b15;
1089
+ v = a[15];
1090
+ t15 += v * b0;
1091
+ t16 += v * b1;
1092
+ t17 += v * b2;
1093
+ t18 += v * b3;
1094
+ t19 += v * b4;
1095
+ t20 += v * b5;
1096
+ t21 += v * b6;
1097
+ t22 += v * b7;
1098
+ t23 += v * b8;
1099
+ t24 += v * b9;
1100
+ t25 += v * b10;
1101
+ t26 += v * b11;
1102
+ t27 += v * b12;
1103
+ t28 += v * b13;
1104
+ t29 += v * b14;
1105
+ t30 += v * b15;
1106
+ t0 += 38 * t16;
1107
+ t1 += 38 * t17;
1108
+ t2 += 38 * t18;
1109
+ t3 += 38 * t19;
1110
+ t4 += 38 * t20;
1111
+ t5 += 38 * t21;
1112
+ t6 += 38 * t22;
1113
+ t7 += 38 * t23;
1114
+ t8 += 38 * t24;
1115
+ t9 += 38 * t25;
1116
+ t10 += 38 * t26;
1117
+ t11 += 38 * t27;
1118
+ t12 += 38 * t28;
1119
+ t13 += 38 * t29;
1120
+ t14 += 38 * t30;
1121
+ c = 1;
1122
+ v = t0 + c + 65535;
1123
+ c = Math.floor(v / 65536);
1124
+ t0 = v - c * 65536;
1125
+ v = t1 + c + 65535;
1126
+ c = Math.floor(v / 65536);
1127
+ t1 = v - c * 65536;
1128
+ v = t2 + c + 65535;
1129
+ c = Math.floor(v / 65536);
1130
+ t2 = v - c * 65536;
1131
+ v = t3 + c + 65535;
1132
+ c = Math.floor(v / 65536);
1133
+ t3 = v - c * 65536;
1134
+ v = t4 + c + 65535;
1135
+ c = Math.floor(v / 65536);
1136
+ t4 = v - c * 65536;
1137
+ v = t5 + c + 65535;
1138
+ c = Math.floor(v / 65536);
1139
+ t5 = v - c * 65536;
1140
+ v = t6 + c + 65535;
1141
+ c = Math.floor(v / 65536);
1142
+ t6 = v - c * 65536;
1143
+ v = t7 + c + 65535;
1144
+ c = Math.floor(v / 65536);
1145
+ t7 = v - c * 65536;
1146
+ v = t8 + c + 65535;
1147
+ c = Math.floor(v / 65536);
1148
+ t8 = v - c * 65536;
1149
+ v = t9 + c + 65535;
1150
+ c = Math.floor(v / 65536);
1151
+ t9 = v - c * 65536;
1152
+ v = t10 + c + 65535;
1153
+ c = Math.floor(v / 65536);
1154
+ t10 = v - c * 65536;
1155
+ v = t11 + c + 65535;
1156
+ c = Math.floor(v / 65536);
1157
+ t11 = v - c * 65536;
1158
+ v = t12 + c + 65535;
1159
+ c = Math.floor(v / 65536);
1160
+ t12 = v - c * 65536;
1161
+ v = t13 + c + 65535;
1162
+ c = Math.floor(v / 65536);
1163
+ t13 = v - c * 65536;
1164
+ v = t14 + c + 65535;
1165
+ c = Math.floor(v / 65536);
1166
+ t14 = v - c * 65536;
1167
+ v = t15 + c + 65535;
1168
+ c = Math.floor(v / 65536);
1169
+ t15 = v - c * 65536;
1170
+ t0 += c - 1 + 37 * (c - 1);
1171
+ c = 1;
1172
+ v = t0 + c + 65535;
1173
+ c = Math.floor(v / 65536);
1174
+ t0 = v - c * 65536;
1175
+ v = t1 + c + 65535;
1176
+ c = Math.floor(v / 65536);
1177
+ t1 = v - c * 65536;
1178
+ v = t2 + c + 65535;
1179
+ c = Math.floor(v / 65536);
1180
+ t2 = v - c * 65536;
1181
+ v = t3 + c + 65535;
1182
+ c = Math.floor(v / 65536);
1183
+ t3 = v - c * 65536;
1184
+ v = t4 + c + 65535;
1185
+ c = Math.floor(v / 65536);
1186
+ t4 = v - c * 65536;
1187
+ v = t5 + c + 65535;
1188
+ c = Math.floor(v / 65536);
1189
+ t5 = v - c * 65536;
1190
+ v = t6 + c + 65535;
1191
+ c = Math.floor(v / 65536);
1192
+ t6 = v - c * 65536;
1193
+ v = t7 + c + 65535;
1194
+ c = Math.floor(v / 65536);
1195
+ t7 = v - c * 65536;
1196
+ v = t8 + c + 65535;
1197
+ c = Math.floor(v / 65536);
1198
+ t8 = v - c * 65536;
1199
+ v = t9 + c + 65535;
1200
+ c = Math.floor(v / 65536);
1201
+ t9 = v - c * 65536;
1202
+ v = t10 + c + 65535;
1203
+ c = Math.floor(v / 65536);
1204
+ t10 = v - c * 65536;
1205
+ v = t11 + c + 65535;
1206
+ c = Math.floor(v / 65536);
1207
+ t11 = v - c * 65536;
1208
+ v = t12 + c + 65535;
1209
+ c = Math.floor(v / 65536);
1210
+ t12 = v - c * 65536;
1211
+ v = t13 + c + 65535;
1212
+ c = Math.floor(v / 65536);
1213
+ t13 = v - c * 65536;
1214
+ v = t14 + c + 65535;
1215
+ c = Math.floor(v / 65536);
1216
+ t14 = v - c * 65536;
1217
+ v = t15 + c + 65535;
1218
+ c = Math.floor(v / 65536);
1219
+ t15 = v - c * 65536;
1220
+ t0 += c - 1 + 37 * (c - 1);
1221
+ o[0] = t0;
1222
+ o[1] = t1;
1223
+ o[2] = t2;
1224
+ o[3] = t3;
1225
+ o[4] = t4;
1226
+ o[5] = t5;
1227
+ o[6] = t6;
1228
+ o[7] = t7;
1229
+ o[8] = t8;
1230
+ o[9] = t9;
1231
+ o[10] = t10;
1232
+ o[11] = t11;
1233
+ o[12] = t12;
1234
+ o[13] = t13;
1235
+ o[14] = t14;
1236
+ o[15] = t15;
1237
+ }
1238
+ function S(o, a) {
1239
+ M(o, a, a);
1240
+ }
1241
+ function inv25519(o, i) {
1242
+ var c = gf();
1243
+ var a;
1244
+ for (a = 0; a < 16; a++) c[a] = i[a];
1245
+ for (a = 253; a >= 0; a--) {
1246
+ S(c, c);
1247
+ if (a !== 2 && a !== 4) M(c, c, i);
1248
+ }
1249
+ for (a = 0; a < 16; a++) o[a] = c[a];
1250
+ }
1251
+ function pow2523(o, i) {
1252
+ var c = gf();
1253
+ var a;
1254
+ for (a = 0; a < 16; a++) c[a] = i[a];
1255
+ for (a = 250; a >= 0; a--) {
1256
+ S(c, c);
1257
+ if (a !== 1) M(c, c, i);
1258
+ }
1259
+ for (a = 0; a < 16; a++) o[a] = c[a];
1260
+ }
1261
+ function crypto_scalarmult(q, n, p) {
1262
+ var z = new Uint8Array(32);
1263
+ var x = new Float64Array(80), r, i;
1264
+ var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf();
1265
+ for (i = 0; i < 31; i++) z[i] = n[i];
1266
+ z[31] = n[31] & 127 | 64;
1267
+ z[0] &= 248;
1268
+ unpack25519(x, p);
1269
+ for (i = 0; i < 16; i++) {
1270
+ b[i] = x[i];
1271
+ d[i] = a[i] = c[i] = 0;
1272
+ }
1273
+ a[0] = d[0] = 1;
1274
+ for (i = 254; i >= 0; --i) {
1275
+ r = z[i >>> 3] >>> (i & 7) & 1;
1276
+ sel25519(a, b, r);
1277
+ sel25519(c, d, r);
1278
+ A(e, a, c);
1279
+ Z(a, a, c);
1280
+ A(c, b, d);
1281
+ Z(b, b, d);
1282
+ S(d, e);
1283
+ S(f, a);
1284
+ M(a, c, a);
1285
+ M(c, b, e);
1286
+ A(e, a, c);
1287
+ Z(a, a, c);
1288
+ S(b, a);
1289
+ Z(c, d, f);
1290
+ M(a, c, _121665);
1291
+ A(a, a, d);
1292
+ M(c, c, a);
1293
+ M(a, d, f);
1294
+ M(d, b, x);
1295
+ S(b, e);
1296
+ sel25519(a, b, r);
1297
+ sel25519(c, d, r);
1298
+ }
1299
+ for (i = 0; i < 16; i++) {
1300
+ x[i + 16] = a[i];
1301
+ x[i + 32] = c[i];
1302
+ x[i + 48] = b[i];
1303
+ x[i + 64] = d[i];
1304
+ }
1305
+ var x32 = x.subarray(32);
1306
+ var x16 = x.subarray(16);
1307
+ inv25519(x32, x32);
1308
+ M(x16, x16, x32);
1309
+ pack25519(q, x16);
1310
+ return 0;
1311
+ }
1312
+ function crypto_scalarmult_base(q, n) {
1313
+ return crypto_scalarmult(q, n, _9);
1314
+ }
1315
+ function crypto_box_keypair(y, x) {
1316
+ randombytes(x, 32);
1317
+ return crypto_scalarmult_base(y, x);
1318
+ }
1319
+ function crypto_box_beforenm(k, y, x) {
1320
+ var s = new Uint8Array(32);
1321
+ crypto_scalarmult(s, x, y);
1322
+ return crypto_core_hsalsa20(k, _0, s, sigma);
1323
+ }
1324
+ var crypto_box_afternm = crypto_secretbox;
1325
+ var crypto_box_open_afternm = crypto_secretbox_open;
1326
+ function crypto_box(c, m, d, n, y, x) {
1327
+ var k = new Uint8Array(32);
1328
+ crypto_box_beforenm(k, y, x);
1329
+ return crypto_box_afternm(c, m, d, n, k);
1330
+ }
1331
+ function crypto_box_open(m, c, d, n, y, x) {
1332
+ var k = new Uint8Array(32);
1333
+ crypto_box_beforenm(k, y, x);
1334
+ return crypto_box_open_afternm(m, c, d, n, k);
1335
+ }
1336
+ var K = [
1337
+ 1116352408,
1338
+ 3609767458,
1339
+ 1899447441,
1340
+ 602891725,
1341
+ 3049323471,
1342
+ 3964484399,
1343
+ 3921009573,
1344
+ 2173295548,
1345
+ 961987163,
1346
+ 4081628472,
1347
+ 1508970993,
1348
+ 3053834265,
1349
+ 2453635748,
1350
+ 2937671579,
1351
+ 2870763221,
1352
+ 3664609560,
1353
+ 3624381080,
1354
+ 2734883394,
1355
+ 310598401,
1356
+ 1164996542,
1357
+ 607225278,
1358
+ 1323610764,
1359
+ 1426881987,
1360
+ 3590304994,
1361
+ 1925078388,
1362
+ 4068182383,
1363
+ 2162078206,
1364
+ 991336113,
1365
+ 2614888103,
1366
+ 633803317,
1367
+ 3248222580,
1368
+ 3479774868,
1369
+ 3835390401,
1370
+ 2666613458,
1371
+ 4022224774,
1372
+ 944711139,
1373
+ 264347078,
1374
+ 2341262773,
1375
+ 604807628,
1376
+ 2007800933,
1377
+ 770255983,
1378
+ 1495990901,
1379
+ 1249150122,
1380
+ 1856431235,
1381
+ 1555081692,
1382
+ 3175218132,
1383
+ 1996064986,
1384
+ 2198950837,
1385
+ 2554220882,
1386
+ 3999719339,
1387
+ 2821834349,
1388
+ 766784016,
1389
+ 2952996808,
1390
+ 2566594879,
1391
+ 3210313671,
1392
+ 3203337956,
1393
+ 3336571891,
1394
+ 1034457026,
1395
+ 3584528711,
1396
+ 2466948901,
1397
+ 113926993,
1398
+ 3758326383,
1399
+ 338241895,
1400
+ 168717936,
1401
+ 666307205,
1402
+ 1188179964,
1403
+ 773529912,
1404
+ 1546045734,
1405
+ 1294757372,
1406
+ 1522805485,
1407
+ 1396182291,
1408
+ 2643833823,
1409
+ 1695183700,
1410
+ 2343527390,
1411
+ 1986661051,
1412
+ 1014477480,
1413
+ 2177026350,
1414
+ 1206759142,
1415
+ 2456956037,
1416
+ 344077627,
1417
+ 2730485921,
1418
+ 1290863460,
1419
+ 2820302411,
1420
+ 3158454273,
1421
+ 3259730800,
1422
+ 3505952657,
1423
+ 3345764771,
1424
+ 106217008,
1425
+ 3516065817,
1426
+ 3606008344,
1427
+ 3600352804,
1428
+ 1432725776,
1429
+ 4094571909,
1430
+ 1467031594,
1431
+ 275423344,
1432
+ 851169720,
1433
+ 430227734,
1434
+ 3100823752,
1435
+ 506948616,
1436
+ 1363258195,
1437
+ 659060556,
1438
+ 3750685593,
1439
+ 883997877,
1440
+ 3785050280,
1441
+ 958139571,
1442
+ 3318307427,
1443
+ 1322822218,
1444
+ 3812723403,
1445
+ 1537002063,
1446
+ 2003034995,
1447
+ 1747873779,
1448
+ 3602036899,
1449
+ 1955562222,
1450
+ 1575990012,
1451
+ 2024104815,
1452
+ 1125592928,
1453
+ 2227730452,
1454
+ 2716904306,
1455
+ 2361852424,
1456
+ 442776044,
1457
+ 2428436474,
1458
+ 593698344,
1459
+ 2756734187,
1460
+ 3733110249,
1461
+ 3204031479,
1462
+ 2999351573,
1463
+ 3329325298,
1464
+ 3815920427,
1465
+ 3391569614,
1466
+ 3928383900,
1467
+ 3515267271,
1468
+ 566280711,
1469
+ 3940187606,
1470
+ 3454069534,
1471
+ 4118630271,
1472
+ 4000239992,
1473
+ 116418474,
1474
+ 1914138554,
1475
+ 174292421,
1476
+ 2731055270,
1477
+ 289380356,
1478
+ 3203993006,
1479
+ 460393269,
1480
+ 320620315,
1481
+ 685471733,
1482
+ 587496836,
1483
+ 852142971,
1484
+ 1086792851,
1485
+ 1017036298,
1486
+ 365543100,
1487
+ 1126000580,
1488
+ 2618297676,
1489
+ 1288033470,
1490
+ 3409855158,
1491
+ 1501505948,
1492
+ 4234509866,
1493
+ 1607167915,
1494
+ 987167468,
1495
+ 1816402316,
1496
+ 1246189591
1497
+ ];
1498
+ function crypto_hashblocks_hl(hh, hl, m, n) {
1499
+ var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h, l, a, b, c, d;
1500
+ var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7];
1501
+ var pos = 0;
1502
+ while (n >= 128) {
1503
+ for (i = 0; i < 16; i++) {
1504
+ j = 8 * i + pos;
1505
+ wh[i] = m[j + 0] << 24 | m[j + 1] << 16 | m[j + 2] << 8 | m[j + 3];
1506
+ wl[i] = m[j + 4] << 24 | m[j + 5] << 16 | m[j + 6] << 8 | m[j + 7];
1507
+ }
1508
+ for (i = 0; i < 80; i++) {
1509
+ bh0 = ah0;
1510
+ bh1 = ah1;
1511
+ bh2 = ah2;
1512
+ bh3 = ah3;
1513
+ bh4 = ah4;
1514
+ bh5 = ah5;
1515
+ bh6 = ah6;
1516
+ bh7 = ah7;
1517
+ bl0 = al0;
1518
+ bl1 = al1;
1519
+ bl2 = al2;
1520
+ bl3 = al3;
1521
+ bl4 = al4;
1522
+ bl5 = al5;
1523
+ bl6 = al6;
1524
+ bl7 = al7;
1525
+ h = ah7;
1526
+ l = al7;
1527
+ a = l & 65535;
1528
+ b = l >>> 16;
1529
+ c = h & 65535;
1530
+ d = h >>> 16;
1531
+ h = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32));
1532
+ l = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32));
1533
+ a += l & 65535;
1534
+ b += l >>> 16;
1535
+ c += h & 65535;
1536
+ d += h >>> 16;
1537
+ h = ah4 & ah5 ^ ~ah4 & ah6;
1538
+ l = al4 & al5 ^ ~al4 & al6;
1539
+ a += l & 65535;
1540
+ b += l >>> 16;
1541
+ c += h & 65535;
1542
+ d += h >>> 16;
1543
+ h = K[i * 2];
1544
+ l = K[i * 2 + 1];
1545
+ a += l & 65535;
1546
+ b += l >>> 16;
1547
+ c += h & 65535;
1548
+ d += h >>> 16;
1549
+ h = wh[i % 16];
1550
+ l = wl[i % 16];
1551
+ a += l & 65535;
1552
+ b += l >>> 16;
1553
+ c += h & 65535;
1554
+ d += h >>> 16;
1555
+ b += a >>> 16;
1556
+ c += b >>> 16;
1557
+ d += c >>> 16;
1558
+ th = c & 65535 | d << 16;
1559
+ tl = a & 65535 | b << 16;
1560
+ h = th;
1561
+ l = tl;
1562
+ a = l & 65535;
1563
+ b = l >>> 16;
1564
+ c = h & 65535;
1565
+ d = h >>> 16;
1566
+ h = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32));
1567
+ l = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32));
1568
+ a += l & 65535;
1569
+ b += l >>> 16;
1570
+ c += h & 65535;
1571
+ d += h >>> 16;
1572
+ h = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2;
1573
+ l = al0 & al1 ^ al0 & al2 ^ al1 & al2;
1574
+ a += l & 65535;
1575
+ b += l >>> 16;
1576
+ c += h & 65535;
1577
+ d += h >>> 16;
1578
+ b += a >>> 16;
1579
+ c += b >>> 16;
1580
+ d += c >>> 16;
1581
+ bh7 = c & 65535 | d << 16;
1582
+ bl7 = a & 65535 | b << 16;
1583
+ h = bh3;
1584
+ l = bl3;
1585
+ a = l & 65535;
1586
+ b = l >>> 16;
1587
+ c = h & 65535;
1588
+ d = h >>> 16;
1589
+ h = th;
1590
+ l = tl;
1591
+ a += l & 65535;
1592
+ b += l >>> 16;
1593
+ c += h & 65535;
1594
+ d += h >>> 16;
1595
+ b += a >>> 16;
1596
+ c += b >>> 16;
1597
+ d += c >>> 16;
1598
+ bh3 = c & 65535 | d << 16;
1599
+ bl3 = a & 65535 | b << 16;
1600
+ ah1 = bh0;
1601
+ ah2 = bh1;
1602
+ ah3 = bh2;
1603
+ ah4 = bh3;
1604
+ ah5 = bh4;
1605
+ ah6 = bh5;
1606
+ ah7 = bh6;
1607
+ ah0 = bh7;
1608
+ al1 = bl0;
1609
+ al2 = bl1;
1610
+ al3 = bl2;
1611
+ al4 = bl3;
1612
+ al5 = bl4;
1613
+ al6 = bl5;
1614
+ al7 = bl6;
1615
+ al0 = bl7;
1616
+ if (i % 16 === 15) {
1617
+ for (j = 0; j < 16; j++) {
1618
+ h = wh[j];
1619
+ l = wl[j];
1620
+ a = l & 65535;
1621
+ b = l >>> 16;
1622
+ c = h & 65535;
1623
+ d = h >>> 16;
1624
+ h = wh[(j + 9) % 16];
1625
+ l = wl[(j + 9) % 16];
1626
+ a += l & 65535;
1627
+ b += l >>> 16;
1628
+ c += h & 65535;
1629
+ d += h >>> 16;
1630
+ th = wh[(j + 1) % 16];
1631
+ tl = wl[(j + 1) % 16];
1632
+ h = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7;
1633
+ l = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7);
1634
+ a += l & 65535;
1635
+ b += l >>> 16;
1636
+ c += h & 65535;
1637
+ d += h >>> 16;
1638
+ th = wh[(j + 14) % 16];
1639
+ tl = wl[(j + 14) % 16];
1640
+ h = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6;
1641
+ l = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6);
1642
+ a += l & 65535;
1643
+ b += l >>> 16;
1644
+ c += h & 65535;
1645
+ d += h >>> 16;
1646
+ b += a >>> 16;
1647
+ c += b >>> 16;
1648
+ d += c >>> 16;
1649
+ wh[j] = c & 65535 | d << 16;
1650
+ wl[j] = a & 65535 | b << 16;
1651
+ }
1652
+ }
1653
+ }
1654
+ h = ah0;
1655
+ l = al0;
1656
+ a = l & 65535;
1657
+ b = l >>> 16;
1658
+ c = h & 65535;
1659
+ d = h >>> 16;
1660
+ h = hh[0];
1661
+ l = hl[0];
1662
+ a += l & 65535;
1663
+ b += l >>> 16;
1664
+ c += h & 65535;
1665
+ d += h >>> 16;
1666
+ b += a >>> 16;
1667
+ c += b >>> 16;
1668
+ d += c >>> 16;
1669
+ hh[0] = ah0 = c & 65535 | d << 16;
1670
+ hl[0] = al0 = a & 65535 | b << 16;
1671
+ h = ah1;
1672
+ l = al1;
1673
+ a = l & 65535;
1674
+ b = l >>> 16;
1675
+ c = h & 65535;
1676
+ d = h >>> 16;
1677
+ h = hh[1];
1678
+ l = hl[1];
1679
+ a += l & 65535;
1680
+ b += l >>> 16;
1681
+ c += h & 65535;
1682
+ d += h >>> 16;
1683
+ b += a >>> 16;
1684
+ c += b >>> 16;
1685
+ d += c >>> 16;
1686
+ hh[1] = ah1 = c & 65535 | d << 16;
1687
+ hl[1] = al1 = a & 65535 | b << 16;
1688
+ h = ah2;
1689
+ l = al2;
1690
+ a = l & 65535;
1691
+ b = l >>> 16;
1692
+ c = h & 65535;
1693
+ d = h >>> 16;
1694
+ h = hh[2];
1695
+ l = hl[2];
1696
+ a += l & 65535;
1697
+ b += l >>> 16;
1698
+ c += h & 65535;
1699
+ d += h >>> 16;
1700
+ b += a >>> 16;
1701
+ c += b >>> 16;
1702
+ d += c >>> 16;
1703
+ hh[2] = ah2 = c & 65535 | d << 16;
1704
+ hl[2] = al2 = a & 65535 | b << 16;
1705
+ h = ah3;
1706
+ l = al3;
1707
+ a = l & 65535;
1708
+ b = l >>> 16;
1709
+ c = h & 65535;
1710
+ d = h >>> 16;
1711
+ h = hh[3];
1712
+ l = hl[3];
1713
+ a += l & 65535;
1714
+ b += l >>> 16;
1715
+ c += h & 65535;
1716
+ d += h >>> 16;
1717
+ b += a >>> 16;
1718
+ c += b >>> 16;
1719
+ d += c >>> 16;
1720
+ hh[3] = ah3 = c & 65535 | d << 16;
1721
+ hl[3] = al3 = a & 65535 | b << 16;
1722
+ h = ah4;
1723
+ l = al4;
1724
+ a = l & 65535;
1725
+ b = l >>> 16;
1726
+ c = h & 65535;
1727
+ d = h >>> 16;
1728
+ h = hh[4];
1729
+ l = hl[4];
1730
+ a += l & 65535;
1731
+ b += l >>> 16;
1732
+ c += h & 65535;
1733
+ d += h >>> 16;
1734
+ b += a >>> 16;
1735
+ c += b >>> 16;
1736
+ d += c >>> 16;
1737
+ hh[4] = ah4 = c & 65535 | d << 16;
1738
+ hl[4] = al4 = a & 65535 | b << 16;
1739
+ h = ah5;
1740
+ l = al5;
1741
+ a = l & 65535;
1742
+ b = l >>> 16;
1743
+ c = h & 65535;
1744
+ d = h >>> 16;
1745
+ h = hh[5];
1746
+ l = hl[5];
1747
+ a += l & 65535;
1748
+ b += l >>> 16;
1749
+ c += h & 65535;
1750
+ d += h >>> 16;
1751
+ b += a >>> 16;
1752
+ c += b >>> 16;
1753
+ d += c >>> 16;
1754
+ hh[5] = ah5 = c & 65535 | d << 16;
1755
+ hl[5] = al5 = a & 65535 | b << 16;
1756
+ h = ah6;
1757
+ l = al6;
1758
+ a = l & 65535;
1759
+ b = l >>> 16;
1760
+ c = h & 65535;
1761
+ d = h >>> 16;
1762
+ h = hh[6];
1763
+ l = hl[6];
1764
+ a += l & 65535;
1765
+ b += l >>> 16;
1766
+ c += h & 65535;
1767
+ d += h >>> 16;
1768
+ b += a >>> 16;
1769
+ c += b >>> 16;
1770
+ d += c >>> 16;
1771
+ hh[6] = ah6 = c & 65535 | d << 16;
1772
+ hl[6] = al6 = a & 65535 | b << 16;
1773
+ h = ah7;
1774
+ l = al7;
1775
+ a = l & 65535;
1776
+ b = l >>> 16;
1777
+ c = h & 65535;
1778
+ d = h >>> 16;
1779
+ h = hh[7];
1780
+ l = hl[7];
1781
+ a += l & 65535;
1782
+ b += l >>> 16;
1783
+ c += h & 65535;
1784
+ d += h >>> 16;
1785
+ b += a >>> 16;
1786
+ c += b >>> 16;
1787
+ d += c >>> 16;
1788
+ hh[7] = ah7 = c & 65535 | d << 16;
1789
+ hl[7] = al7 = a & 65535 | b << 16;
1790
+ pos += 128;
1791
+ n -= 128;
1792
+ }
1793
+ return n;
1794
+ }
1795
+ function crypto_hash(out, m, n) {
1796
+ var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b = n;
1797
+ hh[0] = 1779033703;
1798
+ hh[1] = 3144134277;
1799
+ hh[2] = 1013904242;
1800
+ hh[3] = 2773480762;
1801
+ hh[4] = 1359893119;
1802
+ hh[5] = 2600822924;
1803
+ hh[6] = 528734635;
1804
+ hh[7] = 1541459225;
1805
+ hl[0] = 4089235720;
1806
+ hl[1] = 2227873595;
1807
+ hl[2] = 4271175723;
1808
+ hl[3] = 1595750129;
1809
+ hl[4] = 2917565137;
1810
+ hl[5] = 725511199;
1811
+ hl[6] = 4215389547;
1812
+ hl[7] = 327033209;
1813
+ crypto_hashblocks_hl(hh, hl, m, n);
1814
+ n %= 128;
1815
+ for (i = 0; i < n; i++) x[i] = m[b - n + i];
1816
+ x[n] = 128;
1817
+ n = 256 - 128 * (n < 112 ? 1 : 0);
1818
+ x[n - 9] = 0;
1819
+ ts64(x, n - 8, b / 536870912 | 0, b << 3);
1820
+ crypto_hashblocks_hl(hh, hl, x, n);
1821
+ for (i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]);
1822
+ return 0;
1823
+ }
1824
+ function add(p, q) {
1825
+ var a = gf(), b = gf(), c = gf(), d = gf(), e = gf(), f = gf(), g = gf(), h = gf(), t = gf();
1826
+ Z(a, p[1], p[0]);
1827
+ Z(t, q[1], q[0]);
1828
+ M(a, a, t);
1829
+ A(b, p[0], p[1]);
1830
+ A(t, q[0], q[1]);
1831
+ M(b, b, t);
1832
+ M(c, p[3], q[3]);
1833
+ M(c, c, D2);
1834
+ M(d, p[2], q[2]);
1835
+ A(d, d, d);
1836
+ Z(e, b, a);
1837
+ Z(f, d, c);
1838
+ A(g, d, c);
1839
+ A(h, b, a);
1840
+ M(p[0], e, f);
1841
+ M(p[1], h, g);
1842
+ M(p[2], g, f);
1843
+ M(p[3], e, h);
1844
+ }
1845
+ function cswap(p, q, b) {
1846
+ var i;
1847
+ for (i = 0; i < 4; i++) {
1848
+ sel25519(p[i], q[i], b);
1849
+ }
1850
+ }
1851
+ function pack(r, p) {
1852
+ var tx = gf(), ty = gf(), zi = gf();
1853
+ inv25519(zi, p[2]);
1854
+ M(tx, p[0], zi);
1855
+ M(ty, p[1], zi);
1856
+ pack25519(r, ty);
1857
+ r[31] ^= par25519(tx) << 7;
1858
+ }
1859
+ function scalarmult(p, q, s) {
1860
+ var b, i;
1861
+ set25519(p[0], gf0);
1862
+ set25519(p[1], gf1);
1863
+ set25519(p[2], gf1);
1864
+ set25519(p[3], gf0);
1865
+ for (i = 255; i >= 0; --i) {
1866
+ b = s[i / 8 | 0] >> (i & 7) & 1;
1867
+ cswap(p, q, b);
1868
+ add(q, p);
1869
+ add(p, p);
1870
+ cswap(p, q, b);
1871
+ }
1872
+ }
1873
+ function scalarbase(p, s) {
1874
+ var q = [gf(), gf(), gf(), gf()];
1875
+ set25519(q[0], X);
1876
+ set25519(q[1], Y);
1877
+ set25519(q[2], gf1);
1878
+ M(q[3], X, Y);
1879
+ scalarmult(p, q, s);
1880
+ }
1881
+ function crypto_sign_keypair(pk, sk, seeded) {
1882
+ var d = new Uint8Array(64);
1883
+ var p = [gf(), gf(), gf(), gf()];
1884
+ var i;
1885
+ if (!seeded) randombytes(sk, 32);
1886
+ crypto_hash(d, sk, 32);
1887
+ d[0] &= 248;
1888
+ d[31] &= 127;
1889
+ d[31] |= 64;
1890
+ scalarbase(p, d);
1891
+ pack(pk, p);
1892
+ for (i = 0; i < 32; i++) sk[i + 32] = pk[i];
1893
+ return 0;
1894
+ }
1895
+ var L = new Float64Array([237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]);
1896
+ function modL(r, x) {
1897
+ var carry, i, j, k;
1898
+ for (i = 63; i >= 32; --i) {
1899
+ carry = 0;
1900
+ for (j = i - 32, k = i - 12; j < k; ++j) {
1901
+ x[j] += carry - 16 * x[i] * L[j - (i - 32)];
1902
+ carry = Math.floor((x[j] + 128) / 256);
1903
+ x[j] -= carry * 256;
1904
+ }
1905
+ x[j] += carry;
1906
+ x[i] = 0;
1907
+ }
1908
+ carry = 0;
1909
+ for (j = 0; j < 32; j++) {
1910
+ x[j] += carry - (x[31] >> 4) * L[j];
1911
+ carry = x[j] >> 8;
1912
+ x[j] &= 255;
1913
+ }
1914
+ for (j = 0; j < 32; j++) x[j] -= carry * L[j];
1915
+ for (i = 0; i < 32; i++) {
1916
+ x[i + 1] += x[i] >> 8;
1917
+ r[i] = x[i] & 255;
1918
+ }
1919
+ }
1920
+ function reduce(r) {
1921
+ var x = new Float64Array(64), i;
1922
+ for (i = 0; i < 64; i++) x[i] = r[i];
1923
+ for (i = 0; i < 64; i++) r[i] = 0;
1924
+ modL(r, x);
1925
+ }
1926
+ function crypto_sign(sm, m, n, sk) {
1927
+ var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
1928
+ var i, j, x = new Float64Array(64);
1929
+ var p = [gf(), gf(), gf(), gf()];
1930
+ crypto_hash(d, sk, 32);
1931
+ d[0] &= 248;
1932
+ d[31] &= 127;
1933
+ d[31] |= 64;
1934
+ var smlen = n + 64;
1935
+ for (i = 0; i < n; i++) sm[64 + i] = m[i];
1936
+ for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
1937
+ crypto_hash(r, sm.subarray(32), n + 32);
1938
+ reduce(r);
1939
+ scalarbase(p, r);
1940
+ pack(sm, p);
1941
+ for (i = 32; i < 64; i++) sm[i] = sk[i];
1942
+ crypto_hash(h, sm, n + 64);
1943
+ reduce(h);
1944
+ for (i = 0; i < 64; i++) x[i] = 0;
1945
+ for (i = 0; i < 32; i++) x[i] = r[i];
1946
+ for (i = 0; i < 32; i++) {
1947
+ for (j = 0; j < 32; j++) {
1948
+ x[i + j] += h[i] * d[j];
1949
+ }
1950
+ }
1951
+ modL(sm.subarray(32), x);
1952
+ return smlen;
1953
+ }
1954
+ function unpackneg(r, p) {
1955
+ var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf();
1956
+ set25519(r[2], gf1);
1957
+ unpack25519(r[1], p);
1958
+ S(num, r[1]);
1959
+ M(den, num, D);
1960
+ Z(num, num, r[2]);
1961
+ A(den, r[2], den);
1962
+ S(den2, den);
1963
+ S(den4, den2);
1964
+ M(den6, den4, den2);
1965
+ M(t, den6, num);
1966
+ M(t, t, den);
1967
+ pow2523(t, t);
1968
+ M(t, t, num);
1969
+ M(t, t, den);
1970
+ M(t, t, den);
1971
+ M(r[0], t, den);
1972
+ S(chk, r[0]);
1973
+ M(chk, chk, den);
1974
+ if (neq25519(chk, num)) M(r[0], r[0], I);
1975
+ S(chk, r[0]);
1976
+ M(chk, chk, den);
1977
+ if (neq25519(chk, num)) return -1;
1978
+ if (par25519(r[0]) === p[31] >> 7) Z(r[0], gf0, r[0]);
1979
+ M(r[3], r[0], r[1]);
1980
+ return 0;
1981
+ }
1982
+ function crypto_sign_open(m, sm, n, pk) {
1983
+ var i;
1984
+ var t = new Uint8Array(32), h = new Uint8Array(64);
1985
+ var p = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()];
1986
+ if (n < 64) return -1;
1987
+ if (unpackneg(q, pk)) return -1;
1988
+ for (i = 0; i < n; i++) m[i] = sm[i];
1989
+ for (i = 0; i < 32; i++) m[i + 32] = pk[i];
1990
+ crypto_hash(h, m, n);
1991
+ reduce(h);
1992
+ scalarmult(p, q, h);
1993
+ scalarbase(q, sm.subarray(32));
1994
+ add(p, q);
1995
+ pack(t, p);
1996
+ n -= 64;
1997
+ if (crypto_verify_32(sm, 0, t, 0)) {
1998
+ for (i = 0; i < n; i++) m[i] = 0;
1999
+ return -1;
2000
+ }
2001
+ for (i = 0; i < n; i++) m[i] = sm[i + 64];
2002
+ return n;
2003
+ }
2004
+ var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64;
2005
+ nacl.lowlevel = {
2006
+ crypto_core_hsalsa20,
2007
+ crypto_stream_xor,
2008
+ crypto_stream,
2009
+ crypto_stream_salsa20_xor,
2010
+ crypto_stream_salsa20,
2011
+ crypto_onetimeauth,
2012
+ crypto_onetimeauth_verify,
2013
+ crypto_verify_16,
2014
+ crypto_verify_32,
2015
+ crypto_secretbox,
2016
+ crypto_secretbox_open,
2017
+ crypto_scalarmult,
2018
+ crypto_scalarmult_base,
2019
+ crypto_box_beforenm,
2020
+ crypto_box_afternm,
2021
+ crypto_box,
2022
+ crypto_box_open,
2023
+ crypto_box_keypair,
2024
+ crypto_hash,
2025
+ crypto_sign,
2026
+ crypto_sign_keypair,
2027
+ crypto_sign_open,
2028
+ crypto_secretbox_KEYBYTES,
2029
+ crypto_secretbox_NONCEBYTES,
2030
+ crypto_secretbox_ZEROBYTES,
2031
+ crypto_secretbox_BOXZEROBYTES,
2032
+ crypto_scalarmult_BYTES,
2033
+ crypto_scalarmult_SCALARBYTES,
2034
+ crypto_box_PUBLICKEYBYTES,
2035
+ crypto_box_SECRETKEYBYTES,
2036
+ crypto_box_BEFORENMBYTES,
2037
+ crypto_box_NONCEBYTES,
2038
+ crypto_box_ZEROBYTES,
2039
+ crypto_box_BOXZEROBYTES,
2040
+ crypto_sign_BYTES,
2041
+ crypto_sign_PUBLICKEYBYTES,
2042
+ crypto_sign_SECRETKEYBYTES,
2043
+ crypto_sign_SEEDBYTES,
2044
+ crypto_hash_BYTES,
2045
+ gf,
2046
+ D,
2047
+ L,
2048
+ pack25519,
2049
+ unpack25519,
2050
+ M,
2051
+ A,
2052
+ S,
2053
+ Z,
2054
+ pow2523,
2055
+ add,
2056
+ set25519,
2057
+ modL,
2058
+ scalarmult,
2059
+ scalarbase
2060
+ };
2061
+ function checkLengths(k, n) {
2062
+ if (k.length !== crypto_secretbox_KEYBYTES) throw new Error("bad key size");
2063
+ if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error("bad nonce size");
2064
+ }
2065
+ function checkBoxLengths(pk, sk) {
2066
+ if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error("bad public key size");
2067
+ if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size");
2068
+ }
2069
+ function checkArrayTypes() {
2070
+ for (var i = 0; i < arguments.length; i++) {
2071
+ if (!(arguments[i] instanceof Uint8Array))
2072
+ throw new TypeError("unexpected type, use Uint8Array");
2073
+ }
2074
+ }
2075
+ function cleanup(arr) {
2076
+ for (var i = 0; i < arr.length; i++) arr[i] = 0;
2077
+ }
2078
+ nacl.randomBytes = function(n) {
2079
+ var b = new Uint8Array(n);
2080
+ randombytes(b, n);
2081
+ return b;
2082
+ };
2083
+ nacl.secretbox = function(msg, nonce, key) {
2084
+ checkArrayTypes(msg, nonce, key);
2085
+ checkLengths(key, nonce);
2086
+ var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
2087
+ var c = new Uint8Array(m.length);
2088
+ for (var i = 0; i < msg.length; i++) m[i + crypto_secretbox_ZEROBYTES] = msg[i];
2089
+ crypto_secretbox(c, m, m.length, nonce, key);
2090
+ return c.subarray(crypto_secretbox_BOXZEROBYTES);
2091
+ };
2092
+ nacl.secretbox.open = function(box, nonce, key) {
2093
+ checkArrayTypes(box, nonce, key);
2094
+ checkLengths(key, nonce);
2095
+ var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
2096
+ var m = new Uint8Array(c.length);
2097
+ for (var i = 0; i < box.length; i++) c[i + crypto_secretbox_BOXZEROBYTES] = box[i];
2098
+ if (c.length < 32) return null;
2099
+ if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return null;
2100
+ return m.subarray(crypto_secretbox_ZEROBYTES);
2101
+ };
2102
+ nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
2103
+ nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
2104
+ nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
2105
+ nacl.scalarMult = function(n, p) {
2106
+ checkArrayTypes(n, p);
2107
+ if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size");
2108
+ if (p.length !== crypto_scalarmult_BYTES) throw new Error("bad p size");
2109
+ var q = new Uint8Array(crypto_scalarmult_BYTES);
2110
+ crypto_scalarmult(q, n, p);
2111
+ return q;
2112
+ };
2113
+ nacl.scalarMult.base = function(n) {
2114
+ checkArrayTypes(n);
2115
+ if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size");
2116
+ var q = new Uint8Array(crypto_scalarmult_BYTES);
2117
+ crypto_scalarmult_base(q, n);
2118
+ return q;
2119
+ };
2120
+ nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
2121
+ nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
2122
+ nacl.box = function(msg, nonce, publicKey, secretKey) {
2123
+ var k = nacl.box.before(publicKey, secretKey);
2124
+ return nacl.secretbox(msg, nonce, k);
2125
+ };
2126
+ nacl.box.before = function(publicKey, secretKey) {
2127
+ checkArrayTypes(publicKey, secretKey);
2128
+ checkBoxLengths(publicKey, secretKey);
2129
+ var k = new Uint8Array(crypto_box_BEFORENMBYTES);
2130
+ crypto_box_beforenm(k, publicKey, secretKey);
2131
+ return k;
2132
+ };
2133
+ nacl.box.after = nacl.secretbox;
2134
+ nacl.box.open = function(msg, nonce, publicKey, secretKey) {
2135
+ var k = nacl.box.before(publicKey, secretKey);
2136
+ return nacl.secretbox.open(msg, nonce, k);
2137
+ };
2138
+ nacl.box.open.after = nacl.secretbox.open;
2139
+ nacl.box.keyPair = function() {
2140
+ var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
2141
+ var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
2142
+ crypto_box_keypair(pk, sk);
2143
+ return { publicKey: pk, secretKey: sk };
2144
+ };
2145
+ nacl.box.keyPair.fromSecretKey = function(secretKey) {
2146
+ checkArrayTypes(secretKey);
2147
+ if (secretKey.length !== crypto_box_SECRETKEYBYTES)
2148
+ throw new Error("bad secret key size");
2149
+ var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
2150
+ crypto_scalarmult_base(pk, secretKey);
2151
+ return { publicKey: pk, secretKey: new Uint8Array(secretKey) };
2152
+ };
2153
+ nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
2154
+ nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
2155
+ nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
2156
+ nacl.box.nonceLength = crypto_box_NONCEBYTES;
2157
+ nacl.box.overheadLength = nacl.secretbox.overheadLength;
2158
+ nacl.sign = function(msg, secretKey) {
2159
+ checkArrayTypes(msg, secretKey);
2160
+ if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
2161
+ throw new Error("bad secret key size");
2162
+ var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length);
2163
+ crypto_sign(signedMsg, msg, msg.length, secretKey);
2164
+ return signedMsg;
2165
+ };
2166
+ nacl.sign.open = function(signedMsg, publicKey) {
2167
+ checkArrayTypes(signedMsg, publicKey);
2168
+ if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
2169
+ throw new Error("bad public key size");
2170
+ var tmp = new Uint8Array(signedMsg.length);
2171
+ var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
2172
+ if (mlen < 0) return null;
2173
+ var m = new Uint8Array(mlen);
2174
+ for (var i = 0; i < m.length; i++) m[i] = tmp[i];
2175
+ return m;
2176
+ };
2177
+ nacl.sign.detached = function(msg, secretKey) {
2178
+ var signedMsg = nacl.sign(msg, secretKey);
2179
+ var sig = new Uint8Array(crypto_sign_BYTES);
2180
+ for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
2181
+ return sig;
2182
+ };
2183
+ nacl.sign.detached.verify = function(msg, sig, publicKey) {
2184
+ checkArrayTypes(msg, sig, publicKey);
2185
+ if (sig.length !== crypto_sign_BYTES)
2186
+ throw new Error("bad signature size");
2187
+ if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
2188
+ throw new Error("bad public key size");
2189
+ var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
2190
+ var m = new Uint8Array(crypto_sign_BYTES + msg.length);
2191
+ var i;
2192
+ for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
2193
+ for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i];
2194
+ return crypto_sign_open(m, sm, sm.length, publicKey) >= 0;
2195
+ };
2196
+ nacl.sign.keyPair = function() {
2197
+ var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
2198
+ var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
2199
+ crypto_sign_keypair(pk, sk);
2200
+ return { publicKey: pk, secretKey: sk };
2201
+ };
2202
+ nacl.sign.keyPair.fromSecretKey = function(secretKey) {
2203
+ checkArrayTypes(secretKey);
2204
+ if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
2205
+ throw new Error("bad secret key size");
2206
+ var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
2207
+ for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i];
2208
+ return { publicKey: pk, secretKey: new Uint8Array(secretKey) };
2209
+ };
2210
+ nacl.sign.keyPair.fromSeed = function(seed) {
2211
+ checkArrayTypes(seed);
2212
+ if (seed.length !== crypto_sign_SEEDBYTES)
2213
+ throw new Error("bad seed size");
2214
+ var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
2215
+ var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
2216
+ for (var i = 0; i < 32; i++) sk[i] = seed[i];
2217
+ crypto_sign_keypair(pk, sk, true);
2218
+ return { publicKey: pk, secretKey: sk };
2219
+ };
2220
+ nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
2221
+ nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
2222
+ nacl.sign.seedLength = crypto_sign_SEEDBYTES;
2223
+ nacl.sign.signatureLength = crypto_sign_BYTES;
2224
+ nacl.hash = function(msg) {
2225
+ checkArrayTypes(msg);
2226
+ var h = new Uint8Array(crypto_hash_BYTES);
2227
+ crypto_hash(h, msg, msg.length);
2228
+ return h;
2229
+ };
2230
+ nacl.hash.hashLength = crypto_hash_BYTES;
2231
+ nacl.verify = function(x, y) {
2232
+ checkArrayTypes(x, y);
2233
+ if (x.length === 0 || y.length === 0) return false;
2234
+ if (x.length !== y.length) return false;
2235
+ return vn(x, 0, y, 0, x.length) === 0 ? true : false;
2236
+ };
2237
+ nacl.setPRNG = function(fn) {
2238
+ randombytes = fn;
2239
+ };
2240
+ (function() {
2241
+ var crypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null;
2242
+ if (crypto && crypto.getRandomValues) {
2243
+ var QUOTA = 65536;
2244
+ nacl.setPRNG(function(x, n) {
2245
+ var i, v = new Uint8Array(n);
2246
+ for (i = 0; i < n; i += QUOTA) {
2247
+ crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
2248
+ }
2249
+ for (i = 0; i < n; i++) x[i] = v[i];
2250
+ cleanup(v);
2251
+ });
2252
+ } else if (typeof require !== "undefined") {
2253
+ crypto = require("crypto");
2254
+ if (crypto && crypto.randomBytes) {
2255
+ nacl.setPRNG(function(x, n) {
2256
+ var i, v = crypto.randomBytes(n);
2257
+ for (i = 0; i < n; i++) x[i] = v[i];
2258
+ cleanup(v);
2259
+ });
2260
+ }
2261
+ }
2262
+ })();
2263
+ })(typeof module2 !== "undefined" && module2.exports ? module2.exports : self.nacl = self.nacl || {});
2264
+ }
2265
+ });
2266
+
2267
+ // node_modules/tweetnacl-util/nacl-util.js
2268
+ var require_nacl_util = __commonJS({
2269
+ "node_modules/tweetnacl-util/nacl-util.js"(exports2, module2) {
2270
+ (function(root, f) {
2271
+ "use strict";
2272
+ if (typeof module2 !== "undefined" && module2.exports) module2.exports = f();
2273
+ else if (root.nacl) root.nacl.util = f();
2274
+ else {
2275
+ root.nacl = {};
2276
+ root.nacl.util = f();
2277
+ }
2278
+ })(exports2, function() {
2279
+ "use strict";
2280
+ var util = {};
2281
+ function validateBase64(s) {
2282
+ if (!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(s)) {
2283
+ throw new TypeError("invalid encoding");
2284
+ }
2285
+ }
2286
+ util.decodeUTF8 = function(s) {
2287
+ if (typeof s !== "string") throw new TypeError("expected string");
2288
+ var i, d = unescape(encodeURIComponent(s)), b = new Uint8Array(d.length);
2289
+ for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
2290
+ return b;
2291
+ };
2292
+ util.encodeUTF8 = function(arr) {
2293
+ var i, s = [];
2294
+ for (i = 0; i < arr.length; i++) s.push(String.fromCharCode(arr[i]));
2295
+ return decodeURIComponent(escape(s.join("")));
2296
+ };
2297
+ if (typeof atob === "undefined") {
2298
+ if (typeof Buffer.from !== "undefined") {
2299
+ util.encodeBase64 = function(arr) {
2300
+ return Buffer.from(arr).toString("base64");
2301
+ };
2302
+ util.decodeBase64 = function(s) {
2303
+ validateBase64(s);
2304
+ return new Uint8Array(Array.prototype.slice.call(Buffer.from(s, "base64"), 0));
2305
+ };
2306
+ } else {
2307
+ util.encodeBase64 = function(arr) {
2308
+ return new Buffer(arr).toString("base64");
2309
+ };
2310
+ util.decodeBase64 = function(s) {
2311
+ validateBase64(s);
2312
+ return new Uint8Array(Array.prototype.slice.call(new Buffer(s, "base64"), 0));
2313
+ };
2314
+ }
2315
+ } else {
2316
+ util.encodeBase64 = function(arr) {
2317
+ var i, s = [], len = arr.length;
2318
+ for (i = 0; i < len; i++) s.push(String.fromCharCode(arr[i]));
2319
+ return btoa(s.join(""));
2320
+ };
2321
+ util.decodeBase64 = function(s) {
2322
+ validateBase64(s);
2323
+ var i, d = atob(s), b = new Uint8Array(d.length);
2324
+ for (i = 0; i < d.length; i++) b[i] = d.charCodeAt(i);
2325
+ return b;
2326
+ };
2327
+ }
2328
+ return util;
2329
+ });
2330
+ }
2331
+ });
2332
+
2333
+ // src/security/sloth-vdf.js
2334
+ var require_sloth_vdf = __commonJS({
2335
+ "src/security/sloth-vdf.js"(exports2, module2) {
2336
+ var SlothPermutation2 = class _SlothPermutation {
2337
+ static p = BigInt(
2338
+ "170082004324204494273811327264862981553264701145937538369570764779791492622392118654022654452947093285873855529044371650895045691292912712699015605832276411308653107069798639938826015099738961427172366594187783204437869906954750443653318078358839409699824714551430573905637228307966826784684174483831608534979"
2339
+ );
2340
+ fastPow(base, exponent, modulus) {
2341
+ if (modulus === BigInt(1)) {
2342
+ return BigInt(0);
2343
+ }
2344
+ let result = BigInt(1);
2345
+ let powBase = base % modulus;
2346
+ let powExponent = exponent;
2347
+ while (powExponent > 0) {
2348
+ if (powExponent % BigInt(2) === BigInt(1)) {
2349
+ result = result * powBase % modulus;
2350
+ }
2351
+ powExponent = powExponent / BigInt(2);
2352
+ powBase = powBase * powBase % modulus;
2353
+ }
2354
+ return result;
2355
+ }
2356
+ quadRes(x) {
2357
+ return this.fastPow(x, (_SlothPermutation.p - BigInt(1)) / BigInt(2), _SlothPermutation.p) === BigInt(1);
2358
+ }
2359
+ modSqrtOp(x) {
2360
+ let y;
2361
+ let value = x;
2362
+ if (this.quadRes(value)) {
2363
+ y = this.fastPow(value, (_SlothPermutation.p + BigInt(1)) / BigInt(4), _SlothPermutation.p);
2364
+ } else {
2365
+ value = (-value + _SlothPermutation.p) % _SlothPermutation.p;
2366
+ y = this.fastPow(value, (_SlothPermutation.p + BigInt(1)) / BigInt(4), _SlothPermutation.p);
2367
+ }
2368
+ return y;
2369
+ }
2370
+ modOp(x, t) {
2371
+ let value = x % _SlothPermutation.p;
2372
+ for (let i = BigInt(0); i < t; i += BigInt(1)) {
2373
+ value = this.modSqrtOp(value);
2374
+ }
2375
+ return value;
2376
+ }
2377
+ modVerif(y, x, t) {
2378
+ const input = x % _SlothPermutation.p;
2379
+ let value = y;
2380
+ for (let i = BigInt(0); i < t; i += BigInt(1)) {
2381
+ value = value ** BigInt(2) % _SlothPermutation.p;
2382
+ }
2383
+ if (!this.quadRes(value)) {
2384
+ value = (-value + _SlothPermutation.p) % _SlothPermutation.p;
2385
+ }
2386
+ return input === value || (-input + _SlothPermutation.p) % _SlothPermutation.p === value;
2387
+ }
2388
+ generateProofVDF(t, x) {
2389
+ return this.modOp(x, t);
2390
+ }
2391
+ verifyProofVDF(t, x, y) {
2392
+ return this.modVerif(y, x, t);
2393
+ }
2394
+ };
2395
+ module2.exports = SlothPermutation2;
2396
+ }
2397
+ });
2398
+
2399
+ // src/security/vdf.js
2400
+ var require_vdf = __commonJS({
2401
+ "src/security/vdf.js"(exports2, module2) {
2402
+ var SlothPermutation2 = require_sloth_vdf();
2403
+ var VDF2 = class {
2404
+ static async compute(challengeHex, steps) {
2405
+ const vdfInstance = new SlothPermutation2();
2406
+ const challengeBigInt = BigInt(`0x${challengeHex}`);
2407
+ const result = vdfInstance.generateProofVDF(steps, challengeBigInt);
2408
+ return result.toString(16);
2409
+ }
2410
+ static async verify(challengeHex, steps, resultHex) {
2411
+ const vdfInstance = new SlothPermutation2();
2412
+ const challengeBigInt = BigInt(`0x${challengeHex}`);
2413
+ const resultBigInt = BigInt(`0x${resultHex}`);
2414
+ return vdfInstance.verifyProofVDF(steps, challengeBigInt, resultBigInt);
2415
+ }
2416
+ };
2417
+ module2.exports = VDF2;
2418
+ }
2419
+ });
2420
+
2421
+ // src/security/message-security-service.js
2422
+ var require_message_security_service = __commonJS({
2423
+ "src/security/message-security-service.js"(exports2, module2) {
2424
+ var nacl = require_nacl_fast();
2425
+ var naclUtil = require_nacl_util();
2426
+ var VDF2 = require_vdf();
2427
+ var DEFAULT_SECURITY_OPTIONS2 = {
2428
+ enabled: true,
2429
+ signingEnabled: true,
2430
+ encryptionEnabled: true,
2431
+ powEnabled: true,
2432
+ powTargetMs: 1e3,
2433
+ appPassword: "change-this-app-password",
2434
+ broadcastPasswords: {},
2435
+ resolveBroadcastPassword: null,
2436
+ powSteps: 22,
2437
+ trustedPeerKeys: {}
2438
+ };
2439
+ function stableStringify(value) {
2440
+ if (value === null || typeof value !== "object") {
2441
+ return JSON.stringify(value);
2442
+ }
2443
+ if (Array.isArray(value)) {
2444
+ return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
2445
+ }
2446
+ const keys = Object.keys(value).sort();
2447
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(",")}}`;
2448
+ }
2449
+ function concatBytes(a, b) {
2450
+ const result = new Uint8Array(a.length + b.length);
2451
+ result.set(a, 0);
2452
+ result.set(b, a.length);
2453
+ return result;
2454
+ }
2455
+ function hash32(bytes) {
2456
+ return nacl.hash(bytes).slice(0, 32);
2457
+ }
2458
+ function bytesToHex(bytes) {
2459
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
2460
+ }
2461
+ function utf8ToBytes(value) {
2462
+ return naclUtil.decodeUTF8(value);
2463
+ }
2464
+ function normalizePeerPublicKey(publicKey) {
2465
+ if (!publicKey || typeof publicKey !== "object") {
2466
+ throw new Error("Public key must be an object with signingPublicKey and encryptionPublicKey");
2467
+ }
2468
+ if (!publicKey.signingPublicKey || !publicKey.encryptionPublicKey) {
2469
+ throw new Error("Public key object is missing signingPublicKey or encryptionPublicKey");
2470
+ }
2471
+ return {
2472
+ signingPublicKey: publicKey.signingPublicKey,
2473
+ encryptionPublicKey: publicKey.encryptionPublicKey
2474
+ };
2475
+ }
2476
+ var MessageSecurityService2 = class {
2477
+ constructor({ nodeId, options = {}, now } = {}) {
2478
+ if (!nodeId) {
2479
+ throw new Error("MessageSecurityService requires nodeId");
2480
+ }
2481
+ this.nodeId = nodeId;
2482
+ this.options = {
2483
+ ...DEFAULT_SECURITY_OPTIONS2,
2484
+ ...options
2485
+ };
2486
+ this.now = now || (() => Date.now());
2487
+ const keyPair = options.keyPair || {
2488
+ signing: nacl.sign.keyPair(),
2489
+ encryption: nacl.box.keyPair()
2490
+ };
2491
+ this.signingSecretKey = keyPair.signing.secretKey;
2492
+ this.signingPublicKey = keyPair.signing.publicKey;
2493
+ this.encryptionSecretKey = keyPair.encryption.secretKey;
2494
+ this.encryptionPublicKey = keyPair.encryption.publicKey;
2495
+ this.publicKeyBundle = {
2496
+ signingPublicKey: naclUtil.encodeBase64(this.signingPublicKey),
2497
+ encryptionPublicKey: naclUtil.encodeBase64(this.encryptionPublicKey)
2498
+ };
2499
+ this.peerPublicKeys = /* @__PURE__ */ new Map();
2500
+ for (const [peerId, peerKey] of Object.entries(this.options.trustedPeerKeys || {})) {
2501
+ this.peerPublicKeys.set(peerId, normalizePeerPublicKey(peerKey));
2502
+ }
2503
+ this.calibratedPowSteps = this.options.powSteps;
2504
+ }
2505
+ getPublicKey() {
2506
+ return { ...this.publicKeyBundle };
2507
+ }
2508
+ registerPeerPublicKey(peerId, publicKey) {
2509
+ this.peerPublicKeys.set(peerId, normalizePeerPublicKey(publicKey));
2510
+ }
2511
+ resolvePeerPublicKey(peerId, fallbackPublicKey) {
2512
+ const trusted = this.peerPublicKeys.get(peerId);
2513
+ const fallback = fallbackPublicKey ? normalizePeerPublicKey(fallbackPublicKey) : null;
2514
+ if (trusted && fallback) {
2515
+ const mismatch = trusted.signingPublicKey !== fallback.signingPublicKey || trusted.encryptionPublicKey !== fallback.encryptionPublicKey;
2516
+ if (mismatch) {
2517
+ throw new Error(`Public key mismatch for peer ${peerId}`);
2518
+ }
2519
+ }
2520
+ return trusted || fallback || null;
2521
+ }
2522
+ buildEnvelopeBase({ messageType, payload, targetId = null }) {
2523
+ return {
2524
+ version: 1,
2525
+ senderId: this.nodeId,
2526
+ senderPublicKey: this.getPublicKey(),
2527
+ targetId,
2528
+ messageType,
2529
+ timestamp: this.now(),
2530
+ payload
2531
+ };
2532
+ }
2533
+ async secureOutgoingMessage({ messageType, payload, targetId = null, securityContext = {} }) {
2534
+ if (!this.options.enabled) {
2535
+ return this.buildEnvelopeBase({ messageType, payload, targetId });
2536
+ }
2537
+ const envelope = this.buildEnvelopeBase({ messageType, payload, targetId });
2538
+ const encryptionInfo = await this.encryptPayload({ payload, targetId, securityContext });
2539
+ envelope.payload = encryptionInfo.payload;
2540
+ envelope.security = {
2541
+ encryption: encryptionInfo.security,
2542
+ signing: { enabled: false },
2543
+ pow: { enabled: false }
2544
+ };
2545
+ if (this.options.powEnabled) {
2546
+ const pow = await this.generatePow(envelope);
2547
+ envelope.security.pow = {
2548
+ enabled: true,
2549
+ challenge: pow.challenge,
2550
+ proof: pow.proof,
2551
+ steps: pow.steps,
2552
+ durationMs: pow.durationMs
2553
+ };
2554
+ }
2555
+ if (this.options.signingEnabled) {
2556
+ const signatureBase = this.canonicalSigningInput(envelope);
2557
+ const signature = nacl.sign.detached(
2558
+ naclUtil.decodeUTF8(signatureBase),
2559
+ this.signingSecretKey
2560
+ );
2561
+ envelope.security.signing = {
2562
+ enabled: true,
2563
+ algorithm: "ed25519",
2564
+ signature: naclUtil.encodeBase64(signature)
2565
+ };
2566
+ }
2567
+ return envelope;
2568
+ }
2569
+ canonicalSigningInput(envelope) {
2570
+ return stableStringify({
2571
+ version: envelope.version,
2572
+ senderId: envelope.senderId,
2573
+ senderPublicKey: envelope.senderPublicKey,
2574
+ targetId: envelope.targetId,
2575
+ messageType: envelope.messageType,
2576
+ timestamp: envelope.timestamp,
2577
+ payload: envelope.payload,
2578
+ security: {
2579
+ encryption: envelope.security ? envelope.security.encryption : { enabled: false },
2580
+ pow: envelope.security ? envelope.security.pow : { enabled: false }
2581
+ }
2582
+ });
2583
+ }
2584
+ canonicalPowInput(envelope) {
2585
+ return stableStringify({
2586
+ version: envelope.version,
2587
+ senderId: envelope.senderId,
2588
+ senderPublicKey: envelope.senderPublicKey,
2589
+ targetId: envelope.targetId,
2590
+ messageType: envelope.messageType,
2591
+ timestamp: envelope.timestamp,
2592
+ payload: envelope.payload,
2593
+ security: {
2594
+ encryption: envelope.security ? envelope.security.encryption : { enabled: false }
2595
+ }
2596
+ });
2597
+ }
2598
+ async decryptIncomingMessage(envelope) {
2599
+ if (!this.options.enabled) {
2600
+ return {
2601
+ ignored: false,
2602
+ messageType: envelope.messageType,
2603
+ senderId: envelope.senderId,
2604
+ targetId: envelope.targetId,
2605
+ payload: envelope.payload
2606
+ };
2607
+ }
2608
+ if (!envelope || typeof envelope !== "object") {
2609
+ throw new Error("Incoming message is invalid");
2610
+ }
2611
+ if (envelope.targetId && envelope.targetId !== this.nodeId) {
2612
+ return { ignored: true };
2613
+ }
2614
+ if (envelope.security && envelope.security.pow && envelope.security.pow.enabled && this.options.powEnabled) {
2615
+ await this.verifyPow(envelope);
2616
+ }
2617
+ if (envelope.security && envelope.security.signing && envelope.security.signing.enabled && this.options.signingEnabled) {
2618
+ this.verifySignature(envelope);
2619
+ }
2620
+ const payload = this.decryptPayload(envelope);
2621
+ return {
2622
+ ignored: false,
2623
+ messageType: envelope.messageType,
2624
+ senderId: envelope.senderId,
2625
+ targetId: envelope.targetId,
2626
+ payload
2627
+ };
2628
+ }
2629
+ resolveBroadcastPassword(scope) {
2630
+ const normalizedScope = scope || "default";
2631
+ if (typeof this.options.resolveBroadcastPassword === "function") {
2632
+ const resolved = this.options.resolveBroadcastPassword({
2633
+ scope: normalizedScope,
2634
+ nodeId: this.nodeId,
2635
+ defaultPassword: this.options.appPassword,
2636
+ broadcastPasswords: this.options.broadcastPasswords || {}
2637
+ });
2638
+ if (typeof resolved === "string" && resolved.length > 0) {
2639
+ return resolved;
2640
+ }
2641
+ }
2642
+ const scopePassword = this.options.broadcastPasswords ? this.options.broadcastPasswords[normalizedScope] : null;
2643
+ if (typeof scopePassword === "string" && scopePassword.length > 0) {
2644
+ return scopePassword;
2645
+ }
2646
+ return this.options.appPassword;
2647
+ }
2648
+ async encryptPayload({ payload, targetId, securityContext = {} }) {
2649
+ if (!this.options.encryptionEnabled) {
2650
+ return {
2651
+ payload,
2652
+ security: {
2653
+ enabled: false,
2654
+ mode: "none"
2655
+ }
2656
+ };
2657
+ }
2658
+ const plainText = naclUtil.decodeUTF8(JSON.stringify(payload));
2659
+ if (targetId) {
2660
+ const recipientPublicKey = this.resolvePeerPublicKey(targetId, null);
2661
+ if (!recipientPublicKey) {
2662
+ throw new Error(`Missing public key for target peer ${targetId}`);
2663
+ }
2664
+ const nonce2 = nacl.randomBytes(nacl.box.nonceLength);
2665
+ const encrypted2 = nacl.box(
2666
+ plainText,
2667
+ nonce2,
2668
+ naclUtil.decodeBase64(recipientPublicKey.encryptionPublicKey),
2669
+ this.encryptionSecretKey
2670
+ );
2671
+ return {
2672
+ payload: naclUtil.encodeBase64(encrypted2),
2673
+ security: {
2674
+ enabled: true,
2675
+ mode: "direct",
2676
+ nonce: naclUtil.encodeBase64(nonce2),
2677
+ senderEncryptionPublicKey: this.publicKeyBundle.encryptionPublicKey
2678
+ }
2679
+ };
2680
+ }
2681
+ const scope = securityContext.broadcastScope || "default";
2682
+ const nonce = nacl.randomBytes(nacl.secretbox.nonceLength);
2683
+ const salt = nacl.randomBytes(16);
2684
+ const password = this.resolveBroadcastPassword(scope);
2685
+ const key = hash32(concatBytes(utf8ToBytes(password), salt));
2686
+ const encrypted = nacl.secretbox(plainText, nonce, key);
2687
+ return {
2688
+ payload: naclUtil.encodeBase64(encrypted),
2689
+ security: {
2690
+ enabled: true,
2691
+ mode: "broadcast",
2692
+ scope,
2693
+ nonce: naclUtil.encodeBase64(nonce),
2694
+ salt: naclUtil.encodeBase64(salt)
2695
+ }
2696
+ };
2697
+ }
2698
+ decryptPayload(envelope) {
2699
+ const encryption = envelope.security ? envelope.security.encryption : null;
2700
+ if (!encryption || !encryption.enabled || !this.options.encryptionEnabled) {
2701
+ return envelope.payload;
2702
+ }
2703
+ const encryptedBuffer = naclUtil.decodeBase64(envelope.payload);
2704
+ if (encryption.mode === "broadcast") {
2705
+ const scope = encryption.scope || "default";
2706
+ const password = this.resolveBroadcastPassword(scope);
2707
+ const salt = naclUtil.decodeBase64(encryption.salt);
2708
+ const nonce = naclUtil.decodeBase64(encryption.nonce);
2709
+ const key = hash32(concatBytes(utf8ToBytes(password), salt));
2710
+ const decrypted = nacl.secretbox.open(encryptedBuffer, nonce, key);
2711
+ if (!decrypted) {
2712
+ throw new Error("Unable to decrypt broadcast payload");
2713
+ }
2714
+ return JSON.parse(naclUtil.encodeUTF8(decrypted));
2715
+ }
2716
+ if (encryption.mode === "direct") {
2717
+ const senderPublicKey = naclUtil.decodeBase64(encryption.senderEncryptionPublicKey);
2718
+ const nonce = naclUtil.decodeBase64(encryption.nonce);
2719
+ const decrypted = nacl.box.open(
2720
+ encryptedBuffer,
2721
+ nonce,
2722
+ senderPublicKey,
2723
+ this.encryptionSecretKey
2724
+ );
2725
+ if (!decrypted) {
2726
+ throw new Error("Unable to decrypt direct payload");
2727
+ }
2728
+ return JSON.parse(naclUtil.encodeUTF8(decrypted));
2729
+ }
2730
+ throw new Error(`Unsupported encryption mode: ${encryption.mode}`);
2731
+ }
2732
+ verifySignature(envelope) {
2733
+ const senderPublicKey = this.resolvePeerPublicKey(envelope.senderId, envelope.senderPublicKey);
2734
+ if (!senderPublicKey) {
2735
+ throw new Error(`Missing public key for sender ${envelope.senderId}`);
2736
+ }
2737
+ const signatureBase = this.canonicalSigningInput(envelope);
2738
+ const isValid = nacl.sign.detached.verify(
2739
+ naclUtil.decodeUTF8(signatureBase),
2740
+ naclUtil.decodeBase64(envelope.security.signing.signature),
2741
+ naclUtil.decodeBase64(senderPublicKey.signingPublicKey)
2742
+ );
2743
+ if (!isValid) {
2744
+ const error = new Error(`Invalid signature for sender ${envelope.senderId}`);
2745
+ error.code = "INVALID_SIGNATURE";
2746
+ throw error;
2747
+ }
2748
+ return true;
2749
+ }
2750
+ async determinePowSteps() {
2751
+ if (typeof this.calibratedPowSteps === "bigint") {
2752
+ return this.calibratedPowSteps;
2753
+ }
2754
+ if (typeof this.options.powSteps === "number") {
2755
+ this.calibratedPowSteps = BigInt(Math.max(1, this.options.powSteps));
2756
+ return this.calibratedPowSteps;
2757
+ }
2758
+ const targetMs = Math.max(1, Number(this.options.powTargetMs || 1));
2759
+ const probeChallenge = bytesToHex(hash32(utf8ToBytes(`probe:${this.nodeId}:${this.now()}`)));
2760
+ const probeSteps = BigInt(2);
2761
+ const start = this.now();
2762
+ await VDF2.compute(probeChallenge, probeSteps);
2763
+ const elapsedMs = Math.max(1, this.now() - start);
2764
+ const scaled = Math.max(1, Math.round(targetMs / elapsedMs * Number(probeSteps)));
2765
+ this.calibratedPowSteps = BigInt(scaled);
2766
+ return this.calibratedPowSteps;
2767
+ }
2768
+ async generatePow(envelope) {
2769
+ const challenge = bytesToHex(hash32(utf8ToBytes(this.canonicalPowInput(envelope))));
2770
+ const steps = await this.determinePowSteps();
2771
+ const start = this.now();
2772
+ const proof = await VDF2.compute(challenge, steps);
2773
+ const durationMs = this.now() - start;
2774
+ return {
2775
+ challenge,
2776
+ proof,
2777
+ steps: steps.toString(),
2778
+ durationMs
2779
+ };
2780
+ }
2781
+ async verifyPow(envelope) {
2782
+ const expectedChallenge = bytesToHex(hash32(utf8ToBytes(this.canonicalPowInput(envelope))));
2783
+ const pow = envelope.security.pow;
2784
+ if (!pow || pow.challenge !== expectedChallenge) {
2785
+ const error = new Error("PoW challenge mismatch");
2786
+ error.code = "INVALID_POW";
2787
+ throw error;
2788
+ }
2789
+ const verified = await VDF2.verify(pow.challenge, BigInt(pow.steps), pow.proof);
2790
+ if (!verified) {
2791
+ const error = new Error("PoW verification failed");
2792
+ error.code = "INVALID_POW";
2793
+ throw error;
2794
+ }
2795
+ return true;
2796
+ }
2797
+ };
2798
+ module2.exports = {
2799
+ MessageSecurityService: MessageSecurityService2,
2800
+ stableStringify,
2801
+ DEFAULT_SECURITY_OPTIONS: DEFAULT_SECURITY_OPTIONS2
2802
+ };
2803
+ }
2804
+ });
2805
+
2806
+ // src/core/dignity-p2p.js
2807
+ var require_dignity_p2p = __commonJS({
2808
+ "src/core/dignity-p2p.js"(exports2, module2) {
2809
+ var EventEmitter = require_event_emitter();
2810
+ var { MessageSecurityService: MessageSecurityService2 } = require_message_security_service();
2811
+ var DignityP2P2 = class extends EventEmitter {
2812
+ constructor({ nodeId, networkAdapter, idGenerator, now, security } = {}) {
2813
+ super();
2814
+ if (!nodeId) {
2815
+ throw new Error("DignityP2P requires nodeId");
2816
+ }
2817
+ if (!networkAdapter) {
2818
+ throw new Error("DignityP2P requires networkAdapter");
2819
+ }
2820
+ this.nodeId = nodeId;
2821
+ this.networkAdapter = networkAdapter;
2822
+ this.idGenerator = idGenerator || (() => `${Date.now()}-${Math.random().toString(16).slice(2)}`);
2823
+ this.now = now || (() => Date.now());
2824
+ this.securityService = new MessageSecurityService2({
2825
+ nodeId: this.nodeId,
2826
+ options: security || {},
2827
+ now: this.now
2828
+ });
2829
+ this.bannedPeers = /* @__PURE__ */ new Map();
2830
+ this.peerBanDurationMs = security && typeof security.banDurationMs === "number" ? security.banDurationMs : 48 * 60 * 60 * 1e3;
2831
+ this.resolveBroadcastScope = security && typeof security.resolveBroadcastScope === "function" ? security.resolveBroadcastScope : (() => "default");
2832
+ this.defaultDiscoveryHeartbeatMs = security && typeof security.discoveryHeartbeatMs === "number" ? security.discoveryHeartbeatMs : 15e3;
2833
+ this.defaultPresenceTtlMs = security && typeof security.presenceTtlMs === "number" ? security.presenceTtlMs : 45e3;
2834
+ this.discoveryRooms = /* @__PURE__ */ new Map();
2835
+ this.presenceByScope = /* @__PURE__ */ new Map();
2836
+ this.state = /* @__PURE__ */ new Map();
2837
+ this.appliedOperations = /* @__PURE__ */ new Set();
2838
+ this.boundMessageHandler = this.handleIncomingMessage.bind(this);
2839
+ }
2840
+ async start() {
2841
+ this.networkAdapter.onMessage(this.boundMessageHandler);
2842
+ await this.networkAdapter.start(this.nodeId);
2843
+ }
2844
+ async stop() {
2845
+ const joinedScopes = Array.from(this.discoveryRooms.keys());
2846
+ for (const scope of joinedScopes) {
2847
+ try {
2848
+ await this.leaveDiscovery(scope);
2849
+ } catch (error) {
2850
+ this.emit("warning", { type: "presence-leave-failed", scope, error });
2851
+ }
2852
+ }
2853
+ this.networkAdapter.offMessage(this.boundMessageHandler);
2854
+ await this.networkAdapter.stop();
2855
+ }
2856
+ getCollection(collectionName) {
2857
+ if (!collectionName) {
2858
+ throw new Error("collectionName is required");
2859
+ }
2860
+ if (!this.state.has(collectionName)) {
2861
+ this.state.set(collectionName, /* @__PURE__ */ new Map());
2862
+ }
2863
+ return this.state.get(collectionName);
2864
+ }
2865
+ normalizeRecord(record) {
2866
+ if (!record || record.deletedAt) {
2867
+ return null;
2868
+ }
2869
+ return {
2870
+ id: record.id,
2871
+ ownerId: record.ownerId,
2872
+ createdAt: record.createdAt,
2873
+ updatedAt: record.updatedAt,
2874
+ version: record.version,
2875
+ data: { ...record.data }
2876
+ };
2877
+ }
2878
+ async create(collectionName, data, options = {}) {
2879
+ const collection = this.getCollection(collectionName);
2880
+ const id = options.id || this.idGenerator();
2881
+ if (collection.has(id) && !collection.get(id).deletedAt) {
2882
+ throw new Error(`Object ${id} already exists in ${collectionName}`);
2883
+ }
2884
+ const timestamp = this.now();
2885
+ const operation = {
2886
+ opId: this.idGenerator(),
2887
+ kind: "create",
2888
+ collectionName,
2889
+ id,
2890
+ actorId: this.nodeId,
2891
+ ownerId: this.nodeId,
2892
+ timestamp,
2893
+ payload: { ...data }
2894
+ };
2895
+ this.applyOperation(operation);
2896
+ await this.broadcastMessage("operation", operation, {
2897
+ broadcastScope: options.broadcastScope || this.resolveBroadcastScope({
2898
+ messageType: "operation",
2899
+ operation,
2900
+ collectionName
2901
+ })
2902
+ });
2903
+ return this.read(collectionName, id);
2904
+ }
2905
+ read(collectionName, id) {
2906
+ const collection = this.getCollection(collectionName);
2907
+ return this.normalizeRecord(collection.get(id));
2908
+ }
2909
+ list(collectionName, options = {}) {
2910
+ const collection = this.getCollection(collectionName);
2911
+ const includeDeleted = options.includeDeleted || false;
2912
+ const records = [];
2913
+ for (const record of collection.values()) {
2914
+ if (record.deletedAt && !includeDeleted) {
2915
+ continue;
2916
+ }
2917
+ if (record.deletedAt && includeDeleted) {
2918
+ records.push({
2919
+ id: record.id,
2920
+ ownerId: record.ownerId,
2921
+ deletedAt: record.deletedAt,
2922
+ version: record.version
2923
+ });
2924
+ continue;
2925
+ }
2926
+ records.push(this.normalizeRecord(record));
2927
+ }
2928
+ return records;
2929
+ }
2930
+ async update(collectionName, id, partialData, options = {}) {
2931
+ const existing = this.getCollection(collectionName).get(id);
2932
+ if (!existing || existing.deletedAt) {
2933
+ throw new Error(`Object ${id} does not exist in ${collectionName}`);
2934
+ }
2935
+ if (existing.ownerId !== this.nodeId) {
2936
+ throw new Error(`Only owner ${existing.ownerId} can update object ${id}`);
2937
+ }
2938
+ const operation = {
2939
+ opId: this.idGenerator(),
2940
+ kind: "update",
2941
+ collectionName,
2942
+ id,
2943
+ actorId: this.nodeId,
2944
+ timestamp: this.now(),
2945
+ baseVersion: existing.version,
2946
+ payload: { ...partialData }
2947
+ };
2948
+ this.applyOperation(operation);
2949
+ await this.broadcastMessage("operation", operation, {
2950
+ broadcastScope: options.broadcastScope || this.resolveBroadcastScope({
2951
+ messageType: "operation",
2952
+ operation,
2953
+ collectionName
2954
+ })
2955
+ });
2956
+ return this.read(collectionName, id);
2957
+ }
2958
+ async remove(collectionName, id, options = {}) {
2959
+ const existing = this.getCollection(collectionName).get(id);
2960
+ if (!existing || existing.deletedAt) {
2961
+ throw new Error(`Object ${id} does not exist in ${collectionName}`);
2962
+ }
2963
+ if (existing.ownerId !== this.nodeId) {
2964
+ throw new Error(`Only owner ${existing.ownerId} can delete object ${id}`);
2965
+ }
2966
+ const operation = {
2967
+ opId: this.idGenerator(),
2968
+ kind: "delete",
2969
+ collectionName,
2970
+ id,
2971
+ actorId: this.nodeId,
2972
+ timestamp: this.now(),
2973
+ baseVersion: existing.version
2974
+ };
2975
+ this.applyOperation(operation);
2976
+ await this.broadcastMessage("operation", operation, {
2977
+ broadcastScope: options.broadcastScope || this.resolveBroadcastScope({
2978
+ messageType: "operation",
2979
+ operation,
2980
+ collectionName
2981
+ })
2982
+ });
2983
+ }
2984
+ registerPeerPublicKey(peerId, publicKey) {
2985
+ this.securityService.registerPeerPublicKey(peerId, publicKey);
2986
+ }
2987
+ getPublicKey() {
2988
+ return this.securityService.getPublicKey();
2989
+ }
2990
+ async broadcastMessage(messageType, payload, securityContext = {}) {
2991
+ const envelope = await this.securityService.secureOutgoingMessage({
2992
+ messageType,
2993
+ payload,
2994
+ targetId: null,
2995
+ securityContext
2996
+ });
2997
+ await this.networkAdapter.broadcast(envelope);
2998
+ }
2999
+ async sendDirectMessage(targetId, messageType, payload) {
3000
+ const envelope = await this.securityService.secureOutgoingMessage({
3001
+ messageType,
3002
+ payload,
3003
+ targetId
3004
+ });
3005
+ await this.networkAdapter.broadcast(envelope);
3006
+ }
3007
+ getPresenceMap(scope) {
3008
+ if (!this.presenceByScope.has(scope)) {
3009
+ this.presenceByScope.set(scope, /* @__PURE__ */ new Map());
3010
+ }
3011
+ return this.presenceByScope.get(scope);
3012
+ }
3013
+ upsertPresence(scope, peerId, metadata, ttlMs, announcedAt) {
3014
+ const map = this.getPresenceMap(scope);
3015
+ const existing = map.get(peerId);
3016
+ const next = {
3017
+ peerId,
3018
+ scope,
3019
+ metadata: metadata ? { ...metadata } : {},
3020
+ lastSeenAt: announcedAt,
3021
+ expiresAt: announcedAt + ttlMs
3022
+ };
3023
+ map.set(peerId, next);
3024
+ if (!existing) {
3025
+ this.emit("peerdiscovered", { scope, peerId, metadata: next.metadata });
3026
+ }
3027
+ return next;
3028
+ }
3029
+ prunePresence(scope) {
3030
+ const map = this.presenceByScope.get(scope);
3031
+ if (!map) {
3032
+ return;
3033
+ }
3034
+ const now = this.now();
3035
+ for (const [peerId, entry] of map.entries()) {
3036
+ if (entry.expiresAt <= now) {
3037
+ map.delete(peerId);
3038
+ this.emit("peerleft", { scope, peerId, reason: "timeout" });
3039
+ }
3040
+ }
3041
+ }
3042
+ async joinDiscovery(scope = "main", options = {}) {
3043
+ const normalizedScope = scope || "main";
3044
+ const heartbeatIntervalMs = options.heartbeatIntervalMs || this.defaultDiscoveryHeartbeatMs;
3045
+ const ttlMs = options.ttlMs || this.defaultPresenceTtlMs;
3046
+ const metadata = options.metadata || {};
3047
+ const existing = this.discoveryRooms.get(normalizedScope);
3048
+ if (existing && existing.timer) {
3049
+ clearInterval(existing.timer);
3050
+ }
3051
+ const timer = setInterval(() => {
3052
+ this.announcePresence(normalizedScope).catch((error) => {
3053
+ this.emit("warning", { type: "presence-heartbeat-failed", scope: normalizedScope, error });
3054
+ });
3055
+ }, heartbeatIntervalMs);
3056
+ this.discoveryRooms.set(normalizedScope, {
3057
+ metadata,
3058
+ heartbeatIntervalMs,
3059
+ ttlMs,
3060
+ timer
3061
+ });
3062
+ this.upsertPresence(normalizedScope, this.nodeId, metadata, ttlMs, this.now());
3063
+ await this.announcePresence(normalizedScope);
3064
+ }
3065
+ async announcePresence(scope = "main", metadataOverride = null) {
3066
+ const normalizedScope = scope || "main";
3067
+ const room = this.discoveryRooms.get(normalizedScope);
3068
+ if (!room) {
3069
+ throw new Error(`Scope ${normalizedScope} has not been joined for discovery`);
3070
+ }
3071
+ const metadata = metadataOverride || room.metadata || {};
3072
+ const announcedAt = this.now();
3073
+ this.upsertPresence(normalizedScope, this.nodeId, metadata, room.ttlMs, announcedAt);
3074
+ await this.broadcastMessage(
3075
+ "presence:announce",
3076
+ {
3077
+ scope: normalizedScope,
3078
+ peerId: this.nodeId,
3079
+ metadata,
3080
+ ttlMs: room.ttlMs,
3081
+ announcedAt
3082
+ },
3083
+ { broadcastScope: normalizedScope }
3084
+ );
3085
+ }
3086
+ async leaveDiscovery(scope = "main") {
3087
+ const normalizedScope = scope || "main";
3088
+ const room = this.discoveryRooms.get(normalizedScope);
3089
+ if (!room) {
3090
+ return;
3091
+ }
3092
+ if (room.timer) {
3093
+ clearInterval(room.timer);
3094
+ }
3095
+ this.discoveryRooms.delete(normalizedScope);
3096
+ const map = this.presenceByScope.get(normalizedScope);
3097
+ if (map) {
3098
+ map.delete(this.nodeId);
3099
+ }
3100
+ await this.broadcastMessage(
3101
+ "presence:leave",
3102
+ {
3103
+ scope: normalizedScope,
3104
+ peerId: this.nodeId,
3105
+ leftAt: this.now()
3106
+ },
3107
+ { broadcastScope: normalizedScope }
3108
+ );
3109
+ }
3110
+ listPeers(scope = "main", options = {}) {
3111
+ const normalizedScope = scope || "main";
3112
+ const includeSelf = options.includeSelf !== false;
3113
+ this.prunePresence(normalizedScope);
3114
+ const map = this.presenceByScope.get(normalizedScope);
3115
+ if (!map) {
3116
+ return [];
3117
+ }
3118
+ return Array.from(map.values()).filter((entry) => includeSelf || entry.peerId !== this.nodeId).map((entry) => ({
3119
+ peerId: entry.peerId,
3120
+ scope: entry.scope,
3121
+ metadata: { ...entry.metadata },
3122
+ lastSeenAt: entry.lastSeenAt,
3123
+ expiresAt: entry.expiresAt
3124
+ }));
3125
+ }
3126
+ async handleIncomingMessage(message) {
3127
+ if (message && message.opId && message.kind) {
3128
+ this.applyOperation(message);
3129
+ return;
3130
+ }
3131
+ if (message && message.senderId && this.isPeerBanned(message.senderId)) {
3132
+ this.emit("messageignored", {
3133
+ senderId: message.senderId,
3134
+ reason: "peer-banned"
3135
+ });
3136
+ return;
3137
+ }
3138
+ let decrypted;
3139
+ try {
3140
+ decrypted = await this.securityService.decryptIncomingMessage(message);
3141
+ } catch (error) {
3142
+ const senderId = message ? message.senderId : null;
3143
+ if (senderId && (error.code === "INVALID_SIGNATURE" || error.code === "INVALID_POW")) {
3144
+ this.banPeer(senderId, this.peerBanDurationMs, error.code);
3145
+ }
3146
+ this.emit("securityerror", {
3147
+ senderId,
3148
+ error
3149
+ });
3150
+ return;
3151
+ }
3152
+ if (!decrypted || decrypted.ignored) {
3153
+ return;
3154
+ }
3155
+ if (decrypted.messageType === "operation") {
3156
+ this.applyOperation(decrypted.payload);
3157
+ return;
3158
+ }
3159
+ if (decrypted.messageType === "presence:announce") {
3160
+ const payload = decrypted.payload || {};
3161
+ const scope = payload.scope || "main";
3162
+ const peerId = payload.peerId || decrypted.senderId;
3163
+ if (!peerId) {
3164
+ return;
3165
+ }
3166
+ const presenceMap = this.getPresenceMap(scope);
3167
+ const isNewPeerInScope = !presenceMap.has(peerId);
3168
+ this.upsertPresence(
3169
+ scope,
3170
+ peerId,
3171
+ payload.metadata || {},
3172
+ payload.ttlMs || this.defaultPresenceTtlMs,
3173
+ payload.announcedAt || this.now()
3174
+ );
3175
+ if (isNewPeerInScope && peerId !== this.nodeId && this.discoveryRooms.has(scope)) {
3176
+ this.announcePresence(scope).catch((error) => {
3177
+ this.emit("warning", { type: "presence-handshake-failed", scope, error });
3178
+ });
3179
+ }
3180
+ return;
3181
+ }
3182
+ if (decrypted.messageType === "presence:leave") {
3183
+ const payload = decrypted.payload || {};
3184
+ const scope = payload.scope || "main";
3185
+ const peerId = payload.peerId || decrypted.senderId;
3186
+ const map = this.presenceByScope.get(scope);
3187
+ if (map && peerId && map.has(peerId)) {
3188
+ map.delete(peerId);
3189
+ this.emit("peerleft", { scope, peerId, reason: "leave" });
3190
+ }
3191
+ return;
3192
+ }
3193
+ this.emit("message", {
3194
+ senderId: decrypted.senderId,
3195
+ targetId: decrypted.targetId,
3196
+ type: decrypted.messageType,
3197
+ payload: decrypted.payload
3198
+ });
3199
+ }
3200
+ banPeer(peerId, durationMs = this.peerBanDurationMs, reason = "manual") {
3201
+ if (!peerId) {
3202
+ return;
3203
+ }
3204
+ const bannedUntil = this.now() + Math.max(1, durationMs);
3205
+ this.bannedPeers.set(peerId, {
3206
+ peerId,
3207
+ reason,
3208
+ bannedAt: this.now(),
3209
+ bannedUntil
3210
+ });
3211
+ this.emit("peerbanned", {
3212
+ peerId,
3213
+ reason,
3214
+ bannedUntil
3215
+ });
3216
+ }
3217
+ unbanPeer(peerId) {
3218
+ this.bannedPeers.delete(peerId);
3219
+ this.emit("peerunbanned", { peerId });
3220
+ }
3221
+ getBanInfo(peerId) {
3222
+ const info = this.bannedPeers.get(peerId);
3223
+ if (!info) {
3224
+ return null;
3225
+ }
3226
+ if (info.bannedUntil <= this.now()) {
3227
+ this.bannedPeers.delete(peerId);
3228
+ return null;
3229
+ }
3230
+ return { ...info };
3231
+ }
3232
+ isPeerBanned(peerId) {
3233
+ return this.getBanInfo(peerId) !== null;
3234
+ }
3235
+ applyOperation(operation) {
3236
+ if (!operation || !operation.opId || this.appliedOperations.has(operation.opId)) {
3237
+ return false;
3238
+ }
3239
+ const collection = this.getCollection(operation.collectionName);
3240
+ const current = collection.get(operation.id);
3241
+ if (operation.kind === "create") {
3242
+ if (current && !current.deletedAt) {
3243
+ return false;
3244
+ }
3245
+ collection.set(operation.id, {
3246
+ id: operation.id,
3247
+ ownerId: operation.ownerId,
3248
+ data: { ...operation.payload },
3249
+ createdAt: operation.timestamp,
3250
+ updatedAt: operation.timestamp,
3251
+ deletedAt: null,
3252
+ version: 1
3253
+ });
3254
+ this.appliedOperations.add(operation.opId);
3255
+ this.emit("change", { kind: "create", collection: operation.collectionName, id: operation.id });
3256
+ return true;
3257
+ }
3258
+ if (!current || current.deletedAt) {
3259
+ return false;
3260
+ }
3261
+ if (operation.actorId !== current.ownerId) {
3262
+ return false;
3263
+ }
3264
+ if (typeof operation.baseVersion === "number" && operation.baseVersion !== current.version) {
3265
+ return false;
3266
+ }
3267
+ if (operation.kind === "update") {
3268
+ current.data = {
3269
+ ...current.data,
3270
+ ...operation.payload
3271
+ };
3272
+ current.updatedAt = operation.timestamp;
3273
+ current.version += 1;
3274
+ this.appliedOperations.add(operation.opId);
3275
+ this.emit("change", { kind: "update", collection: operation.collectionName, id: operation.id });
3276
+ return true;
3277
+ }
3278
+ if (operation.kind === "delete") {
3279
+ current.deletedAt = operation.timestamp;
3280
+ current.updatedAt = operation.timestamp;
3281
+ current.version += 1;
3282
+ this.appliedOperations.add(operation.opId);
3283
+ this.emit("change", { kind: "delete", collection: operation.collectionName, id: operation.id });
3284
+ return true;
3285
+ }
3286
+ return false;
3287
+ }
3288
+ };
3289
+ module2.exports = DignityP2P2;
3290
+ }
3291
+ });
3292
+
3293
+ // src/signaling/signaling-pool.js
3294
+ var require_signaling_pool = __commonJS({
3295
+ "src/signaling/signaling-pool.js"(exports2, module2) {
3296
+ var SignalingPool2 = class {
3297
+ constructor(providers = []) {
3298
+ this.providers = [...providers];
3299
+ this.activeProvider = null;
3300
+ }
3301
+ registerProvider(provider) {
3302
+ this.providers.push(provider);
3303
+ }
3304
+ getProvidersByPriority() {
3305
+ return [...this.providers].sort((a, b) => (a.priority || 0) - (b.priority || 0));
3306
+ }
3307
+ async connect(excludedProviderIds = /* @__PURE__ */ new Set()) {
3308
+ const providers = this.getProvidersByPriority().filter(
3309
+ (provider) => !excludedProviderIds.has(provider.id)
3310
+ );
3311
+ let lastError;
3312
+ for (const provider of providers) {
3313
+ try {
3314
+ await provider.connect();
3315
+ this.activeProvider = provider;
3316
+ return provider;
3317
+ } catch (error) {
3318
+ lastError = error;
3319
+ }
3320
+ }
3321
+ throw lastError || new Error("No signaling provider could connect");
3322
+ }
3323
+ async send(message) {
3324
+ if (!this.activeProvider) {
3325
+ await this.connect();
3326
+ }
3327
+ try {
3328
+ await this.activeProvider.send(message);
3329
+ } catch (error) {
3330
+ if (this.activeProvider && typeof this.activeProvider.disconnect === "function") {
3331
+ await this.activeProvider.disconnect();
3332
+ }
3333
+ const failedProviderId = this.activeProvider ? this.activeProvider.id : null;
3334
+ this.activeProvider = null;
3335
+ const excludedProviderIds = failedProviderId ? /* @__PURE__ */ new Set([failedProviderId]) : /* @__PURE__ */ new Set();
3336
+ await this.connect(excludedProviderIds);
3337
+ await this.activeProvider.send(message);
3338
+ return error;
3339
+ }
3340
+ return null;
3341
+ }
3342
+ onMessage(handler) {
3343
+ for (const provider of this.providers) {
3344
+ if (typeof provider.onMessage === "function") {
3345
+ provider.onMessage(handler);
3346
+ }
3347
+ }
3348
+ }
3349
+ async disconnect() {
3350
+ const disconnections = this.providers.filter((provider) => typeof provider.disconnect === "function").map((provider) => provider.disconnect());
3351
+ await Promise.all(disconnections);
3352
+ this.activeProvider = null;
3353
+ }
3354
+ };
3355
+ module2.exports = SignalingPool2;
3356
+ }
3357
+ });
3358
+
3359
+ // src/signaling/websocket-signaling-provider.js
3360
+ var require_websocket_signaling_provider = __commonJS({
3361
+ "src/signaling/websocket-signaling-provider.js"(exports2, module2) {
3362
+ var WebSocketSignalingProvider2 = class {
3363
+ constructor({ id, url, WebSocketImpl, priority = 0 }) {
3364
+ if (!url) {
3365
+ throw new Error("WebSocket signaling provider requires a url");
3366
+ }
3367
+ this.id = id || url;
3368
+ this.url = url;
3369
+ this.priority = priority;
3370
+ this.WebSocketImpl = WebSocketImpl || globalThis.WebSocket;
3371
+ this.socket = null;
3372
+ this.messageHandlers = /* @__PURE__ */ new Set();
3373
+ }
3374
+ async connect() {
3375
+ if (!this.WebSocketImpl) {
3376
+ throw new Error("WebSocket implementation is not available");
3377
+ }
3378
+ await new Promise((resolve, reject) => {
3379
+ const socket = new this.WebSocketImpl(this.url);
3380
+ socket.onopen = () => {
3381
+ this.socket = socket;
3382
+ resolve();
3383
+ };
3384
+ socket.onerror = () => {
3385
+ reject(new Error(`Unable to connect to signaling url ${this.url}`));
3386
+ };
3387
+ socket.onmessage = (event) => {
3388
+ let payload = event.data;
3389
+ try {
3390
+ payload = JSON.parse(event.data);
3391
+ } catch (error) {
3392
+ payload = event.data;
3393
+ }
3394
+ for (const handler of this.messageHandlers) {
3395
+ handler(payload);
3396
+ }
3397
+ };
3398
+ });
3399
+ }
3400
+ onMessage(handler) {
3401
+ this.messageHandlers.add(handler);
3402
+ }
3403
+ async send(message) {
3404
+ if (!this.socket || this.socket.readyState !== 1) {
3405
+ throw new Error(`Signaling socket is not open for ${this.url}`);
3406
+ }
3407
+ this.socket.send(JSON.stringify(message));
3408
+ }
3409
+ async disconnect() {
3410
+ if (!this.socket) {
3411
+ return;
3412
+ }
3413
+ this.socket.close();
3414
+ this.socket = null;
3415
+ }
3416
+ };
3417
+ module2.exports = WebSocketSignalingProvider2;
3418
+ }
3419
+ });
3420
+
3421
+ // src/signaling/default-signaling-config.js
3422
+ var require_default_signaling_config = __commonJS({
3423
+ "src/signaling/default-signaling-config.js"(exports2, module2) {
3424
+ var DEFAULT_CLOUDFLARE_SIGNALING_URLS2 = [
3425
+ "wss://signaling.cloudflare.com",
3426
+ "wss://cloudflare-webrtc-signaling.example",
3427
+ "wss://trycloudflare-signaling.example"
3428
+ ];
3429
+ var DEFAULT_SIGNALING_FALLBACK_URLS2 = [
3430
+ "wss://relay.dignity.dev/signaling",
3431
+ "wss://backup-relay.dignity.dev/signaling"
3432
+ ];
3433
+ module2.exports = {
3434
+ DEFAULT_CLOUDFLARE_SIGNALING_URLS: DEFAULT_CLOUDFLARE_SIGNALING_URLS2,
3435
+ DEFAULT_SIGNALING_FALLBACK_URLS: DEFAULT_SIGNALING_FALLBACK_URLS2
3436
+ };
3437
+ }
3438
+ });
3439
+
3440
+ // src/signaling/create-default-signaling-pool.js
3441
+ var require_create_default_signaling_pool = __commonJS({
3442
+ "src/signaling/create-default-signaling-pool.js"(exports2, module2) {
3443
+ var SignalingPool2 = require_signaling_pool();
3444
+ var WebSocketSignalingProvider2 = require_websocket_signaling_provider();
3445
+ var {
3446
+ DEFAULT_CLOUDFLARE_SIGNALING_URLS: DEFAULT_CLOUDFLARE_SIGNALING_URLS2,
3447
+ DEFAULT_SIGNALING_FALLBACK_URLS: DEFAULT_SIGNALING_FALLBACK_URLS2
3448
+ } = require_default_signaling_config();
3449
+ function createDefaultSignalingPool2(options = {}) {
3450
+ const cloudflareUrls = options.cloudflareUrls || DEFAULT_CLOUDFLARE_SIGNALING_URLS2;
3451
+ const fallbackUrls = options.fallbackUrls || DEFAULT_SIGNALING_FALLBACK_URLS2;
3452
+ const WebSocketImpl = options.WebSocketImpl;
3453
+ const providers = [];
3454
+ cloudflareUrls.forEach((url, index) => {
3455
+ providers.push(
3456
+ new WebSocketSignalingProvider2({
3457
+ id: `cloudflare-${index + 1}`,
3458
+ url,
3459
+ WebSocketImpl,
3460
+ priority: index
3461
+ })
3462
+ );
3463
+ });
3464
+ fallbackUrls.forEach((url, index) => {
3465
+ providers.push(
3466
+ new WebSocketSignalingProvider2({
3467
+ id: `fallback-${index + 1}`,
3468
+ url,
3469
+ WebSocketImpl,
3470
+ priority: cloudflareUrls.length + index
3471
+ })
3472
+ );
3473
+ });
3474
+ if (Array.isArray(options.customProviders)) {
3475
+ providers.push(...options.customProviders);
3476
+ }
3477
+ return new SignalingPool2(providers);
3478
+ }
3479
+ module2.exports = createDefaultSignalingPool2;
3480
+ }
3481
+ });
3482
+
3483
+ // src/network/in-memory-network.js
3484
+ var require_in_memory_network = __commonJS({
3485
+ "src/network/in-memory-network.js"(exports2, module2) {
3486
+ var InMemoryNetworkHub2 = class {
3487
+ constructor() {
3488
+ this.adapters = /* @__PURE__ */ new Map();
3489
+ }
3490
+ register(adapter) {
3491
+ this.adapters.set(adapter.nodeId, adapter);
3492
+ }
3493
+ unregister(nodeId) {
3494
+ this.adapters.delete(nodeId);
3495
+ }
3496
+ async broadcast(senderId, message) {
3497
+ const deliveries = [];
3498
+ for (const [nodeId, adapter] of this.adapters.entries()) {
3499
+ if (nodeId !== senderId) {
3500
+ deliveries.push(adapter.receive(message));
3501
+ }
3502
+ }
3503
+ await Promise.all(deliveries);
3504
+ }
3505
+ };
3506
+ var InMemoryNetworkAdapter2 = class {
3507
+ constructor(hub) {
3508
+ if (!hub) {
3509
+ throw new Error("InMemoryNetworkAdapter requires an InMemoryNetworkHub");
3510
+ }
3511
+ this.hub = hub;
3512
+ this.nodeId = null;
3513
+ this.messageHandlers = /* @__PURE__ */ new Set();
3514
+ }
3515
+ async start(nodeId) {
3516
+ this.nodeId = nodeId;
3517
+ this.hub.register(this);
3518
+ }
3519
+ async stop() {
3520
+ if (this.nodeId) {
3521
+ this.hub.unregister(this.nodeId);
3522
+ }
3523
+ this.nodeId = null;
3524
+ }
3525
+ async broadcast(message) {
3526
+ if (!this.nodeId) {
3527
+ throw new Error("Network adapter has not been started");
3528
+ }
3529
+ await this.hub.broadcast(this.nodeId, message);
3530
+ }
3531
+ onMessage(handler) {
3532
+ this.messageHandlers.add(handler);
3533
+ }
3534
+ offMessage(handler) {
3535
+ this.messageHandlers.delete(handler);
3536
+ }
3537
+ async receive(message) {
3538
+ const deliveries = [];
3539
+ for (const handler of this.messageHandlers) {
3540
+ deliveries.push(handler(message));
3541
+ }
3542
+ await Promise.all(deliveries);
3543
+ }
3544
+ };
3545
+ module2.exports = {
3546
+ InMemoryNetworkHub: InMemoryNetworkHub2,
3547
+ InMemoryNetworkAdapter: InMemoryNetworkAdapter2
3548
+ };
3549
+ }
3550
+ });
3551
+
3552
+ // src/index.js
3553
+ var DignityP2P = require_dignity_p2p();
3554
+ var createDefaultSignalingPool = require_create_default_signaling_pool();
3555
+ var SignalingPool = require_signaling_pool();
3556
+ var WebSocketSignalingProvider = require_websocket_signaling_provider();
3557
+ var {
3558
+ InMemoryNetworkHub,
3559
+ InMemoryNetworkAdapter
3560
+ } = require_in_memory_network();
3561
+ var {
3562
+ DEFAULT_CLOUDFLARE_SIGNALING_URLS,
3563
+ DEFAULT_SIGNALING_FALLBACK_URLS
3564
+ } = require_default_signaling_config();
3565
+ var VDF = require_vdf();
3566
+ var SlothPermutation = require_sloth_vdf();
3567
+ var {
3568
+ MessageSecurityService,
3569
+ DEFAULT_SECURITY_OPTIONS
3570
+ } = require_message_security_service();
3571
+ module.exports = {
3572
+ DignityP2P,
3573
+ createDefaultSignalingPool,
3574
+ SignalingPool,
3575
+ WebSocketSignalingProvider,
3576
+ InMemoryNetworkHub,
3577
+ InMemoryNetworkAdapter,
3578
+ DEFAULT_CLOUDFLARE_SIGNALING_URLS,
3579
+ DEFAULT_SIGNALING_FALLBACK_URLS,
3580
+ VDF,
3581
+ SlothPermutation,
3582
+ MessageSecurityService,
3583
+ DEFAULT_SECURITY_OPTIONS
3584
+ };
3585
+ //# sourceMappingURL=dignity.cjs.js.map