Skip to content
Draft
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
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,34 @@ 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.

To require JWT bearer authentication, define a bearer scheme in the partial Thing Description and configure trusted JWT verification keys when constructing the server:

```javascript
const partialTD = {
title: 'Private Thing',
securityDefinitions: {
bearer_sc: {
scheme: 'bearer',
format: 'jwt',
alg: 'RS256',
},
},
security: 'bearer_sc',
};

const thing = new Thing(partialTD);
const server = new ThingServer(thing, {
jwt: {
issuer: 'https://issuer.example.com/',
audience: 'my-thing',
// Supply a static public JWKS, a JWKS URI, or both.
jwksUri: 'https://issuer.example.com/.well-known/jwks.json',
},
});
```

Consumers must send `Authorization: Bearer <JWT>` when accessing Thing interaction endpoints. `GET /` remains public so consumers can retrieve the Thing Description. Static keys can be supplied as a standard public JWKS using `jwt.jwks`; when both `jwks` and `jwksUri` are configured, static keys are checked first and remote keys are resolved on demand. The token signature, issuer, audience, and required expiration (`exp`) claim are verified. The server supports signed JWTs using asymmetric algorithms; if `alg` is omitted from the TD, the WoT default `ES256` is enforced. Remote JWKS URLs must use HTTPS, except for loopback addresses used in local development. Bearer JWTs should only be sent over HTTPS, either directly to the Thing Server or through a trusted TLS-terminating proxy.

## Development

### Type Checking
Expand Down
12 changes: 11 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"homepage": "https://github.com/benfrancis/webthing-node-2#readme",
"dependencies": {
"ajv": "^8.20.0",
"express": "^5.1.0"
"express": "^5.1.0",
"jose": "^6.2.19"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
Expand Down
260 changes: 256 additions & 4 deletions src/thing-server.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,232 @@
import express from 'express';
import { createServer } from 'node:https';
import { createLocalJWKSet, createRemoteJWKSet, errors, jwtVerify } from 'jose';

/** @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 */
/** @typedef {import('jose').JSONWebKeySet} JSONWebKeySet */
const publicKeyJWTAlgorithms = new Set([
'ES256',
'ES384',
'ES512',
'EdDSA',
'Ed25519',
'PS256',
'PS384',
'PS512',
'RS256',
'RS384',
'RS512',
]);

/**
* @typedef {{
* issuer: string|Array<string>,
* audience: string|Array<string>,
* jwks?: JSONWebKeySet,
* jwksUri?: string|URL
* }} JWTVerificationOptions
*/
/**
* @typedef {{
* tls?: HttpsServerOptions,
* domain?: string,
* jwt?: JWTVerificationOptions
* }} ThingServerOptions
*/

class JWTKeySourceError extends Error {
/**
* @param {unknown} cause
*/
constructor(cause) {
super('Failed to resolve a JWT verification key', { cause });
}
}

/**
* @param {JWTVerificationOptions} options
* @param {string} algorithm
* @returns {(token: string) => Promise<void>}
*/
function createJWTVerifier(options, algorithm) {
/** @param {string|Array<string>} value */
const isNonEmptyValue = (value) =>
typeof value === 'string'
? value.trim().length > 0
: Array.isArray(value) &&
value.length > 0 &&
value.every(
(item) => typeof item === 'string' && item.trim().length > 0,
);
if (!isNonEmptyValue(options.issuer) || !isNonEmptyValue(options.audience)) {
throw new TypeError('JWT options must include an issuer and audience');
}
if (!options.jwks && !options.jwksUri) {
throw new TypeError('JWT options must include a JWKS or JWKS URI');
}
if (
options.jwks &&
(!Array.isArray(options.jwks.keys) || options.jwks.keys.length === 0)
) {
throw new TypeError('Static JWKS must include a non-empty keys array');
}
if (options.jwks?.keys.some((key) => !key || typeof key !== 'object')) {
throw new TypeError('Static JWKS must contain public JWK objects');
}
if (
options.jwks?.keys.some(
(key) =>
key.kty === 'oct' ||
'd' in key ||
'p' in key ||
'q' in key ||
'dp' in key ||
'dq' in key ||
'qi' in key ||
'oth' in key ||
'k' in key,
)
) {
throw new TypeError('Static JWKS must contain public asymmetric keys');
}

const localKeySet = options.jwks
? createLocalJWKSet(options.jwks)
: undefined;
const jwksUrl = options.jwksUri
? options.jwksUri instanceof URL
? options.jwksUri
: new URL(options.jwksUri)
: undefined;
if (
jwksUrl &&
jwksUrl.protocol !== 'https:' &&
!['localhost', '127.0.0.1', '[::1]'].includes(jwksUrl.hostname)
) {
throw new TypeError('Remote JWKS URLs must use HTTPS');
}
if (jwksUrl && (jwksUrl.username || jwksUrl.password)) {
throw new TypeError('Remote JWKS URLs must not contain credentials');
}
const remoteKeySet = jwksUrl ? createRemoteJWKSet(jwksUrl) : undefined;

/**
* @param {import('jose').JWTHeaderParameters} protectedHeader
* @param {import('jose').FlattenedJWSInput} token
*/
const getKey = async (protectedHeader, token) => {
if (localKeySet) {
try {
return await localKeySet(protectedHeader, token);
} catch (error) {
if (error instanceof errors.JWKSNoMatchingKey && remoteKeySet) {
// A static key miss can be satisfied by the remote JWKS.
} else if (error instanceof errors.JWKSNoMatchingKey) {
throw error;
} else {
throw new JWTKeySourceError(error);
}
}
}
if (remoteKeySet) {
try {
return await remoteKeySet(protectedHeader, token);
} catch (error) {
if (error instanceof errors.JWKSNoMatchingKey) {
throw error;
}
throw new JWTKeySourceError(error);
}
}
throw new errors.JWKSNoMatchingKey();
};

const verifyOptions = {
issuer: options.issuer,
audience: options.audience,
requiredClaims: ['exp'],
algorithms: [algorithm],
};

return async (token) => {
await jwtVerify(token, getKey, verifyOptions);
};
}

class ThingServer {
/** @type {((token: string) => Promise<void>)|undefined} */
#verifyJWT;

/**
* Construct the Thing Server.
*
* @param {Thing} thing The Thing to serve.
* @param {ThingServerOptions} [options] Optional TLS and public domain settings.
* @param {ThingServerOptions} [options] Optional TLS, public domain and JWT settings.
*/
constructor(thing, options = {}) {
this.thing = thing;
this.tlsOptions = options.tls;
this.domain = options.domain;
const securityNames = Array.isArray(thing.security)
? thing.security
: [thing.security];
if (securityNames.length !== 1) {
throw new TypeError(
'ThingServer supports one top-level security scheme at a time',
);
}
const securityScheme = thing.securityDefinitions[securityNames[0]];
if (!securityScheme) {
throw new TypeError(
`Thing security scheme "${securityNames[0]}" is not defined`,
);
}

this.#verifyJWT = undefined;
if (securityScheme.scheme === 'bearer') {
if (securityScheme.format && securityScheme.format !== 'jwt') {
throw new TypeError('ThingServer only supports bearer JWT tokens');
}
if (securityScheme.in && securityScheme.in !== 'header') {
throw new TypeError(
'ThingServer bearer JWTs must be provided in the Authorization header',
);
}
if (
securityScheme.name &&
securityScheme.name.toLowerCase() !== 'authorization'
) {
throw new TypeError(
'ThingServer bearer JWTs must use the Authorization header',
);
}
if (!options.jwt) {
throw new TypeError(
'JWT verification options are required for bearer security',
);
}
const algorithm = securityScheme.alg ?? 'ES256';
if (!publicKeyJWTAlgorithms.has(algorithm)) {
throw new TypeError(
'ThingServer only supports signed JWTs using asymmetric algorithms',
);
}
this.#verifyJWT = createJWTVerifier(options.jwt, algorithm);
} else if (securityScheme.scheme === 'nosec') {
if (options.jwt) {
throw new TypeError(
'JWT verification options require a bearer security scheme',
);
}
} else {
throw new TypeError(
`ThingServer does not support the "${securityScheme.scheme}" security scheme`,
);
}

if (
this.tlsOptions &&
!this.tlsOptions.pfx &&
Expand All @@ -28,8 +237,6 @@ class ThingServer {
);
}
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;

Expand All @@ -48,6 +255,51 @@ class ThingServer {
},
);

if (this.#verifyJWT) {
const verifyJWT = this.#verifyJWT;
this.app.use(
/**
* Authenticate requests to Thing interaction endpoints.
*
* @param {Request} request
* @param {Response} response
* @param {import('express').NextFunction} next
*/
async (request, response, next) => {
const authorization = request.get('authorization');
const match = authorization?.match(/^Bearer\s+(\S+)$/i);
if (!match) {
response.set('WWW-Authenticate', 'Bearer').status(401).send();
return;
}

try {
await verifyJWT(match[1]);
} catch (error) {
if (error instanceof JWTKeySourceError) {
console.error('Error verifying bearer JWT:', error.cause);
response.status(503).send();
return;
}
if (
error instanceof errors.JOSEError &&
!(error instanceof errors.JWKSTimeout)
) {
response.set('WWW-Authenticate', 'Bearer').status(401).send();
return;
}
console.error('Error verifying bearer JWT:', error);
response.status(503).send();
return;
}
next();
},
);
}

// Parse request bodies only after authenticating protected requests.
this.app.use(express.json({ strict: false }));

this.app.get(
'/properties/:name',
/**
Expand Down
5 changes: 2 additions & 3 deletions src/thing.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,12 @@ class Thing extends EventEmitter {
validationError.merge(error);
}

// Hard code the nosec security scheme for now
this.securityDefinitions = {
this.securityDefinitions = partialTD.securityDefinitions ?? {
nosec_sc: {
scheme: 'nosec',
},
};
this.security = 'nosec_sc';
this.security = partialTD.security ?? 'nosec_sc';

// TODO: Parse other members

Expand Down
Loading
Loading