-
Notifications
You must be signed in to change notification settings - Fork 1
/
webhub.js
1654 lines (1335 loc) · 42.7 KB
/
webhub.js
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
// Arena Web Hub with support for JWT, HTTPS, Server-Sent Events and WebSockets
console.log('starting arena ...');
var HTTPS = require("https"),
URL = require('url'),
PATH = require('path'),
FS = require('fs'),
HASHES = require('jshashes');
/*
server_options provide localhost a key and certificate as created using:
openssl req -newkey rsa:2048 -x509 -nodes -keyout privkey.pem -new \
-out fullchain.pem -subj /CN=localhost -reqexts SAN -extensions SAN \
-config <(cat /System/Library/OpenSSL/openssl.cnf \
<(printf '[SAN]\nsubjectAltName=DNS:localhost')) -sha256 -days 3650
Users will be warned that a secure connection cannot be made.
On Chrome you can inform the browser that you trust this certificate.
On Safari you will need to follow these steps:
1. Locate where your certificate file is. It is likely to be
somewhere near your web server configurations.
2. Open up Keychain Access. You can get to it from
Application/Utilities/Keychain Access.app.
3. Drag your certificate into Keychain Access.
4. Go into the Certificates section and locate the certificate you just added
5. Double click on it, enter the trust section and under
“When using this certificate” select “Always Trust”
*/
const default_domain = 'localhost';
const default_port = 8888;
const default_certs_dir = '.';
let config = {
certs: default_certs_dir, // must contain privkey.pem and fullchain.pem
port: default_port,
domain: default_domain,
accountPath: '/account',
accountManager: (request, response) => {
// handles all HTTPS requests to the accountPath:
// responsible for adding/removing user accounts,
// logging in and generation of JWT tokens, and
// logging out and handling forgotten passwords
return fail(500, "missing account manager", response);
},
validateJWT: (token, url) => {
// applications are responsible for managing user accounts and JWT tokens
// this function should validate a JWT token given a request's URL
// this is a dummy function to be overwritten by app supplied one
throw new Error("application didn't provide JWT validator")
return false; // return true if token is valid for this URL
}
}
const mime_types = {
"html": "text/html",
"txt": "text/plain",
"js": "text/javascript",
"json": "application/json",
"css": "text/css",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"png": "image/png",
"gif": "image/gif",
"ico": "image/x-icon",
"pdf": "application/pdf",
"ttl": "text/turtle",
"rdf": "text/turtle",
"crl": "text/crl",
"csv": "text/plain"
};
let things = {}; // map from name to thing
class ThingProperty {
constructor(thing, name, meta) {
this.name = name;
this.description = meta.description;
this.meta = meta;
this.type = meta.type;
this.writable = meta.writable;
this.thing = thing;
if (meta.hasOwnProperty('value'))
this.value = meta.value;
else if (thing.model.types && meta.type &&
thing.model.types[meta.type] &&
thing.model.types[meta.type].hasOwnProperty('value')) {
this.value = thing.model.types[meta.type].value;
}
}
// called by exposing app to update property value and notify clients
write(data) {
// be safe
if (data === undefined)
data = null;
//console.log('validate ' + this.name + ' = ' + data);
if (invalid(data, this.meta, this.thing))
throw new Error('writing property ' + this.name +
' with invalid data ' + JSON.stringify(data));
this.value = data;
// notify external clients of change
this.thing.emitValue(this.name, data);
}
}
class ThingAction {
constructor(thing, name, meta) {
this.name = name;
this.description = meta.description;
this.meta = meta;
this.thing = thing;
}
// apps should call thing.addActionHandler to register an
// action handler that returns a promise for the response
// for an exposed thing, invoke should simply call the handler
// for a consumed thing, invoke should use HTTP or WebSockets
// *** FIX ME ***
invoke(input) {
let action = this;
let handler = this.handler;
let perform = function (resolve, reject) {
// do something using action handler
// then resolve or reject as appropriate
// handler should throw exception on error
// *** will a long duration action block HTTP? ***
try {
if (action.meta && action.meta.input && invalid(input, action.meta.input, action.thing)) {
console.log('invalid input: ' + input);
throw new Error('invoking action ' + action.name +
' with invalid input ' + JSON.stringify(input));
}
if (handler) {
// application handler returns a promise
handler(input).then(output => {
if (action.meta.output && invalid(output, action.meta.output, action.thing)) {
console.log('invalid output: ' + output);
throw new Error('invalid action ' + action.name +
' with invalid response ' + JSON.stringify(data));
}
console.log('action ' + action.name + ' returned ' + JSON.stringify(output));
resolve(output);
}).catch(err => {
console.log('action handler failed: ' + err);
reject(err);
});
} else {
// nothing to do so succeed immediately
// or should we fail if there is no handler?
console.log('no handler for action ' + action.name);
resolve();
}
} catch (err) {
reject(err);
}
};
return new Promise(function (resolve, reject) {
perform(resolve, reject);
});
}
}
class ThingEvent {
constructor(thing, name, meta) {
this.name = name;
if (!(meta === undefined) && meta !== null ) {
this.meta = meta;
this.description = meta.description;
this.type = meta.type;
}
this.thing = thing;
this.longpoll = [];
}
emit(data) {
if (invalid(data, this.meta, this.thing))
throw new Error('event ' + this.name +
' with invalid data ' + JSON.stringify(json));
// notify any clients using HTTPS long polling
let longpoll = this.longpoll;
if (longpoll && longpoll.length) {
let body = JSON.stringify(data);
for (let i = 0; i <longpoll.length; ++i ) {
let response = longpoll[i];
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*',
'Content-Length': body.length
});
response.write(body);
response.end();
}
this.longpoll = [];
}
this.thing.emitEvent(this.name, data);
}
}
function new_event_stream(id, stream) {
console.log("new event stream " + id);
console.log("streams[id] = " + streams[id]);
if (!streams[id]) {
++stream_count;
streams[id] = stream;
}
}
function lost_event_stream(id) {
console.log("lost event stream " + id);
if (streams[id]) {
--stream_count;
delete streams[id];
if (stream_count < 1)
stop();
}
}
// check that the data conforms to the metadata
// which includes its type, min and max, etc.
// this assumes that the data model itself is valid
function invalid(data, meta, thing) {
if (meta === undefined) {
if (data === undefined || data === null)
return false;
return true;
}
if (data === undefined && meta.required)
return true;
let type = meta.type;
// missing type accepts anything
if (type === undefined)
return false;
// application defined type?
if (thing.model.types && thing.model.types.hasOwnProperty(type))
return invalid(data, thing.model.types[type], thing);
if (typeof (meta.enum) === 'array') {
list = meta.enum;
for (let i = 0; i < list.length; ++i ) {
if (data === list[i])
return false;
}
return true;
}
if (type === 'null' && data !== null)
return true;
if (type === 'const' && data !== meta.const)
return true;
if (type === 'boolean')
return !(data === true || data === false);
if (type === 'string') {
if (typeof data !== 'string')
return true;
if (meta.regex) {
const regex = new RegExp(meta.regex);
return ! regex.test(data);
}
return false;
}
if (type === 'number' || type === 'integer') {
if (typeof data !== 'number')
return true;
if (type === 'integer' && !Number.isInteger(data))
return true;
if (meta.minimum !== undefined && data < meta.minimum)
return true;
if (meta.maximum !== undefined && data > meta.maximum)
return true;
return false;
}
// arrays and objects are more complicated
// is it acceptable for data to be null when expecting an array?
if (type === 'array') {
if (!Array.isArray(data))
return true;
let length = data.length;
if (meta.minItems !== undefined && length < meta.minItems)
return true;
if (meta.maxItems !== undefined && length > meta.maxItems)
return true;
let items = meta.items;
if (items !== undefined) {
for (let i = 0; i < length; ++i) {
if (!invalid(data[i], meta, thing))
return true;
}
}
return false;
}
// is it acceptable for data to be null when expecting an object?
if (type === 'object') {
if (data === null || typeof data !== 'object' || Array.isArray(data))
return true;
let properties = meta.properties;
for (name in data) {
if (data.hasOwnProperty(name)) {
if (!properties.hasOwnProperty(name))
return true;
if (invalid(data[name], properties[name], thing)) {
return true;
}
}
}
let required = meta.required;
if (required === undefined)
return false;
// we need to check for missing required properties
for (let i = 0; i < required.length; ++i) {
if (!data.hasOwnProperty(required[i]))
return true;
}
return false;
}
return true;
}
function b2a (str) {
return Buffer.from(str, 'latin1').toString('base64');
}
// produce takes a JSON thing description and returns a thing
// you then need to expose it to make it available to clients
function produce(model) {
console.log("called produce");
console.log("model is " + JSON.stringify(model, null, 4));
let thing = {
properties: {},
actions: {},
events: {},
clients: {}, // stream ID -> stream
sockets: [], // list of web sockets
model: model
};
let name,
properties = model.properties,
actions = model.actions,
events = model.events;
thing.id = model.id
thing.name = model.name;
// some hacks for Ege's playground validator
// describing arena's HTTPS support for GET, PUT and POST
// as we can't yet describe arena's web socket subprotocol
if (!model.id)
model.id = "urn:example.org/" + model.name;
model.title = model.name;
model.base = "https://localhost:8888/";
model["@context"] = ["https://www.w3.org/2019/wot/td/v1"];
model.securityDefinitions = {
"bearer_sc": {
"in":"header",
"scheme": "bearer",
"format": "jwt",
"alg": "ES256",
"authorization": "https://localhost:8888/authorize"
}
};
model.security = ["bearer_sc"];
// set forms for all properties
for (name in properties) {
if (properties.hasOwnProperty(name)) {
let property = properties[name];
property.forms = [{
"op": "readproperty",
"href": "properties/" + name,
"contentType": "application/json",
"htv:methodName": "GET"
}, {
"op": "writeproperty",
"href": "properties/" + name,
"contentType": "application/json",
"htv:methodName": "GET"
}];
}
}
// set forms for all actions
for (name in actions) {
if (actions.hasOwnProperty(name)) {
let action = actions[name];
action.forms = [{
"op": "invokeaction",
"href": "actions/" + name,
"contentType": "application/json",
"htv:methodName": "POST"
}];
action.safe = false;
action.idempotent = false;
}
}
// set forms for all events
for (name in events) {
if (events.hasOwnProperty(name)) {
let event = events[name];
event.forms = [{
"op": "subscribeevent",
"href": "events/" + name,
"contentType": "application/json",
"subprotocol": "longpoll"
}];
action.safe = false;
action.idempotent = false;
}
}
// describe handlers for getting and setting all properties
model.forms = [{
"op": "readallproperties",
"href": "properties",
"contentType": "application/json",
"htv:methodName": "GET"
}, {
"op": "writeallproperties",
"href": "properties",
"contentType": "application/json",
"htv:methodName": "PUT"
}];
// this tells my client that the server supports the arena protocols
model.platform = "https://github.com/draggett/arena-webhub";
thing.emitEvent = function (name, json) {
if (thing.events.hasOwnProperty(name)) {
// note that event: is no longer supported for SSE
// so use an object wrapper to convey event name
if (json === undefined)
json = {"event":name};
else
json = {"event":name,"data":json};
let message = JSON.stringify(json);
message = "data: "+ message.replace(/\n/g, '\ndata: ') + "\n\n";
// clients for server-sent event stream
let clients = thing.clients;
for (let id in clients) {
if (clients.hasOwnProperty(id)) {
let client = clients[id];
client.response.write(message);
}
}
let sockets = thing.sockets;
for (let i = 0; i < sockets.length; ++i) {
ws_send(sockets[i], JSON.stringify(json));
}
} else {
console.log('unknown event: ' + name + ' on ' + thing.name);
}
};
thing.emitValue = function (name, value) {
// note that event: is no longer supported for SSE
// so use an object wrapper to convey event name
if (thing.properties.hasOwnProperty(name)) {
// be safe as stringify throws exception on undefined
if (value === undefined)
value = {"property":name};
else
value = {"property":name,"data":value};
let message = JSON.stringify(value);
message = "data: "+ message.replace(/\n/g, '\ndata: ') + "\n\n";
let clients = thing.clients;
if (clients !== undefined) {
for (var id in clients) {
if (clients.hasOwnProperty(id)) {
let client = clients[id];
client.response.write(message);
}
}
}
let sockets = thing.sockets;
if (sockets !== undefined ) {
//console.log('there are ' + sockets.length + ' socket clients');
for (let i = 0; i < sockets.length; ++i) {
ws_send(sockets[i], JSON.stringify(value));
}
//console.log('sent data to sockets');
}
} else {
console.log('unknown property: ' + name + ' on ' + thing.name);
}
};
thing.emitState = function (properties) {
// note that event: is no longer supported for SSE
// so use an object wrapper to convey event name
let obj = {};
if (properties === undefined)
properties = thing.properties;
for (var name in properties) {
if (properties.hasOwnProperty(name)) {
let value = properties[name].value;
if (value !== undefined)
obj[name] = value;
}
}
let json = JSON.stringify({"state":obj});
// for server-sent event stream
message = "data: "+ message.replace(/\n/g, '\ndata: ') + "\n\n";
let clients = thing.clients;
for (var id in clients) {
if (clients.hasOwnProperty(id)) {
let client = clients[id];
client.response.write(message);
}
}
let sockets = thing.sockets;
for (let i = 0; i < sockets.length; ++i) {
ws_send(sockets[i], JSON.stringify(json));
}
};
for (name in properties) {
if (properties.hasOwnProperty(name)) {
thing.properties[name] = new ThingProperty(thing, name, properties[name]);
}
}
for (name in actions) {
if (actions.hasOwnProperty(name)) {
thing.actions[name] = new ThingAction(thing, name, actions[name]);
}
}
for (name in events) {
if (events.hasOwnProperty(name)) {
thing.events[name] = new ThingEvent(thing, name, events[name]);
}
}
thing.setActionHandler = function (name, handler) {
if (thing.actions[name])
thing.actions[name].handler = handler;
};
thing.setWriteHandler = function (name, handler) {
if (thing.properties[name])
thing.properties[name].handler = handler;
};
thing.receive = function (socket, message) {
// handle incoming web socket message
// be safe against zero length messages
if (message.length === 0)
return;
let fail = (id, status, description) => {
if (typeof id !== "string")
id = "unknown";
console.log('fail: ' + id + ' ' + status + ' ' + description);
let json = {
id: id,
status: status
};
if (description !== undefined)
json.description = description;
ws_send(socket, JSON.stringify(json));
};
let succeed = (id, json) => {
if (json) {
json.id = id;
json.status = 200;
} else {
console.log('succeed with no data to return');
json = {
id: id,
status: 200
};
}
ws_send(socket, JSON.stringify(json));
};
try {
let json = JSON.parse(message);
if (json.property) {
let property = thing.properties[json.property];
if (property !== undefined) {
try {
property.write(json.data);
console.log("write succeeded");
succeed(json.id);
} catch (err) {
console.log("couldn't write " + json.data + ' to ' + property.name);
fail(json.id, 400, "bad request");
}
} else {
console.log("message with undefined property");
fail(json.id, 400, "bad request");
}
} else if (json.state !== undefined) {
let obj = json.state;
let properties = thing.properties;
for (name in obj) {
if (obj.hasOwnProperty(name) && properties.hasOwnProperty(name)) {
try {
properties[name].write(obj[name]);
} catch (err) {
console.log("couldn't write " + obj[name] + ' to ' + name);
return fail(json.id, 400, "bad request");
}
}
}
succeed(json.id);
} else if (json.action !== undefined) {
let action = thing.actions[json.action];
if (action !== undefined) {
action.invoke(json.input)
.then(output => {
console.log('output is ' + JSON.stringify(output));
if (output !== undefined)
succeed(json.id, {'output':output});
else
succeed(json.id);
}).catch(err => {
fail(json.id, 500, "action failed");
});
} else {
fail(json.id, 400, "bad request");
}
} else {
fail(json.id, 400, "bad request");
}
} catch (err) {
console.log('badly formed client message: ' + message);
fail(socket, 444, "badly formed client message");
}
};
// used to attach a new web socket
thing.addSocket = function(socket) {
thing.sockets.push(socket);
//.log('addSocket: there are ' + thing.sockets.length + ' sockets');
socket.on('close', () => {
// drop socket from thing.sockets
let sockets = thing.sockets;
const index = sockets.indexOf(socket);
if (index !== -1) {
sockets.splice(index, 1);
};
});
// send state of all properties to sync new client
let state = {};
let properties = thing.properties;
for (let name in properties) {
if (properties.hasOwnProperty(name)) {
state[name] = properties[name].value;
}
}
ws_send(socket, JSON.stringify({state: state}));
};
// why isn't this capability on the action itself?
thing.addActionHandler = (name, handler) => {
if (thing.actions.hasOwnProperty(name))
thing.actions[name].handler = handler;
};
thing.proxy = function (jwt) {
thing.owner = jwt;
};
// republish thing on external web hub, e.g. to
// provide access to things behind a firewall
thing.addRemoteClient = function (wss_uri, jwt) {
const proxy = URL.parse(wss_uri);
const wsKey = b2a(Math.random().toString(36).substring(2, 10) +
Math.random().toString(36).substring(2, 10));
const wsAccept = new HASHES.SHA1().b64(wsKey +
"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
const options = {
hostname: proxy.hostname,
port: proxy.port,
path: proxy.path,
method: 'GET',
headers: {
'Authorization': jwt,
'Connection': 'Upgrade',
'Sec-WebSocket-Key': wskey,
'Sec-WebSocket-Version': 13
}
};
let connect = function (resolve, reject) {
const request = HTTPS.request(options);
request.on('upgrade', (res, socket, head) => {
console.log('got response to upgrade request');
console.log(' with head length = ' + head.length);
// response should be 101 Switching Protocols
if (res.statusCode !== 101 ||
res.headers['Upgrade'] !== 'websocket' ||
res.headers['Connection'] !== 'Upgrade' ||
res.headers['Sec-WebSocket-Accept'] !== wsAccept) {
reject(new Error("couldn't connect to proxy: " + proxy.hostname));
}
thing.message = ""; // empty continuation buffer
// set up listener for incoming frames
socket.on('data', data => {
// if PING respond with PONG
let octet = data.charCodeAt(0);
if ((octet & 15) != 0x09) {
// test FIN to check for continuation frame
if ((octet & 128) == 128) {
// final frame for this message
let message = thing.message + ws_receive(data);
thing.message = "";
//console.log('received: ' + message);
thing.receive(socket, message);
} else {
// save continuation
thing.message += ws_receive(data);
}
}
});
// notify external web hub
// finally add socket to thing
thing.addSocket(socket);
resolve(socket);
});
req.on('error', () => {
reject(new Error("client error"));
});
req.on('close', () => {
console.log("proxy connection closed");
// should periodically try to reconnect
});
};
return new Promise(function (resolve, reject) {
connect(resolve, reject);
});
};
// sent text string to all clients via web sockets
thing.send = function (data) {
let sockets = thing.sockets;
for (let i = 0; i < sockets.length; ++i) {
ws_send(sockets[i], data);
}
};
thing.expose = function () {
let publish = (resolve, reject) => {
things[thing.model.name] = thing;
resolve(model);
}
return new Promise(function (resolve, reject) {
publish(resolve, reject);
});
};
//things[model.name] = thing;
return thing;
}
// see http://cjihrig.com/blog/the-server-side-of-server-sent-events/
// and https://www.w3.org/TR/eventsource/
// thing registers stream and call-back for server to invoke
// when client connects to stream. This passes response to
// the app to use when it has an event to send to clients
// app calls response.end() when done and may then call
// unregister_stream if it doesn't want to handle any more clients
// this module supports server-sent events via HTTP
// apps need to register a path for a stream together with
// call-backs for notification of new stream and lost stream
// thereby allowing apps to send events to the stream
// generates IDs for tracking event streams
let gensym_count = 0;
function gensym() {
return "id"+ (++gensym_count);
}
// helper for http server
function fail(status, description, response) {
let body = status + ' ' + description;
console.log(body);
response.writeHead(status, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*',
'Content-Length': body.length
});
response.write(body);
response.end();
}
// helper for http server
function succeed(status, description, response) {
let body = status + ' ' + description;
console.log(body);
response.writeHead(status, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Content-Length': body.length
});
response.write(body);
response.end();
}
// helper for HTTP request authorisation
function authorised(request) {
// JWT is usually passed via an HTTP header
let token = request.headers.authorization;
// For EventSource and WebSocket, JWT is passed as a URL parameter
if (token === undefined) {
let url = URL.parse(request.url, true);
if (url.query)
token = url.query.jwt;
}
// ask app to validate JWT authorisation token
return (!token || config.validateJWT(token, request.url));
}
// handles GET & HEAD requests
function process_get(request, response, uri) {
// if path is /things then return the set of thing models
let path = URL.parse(request.url).pathname;
if (path === "/things") {
if (!authorised(request))
return fail(401, "unauthorized", response);
let list = [];
for (var name in things) {
if (things.hasOwnProperty(name)) {
list.push(things[name].model);
}
}
body = JSON.stringify(list, null, 4);
response.writeHead(200, {
'Content-Type': mime_types.json,
'Pragma': 'no-cache',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Content-Length': body.length
});
if (request.method === "GET")
response.write(body);
response.end();
return;
}
// does path start with /things/thingID for some thingID?
if (/^\/things\/.+/.test(path)) {
if (!authorised(request))
return fail(401, "unauthorized", response);
path = path.substr(8);
let i = path.indexOf('/');
var thingID, body;
if (i < 0) {
thingID = path;
path = "";
} else {
thingID = path.substr(0, i);
path = path.substr(i);
}
if (thingID) {
let thing = things[thingID];
if (!thing)
return fail(404, "unknown thing: " + thingID, response);
if (!thing.model)