Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4810x 4810x 4746x 66x 64x 2321x 2321x 2321x 2321x 31x 31x 2321x 2321x 4283x 2290x 4302x 6314x 6314x 2031x 4283x 4283x 4283x 4283x 2290x 2290x 2271x 2271x 2271x 19x 2321x 884x 884x 884x 884x 884x 884x 884x 884x 884x 884x 884x 884x 884x 884x 884x 884x 1797x 36x 1797x 884x 693850x 2x 884x 3320x 3320x 3320x 60x 76x 38x 884x 1x 883x 883x 883x 689x 5178x 5178x 349x 349x 349x 349x 349x 349x 349x 349x 349x 698x 349x 5178x 5178x 5110x 5300x 122x 5178x 5178x 158x 5020x 12x 5008x 4828x 5000x 5008x 30x 4978x 30x 4948x 5252x 12x 5240x 5240x 196x 5044x 4948x 208x 4740x 2x 4738x 4738x 5040x 144x 4896x 29x 4867x 4565x 5178x 5178x 5178x 122x 5178x 2860x 2860x 2318x 2318x 4566x 4566x 4566x 4566x 4566x 4566x 3380x 1795x 1795x 26x 1795x 4566x 4566x 4566x 1x 4565x 4565x 18788x 4565x 4744x 4810x 4744x 64x 64x 64x 4565x 4565x 4774x 4680x 4774x 4774x 30x 30x 4744x 4744x 3601x 4565x 4565x 4565x 4565x 629x 629x 629x 629x 619x 629x 629x 258x 629x 629x 500x 629x 4565x 2798x 4565x 4838x 64x 4774x 106x 106x 4668x 4668x 4774x 91x 4774x 629x 4774x 4774x 4774x 4744x 4774x 4774x 4774x 4774x 3631x 3631x 4774x 4744x 38x 4706x 30x 4676x 4774x 4535x 132x 132x 4403x 4x 4x 21995x 21995x 4399x 26394x 28032x 28032x 18688x 28032x 28032x 16216x 8798x 9344x 9344x 108x 8690x 4399x 4399x 4399x 4399x 4399x 4399x 4399x 198994x 4399x 132x 4399x 4399x 4672x 284x 284x 284x 284x 4672x 4399x 4115x 4399x 91x 59x 59x 58x 59x 29x 59x 59x 29x 30x 29x 30x 4399x 4672x 4399x 4399x 4387x 30x 4357x 4357x 4357x 30x 30x 4327x 4327x 629x 629x 629x 629x 619x 629x 629x 258x 629x 629x 500x 629x 4565x 1072x 2x 2x 1x 1x 1x 1x 1070x 379x 379x 379x 379x 379x 379x 379x 1070x 1070x 1070x 1070x 1072x 1075x 3x 1072x 1072x 383x 383x 383x 3x 380x 380x 689x 1075x 31x 1075x 52x 31x 52x 1023x 96x 1075x 379x 1075x 882x 882x 882x 882x 882x 882x 820x 820x 255x 883x 1075x 877x 883x 883x 883x 883x 883x 7x 7x 7x 876x 883x 884x 884x 884x 1x 1x 883x 2649x 883x 883x 68x 68x 30x 883x 883x 883x 883x 883x 1091x 883x 883x 883x 883x 1075x 1070x 5x 883x 883x 883x 883x 36x 847x 883x 883x 272x 883x 24x 859x 883x 883x 882x 820x 62x 62x 63x 1x 939x 939x 60x 30x 30x 879x 879x 876x 3x 1x 613x 613x 613x 613x 613x 613x 994x 177150x 177014x 88388x 88388x 88387x 88626x 88626x 88626x 177150x 177150x 994x 596x 994x 892x 892x 88524x 994x 994x 1x 1x 640x 640x 788x 788x 640x 1x 71x 1x 1x 1x | /*eslint-env node */
/**
* Centro server class
* @module centro-js/lib/server
*/
"use strict";
var crypto = require('crypto'),
async = require('async'),
frame = require('frame-stream'),
EventEmitter = require('events').EventEmitter,
util = require('util'),
QlobberFSQ = require('qlobber-fsq').QlobberFSQ,
MQlobberServer = require('mqlobber').MQlobberServer,
AccessControl = require('mqlobber-access-control').AccessControl,
server_config = require('./server_config'),
in_mem_transport = require('./server_transports/in-mem'),
Ajv = require('ajv');
exports.version = require('./version');
var max_settimeout = Math.pow(2, 31) - 1;
function schedule(t, update, f)
{
var now = new Date().getTime();
if (t > now)
{
update(setTimeout(function ()
{
schedule(t, update, f);
}, Math.min(t - now, max_settimeout)));
}
else
{
update(setTimeout(f, 0));
}
}
function read_frame(config, s, cb)
{
var in_stream = frame.decode(config);
function cleanup()
{
s.removeListener('end', end);
s.removeListener('close', end);
s.removeListener('readable', onread);
}
function end()
{
cleanup();
cb(new Error('ended before frame'));
}
s.on('end', end);
s.on('close', end);
function done(v)
{
if (v)
{
throw v;
}
}
function onread()
{
while (true) //eslint-disable-line no-constant-condition
{
/*jshint validthis: true */
var data = this.read();
if (data === null)
{
break;
}
var buffer = in_stream.buffer;
try
{
in_stream.push = done;
in_stream._transform(data, null, done);
}
catch (v)
{
cleanup();
if (v instanceof Buffer)
{
var rest = buffer ? Buffer.concat([buffer, data]) : data;
s.unshift(rest.slice(in_stream.opts.lengthSize + v.length));
return cb(null, v);
}
cb(v);
}
}
}
s.on('readable', onread);
}
/**
* Create a server which publishes and subscribes to messages on behalf of
* clients.
*
* @class
* @extends events.EventEmitter
*
* @param {Object} config - Configuration options. This supports all the options supported by {@link https://github.com/davedoesdev/mqlobber#mqlobberserverfsq-stream-options|MQlobberServer} and {@link https://github.com/davedoesdev/mqlobber-access-control#accesscontroloptions|AccessControl} as well as the following:
* @param {string|Object} [config.transport] - Specifies which transport to load into the server. This should be either the transport's name or its configuration, with its name in the `server` property.
* @param {(string|Object)[]} [config.transports] - Specifies multiple transports to load into the server.
* @param {Function} [config.authorize] - Function for creating an object which can authorize {@link http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html|JSON Web Tokens} presented by clients. Defaults to {@link https://github.com/davedoesdev/authorize-jwt#moduleexportsconfig-cb|authorize-jwt}. If you supply your own, it must comply with authorize-jwt's API. `authorize_config` or `config` is passed as the first argument.
* @param {Object} [config.authorize_config] - Configuration specific to `config.authorize`.
* @param {string[]} config.allowed_algs - Which JWT algorithms are allowed. Clients which present tokens which aren't signed with one of these algorithms are rejected. You must supply this list.
* @param {boolean} [config.privileged=false] - If true, clients can see messages from all token issuers. If false (the default), a client can only see messages sent by another client if they were both authorized using a token with the same issuer. You can make clients on individual transports privileged by setting this property in their transport-specific config (`config.transports[X].config.privileged`).
* @param {QlobberFSQ|QlobberPG} [config.fsq] - {@link https://github.com/davedoesdev/qlobber-fsq#qlobberfsqoptions|QlobberFSQ} or {@link https://rawgit-now.davedoesdev.now.sh/davedoesdev/qlobber-pg/master/docs/index.html#qlobberpg|QlobberPG} instance for handling messages. Defaults to a new instance of `QlobberFSQ`, passing `fsq_config` or `config` to the constructor.
* @param {Object} [config.fsq_config] - Configuration specific to `config.fsq`.
* @param {string} [config.realm=centro] - When authorization of a client fails, the transport is given information it can (optionally) use when rejecting the connection. This includes a HTTP authentication header specifying this realm.
* @param {string} [config.auth_method=Bearer] - When authorization of a client fails, the transport is given information it can (optionally) use when rejecting the connection. This includes a HTTP authentication header specifying this authentication method. Note that the client can opt to use Bearer or Basic authentication regardless of this setting.
* @param {integer} [config.max_tokens=10] - Maximum number of authorization tokens each client is allowed to present.
* @param {integer} [config.max_token_length=1MiB] - Maximum size of authorization token each client is allowed to present.
* @param {integer} [config.max_topic_length=4KiB] - Maximum length of topics the client can specify, in subscription and publish requests and in the authorization token.
* @param {integer} [config.max_issuer_length=128] - Maximum length of the `iss` claim in authorization tokens.
* @param {integer} [config.max_subscribe_topics=1000] - Maximum number of topics that `subscribe` claims in authorization tokens can contain. These claims specify to which topics client which present them are pre-subscribed.
* @param {integer} [config.max_allow_publish_topics=1000] - Maximum number of topics that `access_control.publish.allow` claims in authorization tokens can contain. These claims are passed to {@link https://github.com/davedoesdev/mqlobber-access-control#accesscontroloptions|AccessControl} and specify to which topics clients which present them can publish messages.
* @param {integer} [config.max_disallow_publish_topics=1000] - Maximum number of topics that `access_control.publish.disallow` claims in authorization tokens can contain. These claims are passed to {@link https://github.com/davedoesdev/mqlobber-access-control#accesscontroloptions|AccessControl} and specify to which topics clients which present them cannot publish messages.
* @param {integer} [config.max_allow_subscribe_topics=1000] - Maximum number of topics that `access_control.subscribe.allow` claims in authorization tokens can contain. These claims are passed to {@link https://github.com/davedoesdev/mqlobber-access-control#accesscontroloptions|AccessControl} and specify to which topics clients which present them cannot subscribe.
* @param {integer} [config.max_disallow_subscribe_topics=1000] - Maximum number of topics that `access_control.subscribe.disallow` claims in authorization tokens can contain. These claims are passed to {@link https://github.com/davedoesdev/mqlobber-access-control#accesscontroloptions|AccessControl} and specify to which topics clients which present them cannot subscribe.
* @param {integer} [config.max_block_topics=1000] - Maximum number of topics that `access_control.block` claims in authorization tokens can contain. These claims are passed to {@link https://github.com/davedoesdev/mqlobber-access-control#accesscontroloptions|AccessControl} and specify which messages aren't delivered to clients which present them.
* @param {integer} [config.max_presence_data_length=1MiB] - Maximum length of `presence.connect.data` and `presence.disconnect.data` claims in authorization tokens can contain. The `presence` claims specify messages to send when clients which present them connect and disconnect.
*/
function CentroServer(config)
{
EventEmitter.call(this);
/**
* {@link https://github.com/davedoesdev/qlobber-fsq#qlobberfsqoptions|QlobberFSQ} or {@link https://rawgit-now.davedoesdev.now.sh/davedoesdev/qlobber-pg/master/docs/index.html#qlobberpg|QlobberPG} instance being used to handle messages.
*
* @member {QlobberFSQ|QlobberPG}
*/
this.fsq = null;
/**
* Operations you can perform on transports you specified when constructing {@link centro-js/lib/server.CentroServer|CentroServer}. Transports can define their own operations in addition to `close`. Indexable by position or transport name.
*
* @member {{close: centro-js/lib/server.closeCallback}[]}
*/
this.transport_ops = null;
config = server_config.config_with_defaults(config);
var ajv = new Ajv();
var validate = ajv.compile(server_config.authz_token_schema(
config, ['iss', 'access_control']));
this.transport_ops = [];
this._pending_authz_destroys = new Set();
this._connections = new Map();
this._connids = new Map();
this._config = config;
this._closing = false;
this._closed = false;
this._close_cb = null;
this._ready = false;
var ths = this,
separator;
function error(err)
{
/*jshint validthis: true */
if (err)
{
ths.emit('error', err, this);
}
return err;
}
this._error = error;
function warning(err)
{
/*jshint validthis: true */
if (err && !ths.emit('warning', err, this))
{
console.error(err); //eslint-disable-line no-console
}
}
this._warning = warning;
function change(uri, rev)
{
warning(new Error('uri revision change: ' + uri));
var conns = ths._connections.get(uri);
if (conns !== undefined)
{
for (var conn of conns)
{
if (conn.rev !== rev)
{
// Remove while iterating on ES6 Sets is consistent
conn.destroy();
}
}
}
}
function authorize(err, default_authz)
{
if (error(err))
{
return;
}
default_authz.keystore.on('change', change);
var transports = config.transports || config.transport;
if ((typeof transports === 'string') ||
(typeof transports[Symbol.iterator] !== 'function'))
{
transports = [transports];
}
function run_transport(config, authz, transport, name, authz_to_close, next)
{
function transport_authorize(obj, destroy, onclose, cb2)
{
var authz_ended = false;
function cb(err, handshakes, tokens)
{
// Note: all calls to cb result in err.authz_error === true
if (err && !obj.url)
{
var hsdata = Buffer.from(JSON.stringify(
{
error: err.message,
version: exports.version
}));
// bpmux _send_handshake
var buf = Buffer.alloc(1 + 4 + 4 + hsdata.length);
buf.writeUInt8(1, 0, true);
buf.writeUInt32BE(0, 1, true);
buf.writeUInt32BE(0, 5, true);
hsdata.copy(buf, 9);
// write frame
var out_stream = frame.encode(config);
out_stream._pushFrameData = function (bufs)
{
for (var buf of bufs)
{
obj.write(buf);
}
};
out_stream.end(buf);
}
ths.emit('authz_end', err, handshakes, tokens, obj, config);
if (ths._pending_authz_destroys.delete(destroy))
{
cb2(err, handshakes, tokens);
}
}
function got_tokens(err, tokens)
{
if (authz_ended)
{
return;
}
authz_ended = true;
if (err)
{
return cb(ths._authz_error(err));
}
if (tokens === undefined)
{
return cb(ths._authz_error('tokens missing'));
}
if (typeof tokens === 'string')
{
tokens = tokens.split(',').filter(function (t)
{
return t;
});
}
if (tokens.length === 0)
{
return cb(ths._authz_error('no tokens'));
}
if (config.max_tokens && (tokens.length > config.max_tokens))
{
return cb(ths._authz_error('too many tokens'));
}
async.mapSeries(tokens, async.ensureAsync(function (token, cb)
{
if (config.max_token_length && (token.length > config.max_token_length))
{
return cb(new Error('token too long'));
}
authz.authorize(token, config.allowed_algs, function (err, payload, uri, rev)
{
if (err)
{
return cb(err);
}
cb(null,
{
payload: payload,
uri: uri,
rev: rev
});
});
}), function (err, handshakes)
{
if (err)
{
return cb(ths._authz_error(err));
}
if (config.privileged && handshakes.length > 1)
{
return cb(ths._authz_error('too many privileged tokens'));
}
var uris = new Set();
for (var hs of handshakes)
{
if (!validate(hs.payload))
{
return cb(ths._authz_error(ajv.errorsText(validate.errors)));
}
if (uris.has(hs.uri))
{
return cb(ths._authz_error('duplicate URI: ' + hs.uri));
}
uris.add(hs.uri);
}
cb(null, handshakes, tokens);
});
}
obj.on('error', warning);
ths._pending_authz_destroys.add(destroy);
ths.emit('authz_start', function (err)
{
got_tokens(err || new Error('cancelled'));
}, onclose, obj, config);
if (obj.url)
{
authz.get_authz_data(obj, function (err, info, tokens)
{
got_tokens(err, tokens);
});
}
else
{
read_frame(config, obj, function (err, v)
{
got_tokens(err, err ? undefined : v.toString());
});
}
}
function transport_connected(handshakes, stream, destroy, onclose)
{
stream.on('error', warning);
var connid,
mqserver,
hs_conns = new Set(),
presence = new Map(),
ack_prefixes = new Map(),
closed = false,
destroyed = false;
function dstroy(now)
{
if (!destroyed && !closed)
{
try
{
dstroy.destroy(mqserver, now);
}
catch (ex)
{
warning(ex);
}
destroyed = true;
}
}
// for testing
dstroy.destroy = destroy;
dstroy.stream = stream;
if (ths._closing)
{
return dstroy();
}
do
{
connid = crypto.randomBytes(32).toString('hex');
}
while (ths._connids.has(connid));
function replace(topic)
{
return topic.split('${self}').join(connid);
}
ths._connids.set(connid, dstroy);
function make_update(conn)
{
return function (timeout)
{
conn.timeout = timeout;
};
}
function make_destroy(conn)
{
return function ()
{
conn.timeout = null;
ths.emit('expired', connid);
dstroy();
};
}
function conn_closed()
{
closed = true;
for (var conn of hs_conns)
{
if (conn.timeout)
{
clearTimeout(conn.timeout);
}
var conns = ths._connections.get(conn.uri);
if (conns === undefined)
{
warning(new Error('unknown uri on closed connection: ' + conn.uri));
continue;
}
conns.delete(conn);
if (conns.size === 0)
{
ths._connections.delete(conn.uri);
}
}
hs_conns.clear();
ths._connids.delete(connid);
ths.emit('disconnect', connid);
for (var entry of presence)
{
var prefix = entry[0],
p = entry[1],
options = {};
if (!config.privileged)
{
prefix += separator;
}
options.single = p.disconnect.single;
if (p.disconnect.ttl !== undefined)
{
options.ttl = Math.min(
options.single ? ths.fsq._single_ttl : ths.fsq._multi_ttl,
p.disconnect.ttl * 1000);
}
var s = ths.fsq.publish(prefix + replace(p.disconnect.topic), options);
if (p.disconnect.data !== undefined)
{
s.write(replace(p.disconnect.data));
}
s.end();
}
if (ths._connids.size === 0)
{
ths.emit('empty');
}
}
onclose(conn_closed);
function process_handshake(hs, cb)
{
if (closed)
{
return cb(new Error('closed'));
}
var prefix;
if (config.privileged)
{
prefix = '';
hs.prefix = prefix;
}
else
{
// Ensure issuer has no separators
prefix = crypto.createHash('sha256')
.update(hs.payload.iss)
.digest('hex');
hs.prefix = prefix + separator;
}
if (hs.payload.ack)
{
ack_prefixes.set(prefix, hs.payload.ack.prefix);
}
if (hs.payload.presence)
{
presence.set(prefix, hs.payload.presence);
}
var conn = {
destroy: dstroy
};
hs_conns.add(conn);
if (hs.payload.exp !== undefined)
{
schedule(hs.payload.exp * 1000,
make_update(conn),
make_destroy(conn));
}
conn.uri = hs.uri;
conn.rev = hs.rev;
var conns = ths._connections.get(hs.uri);
if (conns === undefined)
{
conns = new Set();
ths._connections.set(hs.uri, conns);
}
conns.add(conn);
function got_pub_key(err, pub_key, issuer_id, rev)
{
if (err)
{
return cb(err);
}
if (hs.rev !== rev)
{
return cb(new Error('uri revision has changed: ' + hs.uri));
}
cb();
}
authz.keystore.get_pub_key_by_uri(hs.uri, got_pub_key);
}
function processed_handshakes(err)
{
if (err)
{
warning(err);
return dstroy();
}
if (closed)
{
warning(new Error('closed'));
return;
}
function AggregateTopics(action, type)
{
this.action = action;
this.type = type;
}
AggregateTopics.prototype[Symbol.iterator] = function* ()
{
for (var hs of handshakes)
{
var topics = hs.payload.access_control[this.action];
if (this.type)
{
topics = topics[this.type];
}
topics = topics || [];
for (var topic of topics)
{
yield hs.prefix + replace(topic);
}
}
};
function aggregate_bool(action, type, dflt)
{
for (var hs of handshakes)
{
var b = !!hs.payload.access_control[action][type];
if (b !== dflt)
{
return b;
}
}
return dflt;
}
var access_control = new AccessControl(
{
publish: {
allow: new AggregateTopics('publish', 'allow'),
disallow: new AggregateTopics('publish', 'disallow'),
disallow_single: aggregate_bool('publish', 'disallow_single', false),
disallow_multi: aggregate_bool('publish', 'disallow_multi', false),
max_data_length: config.max_publish_data_length,
max_publications: config.max_publications
},
subscribe: {
allow: new AggregateTopics('subscribe', 'allow'),
disallow: new AggregateTopics('subscribe', 'disallow'),
max_subscriptions: config.max_subscriptions
},
block: new AggregateTopics('block'),
max_topic_length:
config.max_topic_length === undefined ? undefined :
config.privileged ? config.max_topic_length :
(65 + config.max_topic_length)
});
var mqconfig = config.mqlobber || config;
mqserver = new MQlobberServer(
ths.fsq,
stream,
stream._no_keep_alive ?
Object.assign({ keep_alive: false }, mqconfig) :
mqconfig);
mqserver.on('error', warning);
mqserver.on('warning', warning);
access_control.attach(mqserver);
mqserver.on('backoff', function ()
{
warning.call(this, new Error('backoff'));
});
mqserver.on('full', function ()
{
warning.call(this, new Error('full'));
});
var subscriptions = [], subscribed = false;
for (var hs of handshakes)
{
if (hs.payload.subscribe)
{
for (var topic in hs.payload.subscribe)
{
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(hs.payload.subscribe, topic))
{
mqserver.subscribe(hs.prefix + replace(topic),
{
subscribe_to_existing: hs.payload.subscribe[topic]
});
subscribed = true;
}
}
}
subscriptions.push(hs.payload.subscribe || {});
}
if (!subscribed)
{
subscriptions = undefined;
}
if (ack_prefixes.size > 0)
{
mqserver.on('ack', function (info)
{
var pos = -1, prefix = '';
if (!config.privileged)
{
pos = info.topic.indexOf(separator);
}
if (pos >= 0)
{
prefix = info.topic.substr(0, pos);
}
var ack_prefix = ack_prefixes.get(prefix);
if (ack_prefix === undefined)
{
return warning(new Error('unknown prefix on ack topic: ' + info.topic));
}
if (!config.privileged)
{
prefix += separator;
}
ths.fsq.publish(prefix +
replace(ack_prefix) +
info.topic.substr(pos + 1))
.end();
});
}
var prefixes = handshakes.map(function (hs)
{
return hs.prefix;
});
ths.emit('pre_connect',
{
mqserver: mqserver,
access_control: access_control,
connid: connid,
prefixes: prefixes,
subscriptions: subscriptions,
destroy: dstroy,
onclose: onclose,
token_infos: handshakes
});
mqserver.on('handshake', function (hsdata, delay)
{
if (hsdata.length < 4)
{
return warning(new Error('short handshake'));
}
delay()(Buffer.from(JSON.stringify(
{
self: connid,
prefixes: prefixes,
subscriptions: subscriptions,
version: exports.version
})));
var client_version = hsdata.readUInt32BE(0, true);
if (client_version !== exports.version)
{
warning(new Error('unsupported version: ' + client_version));
return dstroy();
}
ths.emit('connect', connid, hsdata.slice(4));
for (var entry of presence)
{
var prefix = entry[0],
p = entry[1],
options = {};
if (!config.privileged)
{
prefix += separator;
}
options.single = p.connect.single;
if (p.connect.ttl !== undefined)
{
options.ttl = Math.min(
options.single ? ths.fsq._single_ttl : ths.fsq._multi_ttl,
p.connect.ttl * 1000);
}
var s = ths.fsq.publish(prefix + replace(p.connect.topic), options);
if (p.connect.data !== undefined)
{
s.write(replace(p.connect.data));
}
s.end();
}
});
}
async.eachSeries(handshakes,
async.ensureAsync(process_handshake),
processed_handshakes);
}
function transport_ready(err, ops)
{
if (err)
{
warning(err);
if (authz_to_close)
{
return authz_to_close.close(function (err2)
{
warning(err2);
next(err);
});
}
return next(err);
}
if (authz_to_close)
{
var close = ops.close;
ops.close = function (cb)
{
authz_to_close.close(function (err2)
{
warning(err2);
close(function (err3)
{
warning(err3);
cb(err2 || err3);
});
});
};
}
ops.authz = authz;
ops.name = name;
ths.emit('transport_ready', config, ops);
return next(null, ops);
}
transport(config,
transport_authorize,
transport_connected,
transport_ready,
error,
warning);
}
function start_transport2(transport, next)
{
if (typeof transport === 'function')
{
run_transport(config, default_authz, transport, null, null, next);
}
else
{
var tconfig = Object.assign({}, config, transport.config);
if (transport.authorize_config)
{
var aconfig = Object.assign({}, tconfig, transport.authorize_config);
aconfig.authorize(aconfig, function (err, authz)
{
if (err)
{
return next(err);
}
authz.keystore.on('change', change);
run_transport(tconfig, authz, transport.server, transport.name, authz, next);
});
}
else
{
run_transport(tconfig, default_authz, transport.server, transport.name, null, next);
}
}
}
function start_transport(transport, next)
{
if (typeof transport === 'string')
{
transport = { server: transport };
}
if (typeof transport.server === 'string')
{
if (transport.name === undefined)
{
transport.name = transport.server;
}
transport.server = CentroServer.load_transport(transport.server);
}
else if (transport === in_mem_transport)
{
transport = { server: transport };
}
if (transport.server === in_mem_transport)
{
transport.authorize_config = Object.assign(
{
db_type: 'in-mem'
}, transport.authorize_config);
}
if (!ths.fsq)
{
var fconfig = Object.assign({}, config, config.fsq_config);
ths.fsq = config.fsq || new QlobberFSQ(fconfig);
ths.fsq.on('warning', warning);
ths.fsq.on('error', error);
separator = ths.fsq._matcher._separator;
if (!ths.fsq.initialized)
{
return ths.fsq.on('start', function ()
{
start_transport2(transport, next);
});
}
}
start_transport2(transport, next);
}
function transports_started(err, transport_ops)
{
for (var ops of transport_ops)
{
if (ops && ops.name !== undefined)
{
transport_ops[ops.name] = ops;
}
}
ths.transport_ops = transport_ops;
ths.authz = default_authz;
process.nextTick(function ()
{
ths._ready = !error(err);
if (ths._close_cb || err)
{
var close_cb = ths._close_cb;
ths._close_cb = null;
return ths._close(close_cb);
}
ths.emit('ready');
});
}
async.mapSeries(transports,
async.ensureAsync(start_transport),
transports_started);
}
process.nextTick(function ()
{
var aconfig = Object.assign({}, config, config.authorize_config);
config.authorize(aconfig, authorize);
});
}
util.inherits(CentroServer, EventEmitter);
CentroServer.prototype._close = function (cb)
{
var ths = this;
function set_cb(f)
{
cb = f || function () {};
}
set_cb(cb);
function close_transports(err)
{
for (var destroy of ths._pending_authz_destroys)
{
try
{
destroy(true);
}
catch (ex)
{
ths._warning(ex);
}
}
ths._pending_authz_destroys.clear();
function cont(cb2)
{
set_cb(cb2);
var closed = false,
transport_ops = ths.transport_ops;
ths.transport_ops = [];
function check()
{
if (closed && (ths._connids.size === 0))
{
ths._closed = true;
ths.emit('close');
cb();
}
}
async.each(transport_ops, async.ensureAsync(function (ops, cb)
{
if (ops)
{
return ops.close(cb);
}
cb();
}), function (err)
{
function cont2(cb2)
{
set_cb(cb2);
closed = true;
check();
}
if (err)
{
return cb(err, cont2);
}
cont2(cb);
});
ths.once('empty', check);
for (var dstroy of ths._connids.values())
{
// Remove while iterating on ES6 Maps is consistent
dstroy(true);
}
}
if (err)
{
return cb(err, cont);
}
cont(cb);
}
function close_authz()
{
ths.authz.close(close_transports);
}
if (this.fsq)
{
if (!this._config.fsq)
{
return this.fsq.stop_watching(close_authz);
}
this.fsq.removeListener('warning', this._warning);
this.fsq.removeListener('error', this._error);
}
close_authz();
};
/**
* Close the server.
*
@param {centro-js/lib/server.closeCallback} cb - Called when the server has been closed.
*/
CentroServer.prototype.close = function (cb)
{
cb = cb || function () {};
if (this._closing)
{
if (this._closed)
{
return cb();
}
return this.once('close', cb);
}
this._closing = true;
if (this._ready)
{
return this._close(cb);
}
this._close_cb = cb;
};
CentroServer.prototype._authz_error = function (err)
{
err = new Error(err.message || String(err));
err.statusCode = 401;
err.authenticate = this._config.auth_method +
' realm="' + this._config.realm + '"';
err.authz_error = true;
this._warning(err);
return err;
};
function pipeline(obj, evname, handler)
{
var def_evname = 'default_' + evname + '_handler', handlers;
function next(i, orig_arguments)
{
var f = function ()
{
// Note: must be synchronous call to next because handlers may
// be setting up pipes and the pipe chain must be set up before
// the first reads data.
var h;
if (i === handlers.length)
{
h = obj[def_evname];
if (h)
{
h.apply(obj, arguments);
}
}
else
{
h = handlers[i];
var args = Array.prototype.slice.call(arguments);
h.apply(obj, args.concat(next(i + 1, orig_arguments)));
}
};
f.orig_arguments = orig_arguments;
return f;
}
if (!obj.centro_pipeline_handlers)
{
obj.centro_pipeline_handlers = new Map();
}
if (!obj.centro_pipeline_handlers.has(evname))
{
obj.centro_pipeline_handlers.set(evname, []);
obj.on(evname, function ()
{
next(0, arguments).apply(this, arguments);
});
}
handlers = obj.centro_pipeline_handlers.get(evname);
handlers.push(handler);
}
CentroServer.prototype.pipeline = pipeline;
/**
* Attach an extension to the server.
*
* @param {Object} ext - Extension to attach.
* @param {Object} [config] - Configuration to pass to the extension.
*/
CentroServer.prototype.attach_extension = function (ext, config)
{
ext = ext.call(this, config);
for (var ev in ext)
{
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(ext, ev))
{
this.on(ev, ext[ev]);
}
}
return ext; // for testing
};
CentroServer.load_transport = function (name)
{
return require('./server_transports/' + name);
};
exports.CentroServer = CentroServer;
exports.read_frame = read_frame;
exports.pipeline = pipeline;
/*eslint-disable no-unused-vars */
/**
* Callback type for server or transport close.
*
* @callback closeCallback
* @memberof centro-js/lib/server
* @param {?Error} err - Error, if one occurred.
*/
/* istanbul ignore next */
exports._closeCallback = function (err) {};
/**
* Callback type for cancelling authorization.
*
* @callback cancelCallback
* @memberof centro-js/lib/server
* @param {?Error} err - Error which led to cancelling the authorization, if available.
*/
/* istanbul ignore next */
exports._cancelCallback = function (err) {};
/**
* Callback type for registering close handler.
*
* @callback oncloseCallback
* @memberof centro-js/lib/server
* @param {centro-js/lib/server.closeCallback} cb - Called when close completes.
*/
/* istanbul ignore next */
exports._oncloseCallback = function (cb) {};
/** Callback type for closing a connection.
*
* @callback destroyCallback
* @memberof centro-js/lib/server
*/
/* istanbul ignore next */
exports._destroyCallback = function () {};
/**
* Ready event. Emitted when the server is ready to accept connections.
*
* @event CentroServer#ready
* @memberof centro-js/lib/server
*/
/* istanbul ignore next */
exports._ready_event = function () {};
/**
* Transport ready event. Emitted when an individual transport has been loaded
* and is ready to accept connections.
*
* @event CentroServer#transport_ready
* @memberof centro-js/lib/server
* @param {Object} config - Configuration you gave to the transport when constructing {@link centro-js/lib/server.CentroServer|CentroServer}.
* @param {Object} ops - Operations you can perform on the transport, including:
* @param {centro-js/lib/server.closeCallback} close - Close the transport.
*
*/
/* istanbul ignore next */
exports._transport_ready_event = function (config, ops) {};
/**
* Authorization start event. This is the first event emitted when a client
* connects.
*
* @event CentroServer#authz_start
* @memberof centro-js/lib/server
* @param {centro-js/lib/server.cancelCallback} cancel - Call this to cancel authorization.
* @param {centro-js/lib/server.oncloseCallback} onclose - Call this to register a handler when the connection is closed.
* @param {Object} obj - What's being authorized. This is either a HTTP request (with a `url` property) or a stream.
* @param {Object} config - Configuration you gave to the transport when constructing {@link centro-js/lib/server.CentroServer|CentroServer}.
*/
/* istanbul ignore next */
exports._authz_start_event = function (cancel, onclose, obj, config) {};
/**
* Authorization end event. Emitted when a client has been accepted or rejected.
*
* @event CentroServer#authz_end
* @memberof centro-js/lib/server
* @param {?Object} err - `null` if client was accepted otherwise cause of rejection.
* @param {{payload: Object, uri: string, rev: rev}[]} [token_infos] - For each authorization token the client presented, its payload, issuer URI and public key revision (see {@link https://github.com/davedoesdev/authorize-jwt|authorize-jwt}).
* @param {{string}[]} [tokens] - The raw authorization tokens.
* @param {Object} [obj] - What was authorized. This is either a HTTP request (with a `url` property) or a stream.
* @param {Object} [config] - Configuration you gave to the transport when constructing {@link centro-js/lib/server.CentroServer|CentroServer}.
*/
/* istanbul ignore next */
exports._authz_end_event = function (err, handshakes, tokens, obj, config) {};
/**
* Pre-connect event. Emitted after {@link centro-js/lib/server.event:CentroServer#authz_end|authz_end}
* but before {@link centro-js/lib/server.event:CentroServer#connect|connect}. The client connection
* has been authorized but handshake data has not yet been received.
*
* @event CentroServer#pre_connect
* @memberof centro-js/lib/server
* @param {Object} info - Information about the connection.
* @param {MQlobberServer} info.mqserver - {@link https://github.com/davedoesdev/mqlobber#mqlobberserverfsq-stream-options|MQlobberServer} object managing the connection.
* @param {AccessControl} info.access_control - {@link https://github.com/davedoesdev/mqlobber-access-control#accesscontroloptions|AccessControl} object enforcing access control on the connection.
* @param {string} info.connid - Unique ID for the connection.
* @param {string[]} info.prefixes - For each authorization token the client presented, a prefix which `info.access_control` enforces on topics. The prefix is a hash of the token's issuer ID, thus preventing clients with tokens from different issuers sending and receiving messages to each other. That is, messages are 'scoped' by token issuer.
* @param {{Object.<string, boolean>}[]} info.subscriptions - A list of topics to which the client is pre-subscribed, along with whether whether existing messages will be delivered to it.
* @param {centro-js/lib/server.destroyCallback} info.destroy - Call this to close the connection.
* @param {centro-js/lib/server.oncloseCallback} info.onclose - Call this to register a handler when the connection is closed.
* @param {{payload: Object, uri: string, rev: rev}[]} info.token_infos - For each authorization token the client presented, its payload, issuer URI and public key revision (see {@link https://github.com/davedoesdev/authorize-jwt|authorize-jwt}).
*/
/* istanbul ignore next */
exports._pre_connect_event = function (info) {};
/**
* Connect event. Emitted when handshake data has been received on a connection.
*
* @event CentroServer#connect
* @memberof centro-js/lib/server
* @param {Buffer} hsdata - Handshake received from the client.
*/
/* istanbul ignore next */
exports._connect_event = function (connid, hsdata) {};
/**
* Disconnect event. Emitted when a client disconnects.
*
* @event CentroServer#disconnect
* @memberof centro-js/lib/server
* @param {string} connid - Unique ID for the connection.
*/
/* istanbul ignore next */
exports._disconnect_event = function (connid) {};
/**
* Expired event. Emitted when a token presented by a client expires whilst it
* is connected. After the event is emitted, the connection is destroyed.
*
* @event CentroServer#expired
* @memberof centro-js/lib/server
* @param {string} connid - Unique ID for the connection.
*/
/* istanbul ignore next */
exports._expired_event = function (connid) {};
/**
* Empty event. Emitted when a client disconnects and there are no other
* clients connected.
*
* @event CentroServer#empty
* @memberof centro-js/lib/server
*/
/* istanbul ignore next */
exports._empty_event = function () {};
/**
* Close event. Emitted when the server has been closed (see {@link centro-js/lib/server.CentroServer#close|close}).
*
* @event CentroServer#close
* @memberof centro-js/lib/server
*/
/* istanbul ignore next */
exports._close_event = function () {};
/**
* Error event.
*
* @event CentroServer#error
* @memberof centro-js/lib/server
* @param {Object} err - The error which occurred.
* @param {Object} obj - The object which originally raised the error.
*/
/* istanbul ignore next */
exports._error_event = function (err, obj) {};
/**
* Warning event. If you don't listen to this event then the error is printed
* to `console.error`.
*
* @event CentroServer#warning
* @memberof centro-js/lib/server
* @param {Object} err - The non-fatal error which occurred.
* @param {Object} obj - The object which originally raised the error.
*/
/* istanbul ignore next */
exports._warning_event = function (err, obj) {};
|