<script type="module">
import tenso from 'https://cdn.skypack.dev/tenso';
</script>
README
Tenso
Tenso is an HTTP REST API framework, that will handle the serialization & creation of hypermedia links; all you have to do is give it Arrays or Objects.
Routes are loaded as a module, with each HTTP method as an export, affording a very customizable API server.
You can use res to res.send(body[, status, headers]), res.redirect(url), or res.error(status[, Error]).
The following example will create GET routes that will return an Array at /, an Error at /reports/tps, & a version 4 UUID at /uuid.
As of 10.3.0 you can specify always as a method to run middleware before authorization middleware, which will skip always middleware registered after it (via instance methods).
Protected routes are routes that require authorization for access, and will redirect to authentication end points if needed.
Unprotected Routes
Unprotected routes are routes that do not require authorization for access, and will exit the authorization pipeline early to avoid rate limiting, csrf tokens, & other security measures. These routes are the DMZ of your API! Youmust secure these end points with alternative methods if accepting input!
Reserved Route
The /assets/* route is reserved for the HTML browsable interface assets; please do not try to reuse this for data.
Request Helpers
Tenso decorates req with "helpers" such as req.allow, req.csrf, req.ip, req.parsed, & req.private. PATCH, PUT, & POST payloads are available as req.body. Sessions are available as req.session when using local authentication.
Tenso decorates res with "helpers" such as res.send(), res.status(), & res.json().
Responses
Responses will have a standard shape, and will be utf-8 by default. The result will be in data. Hypermedia (pagination & links) will be in links:[ {"uri": "...", "rel": "..."}, ...], & also in the Link HTTP header.
Page size can be specified via the page_size parameter, e.g. ?page_size=25.
Sort order can be specified via then order-by which accepts [field ]asc|desc & can be combined like an SQL 'ORDER BY', e.g. ?order_by=desc or ?order_by=lastName%20asc&order_by=firstName%20asc&order_by=age%20desc
{
"data": "`null` or ?",
"error": "`null` or an `Error` stack trace / message",
"links": [],
"status": 200
}
Final modifications can be made to a response body after hypermedia() by overriding tenso.final(req, res, body).
REST / Hypermedia
Hypermedia is a prerequisite of REST, and is best described by the Richardson Maturity Model. Tenso will automagically paginate Arrays of results, or parse Entity representations for keys that imply
relationships, and create the appropriate Objects in the link Array, as well as the Link HTTP header. Object keys that match this pattern: /_(guid|uuid|id|uri|url)$/ will be considered
hypermedia links.
For example, if the key user_id was found, it would be mapped to /users/:id with a link rel of related.
Tenso will bend the rules of REST when using authentication strategies provided by passport.js, or CSRF if is enabled, because they rely on a session. Session storage is in memory, or Redis. You have the option of a stateless or stateful API.
Hypermedia processing of the response body can be disabled as of 10.2.0, by setting req.hypermedia = false via middleware.
Browsable API / Renderers / Serializers
Tenso 1.4.0 added a few common format renderers, such as CSV, HTML, YAML, & XML. The HTML interface is a browsable API! You can use it to verify requests & responses, or simply poke around your API to see how it behaves.
Custom renderers can be registered with server.renderer('mimetype', fn); or directly on server.renderers. The parameters for a renderer are (req, res, arg). Custom serializes can be registered with server.serializer('mimetype', fn); or directly on server.serializers. The parameters for a serializer are (arg, err, status = 200, stack = false); if arg is null then err must be an Error & stack determines if the response body is the Error.message or Error.stack property.
Parsers
Custom renderers can be registered with server.parser('mimetype', fn); or directly on server.parsers. The parameters for a renderer are (arg).
Configuration
This is a sample configuration for Tenso, without authentication or SSL. This would be ideal for development, but not production! Enabling SSL is as easy as providing file paths for the two keys.
quot;, /* Optional, changes hypermedia detection / generation */
"id": "^(_id|id)quot; /* Optional, changes hypermedia detection / generation */
},
"session": { /* Optional */
"secret": null,
"store": "memory", /* "memory" or "redis" */
"redis": {} /* See connect-redis for options */
},
"ssl": { /* Optional */
"cert": null,
"key": null
},
"renderHeaders": true, /* false will disable headers in HTML interface */
"title": "My API", /* Page title for browsable API */
"uid": 33 /* Optional, system account uid to drop to after starting with elevated privileges to run on a low port */
}
Authentication
The protect Array is the endpoints that will require authentication. The redirect String is the end point users will be redirected to upon successfully authenticating, the default is /.
Sessions are used for non Basic or Bearer Token authentication, and will have /login, /logout, & custom routes. Redis is supported for session storage.
Multiple authentication strategies can be enabled at once.
Authentication attempts have a random delay to deal with "timing attacks"; always rate limit in production environment!
JWT (JSON Web Token) authentication is stateless and does not have an entry point. The auth(token, callback) function must verify token.sub, and must execute callback(err, user).
This authentication strategy relies on out-of-band information for the secret, and other optional token attributes.
{
"auth": {
"jwt": {
"enabled": true,
"auth": function (token, cb) { ... }, /* Authentication handler, to 'find' or 'create' a User */
"algorithms": [], /* Optional signing algorithms, defaults to ["HS256", "HS384", "HS512"] */
"audience": "", /* Optional, used to verify `aud` */
"issuer: "", /* Optional, used to verify `iss` */
"ignoreExpiration": false, /* Optional, set to `true` to ignore expired tokens */
"scheme": "Bearer", /* Optional, set to specify the `Authorization` scheme */
"secretOrKey": ""
}
"protect": ["/private"]
}
}
Local
Local authentication will create /login. auth(username, password) must execute callback(err, user).
{
"auth": {
"local": {
"enabled": true,
"auth": function ( ... ) { ... }, /* Authentication handler, to 'find' or 'create' a User */
}
"protect": ["/private"]
}
}
OAuth2
OAuth2 authentication will create /auth, /auth/oauth2, & /auth/oauth2/callback routes. auth(accessToken, refreshToken, profile, callback) must execute callback(err, user).
{
"auth": {
"oauth2": {
"enabled": true,
"auth": function ( ... ) { ... }, /* Authentication handler, to 'find' or 'create' a User */
"auth_url": "", /* Authorization URL */
"token_url": "", /* Token URL */
"client_id": "", /* Get this from authorization server */
"client_secret": "" /* Get this from authorization server */
},
"protect": ["/private"]
}
}
Sessions can use a memory (default) or redis store. Memory will limit your sessions to a single server instance, while redis will allow you to share sessions across a cluster of processes, or machines. To use redis, set the store property to "redis".
If the session secret is not provided, a version 4 UUID will be used.
Tenso uses lusca for security as a middleware. Please see it's documentation for how to configure it; each method & argument is a key:value pair for security.
{
"security": { ... }
}
Rate Limiting
Rate limiting is controlled by configuration, and is disabled by default. Rate limiting is based on token, session, or ip, depending upon authentication method.
Rate limiting can be overridden by providing an override function that takes req & rate, and must return (a modified) rate.
{
"rate": {
"enabled": true,
"limit": 450, /* Maximum requests allowed before `reset` */
"reset": 900, /* TTL in seconds */
"status": 429, /* Optional HTTP status */
"message": "Too many requests", /* Optional error message */
"override": function ( req, rate ) { ... } /* Override the default rate limiting */
}
}
Limiting upload size
A 'max byte' limit can be enforced on all routes that handle PATCH, POST, & PUT requests. The default limit is 20 KB (20480 B).
{
"maxBytes": 5242880
}
Logging
Standard log levels are supported, and are emitted to stdout & stderr. Stack traces can be enabled.
The browsable template can be overridden with a custom HTML document.
{
"template": ""
}
Static assets folder
The browsable template can load assets from this folder.
{
"static": "/assets"
}
Static assets cache
The browsable template assets have a default public cache of 300 seconds (5 minutes). These assets will always be considered public, but you can customize how long they are cacheable.