Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 29 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,13 +105,17 @@ thing.setPropertyWriteHandler('level', async function (value) {
});
```

Property values must conform to the data schema defined in the Thing Description.

Property changes are emitted automatically when an observable property is written via its write handler, but for other property changes you should explicitly call `emitPropertyChange()` to notify active SSE observers:

```javascript
await thing.emitPropertyChange('on', true);
```

If the value argument is omitted then the current value is read using the read handler and that value is emitted.
If the value argument is omitted then the current value is read using the read handler and that value is emitted:

```javascript
await thing.emitPropertyChange('on');
```

Expand All @@ -125,29 +129,51 @@ thing.setActionInvokeHandler('fade', async (input, signal) => {
});
```

Action inputs and outputs must conform to their respective data schemas defined in the Thing Description.

For synchronous actions set `synchronous` to `true` in the Thing Description. The invoke handler should accept the action input as an argument and return a promise which resolves with the action output.

For asynchronous actions set `synchronous` to `false` in the Thing Description. The invoke handler should accept the action input as its first argument, and an optional `AbortSignal` as a second argument so the action can be stopped if the request is cancelled.

### Events

Call `emitEvent()` whenever an event occurs for one of the
event affordances defined in the Thing Description:
event affordances defined in the Thing Description, passing the event name and data payload (if any) as arguments:

```javascript
thing.emitEvent('overheated', 90);
```

Event payloads must conform to the event data schema defined in the Thing Description.

### Thing Server

Expose to the Thing to the Web of Things by instantiating a Thing server for the Thing, then calling start() to start its web server (providing a port number as an argument):
Expose the Thing to the Web of Things by instantiating a Thing Server for the Thing, then calling start() to start its web server (providing a port number as an argument):

```javascript
const server = new ThingServer(thing);

server.start(8080);
```

To serve over HTTPS, provide Node.js HTTPS server options with your certificate and private key. The optional `domain` replaces the request host in the generated Thing Description:

```javascript
import { readFileSync } from 'node:fs';

const secureServer = new ThingServer(thing, {
tls: {
key: readFileSync('/path/to/private-key.pem'),
cert: readFileSync('/path/to/certificate.pem'),
},
domain: 'thing.example.com',
});

secureServer.start(8443);
```

The certificate and key must be obtained and renewed by your deployment; do not commit private keys to your project. Without `tls` options, the server continues to use HTTP.

## Development

### Type Checking
Expand Down
38 changes: 32 additions & 6 deletions src/thing-server.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,36 @@
import express from 'express';
import { createServer } from 'node:https';

/** @typedef {import('./thing.js').default} Thing */
/** @typedef {express.Request} Request */
/** @typedef {express.Response} Response */
/** @typedef {import('node:https').ServerOptions} HttpsServerOptions */
/** @typedef {{ tls?: HttpsServerOptions, domain?: string }} ThingServerOptions */

class ThingServer {
/**
* Construct the Thing Server.
*
* @param {Thing} thing The Thing to serve.
* @param {ThingServerOptions} [options] Optional TLS and public domain settings.
*/
constructor(thing) {
constructor(thing, options = {}) {
this.thing = thing;
this.tlsOptions = options.tls;
this.domain = options.domain;
if (
this.tlsOptions &&
!this.tlsOptions.pfx &&
!(this.tlsOptions.key && this.tlsOptions.cert)
) {
throw new TypeError(
'TLS options must include a private key and certificate or a PFX bundle',
);
}
this.app = express();
// Use JSON middleware and allow bare primite values as valid JSON
this.app.use(express.json({ strict: false }));
/** @type {import('node:net').Server | null} */
this.server = null;

this.app.get(
Expand All @@ -26,8 +42,9 @@ class ThingServer {
* @param {Response} response
*/
(request, response) => {
const host = request.headers.host;
response.json(this.thing.getThingDescription(host));
const host = this.domain ?? request.headers.host;
const protocol = request.secure ? 'https' : 'http';
response.json(this.thing.getThingDescription(host, protocol));
},
);

Expand Down Expand Up @@ -519,9 +536,18 @@ class ThingServer {
* @param {number} port The TCP port number to listen on.
*/
start(port) {
this.server = this.app.listen(port, () => {
console.log(`Web Thing being served on port ${port}`);
});
const onListening = () => {
const protocol = this.tlsOptions ? 'HTTPS' : 'HTTP';
console.log(`Web Thing being served over ${protocol} on port ${port}`);
};
if (this.tlsOptions) {
this.server = createServer(this.tlsOptions, this.app).listen(
port,
onListening,
);
} else {
this.server = this.app.listen(port, onListening);
}
}

/**
Expand Down
5 changes: 3 additions & 2 deletions src/thing.js
Original file line number Diff line number Diff line change
Expand Up @@ -364,9 +364,10 @@ class Thing extends EventEmitter {
* Get Thing Description.
*
* @param {string|undefined} host The host at which the Thing is being served.
* @param {'http'|'https'} [protocol] The protocol used to serve the Thing.
* @returns {ThingDescription} A complete Thing Description for the Thing.
*/
getThingDescription(host) {
getThingDescription(host, protocol = 'http') {
/**
* @type {Record<string, PropertyDescription>}
*/
Expand Down Expand Up @@ -411,7 +412,7 @@ class Thing extends EventEmitter {
// If a base argument is provided then use that, otherwise use the base provided in the
// partial Thing Description.
if (host) {
thingDescription.base = `http://${host}/`;
thingDescription.base = `${protocol}://${host}/`;
} else if (this.base) {
thingDescription.base = this.base.href;
}
Expand Down
19 changes: 19 additions & 0 deletions test/fixtures/localhost-cert.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDJzCCAg+gAwIBAgIUXjOkxXYHF3Zf6n5vaibiqec23CIwDQYJKoZIhvcNAQEL
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MCAXDTI2MTIwNDE3NTg0NFoYDzIxMjYx
MTEwMTc1ODQ0WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQCiNbzAfSLjiCbfCSn4lnNc9afYyJBy3aiPiQLui9v7
UW+Djjgb2/hevTGQh/+c+U1rvNebXdUra3/JDbMuaXm9iF0t4tBDlQtGCMSNwrol
5ys5jYZpBllKmb6wnyPpgVF7PDS0N+0M9T8F2dbR8cYTvI7elzdCAVnEZfJxsi0A
AuyF5+27h9XJ+UQSKuqRqnNXEEEqL0mFMUefI4M5qkVeUoeCrlepbIbiVcZGoC1C
eQmVvl+ZZZlU/PmBOOr5bRRYFZU3Y98zWhVp+OgrYA6d1XSrsqgtEv/voQdMIcqB
0bJ8ZT5i13Mpc+hiCAavrOFqlZsISnYD7Iyvhfb1dkUHAgMBAAGjbzBtMB0GA1Ud
DgQWBBTF7qyE48eLYmcR814ziLc5JZ4NljAfBgNVHSMEGDAWgBSH6j76fPzt9o+C
+rrPbm0LmEIzgTAPBgNVHRMBAf8EBTADAQH/MBoGA1UdEQQTMBGCCWxvY2FsaG9z
dIcEfwAAATANBgkqhkiG9w0BAQsFAAOCAQEAW4xyKNeYzus5RyPFoH7WLC4maF5H
PR+PWP5QlFnyh0miSYK6YJciPJFwryeYZKBVc1sscRz+qG8V9RdSeX9XjOfrMF/N
xhlIJHUBBbFHRtrOOK2R1+jRQNlsEHLajAt/S339xzSBpXAPfhfZyptq6P7sd835
ZQT4KEtMz2dZugboO4HJNV7XUVBjULtBP1Z2vXrSJ2w0MNDPqsuWlOHluUcDotSe
nkDXuuW4IuCXHfX01E9P4/ZErMBa6UqFCEYw8UPNLueRkbK7/mB5C1OeUr+XWsJs
qqZ1gkaAAb/Nvki1/x4AD9w8lwweIVztZJ3/S4yKhnsiBiwDqNzN/3oHjQ==
-----END CERTIFICATE-----
28 changes: 28 additions & 0 deletions test/fixtures/localhost-key.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCiNbzAfSLjiCbf
CSn4lnNc9afYyJBy3aiPiQLui9v7UW+Djjgb2/hevTGQh/+c+U1rvNebXdUra3/J
DbMuaXm9iF0t4tBDlQtGCMSNwrol5ys5jYZpBllKmb6wnyPpgVF7PDS0N+0M9T8F
2dbR8cYTvI7elzdCAVnEZfJxsi0AAuyF5+27h9XJ+UQSKuqRqnNXEEEqL0mFMUef
I4M5qkVeUoeCrlepbIbiVcZGoC1CeQmVvl+ZZZlU/PmBOOr5bRRYFZU3Y98zWhVp
+OgrYA6d1XSrsqgtEv/voQdMIcqB0bJ8ZT5i13Mpc+hiCAavrOFqlZsISnYD7Iyv
hfb1dkUHAgMBAAECggEAJRuW/RADebrNbauKgvhkFsmJ5tFnHifwJjnpRkoPfoxQ
Lu/Lj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SxGk+qq2EQkVU6ForGTxNM
Im5aOoMZkdWrEqJOAALbSTxjyzOASltpVDc1o6vqeuUJ96EQLIKgpVc9Tak6fi+l
yiePOTSjmz3mP+jIXcNZt08=
-----END PRIVATE KEY-----
82 changes: 82 additions & 0 deletions test/thing-server.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { describe, it, before, beforeEach, after } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { once } from 'node:events';
import https from 'node:https';
import Thing from '../src/thing.js';
import ThingServer from '../src/thing-server.js';

Expand Down Expand Up @@ -89,6 +92,85 @@ describe('ThingServer', () => {
server.stop();
});

describe('start()', () => {
it('should serve HTTPS with the configured domain in the Thing Description', async () => {
const certificate = readFileSync(
new URL('./fixtures/localhost-cert.pem', import.meta.url),
);
const key = readFileSync(
new URL('./fixtures/localhost-key.pem', import.meta.url),
);
const secureServer = new ThingServer(
new Thing({ title: 'Secure Thing' }),
{
tls: { key, cert: certificate },
domain: 'thing.example.com',
},
);

secureServer.start(0);
try {
await once(secureServer.server, 'listening');
const address = secureServer.server.address();
assert.ok(address && typeof address !== 'string');

const response = await new Promise((resolve, reject) => {
const request = https.get(
`https://localhost:${address.port}/`,
// The test certificate is self-signed.
{ rejectUnauthorized: false },
resolve,
);
request.on('error', reject);
});
const chunks = [];
for await (const chunk of response) {
chunks.push(chunk);
}

assert.equal(response.statusCode, 200);
assert.equal(
JSON.parse(Buffer.concat(chunks).toString()).base,
'https://thing.example.com/',
);
} finally {
secureServer.stop();
}
});

it('should continue serving HTTP when TLS options are omitted', async () => {
const httpServer = new ThingServer(new Thing({ title: 'HTTP Thing' }));
httpServer.start(0);
try {
await once(httpServer.server, 'listening');
const address = httpServer.server.address();
assert.ok(address && typeof address !== 'string');
const response = await fetch(`http://localhost:${address.port}/`);
assert.equal(response.status, 200);
assert.equal(
(await response.json()).base,
`http://localhost:${address.port}/`,
);
} finally {
httpServer.stop();
}
});

it('should reject incomplete TLS options', () => {
assert.throws(
() =>
new ThingServer(new Thing({ title: 'Invalid TLS Thing' }), {
tls: {},
}),
{
name: 'TypeError',
message:
'TLS options must include a private key and certificate or a PFX bundle',
},
);
});
});

describe('GET /', () => {
it('should return the Thing Description', async () => {
const response = await fetch(baseUrl + '/');
Expand Down
Loading