* Initialize the WebThingServer. * * For documentation on the additional route handlers, see: * http://expressjs.com/en/4x/api.html#app.use * * @param {Object} things Things managed by this server -- should be of type * SingleThing or MultipleThings * @par
(
things: SingleThing|MultipleThings,
port: number|null = null,
hostname: string|null = null,
sslOptions: https.ServerOptions|null = null,
additionalRoutes: any[]|null = null,
basePath = '/',
disableHostValidation = false
)
| 692 | * lead to DNS rebinding attacks |
| 693 | */ |
| 694 | constructor( |
| 695 | things: SingleThing|MultipleThings, |
| 696 | port: number|null = null, |
| 697 | hostname: string|null = null, |
| 698 | sslOptions: https.ServerOptions|null = null, |
| 699 | additionalRoutes: any[]|null = null, |
| 700 | basePath = '/', |
| 701 | disableHostValidation = false |
| 702 | ) { |
| 703 | this.things = things; |
| 704 | this.name = things.getName(); |
| 705 | this.port = Number(port) || (sslOptions ? 443 : 80); |
| 706 | this.hostname = hostname; |
| 707 | this.basePath = basePath.replace(/\/$/, ''); |
| 708 | this.disableHostValidation = !!disableHostValidation; |
| 709 | |
| 710 | const systemHostname = os.hostname().toLowerCase(); |
| 711 | this.hosts = [ |
| 712 | 'localhost', |
| 713 | `localhost:${port}`, |
| 714 | `${systemHostname}.local`, |
| 715 | `${systemHostname}.local:${port}`, |
| 716 | ]; |
| 717 | |
| 718 | utils.getAddresses().forEach((address) => { |
| 719 | this.hosts.push(address, `${address}:${port}`); |
| 720 | }); |
| 721 | |
| 722 | if (hostname) { |
| 723 | hostname = hostname.toLowerCase(); |
| 724 | this.hosts.push(hostname, `${hostname}:${port}`); |
| 725 | } |
| 726 | |
| 727 | if (things instanceof MultipleThings) { |
| 728 | const list = things.getThings(); |
| 729 | for (let i = 0; i < list.length; i++) { |
| 730 | const thing = list[i]; |
| 731 | thing.setHrefPrefix(`${this.basePath}/${i}`); |
| 732 | } |
| 733 | } else { |
| 734 | things.getThing().setHrefPrefix(this.basePath); |
| 735 | } |
| 736 | |
| 737 | this.app = express(); |
| 738 | this.app.use(bodyParser.json()); |
| 739 | |
| 740 | // Validate Host header |
| 741 | this.app.use((request, response, next: () => unknown) => { |
| 742 | const host = request.headers.host; |
| 743 | if (this.disableHostValidation || |
| 744 | (host && this.hosts.includes(host.toLowerCase()))) { |
| 745 | next(); |
| 746 | } else { |
| 747 | response.status(403).send('Forbidden'); |
| 748 | } |
| 749 | }); |
| 750 | |
| 751 | // Set CORS headers |