@blamejs/core 0.6.13 → 0.6.20

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,552 @@
1
+ "use strict";
2
+
3
+ var tls = require("node:tls");
4
+ var dgram = require("node:dgram");
5
+ var nodeCrypto = require("node:crypto");
6
+
7
+ var C = require("./constants");
8
+ var validateOpts = require("./validate-opts");
9
+ var { defineClass } = require("./framework-error");
10
+
11
+ var NtsError = defineClass("NtsError", { alwaysPermanent: false });
12
+
13
+ var NTS_KE_DEFAULT_PORT = 4460;
14
+ var NTPV4_DEFAULT_PORT = 123;
15
+ var NTP_TO_UNIX_OFFSET_SECONDS = 2208988800;
16
+
17
+ var REC_END = 0;
18
+ var REC_NEXT_PROTOCOL = 1;
19
+ var REC_ERROR = 2;
20
+ var REC_WARNING = 3;
21
+ var REC_AEAD_ALGORITHM = 4;
22
+ var REC_NEW_COOKIE = 5;
23
+ var REC_NTPV4_SERVER = 6;
24
+ var REC_NTPV4_PORT = 7;
25
+
26
+ var NTPV4_PROTOCOL_ID = 0;
27
+
28
+ var AEAD_AES_SIV_CMAC_256 = 15;
29
+ var AEAD_CHACHA20_POLY1305 = 30;
30
+
31
+ var EXTENSION_UNIQUE_IDENTIFIER = 0x0104;
32
+ var EXTENSION_NTS_COOKIE = 0x0204;
33
+ var EXTENSION_NTS_AUTHENTICATOR_AND_ENC = 0x0404;
34
+
35
+ function _u16be(v) { var b = Buffer.alloc(2); b.writeUInt16BE(v, 0); return b; }
36
+
37
+ function _encodeRecord(critical, type, body) {
38
+ var hdr = Buffer.alloc(4);
39
+ var typeField = type & 0x7fff;
40
+ if (critical) typeField |= 0x8000;
41
+ hdr.writeUInt16BE(typeField, 0);
42
+ hdr.writeUInt16BE(body.length, 2);
43
+ return Buffer.concat([hdr, body]);
44
+ }
45
+
46
+ function _decodeRecords(buf) {
47
+ var out = [];
48
+ var off = 0;
49
+ while (off + 4 <= buf.length) {
50
+ var t = buf.readUInt16BE(off);
51
+ var critical = (t & 0x8000) !== 0;
52
+ var type = t & 0x7fff;
53
+ var len = buf.readUInt16BE(off + 2);
54
+ off += 4;
55
+ if (off + len > buf.length) {
56
+ throw new NtsError("nts/bad-record", "NTS-KE record body length " + len + " exceeds buffer");
57
+ }
58
+ var body = buf.slice(off, off + len);
59
+ off += len;
60
+ out.push({ critical: critical, type: type, body: body });
61
+ if (type === REC_END) break;
62
+ }
63
+ return out;
64
+ }
65
+
66
+ function _aesEncryptBlock(key, block) {
67
+ var c = nodeCrypto.createCipheriv("aes-" + (key.length * 8) + "-ecb", key, Buffer.alloc(0));
68
+ c.setAutoPadding(false);
69
+ return Buffer.concat([c.update(block), c.final()]);
70
+ }
71
+
72
+ function _shl1(buf) {
73
+ var out = Buffer.alloc(buf.length);
74
+ var carry = 0;
75
+ for (var i = buf.length - 1; i >= 0; i--) {
76
+ var v = (buf[i] << 1) | carry;
77
+ out[i] = v & 0xff;
78
+ carry = (v >> 8) & 1;
79
+ }
80
+ return out;
81
+ }
82
+
83
+ function _xorBuf(a, b) {
84
+ var out = Buffer.alloc(a.length);
85
+ for (var i = 0; i < a.length; i++) out[i] = a[i] ^ b[i];
86
+ return out;
87
+ }
88
+
89
+ function _cmacSubkeys(key) {
90
+ var L = _aesEncryptBlock(key, Buffer.alloc(16, 0));
91
+ var Rb = Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x87]);
92
+ var K1 = _shl1(L);
93
+ if (L[0] & 0x80) K1 = _xorBuf(K1, Rb);
94
+ var K2 = _shl1(K1);
95
+ if (K1[0] & 0x80) K2 = _xorBuf(K2, Rb);
96
+ return { K1: K1, K2: K2 };
97
+ }
98
+
99
+ function _cmac(key, message) {
100
+ var subkeys = _cmacSubkeys(key);
101
+ var n = Math.ceil(message.length / 16);
102
+ if (n === 0) n = 1;
103
+ var lastIsComplete = (message.length > 0) && (message.length % 16 === 0);
104
+ var blocks = [];
105
+ for (var i = 0; i < n - 1; i++) {
106
+ blocks.push(message.slice(i * 16, i * 16 + 16));
107
+ }
108
+ var lastBlock;
109
+ if (lastIsComplete) {
110
+ lastBlock = _xorBuf(message.slice((n - 1) * 16, n * 16), subkeys.K1);
111
+ } else {
112
+ var rem = message.slice((n - 1) * 16);
113
+ var padded = Buffer.alloc(16);
114
+ rem.copy(padded);
115
+ padded[rem.length] = 0x80;
116
+ lastBlock = _xorBuf(padded, subkeys.K2);
117
+ }
118
+ blocks.push(lastBlock);
119
+ var X = Buffer.alloc(16, 0);
120
+ for (var b = 0; b < blocks.length; b++) {
121
+ X = _aesEncryptBlock(key, _xorBuf(X, blocks[b]));
122
+ }
123
+ return X;
124
+ }
125
+
126
+ function _dbl(buf) {
127
+ var Rb = Buffer.from([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x87]);
128
+ var shifted = _shl1(buf);
129
+ if (buf[0] & 0x80) shifted = _xorBuf(shifted, Rb);
130
+ return shifted;
131
+ }
132
+
133
+ function _s2v(K, strings, plaintext) {
134
+ var D = _cmac(K, Buffer.alloc(16, 0));
135
+ for (var i = 0; i < strings.length; i++) {
136
+ D = _xorBuf(_dbl(D), _cmac(K, strings[i]));
137
+ }
138
+ var T;
139
+ if (plaintext.length >= 16) {
140
+ var head = plaintext.slice(0, plaintext.length - 16);
141
+ var tail = plaintext.slice(plaintext.length - 16);
142
+ var xored = _xorBuf(tail, D);
143
+ T = Buffer.concat([head, xored]);
144
+ } else {
145
+ var padded = Buffer.alloc(16);
146
+ plaintext.copy(padded);
147
+ padded[plaintext.length] = 0x80;
148
+ T = _xorBuf(_dbl(D), padded);
149
+ }
150
+ return _cmac(K, T);
151
+ }
152
+
153
+ function _aesCtr(key, iv, data) {
154
+ var ivCopy = Buffer.from(iv);
155
+ ivCopy[8] &= 0x7f;
156
+ ivCopy[12] &= 0x7f;
157
+ var c = nodeCrypto.createCipheriv("aes-" + (key.length * 8) + "-ctr", key, ivCopy);
158
+ return Buffer.concat([c.update(data), c.final()]);
159
+ }
160
+
161
+ function aesSivEncrypt(K, plaintext, associatedData) {
162
+ if (K.length !== 32 && K.length !== 48 && K.length !== 64) {
163
+ throw new NtsError("nts/bad-key", "AES-SIV key must be 32/48/64 bytes, got " + K.length);
164
+ }
165
+ var half = K.length / 2;
166
+ var K1 = K.slice(0, half);
167
+ var K2 = K.slice(half);
168
+ var V = _s2v(K1, associatedData || [], plaintext);
169
+ var ct = _aesCtr(K2, V, plaintext);
170
+ return Buffer.concat([V, ct]);
171
+ }
172
+
173
+ function aesSivDecrypt(K, ciphertextWithIv, associatedData) {
174
+ var half = K.length / 2;
175
+ var K1 = K.slice(0, half);
176
+ var K2 = K.slice(half);
177
+ var V = ciphertextWithIv.slice(0, 16);
178
+ var ct = ciphertextWithIv.slice(16);
179
+ var pt = _aesCtr(K2, V, ct);
180
+ var Vcheck = _s2v(K1, associatedData || [], pt);
181
+ if (!nodeCrypto.timingSafeEqual(V, Vcheck)) {
182
+ throw new NtsError("nts/auth-failed", "AES-SIV authentication failed");
183
+ }
184
+ return pt;
185
+ }
186
+
187
+ function _negotiateAead(preferList) {
188
+ var defaultList = [AEAD_AES_SIV_CMAC_256, AEAD_CHACHA20_POLY1305];
189
+ var list = (preferList && preferList.length > 0) ? preferList : defaultList;
190
+ var body = Buffer.alloc(list.length * 2);
191
+ for (var i = 0; i < list.length; i++) body.writeUInt16BE(list[i], i * 2);
192
+ return body;
193
+ }
194
+
195
+ function _buildKeRequest(opts) {
196
+ var aeadBody = _negotiateAead(opts.aead);
197
+ var nextProto = _u16be(NTPV4_PROTOCOL_ID);
198
+ var records = [
199
+ _encodeRecord(true, REC_NEXT_PROTOCOL, nextProto),
200
+ _encodeRecord(true, REC_AEAD_ALGORITHM, aeadBody),
201
+ _encodeRecord(true, REC_END, Buffer.alloc(0)),
202
+ ];
203
+ return Buffer.concat(records);
204
+ }
205
+
206
+ function _exportKeys(socket, aeadId) {
207
+ var label = "EXPORTER-network-time-security";
208
+ var contextC2S = Buffer.from([0x00, 0x00, (aeadId >> 8) & 0xff, aeadId & 0xff, 0x00]);
209
+ var contextS2C = Buffer.from([0x00, 0x00, (aeadId >> 8) & 0xff, aeadId & 0xff, 0x01]);
210
+ var keyLen = aeadId === AEAD_AES_SIV_CMAC_256 ? 32 : 32;
211
+ var c2s = socket.exportKeyingMaterial(keyLen, label, contextC2S);
212
+ var s2c = socket.exportKeyingMaterial(keyLen, label, contextS2C);
213
+ return { c2s: c2s, s2c: s2c };
214
+ }
215
+
216
+ function performKeHandshake(opts) {
217
+ opts = opts || {};
218
+ validateOpts(opts, ["host", "port", "servername", "aead", "ca", "timeoutMs"], "nts.performKeHandshake");
219
+ if (typeof opts.host !== "string" || opts.host.length === 0) {
220
+ throw new NtsError("nts/bad-host", "nts.performKeHandshake: host required");
221
+ }
222
+ var timeoutMs = opts.timeoutMs || C.TIME.seconds(10);
223
+ return new Promise(function (resolve, reject) {
224
+ var settled = false;
225
+ function done(err, result) {
226
+ if (settled) return;
227
+ settled = true;
228
+ if (err) reject(err); else resolve(result);
229
+ }
230
+ var connectOpts = {
231
+ host: opts.host,
232
+ port: opts.port || NTS_KE_DEFAULT_PORT,
233
+ servername: opts.servername || opts.host,
234
+ ALPNProtocols: ["ntske/1"],
235
+ minVersion: "TLSv1.3",
236
+ ecdhCurve: C.TLS_GROUP_CURVE_STR,
237
+ };
238
+ if (opts.ca) connectOpts.ca = opts.ca;
239
+ var sock = tls.connect(connectOpts);
240
+ var timer = setTimeout(function () {
241
+ try { sock.destroy(); } catch (_e) {}
242
+ done(new NtsError("nts/ke-timeout", "NTS-KE handshake timed out after " + timeoutMs + "ms"));
243
+ }, timeoutMs);
244
+ timer.unref && timer.unref();
245
+ sock.on("error", function (e) {
246
+ clearTimeout(timer);
247
+ done(new NtsError("nts/ke-socket", "NTS-KE socket error: " + e.message));
248
+ });
249
+ sock.on("secureConnect", function () {
250
+ if (sock.alpnProtocol !== "ntske/1") {
251
+ clearTimeout(timer);
252
+ try { sock.destroy(); } catch (_e) {}
253
+ done(new NtsError("nts/bad-alpn",
254
+ "NTS-KE server did not negotiate ALPN 'ntske/1', got " + JSON.stringify(sock.alpnProtocol)));
255
+ return;
256
+ }
257
+ var req = _buildKeRequest(opts);
258
+ sock.write(req);
259
+ });
260
+ var got = Buffer.alloc(0);
261
+ var warnings = [];
262
+ sock.on("data", function (chunk) {
263
+ got = Buffer.concat([got, chunk]);
264
+ try {
265
+ var records = _decodeRecords(got);
266
+ var endRec = records.find(function (r) { return r.type === REC_END; });
267
+ if (!endRec) return;
268
+ clearTimeout(timer);
269
+ var errRec = records.find(function (r) { return r.type === REC_ERROR; });
270
+ if (errRec) {
271
+ try { sock.destroy(); } catch (_e) {}
272
+ done(new NtsError("nts/ke-error", "NTS-KE server returned error code " + errRec.body.readUInt16BE(0)));
273
+ return;
274
+ }
275
+ var warnRecs = records.filter(function (r) { return r.type === REC_WARNING; });
276
+ if (warnRecs.length > 0) {
277
+ warnings = warnRecs.map(function (r) {
278
+ return r.body.length >= 2 ? r.body.readUInt16BE(0) : null;
279
+ }).filter(function (v) { return v != null; });
280
+ }
281
+ var aeadRec = records.find(function (r) { return r.type === REC_AEAD_ALGORITHM; });
282
+ if (!aeadRec || aeadRec.body.length < 2) {
283
+ try { sock.destroy(); } catch (_e) {}
284
+ done(new NtsError("nts/no-aead", "NTS-KE response missing AEAD algorithm"));
285
+ return;
286
+ }
287
+ var aeadId = aeadRec.body.readUInt16BE(0);
288
+ if (aeadId !== AEAD_AES_SIV_CMAC_256 && aeadId !== AEAD_CHACHA20_POLY1305) {
289
+ try { sock.destroy(); } catch (_e) {}
290
+ done(new NtsError("nts/unsupported-aead", "NTS-KE server selected unsupported AEAD " + aeadId));
291
+ return;
292
+ }
293
+ var cookies = records.filter(function (r) { return r.type === REC_NEW_COOKIE; })
294
+ .map(function (r) { return r.body; });
295
+ if (cookies.length === 0) {
296
+ try { sock.destroy(); } catch (_e) {}
297
+ done(new NtsError("nts/no-cookies", "NTS-KE response contained no cookies"));
298
+ return;
299
+ }
300
+ var ntpServer = opts.host;
301
+ var ntpPort = NTPV4_DEFAULT_PORT;
302
+ var srvRec = records.find(function (r) { return r.type === REC_NTPV4_SERVER; });
303
+ if (srvRec) ntpServer = srvRec.body.toString("ascii");
304
+ var portRec = records.find(function (r) { return r.type === REC_NTPV4_PORT; });
305
+ if (portRec && portRec.body.length >= 2) ntpPort = portRec.body.readUInt16BE(0);
306
+ var keys = _exportKeys(sock, aeadId);
307
+ try { sock.end(); } catch (_e) {}
308
+ done(null, {
309
+ aeadId: aeadId,
310
+ c2sKey: keys.c2s,
311
+ s2cKey: keys.s2c,
312
+ cookies: cookies,
313
+ ntpServer: ntpServer,
314
+ ntpPort: ntpPort,
315
+ warnings: warnings,
316
+ });
317
+ } catch (e) {
318
+ clearTimeout(timer);
319
+ try { sock.destroy(); } catch (_e) {}
320
+ done(e);
321
+ }
322
+ });
323
+ });
324
+ }
325
+
326
+ function _encodeExtensionField(type, body) {
327
+ var padLen = (4 - (body.length % 4)) % 4;
328
+ var padded = padLen === 0 ? body : Buffer.concat([body, Buffer.alloc(padLen)]);
329
+ var hdr = Buffer.alloc(4);
330
+ hdr.writeUInt16BE(type, 0);
331
+ hdr.writeUInt16BE(padded.length + 4, 2);
332
+ return Buffer.concat([hdr, padded]);
333
+ }
334
+
335
+ function _aeadEncrypt(aeadId, key, nonce, plaintext, aad) {
336
+ if (aeadId === AEAD_AES_SIV_CMAC_256) {
337
+ var ad = aad ? [aad, nonce] : [nonce];
338
+ return aesSivEncrypt(key, plaintext, ad);
339
+ }
340
+ if (aeadId === AEAD_CHACHA20_POLY1305) {
341
+ var c = nodeCrypto.createCipheriv("chacha20-poly1305", key, nonce, { authTagLength: 16 });
342
+ if (aad) c.setAAD(aad, { plaintextLength: plaintext.length });
343
+ var ct = Buffer.concat([c.update(plaintext), c.final()]);
344
+ var tag = c.getAuthTag();
345
+ return Buffer.concat([ct, tag]);
346
+ }
347
+ throw new NtsError("nts/aead-unsupported", "aeadEncrypt: unsupported aead " + aeadId);
348
+ }
349
+
350
+ function _aeadDecrypt(aeadId, key, nonce, ciphertext, aad) {
351
+ if (aeadId === AEAD_AES_SIV_CMAC_256) {
352
+ var ad = aad ? [aad, nonce] : [nonce];
353
+ return aesSivDecrypt(key, ciphertext, ad);
354
+ }
355
+ if (aeadId === AEAD_CHACHA20_POLY1305) {
356
+ var ct = ciphertext.slice(0, ciphertext.length - 16);
357
+ var tag = ciphertext.slice(ciphertext.length - 16);
358
+ var d = nodeCrypto.createDecipheriv("chacha20-poly1305", key, nonce, { authTagLength: 16 });
359
+ if (aad) d.setAAD(aad, { plaintextLength: ct.length });
360
+ d.setAuthTag(tag);
361
+ return Buffer.concat([d.update(ct), d.final()]);
362
+ }
363
+ throw new NtsError("nts/aead-unsupported", "aeadDecrypt: unsupported aead " + aeadId);
364
+ }
365
+
366
+ function _nonceForAead(aeadId) {
367
+ if (aeadId === AEAD_AES_SIV_CMAC_256) return nodeCrypto.randomBytes(16);
368
+ return nodeCrypto.randomBytes(12);
369
+ }
370
+
371
+ function _walkExtensions(msg, startOff) {
372
+ var exts = [];
373
+ var off = startOff;
374
+ while (off + 4 <= msg.length) {
375
+ var t = msg.readUInt16BE(off);
376
+ var len = msg.readUInt16BE(off + 2);
377
+ if (len < 4 || off + len > msg.length) {
378
+ throw new NtsError("nts/bad-extension", "NTS extension length " + len + " at offset " + off + " exceeds buffer");
379
+ }
380
+ exts.push({ type: t, start: off, len: len, body: msg.slice(off + 4, off + len) });
381
+ off += len;
382
+ }
383
+ return exts;
384
+ }
385
+
386
+ function querySingle(opts) {
387
+ opts = opts || {};
388
+ validateOpts(opts, ["host", "port", "aeadId", "c2sKey", "s2cKey", "cookies", "timeoutMs"], "nts.querySingle");
389
+ if (!Buffer.isBuffer(opts.c2sKey) || opts.c2sKey.length === 0) {
390
+ throw new NtsError("nts/no-c2s-key", "nts.querySingle: c2sKey required (Buffer)");
391
+ }
392
+ if (!Buffer.isBuffer(opts.s2cKey) || opts.s2cKey.length === 0) {
393
+ throw new NtsError("nts/no-s2c-key", "nts.querySingle: s2cKey required (Buffer)");
394
+ }
395
+ var timeoutMs = opts.timeoutMs || C.TIME.seconds(5);
396
+ if (!Array.isArray(opts.cookies) || opts.cookies.length === 0) {
397
+ throw new NtsError("nts/no-cookies", "nts.querySingle: cookies array required");
398
+ }
399
+ return new Promise(function (resolve, reject) {
400
+ var sock = dgram.createSocket("udp4");
401
+ var settled = false;
402
+ function done(err, result) {
403
+ if (settled) return;
404
+ settled = true;
405
+ try { sock.close(); } catch (_e) {}
406
+ if (err) reject(err); else resolve(result);
407
+ }
408
+ var unique = nodeCrypto.randomBytes(32);
409
+ var cookie = opts.cookies[0];
410
+ var packet = Buffer.alloc(48);
411
+ packet[0] = 0x23;
412
+ var ext1 = _encodeExtensionField(EXTENSION_UNIQUE_IDENTIFIER, unique);
413
+ var ext2 = _encodeExtensionField(EXTENSION_NTS_COOKIE, cookie);
414
+ var aeadHeader = Buffer.concat([packet, ext1, ext2]);
415
+ var nonce = _nonceForAead(opts.aeadId);
416
+ var encrypted = _aeadEncrypt(opts.aeadId, opts.c2sKey, nonce, Buffer.alloc(0), aeadHeader);
417
+ var nonceLen = nonce.length;
418
+ var ctLen = encrypted.length;
419
+ var authBody = Buffer.alloc(4 + nonceLen + ctLen);
420
+ authBody.writeUInt16BE(nonceLen, 0);
421
+ authBody.writeUInt16BE(ctLen, 2);
422
+ nonce.copy(authBody, 4);
423
+ encrypted.copy(authBody, 4 + nonceLen);
424
+ var ext3 = _encodeExtensionField(EXTENSION_NTS_AUTHENTICATOR_AND_ENC, authBody);
425
+ var fullPacket = Buffer.concat([packet, ext1, ext2, ext3]);
426
+ var sendTimeMs = Date.now();
427
+ var timer = setTimeout(function () {
428
+ done(new NtsError("nts/timeout", "NTS query timed out after " + timeoutMs + "ms"));
429
+ }, timeoutMs);
430
+ timer.unref && timer.unref();
431
+ sock.on("error", function (e) {
432
+ clearTimeout(timer);
433
+ done(new NtsError("nts/socket", "NTS udp error: " + e.message));
434
+ });
435
+ sock.on("message", function (msg) {
436
+ clearTimeout(timer);
437
+ var receiveTimeMs = Date.now();
438
+ try {
439
+ if (msg.length < 48) {
440
+ done(new NtsError("nts/bad-reply", "NTS reply too short"));
441
+ return;
442
+ }
443
+ var exts;
444
+ try { exts = _walkExtensions(msg, 48); }
445
+ catch (e) { done(e); return; }
446
+ var uniqueExt = exts.find(function (e) { return e.type === EXTENSION_UNIQUE_IDENTIFIER; });
447
+ if (!uniqueExt || uniqueExt.body.length < 32 ||
448
+ !nodeCrypto.timingSafeEqual(uniqueExt.body.slice(0, 32), unique)) {
449
+ done(new NtsError("nts/unique-mismatch", "NTS reply unique-identifier mismatch (replay or spoof)"));
450
+ return;
451
+ }
452
+ var authExt = exts.find(function (e) { return e.type === EXTENSION_NTS_AUTHENTICATOR_AND_ENC; });
453
+ if (!authExt) {
454
+ done(new NtsError("nts/no-authenticator", "NTS reply missing AUTHENTICATOR_AND_ENC extension (server not authenticated — unverifiable)"));
455
+ return;
456
+ }
457
+ if (authExt.body.length < 4) {
458
+ done(new NtsError("nts/bad-authenticator", "NTS authenticator body truncated"));
459
+ return;
460
+ }
461
+ var replyNonceLen = authExt.body.readUInt16BE(0);
462
+ var replyCtLen = authExt.body.readUInt16BE(2);
463
+ if (4 + replyNonceLen + replyCtLen > authExt.body.length) {
464
+ done(new NtsError("nts/bad-authenticator", "NTS authenticator nonce+ct exceed body length"));
465
+ return;
466
+ }
467
+ var replyNonce = authExt.body.slice(4, 4 + replyNonceLen);
468
+ var replyCt = authExt.body.slice(4 + replyNonceLen, 4 + replyNonceLen + replyCtLen);
469
+ var aad = msg.slice(0, authExt.start);
470
+ var encryptedExtPlain;
471
+ try {
472
+ encryptedExtPlain = _aeadDecrypt(opts.aeadId, opts.s2cKey, replyNonce, replyCt, aad);
473
+ } catch (e) {
474
+ done(new NtsError("nts/auth-failed", "NTS authenticator AEAD verification failed: " + e.message));
475
+ return;
476
+ }
477
+ var newCookies = [];
478
+ if (encryptedExtPlain && encryptedExtPlain.length >= 4) {
479
+ var encExts;
480
+ try { encExts = _walkExtensions(encryptedExtPlain, 0); }
481
+ catch (_e) { encExts = []; }
482
+ for (var ei = 0; ei < encExts.length; ei++) {
483
+ if (encExts[ei].type === EXTENSION_NTS_COOKIE) {
484
+ newCookies.push(Buffer.from(encExts[ei].body));
485
+ }
486
+ }
487
+ }
488
+ if (newCookies.length > 0) {
489
+ opts.cookies.shift();
490
+ for (var ci = 0; ci < newCookies.length; ci++) opts.cookies.push(newCookies[ci]);
491
+ }
492
+ var ntpSeconds = msg.readUInt32BE(40);
493
+ var ntpFraction = msg.readUInt32BE(44);
494
+ var serverUnixSeconds = ntpSeconds - NTP_TO_UNIX_OFFSET_SECONDS;
495
+ var fracMs = Math.round(ntpFraction / 0x100000000 * 1000);
496
+ var serverTimeMs = serverUnixSeconds * 1000 + fracMs;
497
+ var midpointMs = sendTimeMs + (receiveTimeMs - sendTimeMs) / 2;
498
+ var driftMs = serverTimeMs - midpointMs;
499
+ done(null, {
500
+ driftMs: driftMs,
501
+ serverTimeMs: serverTimeMs,
502
+ server: opts.host,
503
+ authenticated: true,
504
+ newCookieCount: newCookies.length,
505
+ cookiesRemaining: opts.cookies.length,
506
+ });
507
+ } catch (e) {
508
+ done(new NtsError("nts/bad-reply", "NTS reply processing failed: " + e.message));
509
+ }
510
+ });
511
+ sock.send(fullPacket, 0, fullPacket.length, opts.port || NTPV4_DEFAULT_PORT, opts.host, function (err) {
512
+ if (err) {
513
+ clearTimeout(timer);
514
+ done(new NtsError("nts/send", "NTS send failed: " + err.message));
515
+ }
516
+ });
517
+ });
518
+ }
519
+
520
+ async function query(opts) {
521
+ opts = opts || {};
522
+ validateOpts(opts, ["host", "kePort", "ntpPort", "aead", "ca", "timeoutMs", "servername"], "nts.query");
523
+ var ke = await performKeHandshake({
524
+ host: opts.host,
525
+ port: opts.kePort,
526
+ servername: opts.servername,
527
+ aead: opts.aead,
528
+ ca: opts.ca,
529
+ timeoutMs: opts.timeoutMs,
530
+ });
531
+ var result = await querySingle({
532
+ host: ke.ntpServer,
533
+ port: opts.ntpPort || ke.ntpPort,
534
+ aeadId: ke.aeadId,
535
+ c2sKey: ke.c2sKey,
536
+ s2cKey: ke.s2cKey,
537
+ cookies: ke.cookies,
538
+ timeoutMs: opts.timeoutMs,
539
+ });
540
+ return Object.assign({}, result, { aeadId: ke.aeadId, cookieCount: ke.cookies.length });
541
+ }
542
+
543
+ module.exports = {
544
+ performKeHandshake: performKeHandshake,
545
+ querySingle: querySingle,
546
+ query: query,
547
+ aesSivEncrypt: aesSivEncrypt,
548
+ aesSivDecrypt: aesSivDecrypt,
549
+ AEAD_AES_SIV_CMAC_256: AEAD_AES_SIV_CMAC_256,
550
+ AEAD_CHACHA20_POLY1305: AEAD_CHACHA20_POLY1305,
551
+ NtsError: NtsError,
552
+ };