RingoJS

Module Index

  • helpers

    A collection of helper functions that makes working with Stick middleware easier.

  • middleware

    Convenience module that provides access to all Stick middleware using a single require() call.

  • stick

    The stick module provides the Application class which is the centerpiece of the Stick framework.

    A Stick Application is a JSGI application which provides means to compose complex applications out of modular middleware components.

  • middleware/accept

    This module provides middleware to check if a HTTP request accepts the possible response and makes content negotiation more convenient.

  • middleware/basicauth

    Basic Authentication middleware.

    To apply authentication to parts of your website configure this middleware and call the app's basicauth method with the URI path, user name, digest, and the name of digest's function of the user's password as arguments for each path you want to protect:

  • middleware/cookies

    This module provides middleware for reading cookies from the request. It does not provide any functions to set cookies in the response.

  • middleware/cors

    Cross-site HTTP request headers

    Implements the CORS (Cross-Origin Resource Sharing) protocol to enable cross-origin requests in browsers. Arbitrary HTTP clients may not comply to the protocol, so CORS cannot replace any server-side security mechanism.

    Configuration options:

    app.cors() accepts an object as parameter containing the following properties:

    • allowOrigin: configures the Access-Control-Allow-Origin header depending on the request's origin. Defaults to "*". The following options are supported:
      • String to set a specific origin; e.g. "https://example.com" or "*"
      • RegExp for dynamic origins; e.g. /https:\/\/www[12345]\.example\.com/
      • Array of strings to allow a set of different origins; e.g. ["https://example.com", "https://www.example.com"]
    • allowMethods: configures Access-Control-Allow-Methods; e.g. ["GET", "POST", "DELETE"]
    • allowHeaders: configures Access-Control-Allow-Headers; e.g. User-Agent, X-Custom-Header
    • exposeHeaders: configures Access-Control-Expose-Headers; e.g. Content-Length, X-Kuma-Revision
    • allowCredentials: if true, Access-Control-Allow-Credentials will be set to "true"
    • maxAge: configures Access-Control-Max-Age; use a negative value to disable preflight request caching
    • passthroughPreflights: if true, preflight requests will be forwarded to subsequent middlewares
    • optionsSuccessStatus: default HTTP status code for preflight responses

    The default configuration is equivalent to:

    app.cors({
      allowOrigin: "*",
      allowMethods: ["GET", "HEAD", "PUT", "PATCH", "POST", "DELETE"],
      allowHeaders:  [],
      exposeHeaders: [],
      allowCredentials: false,
      maxAge: -1,
      passthroughPreflights: false,
      optionsSuccessStatus: 204
    });
    

    For a detailed explanation on what the different headers do, see MDN on CORS.

  • middleware/csrf

    A middleware for CSRF mitigation, using either the synchronizer token or the double submission cookie pattern (see OWASP CSRF Prevention Cheat Sheet for a detailed explanation).

    This middleware extends the request object by adding two methods:

    • getCsrfToken() returns the CSRF token value for the current request, creating and storing it in the current session if necessary
    • rotateCsrfToken() creates a new CSRF token and stores it in the current session

    Use getCsrfToken() of the request object to add the token value as hidden input to all forms generated by the application, and make sure the name of the form input is configured accordingly (defaults to "csrftoken").

    The token value returned by getCsrfToken() is additionally stored either in the current session (default) or in a cookie. The POST parameter and the token value stored are compared, and in case of a mismatch this middleware returns a 403 "Forbidden" response.

    For non-POST requests this middleware accepts the token sent as query parameter or custom header field.

    Configuration options:

    app.csrf() accepts an object as parameter containing the following properties (default values in brackets):

    • tokenLength: The length of the CSRF token (32)
    • checkReferrer: Enable strict referrer checking for HTTPS requests (true)
    • rotate: If true tokens are only used once and modified after each validation (false)
    • getToken: By default the middleware expects the submitted CSRF token in either a post or query parameter csrftoken or in a custom request header x-csrf-token (in this order). To customize this define a function that will receive the request object as single argument and is expected to return the CSRF token (or null).
    • getFailureResponse: An optional function receiving the request as single argument. This method is called if the CSRF validation failed, and is expected to return a valid JSGI response (default: 403 forbidden).
    • safeMethods: An array containing request method names that are considered safe, so no token validation is done (["GET", "HEAD", "OPTIONS", "TRACE"]) – isSafeRequest: A function which returns true if the request is safe, false otherwise. A request is considered safe if it fulfills isSafeRequest || safeMethods.

    Cookie mode

    The following options switch the middleware into "double submission cookie" mode, and allow detailed configuration of the cookie:

    • useCookie: If true the CSRF token is stored in a cookie
    • cookieName: The name of the cookie to set ("csrftoken")
    • cookieHttpOnly: If true the httpOnly flag of the cookie is set (true)
    • cookieSecure: If true the secure flag of the cookie is set (false)
  • middleware/error

    Middleware to catch errors and generate simple error pages.

    By default, resource stick/middleware/error.html is used as page template. This can be set through the app.error.template property. This is the complete list of properties that influence the behaviour of this middleware:

    • template the error page template (string)
    • message static error message to use instead of actual message (string)
    • location whether to report any information about the code location of the error (boolean)
    • stack whether to include a JavaScript stack trace (boolean)
    • javaStack whether to include a Java stack trace (boolean)
  • middleware/etag

    Middleware for conditional HTTP GET request based on response body message digests.

    The response body must implement a digest() method for this middleware to work.

  • middleware/gzip

    Middleware for on-the-fly GZip compression of response bodies.

    By default only text content types are compressed. This can be controlled using the gzip.contentTypes property:

  • middleware/locale

    This module provides middleware to find the user's locale

  • middleware/method

    JSGI middleware for HTTP method override.

    Since older browsers are not able to send XMLHttpRequest with methods other than GET and POST, this middleware allows the method of POST requests to be overridden based on the value of a HTTP form parameter. The default name for the override parameter is _method. This can be configured through the method.key property.

  • middleware/mount

    This module provides middleware for mounting other applications on a specific URI path or virtual host.

    Applying this middleware adds a mount method to the application. The mount method takes a path or virtual host specification and an application as arguments. If the spec is a string, it is interpreted as the URI path on which the app will be mounted. If it is an object, it may contain path or host properties that will be matched against the URI path and Host header of incoming requests. Note that virtual host based mounting has not been tested so far.

    The mount method accepts an optional third boolean noRedirect argument. If set to true it will disable redirecting GET requests to the mount base URL without a trailing slash to the same URL with trailing slash. By default, mount middleware will send a redirect to the mount URL with trailing slash.

    Mounting one application within another causes the scriptName and pathInfo properties in the request object to be adjusted so that the mounted application receives the same pathInfo as if it was the main application. This means that forward and reverse request routing will usually work as expected.

    This middleware maintains an index mapping applications to mount points which can be accessed using the lookup function. The [stick/helpers][helpers] module provides higher level functions for this which include support for the route middleware.

  • middleware/notfound

    Middleware for simple Not-Found pages.

    By default, resource stick/middleware/notfound.html is used as page template. This can be set through the app.notfound.template property.

    • template the notfound page template (string)
  • middleware/params

    This module provides middleware for parsing HTTP parameters from the query string and request body. It does not parse multipart MIME data such as file uploads which are handled by the upload module.

    This installs a params() method in the application that accepts a configuration object with the following properties:

    • limit: maximum length of the request body in bytes, -1 disables the limit, defaults to 100 KiB
    • strict: if true (default), only accept JSON following RFC 4627, otherwise also parse pseudo-JSON like "1234"
    • reviver: optional function to transform the result JSON, see JSON.parse(str, reviver) for details
  • middleware/profiler

    This module provides profiling middleware to measure the application's runtime behaviour.

    Profiler data is written to the module's logger. You have to run the application in interpreted mode (passing -o -1 on the command line) to get meaningful results.

  • middleware/render

    This module provides middleware for rendering responses using ringo/mustache.

    This middleware installs a render function in the application object which is used to render HTTP responses. The behaviour of app.render can be tweaked by setting the following properties:

    • render.base - the base path or repository to look for templates
    • render.helpers - helper functions that will be merged in the context
    • render.master - master template which is applied on the top of processing the page with template given in the .render function.
    • render.contentType - MIME type to use for HTTP response
    • render.charset - charset name to use for HTTP response
  • middleware/requestlog

    Middleware for collecting log messages issued during execution of the current request.

    This adds a requestlog property to the application object with an items property. During execution of a request items contains an array containing all the log messages issued for the request. Log messages are represented as arrays in the format [time, level, name, message].

    During request execution, the requestlog property also defines a property called start containing the time the execution started.

    By default, messages are appended to the response if its Content-Type is text/html. This can be controlled using the app.requestlog.append boolean flag.

  • middleware/route

    Middleware for HTTP method based local request routing.

    This installs get, post, put, del and options methods in the application object for routing requests with the corresponding HTTP methods. These methods take a path spec as first argument and a function as second argument.

    Paths and Placeholders

    The path spec can consist of static parts and placeholders. Named placeholders are prefixed by : (colon) and match all characters except for / (slash) and . (dot). A named placeholder can be marked as optional by appending ? (question mark). Unnamed placeholders are denoted by the asterisk character * and match all characters including slashes and dots.

    In the following example, ":id" is a named placeholder:

    "/post/:id"
    

    All placeholders are passed to the action function as positional arguments following the request object in the order in which they appear in the path spec. Unmatched optional placeholders will be undefined.

    app.get("/post/:id", function(req, id) {...});
    

    Reverse Routing

    The route middleware supports generating URLs from route names and parameters required by the route.

    Routes names can either be defined explicitly by passing the route name as third argument, or are derived from the route's path spec by stripping out all placeholders and removing a leading slash. For example, a path spec /post/:id.html results in route name "post.html". If a path spec does not contain any static part, its route name is "index".

    Passing a valid route name and the parameters required by the route to the route.reverse method will return the URI path for the corresponding action. For example, with a route spec /post/:id.html, calling app.route.reverse({action: "post.html", id: 5}) will return the string "/post/5.html".

    The [stick/helpers][helpers] module provides higher level helpers for reverse routing including support for mounted applications.

  • middleware/session

    This module provides middleware for HTTP sessions.

    It adds a session property to the request object that allows to store arbitrary data on on a per-visitor basis.

    The default session implementation is based on Java Servlet sessions. This can be overridden by setting the app.session.impl property to an alternative session constructor.

    app.session.impl = MySession;
    

    The session constructor will be called with the request object as only argument when the session is first accessed.

  • middleware/static

    Middleware for serving static resources.

    This installs a static() method in the application that accepts the following arguments:

    • `base`: the base resource directory (required)
    • `index`: the name of a file to serve if the path matches a directory (e.g. "index.html")
    • `baseURI`: a common prefix for a resource URI (e.g. "/static")
    • `options`: an object with fine-grained configuration options
      • `servePrecompressed`: if true (default), static resources with a pre-compressed gzip equivalent will be served instead of the original file.
      • `maxAge`: set the `Cache-Control` header in seconds, default is 0.
      • `lastModified`: if true (default), set the `Last-Modified` header to the modification date of the resource.
      • `setHeaders`: allows a user to specify a function which returns additional headers to be set for a given path. The given function produces an object containing the header names as keys and takes the path as argument. User-provided headers take precedence over all other headers.
      • `dotfiles`: determines how should files starting with a dot character be treated. `allow` (default) serves dotfiles, `deny` respond with status 403, `ignore` respond with status 404.

    You can call static() multiple times to register multiple resources to be served.

  • middleware/upload

    This module provides support for parsing multipart MIME messages used for file uploads.

    This module behaves analogous and can be used in combination with the [params][middleware/params] middleware.