Repository: hapijs/hapi Branch: master Commit: f2a24f6635c0 Files: 71 Total size: 1.3 MB Directory structure: gitextract_wo27wudb/ ├── .github/ │ └── workflows/ │ └── ci-module.yml ├── .gitignore ├── .npmrc ├── API.md ├── LICENSE.md ├── README.md ├── SPONSORS.md ├── lib/ │ ├── auth.js │ ├── compression.js │ ├── config.js │ ├── core.js │ ├── cors.js │ ├── ext.js │ ├── handler.js │ ├── headers.js │ ├── index.d.ts │ ├── index.js │ ├── methods.js │ ├── request.js │ ├── response.js │ ├── route.js │ ├── security.js │ ├── server.js │ ├── streams.js │ ├── toolkit.js │ ├── transmit.js │ ├── types/ │ │ ├── index.d.ts │ │ ├── plugin.d.ts │ │ ├── request.d.ts │ │ ├── response.d.ts │ │ ├── route.d.ts │ │ ├── server/ │ │ │ ├── auth.d.ts │ │ │ ├── cache.d.ts │ │ │ ├── encoders.d.ts │ │ │ ├── events.d.ts │ │ │ ├── ext.d.ts │ │ │ ├── index.d.ts │ │ │ ├── info.d.ts │ │ │ ├── inject.d.ts │ │ │ ├── methods.d.ts │ │ │ ├── options.d.ts │ │ │ ├── server.d.ts │ │ │ └── state.d.ts │ │ └── utils.d.ts │ └── validation.js ├── package.json ├── test/ │ ├── .hidden │ ├── auth.js │ ├── common.js │ ├── core.js │ ├── cors.js │ ├── file/ │ │ └── note.txt │ ├── handler.js │ ├── headers.js │ ├── index.js │ ├── methods.js │ ├── payload.js │ ├── request.js │ ├── response.js │ ├── route.js │ ├── security.js │ ├── server.js │ ├── state.js │ ├── templates/ │ │ ├── invalid.html │ │ ├── plugin/ │ │ │ └── test.html │ │ └── test.html │ ├── toolkit.js │ ├── transmit.js │ ├── types/ │ │ └── index.ts │ └── validation.js └── typescript.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/ci-module.yml ================================================ name: ci on: push: branches: - v21 - master pull_request: workflow_dispatch: jobs: test: uses: hapijs/.github/.github/workflows/ci-module.yml@master with: min-node-version: 14 ================================================ FILE: .gitignore ================================================ **/node_modules **/package-lock.json coverage.* **/.DS_Store **/._* **/*.pem **/.vs **/.vscode **/.idea ================================================ FILE: .npmrc ================================================ save=false ================================================ FILE: API.md ================================================ ## Server The server object is the main application container. The server manages all incoming requests along with all the facilities provided by the framework. Each server supports a single connection (e.g. listen to port `80`). ### `server([options])` Creates a new server object where: - `options` - (optional) a [server configuration object](#server.options). ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ load: { sampleInterval: 1000 } }); ``` ### Server options The server options control the behavior of the server object. Note that the options object is deeply cloned (with the exception of [`listener`](#server.options.listener) which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on. All options are optionals. #### `server.options.address` Default value: `'::'` if IPv6 is available, otherwise `'0.0.0.0'` (i.e. all available network interfaces). Sets the hostname or IP address the server will listen on. If not configured, defaults to [`host`](#server.options.host) if present, otherwise to all available network interfaces. Set to `'127.0.0.1'`, `'::1'`, or `'localhost'` to restrict the server to only those coming from the same host. #### `server.options.app` Default value: `{}`. Provides application-specific configuration which can later be accessed via [`server.settings.app`](#server.settings). The framework does not interact with this object. It is simply a reference made available anywhere a `server` reference is provided. Note the difference between `server.settings.app` which is used to store static configuration values and [`server.app`](#server.app) which is meant for storing run-time state. #### `server.options.autoListen` Default value: `true`. Used to disable the automatic initialization of the [`listener`](#server.options.listener). When `false`, indicates that the [`listener`](#server.options.listener) will be started manually outside the framework. Cannot be set to `false` along with a [`port`](#server.options.port) value. #### `server.options.cache` Default value: `{ provider: { constructor: require('@hapi/catbox-memory'), options: { partition: 'hapi-cache' } } }`. Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. **hapi** uses [**catbox**](https://hapi.dev/family/catbox/api) for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if [methods](#server.methods) and [plugins](#plugins) explicitly store their state in the cache. The server cache configuration only defines the storage container itself. The configuration can be assigned one or more (array): - a class or prototype function (usually obtained by calling `require()` on a **catbox** strategy such as `require('@hapi/catbox-redis')`). A new **catbox** [client](https://hapi.dev/family/catbox/api#client) will be created internally using this constructor. - a configuration object with the following: - `engine` - a **catbox** engine object instance. - `name` - an identifier used later when provisioning or configuring caching for [server methods](#server.methods) or [plugins](#plugins). Each cache name must be unique. A single item may omit the `name` option which defines the default cache. If every cache includes a `name`, a default memory cache is provisioned as well. - `provider` - a class, a constructor function, or an object with the following: - `constructor` - a class or a prototype function. - `options` - (optional) a settings object passed as-is to the `constructor` with the following: - `partition` - (optional) string used to isolate cached data. Defaults to `'hapi-cache'`. - other constructor-specific options passed to the `constructor` on instantiation. - `shared` - if `true`, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to `false`. - One (and only one) of `engine` or `provider` is required per configuration object. #### `server.options.compression` Default value: `{ minBytes: 1024 }`. Defines server handling of content encoding requests. If `false`, response content encoding is disabled and no compression is performed by the server. ##### `server.options.compression.minBytes` Default value: '1024'. Sets the minimum response payload size in bytes that is required for content encoding compression. If the payload size is under the limit, no compression is performed. #### `server.options.debug` Default value: `{ request: ['implementation'] }`. Determines which logged events are sent to the console. This should only be used for development and does not affect which events are actually logged internally and recorded. Set to `false` to disable all console logging, or to an object with: - `log` - a string array of server log tags to be displayed via `console.error()` when the events are logged via [`server.log()`](#server.log()) as well as internally generated [server logs](#server-logs). Defaults to no output. - `request` - a string array of request log tags to be displayed via `console.error()` when the events are logged via [`request.log()`](#request.log()) as well as internally generated [request logs](#request-logs). For example, to display all errors, set the option to `['error']`. To turn off all console debug messages set it to `false`. To display all request logs, set it to `'*'`. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. For example, to display all errors, set the `log` or `request` to `['error']`. To turn off all output set the `log` or `request` to `false`. To display all server logs, set the `log` or `request` to `'*'`. To disable all debug information, set `debug` to `false`. #### `server.options.host` Default value: the operating system hostname and if not available, to `'localhost'`. The public hostname or IP address. Used to set [`server.info.host`](#server.info) and [`server.info.uri`](#server.info) and as [`address`](#server.options.address) if none is provided. #### `server.options.info.remote` Default value: `false`. If `true`, the `request.info.remoteAddress` and `request.info.remotePort` are populated when the request is received which can consume more resource (but is ok if the information is needed, especially for aborted requests). When `false`, the fields are only populated upon demand (but will be `undefined` if accessed after the request is aborted). #### `server.options.listener` Default value: none. An optional node HTTP (or HTTPS) [`http.Server`](https://nodejs.org/api/http.html#http_class_http_server) object (or an object with a compatible interface). If the `listener` needs to be manually started, set [`autoListen`](#server.options.autolisten) to `false`. If the `listener` uses TLS, set [`tls`](#server.options.tls) to `true`. #### `server.options.load` Default value: `{ sampleInterval: 0, maxHeapUsedBytes: 0, maxRssBytes: 0, maxEventLoopDelay: 0, maxEventLoopUtilization: 0 }`. Server excessive load handling limits where: - `sampleInterval` - the frequency of sampling in milliseconds. When set to `0`, the other load options are ignored. Defaults to `0` (no sampling). - `maxHeapUsedBytes` - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to `0` (no limit). - `maxRssBytes` - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to `0` (no limit). - `maxEventLoopDelay` - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to `0` (no limit). - `maxEventLoopUtilization` - maximum event loop utilization value over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to `0` (no limit). #### `server.options.mime` Default value: none. Options passed to the [**mimos**](https://hapi.dev/family/mimos/api) module when generating the mime database used by the server (and accessed via [`server.mime`](#server.mime)): - `override` - an object hash that is merged into the built in mime information specified [here](https://github.com/jshttp/mime-db). Each key value pair represents a single mime object. Each override value must contain: - `key` - the lower-cased mime-type string (e.g. `'application/javascript'`). - `value` - an object following the specifications outlined [here](https://github.com/jshttp/mime-db#data-structure). Additional values include: - `type` - specify the `type` value of result objects, defaults to `key`. - `predicate` - method with signature `function(mime)` when this mime type is found in the database, this function will execute to allows customizations. ```js const options = { mime: { override: { 'node/module': { source: 'iana', compressible: true, extensions: ['node', 'module', 'npm'], type: 'node/module' }, 'application/javascript': { source: 'iana', charset: 'UTF-8', compressible: true, extensions: ['js', 'javascript'], type: 'text/javascript' }, 'text/html': { predicate: function(mime) { if (someCondition) { mime.foo = 'test'; } else { mime.foo = 'bar'; } return mime; } } } } }; ``` #### `server.options.operations` Default value: `{ cleanStop: true }`. Defines server handling of server operations: - `cleanStop` - if `true`, the server keeps track of open connections and properly closes them when the server is stopped. Under normal load, this should not interfere with server performance. However, under severe load connection monitoring can consume additional resources and aggravate the situation. If the server is never stopped, or if it is forced to stop without waiting for open connection to close, setting this to `false` can save resources that are not being utilized anyway. Defaults to `true`. #### `server.options.plugins` Default value: `{}`. Plugin-specific configuration which can later be accessed via [`server.settings.plugins`](#server.settings). `plugins` is an object where each key is a plugin name and the value is the configuration. Note the difference between [`server.settings.plugins`](#server.settings) which is used to store static configuration values and [`server.plugins`](#server.plugins) which is meant for storing run-time state. #### `server.options.port` Default value: `0` (an ephemeral port). The TCP port the server will listen to. Defaults the next available port when the server is started (and assigned to [`server.info.port`](#server.info)). If `port` is a string containing a '/' character, it is used as a UNIX domain socket path. If it starts with '\\.\pipe', it is used as a Windows named pipe. #### `server.options.query` Default value: `{}`. Defines server handling of the request path query component. ##### `server.options.query.parser` Default value: none. Sets a query parameters parser method using the signature `function(query)` where: - `query` - an object containing the incoming [`request.query`](#request.query) parameters. - the method must return an object where each key is a parameter and matching value is the parameter value. If the method throws, the error is used as the response or returned when [`request.setUrl()`](#request.setUrl()) is called. ```js const Qs = require('qs'); const options = { query: { parser: (query) => Qs.parse(query) } }; ``` #### `server.options.router` Default value: `{ isCaseSensitive: true, stripTrailingSlash: false }`. Controls how incoming request URIs are matched against the routing table: - `isCaseSensitive` - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to `true`. - `stripTrailingSlash` - removes trailing slashes on incoming paths. Defaults to `false`. #### `server.options.routes` Default value: none. A [route options](#route-options) object used as the default configuration for every route. #### `server.options.state` Default value: ```js { strictHeader: true, ignoreErrors: false, isSecure: true, isHttpOnly: true, isSameSite: 'Strict', isPartitioned: false, encoding: 'none' } ``` Sets the default configuration for every state (cookie) set explicitly via [`server.state()`](#server.state()) or implicitly (without definition) using the [state configuration](#server.state()) object. #### `server.options.tls` Default value: none. Used to create an HTTPS connection. The `tls` object is passed unchanged to the node HTTPS server as described in the [node HTTPS documentation](https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener). Set to `true` when passing a [`listener`](#server.options.listener) object that has been configured to use TLS directly. #### `server.options.uri` Default value: constructed from runtime server information. The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server [`server.info.uri`](#server.info), otherwise constructed from the server settings. ### Server properties #### `server.app` Access: read / write. Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. ```js const server = Hapi.server(); server.app.key = 'value'; const handler = function (request, h) { return request.server.app.key; // 'value' }; ``` #### `server.auth.api` Access: authentication strategy specific. An object where each key is an authentication strategy name and the value is the exposed strategy API. Available only when the authentication scheme exposes an API by returning an `api` key in the object returned from its implementation function. ```js const server = Hapi.server({ port: 80 }); const scheme = function (server, options) { return { api: { settings: { x: 5 } }, authenticate: function (request, h) { const authorization = request.headers.authorization; if (!authorization) { throw Boom.unauthorized(null, 'Custom'); } return h.authenticated({ credentials: { user: 'john' } }); } }; }; server.auth.scheme('custom', scheme); server.auth.strategy('default', 'custom'); console.log(server.auth.api.default.settings.x); // 5 ``` #### `server.auth.settings.default` Access: read only. Contains the default authentication configuration if a default strategy was set via [`server.auth.default()`](#server.auth.default()). #### `server.decorations` Access: read only. Provides access to the decorations already applied to various framework interfaces. The object must not be modified directly, but only through [`server.decorate`](#server.decorate()). Contains: - `request` - decorations on the [request object](#request). - `response` - decorations on the [response object](#response-object). - `toolkit` - decorations on the [response toolkit](#response-toolkit). - `server` - decorations on the [server](#server) object. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const success = function () { return this.response({ status: 'ok' }); }; server.decorate('toolkit', 'success', success); console.log(server.decorations.toolkit); // ['success'] ``` #### `server.events` Access: **podium** public interface. The server events emitter. Utilizes the [**podium**](https://hapi.dev/family/podium/api) with support for event criteria validation, channels, and filters. Use the following methods to interact with `server.events`: - [`server.event(events)`](#server.event()) - register application events. - [`server.events.emit(criteria, data)`](#server.events.emit()) - emit server events. - [`server.events.on(criteria, listener, context)`](#server.events.on()) - subscribe to all events. - [`server.events.once(criteria, listener, context)`](#server.events.once()) - subscribe to a single event. Other methods include: `server.events.removeListener(name, listener)`, `server.events.removeAllListeners(name)`, and `server.events.hasListeners(name)`. ##### `'log'` Event The `'log'` event type emits internal server events generated by the framework as well as application events logged with [`server.log()`](#server.log()). The `'log'` event handler uses the function signature `function(event, tags)` where: - `event` - an object with the following properties: - `timestamp` - the event timestamp. - `tags` - an array of tags identifying the event (e.g. `['error', 'http']`). - `channel` - set to `'internal'` for internally generated events, otherwise `'app'` for events generated by [`server.log()`](#server.log()). - `data` - event-specific information. Available when event data was provided and is not an error. Errors are passed via `error`. - `error` - the error object related to the event if applicable. Cannot appear together with `data`. - `tags` - an object where each `event.tag` is a key and the value is `true`. Useful for quick identification of events. ```js server.events.on('log', (event, tags) => { if (tags.error) { console.log(`Server error: ${event.error ? event.error.message : 'unknown'}`); } }); ``` The internally generated events are (identified by their `tags`): - `load` - logs the current server load measurements when the server rejects a request due to [high load](#server.options.load). The event data contains the process load metrics. - `connection` `client` `error` - a `clientError` event was received from the HTTP or HTTPS listener. The event data is the error object received. ##### `'cachePolicy'` Event The `'cachePolicy'` event type is emitted when a server [cache policy](https://hapi.dev/module/catbox/api#policy) is created via [`server.cache()`](#server.cache()) or a [`server.method()`](#server.method()) with caching enabled is registered. The `'cachePolicy'` event handler uses the function signature `function(cachePolicy, cache, segment)` where: - `cachePolicy` - the catbox [cache policy](https://hapi.dev/module/catbox/api#policy). - `cache` - the [cache provision](#server.options.cache) name used when the policy was created or `undefined` if the default cache was used. - `segment` - the segment name used when the policy was created. ```js server.events.on('cachePolicy', (cachePolicy, cache, segment) => { console.log(`New cache policy created using cache: ${cache === undefined ? 'default' : cache} and segment: ${segment}`); }); ``` ##### `'request'` Event The `'request'` event type emits internal request events generated by the framework as well as application events logged with [`request.log()`](#request.log()). The `'request'` event handler uses the function signature `function(request, event, tags)` where: - `request` - the [request object](#request). - `event` - an object with the following properties: - `timestamp` - the event timestamp. - `tags` - an array of tags identifying the event (e.g. `['error', 'http']`). - `channel` - one of - `'app'` - events generated by [`request.log()`](#request.log()). - `'error'` - emitted once per request if the response had a `500` status code. - `'internal'` - internally generated events. - `request` - the request [identifier](#request.info.id). - `data` - event-specific information. Available when event data was provided and is not an error. Errors are passed via `error`. - `error` - the error object related to the event if applicable. Cannot appear together with `data`. - `tags` - an object where each `event.tag` is a key and the value is `true`. Useful for quick identification of events. ```js server.events.on('request', (request, event, tags) => { if (tags.error) { console.log(`Request ${event.request} error: ${event.error ? event.error.message : 'unknown'}`); } }); ``` To listen to only one of the channels, use the event criteria object: ```js server.events.on({ name: 'request', channels: 'error' }, (request, event, tags) => { console.log(`Request ${event.request} failed`); }); ``` The internally generated events are (identified by their `tags`): - `accept-encoding` `error` - a request received contains an invalid Accept-Encoding header. - `auth` `unauthenticated` - no authentication scheme included with the request. - `auth` `unauthenticated` `response` `{strategy}` - the authentication strategy listed returned a non-error response (e.g. a redirect to a login page). - `auth` `unauthenticated` `error` `{strategy}` - the request failed to pass the listed authentication strategy (invalid credentials). - `auth` `unauthenticated` `missing` `{strategy}` - the request failed to pass the listed authentication strategy (no credentials found). - `auth` `unauthenticated` `try` `{strategy}` - the request failed to pass the listed authentication strategy in `'try'` mode and will continue. - `auth` `scope` `error` - the request authenticated but failed to meet the scope requirements. - `auth` `entity` `user` `error` - the request authenticated but included an application entity when a user entity was required. - `auth` `entity` `app` `error` - the request authenticated but included a user entity when an application entity was required. - `ext` `error` - an `onPostResponse` extension handler errored. - `handler` `error` - the route handler returned an error. Includes the execution duration and the error message. - `pre` `error` - a pre method was executed and returned an error. Includes the execution duration, assignment key, and error. - `internal` `error` - an HTTP 500 error response was assigned to the request. - `internal` `implementation` `error` - an incorrectly implemented [lifecycle method](#lifecycle-methods). - `request` `error` `abort` - the request aborted. - `request` `error` `close` - the request closed prematurely. - `request` `error` - the request stream emitted an error. Includes the error. - `request` `server` `timeout` `error` - the request took too long to process by the server. Includes the timeout configuration value and the duration. - `state` `error` - the request included an invalid cookie or cookies. Includes the cookies and error details. - `state` `response` `error` - the response included an invalid cookie which prevented generating a valid header. Includes the error. - `payload` `error` - failed processing the request payload. Includes the error. - `response` `error` - failed writing the response to the client. Includes the error. - `response` `error` `close` - failed writing the response to the client due to prematurely closed connection. - `response` `error` `aborted` - failed writing the response to the client due to prematurely aborted connection. - `response` `error` `cleanup` - failed freeing response resources. - `validation` `error` `{input}` - input (i.e. payload, query, params, headers) validation failed. Includes the error. Only emitted when `failAction` is set to `'log'`. - `validation` `response` `error` - response validation failed. Includes the error message. Only emitted when `failAction` is set to `'log'`. ##### `'response'` Event The `'response'` event type is emitted after the response is sent back to the client (or when the client connection closed and no response sent, in which case [`request.response`](#request.response) is `null`). A single event is emitted per request. The `'response'` event handler uses the function signature `function(request)` where: - `request` - the [request object](#request). ```js server.events.on('response', (request) => { console.log(`Response sent for request: ${request.info.id}`); }); ``` ##### `'route'` Event The `'route'` event type is emitted when a route is added via [`server.route()`](#server.route()). The `'route'` event handler uses the function signature `function(route)` where: - `route` - the [route information](#request.route). The `route` object must not be modified. ```js server.events.on('route', (route) => { console.log(`New route added: ${route.path}`); }); ``` ##### `'start'` Event The `'start'` event type is emitted when the server is started using [`server.start()`](#server.start()). The `'start'` event handler uses the function signature `function()`. ```js server.events.on('start', () => { console.log('Server started'); }); ``` ##### `'closing'` Event The `'closing'` event type is emitted when the server is stopped using [`server.stop()`](#server.stop()). It is triggered when incoming requests are no longer accepted but before all underlying active connections have been closed, and thus before the [`'stop'`](#server.events.stop) event is triggered. The `'closing'` event handler uses the function signature `function()`. ```js server.events.on('closing', () => { console.log('Server is closing'); }); ``` ##### `'stop'` Event The `'stop'` event type is emitted when the server is stopped using [`server.stop()`](#server.stop()). The `'stop'` event handler uses the function signature `function()`. ```js server.events.on('stop', () => { console.log('Server stopped'); }); ``` #### `server.info` Access: read only. An object containing information about the server where: - `id` - a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). - `created` - server creation timestamp. - `started` - server start timestamp (`0` when stopped). - `port` - the connection port based on the following rules: - before the server has been started: the configured [`port`](#server.options.port) value. - after the server has been started: the actual port assigned when no port is configured or was set to `0`. - `host` - The [`host`](#server.options.host) configuration value. - `address` - the active IP address the connection was bound to after starting. Set to `undefined` until the server has been started or when using a non TCP port (e.g. UNIX domain socket). - `protocol` - the protocol used: - `'http'` - HTTP. - `'https'` - HTTPS. - `'socket'` - UNIX domain socket or Windows named pipe. - `uri` - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the [`uri`](#server.options.uri) value if set, otherwise constructed from the available settings. If no [`port`](#server.options.port) is configured or is set to `0`, the `uri` will not include a port component until the server is started. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); console.log(server.info.port); // 80 ``` #### `server.listener` Access: read only and listener public interface. The node HTTP server object. ```js const Hapi = require('@hapi/hapi'); const SocketIO = require('socket.io'); const server = Hapi.server({ port: 80 }); const io = SocketIO.listen(server.listener); io.sockets.on('connection', (socket) => { socket.emit({ msg: 'welcome' }); }); ``` #### `server.load` Access: read only. An object containing the process load metrics (when [`load.sampleInterval`](#server.options.load) is enabled): - `eventLoopDelay` - event loop delay milliseconds. - `eventLoopUtilization` - current event loop utilization value. - `heapUsed` - V8 heap usage. - `rss` - RSS memory usage. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ load: { sampleInterval: 1000 } }); console.log(server.load.rss); ``` #### `server.methods` Access: read only. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. `sever.methods` is an object which provides access to the methods registered via [server.method()](#server.method()) where each server method name is an object property. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server(); server.method('add', (a, b) => (a + b)); const result = server.methods.add(1, 2); // 3 ``` #### `server.mime` Access: read only and **mimos** public interface. Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the [`mime`](#server.options.mime) server setting. ```js const Hapi = require('@hapi/hapi'); const options = { mime: { override: { 'node/module': { source: 'steve', compressible: false, extensions: ['node', 'module', 'npm'], type: 'node/module' } } } }; const server = Hapi.server(options); console.log(server.mime.path('code.js').type) // 'application/javascript' console.log(server.mime.path('file.npm').type) // 'node/module' ``` #### `server.plugins` Access: read / write. An object containing the values exposed by each registered plugin where each key is a plugin name and the values are the exposed properties by each plugin using [`server.expose()`](#server.expose()). Plugins may set the value of the `server.plugins[name]` object directly or via the `server.expose()` method. ```js exports.plugin = { name: 'example', register: function (server, options) { server.expose('key', 'value'); server.plugins.example.other = 'other'; console.log(server.plugins.example.key); // 'value' console.log(server.plugins.example.other); // 'other' } }; ``` #### `server.realm` Access: read only. The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When registering a plugin or an authentication scheme, a `server` object reference is provided with a new `server.realm` container specific to that registration. It allows each plugin to maintain its own settings without leaking and affecting other plugins. For example, a plugin can set a default file path for local resources without breaking other plugins' configured paths. When calling [`server.bind()`](#server.bind()), the active realm's `settings.bind` property is set which is then used by routes and extensions added at the same level (server root or plugin). The `server.realm` object contains: - `modifiers` - when the server object is provided as an argument to the plugin `register()` method, `modifiers` provides the registration preferences passed the [`server.register()`](#server.register()) method and includes: - `route` - routes preferences: - `prefix` - the route path prefix used by any calls to [`server.route()`](#server.route()) from the server. Note that if a prefix is used and the route path is set to `'/'`, the resulting path will not include the trailing slash. - `vhost` - the route virtual host settings used by any calls to [`server.route()`](#server.route()) from the server. - `parent` - the realm of the parent server object, or `null` for the root server. - `plugin` - the active plugin name (empty string if at the server root). - `pluginOptions` - the plugin options passed at registration. - `plugins` - plugin-specific state to be shared only among activities sharing the same active state. `plugins` is an object where each key is a plugin name and the value is the plugin state. - `settings` - settings overrides: - `files.relativeTo` - `bind` The `server.realm` object should be considered read-only and must not be changed directly except for the `plugins` property which can be directly manipulated by each plugin, setting its properties inside `plugins[name]`. ```js exports.register = function (server, options) { console.log(server.realm.modifiers.route.prefix); }; ``` #### `server.registrations` Access: read only. An object of the currently registered plugins where each key is a registered plugin name and the value is an object containing: - `version` - the plugin version. - `name` - the plugin name. - `options` - (optional) options passed to the plugin during registration. #### `server.settings` Access: read only. The server configuration object after defaults applied. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ app: { key: 'value' } }); console.log(server.settings.app); // { key: 'value' } ``` #### `server.states` Access: read only and **statehood** public interface. The server cookies manager. #### `server.states.settings` Access: read only. The server cookies manager settings. The settings are based on the values configured in [`server.options.state`](#server.options.state). #### `server.states.cookies` Access: read only. An object containing the configuration of each cookie added via [`server.state()`](#server.state()) where each key is the cookie name and value is the configuration object. #### `server.states.names` Access: read only. An array containing the names of all configured cookies. #### `server.type` Access: read only. A string indicating the listener type where: - `'socket'` - UNIX domain socket or Windows named pipe. - `'tcp'` - an HTTP listener. #### `server.version` Access: read only. The **hapi** module version number. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server(); console.log(server.version); // '17.0.0' ``` ### `server.auth.default(options)` Sets a default strategy which is applied to every route where: - `options` - one of: - a string with the default strategy name - an authentication configuration object using the same format as the [route `auth` handler options](#route.options.auth). Return value: none. The default does not apply when a route config specifies `auth` as `false`, or has an authentication strategy configured (contains the [`strategy`](#route.options.auth.strategy) or [`strategies`](#route.options.auth.strategies) authentication settings). Otherwise, the route authentication config is applied to the defaults. Note that if the route has authentication configured, the default only applies at the time of adding the route, not at runtime. This means that calling `server.auth.default()` after adding a route with some authentication config will have no impact on the routes added prior. However, the default will apply to routes added before `server.auth.default()` is called if those routes lack any authentication config. The default auth strategy configuration can be accessed via [`server.auth.settings.default`](#server.auth.settings.default). To obtain the active authentication configuration of a route, use `server.auth.lookup(request.route)`. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); server.auth.scheme('custom', scheme); server.auth.strategy('default', 'custom'); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: function (request, h) { return request.auth.credentials.user; } }); ``` ### `server.auth.scheme(name, scheme)` Registers an authentication scheme where: - `name` - the scheme name. - `scheme` - the method implementing the scheme with signature `function(server, options)` where: - `server` - a reference to the server object the scheme is added to. Each auth strategy is given its own [`server.realm`](#server.realm) whose parent is the realm of the `server` in the call to [`server.auth.strategy()`](#server.auth.strategy()). - `options` - (optional) the scheme `options` argument passed to [`server.auth.strategy()`](#server.auth.strategy()) when instantiation a strategy. Return value: none. The `scheme` function must return an [authentication scheme object](#authentication-scheme) when invoked. #### Authentication scheme An authentication scheme is an object with the following properties: - `api` - (optional) object which is exposed via the [`server.auth.api`](#server.auth.api) object. - `async authenticate(request, h)` - (required) a [lifecycle method](#lifecycle-methods) function called for each incoming request configured with the authentication scheme. The method is provided with two special toolkit methods for returning an authenticated or an unauthenticate result: - [`h.authenticated()`](#h.authenticated()) - indicate request authenticated successfully. - [`h.unauthenticated()`](#h.unauthenticated()) - indicate request failed to authenticate. - `async payload(request, h)` - (optional) a [lifecycle method](#lifecycle-methods) to authenticate the request payload. - `async response(request, h)` - (optional) a [lifecycle method](#lifecycle-methods) to decorate the response with authentication headers before the response headers or payload is written. - `async verify(auth)` - (optional) a method used to verify the authentication credentials provided are still valid (e.g. not expired or revoked after the initial authentication) where: - `auth` - the [`request.auth`](#request.auth) object containing the `credentials` and `artifacts` objects returned by the scheme's `authenticate()` method. - the method throws an `Error` when the credentials passed are no longer valid (e.g. expired or revoked). Note that the method does not have access to the original request, only to the credentials and artifacts produced by the `authenticate()` method. - `options` - (optional) an object with the following keys: - `payload` - if `true`, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to `false`. When the scheme `authenticate()` method implementation throws an error or calls [`h.unauthenticated()`](#h.unauthenticated()), the specifics of the error affect whether additional authentication strategies will be attempted (if configured for the route). If the error includes a message, no additional strategies will be attempted. If the `err` does not include a message but does include the scheme name (e.g. `Boom.unauthorized(null, 'Custom')`), additional strategies will be attempted in the order of preference (defined in the route configuration). If authentication fails, the scheme names will be present in the 'WWW-Authenticate' header. When the scheme `payload()` method throws an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. `Boom.unauthorized(null, 'Custom')`), authentication may still be successful if the route [`auth.payload`](#route.options.auth.payload) configuration is set to `'optional'`. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const scheme = function (server, options) { return { authenticate: function (request, h) { const req = request.raw.req; const authorization = req.headers.authorization; if (!authorization) { throw Boom.unauthorized(null, 'Custom'); } return h.authenticated({ credentials: { user: 'john' } }); } }; }; server.auth.scheme('custom', scheme); ``` ### `server.auth.strategy(name, scheme, [options])` Registers an authentication strategy where: - `name` - the strategy name. - `scheme` - the scheme name (must be previously registered using [`server.auth.scheme()`](#server.auth.scheme())). - `options` - scheme options based on the scheme requirements. Return value: none. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); server.auth.scheme('custom', scheme); server.auth.strategy('default', 'custom'); server.route({ method: 'GET', path: '/', options: { auth: 'default', handler: function (request, h) { return request.auth.credentials.user; } } }); ``` ### `await server.auth.test(strategy, request)` Tests a request against an authentication strategy where: - `strategy` - the strategy name registered with [`server.auth.strategy()`](#server.auth.strategy()). - `request` - the [request object](#request). Return value: an object containing the authentication `credentials` and `artifacts` if authentication was successful, otherwise throws an error. Note that the `test()` method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); server.auth.scheme('custom', scheme); server.auth.strategy('default', 'custom'); server.route({ method: 'GET', path: '/', handler: async function (request, h) { try { const { credentials, artifacts } = await request.server.auth.test('default', request); return { status: true, user: credentials.name }; } catch (err) { return { status: false }; } } }); ``` ### `await server.auth.verify(request)` Verify a request's authentication credentials against an authentication strategy where: - `request` - the [request object](#request). Return value: nothing if verification was successful, otherwise throws an error. Note that the `verify()` method does not take into account the route authentication configuration or any other information from the request other than the `request.auth` object. It also does not perform payload authentication. It is limited to verifying that the previously valid credentials are still valid (e.g. have not been revoked or expired). It does not include verifying scope, entity, or other route properties. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); server.auth.scheme('custom', scheme); server.auth.strategy('default', 'custom'); server.route({ method: 'GET', path: '/', handler: async function (request, h) { try { const credentials = await request.server.auth.verify(request); return { status: true, user: credentials.name }; } catch (err) { return { status: false }; } } }); ``` ### `server.bind(context)` Sets a global context used as the default bind object when adding a route or an extension where: - `context` - the object used to bind `this` in [lifecycle methods](#lifecycle-methods) such as the [route handler](#route.options.handler) and [extension methods](#server.ext()). The context is also made available as [`h.context`](#h.context). Return value: none. When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. Ignored if the method being bound is an arrow function. ```js const handler = function (request, h) { return this.message; // Or h.context.message }; exports.plugin = { name: 'example', register: function (server, options) { const bind = { message: 'hello' }; server.bind(bind); server.route({ method: 'GET', path: '/', handler }); } }; ``` ### `server.cache(options)` Provisions a cache segment within the server cache facility where: - `options` - [**catbox** policy](https://hapi.dev/family/catbox/api#policy) configuration where: - `expiresIn` - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with `expiresAt`. - `expiresAt` - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with `expiresIn`. - `generateFunc` - a function used to generate a new cache item if one is not found in the cache when calling `get()`. The method's signature is `async function(id, flags)` where: - `id` - the `id` string or object provided to the `get()` method. - `flags` - an object used to pass back additional flags to the cache where: - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. - `staleIn` - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when `generateFunc` is provided. Must be less than `expiresIn`. - `staleTimeout` - number of milliseconds to wait before checking if an item is stale. - `generateTimeout` - number of milliseconds to wait before returning a timeout error when the `generateFunc` function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if `generateFunc` is present. Set to `false` to disable timeouts which may cause all `get()` requests to get stuck forever. - `generateOnReadError` - if `false`, an upstream cache read error will stop the `cache.get()` method from calling the generate function and will instead pass back the cache error. Defaults to `true`. - `generateIgnoreWriteError` - if `false`, an upstream cache write error when calling `cache.get()` will be passed back with the generated value when calling. Defaults to `true`. - `dropOnError` - if `true`, an error or timeout in the `generateFunc` causes the stale value to be evicted from the cache. Defaults to `true`. - `pendingGenerateTimeout` - number of milliseconds while `generateFunc` call is in progress for a given id, before a subsequent `generateFunc` call is allowed. Defaults to `0` (no blocking of concurrent `generateFunc` calls beyond `staleTimeout`). - `cache` - the cache name configured in [`server.cache`](#server.options.cache). Defaults to the default cache. - `segment` - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. - `shared` - if `true`, allows multiple cache provisions to share the same segment. Default to `false`. Return value: a [**catbox** policy](https://hapi.dev/family/catbox/api#policy) object. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); const cache = server.cache({ segment: 'countries', expiresIn: 60 * 60 * 1000 }); await cache.set('norway', { capital: 'oslo' }); const value = await cache.get('norway'); } ``` ### `await server.cache.provision(options)` Provisions a server cache as described in [`server.cache`](#server.options.cache) where: - `options` - same as the server [`cache`](#server.options.cache) configuration options. Return value: none. Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); await server.initialize(); await server.cache.provision({ provider: require('@hapi/catbox-memory'), name: 'countries' }); const cache = server.cache({ cache: 'countries', expiresIn: 60 * 60 * 1000 }); await cache.set('norway', { capital: 'oslo' }); const value = await cache.get('norway'); } ``` ### `server.control(server)` Links another server to the initialize/start/stop state of the current server by calling the controlled server `initialize()`/`start()`/`stop()` methods whenever the current server methods are called, where: - `server` - the **hapi** server object to be controlled. ### `server.decoder(encoding, decoder)` Registers a custom content decoding compressor to extend the built-in support for `'gzip'` and '`deflate`' where: - `encoding` - the decoder name string. - `decoder` - a function using the signature `function(options)` where `options` are the encoding specific options configured in the route [`payload.compression`](#route.options.payload.compression) configuration option, and the return value is an object compatible with the output of node's [`zlib.createGunzip()`](https://nodejs.org/api/zlib.html#zlib_zlib_creategunzip_options). Return value: none. ```js const Zlib = require('zlib'); const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); server.decoder('special', (options) => Zlib.createGunzip(options)); ``` ### `server.decorate(type, property, method, [options])` Extends various framework interfaces with custom methods where: - `type` - the interface being decorated. Supported types: - `'handler'` - adds a new handler type to be used in [routes handlers](#route.options.handler). - `'request'` - adds methods to the [Request object](#request). - `'response'` - adds methods to the [Response object](#response-object). - `'server'` - adds methods to the [Server](#server) object. - `'toolkit'` - adds methods to the [response toolkit](#response-toolkit). - `property` - the object decoration key name or symbol. - `method` - the extension function or other value. - `options` - (optional) supports the following optional settings: - `apply` - when the `type` is `'request'`, if `true`, the `method` function is invoked using the signature `function(request)` where `request` is the current request object and the returned value is assigned as the decoration. - `extend` - if `true`, overrides an existing decoration. The `method` must be a function with the signature `function(existing)` where: - `existing` - is the previously set decoration method value. - must return the new decoration function or value. - cannot be used to extend handler decorations. Return value: none. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const success = function () { return this.response({ status: 'ok' }); }; server.decorate('toolkit', 'success', success); server.route({ method: 'GET', path: '/', handler: function (request, h) { return h.success(); } }); ``` When registering a handler decoration, the `method` must be a function using the signature `function(route, options)` where: - `route` - the [route information](#request.route). - `options` - the configuration object provided in the handler config. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ host: 'localhost', port: 8000 }); // Defines new handler for routes on this server const handler = function (route, options) { return function (request, h) { return 'new handler: ' + options.msg; } }; server.decorate('handler', 'test', handler); server.route({ method: 'GET', path: '/', handler: { test: { msg: 'test' } } }); await server.start(); } ``` The `method` function can have a `defaults` object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature `function(method)` and returns the route default configuration. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ host: 'localhost', port: 8000 }); const handler = function (route, options) { return function (request, h) { return 'new handler: ' + options.msg; } }; // Change the default payload processing for this handler handler.defaults = { payload: { output: 'stream', parse: false } }; server.decorate('handler', 'test', handler); ``` ### `server.dependency(dependencies, [after])` Used within a plugin to declare a required dependency on other [plugins](#plugins) required for the current plugin to operate (plugins listed must be registered before the server is initialized or started) where: - `dependencies` - one of: - a single plugin name string. - an array of plugin name strings. - an object where each key is a plugin name and each matching value is a [version range string](https://www.npmjs.com/package/semver) which must match the registered plugin version. - `after` - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. The function signature is `async function(server)` where: - `server` - the server the `dependency()` method was called on. Return value: none. The `after` method is identical to setting a server extension point on `'onPreStart'`. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an `after` function to be called after the other). ```js const after = function (server) { // Additional plugin registration logic }; exports.plugin = { name: 'example', register: function (server, options) { server.dependency('yar', after); } }; ``` Dependencies can also be set via the plugin `dependencies` property (does not support setting `after`): ```js exports.plugin = { name: 'test', version: '1.0.0', dependencies: { yar: '1.x.x' }, register: function (server, options) { } }; ``` The `dependencies` configuration accepts one of: - a single plugin name string. - an array of plugin name strings. - an object where each key is a plugin name and each matching value is a [version range string](https://www.npmjs.com/package/semver) which must match the registered plugin version. ### `server.encoder(encoding, encoder)` Registers a custom content encoding compressor to extend the built-in support for `'gzip'` and '`deflate`' where: - `encoding` - the encoder name string. - `encoder` - a function using the signature `function(options)` where `options` are the encoding specific options configured in the route [`compression`](#route.options.compression) option, and the return value is an object compatible with the output of node's [`zlib.createGzip()`](https://nodejs.org/api/zlib.html#zlib_zlib_creategzip_options). Return value: none. ```js const Zlib = require('zlib'); const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80, routes: { compression: { special: { chunkSize: 16 * 1024 } } } }); server.encoder('special', (options) => Zlib.createGzip(options)); ``` ### `server.event(events)` Register custom application events where: - `events` - must be one of: - an event name string. - an event options object with the following optional keys (unless noted otherwise): - `name` - the event name string (required). - `channels` - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). - `clone` - if `true`, the `data` object passed to [`server.events.emit()`](#server.events.emit()) is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to `false` (`data` is passed as-is). - `spread` - if `true`, the `data` object passed to [`server.event.emit()`](#server.event.emit()) must be an array and the `listener` method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to `false` (`data` is emitted as a single argument regardless of its type). - `tags` - if `true` and the `criteria` object passed to [`server.event.emit()`](#server.event.emit()) includes `tags`, the tags are mapped to an object (where each tag string is the key and the value is `true`) which is appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to `false`. - `shared` - if `true`, the same event `name` can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to `false` (a duplicate registration will throw an error). - an array containing any of the above. Return value: none. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); server.event('test'); server.events.on('test', (update) => console.log(update)); await server.events.gauge('test', 'hello'); } ``` ### `server.events.emit(criteria, data)` Emits a custom application event to all the subscribed listeners where: - `criteria` - the event update criteria which must be one of: - the event name string. - an object with the following optional keys (unless noted otherwise): - `name` - the event name string (required). - `channel` - the channel name string. - `tags` - a tag string or array of tag strings. - `data` - the value emitted to the subscribers. If `data` is a function, the function signature is `function()` and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the `data` function is not invoked. Return value: none. Note that events must be registered before they can be emitted or subscribed to by calling [`server.event(events)`](#server.event()). This is done to detect event name misspelling and invalid event activities. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); server.event('test'); server.events.on('test', (update) => console.log(update)); server.events.emit('test', 'hello'); } ``` ### `server.events.on(criteria, listener, context)` Subscribe to an event where: - `criteria` - the subscription criteria which must be one of: - event name string which can be any of the [built-in server events](#server.events) or a custom application event registered with [`server.event()`](#server.event()). - a criteria object with the following optional keys (unless noted otherwise): - `name` - (required) the event name string. - `channels` - a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the `channels` array must match the allowed channels. If `channels` are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. - `clone` - if `true`, the `data` object passed to [`server.event.emit()`](#server.event.emit()) is cloned before it is passed to the `listener` method. Defaults to the event registration option (which defaults to `false`). - `count` - a positive integer indicating the number of times the `listener` can be called after which the subscription is automatically removed. A count of `1` is the same as calling `server.events.once()`. Defaults to no limit. - `filter` - the event tags (if present) to subscribe to which can be one of: - a tag string. - an array of tag strings. - an object with the following: - `tags` - a tag string or array of tag strings. - `all` - if `true`, all `tags` must be present for the event update to match the subscription. Defaults to `false` (at least one matching tag). - `spread` - if `true`, and the `data` object passed to [`server.event.emit()`](#server.event.emit()) is an array, the `listener` method is called with each array element passed as a separate argument. This should only be used when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to `false`). - `tags` - if `true` and the `criteria` object passed to [`server.event.emit()`](#server.event.emit()) includes `tags`, the tags are mapped to an object (where each tag string is the key and the value is `true`) which is appended to the arguments list at the end. Defaults to the event registration option (which defaults to `false`). - `listener` - the handler method set to receive event updates. The function signature depends on the event argument, and the `spread` and `tags` options. - `context` - an object that binds to the listener handler. Return value: none. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); server.event('test'); server.events.on('test', (update) => console.log(update)); server.events.emit('test', 'hello'); } ``` ### `server.events.once(criteria, listener, context)` Same as calling [`server.events.on()`](#server.events.on()) with the `count` option set to `1`. Return value: none. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); server.event('test'); server.events.once('test', (update) => console.log(update)); server.events.emit('test', 'hello'); server.events.emit('test', 'hello'); // Ignored } ``` ### `await server.events.once(criteria)` Same as calling [`server.events.on()`](#server.events.on()) with the `count` option set to `1`. Return value: a promise that resolves when the event is emitted. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); server.event('test'); const pending = server.events.once('test'); server.events.emit('test', 'hello'); const update = await pending; } ``` ### `await server.events.gauge(criteria, data)` Behaves identically to [`server.events.emit()`](#server.events.emit()), but also returns an array of the results of all the event listeners that run. The return value is that of `Promise.allSettled()`, where each item in the resulting array is `{ status: 'fulfilled', value }` in the case of a successful handler, or `{ status: 'rejected', reason }` in the case of a handler that throws. Please note that system errors such as a `TypeError` are not handled specially, and it's recommended to scrutinize any rejections using something like [bounce](https://hapi.dev/module/bounce/). ### `server.expose(key, value, [options])` Used within a plugin to expose a property via [`server.plugins[name]`](#server.plugins) where: - `key` - the key assigned ([`server.plugins[name][key]`](#server.plugins)). - `value` - the value assigned. - `options` - optional settings: - `scope` - controls how to handle the presence of a plugin scope in the name (e.g. `@hapi/test`): - `false` - the scope is removed (e.g. `@hapi/test` is changed to `test` under `server.plugins`). This is the default. - `true` - the scope is retained as-is (e.g. `@hapi/test` is used as `server.plugins['@hapi/test']`). - `'underscore'` - the scope is rewritten (e.g. `@hapi/test` is used as `server.plugins.hapi__test`). Return value: none. ```js exports.plugin = name: 'example', register: function (server, options) { server.expose('util', () => console.log('something')); } }; ``` ### `server.expose(obj)` Merges an object into to the existing content of [`server.plugins[name]`](#server.plugins) where: - `obj` - the object merged into the exposed properties container. Return value: none. ```js exports.plugin = { name: 'example', register: function (server, options) { server.expose({ util: () => console.log('something') }); } }; ``` Note that all the properties of `obj` are deeply cloned into [`server.plugins[name]`](#server.plugins), so avoid using this method for exposing large objects that may be expensive to clone or singleton objects such as database client objects. Instead favor [`server.expose(key, value)`](#server.expose()), which only copies a reference to `value`. ### `server.ext(events)` Registers an extension function in one of the [request lifecycle](#request-lifecycle) extension points where: - `events` - an object or array of objects with the following: - `type` - (required) the extension point event name. The available extension points include the [request extension points](#request-lifecycle) as well as the following server extension points: - `'onPreStart'` - called before the connection listeners are started. - `'onPostStart'` - called after the connection listeners are started. - `'onPreStop'` - called before the connection listeners are stopped. - `'onPostStop'` - called after the connection listeners are stopped. - `method` - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: - server extension points: `async function(server)` where: - `server` - the server object. - `this` - the object provided via `options.bind` or the current active context set with [`server.bind()`](#server.bind()). - request extension points: a [lifecycle method](#lifecycle-methods). - `options` - (optional) an object with the following: - `before` - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. - `after` - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. - `bind` - a context object passed back to the provided method (via `this`) when called. Ignored if the method is an arrow function. - `sandbox` - if set to `'plugin'` when adding a [request extension points](#request-lifecycle) the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to `'server'` which applies to any route added to the server the extension is added to. - `timeout` - number of milliseconds to wait for the `method` to complete before returning a timeout error. Defaults to no timeout. Return value: none. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); server.ext({ type: 'onRequest', method: function (request, h) { // Change all requests to '/test' request.setUrl('/test'); return h.continue; } }); server.route({ method: 'GET', path: '/test', handler: () => 'ok' }); await server.start(); // All requests will get routed to '/test' } ``` ### `server.ext(event, [method, [options]])` Registers a single extension event using the same properties as used in [`server.ext(events)`](#server.ext()), but passed as arguments. The `method` may be omitted (if `options` isn't present) or passed `null` which will cause the function to return a promise. The promise is resolved with the `request` object on the first invocation of the extension point. This is primarily used for writing tests without having to write custom handlers just to handle a single event. Return value: a promise if `method` is omitted, otherwise `undefined`. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); server.ext('onRequest', function (request, h) { // Change all requests to '/test' request.setUrl('/test'); return h.continue; }); server.route({ method: 'GET', path: '/test', handler: () => 'ok' }); await server.start(); // All requests will get routed to '/test' } ``` ### `await server.initialize()` Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. Return value: none. Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call [`server.stop()`](#server.stop()) first to reset the server state. ```js const Hapi = require('@hapi/hapi'); const Hoek = require('@hapi/hoek'); async function example() { const server = Hapi.server({ port: 80 }); await server.initialize(); } ``` ### `await server.inject(options)` Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead and limitations of the network stack. The method utilizes the [**shot**](https://hapi.dev/family/shot/api) module for performing injections, with some additional options and response properties: - `options` - can be assigned a string with the requested URI, or an object with: - `method` - (optional) the request HTTP method (e.g. `'POST'`). Defaults to `'GET'`. - `url` - (required) the request URL. If the URI includes an authority (e.g. `'example.com:8080'`), it is used to automatically set an HTTP 'Host' header, unless one was specified in `headers`. - `authority` - (optional) a string specifying the HTTP 'Host' header value. Only used if 'Host' is not specified in `headers` and the `url` does not include an authority component. Default is inferred from runtime server information. - `headers` - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default **shot** headers. - `payload` - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to `'application/json'` if no 'Content-Type' header provided. - `auth` - (optional) an object containing parsed authentication credentials where: - `strategy` - (required) the authentication strategy name matching the provided credentials. - `credentials` - (required) a credentials object containing authentication information. The `credentials` are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. - `artifacts` - (optional) an artifacts object containing authentication artifact information. The `artifacts` are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no artifacts. - `payload` - (optional) disables payload authentication when set to false. Only required when an authentication strategy requires payload authentication. Defaults to `true`. - `app` - (optional) sets the initial value of `request.app`, defaults to `{}`. - `plugins` - (optional) sets the initial value of `request.plugins`, defaults to `{}`. - `allowInternals` - (optional) allows access to routes with `options.isInternal` set to `true`. Defaults to `false`. - `remoteAddress` - (optional) sets the remote address for the incoming connection. - `simulate` - (optional) an object with options used to simulate client request stream conditions for testing: - `error` - if `true`, emits an `'error'` event after payload transmission (if any). Defaults to `false`. - `close` - if `true`, emits a `'close'` event after payload transmission (if any). Defaults to `false`. - `end` - if `false`, does not end the stream. Defaults to `true`. - `split` - indicates whether the request payload will be split into chunks. Defaults to `undefined`, meaning payload will not be chunked. - `validate` - (optional) if `false`, the `options` inputs are not validated. This is recommended for run-time usage of `inject()` to make it perform faster where input validation can be tested separately. Return value: a response object with the following properties: - `statusCode` - the HTTP status code. - `headers` - an object containing the headers set. - `payload` - the response payload string. - `rawPayload` - the raw response payload buffer. - `raw` - an object with the injection request and response objects: - `req` - the simulated node request object. - `res` - the simulated node response object. - `result` - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to `payload`. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). - `request` - the [request object](#request). Throws a Boom error if the request processing fails. The partial response object is exposed on the `data` property. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); server.route({ method: 'GET', path: '/', handler: () => 'Success!' }); const res = await server.inject('/'); console.log(res.result); // 'Success!' } ``` ### `server.log(tags, [data, [timestamp]])` Logs server events that cannot be associated with a specific request. When called the server emits a `'log'` event which can be used by other listeners or [plugins](#plugins) to record the information or output to the console. The arguments are: - `tags` - (required) a string or an array of strings (e.g. `['error', 'database', 'read']`) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the `'hapi'` tag along with event-specific information. - `data` - (optional) an message string or object with the application data being logged. If `data` is a function, the function signature is `function()` and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the `data` function is not invoked. - `timestamp` - (optional) an timestamp expressed in milliseconds. Defaults to `Date.now()` (now). Return value: none. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); server.events.on('log', (event, tags) => { if (tags.error) { console.log(event); } }); server.log(['test', 'error'], 'Test event'); ``` ### `server.lookup(id)` Looks up a route configuration where: - `id` - the [route identifier](#route.options.id). Return value: the [route information](#request.route) if found, otherwise `null`. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { id: 'root', handler: () => 'ok' } }); const route = server.lookup('root'); ``` ### `server.match(method, path, [host])` Looks up a route configuration where: - `method` - the HTTP method (e.g. 'GET', 'POST'). - `path` - the requested path (must begin with '/'). - `host` - (optional) hostname (to match against routes with `vhost`). Return value: the [route information](#request.route) if found, otherwise `null`. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { id: 'root', handler: () => 'ok' } }); const route = server.match('get', '/'); ``` ### `server.method(name, method, [options])` Registers a [server method](#server.methods) where: - `name` - a unique method name used to invoke the method via [`server.methods[name]`](#server.method). - `method` - the method function with a signature `async function(...args, [flags])` where: - `...args` - the method function arguments (can be any number of arguments or none). - `flags` - when caching is enabled, an object used to set optional method result flags. This parameter is provided automatically and can only be accessed/modified within the method function. It cannot be passed as an argument. - `ttl` - `0` if result is valid but cannot be cached. Defaults to cache policy. - `options` - (optional) configuration object: - `bind` - a context object passed back to the method function (via `this`) when called. Defaults to active context (set via [`server.bind()`](#server.bind()) when the method is registered. Ignored if the method is an arrow function. - `cache` - the same cache configuration used in [`server.cache()`](#server.cache()). The `generateTimeout` option is required, and the `generateFunc` options is not allowed. - `generateKey` - a function used to generate a unique key (for caching) from the arguments passed to the method function (the `flags` argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types `'string'`, `'number'`, or `'boolean'`. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or `null` if no key can be generated). Return value: none. Method names can be nested (e.g. `utils.users.get`) which will automatically create the full path under [`server.methods`](#server.methods) (e.g. accessed via `server.methods.utils.users.get`). When configured with caching enabled, `server.methods[name].cache` is assigned an object with the following properties and methods: - `await drop(...args)` - a function that can be used to clear the cache for a given key. - `stats` - an object with cache statistics, see **catbox** for stats documentation. Simple arguments example: ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); const add = (a, b) => (a + b); server.method('sum', add, { cache: { expiresIn: 2000, generateTimeout: 100 } }); console.log(await server.methods.sum(4, 5)); // 9 } ``` Object argument example: ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); const addArray = function (array) { let sum = 0; array.forEach((item) => { sum += item; }); return sum; }; const options = { cache: { expiresIn: 2000, generateTimeout: 100 }, generateKey: (array) => array.join(',') }; server.method('sumObj', addArray, options); console.log(await server.methods.sumObj([5, 6])); // 11 } ``` ### `server.method(methods)` Registers a server method function as described in [`server.method()`](#server.method()) using a configuration object where: - `methods` - an object or an array of objects where each one contains: - `name` - the method name. - `method` - the method function. - `options` - (optional) settings. Return value: none. ```js const add = function (a, b) { return a + b; }; server.method({ name: 'sum', method: add, options: { cache: { expiresIn: 2000, generateTimeout: 100 } } }); ``` ### `server.path(relativeTo)` Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: - `relativeTo` - the path prefix added to any relative file path starting with `'.'`. Return value: none. Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default [route configuration](#server.options.routes) [`files.relativeTo`](#route.options.files) settings is used. The path only applies to routes added after it has been set. ```js exports.plugin = { name: 'example', register: function (server, options) { // Assuming the Inert plugin was registered previously server.path(__dirname + '../static'); server.route({ path: '/file', method: 'GET', handler: { file: './test.html' } }); } }; ``` ### `await server.register(plugins, [options])` Registers a plugin where: - `plugins` - one or an array of: - a [plugin object](#plugins). - an object with the following: - `plugin` - a [plugin object](#plugins). - `options` - (optional) options passed to the plugin during registration. - `once`, `routes` - (optional) plugin-specific registration options as defined below. - `options` - (optional) registration options (different from the options passed to the registration function): - `once` - if `true`, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to `false`. If not set to `true`, an error will be thrown the second time a plugin is registered on the server. - `routes` - modifiers applied to each route added by the plugin: - `prefix` - string added as prefix to any route path (must begin with `'/'`). If a plugin registers a child plugin the `prefix` is passed on to the child or is added in front of the child-specific prefix. - `vhost` - virtual host string (or array of strings) applied to every route. The outer-most `vhost` overrides the any nested configuration. Return value: a reference to the `server`. ```js async function example() { await server.register({ plugin: require('plugin_name'), options: { message: 'hello' } }); } ``` ### `server.route(route)` Adds a route where: - `route` - a route configuration object or an array of configuration objects where each object contains: - `path` - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's [`router`](#server.options.router) configuration. The path can include named parameters enclosed in `{}` which will be matched against literal values in the request as described in [Path parameters](#path-parameters). - `method` - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use `'*'` to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. - `vhost` - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. - `handler` - (required when [`handler`](#route.options.handler) is not set) the route handler function called to generate the response after successful authentication and validation. - `options` - additional [route options](#route-options). The `options` value can be an object or a function that returns an object using the signature `function(server)` where `server` is the server the route is being added to and `this` is bound to the current [realm](#server.realm)'s `bind` option. - `rules` - route custom rules object. The object is passed to each rules processor registered with [`server.rules()`](#server.rules()). Cannot be used if [`route.options.rules`](#route.options.rules) is defined. Return value: none. Note that the `options` object is deeply cloned (with the exception of `bind` which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); // Handler in top level server.route({ method: 'GET', path: '/status', handler: () => 'ok' }); // Handler in config const user = { cache: { expiresIn: 5000 }, handler: function (request, h) { return { name: 'John' }; } }; server.route({ method: 'GET', path: '/user', options: user }); // An array of routes server.route([ { method: 'GET', path: '/1', handler: function (request, h) { return 'ok'; } }, { method: 'GET', path: '/2', handler: function (request, h) { return 'ok'; } } ]); ``` #### Path parameters Parameterized paths are processed by matching the named parameters to the content of the incoming request path at that path segment. For example, `'/book/{id}/cover'` will match `'/book/123/cover'` and `request.params.id` will be set to `'123'`. Each path segment (everything between the opening `'/'` and the closing `'/'` unless it is the end of the path) can only include one named parameter. A parameter can cover the entire segment (`'/{param}'`) or part of the segment (`'/file.{ext}'`). A path parameter may only contain letters, numbers and underscores, e.g. `'/{file-name}'` is invalid and `'/{file_name}'` is valid. An optional `'?'` suffix following the parameter name indicates an optional parameter (only allowed if the parameter is at the ends of the path or only covers part of the segment as in `'/a{param?}/b'`). For example, the route `'/book/{id?}'` matches `'/book/'` with the value of `request.params.id` set to an empty string `''`. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const getAlbum = function (request, h) { return 'You asked for ' + (request.params.song ? request.params.song + ' from ' : '') + request.params.album; }; server.route({ path: '/{album}/{song?}', method: 'GET', handler: getAlbum }); ``` In addition to the optional `?` suffix, a parameter name can also specify the number of matching segments using the `*` suffix, followed by a number greater than 1. If the number of expected parts can be anything, then use `*` without a number (matching any number of segments can only be used in the last path segment). ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const getPerson = function (request, h) { const nameParts = request.params.name.split('/'); return { first: nameParts[0], last: nameParts[1] }; }; server.route({ path: '/person/{name*2}', // Matches '/person/john/doe' method: 'GET', handler: getPerson }); ``` #### Path matching order The router iterates through the routing table on each incoming request and executes the first (and only the first) matching route. Route matching is done based on the combination of the request path and the HTTP verb (e.g. 'GET, 'POST'). The query is excluded from the routing logic. Requests are matched in a deterministic order where the order in which routes are added does not matter. Routes are matched based on the specificity of the route which is evaluated at each segment of the incoming request path. Each request path is split into its segment (the parts separated by `'/'`). The segments are compared to the routing table one at a time and are matched against the most specific path until a match is found. If no match is found, the next match is tried. When matching routes, string literals (no path parameter) have the highest priority, followed by mixed parameters (`'/a{p}b'`), parameters (`'/{p}'`), and then wildcard (`/{p*}`). Note that mixed parameters are slower to compare as they cannot be hashed and require an array iteration over all the regular expressions representing the various mixed parameter at each routing table node. #### Catch all route If the application needs to override the default Not Found (404) error response, it can add a catch-all route for a specific method or all methods. Only one catch-all route can be defined. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const handler = function (request, h) { return h.response('The page was not found').code(404); }; server.route({ method: '*', path: '/{p*}', handler }); ``` ### `server.rules(processor, [options])` Defines a route rules processor for converting route rules object into route configuration where: - `processor` - a function using the signature `function(rules, info)` where: - `rules` - the [custom object](#route.options.rules) defined in your routes configuration for you to use its values. - `info` - an object with the following properties: - `method` - the route method. - `path` - the route path. - `vhost` - the route virtual host (if any defined). - returns a route config object. - `options` - optional settings: - `validate` - rules object validation: - `schema` - **joi** schema. - `options` - optional **joi** validation options. Defaults to `{ allowUnknown: true }`. Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config. Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin overrides the config generated by the root processor if they overlap. Similarly, the route's own config overrides the config produced by the rules processors. ```js const validateSchema = { auth: Joi.string(), myCustomPre: Joi.array().min(2).items(Joi.string()), payload: Joi.object() }; const myPreHelper = (name) => { return { method: (request, h) => { return `hello ${name || 'world'}!`; }, assign: 'myPreHelper' }; }; const processor = (rules, info) => { if (!rules) { return null; } const options = {}; if (rules.auth) { options.auth = { strategy: rules.auth, validate: { entity: 'user' } }; } if (rules.myCustomPre) { options.pre = [ myPreHelper(...rules.myCustomPre) ]; } if (rules.payload) { options.validate = { payload: Joi.object(rules.payload) }; } return options; }; server.rules(processor, { validate: { schema: validateSchema } }); server.route({ method: 'GET', path: '/', rules: { auth: 'jwt', myCustomPre: ['arg1', 'arg2'], payload: { a: Joi.boolean(), b: Joi.string() } }, options: { id: 'my-route' } }); ``` ### `await server.start()` Starts the server by listening for incoming requests on the configured port (unless the connection was configured with [`autoListen`](#server.options.autoListen) set to `false`). Return value: none. Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call [`server.stop()`](#server.stop()) first to reset the server state. If a started server is started again, the second call to `server.start()` is ignored. No events will be emitted and no extension points invoked. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); await server.start(); console.log('Server started at: ' + server.info.uri); } ``` ### `server.state(name, [options])` [HTTP state management](https://tools.ietf.org/html/rfc6265) uses client cookies to persist a state across multiple requests. Registers a cookie definitions where: - `name` - the cookie name string. - `options` - are the optional cookie settings: - `ttl` - time-to-live in milliseconds. Defaults to `null` (session time-life - cookies are deleted when the browser is closed). - `isSecure` - sets the 'Secure' flag. Defaults to `true`. - `isHttpOnly` - sets the 'HttpOnly' flag. Defaults to `true`. - `isSameSite` - sets the ['SameSite' flag](https://www.owasp.org/index.php/SameSite). The value must be one of: - `false` - no flag. - `'Strict'` - sets the value to `'Strict'` (this is the default value). - `'Lax'` - sets the value to `'Lax'`. - `'None'` - sets the value to `'None'`. - `isPartitioned` - sets the ['Partitioned' flag](https://developers.google.com/privacy-sandbox/3pcd/chips). Defaults to `false`. Requires `isSecure` to be `true` and `isSameSite` to be `'None'`. - `path` - the path scope. Defaults to `null` (no path). - `domain` - the domain scope. Defaults to `null` (no domain). - `autoValue` - if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature `async function(request)` where: - `request` - the [request object](#request). - `encoding` - encoding performs on the provided value before serialization. Options are: - `'none'` - no encoding. When used, the cookie value must be a string. This is the default value. - `'base64'` - string value is encoded using Base64. - `'base64json'` - object value is JSON-stringified then encoded using Base64. - `'form'` - object value is encoded using the _x-www-form-urlencoded_ method. - `'iron'` - Encrypts and sign the value using [**iron**](https://hapi.dev/family/iron/api). - `sign` - an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean to verify that the cookie value was generated by the server. Redundant when `'iron'` encoding is used. Options are: - `integrity` - algorithm options. Defaults to [`require('iron').defaults.integrity`](https://hapi.dev/family/iron/api/#options). - `password` - password used for HMAC key generation (must be at least 32 characters long). - `password` - password used for `'iron'` encoding (must be at least 32 characters long). - `iron` - options for `'iron'` encoding. Defaults to [`require('iron').defaults`](https://hapi.dev/family/iron/api/#options). - `ignoreErrors` - if `true`, errors are ignored and treated as missing cookies. - `clearInvalid` - if `true`, automatically instruct the client to remove invalid cookies. Defaults to `false`. - `strictHeader` - if `false`, allows any cookie value including values in violation of [RFC 6265](https://tools.ietf.org/html/rfc6265). Defaults to `true`. - `passThrough` - used by proxy plugins (e.g. [**h2o2**](https://hapi.dev/family/h2o2/api)). - `contextualize` - a function using the signature `async function(definition, request)` used to override a request-specific cookie settings where: - `definition` - a copy of the `options` to be used for formatting the cookie that can be manipulated by the function to customize the request cookie header. Note that changing the `definition.contextualize` property will be ignored. - `request` - the current request object. Return value: none. State defaults can be modified via the [server.options.state](#server.options.state) configuration option. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); // Set cookie definition server.state('session', { ttl: 24 * 60 * 60 * 1000, // One day isSecure: true, path: '/', encoding: 'base64json' }); // Set state in route handler const handler = function (request, h) { let session = request.state.session; if (!session) { session = { user: 'joe' }; } session.last = Date.now(); return h.response('Success').state('session', session); }; ``` Registered cookies are automatically parsed when received. Parsing rules depends on the route [`state.parse`](#route.options.state) configuration. If an incoming registered cookie fails parsing, it is not included in [`request.state`](#request.state), regardless of the [`state.failAction`](#route.options.state.failAction) setting. When [`state.failAction`](#route.options.state.failAction) is set to `'log'` and an invalid cookie value is received, the server will emit a [`'request'` event](#server.events.request). To capture these errors subscribe to the `'request'` event on the `'internal'` channel and filter on `'error'` and `'state'` tags: ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); server.events.on({ name: 'request', channels: 'internal' }, (request, event, tags) => { if (tags.error && tags.state) { console.error(event); } }); ``` ### `server.states.add(name, [options])` Access: read only. Same as calling [`server.state()`](#server.state()). ### `await server.states.format(cookies)` Formats an HTTP 'Set-Cookie' header based on the [`server.options.state`](#server.options.state) where: - `cookies` - a single object or an array of object where each contains: - `name` - the cookie name. - `value` - the cookie value. - `options` - cookie configuration to override the server settings. Return value: a header string. Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formatting (e.g. when headers are set manually). ### `await server.states.parse(header)` Parses an HTTP 'Cookies' header based on the [`server.options.state`](#server.options.state) where: - `header` - the HTTP header. Return value: an object where each key is a cookie name and value is the parsed cookie. Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). ### `await server.stop([options])` Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: - `options` - (optional) object with: - `timeout` - sets the timeout in millisecond before forcefully terminating any open connections that arrived before the server stopped accepting new connections. The timeout only applies to waiting for existing connections to close, and not to any [`'onPreStop'` or `'onPostStop'` server extensions](#server.ext.args()) which can delay or block the stop operation indefinitely. Ignored if [`server.options.operations.cleanStop`](#server.options.operations) is `false`. Note that if the server is set as a [group controller](#server.control()), the timeout is per controlled server and the controlling server itself. Defaults to `5000` (5 seconds). Return value: none. ```js const Hapi = require('@hapi/hapi'); async function example() { const server = Hapi.server({ port: 80 }); await server.start(); await server.stop({ timeout: 60 * 1000 }); console.log('Server stopped'); } ``` ### `server.table([host])` Returns a copy of the routing table where: - `host` - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts. Return value: an array of routes where each route contains: - `settings` - the route config with defaults applied. - `method` - the HTTP method in lower case. - `path` - the route path. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); server.route({ method: 'GET', path: '/example', handler: () => 'ok' }); const table = server.table(); ``` ### `server.validator(validator)` Registers a server validation module used to compile raw validation rules into validation schemas for all routes where: - `validator` - the validation module (e.g. **joi**). Return value: none. Note: the validator is only used when validation rules are not pre-compiled schemas. When a validation rules is a function or schema object, the rule is used as-is and the validator is not used. When setting a validator inside a plugin, the validator is only applied to routes set up by the plugin and plugins registered by it. ```js const Hapi = require('@hapi/hapi'); const Joi = require('joi'); async function example() { const server = Hapi.server({ port: 80 }); server.validator(Joi); } ``` ## Route options Each route can be customized to change the default behavior of the request lifecycle. ### `route.options.app` Application-specific route configuration state. Should not be used by [plugins](#plugins) which should use `options.plugins[name]` instead. ### `route.options.auth` Route authentication configuration. Value can be: - `false` to disable authentication if a default strategy is set. - a string with the name of an authentication strategy registered with [`server.auth.strategy()`](#server.auth.strategy()). The strategy will be set to `'required'` mode. - an [authentication configuration object](#authentication-options). #### `route.options.auth.access` Default value: none. An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object must include at least one of [`scope`](#route.options.auth.access.scope) or [`entity`](#route.options.auth.access.entity). #### `route.options.auth.access.scope` Default value: `false` (no scope requirements). The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object `scope` property must contain at least one of the scopes defined to access the route. If a scope string begins with a `+` character, that scope is required. If a scope string begins with a `!` character, that scope is forbidden. For example, the scope `['!a', '+b', 'c', 'd']` means the incoming request credentials' `scope` must not include 'a', must include 'b', and must include one of 'c' or 'd'. You may also access properties on the request object (`query`, `params`, `payload`, and `credentials`) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as `'user-{params.id}'`. #### `route.options.auth.access.entity` Default value: `'any'`. The required authenticated entity type. If set, must match the `entity` value of the request authenticated credentials. Available values: - `'any'` - the authentication can be on behalf of a user or application. - `'user'` - the authentication must be on behalf of a user which is identified by the presence of a `'user'` attribute in the `credentials` object returned by the authentication strategy. - `'app'` - the authentication must be on behalf of an application which is identified by the lack of presence of a `user` attribute in the `credentials` object returned by the authentication strategy. #### `route.options.auth.mode` Default value: `'required'`. The authentication mode. Available values: - `'required'` - authentication is required. - `'optional'` - authentication is optional - the request must include valid credentials or no credentials at all. - `'try'` - similar to `'optional'`, any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error. #### `route.options.auth.payload` Default value: `false`, unless the scheme requires payload authentication. If set, the incoming request payload is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. [Hawk](https://hapi.dev/family/hawk/api)). Cannot be set to a value other than `'required'` when the scheme sets the authentication `options.payload` to `true`. Available values: - `false` - no payload authentication. - `'required'` - payload authentication required. - `'optional'` - payload authentication performed only when the client includes payload authentication information (e.g. `hash` attribute in Hawk). #### `route.options.auth.strategies` Default value: the default strategy set via [`server.auth.default()`](#server.auth.default()). An array of string strategy names in the order they should be attempted. Cannot be used together with [`strategy`](#route.options.auth.strategy). #### `route.options.auth.strategy` Default value: the default strategy set via [`server.auth.default()`](#server.auth.default()). A string strategy names. Cannot be used together with [`strategies`](#route.options.auth.strategies). ### `route.options.bind` Default value: `null`. An object passed back to the provided `handler` (via `this`) when called. Ignored if the method is an arrow function. ### `route.options.cache` Default value: `{ privacy: 'default', statuses: [200], otherwise: 'no-cache' }`. If the route method is 'GET', the route can be configured to include HTTP caching directives in the response. Caching can be customized using an object with the following options: - `privacy` - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: - `'default'` - no privacy flag. - `'public'` - mark the response as suitable for public caching. - `'private'` - mark the response as suitable only for private caching. - `expiresIn` - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with `expiresAt`. - `expiresAt` - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with `expiresIn`. - `statuses` - an array of HTTP response status code numbers (e.g. `200`) which are allowed to include a valid caching directive. - `otherwise` - a string with the value of the 'Cache-Control' header when caching is disabled. The default `Cache-Control: no-cache` header can be disabled by setting `cache` to `false`. ### `route.options.compression` An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in [`compression`](#route.options.payload.compression). ### `route.options.cors` Default value: `false` (no CORS headers). The [Cross-Origin Resource Sharing](https://www.w3.org/TR/cors/) protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. To enable, set `cors` to `true`, or to an object with the following options: - `origin` - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard `'*'` character, or a single `'*'` origin string. If set to `'ignore'`, any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to `'*'`. Defaults to any origin `['*']`. - `maxAge` - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to `86400` (one day). - `headers` - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to `['Accept', 'Authorization', 'Content-Type', 'If-None-Match']`. - `additionalHeaders` - a strings array of additional headers to `headers`. Use this to keep the default headers in place. - `exposedHeaders` - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to `['WWW-Authenticate', 'Server-Authorization']`. - `additionalExposedHeaders` - a strings array of additional headers to `exposedHeaders`. Use this to keep the default headers in place. - `credentials` - if `true`, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to `false`. - `preflightStatusCode` - the status code used for CORS preflight responses, either `200` or `204`. Defaults to `200`. ### `route.options.description` Default value: none. Route description used for generating documentation (string). This setting is not available when setting server route defaults using [`server.options.routes`](#server.options.routes). ### `route.options.ext` Default value: none. Route-level [request extension points](#request-lifecycle) by setting the option to an object with a key for each of the desired extension points (`'onRequest'` is not allowed), and the value is the same as the [`server.ext(events)`](#server.ext()) `event` argument. ### `route.options.files` Default value: `{ relativeTo: '.' }`. Defines the behavior for accessing files: - `relativeTo` - determines the folder relative paths are resolved against. ### `route.options.handler` Default value: none. The route handler function performs the main business logic of the route and sets the response. `handler` can be assigned: - a [lifecycle method](#lifecycle-methods). - an object with a single property using the name of a handler type registered with the [`server.decorate()`](#server.decorate()) method. The matching property value is passed as options to the registered handler generator. ```js const handler = function (request, h) { return 'success'; }; ``` Note: handlers using a fat arrow style function cannot be bound to any `bind` property. Instead, the bound context is available under [`h.context`](#h.context). ### `route.options.id` Default value: none. An optional unique identifier used to look up the route using [`server.lookup()`](#server.lookup()). Cannot be assigned to routes added with an array of methods. ### `route.options.isInternal` Default value: `false`. If `true`, the route cannot be accessed through the HTTP listener but only through the [`server.inject()`](#server.inject()) interface with the `allowInternals` option set to `true`. Used for internal routes that should not be accessible to the outside world. ### `route.options.json` Default value: none. Optional arguments passed to `JSON.stringify()` when converting an object or error response to a string payload or escaping it after stringification. Supports the following: - `replacer` - the replacer function or array. Defaults to no action. - `space` - number of spaces to indent nested object keys. Defaults to no indentation. - `suffix` - string suffix added after conversion to JSON string. Defaults to no suffix. - `escape` - calls [`Hoek.jsonEscape()`](https://hapi.dev/family/hoek/api/#escapejsonstring) after conversion to JSON string. Defaults to `false`. ### `route.options.log` Default value: `{ collect: false }`. Request logging options: - `collect` - if `true`, request-level logs (both internal and application) are collected and accessible via [`request.logs`](#request.logs). ### `route.options.notes` Default value: none. Route notes used for generating documentation (string or array of strings). This setting is not available when setting server route defaults using [`server.options.routes`](#server.options.routes). ### `route.options.payload` Determines how the request payload is processed. #### `route.options.payload.allow` Default value: allows parsing of the following mime types: - application/json - application/*+json - application/octet-stream - application/x-www-form-urlencoded - multipart/form-data - text/* A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed above will not enable them to be parsed, and if [`parse`](#route.options.payload.parse) is `true`, the request will result in an error response. #### `route.options.payload.compression` Default value: none. An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in [`compression`](#server.options.compression). #### `route.options.payload.defaultContentType` Default value: `'application/json'`. The default content type if the 'Content-Type' request header is missing. #### `route.options.payload.failAction` Default value: `'error'` (return a Bad Request (400) error response). A [`failAction` value](#lifecycle-failAction) which determines how to handle payload parsing errors. #### `route.options.payload.maxBytes` Default value: `1048576` (1MB). Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. #### `route.options.payload.maxParts` Default value: `1000`. Limits the number of parts allowed in multipart payloads. #### `route.options.payload.multipart` Default value: `false`. Overrides payload processing for multipart requests. Value can be one of: - `false` - disable multipart processing (this is the default value). - `true` - enable multipart processing using the [`output`](#route.options.payload.output) value. - an object with the following required options: - `output` - same as the [`output`](#route.options.payload.output) option with an additional value option: - `annotated` - wraps each multipart part in an object with the following keys: - `headers` - the part headers. - `filename` - the part file name. - `payload` - the processed part payload. #### `route.options.payload.output` Default value: `'data'`. The processed payload format. The value must be one of: - `'data'` - the incoming payload is read fully into memory. If [`parse`](#route.options.payload.parse) is `true`, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If [`parse`](#route.options.payload.parse) is `false`, a raw `Buffer` is returned. - `'stream'` - the incoming payload is made available via a `Stream.Readable` interface. If the payload is 'multipart/form-data' and [`parse`](#route.options.payload.parse) is `true`, field values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a `hapi` property containing the `filename` and `headers` properties. Note that payload streams for multipart payloads are a synthetic interface created on top of the entire multipart content loaded into memory. To avoid loading large multipart payloads into memory, set [`parse`](#route.options.payload.parse) to `false` and handle the multipart payload in the handler using a streaming parser (e.g. [**pez**](https://hapi.dev/family/pez/api)). - `'file'` - the incoming payload is written to temporary file in the directory specified by the [`uploads`](#route.options.payload.uploads) settings. If the payload is 'multipart/form-data' and [`parse`](#route.options.payload.parse) is `true`, field values are presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the `request.app` object), and listening to the server `'response'` event to perform cleanup. #### `route.options.payload.override` Default value: none. A mime type string overriding the 'Content-Type' header value received. #### `route.options.payload.parse` Default value: `true`. Determines if the incoming payload is processed or presented raw. Available values: - `true` - if the request 'Content-Type' matches the allowed mime types set by [`allow`](#route.options.payload.allow) (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded. - `false` - the raw payload is returned unmodified. - `'gunzip'` - the raw payload is returned unmodified after any known content encoding is decoded. #### `route.options.payload.protoAction` Default value: `'error'`. Sets handling of incoming payload that may contain a prototype poisoning security attack. Available values: - `'error'` - returns a `400` bad request error when the payload contains a prototype. - `'remove'` - sanitizes the payload to remove the prototype. - `'ignore'` - disables the protection and allows the payload to pass as received. Use this option only when you are sure that such incoming data cannot pose any risks to your application. #### `route.options.payload.timeout` Default value: to `10000` (10 seconds). Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response. Set to `false` to disable. #### `route.options.payload.uploads` Default value: `os.tmpdir()`. The directory used for writing file uploads. ### `route.options.plugins` Default value: `{}`. Plugin-specific configuration. `plugins` is an object where each key is a plugin name and the value is the plugin configuration. ### `route.options.pre` Default value: none. The `pre` option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared across routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). `pre` is assigned an ordered array of methods which are called serially in order. If the `pre` array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of the methods error, return a [takeover response](#takeover-response), or abort signal, the other parallel methods will continue to execute but will be ignored once completed. `pre` can be assigned a mixed array of: - an array containing the elements listed below, which are executed in parallel. - an object with: - `method` - a [lifecycle method](#lifecycle-methods). - `assign` - key name used to assign the response of the method to in [`request.pre`](#request.pre) and [`request.preResponses`](#request.preResponses). - `failAction` - A [`failAction` value](#lifecycle-failAction) which determine what to do when a pre-handler method throws an error. If `assign` is specified and the `failAction` setting is not `'error'`, the error will be assigned. - a method function - same as including an object with a single `method` key. Note that pre-handler methods do not behave the same way other [lifecycle methods](#lifecycle-methods) do when a value is returned. Instead of the return value becoming the new response payload, the value is used to assign the corresponding [`request.pre`](#request.pre) and [`request.preResponses`](#request.preResponses) properties. Otherwise, the handling of errors, [takeover response](#takeover-response) response, or abort signal behave the same as any other [lifecycle methods](#lifecycle-methods). ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const pre1 = function (request, h) { return 'Hello'; }; const pre2 = function (request, h) { return 'World'; }; const pre3 = function (request, h) { return request.pre.m1 + ' ' + request.pre.m2; }; server.route({ method: 'GET', path: '/', options: { pre: [ [ // m1 and m2 executed in parallel { method: pre1, assign: 'm1' }, { method: pre2, assign: 'm2' } ], { method: pre3, assign: 'm3' }, ], handler: function (request, h) { return request.pre.m3 + '!\n'; } } }); ``` ### `route.options.response` Processing rules for the outgoing response. #### `route.options.response.disconnectStatusCode` Default value: `499`. The default HTTP status code used to set a response error when the request is closed or aborted before the response is fully transmitted. Value can be any integer greater or equal to `400`. The default value `499` is based on the non-standard nginx "CLIENT CLOSED REQUEST" error. The value is only used for logging as the request has already ended. #### `route.options.response.emptyStatusCode` Default value: `204`. The default HTTP status code when the payload is considered empty. Value can be `200` or `204`. Note that a `200` status code is converted to a `204` only at the time of response transmission (the response status code will remain `200` throughout the request lifecycle unless manually set). #### `route.options.response.failAction` Default value: `'error'` (return an Internal Server Error (500) error response). A [`failAction` value](#lifecycle-failAction) which defines what to do when a response fails payload validation. #### `route.options.response.modify` Default value: `false`. If `true`, applies the validation rule changes to the response payload. #### `route.options.response.options` Default value: none. [**joi**](https://joi.dev/api) options object pass to the validation function. Useful to set global options such as `stripUnknown` or `abortEarly`. If a custom validation function is defined via [`schema`](#route.options.response.schema) or [`status`](#route.options.response.status) then `options` can an arbitrary object that will be passed to this function as the second argument. #### `route.options.response.ranges` Default value: `true`. If `false`, payload [range](https://tools.ietf.org/html/rfc7233#section-3) support is disabled. #### `route.options.response.sample` Default value: `100` (all responses). The percent of response payloads validated (0 - 100). Set to `0` to disable all validation. #### `route.options.response.schema` Default value: `true` (no validation). The default response payload validation rules (for all non-error responses) expressed as one of: - `true` - any payload allowed (no validation). - `false` - no payload allowed. - a [**joi**](https://joi.dev/api) validation object. The [`options`](#route.options.response.options) along with the request context (`{ headers, params, query, payload, state, app, auth }`) are passed to the validation function. - a validation function using the signature `async function(value, options)` where: - `value` - the pending response payload. - `options` - The [`options`](#route.options.response.options) along with the request context (`{ headers, params, query, payload, state, app, auth }`). - if the function returns a value and [`modify`](#route.options.response.modify) is `true`, the value is used as the new response. If the original response is an error, the return value is used to override the original error `output.payload`. If an error is thrown, the error is processed according to [`failAction`](#route.options.response.failAction). #### `route.options.response.status` Default value: none. Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default [`schema`](#route.options.response.schema). `status` is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as [`schema`](#route.options.response.schema). ### `route.options.rules` Default value: none. A custom rules object passed to each rules processor registered with [`server.rules()`](#server.rules()). ### `route.options.security` Default value: `false` (security headers disabled). Sets common security headers. To enable, set `security` to `true` or to an object with the following options: - `hsts` - controls the 'Strict-Transport-Security' header, where: - `true` - the header will be set to `max-age=15768000`. This is the default value. - a number - the maxAge parameter will be set to the provided value. - an object with the following fields: - `maxAge` - the max-age portion of the header, as a number. Default is `15768000`. - `includeSubDomains` - a boolean specifying whether to add the `includeSubDomains` flag to the header. - `preload` - a boolean specifying whether to add the `'preload'` flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. - `xframe` - controls the 'X-Frame-Options' header, where: - `true` - the header will be set to `'DENY'`. This is the default value. - `'deny'` - the headers will be set to `'DENY'`. - `'sameorigin'` - the headers will be set to `'SAMEORIGIN'`. - an object for specifying the 'allow-from' rule, where: - `rule` - one of: - `'deny'` - `'sameorigin'` - `'allow-from'` - `source` - when `rule` is `'allow-from'` this is used to form the rest of the header, otherwise this field is ignored. If `rule` is `'allow-from'` but `source` is unset, the rule will be automatically changed to `'sameorigin'`. - `xss` - controls the 'X-XSS-Protection' header, where: - `'disabled'` - the header will be set to `'0'`. This is the default value. - `'enabled'` - the header will be set to `'1; mode=block'`. - `false` - the header will be omitted. Note: when enabled, this setting can create a security vulnerabilities in versions of Internet Explorer below 8, unpatched versions of IE8, and browsers that employ an XSS filter/auditor. See [here](https://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/), [here](https://technet.microsoft.com/library/security/ms10-002), and [here](https://blog.innerht.ml/the-misunderstood-x-xss-protection/) for more information. - `noOpen` - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to `true` setting the header to `'noopen'`. - `noSniff` - boolean controlling the 'X-Content-Type-Options' header. Defaults to `true` setting the header to its only and default option, `'nosniff'`. - `referrer` - controls the ['Referrer-Policy'](https://www.w3.org/TR/referrer-policy/) header, which has the following possible values. - `false` - the 'Referrer-Policy' header will not be sent to clients with responses. This is the default value. - `''` - instructs clients that the Referrer-Policy will be [defined elsewhere](https://www.w3.org/TR/referrer-policy/#referrer-policy-empty-string), such as in a meta html tag. - `'no-referrer'` - instructs clients to never include the referrer header when making requests. - `'no-referrer-when-downgrade'` - instructs clients to never include the referrer when navigating from HTTPS to HTTP. - `'same-origin'` - instructs clients to only include the referrer on the current site origin. - `'origin'` - instructs clients to include the referrer but strip off path information so that the value is the current origin only. - `'strict-origin'` - same as `'origin'` but instructs clients to omit the referrer header when going from HTTPS to HTTP. - `'origin-when-cross-origin'` - instructs clients to include the full path in the referrer header for same-origin requests but only the origin components of the URL are included for cross origin requests. - `'strict-origin-when-cross-origin'` - same as `'origin-when-cross-origin'` but the client is instructed to omit the referrer when going from HTTPS to HTTP. - `'unsafe-url'` - instructs the client to always include the referrer with the full URL. ### `route.options.state` Default value: `{ parse: true, failAction: 'error' }`. HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in [RFC 6265](https://tools.ietf.org/html/rfc6265)). `state` supports the following options: - `parse` - determines if incoming 'Cookie' headers are parsed and stored in the [`request.state`](#request.state) object. - `failAction` - A [`failAction` value](#lifecycle-failAction) which determines how to handle cookie parsing errors. Defaults to `'error'` (return a Bad Request (400) error response). ### `route.options.tags` Default value: none. Route tags used for generating documentation (array of strings). This setting is not available when setting server route defaults using [`server.options.routes`](#server.options.routes). ### `route.options.timeout` Default value: `{ server: false }`. Timeouts for processing durations. #### `route.options.timeout.server` Default value: `false`. Response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming request before giving up and responding with a Service Unavailable (503) error response. #### `route.options.timeout.socket` Default value: none (use node default of 2 minutes). By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to `false` to disable socket timeouts. ### `route.options.validate` Default value: `{ headers: true, params: true, query: true, payload: true, state: true, failAction: 'error' }`. Request input validation rules for various request components. #### `route.options.validate.errorFields` Default value: none. An optional object with error fields copied into every validation error response. #### `route.options.validate.failAction` Default value: `'error'` (return a Bad Request (400) error response). A [`failAction` value](#lifecycle-failAction) which determines how to handle failed validations. When set to a function, the `err` argument includes the type of validation error under `err.output.payload.validation.source`. The default error that would otherwise have been logged or returned can be accessed under `err.data.defaultError`. #### `route.options.validate.headers` Default value: `true` (no validation). Validation rules for incoming request headers: - `true` - any headers allowed (no validation performed). - a [**joi**](https://joi.dev/api) validation object. - a validation function using the signature `async function(value, options)` where: - `value` - the [`request.headers`](#request.headers) object containing the request headers. - `options` - [`options`](#route.options.validate.options). - if a value is returned, the value is used as the new [`request.headers`](#request.headers) value and the original value is stored in [`request.orig.headers`](#request.orig). Otherwise, the headers are left unchanged. If an error is thrown, the error is handled according to [`failAction`](#route.options.validate.failAction). Note that all header field names must be in lowercase to match the headers normalized by node. #### `route.options.validate.options` Default value: none. An options object passed to the [**joi**](https://joi.dev/api) rules or the custom validation methods. Used for setting global options such as `stripUnknown` or `abortEarly`. If a custom validation function (see `headers`, `params`, `query`, or `payload` above) is defined then `options` can an arbitrary object that will be passed to this function as the second parameter. The values of the other inputs (i.e. `headers`, `query`, `params`, `payload`, `state`, `app`, and `auth`) are added to the `options` object under the validation `context` (accessible in rules as `Joi.ref('$query.key')`). Note that validation is performed in order (i.e. headers, params, query, and payload) and if type casting is used (e.g. converting a string to a number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. If the validation rules for `headers`, `params`, `query`, and `payload` are defined at both the server [`routes`](#server.options.routes) level and at the route level, the individual route settings override the routes defaults (the rules are not merged). #### `route.options.validate.params` Default value: `true` (no validation). Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in [`request.params`](#request.params), where: - `true` - any path parameter value allowed (no validation performed). - a [**joi**](https://joi.dev/api) validation object. - a validation function using the signature `async function(value, options)` where: - `value` - the [`request.params`](#request.params) object containing the request path parameters. - `options` - [`options`](#route.options.validate.options). - if a value is returned, the value is used as the new [`request.params`](#request.params) value and the original value is stored in [`request.orig.params`](#request.orig). Otherwise, the path parameters are left unchanged. If an error is thrown, the error is handled according to [`failAction`](#route.options.validate.failAction). Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. #### `route.options.validate.payload` Default value: `true` (no validation). Validation rules for incoming request payload (request body), where: - `true` - any payload allowed (no validation performed). - `false` - no payload allowed. - a [**joi**](https://joi.dev/api) validation object. - Note that empty payloads are represented by a `null` value. If a validation schema is provided and empty payload are allowed, the schema must be explicitly defined by setting the rule to a **joi** schema with `null` allowed (e.g. `Joi.object({ /* keys here */ }).allow(null)`). - a validation function using the signature `async function(value, options)` where: - `value` - the [`request.payload`](#request.payload) object containing the request payload. - `options` - [`options`](#route.options.validate.options). - if a value is returned, the value is used as the new [`request.payload`](#request.payload) value and the original value is stored in [`request.orig.payload`](#request.orig). Otherwise, the payload is left unchanged. If an error is thrown, the error is handled according to [`failAction`](#route.options.validate.failAction). Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well as the significant performance cost of validating large amounts of data. #### `route.options.validate.query` Default value: `true` (no validation). Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in [`request.query`](#request.query) prior to validation. Where: - `true` - any query parameter value allowed (no validation performed). - `false` - no query parameter value allowed. - a [**joi**](https://joi.dev/api) validation object. - a validation function using the signature `async function(value, options)` where: - `value` - the [`request.query`](#request.query) object containing the request query parameters. - `options` - [`options`](#route.options.validate.options). - if a value is returned, the value is used as the new [`request.query`](#request.query) value and the original value is stored in [`request.orig.query`](#request.orig). Otherwise, the query parameters are left unchanged. If an error is thrown, the error is handled according to [`failAction`](#route.options.validate.failAction). Note that changes to the query parameters will not be reflected in [`request.url`](#request.url). #### `route.options.validate.state` Default value: `true` (no validation). Validation rules for incoming cookies. The `cookie` header is parsed and decoded into the [`request.state`](#request.state) prior to validation. Where: - `true` - any cookie value allowed (no validation performed). - `false` - no cookies allowed. - a [**joi**](https://joi.dev/api) validation object. - a validation function using the signature `async function(value, options)` where: - `value` - the [`request.state`](#request.state) object containing all parsed cookie values. - `options` - [`options`](#route.options.validate.options). - if a value is returned, the value is used as the new [`request.state`](#request.state) value and the original value is stored in [`request.orig.state`](#request.orig). Otherwise, the cookie values are left unchanged. If an error is thrown, the error is handled according to [`failAction`](#route.options.validate.failAction). #### `route.options.validate.validator` Default value: `null` (no default validator). Sets a server validation module used to compile raw validation rules into validation schemas (e.g. **joi**). Note: the validator is only used when validation rules are not pre-compiled schemas. When a validation rules is a function or schema object, the rule is used as-is and the validator is not used. ## Request lifecycle Each incoming request passes through the request lifecycle. The specific steps vary based on the server and route configurations, but the order in which the applicable steps are executed is always the same. The following is the complete list of steps a request can go through: - _**onRequest**_ - always called when `onRequest` extensions exist. - the request path and method can be modified via the [`request.setUrl()`](#request.setUrl()) and [`request.setMethod()`](#request.setMethod()) methods. Changes to the request path or method will impact how the request is routed and can be used for rewrite rules. - [`request.payload`](#request.payload) is `undefined` and can be overridden with any non-`undefined` value to bypass payload processing. - [`request.route`](#request.route) is unassigned. - [`request.url`](#request.url) can be `null` if the incoming request path is invalid. - [`request.path`](#request.path) can be an invalid path. - _**Route lookup**_ - lookup based on `request.path` and `request.method`. - skips to _**onPreResponse**_ if no route is found or if the path violates the HTTP specification. - _**Cookies processing**_ - based on the route [`state`](#route.options.state) option. - error handling based on [`failAction`](#route.options.state.failAction). - _**onPreAuth**_ - called regardless if authentication is performed. - _**Authentication**_ - based on the route [`auth`](#route.options.auth) option. - _**Payload processing**_ - based on the route [`payload`](#route.options.payload) option and if [`request.payload`](#request.payload) has not been overridden in _**onRequest**_. - error handling based on [`failAction`](#route.options.payload.failAction). - _**Payload authentication**_ - based on the route [`auth`](#route.options.auth) option. - _**onCredentials**_ - called only if authentication is performed. - _**Authorization**_ - based on the route authentication [`access`](#route.options.auth.access) option. - _**onPostAuth**_ - called regardless if authentication is performed. - _**Headers validation**_ - based on the route [`validate.headers`](#route.options.validate.headers) option. - error handling based on [`failAction`](#route.options.validate.failAction). - _**Path parameters validation**_ - based on the route [`validate.params`](#route.options.validate.params) option. - error handling based on [`failAction`](#route.options.validate.failAction). - _**Query validation**_ - based on the route [`validate.query`](#route.options.validate.query) option. - error handling based on [`failAction`](#route.options.validate.failAction). - _**Payload validation**_ - based on the route [`validate.payload`](#route.options.validate.payload) option. - error handling based on [`failAction`](#route.options.validate.failAction). - _**State validation**_ - based on the route [`validate.state`](#route.options.validate.state) option. - error handling based on [`failAction`](#route.options.validate.failAction). - _**onPreHandler**_ - _**Pre-handler methods**_ - based on the route [`pre`](#route.options.pre) option. - error handling based on each pre-handler method's `failAction` setting. - _**Route handler**_ - executes the route [`handler`](#route.options.handler). - _**onPostHandler**_ - the response contained in [`request.response`](#request.response) may be modified (but not assigned a new value). To return a different response type (for example, replace an error with an HTML response), return a new response value. - _**Response validation**_ - error handling based on [`failAction`](#route.options.response.failAction). - _**onPreResponse**_ - always called, unless the request is aborted. - the response contained in [`request.response`](#request.response) may be modified (but not assigned a new value). To return a different response type (for example, replace an error with an HTML response), return a new response value. Note that any errors generated will not be passed back to _**onPreResponse**_ to prevent an infinite loop. - _**Response transmission**_ - may emit a [`'request'` event](#server.events.request) on the `'error'` channel. - _**Finalize request**_ - emits `'response'` event. - _**onPostResponse**_ - return value is ignored since the response is already set. - emits a [`'request'` event](#server.events.request) on the `'error'` channel if an error is returned. - all extension handlers are executed even if some error. - note that since the handlers are executed in serial (each is `await`ed), care must be taken to avoid blocking execution if other extension handlers expect to be called immediately when the response is sent. If an _**onPostResponse**_ handler is performing IO, it should defer that activity to another tick and return immediately (either without a return value or without a promise that is solve to resolve). ### Lifecycle methods Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: [extensions](#server.ext()), [authentication](#authentication-scheme), [handlers](#route.options.handler), [pre-handler methods](#route.options.pre), and [`failAction` function values](#lifecycle-failAction) are lifecyle methods provided by the developer and executed by the framework. Each lifecycle method is a function with the signature `await function(request, h, [err])` where: - `request` - the [request object](#request). - `h` - the [response toolkit](#response-toolkit) the handler must call to set a response and return control back to the framework. - `err` - an error object available only when the method is used as a [`failAction` value](#lifecycle-failAction). Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns without a value or resolves to an `undefined` value, an Internal Server Error (500) error response is sent. The return value must be one of: - Plain value: - `null` - string - number - boolean - `Buffer` object - `Error` object - plain `Error`. - a [`Boom`](https://hapi.dev/family/boom/api) object. - `Stream` object - must be compatible with the "streams2" API and not be in `objectMode`. - if the stream object has a `statusCode` property, that status code will be used as the default response code based on the [`passThrough`](#response.settings.passThrough) option. - if the stream object has a `headers` property, the headers will be included in the response based on the [`passThrough`](#response.settings.passThrough) option. - if the stream object has a function property `setCompressor(compressor)` and the response passes through a compressor, a reference to the compressor stream will be passed to the response stream via this method. - any object or array - must not include circular references. - a toolkit signal: - [`h.abandon`](#h.abandon) - abort processing the request. - [`h.close`](#h.close) - abort processing the request and call `end()` to ensure the response is closed. - [`h.continue`](#h.continue) - continue processing the request lifecycle without changing the response. - a toolkit method response: - [`h.response()`](#h.response()) - wraps a plain response in a [response object](#response-object). - [`h.redirect()`](#h.redirect()) - wraps a plain response with a redirection directive. - [`h.authenticated()`](#h.authenticated()) - indicate request authenticated successfully (auth scheme only). - [`h.unauthenticated()`](#h.unauthenticated()) - indicate request failed to authenticate (auth scheme only). - a promise object that resolve to any of the above values Any error thrown by a lifecycle method will be used as the [response object](#response-object). While errors and valid values can be returned, it is recommended to throw errors. Throwing non-error values will generate a Bad Implementation (500) error response. ```js const handler = function (request, h) { if (request.query.forbidden) { throw Boom.badRequest(); } return 'success'; }; ``` If the route has a [`bind`](#route.options.bind) option or [`server.bind()`](#server.bind()) was called, the lifecycle method will be bound to the provided context via `this` as well as accessible via [`h.context`](#h.context). #### Lifecycle workflow The flow between each lifecycle step depends on the value returned by each lifecycle method as follows: - an error: - the lifecycle skips to the _**Response validation**_ step. - if returned by the _**onRequest**_ step it skips to the _**onPreResponse**_ step. - if returned by the _**Response validation**_ step it skips to the _**onPreResponse**_ step. - if returned by the _**onPreResponse**_ step it skips to the _**Response transmission**_ step. - an abort signal ([`h.abandon`](#h.abandon) or [`h.close`](#h.close)): - skips to the _**Finalize request**_ step. - a [`h.continue`](#h.continue) signal: - continues processing the request lifecycle without changing the request response. - cannot be used by the [`authenticate()`](#authentication-scheme) scheme method. - a [takeover response](#takeover-response): - overrides the request response with the provided value and skips to the _**Response validation**_ step. - if returned by the _**Response validation**_ step it skips to the _**onPreResponse**_ step. - if returned by the _**onPreResponse**_ step it skips to the _**Response transmission**_ step. - any other response: - overrides the request response with the provided value and continues processing the request lifecycle. - cannot be returned from any step prior to the _**Pre-handler methods**_ step. The [`authenticate()`](#authentication-scheme) method has access to two additional return values: - [`h.authenticated()`](#h.authenticated()) - indicate request authenticated successfully. - [`h.unauthenticated()`](#h.unauthenticated()) - indicate request failed to authenticate. Note that these rules apply somewhat differently when used in a [pre-handler method](#route.options.pre). #### Takeover response A takeover response is a [`response object`](#response-object) on which [`response.takeover()`](#response.takever()) was called to signal that the [lifecycle method](#lifecycle-methods) return value should be set as the response and skip to immediately validate and trasmit the value, bypassing other lifecycle steps. #### `failAction` configuration Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be configured to perform another action. When supported the `failAction` option supports the following values: - `'error'` - return the error object as the response. - `'log'` - report the error but continue processing the request. - `'ignore'` - take no action and continue processing the request. - a [lifecycle method](#lifecycle-methods) with the signature `async function(request, h, err)` where: - `request` - the [request object](#request). - `h` - the [response toolkit](#response-toolkit). - `err` - the error object. #### Errors **hapi** uses the [**boom**](https://hapi.dev/family/boom/api) error library for all its internal error generation. **boom** provides an expressive interface to return HTTP errors. Any error thrown by a [lifecycle method](#lifecycle-methods) is converted into a **boom** object and defaults to status code `500` if the error is not already a **boom** object. When the error is sent back to the client, the response contains a JSON object with the `statusCode`, `error`, and `message` keys. ```js const Hapi = require('@hapi/hapi'); const Boom = require('@hapi/boom'); const server = Hapi.server(); server.route({ method: 'GET', path: '/badRequest', handler: function (request, h) { throw Boom.badRequest('Unsupported parameter'); // 400 } }); server.route({ method: 'GET', path: '/internal', handler: function (request, h) { throw new Error('unexpect error'); // 500 } }); ``` ##### Error transformation Errors can be customized by changing their `output` content. The **boom** error object includes the following properties: - `isBoom` - if `true`, indicates this is a `Boom` object instance. - `message` - the error message. - `output` - the formatted response. Can be directly manipulated after object construction to return a custom error response. Allowed root keys: - `statusCode` - the HTTP status code (typically 4xx or 5xx). - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content. - `payload` - the formatted object used as the response payload. Can be directly manipulated but any changes will be lost if `reformat()` is called. Any content allowed and by default includes the following content: - `statusCode` - the HTTP status code, derived from `error.output.statusCode`. - `error` - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from `statusCode`. - `message` - the error message derived from `error.message`. - inherited `Error` properties. It also supports the following method: - `reformat()` - rebuilds `error.output` using the other object properties. ```js const Boom = require('@hapi/boom'); const handler = function (request, h) { const error = Boom.badRequest('Cannot feed after midnight'); error.output.statusCode = 499; // Assign a custom error code error.reformat(); error.output.payload.custom = 'abc_123'; // Add custom key throw error; }); ``` When a different error representation is desired, such as an HTML page or a different payload format, the `'onPreResponse'` extension point may be used to identify errors and replace them with a different [response object](#response-object), as in this example using [Vision's](https://hapi.dev/family/vision/api) `.view()` [response toolkit](#response-toolkit) property. ```js const Hapi = require('@hapi/hapi'); const Vision = require('@hapi/vision'); const server = Hapi.server({ port: 80 }); server.register(Vision, (err) => { server.views({ engines: { html: require('handlebars') } }); }); const preResponse = function (request, h) { const response = request.response; if (!response.isBoom) { return h.continue; } // Replace error with friendly HTML const error = response; const ctx = { message: (error.output.statusCode === 404 ? 'page not found' : 'something went wrong') }; return h.view('error', ctx).code(error.output.statusCode); }; server.ext('onPreResponse', preResponse); ``` ### Response Toolkit Access: read only. The response toolkit is a collection of properties and utilities passed to every [lifecycle method](#lifecycle-methods). It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this document the `h` notation is used. It is named in the spirit of the RethinkDB `r` method, with `h` for **h**api. #### Toolkit properties ##### `h.abandon` Access: read only. A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step without further interaction with the node response stream. It is the developer's responsibility to write and end the response directly via [`request.raw.res`](#request.raw). ##### `h.close` Access: read only. A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after calling `request.raw.res.end())` to close the node response stream. ##### `h.context` Access: read / write (will impact the shared context if the object is modified). A response symbol. Provides access to the route or server context set via the route [`bind`](#route.options.bind) option or [`server.bind()`](#server.bind()). ##### `h.continue` Access: read only. A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response. ##### `h.realm` Access: read only. The [server realm](#server.realm) associated with the matching route. Defaults to the root server realm in the _**onRequest**_ step. ##### `h.request` Access: read only and public request interface. The [request] object. This is a duplication of the `request` lifecycle method argument used by [toolkit decorations](#server.decorate()) to access the current request. #### `h.authenticated(data)` Used by the [authentication] method to pass back valid credentials where: - `data` - an object with: - `credentials` - (required) object representing the authenticated entity. - `artifacts` - (optional) authentication artifacts object specific to the authentication scheme. Return value: an internal authentication object. #### `h.entity(options)` Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request conditions, `h.entity()` returns a [response object](#response-object) for the lifecycle method to return as its value which will set a 304 response. Otherwise, it sets the provided entity headers and returns `undefined`. The method arguments are: - `options` - a required configuration object with: - `etag` - the ETag string. Required if `modified` is not present. Defaults to no header. - `modified` - the Last-Modified header value. Required if `etag` is not present. Defaults to no header. - `vary` - same as the [`response.etag()`](#response.etag()) option. Defaults to `true`. Return value: - a [response object](#response-object) if the response is unmodified. - `undefined` if the response has changed. If `undefined` is returned, the developer must return a valid lifecycle method value. If a response is returned, it should be used as the return value (but may be customize using the response methods). ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); server.route({ method: 'GET', path: '/', options: { cache: { expiresIn: 5000 }, handler: function (request, h) { const response = h.entity({ etag: 'abc' }); if (response) { response.header('X', 'y'); return response; } return 'ok'; } } }); ``` #### `h.redirect(uri)` Redirects the client to the specified uri. Same as calling `h.response().redirect(uri)`. Returns a [response object](#response-object). ```js const handler = function (request, h) { return h.redirect('http://example.com'); }; ``` #### `h.response([value])` Wraps the provided value and returns a [`response`](#response-object) object which allows customizing the response (e.g. setting the HTTP status code, custom headers, etc.), where: - `value` - (optional) return value. Defaults to `null`. Returns a [response object](#response-object). ```js // Detailed notation const handler = function (request, h) { const response = h.response('success'); response.type('text/plain'); response.header('X-Custom', 'some-value'); return response; }; // Chained notation const handler = function (request, h) { return h.response('success') .type('text/plain') .header('X-Custom', 'some-value'); }; ``` #### `h.state(name, value, [options])` Sets a response cookie using the same arguments as [`response.state()`](#response.state()). Return value: none. ```js const ext = function (request, h) { h.state('cookie-name', 'value'); return h.continue; }; ``` #### `h.unauthenticated(error, [data])` Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: - `error` - (required) the authentication error. - `data` - (optional) an object with: - `credentials` - (required) object representing the authenticated entity. - `artifacts` - (optional) authentication artifacts object specific to the authentication scheme. The method is used to pass both the authentication error and the credentials. For example, if a request included expired credentials, it allows the method to pass back the user information (combined with a `'try'` authentication [`mode`](#route.options.auth.mode)) for error customization. There is no difference between throwing the error or passing it with the `h.unauthenticated()` method if no credentials are passed, but it might still be helpful for code clarity. #### `h.unstate(name, [options])` Clears a response cookie using the same arguments as [`response.unstate()`](#response.unstate()). ```js const ext = function (request, h) { h.unstate('cookie-name'); return h.continue; }; ``` ### Response object The response object contains the request response value along with various HTTP headers and flags. When a [lifecycle method](#lifecycle-methods) returns a value, the value is wrapped in a response object along with some default flags (e.g. `200` status code). In order to customize a response before it is returned, the [`h.response()`](#h.response()) method is provided. #### Response properties ##### `response.app` Access: read / write. Default value: `{}`. Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by [plugins](#plugins) which should use [`plugins[name]`](#response.plugins). ##### `response.contentType` Access: read. Default value: none. Provides a preview of the response HTTP Content-Type header based on the implicit response type, any explicit Content-Type header set, and any content character-set defined. The returned value is only a preview as the content type can change later both internally and by user code (it represents current response state). The value is `null` if no implicit type can be determined. ##### `response.events` Access: read only and the public **podium** interface. The `response.events` object supports the following events: - `'peek'` - emitted for each chunk of data written back to the client connection. The event method signature is `function(chunk, encoding)`. - `'finish'` - emitted when the response finished writing but before the client response connection is ended. The event method signature is `function ()`. ```js const Crypto = require('crypto'); const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const preResponse = function (request, h) { const response = request.response; if (response.isBoom) { return null; } const hash = Crypto.createHash('sha1'); response.events.on('peek', (chunk) => { hash.update(chunk); }); response.events.once('finish', () => { console.log(hash.digest('hex')); }); return h.continue; }; server.ext('onPreResponse', preResponse); ``` ##### `response.headers` Access: read only. Default value: `{}`. An object containing the response headers where each key is a header field name and the value is the string header value or array of string. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. ##### `response.plugins` Access: read / write. Default value: `{}`. Plugin-specific state. Provides a place to store and pass request-level plugin data. `plugins` is an object where each key is a plugin name and the value is the state. ##### `response.settings` Access: read only. Object containing the response handling flags. ###### `response.settings.passThrough` Access: read only. Defaults value: `true`. If `true` and [`source`](#response.source) is a `Stream`, copies the `statusCode` and `headers` properties of the stream object to the outbound response. ###### `response.settings.stringify` Access: read only. Default value: `null` (use route defaults). Override the route [`json`](#route.options.json) options used when [`source`](#response.source) value requires stringification. ###### `response.settings.ttl` Access: read only. Default value: `null` (use route defaults). If set, overrides the route [`cache`](#route.options.cache) with an expiration value in milliseconds. ###### `response.settings.varyEtag` Default value: `false`. If `true`, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a `'-'` character) when the HTTP 'Vary' header is present. ##### `response.source` Access: read only. The raw value returned by the [lifecycle method](#lifecycle-methods). ##### `response.statusCode` Access: read only. Default value: `200`. The HTTP response status code. ##### `response.variety` Access: read only. A string indicating the type of [`source`](#response.source) with available values: - `'plain'` - a plain response such as string, number, `null`, or simple object. - `'buffer'` - a `Buffer`. - `'stream'` - a `Stream`. #### `response.bytes(length)` Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: - `length` - the header value. Must match the actual payload size. Return value: the current response object. #### `response.charset(charset)` Sets the 'Content-Type' HTTP header 'charset' property where: - `charset` - the charset property value. When `charset` value is falsy, it will prevent hapi from using its default charset setting. Return value: the current response object. #### `response.code(statusCode)` Sets the HTTP status code where: - `statusCode` - the HTTP status code (e.g. 200). Return value: the current response object. #### `response.message(httpMessage)` Sets the HTTP status message where: - `httpMessage` - the HTTP status message (e.g. 'Ok' for status code 200). Return value: the current response object. #### `response.compressed(encoding)` Sets the HTTP 'content-encoding' header where: - `encoding` - the header value string. Return value: the current response object. Note that setting content encoding via this method does not set a 'vary' HTTP header with 'accept-encoding' value. To vary the response, use the `response.header()` method instead. #### `response.created(uri)` Sets the HTTP status code to Created (201) and the HTTP 'Location' header where: - `uri` - an absolute or relative URI used as the 'Location' header value. Return value: the current response object. #### `response.encoding(encoding)` Sets the string encoding scheme used to serial data into the HTTP payload where: - `encoding` - the encoding property value (see [node Buffer encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). Return value: the current response object. #### `response.etag(tag, options)` Sets the representation [entity tag](https://tools.ietf.org/html/rfc7232#section-2.3) where: - `tag` - the entity tag string without the double-quote. - `options` - (optional) settings where: - `weak` - if `true`, the tag will be prefixed with the `'W/'` weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to `false`. - `vary` - if `true` and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a `'-'` character). Ignored when `weak` is `true`. Defaults to `true`. Return value: the current response object. #### `response.header(name, value, options)` Sets an HTTP header where: - `name` - the header name. - `value` - the header value. - `options` - (optional) object where: - `append` - if `true`, the value is appended to any existing header value using `separator`. Defaults to `false`. - `separator` - string used as separator when appending to an existing value. Defaults to `','`. - `override` - if `false`, the header value is not set if an existing value present. Defaults to `true`. - `duplicate` - if `false`, the header value is not modified if the provided value is already included. Does not apply when `append` is `false` or if the `name` is `'set-cookie'`. Defaults to `true`. Return value: the current response object. #### `response.location(uri)` Sets the HTTP 'Location' header where: - `uri` - an absolute or relative URI used as the 'Location' header value. Return value: the current response object. #### `response.redirect(uri)` Sets an HTTP redirection response (302) and decorates the response with additional methods, where: - `uri` - an absolute or relative URI used to redirect the client to another resource. Return value: the current response object. Decorates the response object with the [`response.temporary()`](#response.temporary()), [`response.permanent()`](#response.permanent()), and [`response.rewritable()`](#response.rewritable()) methods to easily change the default redirection code (302). | | Permanent | Temporary | | -------------- | ---------- | --------- | | Rewritable | 301 | 302 | | Non-rewritable | 308 | 307 | #### `response.replacer(method)` Sets the `JSON.stringify()` `replacer` argument where: - `method` - the replacer function or array. Defaults to none. Return value: the current response object. #### `response.spaces(count)` Sets the `JSON.stringify()` `space` argument where: - `count` - the number of spaces to indent nested object keys. Defaults to no indentation. Return value: the current response object. #### `response.state(name, value, [options])` Sets an HTTP cookie where: - `name` - the cookie name. - `value` - the cookie value. If no `options.encoding` is defined, must be a string. See [`server.state()`](#server.state()) for supported `encoding` values. - `options` - (optional) configuration. If the state was previously registered with the server using [`server.state()`](#server.state()), the specified keys in `options` are merged with the default server definition. Return value: the current response object. #### `response.suffix(suffix)` Sets a string suffix when the response is process via `JSON.stringify()` where: - `suffix` - the string suffix. Return value: the current response object. #### `response.ttl(msec)` Overrides the default route cache expiration rule for this response instance where: - `msec` - the time-to-live value in milliseconds. Return value: the current response object. #### `response.type(mimeType)` Sets the HTTP 'Content-Type' header where: - `mimeType` - is the mime type. Return value: the current response object. Should only be used to override the built-in default for each response type. #### `response.unstate(name, [options])` Clears the HTTP cookie by setting an expired value where: - `name` - the cookie name. - `options` - (optional) configuration for expiring cookie. If the state was previously registered with the server using [`server.state()`](#serverstatename-options), the specified `options` are merged with the server definition. Return value: the current response object. #### `response.vary(header)` Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: - `header` - the HTTP request header name. Return value: the current response object. #### `response.takeover()` Marks the response object as a [takeover response](#takeover-response). Return value: the current response object. #### `response.temporary(isTemporary)` Sets the status code to `302` or `307` (based on the [`response.rewritable()`](#response.rewriteable()) setting) where: - `isTemporary` - if `false`, sets status to permanent. Defaults to `true`. Return value: the current response object. Only available after calling the [`response.redirect()`](#response.redirect()) method. #### `response.permanent(isPermanent)` Sets the status code to `301` or `308` (based on the [`response.rewritable()`](#response.rewritable()) setting) where: - `isPermanent` - if `false`, sets status to temporary. Defaults to `true`. Return value: the current response object. Only available after calling the [`response.redirect()`](#response.redirect()) method. #### `response.rewritable(isRewritable)` Sets the status code to `301`/`302` for rewritable (allows changing the request method from 'POST' to 'GET') or `307`/`308` for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the [`response.temporary()`](#response.temporary()) or [`response.permanent()`](#response.permanent()) setting. Arguments: - `isRewritable` - if `false`, sets to non-rewritable. Defaults to `true`. Return value: the current response object. Only available after calling the [`response.redirect()`](#response.redirect()) method. ## Request The request object is created internally for each incoming request. It is not the same object received from the node HTTP server callback (which is available via [`request.raw.req`](#request.raw)). The request properties change throughout the [request lifecycle](#request-lifecycle). ### Request properties #### `request.app` Access: read / write. Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by [plugins](#plugins) which should use `plugins[name]`. #### `request.auth` Access: read only. Authentication information: - `artifacts` - an artifact object received from the authentication strategy and used in authentication-related actions. - `credentials` - the `credential` object received during the authentication process. The presence of an object does not mean successful authentication. - `error` - the authentication error if failed and mode set to `'try'`. - `isAuthenticated` - `true` if the request has been successfully authenticated, otherwise `false`. - `isAuthorized` - `true` is the request has been successfully authorized against the route authentication [`access`](#route.options.auth.access) configuration. If the route has not access rules defined or if the request failed authorization, set to `false`. - `isInjected` - `true` if the request has been authenticated via the [`server.inject()`](#server.inject()) `auth` option, otherwise `undefined`. - `mode` - the route authentication mode. - `strategy` - the name of the strategy used. #### `request.events` Access: read only and the public **podium** interface. The `request.events` supports the following events: - `'peek'` - emitted for each chunk of payload data read from the client connection. The event method signature is `function(chunk, encoding)`. - `'finish'` - emitted when the request payload finished reading. The event method signature is `function ()`. - `'disconnect'` - emitted when a request errors or aborts unexpectedly. ```js const Crypto = require('crypto'); const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const onRequest = function (request, h) { const hash = Crypto.createHash('sha1'); request.events.on('peek', (chunk) => { hash.update(chunk); }); request.events.once('finish', () => { console.log(hash.digest('hex')); }); request.events.once('disconnect', () => { console.error('request aborted'); }); return h.continue; }; server.ext('onRequest', onRequest); ``` #### `request.headers` Access: read only. The raw request headers (references `request.raw.req.headers`). #### `request.info` Access: read only. Request information: - `acceptEncoding` - the request preferred encoding. - `completed` - request processing completion timestamp (`0` is still processing). - `cors` - request CORS information (available only after the `'onRequest'` extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle), where: - `isOriginMatch` - `true` if the request 'Origin' header matches the configured CORS restrictions. Set to `false` if no 'Origin' header is found or if it does not match. - `host` - content of the HTTP 'Host' header (e.g. 'example.com:8080'). - `hostname` - the hostname part of the 'Host' header (e.g. 'example.com'). - `id` - a unique request identifier (using the format '{now}:{server.info.id}:{5 digits counter}'). - `received` - request reception timestamp. - `referrer` - content of the HTTP 'Referrer' (or 'Referer') header. - `remoteAddress` - remote client IP address. - `remotePort` - remote client port. - `responded` - request response timestamp (`0` is not responded yet or response failed when `completed` is set). Note that the `request.info` object is not meant to be modified. #### `request.isInjected` Access: read only. `true` if the request was created via [`server.inject()`](#server.inject()), and `false` otherwise. #### `request.logs` Access: read only. An array containing the logged request events. Note that this array will be empty if route [`log.collect`](#route.options.log) is set to `false`. #### `request.method` Access: read only. The request method in lower case (e.g. `'get'`, `'post'`). #### `request.mime` Access: read only. The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. #### `request.orig` Access: read only. An object containing the values of `params`, `query`, `payload` and `state` before any validation modifications made. Only set when input validation is performed. #### `request.params` Access: read only. An object where each key is a path parameter name with matching value as described in [Path parameters](#path-parameters). #### `request.paramsArray` Access: read only. An array containing all the path `params` values in the order they appeared in the path. #### `request.path` Access: read only. The request URI's [pathname](https://nodejs.org/api/url.html#url_urlobject_pathname) component. #### `request.payload` Access: read only / write in `'onRequest'` extension method. The request payload based on the route `payload.output` and `payload.parse` settings. Set to `undefined` in `'onRequest'` extension methods and can be overridden to any non-`undefined` value to bypass payload processing. #### `request.plugins` Access: read / write. Plugin-specific state. Provides a place to store and pass request-level plugin data. The `plugins` is an object where each key is a plugin name and the value is the state. #### `request.pre` Access: read only. An object where each key is the name assigned by a [route pre-handler methods](#route.options.pre) function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use `responses`. #### `request.response` Access: read / write (see limitations below). The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an [extension point](#server.ext()), return a new response value. Contains an error when a request terminates prematurely when the client disconnects. #### `request.preResponses` Access: read only. Same as `pre` but represented as the response object created by the pre method. #### `request.query` Access: read only. An object where each key is a query parameter name and each matching value is the parameter value or an array of values if a parameter repeats. Can be modified indirectly via [request.setUrl](#request.setUrl()). #### `request.raw` Access: read only. An object containing the Node HTTP server objects. **Direct interaction with these raw objects is not recommended.** - `req` - the node request object. - `res` - the node response object. #### `request.route` Access: read only. The request route information object, where: - `method` - the route HTTP method. - `path` - the route path. - `vhost` - the route vhost option if configured. - `realm` - the [active realm](#server.realm) associated with the route. - `settings` - the [route options](#route-options) object with all defaults applied. - `fingerprint` - the route internal normalized string representing the normalized path. #### `request.server` Access: read only and the public server interface. The server object. #### `request.state` Access: read only. An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. #### `request.url` Access: read only. The parsed request URI. ### `request.generateResponse(source, [options])` Returns a [`response`](#response-object) which you can pass to [h.response()](#h.response()) where: - `source` - the value to set as the source of [h.response()](#h.response()), optional. - `options` - optional object with the following optional properties: - `variety` - a sting name of the response type (e.g. `'file'`). - `prepare` - a function with the signature `async function(response)` used to prepare the response after it is returned by a [lifecycle method](#lifecycle-methods) such as setting a file descriptor, where: - `response` - the response object being prepared. - must return the prepared response object (`response`). - may throw an error which is used as the prepared response. - `marshal` - a function with the signature `async function(response)` used to prepare the response for transmission to the client before it is sent, where: - `response` - the response object being marshaled. - must return the prepared value (not as response object) which can be any value accepted by the [`h.response()`](#h.response()) `value` argument. - may throw an error which is used as the marshaled value. - `close` - a function with the signature `function(response)` used to close the resources opened by the response object (e.g. file handlers), where: - `response` - the response object being marshaled. - should not throw errors (which are logged but otherwise ignored). ### `request.active()` Returns `true` when the request is active and processing should continue and `false` when the request terminated early or completed its lifecycle. Useful when request processing is a resource-intensive operation and should be terminated early if the request is no longer active (e.g. client disconnected or aborted early). ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); server.route({ method: 'POST', path: '/worker', handler: function (request, h) { // Do some work... // Check if request is still active if (!request.active()) { return h.close; } // Do some more work... return null; } }); ``` ### `request.log(tags, [data])` Logs request-specific events. When called, the server emits a [`'request'` event](#server.events.request) on the `'app'` channel which can be used by other listeners or [plugins](#plugins). The arguments are: - `tags` - a string or an array of strings (e.g. `['error', 'database', 'read']`) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. - `data` - (optional) an message string or object with the application data being logged. If `data` is a function, the function signature is `function()` and it called once to generate (return value) the actual data emitted to the listeners. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80, routes: { log: { collect: true } } }); server.events.on({ name: 'request', channels: 'app' }, (request, event, tags) => { if (tags.error) { console.log(event); } }); const handler = function (request, h) { request.log(['test', 'error'], 'Test event'); return null; }; ``` Note that any logs generated by the server internally will be emitted using the [`'request'` event](#server.events.request) on the `'internal'` channel. ```js server.events.on({ name: 'request', channels: 'internal' }, (request, event, tags) => { console.log(event); }); ``` ### `request.route.auth.access(request)` Validates a request against the route's authentication [`access`](#route.options.auth.access) configuration, where: - `request` - the [request object](#request). Return value: `true` if the `request` would have passed the route's access requirements. Note that the route's authentication mode and strategies are ignored. The only match is made between the `request.auth.credentials` scope and entity information and the route [`access`](#route.options.auth.access) configuration. If the route uses dynamic scopes, the scopes are constructed against the [`request.query`](#request.query), [`request.params`](#request.params), [`request.payload`](#request.payload), and [`request.auth.credentials`](#request.auth) which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return `false` if the route requires any authentication. ### `request.setMethod(method)` Changes the request method before the router begins processing the request where: - `method` - is the request HTTP method (e.g. `'GET'`). ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const onRequest = function (request, h) { // Change all requests to 'GET' request.setMethod('GET'); return h.continue; }; server.ext('onRequest', onRequest); ``` Can only be called from an `'onRequest'` extension method. ### `request.setUrl(url, [stripTrailingSlash]` Changes the request URI before the router begins processing the request where: - `url` - the new request URI. `url` can be a string or an instance of [`Url.URL`](https://nodejs.org/dist/latest-v10.x/docs/api/url.html#url_class_url) in which case `url.href` is used. - `stripTrailingSlash` - if `true`, strip the trailing slash from the path. Defaults to `false`. ```js const Hapi = require('@hapi/hapi'); const server = Hapi.server({ port: 80 }); const onRequest = function (request, h) { // Change all requests to '/test' request.setUrl('/test'); return h.continue; }; server.ext('onRequest', onRequest); ``` Can only be called from an `'onRequest'` extension method. ## Plugins Plugins provide a way to organize application code by splitting the server logic into smaller components. Each plugin can manipulate the server through the standard server interface, but with the added ability to sandbox certain properties. For example, setting a file path in one plugin doesn't affect the file path set in another plugin. A plugin is an object with the following properties: - `register` - (required) the registration function with the signature `async function(server, options)` where: - `server` - the server object with a plugin-specific [`server.realm`](#server.realm). - `options` - any options passed to the plugin during registration via [`server.register()`](#server.register()). - `name` - (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm registry) should use the same name as the name field in their 'package.json' file. Names must be unique within each application. - `version` - (optional) plugin version string. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's 'package.json' file. - `multiple` - (optional) if `true`, allows the plugin to be registered multiple times with the same server. Defaults to `false`. - `dependencies` - (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via [`server.dependency()`](#server.dependency()). - `requirements` - (optional) object declaring the plugin supported [semver range](https://semver.org/) for: - `node` runtime [semver range](https://nodejs.org/en/about/releases/) string. - `hapi` framework [semver range](#server.version) string. - `once` - (optional) if `true`, will only register the plugin once per server. If set, overrides the `once` option passed to [`server.register()`](#server.register()). Defaults to no override. ```js const plugin = { name: 'test', version: '1.0.0', register: function (server, options) { server.route({ method: 'GET', path: '/test', handler: function (request, h) { return 'ok'; } }); } }; ``` Alternatively, the `name` and `version` can be included via the `pkg` property containing the 'package.json' file for the module which already has the name and version included: ```js const plugin = { pkg: require('./package.json'), register: function (server, options) { server.route({ method: 'GET', path: '/test', handler: function (request, h) { return 'ok'; } }); } }; ``` ================================================ FILE: LICENSE.md ================================================ Copyright (c) 2011-2022, Project contributors Copyright (c) 2011-2020, Sideway Inc Copyright (c) 2011-2014, Walmart Copyright (c) 2011, Yahoo Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - The names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS OFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: README.md ================================================ # @hapi/hapi #### The Simple, Secure Framework Developers Trust Build powerful, scalable applications, with minimal overhead and full out-of-the-box functionality - your code, your way. ### Visit the [hapi.dev](https://hapi.dev) Developer Portal for tutorials, documentation, and support ## Useful resources - [Documentation and API](https://hapi.dev/) - [Version status](https://hapi.dev/resources/status/#hapi) (builds, dependencies, node versions, licenses, eol) - [Changelog](https://hapi.dev/resources/changelog/) - [Project policies](https://hapi.dev/policies/) - [Support](https://hapi.dev/support/) ## Technical Steering Committee (TSC) Members - Devin Ivy ([@devinivy](https://github.com/devinivy)) - Lloyd Benson ([@lloydbenson](https://github.com/lloydbenson)) - Nathan LaFreniere ([@nlf](https://github.com/nlf)) - Wyatt Lyon Preul ([@geek](https://github.com/geek)) - Nicolas Morel ([@marsup](https://github.com/marsup)) - Jonathan Samines ([@jonathansamines](https://github.com/jonathansamines)) ================================================ FILE: SPONSORS.md ================================================ We'd like to thank our sponsors as well as the legacy sponsors who have supported hapi throughout the years. Thanks so much for your support! > Below are hapi's top recurring sponsors, but there are many more to thank. For the complete list, see [hapi.dev/policies/sponsors](https://hapi.dev/policies/sponsors/) or [hapijs/.github/SPONSORS.md](https://github.com/hapijs/.github/blob/master/SPONSORS.md). # Staff Sponsors - [Big Room Studios](https://www.bigroomstudios.com/) - [Dixeed](https://dixeed.com/) # Top Sponsors - Fabian Gündel / [DataWrapper.de](https://www.datawrapper.de/) - Devin Stewart - [Raider.IO](https://raider.io/) - [Florence Healthcare](https://florencehc.com/) ================================================ FILE: lib/auth.js ================================================ 'use strict'; const Boom = require('@hapi/boom'); const Bounce = require('@hapi/bounce'); const Hoek = require('@hapi/hoek'); const Config = require('./config'); const Request = require('./request'); const internals = { missing: Symbol('missing') }; exports = module.exports = internals.Auth = class { #core = null; #schemes = {}; #strategies = {}; api = {}; // Do not reassign api or settings, as they are referenced in public() settings = { default: null // Strategy used as default if route has no auth settings }; constructor(core) { this.#core = core; } public(server) { return { api: this.api, settings: this.settings, scheme: this.scheme.bind(this), strategy: this._strategy.bind(this, server), default: this.default.bind(this), test: this.test.bind(this), verify: this.verify.bind(this), lookup: this.lookup.bind(this) }; } scheme(name, scheme) { Hoek.assert(name, 'Authentication scheme must have a name'); Hoek.assert(!this.#schemes[name], 'Authentication scheme name already exists:', name); Hoek.assert(typeof scheme === 'function', 'scheme must be a function:', name); this.#schemes[name] = scheme; } _strategy(server, name, scheme, options = {}) { Hoek.assert(name, 'Authentication strategy must have a name'); Hoek.assert(typeof options === 'object', 'options must be an object'); Hoek.assert(!this.#strategies[name], 'Authentication strategy name already exists'); Hoek.assert(scheme, 'Authentication strategy', name, 'missing scheme'); Hoek.assert(this.#schemes[scheme], 'Authentication strategy', name, 'uses unknown scheme:', scheme); server = server._clone(); const strategy = this.#schemes[scheme](server, options); Hoek.assert(strategy.authenticate, 'Invalid scheme:', name, 'missing authenticate() method'); Hoek.assert(typeof strategy.authenticate === 'function', 'Invalid scheme:', name, 'invalid authenticate() method'); Hoek.assert(!strategy.payload || typeof strategy.payload === 'function', 'Invalid scheme:', name, 'invalid payload() method'); Hoek.assert(!strategy.response || typeof strategy.response === 'function', 'Invalid scheme:', name, 'invalid response() method'); strategy.options = strategy.options ?? {}; Hoek.assert(strategy.payload || !strategy.options.payload, 'Cannot require payload validation without a payload method'); this.#strategies[name] = { methods: strategy, realm: server.realm }; if (strategy.api) { this.api[name] = strategy.api; } } default(options) { Hoek.assert(!this.settings.default, 'Cannot set default strategy more than once'); options = Config.apply('auth', options, 'default strategy'); this.settings.default = this._setupRoute(Hoek.clone(options)); // Prevent changes to options const routes = this.#core.router.table(); for (const route of routes) { route.rebuild(); } } async test(name, request) { Hoek.assert(name, 'Missing authentication strategy name'); const strategy = this.#strategies[name]; Hoek.assert(strategy, 'Unknown authentication strategy:', name); const bind = strategy.methods; const realm = strategy.realm; const response = await request._core.toolkit.execute(strategy.methods.authenticate, request, { bind, realm, auth: true }); if (!response.isAuth) { throw response; } if (response.error) { throw response.error; } return response.data; } async verify(request) { const auth = request.auth; if (auth.error) { throw auth.error; } if (!auth.isAuthenticated) { return; } const strategy = this.#strategies[auth.strategy]; Hoek.assert(strategy, 'Unknown authentication strategy:', auth.strategy); if (!strategy.methods.verify) { return; } const bind = strategy.methods; await strategy.methods.verify.call(bind, auth); } static testAccess(request, route) { const auth = request._core.auth; try { return auth._access(request, route); } catch (err) { Bounce.rethrow(err, 'system'); return false; } } _setupRoute(options, path) { if (!options) { return options; // Preserve the difference between undefined and false } if (typeof options === 'string') { options = { strategies: [options] }; } else if (options.strategy) { options.strategies = [options.strategy]; delete options.strategy; } if (path && !options.strategies) { Hoek.assert(this.settings.default, 'Route missing authentication strategy and no default defined:', path); options = Hoek.applyToDefaults(this.settings.default, options); } path = path ?? 'default strategy'; Hoek.assert(options.strategies?.length, 'Missing authentication strategy:', path); options.mode = options.mode ?? 'required'; if (options.entity !== undefined || // Backwards compatibility with <= 11.x.x options.scope !== undefined) { options.access = [{ entity: options.entity, scope: options.scope }]; delete options.entity; delete options.scope; } if (options.access) { for (const access of options.access) { access.scope = internals.setupScope(access); } } if (options.payload === true) { options.payload = 'required'; } let hasAuthenticatePayload = false; for (const name of options.strategies) { const strategy = this.#strategies[name]; Hoek.assert(strategy, 'Unknown authentication strategy', name, 'in', path); Hoek.assert(strategy.methods.payload || options.payload !== 'required', 'Payload validation can only be required when all strategies support it in', path); hasAuthenticatePayload = hasAuthenticatePayload || strategy.methods.payload; Hoek.assert(!strategy.methods.options.payload || options.payload === undefined || options.payload === 'required', 'Cannot set authentication payload to', options.payload, 'when a strategy requires payload validation in', path); } Hoek.assert(!options.payload || hasAuthenticatePayload, 'Payload authentication requires at least one strategy with payload support in', path); return options; } lookup(route) { if (route.settings.auth === false) { return false; } return route.settings.auth || this.settings.default; } _enabled(route, type) { const config = this.lookup(route); if (!config) { return false; } if (type === 'authenticate') { return true; } if (type === 'access') { return !!config.access; } for (const name of config.strategies) { const strategy = this.#strategies[name]; if (strategy.methods[type]) { return true; } } return false; } static authenticate(request) { const auth = request._core.auth; return auth._authenticate(request); } async _authenticate(request) { const config = this.lookup(request.route); const errors = []; request.auth.mode = config.mode; // Injection bypass if (request.auth.credentials) { internals.validate(null, { credentials: request.auth.credentials, artifacts: request.auth.artifacts }, request.auth.strategy, config, request, errors); return; } // Try each strategy for (const name of config.strategies) { const strategy = this.#strategies[name]; const bind = strategy.methods; const realm = strategy.realm; const response = await request._core.toolkit.execute(strategy.methods.authenticate, request, { bind, realm, auth: true }); const message = (response.isAuth ? internals.validate(response.error, response.data, name, config, request, errors) : internals.validate(response, null, name, config, request, errors)); if (!message) { return; } if (message !== internals.missing) { return message; } } // No more strategies const err = Boom.unauthorized('Missing authentication', errors); if (config.mode === 'required') { throw err; } request.auth.isAuthenticated = false; request.auth.credentials = null; request.auth.error = err; request._log(['auth', 'unauthenticated']); } static access(request) { const auth = request._core.auth; request.auth.isAuthorized = auth._access(request); } _access(request, route) { const config = this.lookup(route || request.route); if (!config?.access) { return true; } const credentials = request.auth.credentials; if (!credentials) { if (config.mode !== 'required') { return false; } throw Boom.forbidden('Request is unauthenticated'); } const requestEntity = (credentials.user ? 'user' : 'app'); const scopeErrors = []; for (const access of config.access) { // Check entity const entity = access.entity; if (entity && entity !== 'any' && entity !== requestEntity) { continue; } // Check scope let scope = access.scope; if (scope) { if (!credentials.scope) { scopeErrors.push(scope); continue; } scope = internals.expandScope(request, scope); if (!internals.validateScope(credentials, scope, 'required') || !internals.validateScope(credentials, scope, 'selection') || !internals.validateScope(credentials, scope, 'forbidden')) { scopeErrors.push(scope); continue; } } return true; } // Scope error if (scopeErrors.length) { request._log(['auth', 'scope', 'error']); throw Boom.forbidden('Insufficient scope', { got: credentials.scope, need: scopeErrors }); } // Entity error if (requestEntity === 'app') { request._log(['auth', 'entity', 'user', 'error']); throw Boom.forbidden('Application credentials cannot be used on a user endpoint'); } request._log(['auth', 'entity', 'app', 'error']); throw Boom.forbidden('User credentials cannot be used on an application endpoint'); } static async payload(request) { if (!request.auth.isAuthenticated || !request.auth[Request.symbols.authPayload]) { return; } const auth = request._core.auth; const strategy = auth.#strategies[request.auth.strategy]; Hoek.assert(strategy, 'Unknown authentication strategy:', request.auth.strategy); if (!strategy.methods.payload) { return; } const config = auth.lookup(request.route); const setting = config.payload ?? (strategy.methods.options.payload ? 'required' : false); if (!setting) { return; } const bind = strategy.methods; const realm = strategy.realm; const response = await request._core.toolkit.execute(strategy.methods.payload, request, { bind, realm }); if (response.isBoom && response.isMissing) { return setting === 'optional' ? undefined : Boom.unauthorized('Missing payload authentication'); } return response; } static async response(response) { const request = response.request; const auth = request._core.auth; if (!request.auth.isAuthenticated) { return; } const strategy = auth.#strategies[request.auth.strategy]; Hoek.assert(strategy, 'Unknown authentication strategy:', request.auth.strategy); if (!strategy.methods.response) { return; } const bind = strategy.methods; const realm = strategy.realm; const error = await request._core.toolkit.execute(strategy.methods.response, request, { bind, realm, continue: 'undefined' }); if (error) { throw error; } } }; internals.setupScope = function (access) { // No scopes if (!access.scope) { return false; } // Already setup if (!Array.isArray(access.scope)) { return access.scope; } const scope = {}; for (const value of access.scope) { const prefix = value[0]; const type = prefix === '+' ? 'required' : (prefix === '!' ? 'forbidden' : 'selection'); const clean = type === 'selection' ? value : value.slice(1); scope[type] = scope[type] ?? []; scope[type].push(clean); if ((!scope._hasParameters?.[type]) && /{([^}]+)}/.test(clean)) { scope._hasParameters = scope._hasParameters ?? {}; scope._hasParameters[type] = true; } } return scope; }; internals.validate = function (err, result, name, config, request, errors) { // err can be Boom, Error, or a valid response object result = result ?? {}; request.auth.isAuthenticated = !err; if (err) { // Non-error response if (err instanceof Error === false) { request._log(['auth', 'unauthenticated', 'response', name], { statusCode: err.statusCode }); return err; } // Missing authenticated if (err.isMissing) { request._log(['auth', 'unauthenticated', 'missing', name], err); errors.push(err.output.headers['WWW-Authenticate']); return internals.missing; } } request.auth.strategy = name; request.auth.credentials = result.credentials; request.auth.artifacts = result.artifacts; // Authenticated if (!err) { return; } // Unauthenticated request.auth.error = err; if (config.mode === 'try') { request._log(['auth', 'unauthenticated', 'try', name], err); return; } request._log(['auth', 'unauthenticated', 'error', name], err); throw err; }; internals.expandScope = function (request, scope) { if (!scope._hasParameters) { return scope; } const expanded = { required: internals.expandScopeType(request, scope, 'required'), selection: internals.expandScopeType(request, scope, 'selection'), forbidden: internals.expandScopeType(request, scope, 'forbidden') }; return expanded; }; internals.expandScopeType = function (request, scope, type) { if (!scope._hasParameters[type]) { return scope[type]; } const expanded = []; const context = { params: request.params, query: request.query, payload: request.payload, credentials: request.auth.credentials }; for (const template of scope[type]) { expanded.push(Hoek.reachTemplate(context, template)); } return expanded; }; internals.validateScope = function (credentials, scope, type) { if (!scope[type]) { return true; } const count = typeof credentials.scope === 'string' ? scope[type].indexOf(credentials.scope) !== -1 ? 1 : 0 : Hoek.intersect(scope[type], credentials.scope).length; if (type === 'forbidden') { return count === 0; } if (type === 'required') { return count === scope.required.length; } return !!count; }; ================================================ FILE: lib/compression.js ================================================ 'use strict'; const Zlib = require('zlib'); const Accept = require('@hapi/accept'); const Bounce = require('@hapi/bounce'); const Hoek = require('@hapi/hoek'); const internals = { common: ['gzip, deflate', 'deflate, gzip', 'gzip', 'deflate', 'gzip, deflate, br'] }; exports = module.exports = internals.Compression = class { decoders = { gzip: (options) => Zlib.createGunzip(options), deflate: (options) => Zlib.createInflate(options) }; encodings = ['identity', 'gzip', 'deflate']; encoders = { identity: null, gzip: (options) => Zlib.createGzip(options), deflate: (options) => Zlib.createDeflate(options) }; #common = null; constructor() { this._updateCommons(); } _updateCommons() { this.#common = new Map(); for (const header of internals.common) { this.#common.set(header, Accept.encoding(header, this.encodings)); } } addEncoder(encoding, encoder) { Hoek.assert(this.encoders[encoding] === undefined, `Cannot override existing encoder for ${encoding}`); Hoek.assert(typeof encoder === 'function', `Invalid encoder function for ${encoding}`); this.encoders[encoding] = encoder; this.encodings.unshift(encoding); this._updateCommons(); } addDecoder(encoding, decoder) { Hoek.assert(this.decoders[encoding] === undefined, `Cannot override existing decoder for ${encoding}`); Hoek.assert(typeof decoder === 'function', `Invalid decoder function for ${encoding}`); this.decoders[encoding] = decoder; } accept(request) { const header = request.headers['accept-encoding']; if (!header) { return 'identity'; } const common = this.#common.get(header); if (common) { return common; } try { return Accept.encoding(header, this.encodings); } catch (err) { Bounce.rethrow(err, 'system'); err.header = header; request._log(['accept-encoding', 'error'], err); return 'identity'; } } encoding(response, length) { if (response.settings.compressed) { response.headers['content-encoding'] = response.settings.compressed; return null; } const request = response.request; if (!request._core.settings.compression || length !== null && length < request._core.settings.compression.minBytes) { return null; } const mime = request._core.mime.type(response.headers['content-type'] || 'application/octet-stream'); if (!mime.compressible) { return null; } response.vary('accept-encoding'); if (response.headers['content-encoding']) { return null; } return request.info.acceptEncoding === 'identity' ? null : request.info.acceptEncoding; } encoder(request, encoding) { const encoder = this.encoders[encoding]; Hoek.assert(encoder !== undefined, `Unknown encoding ${encoding}`); return encoder(request.route.settings.compression[encoding]); } }; ================================================ FILE: lib/config.js ================================================ 'use strict'; const Os = require('os'); const Somever = require('@hapi/somever'); const Validate = require('@hapi/validate'); const internals = {}; exports.symbol = Symbol('hapi-response'); exports.apply = function (type, options, ...message) { const result = internals[type].validate(options); if (result.error) { throw new Error(`Invalid ${type} options ${message.length ? '(' + message.join(' ') + ')' : ''} ${result.error.annotate()}`); } return result.value; }; exports.enable = function (options) { const settings = options ? Object.assign({}, options) : {}; // Shallow cloned if (settings.security === true) { settings.security = {}; } if (settings.cors === true) { settings.cors = {}; } return settings; }; exports.versionMatch = (version, range) => Somever.match(version, range, { includePrerelease: true }); internals.access = Validate.object({ entity: Validate.valid('user', 'app', 'any'), scope: [false, Validate.array().items(Validate.string()).single().min(1)] }); internals.auth = Validate.alternatives([ Validate.string(), internals.access.keys({ mode: Validate.valid('required', 'optional', 'try'), strategy: Validate.string(), strategies: Validate.array().items(Validate.string()).min(1), access: Validate.array().items(internals.access.min(1)).single().min(1), payload: [ Validate.valid('required', 'optional'), Validate.boolean() ] }) .without('strategy', 'strategies') .without('access', ['scope', 'entity']) ]); internals.event = Validate.object({ method: Validate.array().items(Validate.function()).single(), options: Validate.object({ before: Validate.array().items(Validate.string()).single(), after: Validate.array().items(Validate.string()).single(), bind: Validate.any(), sandbox: Validate.valid('server', 'plugin'), timeout: Validate.number().integer().min(1) }) .default({}) }); internals.exts = Validate.array() .items(internals.event.keys({ type: Validate.string().required() })).single(); internals.failAction = Validate.alternatives([ Validate.valid('error', 'log', 'ignore'), Validate.function() ]) .default('error'); internals.routeBase = Validate.object({ app: Validate.object().allow(null), auth: internals.auth.allow(false), bind: Validate.object().allow(null), cache: Validate.object({ expiresIn: Validate.number(), expiresAt: Validate.string(), privacy: Validate.valid('default', 'public', 'private'), statuses: Validate.array().items(Validate.number().integer().min(200)).min(1).single().default([200, 204]), otherwise: Validate.string().default('no-cache') }) .allow(false) .default(), compression: Validate.object() .pattern(/.+/, Validate.object()) .default(), cors: Validate.object({ origin: Validate.array().min(1).allow('ignore').default(['*']), maxAge: Validate.number().default(86400), headers: Validate.array().items(Validate.string()).default(['Accept', 'Authorization', 'Content-Type', 'If-None-Match']), additionalHeaders: Validate.array().items(Validate.string()).default([]), exposedHeaders: Validate.array().items(Validate.string()).default(['WWW-Authenticate', 'Server-Authorization']), additionalExposedHeaders: Validate.array().items(Validate.string()).default([]), credentials: Validate.boolean().when('origin', { is: 'ignore', then: false }).default(false), preflightStatusCode: Validate.valid(200, 204).default(200) }) .allow(false, true) .default(false), ext: Validate.object({ onPreAuth: Validate.array().items(internals.event).single(), onCredentials: Validate.array().items(internals.event).single(), onPostAuth: Validate.array().items(internals.event).single(), onPreHandler: Validate.array().items(internals.event).single(), onPostHandler: Validate.array().items(internals.event).single(), onPreResponse: Validate.array().items(internals.event).single(), onPostResponse: Validate.array().items(internals.event).single() }) .default({}), files: Validate.object({ relativeTo: Validate.string().pattern(/^([\/\.])|([A-Za-z]:\\)|(\\\\)/).default('.') }) .default(), json: Validate.object({ replacer: Validate.alternatives(Validate.function(), Validate.array()).allow(null).default(null), space: Validate.number().allow(null).default(null), suffix: Validate.string().allow(null).default(null), escape: Validate.boolean().default(false) }) .default(), log: Validate.object({ collect: Validate.boolean().default(false) }) .default(), payload: Validate.object({ output: Validate.valid('data', 'stream', 'file').default('data'), parse: Validate.boolean().allow('gunzip').default(true), multipart: Validate.object({ output: Validate.valid('data', 'stream', 'file', 'annotated').required() }) .default(false) .allow(true, false), allow: Validate.array().items(Validate.string()).single(), override: Validate.string(), protoAction: Validate.valid('error', 'remove', 'ignore').default('error'), maxBytes: Validate.number().integer().positive().default(1024 * 1024), maxParts: Validate.number().integer().positive().default(1000), uploads: Validate.string().default(Os.tmpdir()), failAction: internals.failAction, timeout: Validate.number().integer().positive().allow(false).default(10 * 1000), defaultContentType: Validate.string().default('application/json'), compression: Validate.object() .pattern(/.+/, Validate.object()) .default() }) .default(), plugins: Validate.object(), response: Validate.object({ disconnectStatusCode: Validate.number().integer().min(400).default(499), emptyStatusCode: Validate.valid(200, 204).default(204), failAction: internals.failAction, modify: Validate.boolean(), options: Validate.object(), ranges: Validate.boolean().default(true), sample: Validate.number().min(0).max(100).when('modify', { then: Validate.forbidden() }), schema: Validate.alternatives(Validate.object(), Validate.array(), Validate.function()).allow(true, false), status: Validate.object().pattern(/\d\d\d/, Validate.alternatives(Validate.object(), Validate.array(), Validate.function()).allow(true, false)) }) .default(), security: Validate.object({ hsts: Validate.alternatives([ Validate.object({ maxAge: Validate.number(), includeSubdomains: Validate.boolean(), includeSubDomains: Validate.boolean(), preload: Validate.boolean() }), Validate.boolean(), Validate.number() ]) .default(15768000), xframe: Validate.alternatives([ Validate.boolean(), Validate.valid('sameorigin', 'deny'), Validate.object({ rule: Validate.valid('sameorigin', 'deny', 'allow-from'), source: Validate.string() }) ]) .default('deny'), xss: Validate.valid('enabled', 'disabled', false).default('disabled'), noOpen: Validate.boolean().default(true), noSniff: Validate.boolean().default(true), referrer: Validate.alternatives([ Validate.boolean().valid(false), Validate.valid('', 'no-referrer', 'no-referrer-when-downgrade', 'unsafe-url', 'same-origin', 'origin', 'strict-origin', 'origin-when-cross-origin', 'strict-origin-when-cross-origin') ]) .default(false) }) .allow(null, false, true) .default(false), state: Validate.object({ parse: Validate.boolean().default(true), failAction: internals.failAction }) .default(), timeout: Validate.object({ socket: Validate.number().integer().positive().allow(false), server: Validate.number().integer().positive().allow(false).default(false) }) .default(), validate: Validate.object({ headers: Validate.alternatives(Validate.object(), Validate.array(), Validate.function()).allow(null, true), params: Validate.alternatives(Validate.object(), Validate.array(), Validate.function()).allow(null, true), query: Validate.alternatives(Validate.object(), Validate.array(), Validate.function()).allow(null, false, true), payload: Validate.alternatives(Validate.object(), Validate.array(), Validate.function()).allow(null, false, true), state: Validate.alternatives(Validate.object(), Validate.array(), Validate.function()).allow(null, false, true), failAction: internals.failAction, errorFields: Validate.object(), options: Validate.object().default(), validator: Validate.object() }) .default() }); internals.server = Validate.object({ address: Validate.string().hostname(), app: Validate.object().allow(null), autoListen: Validate.boolean(), cache: Validate.allow(null), // Validated elsewhere compression: Validate.object({ minBytes: Validate.number().min(1).integer().default(1024) }) .allow(false) .default(), debug: Validate.object({ request: Validate.array().items(Validate.string()).single().allow(false).default(['implementation']), log: Validate.array().items(Validate.string()).single().allow(false) }) .allow(false) .default(), host: Validate.string().hostname().allow(null), info: Validate.object({ remote: Validate.boolean().default(false) }) .default({}), listener: Validate.any(), load: Validate.object({ sampleInterval: Validate.number().integer().min(0).default(0) }) .unknown() .default(), mime: Validate.object().empty(null).default(), operations: Validate.object({ cleanStop: Validate.boolean().default(true) }) .default(), plugins: Validate.object(), port: Validate.alternatives([ Validate.number().integer().min(0), // TCP port Validate.string().pattern(/\//), // Unix domain socket Validate.string().pattern(/^\\\\\.\\pipe\\/) // Windows named pipe ]) .allow(null), query: Validate.object({ parser: Validate.function() }) .default(), router: Validate.object({ isCaseSensitive: Validate.boolean().default(true), stripTrailingSlash: Validate.boolean().default(false) }) .default(), routes: internals.routeBase.default(), state: Validate.object(), // Cookie defaults tls: Validate.alternatives([ Validate.object().allow(null), Validate.boolean() ]), uri: Validate.string().pattern(/[^/]$/) }); internals.vhost = Validate.alternatives([ Validate.string().hostname(), Validate.array().items(Validate.string().hostname()).min(1) ]); internals.handler = Validate.alternatives([ Validate.function(), Validate.object().length(1) ]); internals.route = Validate.object({ method: Validate.string().pattern(/^[a-zA-Z0-9!#\$%&'\*\+\-\.^_`\|~]+$/).required(), path: Validate.string().required(), rules: Validate.object(), vhost: internals.vhost, // Validated in route construction handler: Validate.any(), options: Validate.any(), config: Validate.any() // Backwards compatibility }) .without('config', 'options'); internals.pre = [ Validate.function(), Validate.object({ method: Validate.alternatives(Validate.string(), Validate.function()).required(), assign: Validate.string(), mode: Validate.valid('serial', 'parallel'), failAction: internals.failAction }) ]; internals.routeConfig = internals.routeBase.keys({ description: Validate.string(), id: Validate.string(), isInternal: Validate.boolean(), notes: [ Validate.string(), Validate.array().items(Validate.string()) ], pre: Validate.array().items(...internals.pre.concat(Validate.array().items(...internals.pre).min(1))), tags: [ Validate.string(), Validate.array().items(Validate.string()) ] }); internals.cacheConfig = Validate.alternatives([ Validate.function(), Validate.object({ name: Validate.string().invalid('_default'), shared: Validate.boolean(), provider: [ Validate.function(), { constructor: Validate.function().required(), options: Validate.object({ partition: Validate.string().default('hapi-cache') }) .unknown() // Catbox client validates other keys .default({}) } ], engine: Validate.object() }) .xor('provider', 'engine') ]); internals.cache = Validate.array().items(internals.cacheConfig).min(1).single(); internals.cachePolicy = Validate.object({ cache: Validate.string().allow(null).allow(''), segment: Validate.string(), shared: Validate.boolean() }) .unknown(); // Catbox policy validates other keys internals.method = Validate.object({ bind: Validate.object().allow(null), generateKey: Validate.function(), cache: internals.cachePolicy }); internals.methodObject = Validate.object({ name: Validate.string().required(), method: Validate.function().required(), options: Validate.object() }); internals.register = Validate.object({ once: true, routes: Validate.object({ prefix: Validate.string().pattern(/^\/.+/), vhost: internals.vhost }) .default({}) }); internals.semver = Validate.string(); internals.plugin = internals.register.keys({ options: Validate.any(), plugin: Validate.object({ register: Validate.function().required(), name: Validate.string().when('pkg.name', { is: Validate.exist(), otherwise: Validate.required() }), version: Validate.string(), multiple: Validate.boolean().default(false), dependencies: [ Validate.array().items(Validate.string()).single(), Validate.object().pattern(/.+/, internals.semver) ], once: true, requirements: Validate.object({ hapi: Validate.string(), node: Validate.string() }) .default(), pkg: Validate.object({ name: Validate.string(), version: Validate.string().default('0.0.0') }) .unknown() .default({}) }) .unknown() }) .without('once', 'options') .unknown(); internals.rules = Validate.object({ validate: Validate.object({ schema: Validate.alternatives(Validate.object(), Validate.array()).required(), options: Validate.object() .default({ allowUnknown: true }) }) }); ================================================ FILE: lib/core.js ================================================ 'use strict'; const Http = require('http'); const Https = require('https'); const Os = require('os'); const Path = require('path'); const Boom = require('@hapi/boom'); const Bounce = require('@hapi/bounce'); const Call = require('@hapi/call'); const Catbox = require('@hapi/catbox'); const { Engine: CatboxMemory } = require('@hapi/catbox-memory'); const { Heavy } = require('@hapi/heavy'); const Hoek = require('@hapi/hoek'); const { Mimos } = require('@hapi/mimos'); const Podium = require('@hapi/podium'); const Statehood = require('@hapi/statehood'); const Auth = require('./auth'); const Compression = require('./compression'); const Config = require('./config'); const Cors = require('./cors'); const Ext = require('./ext'); const Methods = require('./methods'); const Request = require('./request'); const Response = require('./response'); const Route = require('./route'); const Toolkit = require('./toolkit'); const Validation = require('./validation'); const internals = { counter: { min: 10000, max: 99999 }, events: [ { name: 'cachePolicy', spread: true }, { name: 'log', channels: ['app', 'internal'], tags: true }, { name: 'request', channels: ['app', 'internal', 'error'], tags: true, spread: true }, 'response', 'route', 'start', 'closing', 'stop' ], badRequestResponse: Buffer.from('HTTP/1.1 400 Bad Request\r\n\r\n', 'ascii') }; exports = module.exports = internals.Core = class { actives = new WeakMap(); // Active requests being processed app = {}; auth = new Auth(this); caches = new Map(); // Cache clients compression = new Compression(); controlled = null; // Other servers linked to the phases of this server dependencies = []; // Plugin dependencies events = new Podium.Podium(internals.events); heavy = null; info = null; instances = new Set(); listener = null; methods = new Methods(this); // Server methods mime = null; onConnection = null; // Used to remove event listener on stop phase = 'stopped'; // 'stopped', 'initializing', 'initialized', 'starting', 'started', 'stopping', 'invalid' plugins = {}; // Exposed plugin properties by name registrations = {}; // Tracks plugin for dependency validation { name -> { version } } registring = 0; // > 0 while register() is waiting for plugin callbacks Request = class extends Request { }; Response = class extends Response { }; requestCounter = { value: internals.counter.min, min: internals.counter.min, max: internals.counter.max }; root = null; router = null; settings = null; sockets = null; // Track open sockets for graceful shutdown started = false; states = null; toolkit = new Toolkit.Manager(); type = null; validator = null; extensionsSeq = 0; // Used to keep absolute order of extensions based on the order added across locations extensions = { server: { onPreStart: new Ext('onPreStart', this), onPostStart: new Ext('onPostStart', this), onPreStop: new Ext('onPreStop', this), onPostStop: new Ext('onPostStop', this) }, route: { onRequest: new Ext('onRequest', this), onPreAuth: new Ext('onPreAuth', this), onCredentials: new Ext('onCredentials', this), onPostAuth: new Ext('onPostAuth', this), onPreHandler: new Ext('onPreHandler', this), onPostHandler: new Ext('onPostHandler', this), onPreResponse: new Ext('onPreResponse', this), onPostResponse: new Ext('onPostResponse', this) } }; decorations = { handler: new Map(), request: new Map(), response: new Map(), server: new Map(), toolkit: new Map(), requestApply: null, public: { handler: [], request: [], response: [], server: [], toolkit: [] } }; constructor(options) { const { settings, type } = internals.setup(options); this.settings = settings; this.type = type; this.heavy = new Heavy(this.settings.load); this.mime = new Mimos(this.settings.mime); this.router = new Call.Router(this.settings.router); this.states = new Statehood.Definitions(this.settings.state); this._debug(); this._initializeCache(); if (this.settings.routes.validate.validator) { this.validator = Validation.validator(this.settings.routes.validate.validator); } this.listener = this._createListener(); this._initializeListener(); this.info = this._info(); } _debug() { const debug = this.settings.debug; if (!debug) { return; } // Subscribe to server log events const method = (event) => { const data = event.error ?? event.data; console.error('Debug:', event.tags.join(', '), data ? '\n ' + (data.stack ?? (typeof data === 'object' ? Hoek.stringify(data) : data)) : ''); }; if (debug.log) { const filter = debug.log.some((tag) => tag === '*') ? undefined : debug.log; this.events.on({ name: 'log', filter }, method); } if (debug.request) { const filter = debug.request.some((tag) => tag === '*') ? undefined : debug.request; this.events.on({ name: 'request', filter }, (request, event) => method(event)); } } _initializeCache() { if (this.settings.cache) { this._createCache(this.settings.cache); } if (!this.caches.has('_default')) { this._createCache([{ provider: CatboxMemory }]); // Defaults to memory-based } } _info() { const now = Date.now(); const protocol = this.type === 'tcp' ? (this.settings.tls ? 'https' : 'http') : this.type; const host = this.settings.host || Os.hostname() || 'localhost'; const port = this.settings.port; const info = { created: now, started: 0, host, port, protocol, id: Os.hostname() + ':' + process.pid + ':' + now.toString(36), uri: this.settings.uri ?? (protocol + ':' + (this.type === 'tcp' ? '//' + host + (port ? ':' + port : '') : port)) }; return info; } _counter() { const next = ++this.requestCounter.value; if (this.requestCounter.value > this.requestCounter.max) { this.requestCounter.value = this.requestCounter.min; } return next - 1; } _createCache(configs) { Hoek.assert(this.phase !== 'initializing', 'Cannot provision server cache while server is initializing'); configs = Config.apply('cache', configs); const added = []; for (let config of configs) { // // { provider: } // { provider: { constructor: , options } } // { engine } if (typeof config === 'function') { config = { provider: { constructor: config } }; } const name = config.name ?? '_default'; Hoek.assert(!this.caches.has(name), 'Cannot configure the same cache more than once: ', name === '_default' ? 'default cache' : name); let client = null; if (config.provider) { let provider = config.provider; if (typeof provider === 'function') { provider = { constructor: provider }; } client = new Catbox.Client(provider.constructor, provider.options ?? { partition: 'hapi-cache' }); } else { client = new Catbox.Client(config.engine); } this.caches.set(name, { client, segments: {}, shared: config.shared ?? false }); added.push(client); } return added; } registerServer(server) { if (!this.root) { this.root = server; this._defaultRoutes(); } this.instances.add(server); } async _start() { if (this.phase === 'initialized' || this.phase === 'started') { this._validateDeps(); } if (this.phase === 'started') { return; } if (this.phase !== 'stopped' && this.phase !== 'initialized') { throw new Error('Cannot start server while it is in ' + this.phase + ' phase'); } if (this.phase !== 'initialized') { await this._initialize(); } this.phase = 'starting'; this.started = true; this.info.started = Date.now(); try { await this._listen(); } catch (err) { this.started = false; this.phase = 'invalid'; throw err; } this.phase = 'started'; this.events.emit('start'); try { if (this.controlled) { await Promise.all(this.controlled.map((control) => control.start())); } await this._invoke('onPostStart'); } catch (err) { this.phase = 'invalid'; throw err; } } _listen() { return new Promise((resolve, reject) => { if (!this.settings.autoListen) { resolve(); return; } const onError = (err) => { reject(err); return; }; this.listener.once('error', onError); const finalize = () => { this.listener.removeListener('error', onError); resolve(); return; }; if (this.type !== 'tcp') { this.listener.listen(this.settings.port, finalize); } else { // Default is the unspecified address, :: if IPv6 is available or otherwise the IPv4 address 0.0.0.0 const address = this.settings.address || this.settings.host || null; this.listener.listen(this.settings.port, address, finalize); } }); } async _initialize() { if (this.registring) { throw new Error('Cannot start server before plugins finished registration'); } if (this.phase === 'initialized') { return; } if (this.phase !== 'stopped') { throw new Error('Cannot initialize server while it is in ' + this.phase + ' phase'); } this._validateDeps(); this.phase = 'initializing'; // Start cache try { const caches = []; this.caches.forEach((cache) => caches.push(cache.client.start())); await Promise.all(caches); await this._invoke('onPreStart'); this.heavy.start(); this.phase = 'initialized'; if (this.controlled) { await Promise.all(this.controlled.map((control) => control.initialize())); } } catch (err) { this.phase = 'invalid'; throw err; } } _validateDeps() { for (const { deps, plugin } of this.dependencies) { for (const dep in deps) { const version = deps[dep]; Hoek.assert(this.registrations[dep], 'Plugin', plugin, 'missing dependency', dep); Hoek.assert(version === '*' || Config.versionMatch(this.registrations[dep].version, version), 'Plugin', plugin, 'requires', dep, 'version', version, 'but found', this.registrations[dep].version); } } } async _stop(options = {}) { options.timeout = options.timeout ?? 5000; // Default timeout to 5 seconds if (['stopped', 'initialized', 'started', 'invalid'].indexOf(this.phase) === -1) { throw new Error('Cannot stop server while in ' + this.phase + ' phase'); } this.phase = 'stopping'; try { await this._invoke('onPreStop'); if (this.started) { this.started = false; this.info.started = 0; await this._unlisten(options.timeout); } const caches = []; this.caches.forEach((cache) => caches.push(cache.client.stop())); await Promise.all(caches); this.events.emit('stop'); this.heavy.stop(); if (this.controlled) { await Promise.all(this.controlled.map((control) => control.stop(options))); } await this._invoke('onPostStop'); this.phase = 'stopped'; } catch (err) { this.phase = 'invalid'; throw err; } } _unlisten(timeout) { let timeoutId = null; if (this.settings.operations.cleanStop) { // Set connections timeout const destroy = () => { for (const connection of this.sockets) { connection.destroy(); } this.sockets.clear(); }; timeoutId = setTimeout(destroy, timeout); // Tell idle keep-alive connections to close for (const connection of this.sockets) { if (!this.actives.has(connection)) { connection.end(); } } } // Close connection return new Promise((resolve) => { this.listener.close(() => { if (this.settings.operations.cleanStop) { this.listener.removeListener(this.settings.tls ? 'secureConnection' : 'connection', this.onConnection); clearTimeout(timeoutId); } this._initializeListener(); resolve(); }); this.events.emit('closing'); }); } async _invoke(type) { const exts = this.extensions.server[type]; if (!exts.nodes) { return; } // Execute extensions for (const ext of exts.nodes) { const bind = ext.bind ?? ext.realm.settings.bind; const operation = ext.func.call(bind, ext.server, bind); await Toolkit.timed(operation, { timeout: ext.timeout, name: type }); } } _defaultRoutes() { this.router.special('notFound', new Route({ method: '_special', path: '/{p*}', handler: internals.notFound }, this.root, { special: true })); this.router.special('badRequest', new Route({ method: '_special', path: '/{p*}', handler: internals.badRequest }, this.root, { special: true })); if (this.settings.routes.cors) { Cors.handler(this.root); } } _dispatch(options = {}) { return (req, res) => { // Create request const request = Request.generate(this.root, req, res, options); // Track socket request processing state if (this.settings.operations.cleanStop && req.socket) { this.actives.set(req.socket, request); const env = { core: this, req }; res.on('finish', internals.onFinish.bind(res, env)); } // Check load if (this.settings.load.sampleInterval) { try { this.heavy.check(); } catch (err) { Bounce.rethrow(err, 'system'); this._log(['load'], this.heavy.load); request._reply(err); return; } } request._execute(); }; } _createListener() { const listener = this.settings.listener ?? (this.settings.tls ? Https.createServer(this.settings.tls) : Http.createServer()); listener.on('request', this._dispatch()); listener.on('checkContinue', this._dispatch({ expectContinue: true })); listener.on('clientError', (err, socket) => { this._log(['connection', 'client', 'error'], err); if (socket.readable) { const request = this.settings.operations.cleanStop && this.actives.get(socket); if (request) { // If a request is available, it means that the connection and parsing has progressed far enough to have created the request. if (err.code === 'HPE_INVALID_METHOD') { // This parser error is for a pipelined request. Schedule destroy once current request is done. request.raw.res.once('close', () => { if (socket.readable) { socket.end(internals.badRequestResponse); } else { socket.destroy(err); } }); return; } const error = Boom.badRequest(); error.output.headers = { connection: 'close' }; request._reply(error); } else { socket.end(internals.badRequestResponse); } } else { socket.destroy(err); } }); return listener; } _initializeListener() { this.listener.once('listening', () => { // Update the address, port, and uri with active values if (this.type === 'tcp') { const address = this.listener.address(); this.info.address = address.address; this.info.port = address.port; this.info.uri = this.settings.uri ?? this.info.protocol + '://' + this.info.host + ':' + this.info.port; } if (this.settings.operations.cleanStop) { this.sockets = new Set(); const self = this; const onClose = function () { // 'this' is bound to the emitter self.sockets.delete(this); }; this.onConnection = (connection) => { this.sockets.add(connection); connection.on('close', onClose); }; this.listener.on(this.settings.tls ? 'secureConnection' : 'connection', this.onConnection); } }); } _cachePolicy(options, _segment, realm) { options = Config.apply('cachePolicy', options); const plugin = realm?.plugin; const segment = options.segment ?? _segment ?? (plugin ? `!${plugin}` : ''); Hoek.assert(segment, 'Missing cache segment name'); const cacheName = options.cache ?? '_default'; const cache = this.caches.get(cacheName); Hoek.assert(cache, 'Unknown cache', cacheName); Hoek.assert(!cache.segments[segment] || cache.shared || options.shared, 'Cannot provision the same cache segment more than once'); cache.segments[segment] = true; const policy = new Catbox.Policy(options, cache.client, segment); this.events.emit('cachePolicy', [policy, options.cache, segment]); return policy; } log(tags, data) { return this._log(tags, data, 'app'); } _log(tags, data, channel = 'internal') { if (!this.events.hasListeners('log')) { return; } if (!Array.isArray(tags)) { tags = [tags]; } const timestamp = Date.now(); const field = data instanceof Error ? 'error' : 'data'; let event = { timestamp, tags, [field]: data, channel }; if (typeof data === 'function') { event = () => ({ timestamp, tags, data: data(), channel }); } this.events.emit({ name: 'log', tags, channel }, event); } }; internals.setup = function (options = {}) { let settings = Hoek.clone(options, { shallow: ['cache', 'listener', 'routes.bind'] }); settings.app = settings.app ?? {}; settings.routes = Config.enable(settings.routes); settings = Config.apply('server', settings); if (settings.port === undefined) { settings.port = 0; } const type = (typeof settings.port === 'string' ? 'socket' : 'tcp'); if (type === 'socket') { settings.port = (settings.port.indexOf('/') !== -1 ? Path.resolve(settings.port) : settings.port.toLowerCase()); } if (settings.autoListen === undefined) { settings.autoListen = true; } Hoek.assert(settings.autoListen || !settings.port, 'Cannot specify port when autoListen is false'); Hoek.assert(settings.autoListen || !settings.address, 'Cannot specify address when autoListen is false'); return { settings, type }; }; internals.notFound = function () { throw Boom.notFound(); }; internals.badRequest = function () { throw Boom.badRequest(); }; internals.onFinish = function (env) { const { core, req } = env; core.actives.delete(req.socket); if (!core.started) { req.socket.end(); } }; ================================================ FILE: lib/cors.js ================================================ 'use strict'; const Boom = require('@hapi/boom'); const Hoek = require('@hapi/hoek'); let Route = null; // Delayed load due to circular dependency const internals = {}; exports.route = function (options) { if (!options) { return false; } const settings = Hoek.clone(options); settings._headers = settings.headers.concat(settings.additionalHeaders); settings._headersString = settings._headers.join(','); for (let i = 0; i < settings._headers.length; ++i) { settings._headers[i] = settings._headers[i].toLowerCase(); } if (settings._headers.indexOf('origin') === -1) { settings._headers.push('origin'); } settings._exposedHeaders = settings.exposedHeaders.concat(settings.additionalExposedHeaders).join(','); if (settings.origin === 'ignore') { settings._origin = false; } else if (settings.origin.indexOf('*') !== -1) { Hoek.assert(settings.origin.length === 1, 'Cannot specify cors.origin * together with other values'); settings._origin = true; } else { settings._origin = { qualified: [], wildcards: [] }; for (const origin of settings.origin) { if (origin.indexOf('*') !== -1) { settings._origin.wildcards.push(new RegExp('^' + Hoek.escapeRegex(origin).replace(/\\\*/g, '.*').replace(/\\\?/g, '.') + '$')); } else { settings._origin.qualified.push(origin); } } } return settings; }; exports.options = function (route, server) { if (route.method === 'options' || !route.settings.cors) { return; } exports.handler(server); }; exports.handler = function (server) { Route = Route || require('./route'); if (server._core.router.specials.options) { return; } const definition = { method: '_special', path: '/{p*}', handler: internals.handler, options: { cors: false } }; const route = new Route(definition, server, { special: true }); server._core.router.special('options', route); }; internals.handler = function (request, h) { // Validate CORS preflight request const method = request.headers['access-control-request-method']; if (!method) { throw Boom.notFound('CORS error: Missing Access-Control-Request-Method header'); } // Lookup route const route = request.server.match(method, request.path, request.info.hostname); if (!route) { throw Boom.notFound(); } const settings = route.settings.cors; if (!settings) { return { message: 'CORS is disabled for this route' }; } // Validate Origin header const origin = request.headers.origin; if (!origin && settings._origin !== false) { throw Boom.notFound('CORS error: Missing Origin header'); } if (!exports.matchOrigin(origin, settings)) { return { message: 'CORS error: Origin not allowed' }; } // Validate allowed headers let headers = request.headers['access-control-request-headers']; if (headers) { headers = headers.toLowerCase().split(/\s*,\s*/); if (Hoek.intersect(headers, settings._headers).length !== headers.length) { return { message: 'CORS error: Some headers are not allowed' }; } } // Reply with the route CORS headers const response = h.response(); response.code(settings.preflightStatusCode); response._header('access-control-allow-origin', settings._origin ? origin : '*'); response._header('access-control-allow-methods', method); response._header('access-control-allow-headers', settings._headersString); response._header('access-control-max-age', settings.maxAge); if (settings.credentials) { response._header('access-control-allow-credentials', 'true'); } if (settings._exposedHeaders) { response._header('access-control-expose-headers', settings._exposedHeaders); } return response; }; exports.headers = function (response) { const request = response.request; const settings = request.route.settings.cors; if (settings._origin !== false) { response.vary('origin'); } if ((request.info.cors && !request.info.cors.isOriginMatch) || // After route lookup !exports.matchOrigin(request.headers.origin, request.route.settings.cors)) { // Response from onRequest return; } response._header('access-control-allow-origin', settings._origin ? request.headers.origin : '*'); if (settings.credentials) { response._header('access-control-allow-credentials', 'true'); } if (settings._exposedHeaders) { response._header('access-control-expose-headers', settings._exposedHeaders, { append: true }); } }; exports.matchOrigin = function (origin, settings) { if (settings._origin === true || settings._origin === false) { return true; } if (!origin) { return false; } if (settings._origin.qualified.indexOf(origin) !== -1) { return true; } for (const wildcard of settings._origin.wildcards) { if (origin.match(wildcard)) { return true; } } return false; }; ================================================ FILE: lib/ext.js ================================================ 'use strict'; const Hoek = require('@hapi/hoek'); const Topo = require('@hapi/topo'); const internals = {}; exports = module.exports = internals.Ext = class { type = null; nodes = null; #core = null; #routes = []; #topo = new Topo.Sorter(); constructor(type, core) { this.#core = core; this.type = type; } add(event) { const methods = [].concat(event.method); for (const method of methods) { const settings = { before: event.options.before, after: event.options.after, group: event.realm.plugin, sort: this.#core.extensionsSeq++ }; const node = { func: method, // Request: function (request, h), Server: function (server) bind: event.options.bind, server: event.server, // Server event realm: event.realm, timeout: event.options.timeout }; this.#topo.add(node, settings); } this.nodes = this.#topo.nodes; // Notify routes for (const route of this.#routes) { route.rebuild(event); } } merge(others) { const merge = []; for (const other of others) { merge.push(other.#topo); } this.#topo.merge(merge); this.nodes = this.#topo.nodes.length ? this.#topo.nodes : null; } subscribe(route) { this.#routes.push(route); } static combine(route, type) { const ext = new internals.Ext(type, route._core); const events = route.settings.ext[type]; if (events) { for (let event of events) { event = Object.assign({}, event); // Shallow cloned Hoek.assert(!event.options.sandbox, 'Cannot specify sandbox option for route extension'); event.realm = route.realm; ext.add(event); } } const server = route._core.extensions.route[type]; const realm = route.realm._extensions[type]; ext.merge([server, realm]); server.subscribe(route); realm.subscribe(route); return ext; } }; ================================================ FILE: lib/handler.js ================================================ 'use strict'; const Hoek = require('@hapi/hoek'); const internals = {}; exports.execute = async function (request) { // Prerequisites if (request._route._prerequisites) { for (const set of request._route._prerequisites) { // Serial execution of each set const pres = []; for (const item of set) { pres.push(internals.handler(request, item.method, item)); } const responses = await Promise.all(pres); // Parallel execution within sets for (const response of responses) { if (response !== undefined) { return response; } } } } // Handler const result = await internals.handler(request, request.route.settings.handler); if (result._takeover || typeof result === 'symbol') { return result; } request._setResponse(result); }; internals.handler = async function (request, method, pre) { const bind = request.route.settings.bind; const realm = request.route.realm; let response = await request._core.toolkit.execute(method, request, { bind, realm, continue: 'null' }); // Handler if (!pre) { if (response.isBoom) { request._log(['handler', 'error'], response); throw response; } return response; } // Pre if (response.isBoom) { response.assign = pre.assign; response = await request._core.toolkit.failAction(request, pre.failAction, response, { tags: ['pre', 'error'], retain: true }); } if (typeof response === 'symbol') { return response; } if (pre.assign) { request.pre[pre.assign] = (response.isBoom ? response : response.source); request.preResponses[pre.assign] = response; } if (response._takeover) { return response; } }; exports.defaults = function (method, handler, core) { let defaults = null; if (typeof handler === 'object') { const type = Object.keys(handler)[0]; const serverHandler = core.decorations.handler.get(type); Hoek.assert(serverHandler, 'Unknown handler:', type); if (serverHandler.defaults) { defaults = (typeof serverHandler.defaults === 'function' ? serverHandler.defaults(method) : serverHandler.defaults); } } return defaults ?? {}; }; exports.configure = function (handler, route) { if (typeof handler === 'object') { const type = Object.keys(handler)[0]; const serverHandler = route._core.decorations.handler.get(type); Hoek.assert(serverHandler, 'Unknown handler:', type); return serverHandler(route.public, handler[type]); } return handler; }; exports.prerequisitesConfig = function (config) { if (!config) { return null; } /* [ [ function (request, h) { }, { method: function (request, h) { } assign: key1 }, { method: function (request, h) { }, assign: key2 } ], { method: function (request, h) { }, assign: key3 } ] */ const prerequisites = []; for (let pres of config) { pres = [].concat(pres); const set = []; for (let pre of pres) { if (typeof pre !== 'object') { pre = { method: pre }; } const item = { method: pre.method, assign: pre.assign, failAction: pre.failAction ?? 'error' }; set.push(item); } prerequisites.push(set); } return prerequisites.length ? prerequisites : null; }; ================================================ FILE: lib/headers.js ================================================ 'use strict'; const Stream = require('stream'); const Boom = require('@hapi/boom'); const internals = {}; exports.cache = function (response) { const request = response.request; if (response.headers['cache-control']) { return; } const settings = request.route.settings.cache; const policy = settings && request._route._cache && (settings._statuses.has(response.statusCode) || (response.statusCode === 304 && settings._statuses.has(200))); if (policy || response.settings.ttl) { const ttl = response.settings.ttl !== null ? response.settings.ttl : request._route._cache.ttl(); const privacy = request.auth.isAuthenticated || response.headers['set-cookie'] ? 'private' : settings.privacy ?? 'default'; response._header('cache-control', 'max-age=' + Math.floor(ttl / 1000) + ', must-revalidate' + (privacy !== 'default' ? ', ' + privacy : '')); } else if (settings) { response._header('cache-control', settings.otherwise); } }; exports.content = async function (response) { const request = response.request; if (response._isPayloadSupported() || request.method === 'head') { await response._marshal(); if (typeof response._payload.size === 'function') { response._header('content-length', response._payload.size(), { override: false }); } if (!response._isPayloadSupported()) { response._close(); // Close unused file streams response._payload = new internals.Empty(); // Set empty stream } exports.type(response); } else { // Set empty stream response._close(); // Close unused file streams response._payload = new internals.Empty(); delete response.headers['content-length']; } }; exports.state = async function (response) { const request = response.request; const states = []; for (const stateName in request._states) { states.push(request._states[stateName]); } try { for (const name in request._core.states.cookies) { const autoValue = request._core.states.cookies[name].autoValue; if (!autoValue || name in request._states || name in request.state) { continue; } if (typeof autoValue !== 'function') { states.push({ name, value: autoValue }); continue; } const value = await autoValue(request); states.push({ name, value }); } if (!states.length) { return; } let header = await request._core.states.format(states, request); const existing = response.headers['set-cookie']; if (existing) { header = (Array.isArray(existing) ? existing : [existing]).concat(header); } response._header('set-cookie', header); } catch (err) { const error = Boom.boomify(err); request._log(['state', 'response', 'error'], error); request._states = {}; // Clear broken state throw error; } }; exports.type = function (response) { const type = response.contentType; if (type !== null && type !== response.headers['content-type']) { response.type(type); } }; exports.entity = function (response) { const request = response.request; if (!request._entity) { return; } if (request._entity.etag && !response.headers.etag) { response.etag(request._entity.etag, { vary: request._entity.vary }); } if (request._entity.modified && !response.headers['last-modified']) { response.header('last-modified', request._entity.modified); } }; exports.unmodified = function (response) { const request = response.request; if (response.statusCode === 304) { return; } const entity = { etag: response.headers.etag, vary: response.settings.varyEtag, modified: response.headers['last-modified'] }; const etag = request._core.Response.unmodified(request, entity); if (etag) { response.code(304); if (etag !== true) { // Override etag with incoming weak match response.headers.etag = etag; } } }; internals.Empty = class extends Stream.Readable { _read(/* size */) { this.push(null); } writeToStream(stream) { stream.end(); } }; ================================================ FILE: lib/index.d.ts ================================================ export * from './types'; ================================================ FILE: lib/index.js ================================================ 'use strict'; const Server = require('./server'); const internals = {}; exports.Server = Server; exports.server = Server; ================================================ FILE: lib/methods.js ================================================ 'use strict'; const Boom = require('@hapi/boom'); const Hoek = require('@hapi/hoek'); const Config = require('./config'); const internals = { methodNameRx: /^[_$a-zA-Z][$\w]*(?:\.[_$a-zA-Z][$\w]*)*$/ }; exports = module.exports = internals.Methods = class { methods = {}; #core = null; constructor(core) { this.#core = core; } add(name, method, options, realm) { if (typeof name !== 'object') { return this._add(name, method, options, realm); } // {} or [{}, {}] const items = [].concat(name); for (let item of items) { item = Config.apply('methodObject', item); this._add(item.name, item.method, item.options ?? {}, realm); } } _add(name, method, options, realm) { Hoek.assert(typeof method === 'function', 'method must be a function'); Hoek.assert(typeof name === 'string', 'name must be a string'); Hoek.assert(name.match(internals.methodNameRx), 'Invalid name:', name); Hoek.assert(!Hoek.reach(this.methods, name, { functions: false }), 'Server method function name already exists:', name); options = Config.apply('method', options, name); const settings = Hoek.clone(options, { shallow: ['bind'] }); settings.generateKey = settings.generateKey ?? internals.generateKey; const bind = settings.bind ?? realm.settings.bind ?? null; const bound = !bind ? method : (...args) => method.apply(bind, args); // Not cached if (!settings.cache) { return this._assign(name, bound); } // Cached Hoek.assert(!settings.cache.generateFunc, 'Cannot set generateFunc with method caching:', name); Hoek.assert(settings.cache.generateTimeout !== undefined, 'Method caching requires a timeout value in generateTimeout:', name); settings.cache.generateFunc = (id, flags) => bound(...id.args, flags); const cache = this.#core._cachePolicy(settings.cache, '#' + name); const func = function (...args) { const key = settings.generateKey.apply(bind, args); if (typeof key !== 'string') { return Promise.reject(Boom.badImplementation('Invalid method key when invoking: ' + name, { name, args })); } return cache.get({ id: key, args }); }; func.cache = { drop: function (...args) { const key = settings.generateKey.apply(bind, args); if (typeof key !== 'string') { return Promise.reject(Boom.badImplementation('Invalid method key when invoking: ' + name, { name, args })); } return cache.drop(key); }, stats: cache.stats }; this._assign(name, func, func); } _assign(name, method) { const path = name.split('.'); let ref = this.methods; for (let i = 0; i < path.length; ++i) { if (!ref[path[i]]) { ref[path[i]] = (i + 1 === path.length ? method : {}); } ref = ref[path[i]]; } } }; internals.supportedArgs = ['string', 'number', 'boolean']; internals.generateKey = function (...args) { let key = ''; for (let i = 0; i < args.length; ++i) { const arg = args[i]; if (!internals.supportedArgs.includes(typeof arg)) { return null; } key = key + (i ? ':' : '') + encodeURIComponent(arg.toString()); } return key; }; ================================================ FILE: lib/request.js ================================================ 'use strict'; const Querystring = require('querystring'); const Url = require('url'); const Boom = require('@hapi/boom'); const Bounce = require('@hapi/bounce'); const Hoek = require('@hapi/hoek'); const Podium = require('@hapi/podium'); const Cors = require('./cors'); const Toolkit = require('./toolkit'); const Transmit = require('./transmit'); const internals = { events: Podium.validate(['finish', { name: 'peek', spread: true }, 'disconnect']), reserved: ['server', 'url', 'query', 'path', 'method', 'mime', 'setUrl', 'setMethod', 'headers', 'id', 'app', 'plugins', 'route', 'auth', 'pre', 'preResponses', 'info', 'isInjected', 'orig', 'params', 'paramsArray', 'payload', 'state', 'response', 'raw', 'domain', 'log', 'logs', 'generateResponse'] }; exports = module.exports = internals.Request = class { constructor(server, req, res, options) { this._allowInternals = !!options.allowInternals; this._closed = false; // true once the response has closed (esp. early) and will not emit any more events this._core = server._core; this._entity = null; // Entity information set via h.entity() this._eventContext = { request: this }; this._events = null; // Assigned an emitter when request.events is accessed this._expectContinue = !!options.expectContinue; this._isInjected = !!options.isInjected; this._isPayloadPending = !!(req.headers['content-length'] || req.headers['transfer-encoding']); // Changes to false when incoming payload fully processed this._isReplied = false; // true when response processing started this._route = this._core.router.specials.notFound.route; // Used prior to routing (only settings are used, not the handler) this._serverTimeoutId = null; this._states = {}; this._url = null; this._urlError = null; this.app = options.app ? Object.assign({}, options.app) : {}; // Place for application-specific state without conflicts with hapi, should not be used by plugins (shallow cloned) this.headers = req.headers; this.logs = []; this.method = req.method.toLowerCase(); this.mime = null; this.orig = {}; this.params = null; this.paramsArray = null; // Array of path parameters in path order this.path = null; this.payload = undefined; this.plugins = options.plugins ? Object.assign({}, options.plugins) : {}; // Place for plugins to store state without conflicts with hapi, should be namespaced using plugin name (shallow cloned) this.pre = {}; // Pre raw values this.preResponses = {}; // Pre response values this.raw = { req, res }; this.response = null; this.route = this._route.public; this.query = null; this.server = server; this.state = null; this.info = new internals.Info(this); this.auth = { isAuthenticated: false, isAuthorized: false, isInjected: options.auth ? true : false, [internals.Request.symbols.authPayload]: options.auth?.payload ?? true, credentials: options.auth?.credentials ?? null, // Special keys: 'app', 'user', 'scope' artifacts: options.auth?.artifacts ?? null, // Scheme-specific artifacts strategy: options.auth?.strategy ?? null, mode: null, error: null }; // Parse request url this._initializeUrl(); } static generate(server, req, res, options) { const request = new server._core.Request(server, req, res, options); // Decorate if (server._core.decorations.requestApply) { for (const [property, assignment] of server._core.decorations.requestApply.entries()) { request[property] = assignment(request); } } request._listen(); return request; } get events() { if (!this._events) { this._events = new Podium.Podium(internals.events); } return this._events; } get isInjected() { return this._isInjected; } get url() { if (this._urlError) { return null; } if (this._url) { return this._url; } return this._parseUrl(this.raw.req.url, this._core.settings.router); } _initializeUrl() { try { this._setUrl(this.raw.req.url, this._core.settings.router.stripTrailingSlash, { fast: true }); } catch (err) { this.path = this.raw.req.url; this.query = {}; this._urlError = Boom.boomify(err, { statusCode: 400, override: false }); } } setUrl(url, stripTrailingSlash) { Hoek.assert(this.params === null, 'Cannot change request URL after routing'); if (url instanceof Url.URL) { url = url.href; } Hoek.assert(typeof url === 'string', 'Url must be a string or URL object'); this._setUrl(url, stripTrailingSlash, { fast: false }); } _setUrl(source, stripTrailingSlash, { fast }) { const url = this._parseUrl(source, { stripTrailingSlash, _fast: fast }); this.query = this._parseQuery(url.searchParams); this.path = url.pathname; } _parseUrl(source, options) { if (source[0] === '/') { // Relative URL if (options._fast) { const url = { pathname: source, searchParams: '' }; const q = source.indexOf('?'); const h = source.indexOf('#'); if (q !== -1 && (h === -1 || q < h)) { url.pathname = source.slice(0, q); const query = h === -1 ? source.slice(q + 1) : source.slice(q + 1, h); url.searchParams = Querystring.parse(query); } else { url.pathname = h === -1 ? source : source.slice(0, h); } this._normalizePath(url, options); return url; } const host = this.info.host || this._formatIpv6Host(this._core.info.host, this._core.info.port); this._url = new Url.URL(`${this._core.info.protocol}://${host}${source}`); } else { // Absolute URI (proxied) this._url = new Url.URL(source); this.info.hostname = this._url.hostname; this.info.host = this._url.host; } this._normalizePath(this._url, options); this._urlError = null; return this._url; } _isBareIpv6(host) { // An IPv6 address contains at least two colons. return /:[^:]*:/.test(host); } _formatIpv6Host(host, port) { return this._isBareIpv6(host) ? `[${host}]:${port}` : `${host}:${port}`; } _normalizePath(url, options) { let path = this._core.router.normalize(url.pathname); if (options.stripTrailingSlash && path.length > 1 && path[path.length - 1] === '/') { path = path.slice(0, -1); } url.pathname = path; } _parseQuery(searchParams) { let query = Object.create(null); // Flatten map if (searchParams instanceof Url.URLSearchParams) { for (let [key, value] of searchParams) { const entry = query[key]; if (entry !== undefined) { value = [].concat(entry, value); } query[key] = value; } } else { query = Object.assign(query, searchParams); } // Custom parser const parser = this._core.settings.query.parser; if (parser) { query = parser(query); if (!query || typeof query !== 'object') { throw Boom.badImplementation('Parsed query must be an object'); } } return query; } setMethod(method) { Hoek.assert(this.params === null, 'Cannot change request method after routing'); Hoek.assert(method && typeof method === 'string', 'Missing method'); this.method = method.toLowerCase(); } active() { return !!this._eventContext.request; } async _execute() { this.info.acceptEncoding = this._core.compression.accept(this); try { await this._onRequest(); } catch (err) { Bounce.rethrow(err, 'system'); return this._reply(err); } this._lookup(); this._setTimeouts(); await this._lifecycle(); this._reply(); } async _onRequest() { // onRequest (can change request method and url) if (this._core.extensions.route.onRequest.nodes) { const response = await this._invoke(this._core.extensions.route.onRequest); if (response) { if (!internals.skip(response)) { throw Boom.badImplementation('onRequest extension methods must return an error, a takeover response, or a continue signal'); } throw response; } } // Validate path if (this._urlError) { throw this._urlError; } } _listen() { if (this._isPayloadPending) { this.raw.req.on('end', internals.event.bind(this.raw.req, this._eventContext, 'end')); } this.raw.res.on('close', internals.event.bind(this.raw.res, this._eventContext, 'close')); this.raw.req.on('error', internals.event.bind(this.raw.req, this._eventContext, 'error')); this.raw.req.on('aborted', internals.event.bind(this.raw.req, this._eventContext, 'abort')); this.raw.res.once('close', internals.closed.bind(this.raw.res, this)); } _lookup() { const match = this._core.router.route(this.method, this.path, this.info.hostname); if (!match.route.settings.isInternal || this._allowInternals) { this._route = match.route; this.route = this._route.public; } this.params = match.params ?? {}; this.paramsArray = match.paramsArray ?? []; if (this.route.settings.cors) { this.info.cors = { isOriginMatch: Cors.matchOrigin(this.headers.origin, this.route.settings.cors) }; } } _setTimeouts() { if (this.raw.req.socket && this.route.settings.timeout.socket !== undefined) { this.raw.req.socket.setTimeout(this.route.settings.timeout.socket || 0); // Value can be false or positive } let serverTimeout = this.route.settings.timeout.server; if (!serverTimeout) { return; } const elapsed = Date.now() - this.info.received; serverTimeout = Math.floor(serverTimeout - elapsed); // Calculate the timeout from when the request was constructed if (serverTimeout <= 0) { internals.timeoutReply(this, serverTimeout); return; } this._serverTimeoutId = setTimeout(internals.timeoutReply, serverTimeout, this, serverTimeout); } async _lifecycle() { for (const func of this._route._cycle) { if (this._isReplied) { return; } try { var response = await (typeof func === 'function' ? func(this) : this._invoke(func)); } catch (err) { Bounce.rethrow(err, 'system'); response = this._core.Response.wrap(err, this); } if (!response || response === Toolkit.symbols.continue) { // Continue continue; } if (!internals.skip(response)) { response = Boom.badImplementation('Lifecycle methods called before the handler can only return an error, a takeover response, or a continue signal'); } this._setResponse(response); return; } } async _invoke(event, options = {}) { for (const ext of event.nodes) { const realm = ext.realm; const bind = ext.bind ?? realm.settings.bind; const response = await this._core.toolkit.execute(ext.func, this, { bind, realm, timeout: ext.timeout, name: event.type, ignoreResponse: options.ignoreResponse }); if (options.ignoreResponse) { if (Boom.isBoom(response)) { this._log(['ext', 'error'], response); } continue; } if (response === Toolkit.symbols.continue) { continue; } if (internals.skip(response) || this.response === null) { return response; } this._setResponse(response); } } async _reply(exit) { if (this._isReplied) { // Prevent any future responses to this request return; } this._isReplied = true; if (this._serverTimeoutId) { clearTimeout(this._serverTimeoutId); } if (exit) { // Can be a valid response or error (if returned from an ext, already handled because this.response is also set) this._setResponse(this._core.Response.wrap(exit, this)); // Wrap to ensure any object thrown is always a valid Boom or Response object } if (!this._eventContext.request) { this._finalize(); return; } if (typeof this.response === 'symbol') { // close or abandon this._abort(); return; } await this._postCycle(); if (!this._eventContext.request || typeof this.response === 'symbol') { // close or abandon this._abort(); return; } await Transmit.send(this); this._finalize(); } async _postCycle() { for (const func of this._route._postCycle) { if (!this._eventContext.request) { return; } try { var response = await (typeof func === 'function' ? func(this) : this._invoke(func)); } catch (err) { Bounce.rethrow(err, 'system'); response = this._core.Response.wrap(err, this); } if (response && response !== Toolkit.symbols.continue) { // Continue this._setResponse(response); } } } _abort() { if (this.response === Toolkit.symbols.close) { this.raw.res.end(); // End the response in case it wasn't already closed } this._finalize(); } _finalize() { this._eventContext.request = null; // Disable req events if (this.response._close) { if (this.response.statusCode === 500 && this.response._error) { const tags = this.response._error.isDeveloperError ? ['internal', 'implementation', 'error'] : ['internal', 'error']; this._log(tags, this.response._error, 'error'); } this.response._close(); } this.info.completed = Date.now(); this._core.events.emit('response', this); if (this._route._extensions.onPostResponse.nodes) { this._invoke(this._route._extensions.onPostResponse, { ignoreResponse: true }); } } _setResponse(response) { if (this.response && !this.response.isBoom && this.response !== response && this.response.source !== response.source) { this.response._close?.(); } if (this.info.completed) { response._close?.(); return; } this.response = response; } _setState(name, value, options) { const state = { name, value }; if (options) { Hoek.assert(!options.autoValue, 'Cannot set autoValue directly in a response'); state.options = Hoek.clone(options); } this._states[name] = state; } _clearState(name, options = {}) { const state = { name }; state.options = Hoek.clone(options); state.options.ttl = 0; this._states[name] = state; } _tap() { if (!this._events) { return null; } if (this._events.hasListeners('peek') || this._events.hasListeners('finish')) { return new this._core.Response.Peek(this._events); } return null; } log(tags, data) { return this._log(tags, data, 'app'); } _log(tags, data, channel = 'internal') { if (!this._core.events.hasListeners('request') && !this.route.settings.log.collect) { return; } if (!Array.isArray(tags)) { tags = [tags]; } const timestamp = Date.now(); const field = data instanceof Error ? 'error' : 'data'; let event = [this, { request: this.info.id, timestamp, tags, [field]: data, channel }]; if (typeof data === 'function') { event = () => [this, { request: this.info.id, timestamp, tags, data: data(), channel }]; } if (this.route.settings.log.collect) { if (typeof data === 'function') { event = event(); } this.logs.push(event[1]); } this._core.events.emit({ name: 'request', channel, tags }, event); } generateResponse(source, options) { return new this._core.Response(source, this, options); } }; internals.Request.reserved = internals.reserved; internals.Request.symbols = { authPayload: Symbol('auth.payload') }; internals.Info = class { constructor(request) { this._request = request; const req = request.raw.req; const host = (req.headers.host || req.headers[':authority'] || '').trim(); const received = Date.now(); this.received = received; this.referrer = req.headers.referrer || req.headers.referer || ''; this.host = host; this.hostname = /^(.*?)(?::\d+)?$/.exec(host)[1]; this.id = `${received}:${request._core.info.id}:${request._core._counter()}`; this._remoteAddress = null; this._remotePort = null; // Assigned later this.acceptEncoding = null; this.cors = null; this.responded = 0; this.completed = 0; if (request._core.settings.info.remote) { this.remoteAddress; this.remotePort; } } get remoteAddress() { if (!this._remoteAddress) { const ipv6Prefix = '::ffff:'; const socketAddress = this._request.raw.req.socket.remoteAddress; if (socketAddress && socketAddress.startsWith(ipv6Prefix) && socketAddress.includes('.', ipv6Prefix.length)) { // Normalize IPv4-mapped IPv6 address, e.g. ::ffff:127.0.0.1 -> 127.0.0.1 this._remoteAddress = socketAddress.slice(ipv6Prefix.length); } else { this._remoteAddress = socketAddress; } } return this._remoteAddress; } get remotePort() { if (this._remotePort === null) { this._remotePort = this._request.raw.req.socket.remotePort || ''; } return this._remotePort; } toJSON() { return { acceptEncoding: this.acceptEncoding, completed: this.completed, cors: this.cors, host: this.host, hostname: this.hostname, id: this.id, received: this.received, referrer: this.referrer, remoteAddress: this.remoteAddress, remotePort: this.remotePort, responded: this.responded }; } }; internals.closed = function (request) { request._closed = true; }; internals.event = function ({ request }, event, err) { if (!request) { return; } request._isPayloadPending = false; if (event === 'close' && request.raw.res.writableEnded) { return; } if (event === 'end') { return; } request._log(err ? ['request', 'error'] : ['request', 'error', event], err); if (event === 'error') { return; } request._eventContext.request = null; if (event === 'abort') { // Calling _reply() means that the abort is applied immediately, unless the response has already // called _reply(), in which case this call is ignored and the transmit logic is responsible for // handling the abort. request._reply(new Boom.Boom('Request aborted', { statusCode: request.route.settings.response.disconnectStatusCode, data: request.response })); if (request._events) { request._events.emit('disconnect'); } } }; internals.timeoutReply = function (request, timeout) { const elapsed = Date.now() - request.info.received; request._log(['request', 'server', 'timeout', 'error'], { timeout, elapsed }); request._reply(Boom.serverUnavailable()); }; internals.skip = function (response) { return response.isBoom || response._takeover || typeof response === 'symbol'; }; ================================================ FILE: lib/response.js ================================================ 'use strict'; const Stream = require('stream'); const Boom = require('@hapi/boom'); const Bounce = require('@hapi/bounce'); const Hoek = require('@hapi/hoek'); const Podium = require('@hapi/podium'); const Streams = require('./streams'); const internals = { events: Podium.validate(['finish', { name: 'peek', spread: true }]), hopByHop: { connection: true, 'keep-alive': true, 'proxy-authenticate': true, 'proxy-authorization': true, 'te': true, 'trailer': true, 'transfer-encoding': true, 'upgrade': true }, reserved: ['app', 'headers', 'plugins', 'request', 'source', 'statusCode', 'variety', 'settings', 'events', 'code', 'message', 'header', 'vary', 'etag', 'type', 'contentType', 'bytes', 'location', 'created', 'compressed', 'replacer', 'space', 'suffix', 'escape', 'passThrough', 'redirect', 'temporary', 'permanent', 'rewritable', 'encoding', 'charset', 'ttl', 'state', 'unstate', 'takeover'] }; exports = module.exports = internals.Response = class { constructor(source, request, options = {}) { this.app = {}; this.headers = {}; // Incomplete as some headers are stored in flags this.plugins = {}; this.request = request; this.source = null; this.statusCode = null; this.variety = null; this.settings = { charset: 'utf-8', // '-' required by IANA compressed: null, encoding: 'utf8', message: null, passThrough: true, stringify: null, // JSON.stringify options ttl: null, varyEtag: false }; this._events = null; this._payload = null; // Readable stream this._error = options.error ?? null; // The boom object when created from an error (used for logging) this._contentType = null; // Used if no explicit content-type is set and type is known this._takeover = false; this._statusCode = false; // true when code() called this._state = this._error ? 'prepare' : 'init'; // One of 'init', 'prepare', 'marshall', 'close' this._processors = { marshal: options.marshal, prepare: options.prepare, close: options.close }; this._setSource(source, options.variety); } static wrap(result, request) { if (result instanceof request._core.Response || typeof result === 'symbol') { return result; } if (result instanceof Error) { return Boom.boomify(result); } return new request._core.Response(result, request); } _setSource(source, variety) { // Method must not set any headers or other properties as source can change later this.variety = variety ?? 'plain'; if (source === null || source === undefined) { source = null; } else if (Buffer.isBuffer(source)) { this.variety = 'buffer'; this._contentType = 'application/octet-stream'; } else if (Streams.isStream(source)) { this.variety = 'stream'; this._contentType = 'application/octet-stream'; } this.source = source; if (this.variety === 'plain' && this.source !== null) { this._contentType = typeof this.source === 'string' ? 'text/html' : 'application/json'; } } get events() { if (!this._events) { this._events = new Podium.Podium(internals.events); } return this._events; } code(statusCode) { Hoek.assert(Number.isSafeInteger(statusCode), 'Status code must be an integer'); this.statusCode = statusCode; this._statusCode = true; return this; } message(httpMessage) { this.settings.message = httpMessage; return this; } header(key, value, options) { key = key.toLowerCase(); if (key === 'vary') { return this.vary(value); } return this._header(key, value, options); } _header(key, value, options = {}) { const append = options.append ?? false; const separator = options.separator || ','; const override = options.override !== false; const duplicate = options.duplicate !== false; if (!append && override || !this.headers[key]) { this.headers[key] = value; } else if (override) { if (key === 'set-cookie') { this.headers[key] = [].concat(this.headers[key], value); } else { const existing = this.headers[key]; if (!duplicate) { const values = existing.split(separator); for (const v of values) { if (v === value) { return this; } } } this.headers[key] = existing + separator + value; } } return this; } vary(value) { if (value === '*') { this.headers.vary = '*'; } else if (!this.headers.vary) { this.headers.vary = value; } else if (this.headers.vary !== '*') { this._header('vary', value, { append: true, duplicate: false }); } return this; } etag(tag, options) { const entity = this.request._core.Response.entity(tag, options); this._header('etag', entity.etag); this.settings.varyEtag = entity.vary; return this; } static entity(tag, options = {}) { Hoek.assert(tag !== '*', 'ETag cannot be *'); return { etag: (options.weak ? 'W/' : '') + '"' + tag + '"', vary: options.vary !== false && !options.weak, // vary defaults to true modified: options.modified }; } static unmodified(request, entity) { if (request.method !== 'get' && request.method !== 'head') { return false; } // Strong verifier if (entity.etag && request.headers['if-none-match']) { const ifNoneMatch = request.headers['if-none-match'].split(/\s*,\s*/); for (const etag of ifNoneMatch) { // Compare tags (https://tools.ietf.org/html/rfc7232#section-2.3.2) if (etag === entity.etag) { // Strong comparison return true; } if (!entity.vary) { continue; } if (etag === `W/${entity.etag}`) { // Weak comparison return etag; } const etagBase = entity.etag.slice(0, -1); const encoders = request._core.compression.encodings; for (const encoder of encoders) { if (etag === etagBase + `-${encoder}"`) { return true; } } } return false; } // Weak verifier if (!entity.modified) { return false; } const ifModifiedSinceHeader = request.headers['if-modified-since']; if (!ifModifiedSinceHeader) { return false; } const ifModifiedSince = internals.parseDate(ifModifiedSinceHeader); if (!ifModifiedSince) { return false; } const lastModified = internals.parseDate(entity.modified); if (!lastModified) { return false; } return ifModifiedSince >= lastModified; } type(type) { this._header('content-type', type); return this; } get contentType() { let type = this.headers['content-type']; if (type) { type = type.trim(); if (this.settings.charset && type.match(/^(?:text\/)|(?:application\/(?:json)|(?:javascript))/) && !type.match(/; *charset=/)) { const semi = type[type.length - 1] === ';'; return type + (semi ? ' ' : '; ') + 'charset=' + this.settings.charset; } return type; } if (this._contentType) { const charset = this.settings.charset && this._contentType !== 'application/octet-stream' ? '; charset=' + this.settings.charset : ''; return this._contentType + charset; } return null; } bytes(bytes) { this._header('content-length', bytes); return this; } location(uri) { this._header('location', uri); return this; } created(location) { Hoek.assert(this.request.method === 'post' || this.request.method === 'put' || this.request.method === 'patch', 'Cannot return 201 status codes for ' + this.request.method.toUpperCase()); this.statusCode = 201; this.location(location); return this; } compressed(encoding) { Hoek.assert(encoding && typeof encoding === 'string', 'Invalid content-encoding'); this.settings.compressed = encoding; return this; } replacer(method) { this.settings.stringify = this.settings.stringify ?? {}; this.settings.stringify.replacer = method; return this; } spaces(count) { this.settings.stringify = this.settings.stringify ?? {}; this.settings.stringify.space = count; return this; } suffix(suffix) { this.settings.stringify = this.settings.stringify ?? {}; this.settings.stringify.suffix = suffix; return this; } escape(escape) { this.settings.stringify = this.settings.stringify ?? {}; this.settings.stringify.escape = escape; return this; } passThrough(enabled) { this.settings.passThrough = enabled !== false; // Defaults to true return this; } redirect(location) { this.statusCode = 302; this.location(location); return this; } temporary(isTemporary) { Hoek.assert(this.headers.location, 'Cannot set redirection mode without first setting a location'); this._setTemporary(isTemporary !== false); // Defaults to true return this; } permanent(isPermanent) { Hoek.assert(this.headers.location, 'Cannot set redirection mode without first setting a location'); this._setTemporary(isPermanent === false); // Defaults to true return this; } rewritable(isRewritable) { Hoek.assert(this.headers.location, 'Cannot set redirection mode without first setting a location'); this._setRewritable(isRewritable !== false); // Defaults to true return this; } _isTemporary() { return this.statusCode === 302 || this.statusCode === 307; } _isRewritable() { return this.statusCode === 301 || this.statusCode === 302; } _setTemporary(isTemporary) { if (isTemporary) { if (this._isRewritable()) { this.statusCode = 302; } else { this.statusCode = 307; } } else { if (this._isRewritable()) { this.statusCode = 301; } else { this.statusCode = 308; } } } _setRewritable(isRewritable) { if (isRewritable) { if (this._isTemporary()) { this.statusCode = 302; } else { this.statusCode = 301; } } else { if (this._isTemporary()) { this.statusCode = 307; } else { this.statusCode = 308; } } } encoding(encoding) { this.settings.encoding = encoding; return this; } charset(charset) { this.settings.charset = charset ?? null; return this; } ttl(ttl) { this.settings.ttl = ttl; return this; } state(name, value, options) { this.request._setState(name, value, options); return this; } unstate(name, options) { this.request._clearState(name, options); return this; } takeover() { this._takeover = true; return this; } _prepare() { Hoek.assert(this._state === 'init'); this._state = 'prepare'; this._passThrough(); if (!this._processors.prepare) { return this; } try { return this._processors.prepare(this); } catch (err) { throw Boom.boomify(err); } } _passThrough() { if (this.variety === 'stream' && this.settings.passThrough) { if (this.source.statusCode && !this.statusCode) { this.statusCode = this.source.statusCode; // Stream is an HTTP response } if (this.source.headers) { let headerKeys = Object.keys(this.source.headers); if (headerKeys.length) { const localHeaders = this.headers; this.headers = {}; const connection = this.source.headers.connection; const byHop = {}; if (connection) { connection.split(/\s*,\s*/).forEach((header) => { byHop[header] = true; }); } for (const key of headerKeys) { const lower = key.toLowerCase(); if (!internals.hopByHop[lower] && !byHop[lower]) { this.header(lower, Hoek.clone(this.source.headers[key])); // Clone arrays } } headerKeys = Object.keys(localHeaders); for (const key of headerKeys) { this.header(key, localHeaders[key], { append: key === 'set-cookie' }); } } } } this.statusCode = this.statusCode ?? 200; } async _marshal() { Hoek.assert(this._state === 'prepare'); this._state = 'marshall'; // Processor marshal let source = this.source; if (this._processors.marshal) { try { source = await this._processors.marshal(this); } catch (err) { throw Boom.boomify(err); } } // Stream source if (Streams.isStream(source)) { this._payload = source; return; } // Plain source (non string or null) const jsonify = this.variety === 'plain' && source !== null && typeof source !== 'string'; if (!jsonify && this.settings.stringify) { throw Boom.badImplementation('Cannot set formatting options on non object response'); } let payload = source; if (jsonify) { const options = this.settings.stringify ?? {}; const space = options.space ?? this.request.route.settings.json.space; const replacer = options.replacer ?? this.request.route.settings.json.replacer; const suffix = options.suffix ?? this.request.route.settings.json.suffix ?? ''; const escape = this.request.route.settings.json.escape; try { if (replacer || space) { payload = JSON.stringify(payload, replacer, space); } else { payload = JSON.stringify(payload); } } catch (err) { throw Boom.boomify(err); } if (suffix) { payload = payload + suffix; } if (escape) { payload = Hoek.escapeJson(payload); } } this._payload = new internals.Response.Payload(payload, this.settings); } _tap() { if (!this._events) { return null; } if (this._events.hasListeners('peek') || this._events.hasListeners('finish')) { return new internals.Response.Peek(this._events); } return null; } _close() { if (this._state === 'close') { return; } this._state = 'close'; if (this._processors.close) { try { this._processors.close(this); } catch (err) { Bounce.rethrow(err, 'system'); this.request._log(['response', 'cleanup', 'error'], err); } } const stream = this._payload || this.source; if (Streams.isStream(stream)) { internals.Response.drain(stream); } } _isPayloadSupported() { return this.request.method !== 'head' && this.statusCode !== 304 && this.statusCode !== 204; } static drain(stream) { stream.destroy(); } }; internals.Response.reserved = internals.reserved; internals.parseDate = function (string) { try { return Date.parse(string); } catch (errIgnore) { } }; internals.Response.Payload = class extends Stream.Readable { constructor(payload, options) { super(); this._data = payload; this._encoding = options.encoding; } _read(size) { if (this._data) { this.push(this._data, this._encoding); } this.push(null); } size() { if (!this._data) { return 0; } return Buffer.isBuffer(this._data) ? this._data.length : Buffer.byteLength(this._data, this._encoding); } writeToStream(stream) { if (this._data) { stream.write(this._data, this._encoding); } stream.end(); } }; internals.Response.Peek = class extends Stream.Transform { constructor(podium) { super(); this._podium = podium; this.on('finish', () => podium.emit('finish')); } _transform(chunk, encoding, callback) { this._podium.emit('peek', [chunk, encoding]); this.push(chunk, encoding); callback(); } }; ================================================ FILE: lib/route.js ================================================ 'use strict'; const Assert = require('assert'); const Bounce = require('@hapi/bounce'); const Catbox = require('@hapi/catbox'); const Hoek = require('@hapi/hoek'); const Subtext = require('@hapi/subtext'); const Validate = require('@hapi/validate'); const Auth = require('./auth'); const Config = require('./config'); const Cors = require('./cors'); const Ext = require('./ext'); const Handler = require('./handler'); const Headers = require('./headers'); const Security = require('./security'); const Streams = require('./streams'); const Validation = require('./validation'); const internals = {}; exports = module.exports = internals.Route = class { constructor(route, server, options = {}) { const core = server._core; const realm = server.realm; // Routing information Config.apply('route', route, route.method, route.path); const method = route.method.toLowerCase(); Hoek.assert(method !== 'head', 'Cannot set HEAD route:', route.path); const path = realm.modifiers.route.prefix ? realm.modifiers.route.prefix + (route.path !== '/' ? route.path : '') : route.path; Hoek.assert(path === '/' || path[path.length - 1] !== '/' || !core.settings.router.stripTrailingSlash, 'Path cannot end with a trailing slash when configured to strip:', route.method, route.path); const vhost = realm.modifiers.route.vhost ?? route.vhost; // Set identifying members (assert) this.method = method; this.path = path; // Prepare configuration let config = route.options ?? route.config ?? {}; if (typeof config === 'function') { config = config.call(realm.settings.bind, server); } config = Config.enable(config); // Shallow clone // Verify route level config (as opposed to the merged settings) this._assert(method !== 'get' || !config.payload, 'Cannot set payload settings on HEAD or GET request'); this._assert(method !== 'get' || !config.validate?.payload, 'Cannot validate HEAD or GET request payload'); // Rules this._assert(!route.rules || !config.rules, 'Route rules can only appear once'); // XOR const rules = route.rules ?? config.rules; const rulesConfig = internals.rules(rules, { method, path, vhost }, server); delete config.rules; // Handler this._assert(route.handler || config.handler, 'Missing or undefined handler'); this._assert(!!route.handler ^ !!config.handler, 'Handler must only appear once'); // XOR const handler = Config.apply('handler', route.handler ?? config.handler); delete config.handler; const handlerDefaults = Handler.defaults(method, handler, core); // Apply settings in order: server <- handler <- realm <- route const settings = internals.config([core.settings.routes, handlerDefaults, realm.settings, rulesConfig, config]); this.settings = Config.apply('routeConfig', settings, method, path); // Route members this._core = core; this.realm = realm; this.settings.vhost = vhost; this.settings.plugins = this.settings.plugins ?? {}; // Route-specific plugins settings, namespaced using plugin name this.settings.app = this.settings.app ?? {}; // Route-specific application settings // Path parsing this._special = !!options.special; this._analysis = this._core.router.analyze(this.path); this.params = this._analysis.params; this.fingerprint = this._analysis.fingerprint; this.public = { method: this.method, path: this.path, vhost, realm, settings: this.settings, fingerprint: this.fingerprint, auth: { access: (request) => Auth.testAccess(request, this.public) } }; // Validation this._setupValidation(); // Payload parsing if (this.method === 'get') { this.settings.payload = null; } else { this.settings.payload.decoders = this._core.compression.decoders; // Reference the shared object to keep up to date } this._assert(!this.settings.validate.payload || this.settings.payload.parse, 'Route payload must be set to \'parse\' when payload validation enabled'); this._assert(!this.settings.validate.state || this.settings.state.parse, 'Route state must be set to \'parse\' when state validation enabled'); // Authentication configuration this.settings.auth = this._special ? false : this._core.auth._setupRoute(this.settings.auth, path); // Cache if (this.method === 'get' && typeof this.settings.cache === 'object' && (this.settings.cache.expiresIn || this.settings.cache.expiresAt)) { this.settings.cache._statuses = new Set(this.settings.cache.statuses); this._cache = new Catbox.Policy({ expiresIn: this.settings.cache.expiresIn, expiresAt: this.settings.cache.expiresAt }); } // CORS this.settings.cors = Cors.route(this.settings.cors); // Security this.settings.security = Security.route(this.settings.security); // Handler this.settings.handler = Handler.configure(handler, this); this._prerequisites = Handler.prerequisitesConfig(this.settings.pre); // Route lifecycle this._extensions = { onPreResponse: Ext.combine(this, 'onPreResponse'), onPostResponse: Ext.combine(this, 'onPostResponse') }; if (this._special) { this._cycle = [internals.drain, Handler.execute]; this.rebuild(); return; } this._extensions.onPreAuth = Ext.combine(this, 'onPreAuth'); this._extensions.onCredentials = Ext.combine(this, 'onCredentials'); this._extensions.onPostAuth = Ext.combine(this, 'onPostAuth'); this._extensions.onPreHandler = Ext.combine(this, 'onPreHandler'); this._extensions.onPostHandler = Ext.combine(this, 'onPostHandler'); this.rebuild(); } _setupValidation() { const validation = this.settings.validate; if (this.method === 'get') { validation.payload = null; } this._assert(!validation.params || this.params.length, 'Cannot set path parameters validations without path parameters'); for (const type of ['headers', 'params', 'query', 'payload', 'state']) { validation[type] = Validation.compile(validation[type], this.settings.validate.validator, this.realm, this._core); } if (this.settings.response.schema !== undefined || this.settings.response.status) { this.settings.response._validate = true; const rule = this.settings.response.schema; this.settings.response.status = this.settings.response.status ?? {}; const statuses = Object.keys(this.settings.response.status); if (rule === true && !statuses.length) { this.settings.response._validate = false; } else { this.settings.response.schema = Validation.compile(rule, this.settings.validate.validator, this.realm, this._core); for (const code of statuses) { this.settings.response.status[code] = Validation.compile(this.settings.response.status[code], this.settings.validate.validator, this.realm, this._core); } } } } rebuild(event) { if (event) { this._extensions[event.type].add(event); } if (this._special) { this._postCycle = this._extensions.onPreResponse.nodes ? [this._extensions.onPreResponse] : []; this._buildMarshalCycle(); return; } // Build lifecycle array this._cycle = []; // 'onRequest' if (this.settings.state.parse) { this._cycle.push(internals.state); } if (this._extensions.onPreAuth.nodes) { this._cycle.push(this._extensions.onPreAuth); } if (this._core.auth._enabled(this, 'authenticate')) { this._cycle.push(Auth.authenticate); } if (this.method !== 'get') { this._cycle.push(internals.payload); if (this._core.auth._enabled(this, 'payload')) { this._cycle.push(Auth.payload); } } if (this._core.auth._enabled(this, 'authenticate') && this._extensions.onCredentials.nodes) { this._cycle.push(this._extensions.onCredentials); } if (this._core.auth._enabled(this, 'access')) { this._cycle.push(Auth.access); } if (this._extensions.onPostAuth.nodes) { this._cycle.push(this._extensions.onPostAuth); } if (this.settings.validate.headers) { this._cycle.push(Validation.headers); } if (this.settings.validate.params) { this._cycle.push(Validation.params); } if (this.settings.validate.query) { this._cycle.push(Validation.query); } if (this.settings.validate.payload) { this._cycle.push(Validation.payload); } if (this.settings.validate.state) { this._cycle.push(Validation.state); } if (this._extensions.onPreHandler.nodes) { this._cycle.push(this._extensions.onPreHandler); } this._cycle.push(Handler.execute); if (this._extensions.onPostHandler.nodes) { this._cycle.push(this._extensions.onPostHandler); } this._postCycle = []; if (this.settings.response._validate && this.settings.response.sample !== 0) { this._postCycle.push(Validation.response); } if (this._extensions.onPreResponse.nodes) { this._postCycle.push(this._extensions.onPreResponse); } this._buildMarshalCycle(); // onPostResponse } _buildMarshalCycle() { this._marshalCycle = [Headers.type]; if (this.settings.cors) { this._marshalCycle.push(Cors.headers); } if (this.settings.security) { this._marshalCycle.push(Security.headers); } this._marshalCycle.push(Headers.entity); if (this.method === 'get' || this.method === '*') { this._marshalCycle.push(Headers.unmodified); } this._marshalCycle.push(Headers.cache); this._marshalCycle.push(Headers.state); this._marshalCycle.push(Headers.content); if (this._core.auth._enabled(this, 'response')) { this._marshalCycle.push(Auth.response); // Must be last in case requires access to headers } } _assert(condition, message) { if (condition) { return; } if (this.method[0] !== '_') { message = `${message}: ${this.method.toUpperCase()} ${this.path}`; } throw new Assert.AssertionError({ message, actual: false, expected: true, operator: '==', stackStartFunction: this._assert }); } }; internals.state = async function (request) { request.state = {}; const req = request.raw.req; const cookies = req.headers.cookie; if (!cookies) { return; } try { var result = await request._core.states.parse(cookies); } catch (err) { Bounce.rethrow(err, 'system'); var parseError = err; } const { states, failed = [] } = result ?? parseError; request.state = states ?? {}; // Clear cookies for (const item of failed) { if (item.settings.clearInvalid) { request._clearState(item.name); } } if (!parseError) { return; } parseError.header = cookies; return request._core.toolkit.failAction(request, request.route.settings.state.failAction, parseError, { tags: ['state', 'error'] }); }; internals.payload = async function (request) { if (request.method === 'get' || request.method === 'head') { // When route.method is '*' return; } if (request.payload !== undefined) { return internals.drain(request); } if (request._expectContinue) { request._expectContinue = false; request.raw.res.writeContinue(); } try { const { payload, mime } = await Subtext.parse(request.raw.req, request._tap(), request.route.settings.payload); request._isPayloadPending = !!payload?._readableState; request.mime = mime; request.payload = payload; } catch (err) { Bounce.rethrow(err, 'system'); await internals.drain(request); request.mime = err.mime; request.payload = null; return request._core.toolkit.failAction(request, request.route.settings.payload.failAction, err, { tags: ['payload', 'error'] }); } }; internals.drain = async function (request) { // Flush out any pending request payload not consumed due to errors if (request._expectContinue) { request._isPayloadPending = false; // If we don't continue, client should not send a payload request._expectContinue = false; } if (request._isPayloadPending) { await Streams.drain(request.raw.req); request._isPayloadPending = false; } }; internals.config = function (chain) { if (!chain.length) { return {}; } let config = chain[0]; for (const item of chain) { config = Hoek.applyToDefaults(config, item, { shallow: ['bind', 'validate.headers', 'validate.payload', 'validate.params', 'validate.query', 'validate.state'] }); } return config; }; internals.rules = function (rules, info, server) { const configs = []; let realm = server.realm; while (realm) { if (realm._rules) { const source = !realm._rules.settings.validate ? rules : Validate.attempt(rules, realm._rules.settings.validate.schema, realm._rules.settings.validate.options); const config = realm._rules.processor(source, info); if (config) { configs.unshift(config); } } realm = realm.parent; } return internals.config(configs); }; ================================================ FILE: lib/security.js ================================================ 'use strict'; const internals = {}; exports.route = function (settings) { if (!settings) { return null; } const security = settings; if (security.hsts) { if (security.hsts === true) { security._hsts = 'max-age=15768000'; } else if (typeof security.hsts === 'number') { security._hsts = 'max-age=' + security.hsts; } else { security._hsts = 'max-age=' + (security.hsts.maxAge ?? 15768000); if (security.hsts.includeSubdomains || security.hsts.includeSubDomains) { security._hsts = security._hsts + '; includeSubDomains'; } if (security.hsts.preload) { security._hsts = security._hsts + '; preload'; } } } if (security.xframe) { if (security.xframe === true) { security._xframe = 'DENY'; } else if (typeof security.xframe === 'string') { security._xframe = security.xframe.toUpperCase(); } else if (security.xframe.rule === 'allow-from') { if (!security.xframe.source) { security._xframe = 'SAMEORIGIN'; } else { security._xframe = 'ALLOW-FROM ' + security.xframe.source; } } else { security._xframe = security.xframe.rule.toUpperCase(); } } return security; }; exports.headers = function (response) { const security = response.request.route.settings.security; if (security._hsts) { response._header('strict-transport-security', security._hsts, { override: false }); } if (security._xframe) { response._header('x-frame-options', security._xframe, { override: false }); } if (security.xss === 'enabled') { response._header('x-xss-protection', '1; mode=block', { override: false }); } else if (security.xss === 'disabled') { response._header('x-xss-protection', '0', { override: false }); } if (security.noOpen) { response._header('x-download-options', 'noopen', { override: false }); } if (security.noSniff) { response._header('x-content-type-options', 'nosniff', { override: false }); } if (security.referrer !== false) { response._header('referrer-policy', security.referrer, { override: false }); } }; ================================================ FILE: lib/server.js ================================================ 'use strict'; const Hoek = require('@hapi/hoek'); const Shot = require('@hapi/shot'); const Teamwork = require('@hapi/teamwork'); const Config = require('./config'); const Core = require('./core'); const Cors = require('./cors'); const Ext = require('./ext'); const Package = require('../package.json'); const Route = require('./route'); const Toolkit = require('./toolkit'); const Validation = require('./validation'); const internals = {}; exports = module.exports = function (options) { const core = new Core(options); return new internals.Server(core); }; internals.Server = class { constructor(core, name, parent) { this._core = core; // Public interface this.app = core.app; this.auth = core.auth.public(this); this.decorations = core.decorations.public; this.cache = internals.cache(this); this.events = core.events; this.info = core.info; this.listener = core.listener; this.load = core.heavy.load; this.methods = core.methods.methods; this.mime = core.mime; this.plugins = core.plugins; this.registrations = core.registrations; this.settings = core.settings; this.states = core.states; this.type = core.type; this.version = Package.version; this.realm = { _extensions: { onPreAuth: new Ext('onPreAuth', core), onCredentials: new Ext('onCredentials', core), onPostAuth: new Ext('onPostAuth', core), onPreHandler: new Ext('onPreHandler', core), onPostHandler: new Ext('onPostHandler', core), onPreResponse: new Ext('onPreResponse', core), onPostResponse: new Ext('onPostResponse', core) }, modifiers: { route: {} }, parent: parent ? parent.realm : null, plugin: name, pluginOptions: {}, plugins: {}, _rules: null, settings: { bind: undefined, files: { relativeTo: undefined } }, validator: null }; // Decorations for (const [property, method] of core.decorations.server.entries()) { this[property] = method; } core.registerServer(this); } _clone(name) { return new internals.Server(this._core, name, this); } bind(context) { Hoek.assert(typeof context === 'object', 'bind must be an object'); this.realm.settings.bind = context; } control(server) { Hoek.assert(server instanceof internals.Server, 'Can only control Server objects'); this._core.controlled = this._core.controlled ?? []; this._core.controlled.push(server); } decoder(encoding, decoder) { return this._core.compression.addDecoder(encoding, decoder); } decorate(type, property, method, options = {}) { Hoek.assert(this._core.decorations.public[type], 'Unknown decoration type:', type); Hoek.assert(property, 'Missing decoration property name'); Hoek.assert(typeof property === 'string' || typeof property === 'symbol', 'Decoration property must be a string or a symbol'); const propertyName = property.toString(); Hoek.assert(propertyName[0] !== '_', 'Property name cannot begin with an underscore:', propertyName); const existing = this._core.decorations[type].get(property); if (options.extend) { Hoek.assert(type !== 'handler', 'Cannot extend handler decoration:', propertyName); Hoek.assert(existing, `Cannot extend missing ${type} decoration: ${propertyName}`); Hoek.assert(typeof method === 'function', `Extended ${type} decoration method must be a function: ${propertyName}`); method = method(existing); } else { Hoek.assert(existing === undefined, `${type[0].toUpperCase() + type.slice(1)} decoration already defined: ${propertyName}`); } if (type === 'handler') { // Handler Hoek.assert(typeof method === 'function', 'Handler must be a function:', propertyName); Hoek.assert(!method.defaults || typeof method.defaults === 'object' || typeof method.defaults === 'function', 'Handler defaults property must be an object or function'); Hoek.assert(!options.extend, 'Cannot extend handler decoration:', propertyName); } else if (type === 'request') { // Request Hoek.assert(!this._core.Request.reserved.includes(property), 'Cannot override the built-in request interface decoration:', propertyName); if (options.apply) { this._core.decorations.requestApply = this._core.decorations.requestApply ?? new Map(); this._core.decorations.requestApply.set(property, method); } else { this._core.Request.prototype[property] = method; } } else if (type === 'response') { // Response Hoek.assert(!this._core.Response.reserved.includes(property), 'Cannot override the built-in response interface decoration:', propertyName); this._core.Response.prototype[property] = method; } else if (type === 'toolkit') { // Toolkit Hoek.assert(!Toolkit.reserved.includes(property), 'Cannot override the built-in toolkit decoration:', propertyName); this._core.toolkit.decorate(property, method); } else { // Server if (typeof property === 'string') { Hoek.assert(!Object.getOwnPropertyNames(internals.Server.prototype).includes(property), 'Cannot override the built-in server interface method:', propertyName); } else { Hoek.assert(!Object.getOwnPropertySymbols(internals.Server.prototype).includes(property), 'Cannot override the built-in server interface method:', propertyName); } this._core.instances.forEach((server) => { server[property] = method; }); } this._core.decorations[type].set(property, method); this._core.decorations.public[type].push(property); } dependency(dependencies, after) { Hoek.assert(this.realm.plugin, 'Cannot call dependency() outside of a plugin'); Hoek.assert(!after || typeof after === 'function', 'Invalid after method'); // Normalize to { plugin: version } if (typeof dependencies === 'string') { dependencies = { [dependencies]: '*' }; } else if (Array.isArray(dependencies)) { const map = {}; for (const dependency of dependencies) { map[dependency] = '*'; } dependencies = map; } this._core.dependencies.push({ plugin: this.realm.plugin, deps: dependencies }); if (after) { this.ext('onPreStart', after, { after: Object.keys(dependencies) }); } } encoder(encoding, encoder) { return this._core.compression.addEncoder(encoding, encoder); } event(event) { this._core.events.registerEvent(event); } expose(key, value, options = {}) { Hoek.assert(this.realm.plugin, 'Cannot call expose() outside of a plugin'); let plugin = this.realm.plugin; if (plugin[0] === '@' && options.scope !== true) { plugin = plugin.replace(/^@([^/]+)\//, ($0, $1) => { return !options.scope ? '' : `${$1}__`; }); } this._core.plugins[plugin] = this._core.plugins[plugin] ?? {}; if (typeof key === 'string') { this._core.plugins[plugin][key] = value; } else { Hoek.merge(this._core.plugins[plugin], key); } } ext(events, method, options) { // (event, method, options) -OR- (events) let promise; if (typeof events === 'string') { if (!method) { const team = new Teamwork.Team(); method = (request, h) => { team.attend(request); return h.continue; }; promise = team.work; } events = { type: events, method, options }; } events = Config.apply('exts', events); for (const event of events) { this._ext(event); } return promise; } _ext(event) { event = Object.assign({}, event); // Shallow cloned event.realm = this.realm; const type = event.type; if (!this._core.extensions.server[type]) { // Realm route extensions if (event.options.sandbox === 'plugin') { Hoek.assert(this.realm._extensions[type], 'Unknown event type', type); return this.realm._extensions[type].add(event); } // Connection route extensions Hoek.assert(this._core.extensions.route[type], 'Unknown event type', type); return this._core.extensions.route[type].add(event); } // Server extensions Hoek.assert(!event.options.sandbox, 'Cannot specify sandbox option for server extension'); Hoek.assert(type !== 'onPreStart' || this._core.phase === 'stopped', 'Cannot add onPreStart (after) extension after the server was initialized'); event.server = this; this._core.extensions.server[type].add(event); } async inject(options) { let settings = options; if (typeof settings === 'string') { settings = { url: settings }; } if (!settings.authority || settings.auth || settings.app || settings.plugins || settings.allowInternals !== undefined) { // Can be false settings = Object.assign({}, settings); // options can be reused (shallow cloned) delete settings.auth; delete settings.app; delete settings.plugins; delete settings.allowInternals; settings.authority = settings.authority ?? this._core.info.host + ':' + this._core.info.port; } Hoek.assert(!options.credentials, 'options.credentials no longer supported (use options.auth)'); if (options.auth) { Hoek.assert(typeof options.auth === 'object', 'options.auth must be an object'); Hoek.assert(options.auth.credentials, 'options.auth.credentials is missing'); Hoek.assert(options.auth.strategy, 'options.auth.strategy is missing'); } const needle = this._core._dispatch({ auth: options.auth, allowInternals: options.allowInternals, app: options.app, plugins: options.plugins, isInjected: true }); const res = await Shot.inject(needle, settings); const custom = res.raw.res[Config.symbol]; if (custom) { delete res.raw.res[Config.symbol]; res.request = custom.request; if (custom.error) { throw custom.error; } if (custom.result !== undefined) { res.result = custom.result; } } if (res.result === undefined) { res.result = res.payload; } return res; } log(tags, data) { return this._core.log(tags, data); } lookup(id) { Hoek.assert(id && typeof id === 'string', 'Invalid route id:', id); const record = this._core.router.ids.get(id); if (!record) { return null; } return record.route.public; } match(method, path, host) { Hoek.assert(method && typeof method === 'string', 'Invalid method:', method); Hoek.assert(path && typeof path === 'string' && path[0] === '/', 'Invalid path:', path); Hoek.assert(!host || typeof host === 'string', 'Invalid host:', host); const match = this._core.router.route(method.toLowerCase(), path, host); Hoek.assert(match !== this._core.router.specials.badRequest, 'Invalid path:', path); if (match === this._core.router.specials.notFound) { return null; } return match.route.public; } method(name, method, options = {}) { return this._core.methods.add(name, method, options, this.realm); } path(relativeTo) { Hoek.assert(relativeTo && typeof relativeTo === 'string', 'relativeTo must be a non-empty string'); this.realm.settings.files.relativeTo = relativeTo; } async register(plugins, options = {}) { if (this.realm.modifiers.route.prefix || this.realm.modifiers.route.vhost) { options = Hoek.clone(options); options.routes = options.routes ?? {}; options.routes.prefix = (this.realm.modifiers.route.prefix ?? '') + (options.routes.prefix ?? '') || undefined; options.routes.vhost = this.realm.modifiers.route.vhost ?? options.routes.vhost; } options = Config.apply('register', options); ++this._core.registring; try { const items = [].concat(plugins); for (let item of items) { /* { register, ...attributes } { plugin: { register, ...attributes }, options, once, routes } { plugin: { plugin: { register, ...attributes } }, options, once, routes } // Required module */ if (!item.plugin) { item = { plugin: item }; } else if (!item.plugin.register) { item = { options: item.options, once: item.once, routes: item.routes, plugin: item.plugin.plugin }; } else if (typeof item === 'function') { item = Object.assign({}, item); // Shallow cloned } item = Config.apply('plugin', item); const name = item.plugin.name ?? item.plugin.pkg.name; const clone = this._clone(name); clone.realm.modifiers.route.prefix = item.routes.prefix ?? options.routes.prefix; clone.realm.modifiers.route.vhost = item.routes.vhost ?? options.routes.vhost; clone.realm.pluginOptions = item.options ?? {}; // Validate requirements const requirements = item.plugin.requirements; Hoek.assert(!requirements.node || Config.versionMatch(process.version, requirements.node), 'Plugin', name, 'requires node version', requirements.node, 'but found', process.version); Hoek.assert(!requirements.hapi || Config.versionMatch(this.version, requirements.hapi), 'Plugin', name, 'requires hapi version', requirements.hapi, 'but found', this.version); // Protect against multiple registrations if (this._core.registrations[name]) { if (item.plugin.once || item.once || options.once) { continue; } Hoek.assert(item.plugin.multiple, 'Plugin', name, 'already registered'); } else { this._core.registrations[name] = { version: item.plugin.version ?? item.plugin.pkg.version, name, options: item.options }; } if (item.plugin.dependencies) { clone.dependency(item.plugin.dependencies); } // Register await item.plugin.register(clone, item.options ?? {}); } } finally { --this._core.registring; } return this; } route(options) { Hoek.assert(typeof options === 'object', 'Invalid route options'); options = [].concat(options); for (const config of options) { if (Array.isArray(config.method)) { for (const method of config.method) { const settings = Object.assign({}, config); // Shallow cloned settings.method = method; this._addRoute(settings, this); } } else { this._addRoute(config, this); } } } _addRoute(config, server) { const route = new Route(config, server); // Do no use config beyond this point, use route members const vhosts = [].concat(route.settings.vhost ?? '*'); for (const vhost of vhosts) { const record = this._core.router.add({ method: route.method, path: route.path, vhost, analysis: route._analysis, id: route.settings.id }, route); route.fingerprint = record.fingerprint; route.params = record.params; } this.events.emit('route', route.public); Cors.options(route.public, server); } rules(processor, options = {}) { Hoek.assert(!this.realm._rules, 'Server realm rules already defined'); const settings = Config.apply('rules', options); if (settings.validate) { const schema = settings.validate.schema; settings.validate.schema = Validation.compile(schema, null, this.realm, this._core); } this.realm._rules = { processor, settings }; } state(name, options) { this.states.add(name, options); } table(host) { return this._core.router.table(host); } validator(validator) { Hoek.assert(!this.realm.validator, 'Validator already set'); this.realm.validator = Validation.validator(validator); } start() { return this._core._start(); } initialize() { return this._core._initialize(); } stop(options) { return this._core._stop(options); } }; internals.cache = (plugin) => { const policy = function (options, _segment) { return this._core._cachePolicy(options, _segment, plugin.realm); }; policy.provision = async (opts) => { const clients = plugin._core._createCache(opts); // Start cache if (['initialized', 'starting', 'started'].includes(plugin._core.phase)) { await Promise.all(clients.map((client) => client.start())); } }; return policy; }; ================================================ FILE: lib/streams.js ================================================ 'use strict'; const Stream = require('stream'); const Boom = require('@hapi/boom'); const Teamwork = require('@hapi/teamwork'); const internals = { team: Symbol('team') }; exports.isStream = function (stream) { const isReadableStream = stream instanceof Stream.Readable; if (!isReadableStream && typeof stream?.pipe === 'function') { throw Boom.badImplementation('Cannot reply with a stream-like object that is not an instance of Stream.Readable'); } if (!isReadableStream) { return false; } if (stream.readableObjectMode) { throw Boom.badImplementation('Cannot reply with stream in object mode'); } return true; }; exports.drain = function (stream) { const team = new Teamwork.Team(); stream[internals.team] = team; stream.on('readable', internals.read); stream.on('error', internals.end); stream.on('end', internals.end); stream.on('close', internals.end); return team.work; }; internals.read = function () { while (this.read()) { } }; internals.end = function () { this.removeListener('readable', internals.read); this.removeListener('error', internals.end); this.removeListener('end', internals.end); this.removeListener('close', internals.end); this[internals.team].attend(); }; ================================================ FILE: lib/toolkit.js ================================================ 'use strict'; const Boom = require('@hapi/boom'); const Bounce = require('@hapi/bounce'); const Hoek = require('@hapi/hoek'); const internals = {}; exports.reserved = [ 'abandon', 'authenticated', 'close', 'context', 'continue', 'entity', 'redirect', 'realm', 'request', 'response', 'state', 'unauthenticated', 'unstate' ]; exports.symbols = { abandon: Symbol('abandon'), close: Symbol('close'), continue: Symbol('continue') }; exports.Manager = class { constructor() { this._toolkit = internals.toolkit(); } async execute(method, request, options) { const h = new this._toolkit(request, options); const bind = options.bind ?? null; try { let operation; if (bind) { operation = method.call(bind, request, h); } else if (options.args) { operation = method(request, h, ...options.args); } else { operation = method(request, h); } var response = await exports.timed(operation, options); } catch (err) { if (Bounce.isSystem(err)) { response = Boom.badImplementation(err); } else if (!Bounce.isError(err)) { response = Boom.badImplementation('Cannot throw non-error object', err); } else { response = Boom.boomify(err); } } // Process response if (options.ignoreResponse) { return response; } if (response === undefined) { response = Boom.badImplementation(`${method.name} method did not return a value, a promise, or throw an error`); } if (options.continue && response === exports.symbols.continue) { if (options.continue === 'undefined') { return; } // 'null' response = null; } if (options.auth && response instanceof internals.Auth) { return response; } if (typeof response !== 'symbol') { response = request._core.Response.wrap(response, request); if (!response.isBoom && response._state === 'init') { await response._prepare(); } } return response; } decorate(name, method) { this._toolkit.prototype[name] = method; } async failAction(request, failAction, err, options) { const retain = options.retain ? err : undefined; if (failAction === 'ignore') { return retain; } if (failAction === 'log') { request._log(options.tags, err); return retain; } if (failAction === 'error') { throw err; } return await this.execute(failAction, request, { realm: request.route.realm, args: [options.details ?? err] }); } }; exports.timed = async function (method, options) { if (!options.timeout) { return method; } const timer = new Promise((resolve, reject) => { const handler = () => { reject(Boom.internal(`${options.name} timed out`)); }; setTimeout(handler, options.timeout); }); return await Promise.race([timer, method]); }; /* const handler = function (request, h) { result / h.response(result) -> result // Not allowed before handler h.response(result).takeover() -> result (respond) h.continue -> null // Defaults to null only in handler and pre, not allowed in auth throw error / h.response(error) -> error (respond) // failAction override in pre -> badImplementation (respond) // Auth only (scheme.payload and scheme.response use the same interface as pre-handler extension methods) h.unauthenticated(error, data) -> error (respond) + data h.authenticated(data ) -> (continue) + data }; */ internals.toolkit = function () { const Toolkit = class { constructor(request, options) { this.context = options.bind; this.realm = options.realm; this.request = request; this._auth = options.auth; } response(result) { Hoek.assert(!result || typeof result !== 'object' || typeof result.then !== 'function', 'Cannot wrap a promise'); Hoek.assert(result instanceof Error === false, 'Cannot wrap an error'); Hoek.assert(typeof result !== 'symbol', 'Cannot wrap a symbol'); return this.request._core.Response.wrap(result, this.request); } redirect(location) { return this.response('').redirect(location); } entity(options) { Hoek.assert(options, 'Entity method missing required options'); Hoek.assert(options.etag || options.modified, 'Entity methods missing required options key'); this.request._entity = options; const entity = this.request._core.Response.entity(options.etag, options); if (this.request._core.Response.unmodified(this.request, entity)) { return this.response().code(304).takeover(); } } state(name, value, options) { this.request._setState(name, value, options); } unstate(name, options) { this.request._clearState(name, options); } authenticated(data) { Hoek.assert(this._auth, 'Method not supported outside of authentication'); Hoek.assert(data?.credentials, 'Authentication data missing credentials information'); return new internals.Auth(null, data); } unauthenticated(error, data) { Hoek.assert(this._auth, 'Method not supported outside of authentication'); Hoek.assert(!data || data.credentials, 'Authentication data missing credentials information'); return new internals.Auth(error, data); } }; Toolkit.prototype.abandon = exports.symbols.abandon; Toolkit.prototype.close = exports.symbols.close; Toolkit.prototype.continue = exports.symbols.continue; return Toolkit; }; internals.Auth = class { constructor(error, data) { this.isAuth = true; this.error = error; this.data = data; } }; ================================================ FILE: lib/transmit.js ================================================ 'use strict'; const Http = require('http'); const Ammo = require('@hapi/ammo'); const Boom = require('@hapi/boom'); const Bounce = require('@hapi/bounce'); const Hoek = require('@hapi/hoek'); const Teamwork = require('@hapi/teamwork'); const Config = require('./config'); const internals = {}; exports.send = async function (request) { const response = request.response; try { if (response.isBoom) { await internals.fail(request, response); return; } await internals.marshal(response); await internals.transmit(response); } catch (err) { Bounce.rethrow(err, 'system'); request._setResponse(err); return internals.fail(request, err); } }; internals.marshal = async function (response) { for (const func of response.request._route._marshalCycle) { await func(response); } }; internals.fail = async function (request, boom) { const response = internals.error(request, boom); request.response = response; // Not using request._setResponse() to avoid double log try { await internals.marshal(response); } catch (err) { Bounce.rethrow(err, 'system'); // Failed to marshal an error - replace with minimal representation of original error const minimal = { statusCode: response.statusCode, error: Http.STATUS_CODES[response.statusCode], message: boom.message }; response._payload = new request._core.Response.Payload(JSON.stringify(minimal), {}); } return internals.transmit(response); }; internals.error = function (request, boom) { const error = boom.output; const response = new request._core.Response(error.payload, request, { error: boom }); response.code(error.statusCode); response.headers = Hoek.clone(error.headers); // Prevent source from being modified return response; }; internals.transmit = function (response) { const request = response.request; const length = internals.length(response); // Pipes const encoding = request._core.compression.encoding(response, length); const ranger = encoding ? null : internals.range(response, length); const compressor = internals.encoding(response, encoding); // Connection: close const isInjection = request.isInjected; if (!(isInjection || request._core.started) || request._isPayloadPending && !request.raw.req._readableState.ended) { response._header('connection', 'close'); } // Write headers internals.writeHead(response); // Injection if (isInjection) { request.raw.res[Config.symbol] = { request }; if (response.variety === 'plain') { request.raw.res[Config.symbol].result = response._isPayloadSupported() ? response.source : null; } } // Finalize response stream const stream = internals.chain([response._payload, response._tap(), compressor, ranger]); return internals.pipe(request, stream); }; internals.length = function (response) { const request = response.request; const header = response.headers['content-length']; if (header === undefined) { return null; } let length = header; if (typeof length === 'string') { length = parseInt(header, 10); if (!isFinite(length)) { delete response.headers['content-length']; return null; } } // Empty response if (length === 0 && !response._statusCode && response.statusCode === 200 && request.route.settings.response.emptyStatusCode !== 200) { response.code(204); delete response.headers['content-length']; } return length; }; internals.range = function (response, length) { const request = response.request; if (!length || !request.route.settings.response.ranges || request.method !== 'get' || response.statusCode !== 200) { return null; } response._header('accept-ranges', 'bytes'); if (!request.headers.range) { return null; } // Check If-Range if (request.headers['if-range'] && request.headers['if-range'] !== response.headers.etag) { // Ignoring last-modified date (weak) return null; } // Parse header const ranges = Ammo.header(request.headers.range, length); if (!ranges) { const error = Boom.rangeNotSatisfiable(); error.output.headers['content-range'] = 'bytes */' + length; throw error; } // Prepare transform if (ranges.length !== 1) { // Ignore requests for multiple ranges return null; } const range = ranges[0]; response.code(206); response.bytes(range.to - range.from + 1); response._header('content-range', 'bytes ' + range.from + '-' + range.to + '/' + length); return new Ammo.Clip(range); }; internals.encoding = function (response, encoding) { const request = response.request; const header = response.headers['content-encoding'] || encoding; if (header && response.headers.etag && response.settings.varyEtag) { response.headers.etag = response.headers.etag.slice(0, -1) + '-' + header + '"'; } if (!encoding || response.statusCode === 206 || !response._isPayloadSupported()) { return null; } delete response.headers['content-length']; response._header('content-encoding', encoding); const compressor = request._core.compression.encoder(request, encoding); if (response.variety === 'stream' && typeof response._payload.setCompressor === 'function') { response._payload.setCompressor(compressor); } return compressor; }; internals.pipe = function (request, stream) { const team = new Teamwork.Team(); // Write payload const env = { stream, request, team }; if (request._closed) { // The request has already been aborted - no need to wait or attempt to write. internals.end(env, 'aborted'); return team.work; } const aborted = internals.end.bind(null, env, 'aborted'); const close = internals.end.bind(null, env, 'close'); const end = internals.end.bind(null, env, null); request.raw.req.on('aborted', aborted); request.raw.res.on('close', close); request.raw.res.on('error', end); request.raw.res.on('finish', end); if (stream.writeToStream) { stream.writeToStream(request.raw.res); } else { stream.on('error', end); stream.on('close', aborted); stream.pipe(request.raw.res); } return team.work; }; internals.end = function (env, event, err) { const { request, stream, team } = env; if (!team) { // Used instead of cleaning up emitter listeners return; } env.team = null; if (request.raw.res.writableEnded) { request.info.responded = Date.now(); team.attend(); return; } if (err) { request.raw.res.destroy(); request._core.Response.drain(stream); } // Update reported response to reflect the error condition const origResponse = request.response; const error = err ? Boom.boomify(err) : new Boom.Boom(`Request ${event}`, { statusCode: request.route.settings.response.disconnectStatusCode, data: origResponse }); request._setResponse(error); // Make inject throw a disconnect error if (request.raw.res[Config.symbol]) { request.raw.res[Config.symbol].error = event ? error : new Boom.Boom(`Response error`, { statusCode: request.route.settings.response.disconnectStatusCode, data: origResponse }); } if (event) { request._log(['response', 'error', event]); } else { request._log(['response', 'error'], err); } request.raw.res.end(); // Triggers injection promise resolve team.attend(); }; internals.writeHead = function (response) { const res = response.request.raw.res; const headers = Object.keys(response.headers); let i = 0; try { for (; i < headers.length; ++i) { const header = headers[i]; const value = response.headers[header]; if (value !== undefined) { res.setHeader(header, value); } } } catch (err) { for (--i; i >= 0; --i) { res.removeHeader(headers[i]); // Undo headers } throw Boom.boomify(err); } if (response.settings.message) { res.statusMessage = response.settings.message; } try { res.writeHead(response.statusCode); } catch (err) { throw Boom.boomify(err); } }; internals.chain = function (sources) { let from = sources[0]; for (let i = 1; i < sources.length; ++i) { const to = sources[i]; if (to) { from.on('close', internals.destroyPipe.bind(from, to)); from.on('error', internals.errorPipe.bind(from, to)); from = from.pipe(to); } } return from; }; internals.destroyPipe = function (to) { if (!this.readableEnded && !this.errored) { to.destroy(); } }; internals.errorPipe = function (to, err) { to.emit('error', err); }; ================================================ FILE: lib/types/index.d.ts ================================================ // Definitions adapted from DefinitelyTyped, originally created by: // Rafael Souza Fijalkowski // Justin Simms // Simon Schick // Rodrigo Saboya // Silas Rech export * from './plugin'; export * from './response'; export * from './request'; export * from './route'; export * from './server'; export * from './utils'; // Kept for backwards compatibility only (remove in next major) export namespace Utils { interface Dictionary { [key: string]: T; } } ================================================ FILE: lib/types/plugin.d.ts ================================================ import { RequestRoute } from './request'; import { RouteOptions } from './route'; import { Server } from './server'; import { Lifecycle } from './utils'; /** * one of * a single plugin name string. * an array of plugin name strings. * an object where each key is a plugin name and each matching value is a * {@link https://www.npmjs.com/package/semver version range string} which must match the registered * plugin version. */ export type Dependencies = string | string[] | Record; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) */ export interface PluginsListRegistered { } /** * An object of the currently registered plugins where each key is a registered plugin name and the value is an * object containing: * * version - the plugin version. * * name - the plugin name. * * options - (optional) options passed to the plugin during registration. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) */ export interface PluginRegistered { /** * the plugin version. */ version: string; /** * the plugin name. */ name: string; /** * options used to register the plugin. */ options: object; } export interface PluginsStates { } export interface PluginSpecificConfiguration { } export interface PluginNameVersion { /** * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm * registry) should use the same name as the name field in their 'package.json' file. Names must be * unique within each application. */ name: string; /** * optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's * 'package.json' file. */ version?: string | undefined; } export interface PluginPackage { /** * Alternatively, the name and version can be included via the pkg property containing the 'package.json' file for the module which already has the name and version included */ pkg: PluginNameVersion; } export interface PluginBase { /** * (required) the registration function with the signature async function(server, options) where: * * server - the server object with a plugin-specific server.realm. * * options - any options passed to the plugin during registration via server.register(). */ register: (server: Server, options: T) => void | Promise; /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ multiple?: boolean | undefined; /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ dependencies?: Dependencies | undefined; /** * Allows defining semver requirements for node and hapi. * @default Allows all. */ requirements?: { node?: string | undefined; hapi?: string | undefined; } | undefined; /** once - (optional) if true, will only register the plugin once per server. If set, overrides the once option passed to server.register(). Defaults to no override. */ once?: boolean | undefined; /** * We need to use D within the PluginBase type to be able to infer it later on, * but this property has no concrete existence in the code. * * See https://github.com/Microsoft/TypeScript/wiki/FAQ#why-doesnt-type-inference-work-on-this-interface-interface-foot-- for details. */ ___$type_of_plugin_decorations$___?: D; } /** * A plugin that is registered by name and version. */ export interface NamedPlugin extends PluginBase, PluginNameVersion {} /** * A plugin that is registered by its package.json file. */ export interface PackagedPlugin extends PluginBase, PluginPackage {} /** * Plugins provide a way to organize application code by splitting the server logic into smaller components. Each * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox * certain properties. For example, setting a file path in one plugin doesn't affect the file path set * in another plugin. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins) * * The type T is the type of the plugin options. */ export type Plugin = NamedPlugin | PackagedPlugin; /** * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When registering a plugin or an authentication scheme, a server object reference is provided * with a new server.realm container specific to that registration. It allows each plugin to maintain its own settings without leaking and affecting other plugins. For example, a plugin can set a * default file path for local resources without breaking other plugins' configured paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by routes * and extensions added at the same level (server root or plugin). * * https://github.com/hapijs/hapi/blob/master/API.md#server.realm */ export interface ServerRealm { /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */ modifiers: { /** routes preferences: */ route: { /** * the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include * the trailing slash. */ prefix: string; /** the route virtual host settings used by any calls to server.route() from the server. */ vhost: string; } }; /** the realm of the parent server object, or null for the root server. */ parent: ServerRealm | null; /** the active plugin name (empty string if at the server root). */ plugin: string; /** the plugin options object passed at registration. */ pluginOptions: object; /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ plugins: PluginsStates; /** settings overrides */ settings: { files: { relativeTo: string; }; bind: object; }; } /** * Registration options (different from the options passed to the registration function): * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the * second time a plugin is registered on the server. * * routes - modifiers applied to each route added by the plugin: * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific * prefix. * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) */ export interface ServerRegisterOptions { /** * if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second * time a plugin is registered on the server. */ once?: boolean | undefined; /** * modifiers applied to each route added by the plugin: */ routes?: { /** * string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. */ prefix: string; /** * virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. */ vhost?: string | string[] | undefined; } | undefined; } export interface ServerRegisterPluginObjectDirect extends ServerRegisterOptions { /** * a plugin object. */ plugin: Plugin; /** * options passed to the plugin during registration. */ options?: T | undefined; } export interface ServerRegisterPluginObjectWrapped extends ServerRegisterOptions { /** * a plugin object. */ plugin: { plugin: Plugin }; /** * options passed to the plugin during registration. */ options?: T | undefined; } /** * An object with the following: * * plugin - a plugin object or a wrapped plugin loaded module. * * options - (optional) options passed to the plugin during registration. * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the * second time a plugin is registered on the server. * * routes - modifiers applied to each route added by the plugin: * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific * prefix. * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) * * The type parameter T is the type of the plugin configuration options. */ export type ServerRegisterPluginObject = ServerRegisterPluginObjectDirect | ServerRegisterPluginObjectWrapped; export type ServerRegisterPluginObjectArray = ( ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject )[]; /** * The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. * If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. */ export interface HandlerDecorationMethod { (route: RequestRoute, options: any): Lifecycle.Method; defaults?: RouteOptions | ((method: any) => RouteOptions) | undefined; } /** * An empty interface to allow typings of custom plugin properties. */ export interface PluginProperties { } ================================================ FILE: lib/types/request.d.ts ================================================ import * as http from 'http'; import * as stream from 'stream'; import * as url from 'url'; import { Boom } from '@hapi/boom'; import { Podium } from '@hapi/podium'; import { PluginsStates, ServerRealm } from './plugin'; import { ResponseValue, ResponseObject } from "./response"; import { RouteRules, RouteSettings } from './route'; import { Server, ServerAuthSchemeObjectApi } from './server'; import { HTTP_METHODS, PeekListener } from './utils'; /** * User extensible types user credentials. */ export interface UserCredentials { } /** * User extensible types app credentials. */ export interface AppCredentials { } /** * User-extensible type for request.auth credentials. */ export interface AuthCredentials< AuthUser = UserCredentials, AuthApp = AppCredentials > { /** * The application scopes to be granted. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) */ scope?: string[] | undefined; /** * If set, will only work with routes that set `access.entity` to `user`. */ user?: AuthUser /** * If set, will only work with routes that set `access.entity` to `app`. */ app?: AuthApp; } export interface AuthArtifacts { [key: string]: unknown; } export type AuthMode = 'required' | 'optional' | 'try'; /** * Authentication information: * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. * * error - the authentication error is failed and mode set to 'try'. * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed * authorization, set to false. * * mode - the route authentication mode. * * strategy - the name of the strategy used. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) */ export interface RequestAuth< AuthUser = UserCredentials, AuthApp = AppCredentials, CredentialsExtra = Record, ArtifactsExtra = Record > { /** an artifact object received from the authentication strategy and used in authentication-related actions. */ artifacts: ArtifactsExtra; /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ credentials: ( AuthCredentials & CredentialsExtra ); /** the authentication error is failed and mode set to 'try'. */ error: Error; /** true if the request has been successfully authenticated, otherwise false. */ isAuthenticated: boolean; /** * true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, * set to false. */ isAuthorized: boolean; /** true if the request has been authenticated via the `server.inject()` `auth` option, otherwise `undefined`. */ isInjected?: boolean | undefined; /** the route authentication mode. */ mode: AuthMode; /** the name of the strategy used. */ strategy: string; } /** * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). * 'finish' - emitted when the request payload finished reading. The event method signature is function (). * 'disconnect' - emitted when a request errors or aborts unexpectedly. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) */ export type RequestEventType = 'peek' | 'finish' | 'disconnect'; /** * Access: read only and the public podium interface. * The request.events supports the following events: * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). * * 'disconnect' - emitted when a request errors or aborts unexpectedly. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) */ export interface RequestEvents extends Podium { /** * Access: read only and the public podium interface. * The request.events supports the following events: * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). * * 'disconnect' - emitted when a request errors or aborts unexpectedly. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) */ on(criteria: 'peek', listener: PeekListener): this; on(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): this; /** * Access: read only and the public podium interface. * The request.events supports the following events: * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). * * 'disconnect' - emitted when a request errors or aborts unexpectedly. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) */ once(criteria: 'peek', listener: PeekListener): this; once(criteria: 'peek'): Promise>; once(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): this; } /** * Request information: * * acceptEncoding - the request preferred encoding. * * cors - if CORS is enabled for the route, contains the following: * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). * * received - request reception timestamp. * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. * * remoteAddress - remote client IP address. * * remotePort - remote client port. * * responded - request response timestamp (0 is not responded yet). * Note that the request.info object is not meant to be modified. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) */ export interface RequestInfo { /** the request preferred encoding. */ acceptEncoding: string; /** if CORS is enabled for the route, contains the following: */ cors: { /** * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after * the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */ isOriginMatch?: boolean | undefined; }; /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ host: string; /** the hostname part of the 'Host' header (e.g. 'example.com'). */ hostname: string; /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}') */ id: string; /** request reception timestamp. */ received: number; /** content of the HTTP 'Referrer' (or 'Referer') header. */ referrer: string; /** remote client IP address. */ remoteAddress: string; /** remote client port. */ remotePort: string; /** request response timestamp (0 is not responded yet). */ responded: number; /** request processing completion timestamp (0 is still processing). */ completed: number; } /** * The request route information object, where: * * method - the route HTTP method. * * path - the route path. * * vhost - the route vhost option if configured. * * realm - the active realm associated with the route. * * settings - the route options object with all defaults applied. * * fingerprint - the route internal normalized string representing the normalized path. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) */ export interface RequestRoute { /** the route HTTP method. */ method: Exclude, 'head'> | '*'; /** the route path. */ path: string; /** the route vhost option if configured. */ vhost?: string | string[] | undefined; /** the active realm associated with the route. */ realm: ServerRealm; /** the route options object with all defaults applied. */ settings: RouteSettings; /** the route internal normalized string representing the normalized path. */ fingerprint: string; auth: { /** * Validates a request against the route's authentication access configuration, where: * @param request - the request object. * @return Return value: true if the request would have passed the route's access requirements. * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access * configuration. If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may * not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route * requires any authentication. * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) */ access(request: Request): boolean; }; } /** * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig) */ export interface RequestOrig { params: object; query: object; payload: object; } export interface RequestLog { request: string; timestamp: number; tags: string[]; data: string | object; channel: string; } export interface RequestQuery { [key: string]: string | string[] | undefined; } /** * Empty interface to allow for user-defined augmentations. */ export interface RouteOptionsApp {} /** * User-extensible type for application specific state on requests (`request.app`). */ export interface RequestApplicationState { } export interface InternalRequestDefaults { Server: Server; Payload: stream.Readable | Buffer | string | object; Query: RequestQuery; Params: Record; Pres: Record; Headers: Record; RequestApp: RequestApplicationState; AuthUser: UserCredentials; AuthApp: AppCredentials; AuthApi: ServerAuthSchemeObjectApi; AuthCredentialsExtra: Record; AuthArtifactsExtra: Record; Rules: RouteRules; Bind: object | null; RouteApp: RouteOptionsApp; } /** * Default request references. Used to give typing to requests, * route handlers, lifecycle methods, auth credentials, etc. * This can be overwritten to whatever is suitable and universal * in your specific app, but whatever references you pass to * server route generic, or lifecycle methods will take precedence * over these. */ export interface ReqRefDefaults extends InternalRequestDefaults {} /** * Route request overrides */ export type ReqRef = Partial>; /** * Utilities for merging request refs and other things */ export type MergeType = Omit & U; export type MergeRefs = MergeType; /** * The request object is created internally for each incoming request. It is not the same object received from the node * HTTP server callback (which is available via [request.raw.req](https://github.com/hapijs/hapi/blob/master/API.md#request.raw)). The request properties change throughout * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle). */ export interface Request extends Podium { /** * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp) */ app: MergeRefs['RequestApp']; /** * Authentication information: * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. * * error - the authentication error is failed and mode set to 'try'. * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed * authorization, set to false. * * mode - the route authentication mode. * * strategy - the name of the strategy used. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) */ readonly auth: RequestAuth< MergeRefs['AuthUser'], MergeRefs['AuthApp'], MergeRefs['AuthCredentialsExtra'], MergeRefs['AuthArtifactsExtra'] >; /** * Access: read only and the public podium interface. * The request.events supports the following events: * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). * * 'disconnect' - emitted when a request errors or aborts unexpectedly. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) */ events: RequestEvents; /** * The raw request headers (references request.raw.req.headers). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) */ readonly headers: MergeRefs['Headers']; /** * Request information: * * acceptEncoding - the request preferred encoding. * * cors - if CORS is enabled for the route, contains the following: * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only * available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). * * received - request reception timestamp. * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. * * remoteAddress - remote client IP address. * * remotePort - remote client port. * * responded - request response timestamp (0 is not responded yet). * Note that the request.info object is not meant to be modified. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) */ readonly info: RequestInfo; /** * An array containing the logged request events. * Note that this array will be empty if route log.collect is set to false. */ readonly logs: RequestLog[]; /** * The request method in lower case (e.g. 'get', 'post'). */ readonly method: Lowercase; /** * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ readonly mime: string; /** * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. */ readonly orig: RequestOrig; /** * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). */ readonly params: MergeRefs['Params']; /** * An array containing all the path params values in the order they appeared in the path. */ readonly paramsArray: keyof MergeRefs['Params'] | string[]; /** * The request URI's pathname component. */ readonly path: string; /** * The request payload based on the route payload.output and payload.parse settings. * TODO check this typing and add references / links. */ readonly payload: MergeRefs['Payload']; /** * Plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ plugins: PluginsStates; /** * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response * object, use responses. */ readonly pre: MergeRefs['Pres']; /** * Access: read / write (see limitations below). * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to * override with a different response. * In case of an aborted request the status code will be set to `disconnectStatusCode`. */ response: ResponseObject | Boom; /** * Same as pre but represented as the response object created by the pre method. */ readonly preResponses: Record; /** * By default the object outputted from node's URL parse() method. */ readonly query: MergeRefs['Query']; /** * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. * * req - the node request object. * * res - the node response object. */ readonly raw: { req: http.IncomingMessage; res: http.ServerResponse; }; /** * The request route information object and method * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest) */ readonly route: RequestRoute; /** * Access: read only and the public server interface. * The server object. */ readonly server: MergeRefs['Server']; /** * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ readonly state: Record; /** * The parsed request URI. */ readonly url: url.URL; /** * Returns `true` when the request is active and processing should continue and `false` when the * request terminated early or completed its lifecycle. Useful when request processing is a * resource-intensive operation and should be terminated early if the request is no longer active * (e.g. client disconnected or aborted early). */ active(): boolean; /** * Returns a response which you can pass into the reply interface where: * @param source - the value to set as the source of the reply interface, optional. * @param options - options for the method, optional. * @return ResponseObject * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options) */ /* tslint:disable-next-line:max-line-length */ generateResponse(source: string | object | null, options?: { variety?: string | undefined; prepare?: ((response: ResponseObject) => Promise) | undefined; marshal?: ((response: ResponseObject) => Promise) | undefined; close?: ((response: ResponseObject) => void) | undefined; } | undefined): ResponseObject; /** * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: * @param tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism * for describing and filtering events. * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return * value) the actual data emitted to the listeners. Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag * set to true. * @return void * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data) */ log(tags: string | string[], data?: string | object | (() => string | object) | undefined): void; /** * Changes the request method before the router begins processing the request where: * @param method - is the request HTTP method (e.g. 'GET'). * @return void * Can only be called from an 'onRequest' extension method. * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod) */ setMethod(method: HTTP_METHODS | Lowercase): void; /** * Changes the request URI before the router begins processing the request where: * Can only be called from an 'onRequest' extension method. * @param url - the new request URI. If url is a string, it is parsed with node's URL parse() method with parseQueryString set to true. url can also be set to an object compatible with node's URL * parse() method output. * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false. * @return void * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) */ setUrl(url: string | url.URL, stripTrailingSlash?: boolean | undefined): void; } ================================================ FILE: lib/types/response.d.ts ================================================ import { Podium } from '@hapi/podium'; import { PluginsStates, ServerRealm } from './plugin'; import { UserCredentials, AppCredentials, AuthArtifacts, AuthCredentials, ReqRef, ReqRefDefaults, MergeRefs, Request } from './request'; import { PeekListener, Lifecycle, Json } from './utils'; import { ServerStateCookieOptions } from './server'; /** * User-extensible type for application specific state on responses (`response.app`). */ export interface ResponseApplicationState { } /** * Access: read only and the public podium interface. * The response.events object supports the following events: * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). * [See docs](https://hapijs.com/api/17.0.1#-responseevents) */ export interface ResponseEvents extends Podium { /** * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). */ on(criteria: 'peek', listener: PeekListener): this; on(criteria: 'finish', listener: (data: undefined) => void): this; /** * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). */ once(criteria: 'peek', listener: PeekListener): this; once(criteria: 'peek'): Promise>; once(criteria: 'finish', listener: (data: undefined) => void): this; } /** * Object where: * * append - if true, the value is appended to any existing header value using separator. Defaults to false. * * separator - string used as separator when appending to an existing value. Defaults to ','. * * override - if false, the header value is not set if an existing value present. Defaults to true. * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) */ export interface ResponseObjectHeaderOptions { append?: boolean | undefined; separator?: string | undefined; override?: boolean | undefined; duplicate?: boolean | undefined; } /** * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status * code). In order to customize a response before it is returned, the h.response() method is provided. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/17.0.1#-responseevents) */ export interface ResponseObject extends Podium { /** * @default {}. * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp) */ app: ResponseApplicationState; /** * Access: read only and the public podium interface. * The response.events object supports the following events: * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). * [See docs](https://hapijs.com/api/17.0.1#-responseevents) */ readonly events: ResponseEvents; /** * @default {}. * An object containing the response headers where each key is a header field name and the value is the string header value or array of string. * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) */ readonly headers: Record; /** * @default {}. * Plugin-specific state. Provides a place to store and pass request-level plugin data. plugins is an object where each key is a plugin name and the value is the state. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins) */ plugins: PluginsStates; /** * Object containing the response handling flags. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) */ readonly settings: ResponseSettings; /** * The raw value returned by the lifecycle method. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource) */ readonly source: Lifecycle.ReturnValue; /** * @default 200. * The HTTP response status code. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode) */ readonly statusCode: number; /** * A string indicating the type of source with available values: * * 'plain' - a plain response such as string, number, null, or simple object. * * 'buffer' - a Buffer. * * 'stream' - a Stream. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety) */ readonly variety: 'plain' | 'buffer' | 'stream'; /** * Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: * @param length - the header value. Must match the actual payload size. * @return Return value: the current response object. * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength) */ bytes(length: number): ResponseObject; /** * Controls the 'Content-Type' HTTP header 'charset' property of the response. * * When invoked without any parameter, will prevent hapi from applying its default charset normalization to 'utf-8' * * When 'charset' parameter is provided, will set the 'Content-Type' HTTP header 'charset' property where: * @param charset - the charset property value. * @return Return value: the current response object. * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset) */ charset(charset?: string): ResponseObject | undefined; /** * Sets the HTTP status code where: * @param statusCode - the HTTP status code (e.g. 200). * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode) */ code(statusCode: number): ResponseObject; /** * Sets the HTTP status message where: * @param httpMessage - the HTTP status message (e.g. 'Ok' for status code 200). * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage) */ message(httpMessage: string): ResponseObject; /** * Sets the HTTP 'content-encoding' header where: * @param encoding - the header value string. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecompressedencoding) */ compressed(encoding: string): ResponseObject; /** * Sets the HTTP status code to Created (201) and the HTTP 'Location' header where: * @param uri - an absolute or relative URI used as the 'Location' header value. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri) */ created(uri: string): ResponseObject; /** * Sets the string encoding scheme used to serial data into the HTTP payload where: * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. * * 'ucs2' - Alias of 'utf16le'. * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). * * 'binary' - Alias for 'latin1'. * * 'hex' - Encode each byte as two hexadecimal characters. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding) */ encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject; /** * Sets the representation entity tag where: * @param tag - the entity tag string without the double-quote. * @param options - (optional) settings where: * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by * a '-' character). Ignored when weak is true. Defaults to true. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options) */ etag(tag: string, options?: {weak: boolean, vary: boolean} | undefined): ResponseObject; /** * Sets an HTTP header where: * @param name - the header name. * @param value - the header value. * @param options - (optional) object where: * * append - if true, the value is appended to any existing header value using separator. Defaults to false. * * separator - string used as separator when appending to an existing value. Defaults to ','. * * override - if false, the header value is not set if an existing value present. Defaults to true. * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) */ header(name: string, value: string, options?: ResponseObjectHeaderOptions | undefined): ResponseObject; /** * Sets the HTTP 'Location' header where: * @param uri - an absolute or relative URI used as the 'Location' header value. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri) */ location(uri: string): ResponseObject; /** * Sets an HTTP redirection response (302) and decorates the response with additional methods, where: * @param uri - an absolute or relative URI used to redirect the client to another resource. * @return Return value: the current response object. * Decorates the response object with the response.temporary(), response.permanent(), and response.rewritable() methods to easily change the default redirection code (302). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi) */ redirect(uri: string): ResponseObject; /** * Sets the JSON.stringify() replacer argument where: * @param method - the replacer function or array. Defaults to none. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod) */ replacer(method: Json.StringifyReplacer): ResponseObject; /** * Sets the JSON.stringify() space argument where: * @param count - the number of spaces to indent nested object keys. Defaults to no indentation. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount) */ spaces(count: number): ResponseObject; /** * Sets an HTTP cookie where: * @param name - the cookie name. * @param value - the cookie value. If no options.encoding is defined, must be a string. See server.state() for supported encoding values. * @param options - (optional) configuration. If the state was previously registered with the server using server.state(), the specified keys in options are merged with the default server * definition. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) */ state(name: string, value: object | string, options?: ServerStateCookieOptions | undefined): ResponseObject; /** * Sets a string suffix when the response is process via JSON.stringify() where: * @param suffix - the string suffix. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix) */ suffix(suffix: string): ResponseObject; /** * Overrides the default route cache expiration rule for this response instance where: * @param msec - the time-to-live value in milliseconds. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec) */ ttl(msec: number): ResponseObject; /** * Sets the HTTP 'Content-Type' header where: * @param mimeType - is the mime type. * @return Return value: the current response object. * Should only be used to override the built-in default for each response type. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype) */ type(mimeType: string): ResponseObject; /** * Clears the HTTP cookie by setting an expired value where: * @param name - the cookie name. * @param options - (optional) configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified options are merged with the server * definition. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options) */ unstate(name: string, options?: ServerStateCookieOptions | undefined): ResponseObject; /** * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: * @param header - the HTTP request header name. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader) */ vary(header: string): ResponseObject; /** * Marks the response object as a takeover response. * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover) */ takeover(): ResponseObject; /** * Sets the status code to 302 or 307 (based on the response.rewritable() setting) where: * @param isTemporary - if false, sets status to permanent. Defaults to true. * @return Return value: the current response object. * Only available after calling the response.redirect() method. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary) */ temporary(isTemporary?: boolean): ResponseObject; /** * Sets the status code to 301 or 308 (based on the response.rewritable() setting) where: * @param isPermanent - if false, sets status to temporary. Defaults to true. * @return Return value: the current response object. * Only available after calling the response.redirect() method. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent) */ permanent(isPermanent?: boolean): ResponseObject; /** * Sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' * to 'GET'). Exact code based on the response.temporary() or response.permanent() setting. Arguments: * @param isRewritable - if false, sets to non-rewritable. Defaults to true. * @return Return value: the current response object. * Only available after calling the response.redirect() method. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable) */ rewritable(isRewritable?: boolean): ResponseObject; } /** * Object containing the response handling flags. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) */ export interface ResponseSettings { /** * Defaults value: true. * If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response. */ readonly passThrough: boolean; /** * @default null (use route defaults). * Override the route json options used when source value requires stringification. */ readonly stringify: Json.StringifyArguments; /** * @default null (use route defaults). * If set, overrides the route cache with an expiration value in milliseconds. */ readonly ttl: number; /** * @default false. * If true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. */ varyEtag: boolean; } /** * See more about Lifecycle * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle * */ export type ResponseValue = string | object; export interface AuthenticationData< AuthUser = UserCredentials, AuthApp = AppCredentials, CredentialsExtra = Record, ArtifactsExtra = AuthArtifacts > { credentials: AuthCredentials & CredentialsExtra; artifacts?: ArtifactsExtra | undefined; } export interface Auth< AuthUser = UserCredentials, AuthApp = AppCredentials, CredentialsExtra = Record, ArtifactsExtra = AuthArtifacts > { readonly isAuth: true; readonly error?: Error | null | undefined; readonly data?: AuthenticationData | undefined; } /** * The response toolkit is a collection of properties and utilities passed to every [lifecycle method](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) */ export interface ResponseToolkit { /** * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step * without further interaction with the node response stream. It is the developer's responsibility to write * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw). */ readonly abandon: symbol; /** * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after * calling request.raw.res.end()) to close the the node response stream. */ readonly close: symbol; /** * A response symbol. Provides access to the route or server context set via the route [bind](https://github.com/hapijs/hapi/blob/master/API.md#route.options.bind) * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()). */ readonly context: any; /** * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response. */ readonly continue: symbol; /** * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching * route. Defaults to the root server realm in the onRequest step. */ readonly realm: ServerRealm; /** * Access: read only and public request interface. * The [request] object. This is a duplication of the request lifecycle method argument used by * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request. */ readonly request: Readonly>; /** * Used by the [authentication] method to pass back valid credentials where: * @param data - an object with: * * credentials - (required) object representing the authenticated entity. * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. * @return Return value: an internal authentication object. */ authenticated < AuthUser = MergeRefs['AuthUser'], AuthApp = MergeRefs['AuthApp'], CredentialsExtra = MergeRefs['AuthCredentialsExtra'], ArtifactsExtra = MergeRefs['AuthArtifactsExtra'] >( data: ( AuthenticationData< AuthUser, AuthApp, CredentialsExtra, ArtifactsExtra > ) ): Auth< AuthUser, AuthApp, CredentialsExtra, ArtifactsExtra >; /** * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined. * The method arguments are: * @param options - a required configuration object with: * * etag - the ETag string. Required if modified is not present. Defaults to no header. * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. * * vary - same as the response.etag() option. Defaults to true. * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed. * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned, * it should be used as the return value (but may be customize using the response methods). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions) */ entity(options?: {etag?: string | undefined, modified?: string | undefined, vary?: boolean | undefined} | undefined): ResponseObject; /** * Redirects the client to the specified uri. Same as calling h.response().redirect(uri). * @param url * @return Returns a response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi) */ redirect(uri?: string | undefined): ResponseObject; /** * Wraps the provided value and returns a response object which allows customizing the response * (e.g. setting the HTTP status code, custom headers, etc.), where: * @param value - (optional) return value. Defaults to null. * @return Returns a response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue) */ response(value?: ResponseValue | undefined): ResponseObject; /** * Sets a response cookie using the same arguments as response.state(). * @param name of the cookie * @param value of the cookie * @param (optional) ServerStateCookieOptions object. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options) */ state(name: string, value: string | object, options?: ServerStateCookieOptions | undefined): void; /** * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: * @param error - (required) the authentication error. * @param data - (optional) an object with: * * credentials - (required) object representing the authenticated entity. * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. * @return void. * The method is used to pass both the authentication error and the credentials. For example, if a request included * expired credentials, it allows the method to pass back the user information (combined with a 'try' * authentication mode) for error customization. * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data) */ unauthenticated < AuthUser = MergeRefs['AuthUser'], AuthApp = MergeRefs['AuthApp'], CredentialsExtra = MergeRefs['AuthCredentialsExtra'], ArtifactsExtra = MergeRefs['AuthArtifactsExtra'] >( error: Error, data?: ( AuthenticationData< AuthUser, AuthApp, CredentialsExtra, ArtifactsExtra > ) | undefined ): Auth< AuthUser, AuthApp, CredentialsExtra, ArtifactsExtra >; /** * Clears a response cookie using the same arguments as * @param name of the cookie * @param options (optional) ServerStateCookieOptions object. * @return void. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options) */ unstate(name: string, options?: ServerStateCookieOptions | undefined): void; } ================================================ FILE: lib/types/route.d.ts ================================================ import { ObjectSchema, ValidationOptions, SchemaMap, Schema } from 'joi'; import { PluginSpecificConfiguration} from './plugin'; import { MergeType, ReqRef, ReqRefDefaults, MergeRefs, AuthMode } from './request'; import { ContentDecoders, ContentEncoders, RouteRequestExtType, RouteExtObject, Server } from './server'; import { Lifecycle, Json, HTTP_METHODS } from './utils'; /** * Overrides for `InternalRouteOptionType`. Extend this to have * typings for route.options.auth['strategy' || 'scope'] * * @example * * interface RoutOptionTypes { * Strategy: 'jwt' | 'basic' | 'myCustom' * Scope: 'user' | 'admin' | 'manager-users' * } */ export interface RouteOptionTypes { } export interface InternalRouteOptionType { Strategy: string; Scope: RouteOptionsAccessScope; } export type RouteOptionsAccessScope = false | string | string[]; export type AccessEntity = 'any' | 'user' | 'app'; export interface RouteOptionsAccessScopeObject { scope: RouteOptionsAccessScope; } export interface RouteOptionsAccessEntityObject { entity: AccessEntity; } export type RouteOptionsAccessObject = RouteOptionsAccessScopeObject | RouteOptionsAccessEntityObject | (RouteOptionsAccessScopeObject & RouteOptionsAccessEntityObject); /** * Route Authentication Options */ export interface RouteOptionsAccess { /** * @default none. * An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object * must include at least one of scope or entity. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess) */ access?: RouteOptionsAccessObject | RouteOptionsAccessObject[] | undefined; /** * @default false (no scope requirements). * The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least * one of the scopes defined to access the route. If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For * example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. You may also access * properties on the request object (query, params, payload, and credentials) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as 'user-{params.id}'. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) */ scope?: MergeType['Scope'] | undefined; /** * @default 'any'. * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values: * * 'any' - the authentication can be on behalf of a user or application. * * 'user' - the authentication must be on behalf of a user which is identified by the presence of a 'user' attribute in the credentials object returned by the authentication strategy. * * 'app' - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication * strategy. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity) */ entity?: AccessEntity | undefined; /** * @default 'required'. * The authentication mode. Available values: * * 'required' - authentication is required. * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all. * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode) */ mode?: AuthMode | undefined; /** * @default false, unless the scheme requires payload authentication. * If set, the incoming request payload is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' * when the scheme sets the authentication options.payload to true. Available values: * * false - no payload authentication. * * 'required' - payload authentication required. * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload) */ payload?: false | 'required' | 'optional' | undefined; /** * @default the default strategy set via server.auth.default(). * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies) */ strategies?: (MergeType['Strategy'])[] | undefined; /** * @default the default strategy set via server.auth.default(). * A string strategy names. Cannot be used together with strategies. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy) */ strategy?: MergeType['Strategy'] | undefined; } /** * Values are: * * * 'default' - no privacy flag. * * * 'public' - mark the response as suitable for public caching. * * * 'private' - mark the response as suitable only for private caching. * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) */ export type RouteOptionsCache = { privacy?: 'default' | 'public' | 'private' | undefined; statuses?: number[] | undefined; otherwise?: string | undefined; } & ( { expiresIn?: number | undefined; expiresAt?: undefined; } | { expiresIn?: undefined; expiresAt?: string | undefined; } | { expiresIn?: undefined; expiresAt?: undefined; } ); /** * @default false (no CORS headers). * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain * than the API server. To enable, set cors to true, or to an object with the following options: * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a * wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. * Defaults to any origin ['*']. * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. * Defaults to 86400 (one day). * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) */ export interface RouteOptionsCors { /** * an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' * character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any * origin ['*']. */ origin?: string[] | '*' | 'ignore' | undefined; /** * number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. * Defaults to 86400 (one day). */ maxAge?: number | undefined; /** * a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. */ headers?: string[] | undefined; /** * a strings array of additional headers to headers. Use this to keep the default headers in place. */ additionalHeaders?: string[] | undefined; /** * a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ exposedHeaders?: string[] | undefined; /** * a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. */ additionalExposedHeaders?: string[] | undefined; /** * if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. */ credentials?: boolean | undefined; /** * the status code used for CORS preflight responses, either 200 or 204. Defaults to 200. */ preflightStatusCode?: 200 | 204; } /** * The value must be one of: * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw * Buffer is returned. * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are * provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart * payloads are a synthetic interface created on top of the entire multipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the * multipart payload in the handler using a streaming parser (e.g. pez). * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of * which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. For context [See * docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) */ export type PayloadOutput = 'data' | 'stream' | 'file'; /** * Determines how the request payload is processed. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) */ export interface RouteOptionsPayload { /** * @default allows parsing of the following mime types: * * application/json * * application/*+json * * application/octet-stream * * application/x-www-form-urlencoded * * multipart/form-data * * text/* * A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed * above will not enable them to be parsed, and if parse is true, the request will result in an error response. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow) */ allow?: string | string[] | undefined; /** * @default none. * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) */ compression?: { [P in keyof ContentDecoders]?: Parameters[0] } | undefined; /** * @default 'application/json'. * The default content type if the 'Content-Type' request header is missing. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype) */ defaultContentType?: string | undefined; /** * @default 'error' (return a Bad Request (400) error response). * A failAction value which determines how to handle payload parsing errors. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction) */ failAction?: Lifecycle.FailAction | undefined; /** * @default 1048576 (1MB). * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes) */ maxBytes?: number | undefined; /** * @default 1000 * Limits the number of parts allowed in multipart payloads. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxparts) */ maxParts?: number; /** * @default none. * Overrides payload processing for multipart requests. Value can be one of: * * false - disable multipart processing. * an object with the following required options: * * output - same as the output option with an additional value option: * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? * * * * headers - the part headers. * * * * filename - the part file name. * * * * payload - the processed part payload. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart) */ multipart?: boolean | { output: PayloadOutput | 'annotated' }; /** * @default 'data'. * The processed payload format. The value must be one of: * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw * Buffer is returned. * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files * are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart * payloads are a synthetic interface created on top of the entire multipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the * multipart payload in the handler using a streaming parser (e.g. pez). * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are * presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track * of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) */ output?: PayloadOutput | undefined; /** * @default none. * A mime type string overriding the 'Content-Type' header value received. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride) */ override?: string | undefined; /** * @default true. * Determines if the incoming payload is processed or presented raw. Available values: * * true - if the request 'Content-Type' matches the allowed mime types set by allow (for the whole payload as well as parts), the payload is converted into an object when possible. If the * format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded. * * false - the raw payload is returned unmodified. * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse) */ parse?: boolean | 'gunzip' | undefined; /** * @default to 'error'. * Sets handling of incoming payload that may contain a prototype poisoning security attack. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadprotoaction) */ protoAction?: 'error' | 'remove' | 'ignore'; /** * @default to 10000 (10 seconds). * Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) * error response. Set to false to disable. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout) */ timeout?: false | number | undefined; /** * @default os.tmpdir(). * The directory used for writing file uploads. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads) */ uploads?: string | undefined; } /** * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) */ export type RouteOptionsPreArray = RouteOptionsPreAllOptions[]; /** * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) */ export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.Method; /** * An object with: * * method - a lifecycle method. * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) */ export interface RouteOptionsPreObject { /** * a lifecycle method. */ method: Lifecycle.Method; /** * key name used to assign the response of the method to in request.pre and request.preResponses. */ assign?: keyof MergeRefs['Pres'] | undefined; /** * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. */ failAction?: Lifecycle.FailAction | undefined; } export type ValidationObject = SchemaMap; /** * * true - any query parameter value allowed (no validation performed). false - no parameter value allowed. * * a joi validation object. * * a validation function using the signature async function(value, options) where: * * * value - the request.* object containing the request parameters. * * * options - options. */ export type RouteOptionsResponseSchema = boolean | ValidationObject | Schema | ((value: object | Buffer | string, options: ValidationOptions) => Promise); /** * Processing rules for the outgoing response. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) */ export interface RouteOptionsResponse { /** * @default 204. * The default HTTP status code when the payload is considered empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time of response transmission (the * response status code will remain 200 throughout the request lifecycle unless manually set). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode) */ emptyStatusCode?: 200 | 204 | undefined; /** * @default 'error' (return an Internal Server Error (500) error response). * A failAction value which defines what to do when a response fails payload validation. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction) */ failAction?: Lifecycle.FailAction | undefined; /** * @default false. * If true, applies the validation rule changes to the response payload. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify) */ modify?: boolean | undefined; /** * @default none. * [joi](https://github.com/hapijs/joi) options object pass to the validation function. Useful to set global options such as stripUnknown or abortEarly (the complete list is available here). If a * custom validation function is defined via schema or status then options can an arbitrary object that will be passed to this function as the second argument. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions) */ options?: ValidationOptions | undefined; // TODO needs validation /** * @default true. * If false, payload range support is disabled. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges) */ ranges?: boolean | undefined; /** * @default 100 (all responses). * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample) */ sample?: number | undefined; /** * @default true (no validation). * The default response payload validation rules (for all non-error responses) expressed as one of: * * true - any payload allowed (no validation). * * false - no payload allowed. * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function. * * a validation function using the signature async function(value, options) where: * * * value - the pending response payload. * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }). * * * if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error * output.payload. If an error is thrown, the error is processed according to failAction. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema) */ schema?: RouteOptionsResponseSchema | undefined; /** * @default none. * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema. * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) */ status?: Record | undefined; /** * The default HTTP status code used to set a response error when the request is closed or aborted before the * response is fully transmitted. * Value can be any integer greater or equal to 400. * The default value 499 is based on the non-standard nginx "CLIENT CLOSED REQUEST" error. * The value is only used for logging as the request has already ended. * @default 499 */ disconnectStatusCode?: number | undefined; } /** * @see https://www.w3.org/TR/referrer-policy/ */ export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'unsafe-url' | 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin'; /** * @default false (security headers disabled). * Sets common security headers. To enable, set security to true or to an object with the following options: * * hsts - controls the 'Strict-Transport-Security' header, where: * * * true - the header will be set to max-age=15768000. This is the default value. * * * a number - the maxAge parameter will be set to the provided value. * * * an object with the following fields: * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. * * xframe - controls the 'X-Frame-Options' header, where: * * * true - the header will be set to 'DENY'. This is the default value. * * * 'deny' - the headers will be set to 'DENY'. * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. * * * an object for specifying the 'allow-from' rule, where: * * * * rule - one of: * * * * * 'deny' * * * * * 'sameorigin' * * * * * 'allow-from' * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically * changed to 'sameorigin'. * * xss - controls the 'X-XSS-Protection' header, where: * * * 'disabled' - the header will be set to '0'. This is the default value. * * * 'enabled' - the header will be set to '1; mode=block'. * * * false - the header will be omitted * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) */ export interface RouteOptionsSecureObject { /** * hsts - controls the 'Strict-Transport-Security' header */ hsts?: boolean | number | { /** * the max-age portion of the header, as a number. Default is 15768000. */ maxAge?: number; /** * a boolean specifying whether to add the includeSubDomains flag to the header. */ includeSubDomains?: boolean; /** * a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ preload?: boolean; } | undefined; /** * controls the 'X-Frame-Options' header */ xframe?: true | 'deny' | 'sameorigin' | { /** * an object for specifying the 'allow-from' rule, */ rule: 'deny' | 'sameorigin' | 'allow-from'; /** * when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed * to 'sameorigin'. */ source: string; } | undefined; /** * controls the 'X-XSS-Protection' header, where: * * 'disabled' - the header will be set to '0'. This is the default value. * * 'enabled' - the header will be set to '1; mode=block'. * * false - the header will be omitted */ xss?: 'disabled' | 'enabled' | false | undefined; /** * boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. */ noOpen?: boolean | undefined; /** * boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. */ noSniff?: boolean | undefined; /** * Controls the `Referrer-Policy` header, which has the following possible values. * @default false Header will not be send. */ referrer?: false | ReferrerPolicy | undefined; } export type RouteOptionsSecure = boolean | RouteOptionsSecureObject; /** * @default { headers: true, params: true, query: true, payload: true, failAction: 'error' }. * Request input validation rules for various request components. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) */ export interface RouteOptionsValidate { /** * @default none. * An optional object with error fields copied into every validation error response. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields) */ errorFields?: object | undefined; /** * @default 'error' (return a Bad Request (400) error response). * A failAction value which determines how to handle failed validations. When set to a function, the err argument includes the type of validation error under err.output.payload.validation.source. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatefailaction) */ failAction?: Lifecycle.FailAction | undefined; /** * Validation rules for incoming request headers: * * If a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error * is thrown, the error is handled according to failAction. Note that all header field names must be in lowercase to match the headers normalized by node. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) * @default true */ headers?: RouteOptionsResponseSchema | undefined; /** * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here). * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter. * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as * Joi.ref('$query.key')). * Note that validation is performed in order (i.e. headers, params, query, and payload) and if type casting is used (e.g. converting a string to a number), the value of inputs not yet validated * will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the * individual route settings override the routes defaults (the rules are not merged). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) * @default true */ options?: ValidationOptions | object | undefined; /** * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where: * * true - any path parameter value allowed (no validation performed). * * a joi validation object. * * a validation function using the signature async function(value, options) where: * * * value - the request.params object containing the request path parameters. * * * options - options. * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an * error is thrown, the error is handled according to failAction. Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) * @default true */ params?: RouteOptionsResponseSchema | undefined; /** * Validation rules for incoming request payload (request body), where: * * If a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is * thrown, the error is handled according to failAction. Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well * as the significant performance cost of validating large amounts of data. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) * @default true */ payload?: RouteOptionsResponseSchema | undefined; /** * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in * request.query prior to validation. Where: * * If a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. * If an error * is thrown, the error is handled according to failAction. Note that changes to the query parameters will not be reflected in request.url. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) * @default true */ query?: RouteOptionsResponseSchema | undefined; /** * Validation rules for incoming cookies. * The cookie header is parsed and decoded into the request.state prior to validation. * @default true */ state?: RouteOptionsResponseSchema | undefined; } export interface CommonRouteProperties { /** * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) */ app?: MergeRefs['RouteApp'] | undefined; /** * @default null. * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind) */ bind?: MergeRefs['Bind'] | undefined; /** * @default { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. * If the route method is 'GET', the route can be configured to include HTTP caching directives in the response. Caching can be customized using an object with the following options: * privacy - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: * * * 'default' - no privacy flag. * * * 'public' - mark the response as suitable for public caching. * * * 'private' - mark the response as suitable only for private caching. * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. * The default Cache-Control: no-cache header can be disabled by setting cache to false. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) */ cache?: false | RouteOptionsCache | undefined; /** * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) */ compression?: { [P in keyof ContentEncoders]?: Parameters[0] } | undefined; /** * @default false (no CORS headers). * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different * domain than the API server. To enable, set cors to true, or to an object with the following options: * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a * wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. * Defaults to any origin ['*']. * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in * policy. Defaults to 86400 (one day). * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) */ cors?: boolean | RouteOptionsCors | undefined; /** * @default none. * Route description used for generating documentation (string). * This setting is not available when setting server route defaults using server.options.routes. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsdescription) */ description?: string | undefined; /** * @default none. * Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the * server.ext(events) event argument. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext) * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) */ ext?: { [key in RouteRequestExtType]?: RouteExtObject | RouteExtObject[] | undefined; } | undefined; /** * @default { relativeTo: '.' }. * Defines the behavior for accessing files: * * relativeTo - determines the folder relative paths are resolved against. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsfiles) */ files?: { relativeTo: string; } | undefined; /** * @default none. * The route handler function performs the main business logic of the route and sets the response. handler can be assigned: * * a lifecycle method. * * an object with a single property using the name of a handler type registered with the server.handler() method. The matching property value is passed as options to the registered handler * generator. Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler) */ handler?: Lifecycle.Method | object | undefined; /** * @default none. * An optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes added with an array of methods. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsid) */ id?: string | undefined; /** * @default false. * If true, the route cannot be accessed through the HTTP listener but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should * not be accessible to the outside world. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsisinternal) */ isInternal?: boolean | undefined; /** * @default none. * Optional arguments passed to JSON.stringify() when converting an object or error response to a string payload or escaping it after stringification. Supports the following: * * replacer - the replacer function or array. Defaults to no action. * * space - number of spaces to indent nested object keys. Defaults to no indentation. * * suffix - string suffix added after conversion to JSON string. Defaults to no suffix. * * escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) */ json?: Json.StringifyArguments | undefined; /** * @default { collect: false }. * Request logging options: * collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionslog) */ log?: { collect: boolean; } | undefined; /** * @default none. * Route notes used for generating documentation (string or array of strings). * This setting is not available when setting server route defaults using server.options.routes. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsnotes) */ notes?: string | string[] | undefined; /** * Determines how the request payload is processed. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) */ payload?: RouteOptionsPayload | undefined; /** * @default {}. * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) */ plugins?: PluginSpecificConfiguration | undefined; /** * @default none. * The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared * across routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). pre is assigned an ordered array of methods which * are called serially in order. If the pre array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of * the methods error, return a takeover response, or abort signal, the other parallel methods will continue to execute but will be ignored once completed. pre can be assigned a mixed array of: * * an array containing the elements listed below, which are executed in parallel. * * an object with: * * * method - a lifecycle method. * * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. * * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be * assigned. * * a method function - same as including an object with a single method key. * Note that pre-handler methods do not behave the same way other lifecycle methods do when a value is returned. Instead of the return value becoming the new response payload, the value is used * to assign the corresponding request.pre and request.preResponses properties. Otherwise, the handling of errors, takeover response response, or abort signal behave the same as any other * lifecycle methods. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) */ pre?: RouteOptionsPreArray | undefined; /** * Processing rules for the outgoing response. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) */ response?: RouteOptionsResponse | undefined; /** * @default false (security headers disabled). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) */ security?: RouteOptionsSecure | undefined; /** * @default { parse: true, failAction: 'error' }. * HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following * options: parse - determines if incoming 'Cookie' headers are parsed and stored in the request.state object. failAction - A failAction value which determines how to handle cookie parsing * errors. Defaults to 'error' (return a Bad Request (400) error response). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsstate) */ state?: { parse?: boolean | undefined; failAction?: Lifecycle.FailAction | undefined; } | undefined; /** * @default none. * Route tags used for generating documentation (array of strings). * This setting is not available when setting server route defaults using server.options.routes. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstags) */ tags?: string[] | undefined; /** * @default { server: false }. * Timeouts for processing durations. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstimeout) */ timeout?: { /** * Response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming request before giving up and responding with a Service Unavailable (503) error * response. */ server?: boolean | number | undefined; /** * @default none (use node default of 2 minutes). * By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to false to disable socket timeouts. */ socket?: boolean | number | undefined; } | undefined; /** * @default { headers: true, params: true, query: true, payload: true, failAction: 'error' }. * Request input validation rules for various request components. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) */ validate?: RouteOptionsValidate | undefined; } export interface AccessScopes { forbidden?: string[] | undefined; required?: string[] | undefined; selection?: string[] | undefined; } export interface AccessSetting { entity?: AccessEntity | undefined; scope: AccessScopes | false; } export interface AuthSettings { strategies: string[]; mode: AuthMode; access?: AccessSetting[] | undefined; } export interface RouteSettings extends CommonRouteProperties { auth?: AuthSettings | undefined; } /** * Each route can be customized to change the default behavior of the request lifecycle. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options) */ export interface RouteOptions extends CommonRouteProperties { /** * Route authentication configuration. Value can be: * false to disable authentication if a default strategy is set. * a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode. * an authentication configuration object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) */ auth?: false | string | RouteOptionsAccess | undefined; } export interface HandlerDecorations {} export interface RouteRules {} export interface RulesInfo { method: string; path: string; vhost: string; } export interface RulesOptions { validate: { schema?: ObjectSchema['Rules']> | Record['Rules'], Schema> | undefined; options?: ValidationOptions | undefined; }; } export interface RulesProcessor { (rules: MergeRefs['Rules'] | null, info: RulesInfo): Partial> | null; } type RouteDefMethods = Exclude, 'HEAD' | 'head'>; /** * A route configuration object or an array of configuration objects where each object contains: * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The * path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same * result as adding the same route with different methods manually. * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the * header only (excluding the port). Defaults to all hosts. * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being * added to and this is bound to the current realm's bind option. * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) */ export interface ServerRoute { /** * (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path * can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. For context [See * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters) */ path: string; /** * (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method * (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same * result as adding the same route with different methods manually. */ method: RouteDefMethods | RouteDefMethods[] | '*'; /** * (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header * only (excluding the port). Defaults to all hosts. */ vhost?: string | string[] | undefined; /** * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. */ handler?: Lifecycle.Method | HandlerDecorations | undefined; /** * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to * and this is bound to the current realm's bind option. */ options?: RouteOptions | ((server: Server) => RouteOptions) | undefined; /** * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. */ rules?: MergeRefs['Rules'] | undefined; } ================================================ FILE: lib/types/server/auth.d.ts ================================================ import { Server } from './server'; import { MergeType, ReqRef, ReqRefDefaults, MergeRefs, Request, RequestAuth} from '../request'; import { ResponseToolkit, AuthenticationData } from '../response'; import { RouteOptionsAccess, InternalRouteOptionType, RouteOptionTypes} from '../route'; import { Lifecycle } from '../utils'; /** * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) */ export type ServerAuthSchemeOptions = object; /** * the method implementing the scheme with signature function(server, options) where: * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) * @param server - a reference to the server object the scheme is added to. * @param options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. */ export type ServerAuthScheme< // tslint:disable-next-line no-unnecessary-generics Options extends ServerAuthSchemeOptions = ServerAuthSchemeOptions, // tslint:disable-next-line no-unnecessary-generics Refs extends ReqRef = ReqRefDefaults > = (server: Server, options?: Options) => ServerAuthSchemeObject; export interface ServerAuthSchemeObjectApi {} /** * The scheme method must return an object with the following * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#authentication-scheme) */ export interface ServerAuthSchemeObject { /** * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object. */ api?: MergeRefs['AuthApi'] | undefined; /** * A lifecycle method function called for each incoming request configured with the authentication scheme. The * method is provided with two special toolkit methods for returning an authenticated or an unauthenticated result: * * h.authenticated() - indicate request authenticated successfully. * * h.unauthenticated() - indicate request failed to authenticate. * @param request the request object. * @param h the ResponseToolkit * @return the Lifecycle.ReturnValue */ authenticate(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; /** * A lifecycle method to authenticate the request payload. * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad * payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), * authentication may still be successful if the route auth.payload configuration is set to 'optional'. * @param request the request object. * @param h the ResponseToolkit * @return the Lifecycle.ReturnValue */ payload?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; /** * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written. * @param request the request object. * @param h the ResponseToolkit * @return the Lifecycle.ReturnValue */ response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; /** * a method used to verify the authentication credentials provided * are still valid (e.g. not expired or revoked after the initial authentication). * the method throws an `Error` when the credentials passed are no longer valid (e.g. expired or * revoked). Note that the method does not have access to the original request, only to the * credentials and artifacts produced by the `authenticate()` method. */ verify?( auth: RequestAuth< MergeRefs['AuthUser'], MergeRefs['AuthApp'], MergeRefs['AuthCredentialsExtra'], MergeRefs['AuthArtifactsExtra'] > ): Promise; /** * An object with the following keys: * * payload */ options?: { /** * if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. */ payload?: boolean | undefined; } | undefined; } /** * An authentication configuration object using the same format as the route auth handler options. * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) */ export interface ServerAuthConfig extends RouteOptionsAccess { } export interface ServerAuth { /** * An object where each key is an authentication strategy name and the value is the exposed strategy API. * Available only when the authentication scheme exposes an API by returning an api key in the object * returned from its implementation function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) */ api: Record; /** * Contains the default authentication configuration is a default strategy was set via * [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). */ readonly settings: { default: ServerAuthConfig; }; /** * Sets a default strategy which is applied to every route where: * @param options - one of: * * a string with the default strategy name * * an authentication configuration object using the same format as the route auth handler options. * @return void. * The default does not apply when a route config specifies auth as false, or has an authentication strategy * configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication * config is applied to the defaults. * Note that if the route has authentication configured, the default only applies at the time of adding the route, * not at runtime. This means that calling server.auth.default() after adding a route with some authentication * config will have no impact on the routes added prior. However, the default will apply to routes added * before server.auth.default() is called if those routes lack any authentication config. * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active * authentication configuration of a route, use server.auth.lookup(request.route). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) */ default(options: string | ServerAuthConfig): void; /** * Registers an authentication scheme where: * @param name the scheme name. * @param scheme - the method implementing the scheme with signature function(server, options) where: * * server - a reference to the server object the scheme is added to. * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. * @return void. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) */ scheme < Refs extends ReqRef = ReqRefDefaults, Options extends object = {} // tslint:disable-next-line no-unnecessary-generics >(name: string, scheme: ServerAuthScheme): void; /** * Registers an authentication strategy where: * @param name - the strategy name. * @param scheme - the scheme name (must be previously registered using server.auth.scheme()). * @param options - scheme options based on the scheme requirements. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) */ strategy( name: MergeType['Strategy'], scheme: string, options?: object ): void; /** * Tests a request against an authentication strategy where: * @param strategy - the strategy name registered with server.auth.strategy(). * @param request - the request object. * @return an object containing the authentication credentials and artifacts if authentication was successful, otherwise throws an error. * Note that the test() method does not take into account the route authentication configuration. It also does not * perform payload authentication. It is limited to the basic strategy authentication execution. It does not * include verifying scope, entity, or other route properties. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) */ test(strategy: string, request: Request): Promise; /** * Verify a request's authentication credentials against an authentication strategy. * Returns nothing if verification was successful, otherwise throws an error. * * Note that the `verify()` method does not take into account the route authentication configuration * or any other information from the request other than the `request.auth` object. It also does not * perform payload authentication. It is limited to verifying that the previously valid credentials * are still valid (e.g. have not been revoked or expired). It does not include verifying scope, * entity, or other route properties. */ // tslint:disable-next-line no-unnecessary-generics verify (request: Request): Promise; } ================================================ FILE: lib/types/server/cache.d.ts ================================================ import { PolicyOptionVariants, Policy, ClientApi, ClientOptions, EnginePrototype, PolicyOptions } from '@hapi/catbox'; export type CachePolicyOptions = PolicyOptionVariants & { /** * @default '_default' */ cache?: string | undefined; segment?: string | undefined; }; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) */ export interface ServerCache { /** * Provisions a cache segment within the server cache facility where: * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: * - `id` - the `id` string or object provided to the `get()` method. * - `flags` - an object used to pass back additional flags to the cache where: * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. * * staleTimeout - number of milliseconds to wait before checking if an item is stale. * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it * is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of * concurrent generateFunc calls beyond staleTimeout). * * cache - the cache name configured in server.cache. Defaults to the default cache. * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a * server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. * @return Catbox Policy. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) */ = CachePolicyOptions>(options: O): Policy; /** * Provisions a server cache as described in server.cache where: * @param options - same as the server cache configuration options. * @return Return value: none. * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) */ provision(options: ServerOptionsCache): Promise; } export type CacheProvider = EnginePrototype | { constructor: EnginePrototype; options?: T | undefined; }; /** * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache) */ export interface ServerOptionsCache extends PolicyOptions { /** catbox engine object. */ engine?: ClientApi | undefined; /** * a class or a prototype function */ provider?: CacheProvider | undefined; /** * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines * the default cache. If every cache includes a name, a default memory cache is provisioned as well. */ name?: string | undefined; /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ shared?: boolean | undefined; /** (optional) string used to isolate cached data. Defaults to 'hapi-cache'. */ partition?: string | undefined; /** other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). */ [s: string]: any; } ================================================ FILE: lib/types/server/encoders.d.ts ================================================ import { createDeflate, createGunzip, createGzip, createInflate } from 'zlib'; /** * Available [content encoders](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder). */ export interface ContentEncoders { deflate: typeof createDeflate; gzip: typeof createGzip; } /** * Available [content decoders](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder). */ export interface ContentDecoders { deflate: typeof createInflate; gzip: typeof createGunzip; } ================================================ FILE: lib/types/server/events.d.ts ================================================ import { Podium } from '@hapi/podium'; import { Request, RequestRoute } from '../request'; /** * an event name string. * an event options object. * a podium emitter object. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) */ export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium; /** * Object that it will be used in Event * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) */ export interface ServerEventsApplicationObject { /** the event name string (required). */ name: string; /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ channels?: string | string[] | undefined; /** * if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). */ clone?: boolean | undefined; /** * if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified * by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). */ spread?: boolean | undefined; /** * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to * the arguments list at the end. A configuration override can be set by each listener. Defaults to false. */ tags?: boolean | undefined; /** * if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first * configuration is used. Defaults to false (a duplicate registration will throw an error). */ shared?: boolean | undefined; } /** * A criteria object with the following optional keys (unless noted otherwise): * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) * * The type parameter T is the type of the name of the event. */ export interface ServerEventCriteria { /** (required) the event name string. */ name: T; /** * a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed * channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. */ channels?: string | string[] | undefined; /** if true, the data object passed to server.event.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ clone?: boolean | undefined; /** * a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.events.once(). * Defaults to no limit. */ count?: number | undefined; /** * filter - the event tags (if present) to subscribe to which can be one of: * * a tag string. * * an array of tag strings. * * an object with the following: * * * tags - a tag string or array of tag strings. * * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). */ filter?: string | string[] | { tags: string | string[] | undefined, all?: boolean | undefined } | undefined; /** * if true, and the data object passed to server.event.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used * when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). */ spread?: boolean | undefined; /** * if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended * to the arguments list at the end. Defaults to the event registration option (which defaults to false). */ tags?: boolean | undefined; } export interface LogEvent { /** the event timestamp. */ timestamp: string; /** an array of tags identifying the event (e.g. ['error', 'http']) */ tags: string[]; /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */ channel: 'internal' | 'app'; /** the request identifier. */ request: string; /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */ data: T; /** the error object related to the event if applicable. Cannot appear together with data */ error: object; } export interface RequestEvent { /** the event timestamp. */ timestamp: string; /** an array of tags identifying the event (e.g. ['error', 'http']) */ tags: string[]; /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */ channel: 'internal' | 'app' | 'error'; /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */ data: object | string; /** the error object related to the event if applicable. Cannot appear together with data */ error: object; } export type LogEventHandler = (event: LogEvent, tags: { [key: string]: true }) => void; export type RequestEventHandler = (request: Request, event: RequestEvent, tags: { [key: string]: true }) => void; export type ResponseEventHandler = (request: Request) => void; export type RouteEventHandler = (route: RequestRoute) => void; export type StartEventHandler = () => void; export type StopEventHandler = () => void; export interface PodiumEvent { emit(criteria: K, listener: (value: T) => void): void; on(criteria: K, listener: (value: T) => void): void; once(criteria: K, listener: (value: T) => void): void; once(criteria: K): Promise; removeListener(criteria: K, listener: Podium.Listener): this; removeAllListeners(criteria: K): this; hasListeners(criteria: K): this; } /** * Access: podium public interface. * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. * Use the following methods to interact with server.events: * [server.event(events)](https://github.com/hapijs/hapi/blob/master/API.md#server.event()) - register application events. * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ export interface ServerEvents extends Podium { /** * Subscribe to an event where: * @param criteria - the subscription criteria which must be one of: * * event name string which can be any of the built-in server events * * a custom application event registered with server.event(). * * a criteria object * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event) * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event) * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event) * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event) * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) */ on(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): this; on(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): this; on(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): this; on(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): this; on(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): this; on(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): this; on(criteria: string | ServerEventCriteria, listener: (value: any) => void): this; /** * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. * @param criteria - the subscription criteria which must be one of: * * event name string which can be any of the built-in server events * * a custom application event registered with server.event(). * * a criteria object * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) */ once(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): this; once(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): this; once(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): this; once(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): this; once(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): this; once(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): this; /** * Same as calling server.events.on() with the count option set to 1. * @param criteria - the subscription criteria which must be one of: * * event name string which can be any of the built-in server events * * a custom application event registered with server.event(). * * a criteria object * @return Return value: a promise that resolves when the event is emitted. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) */ once(criteria: string | ServerEventCriteria): Promise; /** * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ removeListener(name: string, listener: Podium.Listener): this; /** * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ removeAllListeners(name: string): this; /** * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ hasListeners(name: string): boolean; } ================================================ FILE: lib/types/server/ext.d.ts ================================================ import { Server, ServerApplicationState } from './server'; import { ReqRef, ReqRefDefaults } from '../request'; import { Lifecycle } from '../utils'; /** * The extension point event name. The available extension points include the request extension points as well as the following server extension points: * 'onPreStart' - called before the connection listeners are started. * 'onPostStart' - called after the connection listeners are started. * 'onPreStop' - called before the connection listeners are stopped. * 'onPostStop' - called after the connection listeners are stopped. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) */ export type ServerExtType = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'; export type RouteRequestExtType = 'onPreAuth' | 'onCredentials' | 'onPostAuth' | 'onPreHandler' | 'onPostHandler' | 'onPreResponse' | 'onPostResponse'; export type ServerRequestExtType = RouteRequestExtType | 'onRequest'; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) * Registers an extension function in one of the request lifecycle extension points where: * @param events - an object or array of objects with the following: * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: * * * 'onPreStart' - called before the connection listeners are started. * * * 'onPostStart' - called after the connection listeners are started. * * * 'onPreStop' - called before the connection listeners are stopped. * * * 'onPostStop' - called after the connection listeners are stopped. * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: * * * server extension points: async function(server) where: * * * * server - the server object. * * * * this - the object provided via options.bind or the current active context set with server.bind(). * * * request extension points: a lifecycle method. * * options - (optional) an object with the following: * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. * @return void */ export interface ServerExtEventsObject { /** * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: * * 'onPreStart' - called before the connection listeners are started. * * 'onPostStart' - called after the connection listeners are started. * * 'onPreStop' - called before the connection listeners are stopped. */ type: ServerExtType; /** * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: * * server extension points: async function(server) where: * * * server - the server object. * * * this - the object provided via options.bind or the current active context set with server.bind(). * * request extension points: a lifecycle method. */ method: ServerExtPointFunction | ServerExtPointFunction[]; options?: ServerExtOptions | undefined; } export interface RouteExtObject { method: Lifecycle.Method; options?: ServerExtOptions | undefined; } /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) * Registers an extension function in one of the request lifecycle extension points where: * @param events - an object or array of objects with the following: * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: * * * 'onPreStart' - called before the connection listeners are started. * * * 'onPostStart' - called after the connection listeners are started. * * * 'onPreStop' - called before the connection listeners are stopped. * * * 'onPostStop' - called after the connection listeners are stopped. * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: * * * server extension points: async function(server) where: * * * * server - the server object. * * * * this - the object provided via options.bind or the current active context set with server.bind(). * * * request extension points: a lifecycle method. * * options - (optional) an object with the following: * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. * @return void */ export interface ServerExtEventsRequestObject { /** * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: * * 'onPreStart' - called before the connection listeners are started. * * 'onPostStart' - called after the connection listeners are started. * * 'onPreStop' - called before the connection listeners are stopped. * * 'onPostStop' - called after the connection listeners are stopped. */ type: ServerRequestExtType; /** * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: * * server extension points: async function(server) where: * * * server - the server object. * * * this - the object provided via options.bind or the current active context set with server.bind(). * * request extension points: a lifecycle method. */ method: Lifecycle.Method | Lifecycle.Method[]; /** * (optional) an object with the following: * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, * or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. */ options?: ServerExtOptions | undefined; } export type ServerExtPointFunction = (server: Server) => void; /** * An object with the following: * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. For context [See * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) */ export interface ServerExtOptions { /** * a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. */ before?: string | string[] | undefined; /** * a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. */ after?: string | string[] | undefined; /** * a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. */ bind?: object | undefined; /** * if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when * adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. */ sandbox?: 'server' | 'plugin' | undefined; } ================================================ FILE: lib/types/server/index.d.ts ================================================ export * from './auth'; export * from './cache'; export * from './encoders'; export * from './events'; export * from './ext'; export * from './info'; export * from './inject'; export * from './methods'; export * from './options'; export * from './server'; export * from './state'; ================================================ FILE: lib/types/server/info.d.ts ================================================ /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) * An object containing information about the server where: */ export interface ServerInfo { /** * a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). */ id: string; /** * server creation timestamp. */ created: number; /** * server start timestamp (0 when stopped). */ started: number; /** * the connection [port](https://github.com/hapijs/hapi/blob/master/API.md#server.options.port) based on the following rules: * * before the server has been started: the configured port value. * * after the server has been started: the actual port assigned when no port is configured or was set to 0. */ port: number | string; /** * The [host](https://github.com/hapijs/hapi/blob/master/API.md#server.options.host) configuration value. */ host: string; /** * the active IP address the connection was bound to after starting. Set to undefined until the server has been * started or when using a non TCP port (e.g. UNIX domain socket). */ address: undefined | string; /** * the protocol used: * * 'http' - HTTP. * * 'https' - HTTPS. * * 'socket' - UNIX domain socket or Windows named pipe. */ protocol: 'http' | 'https' | 'socket'; /** * a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains * the uri value if set, otherwise constructed from the available settings. If no port is configured or is set * to 0, the uri will not include a port component until the server is started. */ uri: string; } ================================================ FILE: lib/types/server/inject.d.ts ================================================ import { RequestOptions as ShotRequestOptions, ResponseObject as ShotResponseObject } from '@hapi/shot'; import { PluginsStates } from '../plugin'; import { AuthArtifacts, AuthCredentials, Request, RequestApplicationState } from '../request'; /** * An object with: * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload * processing defaults to 'application/json' if no 'Content-Type' header provided. * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if * they were received via an authentication scheme. Defaults to no credentials. * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as * if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. * * app - (optional) sets the initial value of request.app, defaults to {}. * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. * * remoteAddress - (optional) sets the remote address for the incoming connection. * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. * * end - if false, does not end the stream. Defaults to true. * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested * separately. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) * For context [Shot module](https://github.com/hapijs/shot) */ export interface ServerInjectOptions extends ShotRequestOptions { /** * Authentication bypass options. */ auth?: { /** * The authentication strategy name matching the provided credentials. */ strategy: string; /** * The credentials are used to bypass the default authentication strategies, * and are validated directly as if they were received via an authentication scheme. */ credentials: AuthCredentials; /** * The artifacts are used to bypass the default authentication strategies, * and are validated directly as if they were received via an authentication scheme. Defaults to no artifacts. */ artifacts?: AuthArtifacts | undefined; } | undefined; /** * sets the initial value of request.app, defaults to {}. */ app?: RequestApplicationState | undefined; /** * sets the initial value of request.plugins, defaults to {}. */ plugins?: PluginsStates | undefined; /** * allows access to routes with config.isInternal set to true. Defaults to false. */ allowInternals?: boolean | undefined; } /** * A response object with the following properties: * * statusCode - the HTTP status code. * * headers - an object containing the headers set. * * payload - the response payload string. * * rawPayload - the raw response payload buffer. * * raw - an object with the injection request and response objects: * * req - the simulated node request object. * * res - the simulated node response object. * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of * the internal objects returned (instead of parsing the response string). * * request - the request object. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) * For context [Shot module](https://github.com/hapijs/shot) */ export interface ServerInjectResponse extends ShotResponseObject { /** * the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the * internal objects returned (instead of parsing the response string). */ result: Result | undefined; /** * the request object. */ request: Request; } ================================================ FILE: lib/types/server/methods.d.ts ================================================ import { CacheStatisticsObject, PolicyOptions } from "@hapi/catbox"; type AnyMethod = (...args: any[]) => any; export type CachedServerMethod = T & { cache?: { drop(...args: Parameters): Promise; stats: CacheStatisticsObject } }; /** * The method function with a signature async function(...args, [flags]) where: * * ...args - the method function arguments (can be any number of arguments or none). * * flags - when caching is enabled, an object used to set optional method result flags: * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ export type ServerMethod = AnyMethod; /** * The same cache configuration used in server.cache(). * The generateTimeout option is required. * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) */ export interface ServerMethodCache extends PolicyOptions { generateTimeout: number | false; cache?: string; segment?: string; } /** * Configuration object: * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an * arrow function. * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically * generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided * which takes the same arguments as the function and returns a unique string (or null if no key can be generated). For reference [See * docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ export interface ServerMethodOptions { /** * a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow * function. */ bind?: object | undefined; /** * the same cache configuration used in server.cache(). The generateTimeout option is required. */ cache?: ServerMethodCache | undefined; /** * a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a * unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which * takes the same arguments as the function and returns a unique string (or null if no key can be generated). */ generateKey?(...args: any[]): string | null; } /** * An object or an array of objects where each one contains: * * name - the method name. * * method - the method function. * * options - (optional) settings. * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) */ export interface ServerMethodConfigurationObject { /** * the method name. */ name: string; /** * the method function. */ method: ServerMethod; /** * (optional) settings. */ options?: ServerMethodOptions | undefined; } interface BaseServerMethods { [name: string]: ( ServerMethod | CachedServerMethod | BaseServerMethods ); } /** * An empty interface to allow typings of custom server.methods. */ export interface ServerMethods extends BaseServerMethods { } ================================================ FILE: lib/types/server/options.d.ts ================================================ import * as http from 'http'; import * as https from 'https'; import { MimosOptions } from '@hapi/mimos'; import { PluginSpecificConfiguration } from '../plugin'; import { RouteOptions } from '../route'; import { CacheProvider, ServerOptionsCache } from './cache'; import { SameSitePolicy, ServerStateCookieOptions } from './state'; export interface ServerOptionsCompression { minBytes: number; } /** * Empty interface to allow for custom augmentation. */ export interface ServerOptionsApp { } /** * The server options control the behavior of the server object. Note that the options object is deeply cloned * (with the exception of listener which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on. * All options are optionals. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-server-options) */ export interface ServerOptions { /** * @default '0.0.0.0' (all available network interfaces). * Sets the hostname or IP address the server will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces. Set to '127.0.0.1' or 'localhost' to * restrict the server to only those coming from the same host. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsaddress) */ address?: string | undefined; /** * @default {}. * Provides application-specific configuration which can later be accessed via server.settings.app. The framework does not interact with this object. It is simply a reference made available * anywhere a server reference is provided. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time * state. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) */ app?: ServerOptionsApp | undefined; /** * @default true. * Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework. * Cannot be set to true along with a port value. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsautolisten) */ autoListen?: boolean | undefined; /** * @default { engine: require('@hapi/catbox-memory' }. * Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and * capabilities. hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized * if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. The configuration can be assigned one or more * (array): * * a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('@hapi/catbox-redis')). A new catbox client will be created internally using this * function. * * a configuration object with the following: * * * engine - a class, a prototype function, or a catbox engine object. * * * name - an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines * the default cache. If every cache includes a name, a default memory cache is provisioned as well. * * * shared - if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. * * * partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'. * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache) */ cache?: CacheProvider | ServerOptionsCache | ServerOptionsCache[] | undefined; /** * @default { minBytes: 1024 }. * Defines server handling of content encoding requests. If false, response content encoding is disabled and no compression is performed by the server. */ compression?: boolean | ServerOptionsCompression | undefined; /** * @default { request: ['implementation'] }. * Determines which logged events are sent to the console. This should only be used for development and does not affect which events are actually logged internally and recorded. Set to false to * disable all console logging, or to an object with: * * log - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. Defaults to no output. * * request - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to * display all errors, set the option to ['error']. To turn off all console debug messages set it to false. To display all request logs, set it to '*'. Defaults to uncaught errors thrown in * external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. For example, to display all errors, set the log * or request to ['error']. To turn off all output set the log or request to false. To display all server logs, set the log or request to '*'. To disable all debug information, set debug to * false. */ debug?: false | { log?: string | string[] | false | undefined; request?: string | string[] | false | undefined; } | undefined; /** * @default the operating system hostname and if not available, to 'localhost'. * The public hostname or IP address. Used to set server.info.host and server.info.uri and as address is none provided. */ host?: string | undefined; info?: { /** * @default false. * If true, the request.info.remoteAddress and request.info.remotePort are populated when the request is received which can consume more resource (but is ok if the information is needed, * especially for aborted requests). When false, the fields are only populated upon demand (but will be undefined if accessed after the request is aborted). */ remote?: boolean | undefined; } | undefined; /** * @default none. * An optional node HTTP (or HTTPS) http.Server object (or an object with a compatible interface). * If the listener needs to be manually started, set autoListen to false. * If the listener uses TLS, set tls to true. */ listener?: http.Server | undefined; /** * @default { sampleInterval: 0 }. * Server excessive load handling limits where: * * sampleInterval - the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). * * maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). * * maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). * * maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ load?: { /** the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). */ sampleInterval?: number | undefined; /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ maxHeapUsedBytes?: number | undefined; /** * maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ maxRssBytes?: number | undefined; /** * maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. * Defaults to 0 (no limit). */ maxEventLoopDelay?: number | undefined; } | undefined; /** * @default none. * Options passed to the mimos module when generating the mime database used by the server (and accessed via server.mime): * * override - an object hash that is merged into the built in mime information specified here. Each key value pair represents a single mime object. Each override value must contain: * * key - the lower-cased mime-type string (e.g. 'application/javascript'). * * value - an object following the specifications outlined here. Additional values include: * * * type - specify the type value of result objects, defaults to key. * * * predicate - method with signature function(mime) when this mime type is found in the database, this function will execute to allows customizations. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsmime) */ mime?: MimosOptions | undefined; /** * @default { cleanStop: true } * Defines server handling of server operations. */ operations?: { /** * @default true * If true, the server keeps track of open connections and properly closes them when the server is stopped. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsoperations) */ cleanStop?: boolean; } /** * @default {}. * Plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the * difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. */ plugins?: PluginSpecificConfiguration | undefined; /** * @default 0 (an ephemeral port). * The TCP port the server will listen to. Defaults the next available port when the server is started (and assigned to server.info.port). * If port is a string containing a '/' character, it is used as a UNIX domain socket path. If it starts with '\.\pipe', it is used as a Windows named pipe. */ port?: number | string | undefined; /** * @default { isCaseSensitive: true, stripTrailingSlash: false }. * Controls how incoming request URIs are matched against the routing table: * * isCaseSensitive - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. * * stripTrailingSlash - removes trailing slashes on incoming paths. Defaults to false. */ router?: { isCaseSensitive?: boolean | undefined; stripTrailingSlash?: boolean | undefined; } | undefined; /** * @default none. * A route options object used as the default configuration for every route. */ routes?: RouteOptions | undefined; /** * Default value: * { * strictHeader: true, * ignoreErrors: false, * isSecure: true, * isHttpOnly: true, * isSameSite: 'Strict', * encoding: 'none' * } * Sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the state configuration object. */ state?: ServerStateCookieOptions | undefined; /** * @default none. * Used to create an HTTPS connection. The tls object is passed unchanged to the node HTTPS server as described in the node HTTPS documentation. */ tls?: boolean | https.ServerOptions | undefined; /** * @default constructed from runtime server information. * The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server server.info.uri, otherwise constructed from the server settings. */ uri?: string | undefined; /** * Query parameter configuration. */ query?: { /** * the method must return an object where each key is a parameter and matching value is the parameter value. * If the method throws, the error is used as the response or returned when `request.setUrl` is called. */ parser(raw: Record): Record; } | undefined; } ================================================ FILE: lib/types/server/server.d.ts ================================================ import * as http from 'http'; import { Stream } from 'stream'; import { Root } from 'joi'; import { Mimos } from '@hapi/mimos'; import { Dependencies, PluginsListRegistered, Plugin, ServerRealm, ServerRegisterOptions, ServerRegisterPluginObject, ServerRegisterPluginObjectArray, HandlerDecorationMethod, PluginProperties } from '../plugin'; import { ReqRef, ReqRefDefaults, Request, RequestRoute } from '../request'; import { ResponseToolkit } from '../response'; import { RulesOptions, RulesProcessor, ServerRoute } from '../route'; import { HTTP_METHODS, Lifecycle } from '../utils'; import { ServerAuth } from './auth'; import { ServerCache } from './cache'; import { ContentDecoders, ContentEncoders } from './encoders'; import { ServerEventsApplication, ServerEvents } from './events'; import { ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtType, ServerExtPointFunction, ServerExtOptions, ServerRequestExtType } from './ext'; import { ServerInfo } from './info'; import { ServerInjectOptions, ServerInjectResponse } from './inject'; import { ServerMethod, ServerMethodOptions, ServerMethodConfigurationObject, ServerMethods } from './methods'; import { ServerOptions } from './options'; import { ServerState, ServerStateCookieOptions } from './state'; /** * The general case for decorators added via server.decorate. */ export type DecorationMethod = (this: T, ...args: any[]) => any; export type DecorateName = string | symbol; export type DecorationValue = object | any[] | boolean | number | string | symbol | Map | Set; type ReservedRequestKeys = ( 'server' | 'url' | 'query' | 'path' | 'method' | 'mime' | 'setUrl' | 'setMethod' | 'headers' | 'id' | 'app' | 'plugins' | 'route' | 'auth' | 'pre' | 'preResponses' | 'info' | 'isInjected' | 'orig' | 'params' | 'paramsArray' | 'payload' | 'state' | 'response' | 'raw' | 'domain' | 'log' | 'logs' | 'generateResponse' | // Private functions '_allowInternals' | '_closed' | '_core' | '_entity' | '_eventContext' | '_events' | '_expectContinue' | '_isInjected' | '_isPayloadPending' | '_isReplied' | '_route' | '_serverTimeoutId' | '_states' | '_url' | '_urlError' | '_initializeUrl' | '_setUrl' | '_parseUrl' | '_parseQuery' ); type ReservedToolkitKeys = ( 'abandon' | 'authenticated' | 'close' | 'context' | 'continue' | 'entity' | 'redirect' | 'realm' | 'request' | 'response' | 'state' | 'unauthenticated' | 'unstate' ); type ReservedServerKeys = ( // Public functions 'app' | 'auth' | 'cache' | 'decorations' | 'events' | 'info' | 'listener' | 'load' | 'methods' | 'mime' | 'plugins' | 'registrations' | 'settings' | 'states' | 'type' | 'version' | 'realm' | 'control' | 'decoder' | 'bind' | 'control' | 'decoder' | 'decorate' | 'dependency' | 'encoder' | 'event' | 'expose' | 'ext' | 'inject' | 'log' | 'lookup' | 'match' | 'method' | 'path' | 'register' | 'route' | 'rules' | 'state' | 'table' | 'validator' | 'start' | 'initialize' | 'stop' | // Private functions '_core' | '_initialize' | '_start' | '_stop' | '_cachePolicy' | '_createCache' | '_clone' | '_ext' | '_addRoute' ); type ExceptName = Property extends ReservedKeys ? never : Property; /** * User-extensible type for application specific state (`server.app`). */ export interface ServerApplicationState { } /** * The server object is the main application container. The server manages all incoming requests along with all * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server) */ export class Server { /** * Creates a new server object * @param options server configuration object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions) */ constructor(options?: ServerOptions); /** * Provides a safe place to store server-specific run-time application data without potential conflicts with * the framework internals. The data can be accessed whenever the server is accessible. * Initialized with an empty object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp) */ app: A; /** * Server Auth: properties and methods */ readonly auth: ServerAuth; /** * Links another server to the initialize/start/stop state of the current server by calling the * controlled server `initialize()`/`start()`/`stop()` methods whenever the current server methods * are called, where: */ control(server: Server): void; /** * Provides access to the decorations already applied to various framework interfaces. The object must not be * modified directly, but only through server.decorate. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecorations) */ readonly decorations: { /** * decorations on the request object. */ request: string[], /** * decorations on the response toolkit. */ toolkit: string[], /** * decorations on the server object. */ server: string[] }; /** * Register custom application events where: * @param events must be one of: * * an event name string. * * an event options object with the following optional keys (unless noted otherwise): * * * name - the event name string (required). * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is * passed as-is). * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override * specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its * type). * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is * appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only * the first configuration is used. Defaults to false (a duplicate registration will throw an error). * * a podium emitter object. * * an array containing any of the above. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ event(events: ServerEventsApplication | ServerEventsApplication[]): void; /** * Access: podium public interface. * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. * Use the following methods to interact with server.events: * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ events: ServerEvents; /** * An object containing information about the server where: * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). * * created - server creation timestamp. * * started - server start timestamp (0 when stopped). * * port - the connection port based on the following rules: * * host - The host configuration value. * * address - the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). * * protocol - the protocol used: * * 'http' - HTTP. * * 'https' - HTTPS. * * 'socket' - UNIX domain socket or Windows named pipe. * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available * settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) */ readonly info: ServerInfo; /** * Access: read only and listener public interface. * The node HTTP server object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener) */ listener: http.Server; /** * An object containing the process load metrics (when load.sampleInterval is enabled): * * eventLoopDelay - event loop delay milliseconds. * * heapUsed - V8 heap usage. * * rss - RSS memory usage. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverload) */ readonly load: { /** * event loop delay milliseconds. */ eventLoopDelay: number; /** * V8 heap usage. */ heapUsed: number; /** * RSS memory usage. */ rss: number; }; /** * Server methods are functions registered with the server and used throughout the application as a common utility. * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request * handlers without having to create a common module. * sever.methods is an object which provides access to the methods registered via server.method() where each * server method name is an object property. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods */ readonly methods: ServerMethods; /** * Provides access to the server MIME database used for setting content-type information. The object must not be * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime) */ mime: Mimos; /** * An object containing the values exposed by each registered plugin where each key is a plugin name and the values * are the exposed properties by each plugin using server.expose(). Plugins may set the value of * the server.plugins[name] object directly or via the server.expose() method. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) */ plugins: PluginProperties; /** * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When * registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm * container specific to that registration. It allows each plugin to maintain its own settings without leaking * and affecting other plugins. * For example, a plugin can set a default file path for local resources without breaking other plugins' configured * paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by * routes and extensions added at the same level (server root or plugin). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm) */ readonly realm: ServerRealm; /** * An object of the currently registered plugins where each key is a registered plugin name and the value is * an object containing: * * version - the plugin version. * * name - the plugin name. * * options - (optional) options passed to the plugin during registration. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) */ readonly registrations: PluginsListRegistered; /** * The server configuration object after defaults applied. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serversettings) */ readonly settings: ServerOptions; /** * The server cookies manager. * Access: read only and statehood public interface. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstates) */ readonly states: ServerState; /** * A string indicating the listener type where: * * 'socket' - UNIX domain socket or Windows named pipe. * * 'tcp' - an HTTP listener. */ readonly type: 'socket' | 'tcp'; /** * The hapi module version number. */ readonly version: string; /** * Sets a global context used as the default bind object when adding a route or an extension where: * @param context - the object used to bind this in lifecycle methods such as the route handler and extension methods. The context is also made available as h.context. * @return Return value: none. * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. * Ignored if the method being bound is an arrow function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) */ bind(context: object): void; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) */ cache: ServerCache; /** * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where: * @param encoding - the decoder name string. * @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the * return value is an object compatible with the output of node's zlib.createGunzip(). * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) */ decoder(encoding: T, decoder: ContentDecoders[T]): void; decoder(encoding: string, decoder: ((options?: object) => Stream)): void; /** * Extends various framework interfaces with custom methods where: * @param type - the interface being decorated. Supported types: * 'handler' - adds a new handler type to be used in routes handlers. * 'request' - adds methods to the Request object. * 'server' - adds methods to the Server object. * 'toolkit' - adds methods to the response toolkit. * @param property - the object decoration key name. * @param method - the extension function or other value. * @param options - (optional) supports the following optional settings: * apply - when the type is 'request', if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned * as the decoration. extend - if true, overrides an existing decoration. The method must be a function with the signature function(existing) where: existing - is the previously set * decoration method value. must return the new decoration function or value. cannot be used to extend handler decorations. * @return void; * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) */ decorate

(type: 'handler', property: P, method: HandlerDecorationMethod, options?: { apply?: boolean | undefined, extend?: never }): void; decorate

(type: 'request', property: ExceptName, method: (existing: ((...args: any[]) => any)) => (request: Request) => DecorationMethod, options: {apply: true, extend: true}): void; decorate

(type: 'request', property: ExceptName, method: (request: Request) => DecorationMethod, options: {apply: true, extend?: boolean | undefined}): void; decorate

(type: 'request', property: ExceptName, method: DecorationMethod, options?: {apply?: boolean | undefined, extend?: boolean | undefined}): void; decorate

(type: 'request', property: ExceptName, value: (existing: ((...args: any[]) => any)) => (request: Request) => any, options: {apply: true, extend: true}): void; decorate

(type: 'request', property: ExceptName, value: (request: Request) => any, options: {apply: true, extend?: boolean | undefined}): void; decorate

(type: 'request', property: ExceptName, value: DecorationValue, options?: never): void; decorate

(type: 'toolkit', property: ExceptName, method: (existing: ((...args: any[]) => any)) => DecorationMethod, options: {apply?: boolean | undefined, extend: true}): void; decorate

(type: 'toolkit', property: ExceptName, method: DecorationMethod, options?: {apply?: boolean | undefined, extend?: boolean | undefined}): void; decorate

(type: 'toolkit', property: ExceptName, value: (existing: ((...args: any[]) => any)) => any, options: {apply?: boolean | undefined, extend: true}): void; decorate

(type: 'toolkit', property: ExceptName, value: DecorationValue, options?: never): void; decorate

(type: 'server', property: ExceptName, method: (existing: ((...args: any[]) => any)) => DecorationMethod, options: {apply?: boolean | undefined, extend: true}): void; decorate

(type: 'server', property: ExceptName, method: DecorationMethod, options?: {apply?: boolean | undefined, extend?: boolean | undefined}): void; decorate

(type: 'server', property: ExceptName, value: (existing: ((...args: any[]) => any)) => any, options: {apply?: boolean | undefined, extend: true}): void; decorate

(type: 'server', property: ExceptName, value: DecorationValue, options?: never): void; /** * Used within a plugin to declare a required dependency on other plugins where: * @param dependencies - plugins which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is * initialized or started. * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is * initialized or started. The function signature is async function(server) where: server - the server the dependency() method was called on. * @return Return value: none. * The after method is identical to setting a server extension point on 'onPreStart'. * If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). * The method does not provide version dependency which should be implemented using npm peer dependencies. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) */ dependency(dependencies: Dependencies, after?: ((server: Server) => Promise) | undefined): void; /** * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: * @param encoding - the encoder name string. * @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object * compatible with the output of node's zlib.createGzip(). * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) */ encoder(encoding: T, encoder: ContentEncoders[T]): void; encoder(encoding: string, encoder: ((options?: object) => Stream)): void; /** * Used within a plugin to expose a property via server.plugins[name] where: * @param key - the key assigned (server.plugins[name][key]). * @param value - the value assigned. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) */ expose(key: string, value: any): void; /** * Merges an object into to the existing content of server.plugins[name] where: * @param obj - the object merged into the exposed properties container. * @return Return value: none. * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method * for exposing large objects that may be expensive to clone or singleton objects such as database client * objects. Instead favor server.expose(key, value), which only copies a reference to value. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) */ expose(obj: object): void; /** * Registers an extension function in one of the request lifecycle extension points where: * @param events - an object or array of objects with the following: * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: * * * 'onPreStart' - called before the connection listeners are started. * * * 'onPostStart' - called after the connection listeners are started. * * * 'onPreStop' - called before the connection listeners are stopped. * * * 'onPostStop' - called after the connection listeners are stopped. * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: * * * server extension points: async function(server) where: * * * * server - the server object. * * * * this - the object provided via options.bind or the current active context set with server.bind(). * * * request extension points: a lifecycle method. * * options - (optional) an object with the following: * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level * extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. * @return void * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) */ ext(events: ServerExtEventsObject | ServerExtEventsObject[] | ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void; /** * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) */ ext(event: ServerExtType, method: ServerExtPointFunction, options?: ServerExtOptions | undefined): void; ext(event: ServerRequestExtType, method: Lifecycle.Method, options?: ServerExtOptions | undefined): void; /** * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. * @return Return value: none. * Note that if the method fails and throws an error, the server is considered to be in an undefined state and * should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and * other event listeners will get confused by repeated attempts to start the server or make assumptions about the * healthy state of the environment. It is recommended to abort the process when the server fails to start properly. * If you must try to resume after an error, call server.stop() first to reset the server state. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize) */ initialize(): Promise; /** * Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic * internally without the overhead and limitations of the network stack. The method utilizes the shot module for performing injections, with some additional options and response properties: * @param options - can be assigned a string with the requested URI, or an object with: * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload * processing defaults to 'application/json' if no 'Content-Type' header provided. * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as * if they were received via an authentication scheme. Defaults to no credentials. * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly * as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. * * app - (optional) sets the initial value of request.app, defaults to {}. * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. * * remoteAddress - (optional) sets the remote address for the incoming connection. * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. * * end - if false, does not end the stream. Defaults to true. * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested * separately. * @return Return value: a response object with the following properties: * * statusCode - the HTTP status code. * * headers - an object containing the headers set. * * payload - the response payload string. * * rawPayload - the raw response payload buffer. * * raw - an object with the injection request and response objects: * * req - the simulated node request object. * * res - the simulated node response object. * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse * of the internal objects returned (instead of parsing the response string). * * request - the request object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) */ inject (options: string | ServerInjectOptions): Promise>; /** * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or * output to the console. The arguments are: * @param tags - (required) a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive * mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return * value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. * @param timestamp - (optional) an timestamp expressed in milliseconds. Defaults to Date.now() (now). * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp) */ log(tags: string | string[], data?: string | object | (() => any) | undefined, timestamp?: number | undefined): void; /** * Looks up a route configuration where: * @param id - the route identifier. * @return Return value: the route information if found, otherwise null. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid) */ lookup(id: string): RequestRoute | null; /** * Looks up a route configuration where: * @param method - the HTTP method (e.g. 'GET', 'POST'). * @param path - the requested path (must begin with '/'). * @param host - (optional) hostname (to match against routes with vhost). * @return Return value: the route information if found, otherwise null. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) */ match(method: HTTP_METHODS | Lowercase, path: string, host?: string | undefined): RequestRoute | null; /** * Registers a server method where: * @param name - a unique method name used to invoke the method via server.methods[name]. * @param method - the method function with a signature async function(...args, [flags]) where: * * ...args - the method function arguments (can be any number of arguments or none). * * flags - when caching is enabled, an object used to set optional method result flags: * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. * @param options - (optional) configuration object: * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is * an arrow function. * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will * automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation * function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). * @return Return value: none. * Method names can be nested (e.g. utils.users.get) which will automatically create the full path under server.methods (e.g. accessed via server.methods.utils.users.get). * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear * the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ method(name: string, method: ServerMethod, options?: ServerMethodOptions | undefined): void; /** * Registers a server method function as described in server.method() using a configuration object where: * @param methods - an object or an array of objects where each one contains: * * name - the method name. * * method - the method function. * * options - (optional) settings. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) */ method(methods: ServerMethodConfigurationObject | ServerMethodConfigurationObject[]): void; /** * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: * @param relativeTo - the path prefix added to any relative file path starting with '.'. * @return Return value: none. * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default route configuration files.relativeTo settings is used. The * path only applies to routes added after it has been set. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto) */ path(relativeTo: string): void; /** * Registers a plugin where: * @param plugins - one or an array of: * * a plugin object. * * an object with the following: * * * plugin - a plugin object. * * * options - (optional) options passed to the plugin during registration. * * * once, routes - (optional) plugin-specific registration options as defined below. * @param options - (optional) registration options (different from the options passed to the registration function): * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the * second time a plugin is registered on the server. * * routes - modifiers applied to each route added by the plugin: * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the * child-specific prefix. * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) */ register(plugins: Plugin, options?: ServerRegisterOptions | undefined): Promise; register(plugin: ServerRegisterPluginObject, options?: ServerRegisterOptions | undefined): Promise; register(plugins: Plugin[], options?: ServerRegisterOptions | undefined): Promise; register(plugins: ServerRegisterPluginObject[], options?: ServerRegisterOptions | undefined): Promise; register(plugins: ServerRegisterPluginObjectArray, options?: ServerRegisterOptions | undefined): Promise; /** * Adds a route where: * @param route - a route configuration object or an array of configuration objects where each object contains: * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. * The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP * method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has * the same result as adding the same route with different methods manually. * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the * header only (excluding the port). Defaults to all hosts. * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being * added to and this is bound to the current realm's bind option. * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. * @return Return value: none. * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) */ route (route: ServerRoute | ServerRoute[]): void; /** * Defines a route rules processor for converting route rules object into route configuration where: * @param processor - a function using the signature function(rules, info) where: * * rules - * * info - an object with the following properties: * * * method - the route method. * * * path - the route path. * * * vhost - the route virtual host (if any defined). * * returns a route config object. * @param options - optional settings: * * validate - rules object validation: * * * schema - joi schema. * * * options - optional joi validation options. Defaults to { allowUnknown: true }. * Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config. * Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin override the config generated * by the root processor if they overlap. The route config overrides the rules config if the overlap. * @return void * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) */ rules ( processor: RulesProcessor, options?: RulesOptions | undefined ): void; /** * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). * @return Return value: none. * Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the * various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is * recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. If a started server * is started again, the second call to server.start() is ignored. No events will be emitted and no extension points invoked. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart) */ start(): Promise; /** * HTTP state management uses client cookies to persist a state across multiple requests. * @param name - the cookie name string. * @param options - are the optional cookie settings * @return Return value: none. * State defaults can be modified via the server default state configuration option. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) */ state(name: string, options?: ServerStateCookieOptions | undefined): void; /** * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: * @param options - (optional) object with: * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions) */ stop(options?: {timeout: number} | undefined): Promise; /** * Returns a copy of the routing table where: * @param host - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts. * @return Return value: an array of routes where each route contains: * * settings - the route config with defaults applied. * * method - the HTTP method in lower case. * * path - the route path. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost) */ table(host?: string | string[] | undefined): RequestRoute[]; /** * Registers a server validation module used to compile raw validation rules into validation schemas for all routes. * The validator is only used when validation rules are not pre-compiled schemas. When a validation rules is a function or schema object, the rule is used as-is and the validator is not used. */ validator(joi: Root): void; } /** * Factory function to create a new server object (introduced in v17). */ export function server(opts?: ServerOptions | undefined): Server; ================================================ FILE: lib/types/server/state.d.ts ================================================ import { StateOptions, SameSitePolicy } from '@hapi/statehood'; import { Request } from '../request'; export { SameSitePolicy }; /** * Optional cookie settings * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) */ export interface ServerStateCookieOptions extends StateOptions {} /** * A single object or an array of object where each contains: * * name - the cookie name. * * value - the cookie value. * * options - cookie configuration to override the server settings. */ export interface ServerStateFormat { name: string; value: string; options: ServerStateCookieOptions; } /** * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsstate) */ export interface ServerState { /** * The server cookies manager. * Access: read only and statehood public interface. */ readonly states: object; /** * The server cookies manager settings. The settings are based on the values configured in [server.options.state](https://github.com/hapijs/hapi/blob/master/API.md#server.options.state). */ readonly settings: ServerStateCookieOptions; /** * An object containing the configuration of each cookie added via [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()) where each key is the * cookie name and value is the configuration object. */ readonly cookies: { [key: string]: ServerStateCookieOptions; }; /** * An array containing the names of all configured cookies. */ readonly names: string[]; /** * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). */ add(name: string, options?: ServerStateCookieOptions | undefined): void; /** * Formats an HTTP 'Set-Cookie' header based on the server.options.state where: * @param cookies - a single object or an array of object where each contains: * * name - the cookie name. * * value - the cookie value. * * options - cookie configuration to override the server settings. * @return Return value: a header string. * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formatting (e.g. when headers are set manually). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies) */ format(cookies: ServerStateFormat | ServerStateFormat[]): Promise; /** * Parses an HTTP 'Cookies' header based on the server.options.state where: * @param header - the HTTP header. * @return Return value: an object where each key is a cookie name and value is the parsed cookie. * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) */ parse(header: string): Promise>; } ================================================ FILE: lib/types/utils.d.ts ================================================ import * as https from 'https'; import * as stream from 'stream'; import { Boom } from '@hapi/boom'; import { ResponseObject as ShotResponseObject } from '@hapi/shot'; import { ReqRef, ReqRefDefaults, MergeRefs, Request} from './request'; import { ResponseToolkit, Auth } from './response'; /** * All http parser [supported HTTP methods](https://nodejs.org/api/http.html#httpmethods). */ export type HTTP_METHODS = 'ACL' | 'BIND' | 'CHECKOUT' | 'CONNECT' | 'COPY' | 'DELETE' | 'GET' | 'HEAD' | 'LINK' | 'LOCK' | 'M-SEARCH' | 'MERGE' | 'MKACTIVITY' | 'MKCALENDAR' | 'MKCOL' | 'MOVE' | 'NOTIFY' | 'OPTIONS' | 'PATCH' | 'POST' | 'PROPFIND' | 'PROPPATCH' | 'PURGE' | 'PUT' | 'REBIND' | 'REPORT' | 'SEARCH' | 'SOURCE' | 'SUBSCRIBE' | 'TRACE' | 'UNBIND' | 'UNLINK' | 'UNLOCK' | 'UNSUBSCRIBE'; export type PeekListener = (chunk: string, encoding: string) => void; export namespace Json { /** * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} */ type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; /** * Any value greater than 10 is truncated. */ type StringifySpace = number | string; /** * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) */ interface StringifyArguments { /** the replacer function or array. Defaults to no action. */ replacer?: StringifyReplacer | undefined; /** number of spaces to indent nested object keys. Defaults to no indentation. */ space?: StringifySpace | undefined; /* string suffix added after conversion to JSON string. Defaults to no suffix. */ suffix?: string | undefined; /* calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. */ escape?: boolean | undefined; } } export namespace Lifecycle { /** * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecycle methods * provided by the developer and executed by the framework. * Each lifecycle method is a function with the signature await function(request, h, [err]) where: * * request - the request object. * * h - the response toolkit the handler must call to set a response and return control back to the framework. * * err - an error object available only when the method is used as a failAction value. */ type Method< Refs extends ReqRef = ReqRefDefaults, R extends ReturnValue = ReturnValue > = ( this: MergeRefs['Bind'], request: Request, h: ResponseToolkit, err?: Error | undefined ) => R; /** * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. * The return value must be one of: * - Plain value: null, string, number, boolean * - Buffer object * - Error object: plain Error OR a Boom object. * - Stream object * - any object or array * - a toolkit signal: * - a toolkit method response: * - a promise object that resolve to any of the above values * For more info please [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) */ type ReturnValue = ReturnValueTypes | (Promise>); type ReturnValueTypes = (null | string | number | boolean) | (Buffer) | (Error | Boom) | (stream.Stream) | (object | object[]) | symbol | Auth< MergeRefs['AuthUser'], MergeRefs['AuthApp'], MergeRefs['AuthCredentialsExtra'], MergeRefs['AuthArtifactsExtra'] > | ShotResponseObject; /** * Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be * configured to perform another action. When supported the failAction option supports the following values: * * 'error' - return the error object as the response. * * 'log' - report the error but continue processing the request. * * 'ignore' - take no action and continue processing the request. * * a lifecycle method with the signature async function(request, h, err) where: * * * request - the request object. * * * h - the response toolkit. * * * err - the error object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration) */ type FailAction = 'error' | 'log' | 'ignore' | Method; } ================================================ FILE: lib/validation.js ================================================ 'use strict'; const Boom = require('@hapi/boom'); const Hoek = require('@hapi/hoek'); const Validate = require('@hapi/validate'); const internals = {}; exports.validator = function (validator) { Hoek.assert(validator, 'Missing validator'); Hoek.assert(typeof validator.compile === 'function', 'Invalid validator compile method'); return validator; }; exports.compile = function (rule, validator, realm, core) { validator = validator ?? internals.validator(realm, core); // false - nothing allowed if (rule === false) { return Validate.object({}).allow(null); } // Custom function if (typeof rule === 'function') { return rule; } // null, undefined, true - anything allowed if (!rule || // false tested above rule === true) { return null; } // {...} - ... allowed if (typeof rule.validate === 'function') { return rule; } Hoek.assert(validator, 'Cannot set uncompiled validation rules without configuring a validator'); return validator.compile(rule); }; internals.validator = function (realm, core) { while (realm) { if (realm.validator) { return realm.validator; } realm = realm.parent; } return core.validator; }; exports.headers = function (request) { return internals.input('headers', request); }; exports.params = function (request) { return internals.input('params', request); }; exports.payload = function (request) { if (request.method === 'get' || request.method === 'head') { // When route.method is '*' return; } return internals.input('payload', request); }; exports.query = function (request) { return internals.input('query', request); }; exports.state = function (request) { return internals.input('state', request); }; internals.input = async function (source, request) { const localOptions = { context: { headers: request.headers, params: request.params, query: request.query, payload: request.payload, state: request.state, auth: request.auth, app: { route: request.route.settings.app, request: request.app } } }; delete localOptions.context[source]; Hoek.merge(localOptions, request.route.settings.validate.options); try { const schema = request.route.settings.validate[source]; const bind = request.route.settings.bind; var value = await (typeof schema !== 'function' ? internals.validate(request[source], schema, localOptions) : schema.call(bind, request[source], localOptions)); return; } catch (err) { var validationError = err; } finally { request.orig[source] = request[source]; if (value !== undefined) { request[source] = value; } } if (request.route.settings.validate.failAction === 'ignore') { return; } // Prepare error const defaultError = validationError.isBoom ? validationError : Boom.badRequest(`Invalid request ${source} input`); const detailedError = Boom.boomify(validationError, { statusCode: 400, override: false, data: { defaultError } }); detailedError.output.payload.validation = { source, keys: [] }; if (validationError.details) { for (const details of validationError.details) { const path = details.path; detailedError.output.payload.validation.keys.push(Hoek.escapeHtml(path.join('.'))); } } if (request.route.settings.validate.errorFields) { for (const field in request.route.settings.validate.errorFields) { detailedError.output.payload[field] = request.route.settings.validate.errorFields[field]; } } return request._core.toolkit.failAction(request, request.route.settings.validate.failAction, defaultError, { details: detailedError, tags: ['validation', 'error', source] }); }; exports.response = async function (request) { if (request.route.settings.response.sample) { const currentSample = Math.ceil(Math.random() * 100); if (currentSample > request.route.settings.response.sample) { return; } } const response = request.response; const statusCode = response.isBoom ? response.output.statusCode : response.statusCode; const statusSchema = request.route.settings.response.status[statusCode]; if (statusCode >= 400 && !statusSchema) { return; // Do not validate errors by default } const schema = statusSchema !== undefined ? statusSchema : request.route.settings.response.schema; if (schema === null) { return; // No rules } if (!response.isBoom && request.response.variety !== 'plain') { throw Boom.badImplementation('Cannot validate non-object response'); } const localOptions = { context: { headers: request.headers, params: request.params, query: request.query, payload: request.payload, state: request.state, auth: request.auth, app: { route: request.route.settings.app, request: request.app } } }; const source = response.isBoom ? response.output.payload : response.source; Hoek.merge(localOptions, request.route.settings.response.options); try { let value; if (typeof schema !== 'function') { value = await internals.validate(source, schema, localOptions); } else { value = await schema(source, localOptions); } if (value !== undefined && request.route.settings.response.modify) { if (response.isBoom) { response.output.payload = value; } else { response.source = value; } } } catch (err) { return request._core.toolkit.failAction(request, request.route.settings.response.failAction, err, { tags: ['validation', 'response', 'error'] }); } }; internals.validate = function (value, schema, options) { if (typeof schema.validateAsync === 'function') { return schema.validateAsync(value, options); } return schema.validate(value, options); }; ================================================ FILE: package.json ================================================ { "name": "@hapi/hapi", "description": "HTTP Server framework", "homepage": "https://hapi.dev", "version": "21.4.7", "repository": "git://github.com/hapijs/hapi", "main": "lib/index.js", "types": "lib/index.d.ts", "engines": { "node": ">=14.15.0" }, "files": [ "lib" ], "keywords": [ "framework", "http", "api", "web" ], "eslintConfig": { "extends": [ "plugin:@hapi/module" ] }, "dependencies": { "@hapi/accept": "^6.0.3", "@hapi/ammo": "^6.0.1", "@hapi/boom": "^10.0.1", "@hapi/bounce": "^3.0.2", "@hapi/call": "^9.0.1", "@hapi/catbox": "^12.1.1", "@hapi/catbox-memory": "^6.0.2", "@hapi/heavy": "^8.0.1", "@hapi/hoek": "^11.0.7", "@hapi/mimos": "^7.0.1", "@hapi/podium": "^5.0.2", "@hapi/shot": "^6.0.2", "@hapi/somever": "^4.1.1", "@hapi/statehood": "^8.2.1", "@hapi/subtext": "^8.1.1", "@hapi/teamwork": "^6.0.1", "@hapi/topo": "^6.0.2", "@hapi/validate": "^2.0.1" }, "devDependencies": { "@hapi/code": "^9.0.3", "@hapi/eslint-plugin": "^6.0.0", "@hapi/inert": "^7.1.0", "@hapi/joi-legacy-test": "npm:@hapi/joi@^15.0.0", "@hapi/lab": "^25.3.2", "@hapi/vision": "^7.0.3", "@hapi/wreck": "^18.1.0", "@types/node": "^18.19.130", "handlebars": "^4.7.8", "joi": "^17.13.3", "legacy-readable-stream": "npm:readable-stream@^1.0.34", "typescript": "^5.9.3" }, "scripts": { "test": "lab -a @hapi/code -t 100 -L -m 5000 -Y", "test-tap": "lab -a @hapi/code -r tap -o tests.tap -m 5000", "test-cov-html": "lab -a @hapi/code -r html -o coverage.html -m 5000" }, "license": "BSD-3-Clause" } ================================================ FILE: test/.hidden ================================================ Ssssh! ================================================ FILE: test/auth.js ================================================ 'use strict'; const Path = require('path'); const Boom = require('@hapi/boom'); const Code = require('@hapi/code'); const Handlebars = require('handlebars'); const Hapi = require('..'); const Hoek = require('@hapi/hoek'); const Lab = require('@hapi/lab'); const Vision = require('@hapi/vision'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('authentication', () => { it('requires and authenticates a request', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { user: 'steve' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: (request) => request.auth }); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(401); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res2.statusCode).to.equal(200); expect(res2.result).to.equal({ isAuthenticated: true, isAuthorized: false, isInjected: false, credentials: { user: 'steve' }, artifacts: undefined, strategy: 'default', mode: 'required', error: null }, { symbols: false }); }); it('disables authentication on a route', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { auth: false, handler: (request) => request.auth.isAuthenticated } }); const res1 = await server.inject({ url: '/', method: 'POST' }); expect(res1.statusCode).to.equal(200); expect(res1.result).to.be.false(); const res2 = await server.inject({ url: '/', method: 'POST', headers: { authorization: 'Custom steve' } }); expect(res2.statusCode).to.equal(200); expect(res2.result).to.be.false(); }); it('defaults cache to private if request authenticated', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response('ok').ttl(1000) }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(200); expect(res.headers['cache-control']).to.equal('max-age=1, must-revalidate, private'); }); it('authenticates a request against another route', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['one'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => { const credentials = request.auth.credentials; const access = { two: request.server.lookup('two').auth.access(request), three1: request.server.lookup('three').auth.access(request), four1: request.server.lookup('four').auth.access(request), five1: request.server.lookup('five').auth.access(request) }; request.auth.credentials = null; access.three2 = request.server.lookup('three').auth.access(request); access.four2 = request.server.lookup('four').auth.access(request); access.five2 = request.server.lookup('five').auth.access(request); request.auth.credentials = credentials; return access; }, auth: { scope: 'one' } } }); server.route({ method: 'GET', path: '/two', options: { id: 'two', handler: () => null, auth: { scope: 'two' } } }); server.route({ method: 'GET', path: '/three', options: { id: 'three', handler: () => null, auth: { scope: 'one' } } }); server.route({ method: 'GET', path: '/four', options: { id: 'four', handler: () => null, auth: false } }); server.route({ method: 'GET', path: '/five', options: { id: 'five', handler: () => null, auth: { mode: 'required' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal({ two: false, three1: true, three2: false, four1: true, four2: true, five1: true, five2: true }); }); describe('strategy()', () => { it('errors when strategy authenticate function throws', async () => { const server = Hapi.server({ debug: false }); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom'); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.credentials.user }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(500); }); it('throws when strategy missing scheme', () => { const server = Hapi.server(); expect(() => { server.auth.strategy('none'); }).to.throw('Authentication strategy none missing scheme'); }); it('adds a route to server', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} }, route: true }); server.auth.default('default'); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(401); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res2.statusCode).to.equal(204); }); it('uses views', async () => { const implementation = function (server, options) { server.views({ engines: { 'html': Handlebars }, relativeTo: Path.join(__dirname, '/templates/plugin') }); server.route({ method: 'GET', path: '/view', handler: (request, h) => h.view('test', { message: 'steve' }), options: { auth: false } }); return { authenticate: (request, h) => h.view('test', { message: 'xyz' }).takeover() }; }; const server = Hapi.server(); await server.register(Vision); server.views({ engines: { 'html': Handlebars }, relativeTo: Path.join(__dirname, '/no/such/directory') }); server.auth.scheme('custom', implementation); server.auth.strategy('default', 'custom'); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: () => null }); const res1 = await server.inject('/view'); expect(res1.result).to.equal('

steve

'); const res2 = await server.inject('/'); expect(res2.statusCode).to.equal(200); expect(res2.result).to.equal('

xyz

'); }); it('exposes an api', () => { const implementation = function (server, options) { return { api: { x: 5 }, authenticate: (request, h) => h.continue(null, {}) }; }; const server = Hapi.server(); server.auth.scheme('custom', implementation); server.auth.strategy('xyz', 'custom'); server.auth.default('xyz'); expect(server.auth.api.xyz.x).to.equal(5); }); it('has its own realm', async () => { const implementation = function (server) { return { authenticate: (_, h) => h.authenticated({ credentials: server.realm }) }; }; const server = Hapi.server(); server.auth.scheme('custom', implementation); server.auth.strategy('root', 'custom'); let pluginA; await server.register({ name: 'plugin-a', register(srv) { pluginA = srv; srv.auth.strategy('a', 'custom'); } }); const handler = (request) => request.auth.credentials; server.route({ method: 'GET', path: '/a', handler, options: { auth: 'a' } }); server.route({ method: 'GET', path: '/root', handler, options: { auth: 'root' } }); const { result: realm1 } = await server.inject('/a'); expect(realm1.plugin).to.be.undefined(); expect(realm1).to.not.shallow.equal(server.realm); expect(realm1.parent).to.shallow.equal(pluginA.realm); const { result: realm2 } = await server.inject('/root'); expect(realm2.plugin).to.be.undefined(); expect(realm2).to.not.shallow.equal(server.realm); expect(realm2.parent).to.shallow.equal(server.realm); }); }); describe('default()', () => { it('sets default', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); expect(server.auth.settings.default).to.equal({ strategies: ['default'], mode: 'required' }); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.credentials.user }); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(401); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res2.statusCode).to.equal(204); }); it('sets default with object', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default({ strategy: 'default' }); expect(server.auth.settings.default).to.equal({ strategies: ['default'], mode: 'required' }); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.credentials.user }); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(401); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res2.statusCode).to.equal(204); }); it('throws when setting default twice', () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); expect(() => { server.auth.default('default'); server.auth.default('default'); }).to.throw('Cannot set default strategy more than once'); }); it('throws when setting default without strategy', () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); expect(() => { server.auth.default({ mode: 'required' }); }).to.throw('Missing authentication strategy: default strategy'); }); it('matches dynamic scope', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { user: 'steve', scope: 'one-test-admin-x-steve' } } }); server.auth.default({ strategy: 'default', scope: 'one-{params.id}-{params.role}-{payload.x}-{credentials.user}' }); server.route({ method: 'POST', path: '/{id}/{role}', handler: (request) => request.auth.credentials.user }); const res = await server.inject({ method: 'POST', url: '/test/admin', headers: { authorization: 'Custom steve' }, payload: { x: 'x' } }); expect(res.statusCode).to.equal(200); }); }); describe('_setupRoute()', () => { it('throws when route refers to nonexistent strategy', () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('a', 'custom', { users: { steve: {} } }); server.auth.strategy('b', 'custom', { users: { steve: {} } }); expect(() => { server.route({ path: '/', method: 'GET', options: { auth: { strategy: 'c' }, handler: () => 'ok' } }); }).to.throw('Unknown authentication strategy c in /'); }); }); describe('lookup', () => { it('returns the route auth config', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: (request) => request.server.auth.lookup(request.route) }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal({ strategies: ['default'], mode: 'required' }); }); }); describe('authenticate()', () => { it('setups route with optional authentication', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => !!request.auth.credentials, auth: { mode: 'optional' } } }); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(200); expect(res1.payload).to.equal('false'); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res2.statusCode).to.equal(200); expect(res2.payload).to.equal('true'); }); it('exposes mode', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.mode }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('required'); }); it('authenticates using multiple strategies', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('first', 'custom', { users: { steve: 'skip' } }); server.auth.strategy('second', 'custom', { users: { steve: {} } }); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.strategy, auth: { strategies: ['first', 'second'] } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('second'); }); it('authenticates using credentials object', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { user: 'steve' } } }); server.auth.default('default'); const doubleHandler = async (request) => { const options = { url: '/2', auth: { credentials: request.auth.credentials, strategy: 'default' } }; const res = await server.inject(options); return res.result; }; server.route({ method: 'GET', path: '/1', handler: doubleHandler }); server.route({ method: 'GET', path: '/2', handler: (request) => request.auth.credentials.user }); const res = await server.inject({ url: '/1', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('steve'); }); it('authenticates using credentials object (with artifacts)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { user: 'steve' } } }); server.auth.default('default'); const doubleHandler = async (request) => { const options = { url: '/2', auth: { credentials: request.auth.credentials, artifacts: '!', strategy: 'default' } }; const res = await server.inject(options); return res.result; }; const handler = (request) => { return request.auth.credentials.user + request.auth.artifacts; }; server.route({ method: 'GET', path: '/1', handler: doubleHandler }); server.route({ method: 'GET', path: '/2', handler }); const res = await server.inject({ url: '/1', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('steve!'); }); it('authenticates a request with custom auth settings', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { strategy: 'default' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('authenticates a request with auth strategy name config', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: 'default' } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('tries to authenticate a request', async () => { const handler = (request) => { return { status: request.auth.isAuthenticated, error: request.auth.error }; }; const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default({ strategy: 'default', mode: 'try' }); server.route({ method: 'GET', path: '/', handler }); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(200); expect(res1.result.status).to.equal(false); expect(res1.result.error.message).to.equal('Missing authentication'); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom john' } }); expect(res2.statusCode).to.equal(200); expect(res2.result.status).to.equal(false); expect(res2.result.error.message).to.equal('Missing credentials'); const res3 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res3.statusCode).to.equal(200); expect(res3.result.status).to.equal(true); expect(res3.result.error).to.not.exist(); }); it('errors on invalid authenticate callback missing both error and credentials', async () => { const server = Hapi.server({ debug: false }); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.credentials.user }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom' } }); expect(res.statusCode).to.equal(500); }); it('logs error', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.credentials.user }); let logged = false; server.events.on({ name: 'request', channels: 'internal' }, (request, event, tags) => { if (tags.auth) { logged = true; } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom john' } }); expect(res.statusCode).to.equal(401); expect(logged).to.be.true(); }); it('returns a non Error error response', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { message: 'in a bottle' } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.credentials.user }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom message' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('in a bottle'); }); it('passes non Error error response when set to try ', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { message: 'in a bottle' } }); server.auth.default({ strategy: 'default', mode: 'try' }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom message' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('in a bottle'); }); it('matches scope (array to single)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['one'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: 'one' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('matches scope (array to array)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['one', 'two'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: ['one', 'three'] } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('matches scope (single to array)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: 'one' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: ['one', 'three'] } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('matches scope (single to single)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: 'one' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: 'one' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('matches dynamic scope (single to single)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: 'one-test' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/{id}', options: { handler: (request) => request.auth.credentials.user, auth: { scope: 'one-{params.id}' } } }); const res = await server.inject({ url: '/test', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('matches multiple required dynamic scopes', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['test', 'one-test'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/{id}', options: { handler: (request) => request.auth.credentials.user, auth: { scope: ['+one-{params.id}', '+{params.id}'] } } }); const res = await server.inject({ url: '/test', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('matches multiple required dynamic scopes (mixed types)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['test', 'one-test'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/{id}', options: { handler: (request) => request.auth.credentials.user, auth: { scope: ['+one-{params.id}', '{params.id}'] } } }); const res = await server.inject({ url: '/test', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('matches dynamic scope with multiple parts (single to single)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: 'one-test-admin' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/{id}/{role}', options: { handler: (request) => request.auth.credentials.user, auth: { scope: 'one-{params.id}-{params.role}' } } }); const res = await server.inject({ url: '/test/admin', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('does not match broken dynamic scope (single to single)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: 'one-test' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/{id}', options: { handler: (request) => request.auth.credentials.user, auth: { scope: 'one-params.id}' } } }); server.ext('onPreResponse', (request, h) => { expect(request.response.data).to.contain(['got', 'need']); return h.continue; }); const res = await server.inject({ url: '/test', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(403); expect(res.result.message).to.equal('Insufficient scope'); }); it('does not match scope (single to single)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: 'one' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: 'onex' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(403); expect(res.result.message).to.equal('Insufficient scope'); }); it('matches modified scope', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: 'two' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: 'one' } } }); server.ext('onCredentials', (request, h) => { request.auth.credentials.scope = 'one'; return h.continue; }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('errors on missing scope', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['a'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: 'b' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(403); expect(res.result.message).to.equal('Insufficient scope'); }); it('errors on missing scope property', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: 'b' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(403); expect(res.result.message).to.equal('Insufficient scope'); }); it('validates required scope', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['a', 'b'] }, john: { scope: ['a', 'b', 'c'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: ['+c', 'b'] } } }); const res1 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res1.statusCode).to.equal(403); expect(res1.result.message).to.equal('Insufficient scope'); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom john' } }); expect(res2.statusCode).to.equal(204); }); it('validates forbidden scope', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['a', 'b'] }, john: { scope: ['b', 'c'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: ['!a', 'b'] } } }); const res1 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res1.statusCode).to.equal(403); expect(res1.result.message).to.equal('Insufficient scope'); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom john' } }); expect(res2.statusCode).to.equal(204); }); it('validates complex scope', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['a', 'b', 'c'] }, john: { scope: ['b', 'c'] }, mary: { scope: ['b', 'd'] }, lucy: { scope: 'b' }, larry: { scope: ['c', 'd'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: ['!a', '+b', 'c', 'd'] } } }); const res1 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res1.statusCode).to.equal(403); expect(res1.result.message).to.equal('Insufficient scope'); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom john' } }); expect(res2.statusCode).to.equal(204); const res3 = await server.inject({ url: '/', headers: { authorization: 'Custom mary' } }); expect(res3.statusCode).to.equal(204); const res4 = await server.inject({ url: '/', headers: { authorization: 'Custom lucy' } }); expect(res4.statusCode).to.equal(403); expect(res4.result.message).to.equal('Insufficient scope'); const res5 = await server.inject({ url: '/', headers: { authorization: 'Custom larry' } }); expect(res5.statusCode).to.equal(403); expect(res5.result.message).to.equal('Insufficient scope'); }); it('errors on missing scope using arrays', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['a', 'b'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: ['c', 'd'] } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(403); expect(res.result.message).to.equal('Insufficient scope'); }); it('uses default scope when no scope override is set', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('a', 'custom', { users: { steve: { scope: ['two'] } } }); server.auth.default({ strategy: 'a', access: { scope: 'one' } }); server.route({ path: '/', method: 'GET', options: { auth: { mode: 'required' }, handler: () => 'ok' } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(403); expect(res.result.message).to.equal('Insufficient scope'); }); it('ignores default scope when override set to null', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default({ strategy: 'default', scope: 'one' }); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { scope: false } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('matches scope (access single)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['one'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth, auth: { access: { scope: 'one' } } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal({ isAuthenticated: true, isAuthorized: true, isInjected: false, credentials: { scope: ['one'], user: null }, artifacts: undefined, strategy: 'default', mode: 'required', error: null }, { symbols: false }); }); it('matches scope (access array)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['one'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { access: [ { scope: 'other' }, { scope: 'one' } ] } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('errors on matching scope (access array)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['one'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { access: [ { scope: 'two' }, { scope: 'three' }, { entity: 'user', scope: 'one' }, { entity: 'app', scope: 'four' } ] } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(403); expect(res.result.message).to.equal('Insufficient scope'); }); it('matches any entity', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { user: 'steve' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: () => null, auth: { entity: 'any' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('matches user entity', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { user: 'steve' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: () => null, auth: { entity: 'user' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(204); }); it('errors on missing user entity', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { client: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: () => null, auth: { entity: 'user' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom client' } }); expect(res.statusCode).to.equal(403); expect(res.result.message).to.equal('Application credentials cannot be used on a user endpoint'); }); it('matches app entity', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { client: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: () => null, auth: { entity: 'app' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom client' } }); expect(res.statusCode).to.equal(204); }); it('errors on missing app entity', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { user: 'steve' } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: () => null, auth: { entity: 'app' } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(403); expect(res.result.message).to.equal('User credentials cannot be used on an application endpoint'); }); it('logs error code when authenticate returns a non-error error', async () => { const server = Hapi.server(); server.auth.scheme('test', (srv, options) => { return { authenticate: (request, h) => h.response('Redirecting ...').redirect('/test').takeover() }; }); server.auth.strategy('test', 'test', {}); server.auth.default('test'); server.route({ method: 'GET', path: '/', handler: () => 'test' }); let logged = null; server.events.on({ name: 'request', channels: 'internal' }, (request, event, tags) => { if (tags.unauthenticated) { logged = event; } }); await server.inject('/'); expect(logged.data).to.equal({ statusCode: 302 }); }); it('passes the options.artifacts object, even with an auth filter', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: {} } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth.artifacts, auth: 'default' } }); const options = { url: '/', headers: { authorization: 'Custom steve' }, auth: { credentials: { foo: 'bar' }, artifacts: { bar: 'baz' }, strategy: 'default' } }; const res = await server.inject(options); expect(res.statusCode).to.equal(200); expect(res.result.bar).to.equal('baz'); }); it('errors on empty authenticate()', async () => { const scheme = () => { return { authenticate: (request, h) => h.authenticated() }; }; const server = Hapi.server({ debug: false }); server.auth.scheme('custom', scheme); server.auth.strategy('default', 'custom'); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('passes credentials on unauthenticated() in try mode', async () => { const scheme = () => { return { authenticate: (request, h) => h.unauthenticated(Boom.unauthorized(), { credentials: { user: 'steve' } }) }; }; const server = Hapi.server(); server.ext('onPreResponse', (request, h) => { if (request.auth.credentials.user === 'steve') { return h.continue; } }); server.auth.scheme('custom', scheme); server.auth.strategy('default', 'custom'); server.auth.default({ strategy: 'default', mode: 'try' }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); }); it('passes strategy, credentials, artifacts, error on unauthenticated() in required mode', async () => { const scheme = () => { return { authenticate: (request, h) => h.unauthenticated(Boom.unauthorized(), { credentials: { user: 'steve' }, artifacts: '!' }) }; }; const server = Hapi.server(); server.ext('onPreResponse', (request, h) => { if (request.auth.credentials.user === 'steve') { return h.continue; } }); server.ext('onPreResponse', (request, h) => { expect(request.auth.credentials).to.equal({ user: 'steve' }); expect(request.auth.artifacts).to.equal('!'); expect(request.auth.strategy).to.equal('default'); expect(request.auth.error.message).to.equal('Unauthorized'); return h.continue; }); server.auth.scheme('custom', scheme); server.auth.strategy('default', 'custom'); server.auth.default('default', { mode: 'required' }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject('/'); expect(res.statusCode).to.equal(401); }); }); describe('verify()', () => { it('verifies an authenticated request', async () => { const implementation = (...args) => { const imp = internals.implementation(...args); imp.verify = async (auth) => { await Hoek.wait(1); if (auth.credentials.user !== 'steve') { throw Boom.unauthorized('Invalid'); } }; return imp; }; const server = Hapi.server(); server.auth.scheme('custom', implementation); server.auth.strategy('default', 'custom', { users: { steve: { user: 'steve' }, john: { user: 'john' } } }); server.route({ method: 'GET', path: '/', options: { auth: { mode: 'try', strategy: 'default' }, handler: async (request) => { if (request.auth.error && request.auth.error.message === 'Missing authentication') { request.auth.error = null; } return await server.auth.verify(request) || 'ok'; } } }); const res1 = await server.inject('/'); expect(res1.result).to.equal('ok'); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res2.result).to.equal('ok'); const res3 = await server.inject({ url: '/', headers: { authorization: 'Custom unknown' } }); expect(res3.result.message).to.equal('Missing credentials'); const res4 = await server.inject({ url: '/', auth: { credentials: {}, strategy: 'default' } }); expect(res4.result.message).to.equal('Invalid'); const res5 = await server.inject({ url: '/', auth: { credentials: { user: 'steve' }, strategy: 'default' } }); expect(res5.result).to.equal('ok'); const res6 = await server.inject({ url: '/', headers: { authorization: 'Custom john' } }); expect(res6.result.message).to.equal('Invalid'); }); it('skips when verify unsupported', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { user: 'steve' } } }); server.route({ method: 'GET', path: '/', options: { auth: { mode: 'try', strategy: 'default' }, handler: async (request) => { return await server.auth.verify(request) || 'ok'; } } }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.result).to.equal('ok'); }); }); describe('access()', () => { it('skips access when unauthenticated and mode is not required', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { scope: ['one'] } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.auth, auth: { mode: 'optional', access: { scope: 'one' } } } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result.isAuthenticated).to.be.false(); expect(res.result.isAuthorized).to.be.false(); }); }); describe('payload()', () => { it('authenticates request payload', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { validPayload: { payload: null } } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { payload: 'required' } } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom validPayload' } }); expect(res.statusCode).to.equal(204); }); it('skips when scheme does not support it', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { validPayload: { payload: null } }, payload: false }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom validPayload' } }); expect(res.statusCode).to.equal(204); }); it('authenticates request payload (required scheme)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { validPayload: { payload: null } }, options: { payload: true } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: {} } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom validPayload' } }); expect(res.statusCode).to.equal(204); }); it('authenticates request payload (required scheme and required route)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { validPayload: { payload: null } }, options: { payload: true } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { payload: true } } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom validPayload' } }); expect(res.statusCode).to.equal(204); }); it('throws when scheme requires payload authentication and route conflicts', () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { validPayload: { payload: null } }, options: { payload: true } }); server.auth.default('default'); expect(() => { server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { payload: 'optional' } } }); }).to.throw('Cannot set authentication payload to optional when a strategy requires payload validation in /'); }); it('throws when strategy does not support payload authentication', () => { const server = Hapi.server(); const implementation = function () { return { authenticate: internals.implementation().authenticate }; }; server.auth.scheme('custom', implementation); server.auth.strategy('default', 'custom', {}); server.auth.default('default'); expect(() => { server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { payload: 'required' } } }); }).to.throw('Payload validation can only be required when all strategies support it in /'); }); it('throws when no strategy supports optional payload authentication', () => { const server = Hapi.server(); const implementation = function () { return { authenticate: internals.implementation().authenticate }; }; server.auth.scheme('custom', implementation); server.auth.strategy('default', 'custom', {}); server.auth.default('default'); expect(() => { server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { payload: 'optional' } } }); }).to.throw('Payload authentication requires at least one strategy with payload support in /'); }); it('allows one strategy to supports optional payload authentication while another does not', async () => { const server = Hapi.server(); const implementation = function (...args) { return { authenticate: internals.implementation(...args).authenticate }; }; server.auth.scheme('custom1', implementation); server.auth.scheme('custom2', internals.implementation, { users: {} }); server.auth.strategy('default1', 'custom1', { users: { steve: { user: 'steve' } } }); server.auth.strategy('default2', 'custom2', {}); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { strategies: ['default1', 'default2'], payload: 'optional' } } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(200); }); it('skips request payload by default', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { skip: {} } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom skip' } }); expect(res.statusCode).to.equal(204); }); it('skips request payload when unauthenticated', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { skip: {} } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: () => null, auth: { mode: 'try', payload: 'required' } } }); const res = await server.inject({ method: 'POST', url: '/' }); expect(res.statusCode).to.equal(204); }); it('skips optional payload', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { optionalPayload: { payload: Boom.unauthorized(null, 'Custom') } } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { payload: 'optional' } } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom optionalPayload' } }); expect(res.statusCode).to.equal(204); }); it('skips required payload authentication when disabled on injection', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom'); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => null, auth: { mode: 'try', payload: true } } }); const res = await server.inject({ method: 'POST', url: '/', auth: { credentials: { payload: Boom.internal('payload error') }, payload: false, strategy: 'default' } }); expect(res.statusCode).to.equal(204); }); it('errors on missing payload when required', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { optionalPayload: { payload: Boom.unauthorized(null, 'Custom') } } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { payload: 'required' } } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom optionalPayload' } }); expect(res.statusCode).to.equal(401); }); it('errors on invalid payload auth when required', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { optionalPayload: { payload: Boom.unauthorized() } } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { payload: 'required' } } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom optionalPayload' } }); expect(res.statusCode).to.equal(401); }); it('errors on invalid request payload (non error)', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { invalidPayload: { payload: 'Payload is invalid' } } }); server.auth.default('default'); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.auth.credentials.user, auth: { payload: 'required' } } }); const res = await server.inject({ method: 'POST', url: '/', headers: { authorization: 'Custom invalidPayload' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('Payload is invalid'); }); }); describe('response()', () => { it('fails on response error', async () => { const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { response: Boom.internal() } } }); server.auth.default('default'); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.credentials.user }); const res = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res.statusCode).to.equal(500); }); }); describe('test()', () => { it('tests a request', async () => { const handler = async (request) => { try { const { credentials, artifacts } = await request.server.auth.test('default', request); return { status: true, user: credentials.name, artifacts }; } catch (err) { return { status: false }; } }; const server = Hapi.server(); server.auth.scheme('custom', internals.implementation); server.auth.strategy('default', 'custom', { users: { steve: { name: 'steve' }, skip: 'skip' }, artifacts: {} }); server.route({ method: 'GET', path: '/', handler }); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(200); expect(res1.result.status).to.be.false(); const res2 = await server.inject({ url: '/', headers: { authorization: 'Custom steve' } }); expect(res2.statusCode).to.equal(200); expect(res2.result.status).to.be.true(); expect(res2.result.user).to.equal('steve'); expect(res2.result.artifacts).to.equal({}); const res3 = await server.inject({ url: '/', headers: { authorization: 'Custom skip' } }); expect(res3.statusCode).to.equal(200); expect(res3.result.status).to.be.false(); }); }); }); internals.implementation = function (server, options) { const settings = Hoek.clone(options); if (settings && settings.route) { server.route({ method: 'GET', path: '/', handler: (request) => (request.auth.credentials.user || null) }); } const scheme = { authenticate: (request, h) => { const req = request.raw.req; const authorization = req.headers.authorization; if (!authorization) { return Boom.unauthorized(null, 'Custom'); } const parts = authorization.split(/\s+/); if (parts.length !== 2) { return h.continue; // Error without error or credentials } const username = parts[1]; const credentials = settings.users[username]; if (!credentials) { throw Boom.unauthorized('Missing credentials', 'Custom'); } if (credentials === 'skip') { return h.unauthenticated(Boom.unauthorized(null, 'Custom')); } if (typeof credentials === 'string') { return h.response(credentials).takeover(); } credentials.user = credentials.user || null; return h.authenticated({ credentials, artifacts: settings.artifacts }); }, response: (request, h) => { if (request.auth.credentials.response) { throw request.auth.credentials.response; } return h.continue; } }; if (!settings || settings.payload !== false) { scheme.payload = (request, h) => { const result = request.auth.credentials.payload; if (!result) { return h.continue; } if (result.isBoom) { throw result; } return h.response(request.auth.credentials.payload).takeover(); }; } if (settings && settings.options) { scheme.options = settings.options; } return scheme; }; ================================================ FILE: test/common.js ================================================ 'use strict'; const ChildProcess = require('child_process'); const Http = require('http'); const Net = require('net'); const internals = {}; internals.hasLsof = () => { try { ChildProcess.execSync(`lsof -p ${process.pid}`, { stdio: 'ignore' }); } catch (err) { return false; } return true; }; internals.hasIPv6 = () => { const server = Http.createServer().listen(); const { address } = server.address(); server.close(); return Net.isIPv6(address); }; exports.hasLsof = internals.hasLsof(); exports.hasIPv6 = internals.hasIPv6(); ================================================ FILE: test/core.js ================================================ 'use strict'; const ChildProcess = require('child_process'); const Events = require('events'); const Fs = require('fs'); const Http = require('http'); const Https = require('https'); const Net = require('net'); const Os = require('os'); const Path = require('path'); const Stream = require('stream'); const TLS = require('tls'); const Boom = require('@hapi/boom'); const { Engine: CatboxMemory } = require('@hapi/catbox-memory'); const Code = require('@hapi/code'); const Handlebars = require('handlebars'); const Hapi = require('..'); const Hoek = require('@hapi/hoek'); const Inert = require('@hapi/inert'); const Lab = require('@hapi/lab'); const Teamwork = require('@hapi/teamwork'); const Vision = require('@hapi/vision'); const Wreck = require('@hapi/wreck'); const Common = require('./common'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('Core', () => { it('sets app settings defaults', () => { const server = Hapi.server(); expect(server.settings.app).to.equal({}); }); it('sets app settings', () => { const server = Hapi.server({ app: { message: 'test defaults' } }); expect(server.settings.app.message).to.equal('test defaults'); }); it('overrides mime settings', () => { const options = { mime: { override: { 'node/module': { source: 'steve', compressible: false, extensions: ['node', 'module', 'npm'], type: 'node/module' } } } }; const server = Hapi.server(options); expect(server.mime.path('file.npm').type).to.equal('node/module'); expect(server.mime.path('file.npm').source).to.equal('steve'); }); it('allows null port and host', () => { expect(() => { Hapi.server({ host: null, port: null }); }).to.not.throw(); }); it('does not throw when given a default authentication strategy', () => { expect(() => { Hapi.server({ routes: { auth: 'test' } }); }).not.to.throw(); }); it('throws when disabling autoListen and providing a port', () => { expect(() => { Hapi.server({ port: 80, autoListen: false }); }).to.throw('Cannot specify port when autoListen is false'); }); it('throws when disabling autoListen and providing special host', () => { expect(() => { Hapi.server({ port: '/a/b/hapi-server.socket', autoListen: false }); }).to.throw('Cannot specify port when autoListen is false'); }); it('defaults address to 0.0.0.0 or :: when no host is provided', async (flags) => { const server = Hapi.server(); await server.start(); flags.onCleanup = () => server.stop(); const expectedBoundAddress = Common.hasIPv6 ? '::' : '0.0.0.0'; expect(server.info.address).to.equal(expectedBoundAddress); }); it('is accessible on localhost when using default host', async (flags) => { // With hapi v20 this would fail on ipv6 machines on node v18+ due to DNS resolution changes in node (see nodejs/node#40537). // To address this in hapi v21 we bind to :: if available, otherwise the former default of 0.0.0.0. const server = Hapi.server(); server.route({ method: 'get', path: '/', handler: () => 'ok' }); await server.start(); flags.onCleanup = () => server.stop(); const req = Http.get(`http://localhost:${server.info.port}`); const [res] = await Events.once(req, 'response'); let result = ''; for await (const chunk of res) { result += chunk.toString(); } expect(result).to.equal('ok'); }); it('uses address when present instead of host', async (flags) => { const server = Hapi.server({ host: 'no.such.domain.hapi', address: 'localhost' }); await server.start(); flags.onCleanup = () => server.stop(); expect(server.info.host).to.equal('no.such.domain.hapi'); expect(server.info.address).to.match(/^127\.0\.0\.1|::1$/); // ::1 on node v18 with ipv6 support }); it('uses uri when present instead of host and port', async (flags) => { const server = Hapi.server({ host: 'no.such.domain.hapi', address: 'localhost', uri: 'http://uri.example.com:8080' }); expect(server.info.uri).to.equal('http://uri.example.com:8080'); await server.start(); flags.onCleanup = () => server.stop(); expect(server.info.host).to.equal('no.such.domain.hapi'); expect(server.info.address).to.match(/^127\.0\.0\.1|::1$/); // ::1 on node v18 with ipv6 support expect(server.info.uri).to.equal('http://uri.example.com:8080'); }); it('throws on uri ending with /', () => { expect(() => { Hapi.server({ uri: 'http://uri.example.com:8080/' }); }).to.throw(/Invalid server options/); }); it('creates a server listening on a unix domain socket', { skip: process.platform === 'win32' }, async () => { const port = Path.join(__dirname, 'hapi-server.socket'); if (Fs.existsSync(port)) { Fs.unlinkSync(port); } const server = Hapi.server({ port }); expect(server.type).to.equal('socket'); await server.start(); const absSocketPath = Path.resolve(port); expect(server.info.port).to.equal(absSocketPath); await server.stop(); if (Fs.existsSync(port)) { Fs.unlinkSync(port); } }); it('creates a server listening on a windows named pipe', async () => { const port = '\\\\.\\pipe\\6653e55f-26ec-4268-a4f2-882f4089315c'; const server = Hapi.server({ port }); expect(server.type).to.equal('socket'); await server.start(); expect(server.info.port).to.equal(port); await server.stop(); }); it('creates an https server when passed tls options', () => { const tlsOptions = { key: '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA0UqyXDCqWDKpoNQQK/fdr0OkG4gW6DUafxdufH9GmkX/zoKz\ng/SFLrPipzSGINKWtyMvo7mPjXqqVgE10LDI3VFV8IR6fnART+AF8CW5HMBPGt/s\nfQW4W4puvBHkBxWSW1EvbecgNEIS9hTGvHXkFzm4xJ2e9DHp2xoVAjREC73B7JbF\nhc5ZGGchKw+CFmAiNysU0DmBgQcac0eg2pWoT+YGmTeQj6sRXO67n2xy/hA1DuN6\nA4WBK3wM3O4BnTG0dNbWUEbe7yAbV5gEyq57GhJIeYxRvveVDaX90LoAqM4cUH06\n6rciON0UbDHV2LP/JaH5jzBjUyCnKLLo5snlbwIDAQABAoIBAQDJm7YC3pJJUcxb\nc8x8PlHbUkJUjxzZ5MW4Zb71yLkfRYzsxrTcyQA+g+QzA4KtPY8XrZpnkgm51M8e\n+B16AcIMiBxMC6HgCF503i16LyyJiKrrDYfGy2rTK6AOJQHO3TXWJ3eT3BAGpxuS\n12K2Cq6EvQLCy79iJm7Ks+5G6EggMZPfCVdEhffRm2Epl4T7LpIAqWiUDcDfS05n\nNNfAGxxvALPn+D+kzcSF6hpmCVrFVTf9ouhvnr+0DpIIVPwSK/REAF3Ux5SQvFuL\njPmh3bGwfRtcC5d21QNrHdoBVSN2UBLmbHUpBUcOBI8FyivAWJhRfKnhTvXMFG8L\nwaXB51IZAoGBAP/E3uz6zCyN7l2j09wmbyNOi1AKvr1WSmuBJveITouwblnRSdvc\nsYm4YYE0Vb94AG4n7JIfZLKtTN0xvnCo8tYjrdwMJyGfEfMGCQQ9MpOBXAkVVZvP\ne2k4zHNNsfvSc38UNSt7K0HkVuH5BkRBQeskcsyMeu0qK4wQwdtiCoBDAoGBANF7\nFMppYxSW4ir7Jvkh0P8bP/Z7AtaSmkX7iMmUYT+gMFB5EKqFTQjNQgSJxS/uHVDE\nSC5co8WGHnRk7YH2Pp+Ty1fHfXNWyoOOzNEWvg6CFeMHW2o+/qZd4Z5Fep6qCLaa\nFvzWWC2S5YslEaaP8DQ74aAX4o+/TECrxi0z2lllAoGAdRB6qCSyRsI/k4Rkd6Lv\nw00z3lLMsoRIU6QtXaZ5rN335Awyrfr5F3vYxPZbOOOH7uM/GDJeOJmxUJxv+cia\nPQDflpPJZU4VPRJKFjKcb38JzO6C3Gm+po5kpXGuQQA19LgfDeO2DNaiHZOJFrx3\nm1R3Zr/1k491lwokcHETNVkCgYBPLjrZl6Q/8BhlLrG4kbOx+dbfj/euq5NsyHsX\n1uI7bo1Una5TBjfsD8nYdUr3pwWltcui2pl83Ak+7bdo3G8nWnIOJ/WfVzsNJzj7\n/6CvUzR6sBk5u739nJbfgFutBZBtlSkDQPHrqA7j3Ysibl3ZIJlULjMRKrnj6Ans\npCDwkQKBgQCM7gu3p7veYwCZaxqDMz5/GGFUB1My7sK0hcT7/oH61yw3O8pOekee\nuctI1R3NOudn1cs5TAy/aypgLDYTUGQTiBRILeMiZnOrvQQB9cEf7TFgDoRNCcDs\nV/ZWiegVB/WY7H0BkCekuq5bHwjgtJTpvHGqQ9YD7RhE8RSYOhdQ/Q==\n-----END RSA PRIVATE KEY-----\n', cert: '-----BEGIN CERTIFICATE-----\nMIIDBjCCAe4CCQDvLNml6smHlTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJV\nUzETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0\ncyBQdHkgTHRkMB4XDTE0MDEyNTIxMjIxOFoXDTE1MDEyNTIxMjIxOFowRTELMAkG\nA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0\nIFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nANFKslwwqlgyqaDUECv33a9DpBuIFug1Gn8Xbnx/RppF/86Cs4P0hS6z4qc0hiDS\nlrcjL6O5j416qlYBNdCwyN1RVfCEen5wEU/gBfAluRzATxrf7H0FuFuKbrwR5AcV\nkltRL23nIDRCEvYUxrx15Bc5uMSdnvQx6dsaFQI0RAu9weyWxYXOWRhnISsPghZg\nIjcrFNA5gYEHGnNHoNqVqE/mBpk3kI+rEVzuu59scv4QNQ7jegOFgSt8DNzuAZ0x\ntHTW1lBG3u8gG1eYBMquexoSSHmMUb73lQ2l/dC6AKjOHFB9Ouq3IjjdFGwx1diz\n/yWh+Y8wY1Mgpyiy6ObJ5W8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAoSc6Skb4\ng1e0ZqPKXBV2qbx7hlqIyYpubCl1rDiEdVzqYYZEwmst36fJRRrVaFuAM/1DYAmT\nWMhU+yTfA+vCS4tql9b9zUhPw/IDHpBDWyR01spoZFBF/hE1MGNpCSXXsAbmCiVf\naxrIgR2DNketbDxkQx671KwF1+1JOMo9ffXp+OhuRo5NaGIxhTsZ+f/MA4y084Aj\nDI39av50sTRTWWShlN+J7PtdQVA5SZD97oYbeUeL7gI18kAJww9eUdmT0nEjcwKs\nxsQT1fyKbo7AlZBY4KSlUMuGnn0VnAsB9b+LxtXlDfnjyM8bVQx1uAfRo0DO8p/5\n3J5DTjAU55deBQ==\n-----END CERTIFICATE-----\n' }; const server = Hapi.server({ tls: tlsOptions }); expect(server.listener instanceof Https.Server).to.equal(true); }); it('uses a provided listener', async () => { const listener = Http.createServer(); const server = Hapi.server({ listener }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); await server.start(); const { payload } = await Wreck.get('http://localhost:' + server.info.port + '/'); expect(payload.toString()).to.equal('ok'); await server.stop(); }); it('uses a provided listener (TLS)', async () => { const listener = Http.createServer(); const server = Hapi.server({ listener, tls: true }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); await server.start(); expect(server.info.protocol).to.equal('https'); await server.stop(); }); it('uses a provided listener with manual listen', async () => { const listener = Http.createServer(); const server = Hapi.server({ listener, autoListen: false }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const listen = () => { return new Promise((resolve) => listener.listen(0, 'localhost', resolve)); }; await listen(); await server.start(); const { payload } = await Wreck.get('http://localhost:' + server.info.port + '/'); expect(payload.toString()).to.equal('ok'); await server.stop(); }); it('sets info.uri with default localhost when no hostname', () => { const orig = Os.hostname; Os.hostname = function () { Os.hostname = orig; return ''; }; const server = Hapi.server({ port: 80 }); expect(server.info.uri).to.equal('http://localhost:80'); }); it('sets info.uri without port when 0', () => { const server = Hapi.server({ host: 'example.com' }); expect(server.info.uri).to.equal('http://example.com'); }); it('closes connection on socket timeout', async () => { const server = Hapi.server({ routes: { timeout: { socket: 50 }, payload: { timeout: 45 } } }); server.route({ method: 'GET', path: '/', options: { handler: async (request) => { await Hoek.wait(70); return 'too late'; } } }); await server.start(); try { await Wreck.request('GET', 'http://localhost:' + server.info.port + '/'); } catch (err) { expect(err.message).to.equal('Client request error: socket hang up'); } await server.stop(); }); it('disables node socket timeout', async () => { const server = Hapi.server({ routes: { timeout: { socket: false } } }); server.route({ method: 'GET', path: '/', handler: () => null }); await server.start(); let timeout; const orig = Net.Socket.prototype.setTimeout; Net.Socket.prototype.setTimeout = function (...args) { timeout = 'gotcha'; Net.Socket.prototype.setTimeout = orig; return orig.apply(this, args); }; const res = await Wreck.request('GET', 'http://localhost:' + server.info.port + '/'); await Wreck.read(res); expect(timeout).to.equal('gotcha'); await server.stop(); }); it('throws on invalid config', () => { expect(() => { Hapi.server({ something: false }); }).to.throw(/Invalid server options/); }); it('combines configuration from server and defaults (cors)', () => { const server = Hapi.server({ routes: { cors: { origin: ['example.com'] } } }); expect(server.settings.routes.cors.origin).to.equal(['example.com']); }); it('combines configuration from server and defaults (security)', () => { const server = Hapi.server({ routes: { security: { hsts: 2, xss: false } } }); expect(server.settings.routes.security.hsts).to.equal(2); expect(server.settings.routes.security.xss).to.be.false(); expect(server.settings.routes.security.xframe).to.equal('deny'); expect(server.settings.routes.security.referrer).to.equal(false); }); describe('_debug()', () => { it('outputs 500 on ext exception', async () => { const server = Hapi.server(); const ext = async (request) => { await Hoek.wait(0); const not = null; not.here; }; server.ext('onPreHandler', ext); server.route({ method: 'GET', path: '/', handler: () => null }); const log = server.events.once({ name: 'request', channels: 'error' }); const orig = console.error; console.error = function (...args) { console.error = orig; expect(args[0]).to.equal('Debug:'); expect(args[1]).to.equal('internal, implementation, error'); }; const res = await server.inject('/'); expect(res.statusCode).to.equal(500); const [, event] = await log; expect(event.error.message).to.include(['Cannot read prop', 'null', 'here']); }); }); describe('_createCache()', () => { it('provisions cache using engine instance', async () => { // Config provision const engine = new CatboxMemory(); const server = Hapi.server({ cache: { engine, name: 'test1' } }); expect(server._core.caches.get('test1').client.connection).to.shallow.equal(engine); // Active provision await server.cache.provision({ engine, name: 'test2' }); expect(server._core.caches.get('test2').client.connection).to.shallow.equal(engine); // Active provision but indirect constructor const Provider = function (options) { this.settings = options; }; const ref = {}; await server.cache.provision({ provider: { constructor: Provider, options: { ref } }, name: 'test3' }); expect(server._core.caches.get('test3').client.connection.settings.ref).to.shallow.equal(ref); }); }); describe('start()', () => { it('starts and stops', async () => { const server = Hapi.server(); let started = 0; let stopped = 0; server.events.on('start', () => { ++started; }); server.events.on('stop', () => { ++stopped; }); await server.start(); expect(server._core.started).to.equal(true); await server.stop(); expect(server._core.started).to.equal(false); expect(started).to.equal(1); expect(stopped).to.equal(1); }); it('initializes, starts, and stops', async () => { const server = Hapi.server(); let started = 0; let stopped = 0; server.events.on('start', () => { ++started; }); server.events.on('stop', () => { ++stopped; }); await server.initialize(); await server.start(); expect(server._core.started).to.equal(true); await server.stop(); expect(server._core.started).to.equal(false); expect(started).to.equal(1); expect(stopped).to.equal(1); }); it('does not re-initialize the server', async () => { const server = Hapi.server(); await server.initialize(); await server.initialize(); }); it('returns connection start error', async () => { const server1 = Hapi.server(); await server1.start(); const port = server1.info.port; const server2 = Hapi.server({ port }); await expect(server2.start()).to.reject(/EADDRINUSE/); await server1.stop(); }); it('returns onPostStart error', async () => { const server = Hapi.server(); const postStart = function (srv) { throw new Error('boom'); }; server.ext('onPostStart', postStart); await expect(server.start()).to.reject('boom'); await server.stop(); expect(server.info.started).to.equal(0); }); it('errors on bad cache start', async () => { const cache = { engine: { start: function () { throw new Error('oops'); }, stop: function () { } } }; const server = Hapi.server({ cache }); await expect(server.start()).to.reject('oops'); }); it('fails to start server when registration incomplete', async () => { const plugin = { name: 'plugin', register: Hoek.ignore }; const server = Hapi.server(); server.register(plugin); await expect(server.start()).to.reject('Cannot start server before plugins finished registration'); }); it('fails to initialize server when not stopped', async () => { const plugin = function () { }; plugin.attributes = { name: 'plugin' }; const server = Hapi.server(); await server.start(); await expect(server.initialize()).to.reject('Cannot initialize server while it is in started phase'); await server.stop(); }); it('fails to start server when starting', async () => { const plugin = function () { }; plugin.attributes = { name: 'plugin' }; const server = Hapi.server(); const starting = server.start(); await expect(server.start()).to.reject('Cannot start server while it is in initializing phase'); await starting; await server.stop(); }); }); describe('stop()', () => { it('stops the cache', async () => { const server = Hapi.server(); const cache = server.cache({ segment: 'test', expiresIn: 1000 }); await server.initialize(); await cache.set('a', 'going in', 0); const value = await cache.get('a'); expect(value).to.equal('going in'); await server.stop(); await expect(cache.get('a')).to.reject(); }); it('returns an extension error (onPreStop)', async () => { const server = Hapi.server(); const preStop = function (srv) { throw new Error('failed cleanup'); }; server.ext('onPreStop', preStop); await server.start(); await expect(server.stop()).to.reject('failed cleanup'); }); it('returns an extension error (onPostStop)', async () => { const server = Hapi.server(); const postStop = function (srv) { throw new Error('failed cleanup'); }; server.ext('onPostStop', postStop); await server.start(); await expect(server.stop()).to.reject('failed cleanup'); }); it('returns an extension timeout (onPreStop)', async () => { const server = Hapi.server(); const preStop = function (srv) { return Hoek.block(); }; server.ext('onPreStop', preStop, { timeout: 100 }); await server.start(); await expect(server.stop()).to.reject('onPreStop timed out'); }); it('errors when stopping a stopping server', async () => { const server = Hapi.server(); const stopping = server.stop(); await expect(server.stop()).to.reject('Cannot stop server while in stopping phase'); await stopping; }); it('errors on bad cache stop', async () => { const cache = { engine: { start: function () { }, stop: function () { throw new Error('oops'); } } }; const server = Hapi.server({ cache }); await server.start(); await expect(server.stop()).to.reject('oops'); }); }); describe('_init()', () => { it('clears connections on close (HTTP)', async () => { const server = Hapi.server(); let count = 0; server.route({ method: 'GET', path: '/', handler: (request, h) => { ++count; return h.abandon; } }); await server.start(); const promise = Wreck.request('GET', `http://localhost:${server.info.port}/`, { rejectUnauthorized: false }); await Hoek.wait(50); const count1 = await internals.countConnections(server); expect(count1).to.equal(1); expect(server._core.sockets.size).to.equal(1); expect(count).to.equal(1); promise.req.destroy(); await expect(promise).to.reject(); await Hoek.wait(50); const count2 = await internals.countConnections(server); expect(count2).to.equal(0); expect(server._core.sockets.size).to.equal(0); expect(count).to.equal(1); await server.stop(); }); it('clears connections on close (HTTPS)', async () => { const tlsOptions = { key: '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA0UqyXDCqWDKpoNQQK/fdr0OkG4gW6DUafxdufH9GmkX/zoKz\ng/SFLrPipzSGINKWtyMvo7mPjXqqVgE10LDI3VFV8IR6fnART+AF8CW5HMBPGt/s\nfQW4W4puvBHkBxWSW1EvbecgNEIS9hTGvHXkFzm4xJ2e9DHp2xoVAjREC73B7JbF\nhc5ZGGchKw+CFmAiNysU0DmBgQcac0eg2pWoT+YGmTeQj6sRXO67n2xy/hA1DuN6\nA4WBK3wM3O4BnTG0dNbWUEbe7yAbV5gEyq57GhJIeYxRvveVDaX90LoAqM4cUH06\n6rciON0UbDHV2LP/JaH5jzBjUyCnKLLo5snlbwIDAQABAoIBAQDJm7YC3pJJUcxb\nc8x8PlHbUkJUjxzZ5MW4Zb71yLkfRYzsxrTcyQA+g+QzA4KtPY8XrZpnkgm51M8e\n+B16AcIMiBxMC6HgCF503i16LyyJiKrrDYfGy2rTK6AOJQHO3TXWJ3eT3BAGpxuS\n12K2Cq6EvQLCy79iJm7Ks+5G6EggMZPfCVdEhffRm2Epl4T7LpIAqWiUDcDfS05n\nNNfAGxxvALPn+D+kzcSF6hpmCVrFVTf9ouhvnr+0DpIIVPwSK/REAF3Ux5SQvFuL\njPmh3bGwfRtcC5d21QNrHdoBVSN2UBLmbHUpBUcOBI8FyivAWJhRfKnhTvXMFG8L\nwaXB51IZAoGBAP/E3uz6zCyN7l2j09wmbyNOi1AKvr1WSmuBJveITouwblnRSdvc\nsYm4YYE0Vb94AG4n7JIfZLKtTN0xvnCo8tYjrdwMJyGfEfMGCQQ9MpOBXAkVVZvP\ne2k4zHNNsfvSc38UNSt7K0HkVuH5BkRBQeskcsyMeu0qK4wQwdtiCoBDAoGBANF7\nFMppYxSW4ir7Jvkh0P8bP/Z7AtaSmkX7iMmUYT+gMFB5EKqFTQjNQgSJxS/uHVDE\nSC5co8WGHnRk7YH2Pp+Ty1fHfXNWyoOOzNEWvg6CFeMHW2o+/qZd4Z5Fep6qCLaa\nFvzWWC2S5YslEaaP8DQ74aAX4o+/TECrxi0z2lllAoGAdRB6qCSyRsI/k4Rkd6Lv\nw00z3lLMsoRIU6QtXaZ5rN335Awyrfr5F3vYxPZbOOOH7uM/GDJeOJmxUJxv+cia\nPQDflpPJZU4VPRJKFjKcb38JzO6C3Gm+po5kpXGuQQA19LgfDeO2DNaiHZOJFrx3\nm1R3Zr/1k491lwokcHETNVkCgYBPLjrZl6Q/8BhlLrG4kbOx+dbfj/euq5NsyHsX\n1uI7bo1Una5TBjfsD8nYdUr3pwWltcui2pl83Ak+7bdo3G8nWnIOJ/WfVzsNJzj7\n/6CvUzR6sBk5u739nJbfgFutBZBtlSkDQPHrqA7j3Ysibl3ZIJlULjMRKrnj6Ans\npCDwkQKBgQCM7gu3p7veYwCZaxqDMz5/GGFUB1My7sK0hcT7/oH61yw3O8pOekee\nuctI1R3NOudn1cs5TAy/aypgLDYTUGQTiBRILeMiZnOrvQQB9cEf7TFgDoRNCcDs\nV/ZWiegVB/WY7H0BkCekuq5bHwjgtJTpvHGqQ9YD7RhE8RSYOhdQ/Q==\n-----END RSA PRIVATE KEY-----\n', cert: '-----BEGIN CERTIFICATE-----\nMIIDBjCCAe4CCQDvLNml6smHlTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJV\nUzETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0\ncyBQdHkgTHRkMB4XDTE0MDEyNTIxMjIxOFoXDTE1MDEyNTIxMjIxOFowRTELMAkG\nA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0\nIFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nANFKslwwqlgyqaDUECv33a9DpBuIFug1Gn8Xbnx/RppF/86Cs4P0hS6z4qc0hiDS\nlrcjL6O5j416qlYBNdCwyN1RVfCEen5wEU/gBfAluRzATxrf7H0FuFuKbrwR5AcV\nkltRL23nIDRCEvYUxrx15Bc5uMSdnvQx6dsaFQI0RAu9weyWxYXOWRhnISsPghZg\nIjcrFNA5gYEHGnNHoNqVqE/mBpk3kI+rEVzuu59scv4QNQ7jegOFgSt8DNzuAZ0x\ntHTW1lBG3u8gG1eYBMquexoSSHmMUb73lQ2l/dC6AKjOHFB9Ouq3IjjdFGwx1diz\n/yWh+Y8wY1Mgpyiy6ObJ5W8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAoSc6Skb4\ng1e0ZqPKXBV2qbx7hlqIyYpubCl1rDiEdVzqYYZEwmst36fJRRrVaFuAM/1DYAmT\nWMhU+yTfA+vCS4tql9b9zUhPw/IDHpBDWyR01spoZFBF/hE1MGNpCSXXsAbmCiVf\naxrIgR2DNketbDxkQx671KwF1+1JOMo9ffXp+OhuRo5NaGIxhTsZ+f/MA4y084Aj\nDI39av50sTRTWWShlN+J7PtdQVA5SZD97oYbeUeL7gI18kAJww9eUdmT0nEjcwKs\nxsQT1fyKbo7AlZBY4KSlUMuGnn0VnAsB9b+LxtXlDfnjyM8bVQx1uAfRo0DO8p/5\n3J5DTjAU55deBQ==\n-----END CERTIFICATE-----\n' }; const server = Hapi.server({ tls: tlsOptions }); let count = 0; server.route({ method: 'GET', path: '/', handler: (request, h) => { ++count; return h.abandon; } }); await server.start(); const promise = Wreck.request('GET', `https://localhost:${server.info.port}/`, { rejectUnauthorized: false }); await Hoek.wait(100); const count1 = await internals.countConnections(server); expect(count1).to.equal(1); expect(server._core.sockets.size).to.equal(1); expect(count).to.equal(1); promise.req.destroy(); await expect(promise).to.reject(); await Hoek.wait(50); const count2 = await internals.countConnections(server); expect(count2).to.equal(0); expect(server._core.sockets.size).to.equal(0); expect(count).to.equal(1); await server.stop(); }); }); describe('_start()', () => { it('starts connection', async () => { const server = Hapi.server(); await server.start(); let expectedBoundAddress = '0.0.0.0'; if (Net.isIPv6(server.listener.address().address)) { expectedBoundAddress = '::'; } expect(server.info.host).to.equal(Os.hostname()); expect(server.info.address).to.equal(expectedBoundAddress); expect(server.info.port).to.be.a.number().and.above(1); await server.stop(); }); it('starts connection (tls)', async () => { const tlsOptions = { key: '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA0UqyXDCqWDKpoNQQK/fdr0OkG4gW6DUafxdufH9GmkX/zoKz\ng/SFLrPipzSGINKWtyMvo7mPjXqqVgE10LDI3VFV8IR6fnART+AF8CW5HMBPGt/s\nfQW4W4puvBHkBxWSW1EvbecgNEIS9hTGvHXkFzm4xJ2e9DHp2xoVAjREC73B7JbF\nhc5ZGGchKw+CFmAiNysU0DmBgQcac0eg2pWoT+YGmTeQj6sRXO67n2xy/hA1DuN6\nA4WBK3wM3O4BnTG0dNbWUEbe7yAbV5gEyq57GhJIeYxRvveVDaX90LoAqM4cUH06\n6rciON0UbDHV2LP/JaH5jzBjUyCnKLLo5snlbwIDAQABAoIBAQDJm7YC3pJJUcxb\nc8x8PlHbUkJUjxzZ5MW4Zb71yLkfRYzsxrTcyQA+g+QzA4KtPY8XrZpnkgm51M8e\n+B16AcIMiBxMC6HgCF503i16LyyJiKrrDYfGy2rTK6AOJQHO3TXWJ3eT3BAGpxuS\n12K2Cq6EvQLCy79iJm7Ks+5G6EggMZPfCVdEhffRm2Epl4T7LpIAqWiUDcDfS05n\nNNfAGxxvALPn+D+kzcSF6hpmCVrFVTf9ouhvnr+0DpIIVPwSK/REAF3Ux5SQvFuL\njPmh3bGwfRtcC5d21QNrHdoBVSN2UBLmbHUpBUcOBI8FyivAWJhRfKnhTvXMFG8L\nwaXB51IZAoGBAP/E3uz6zCyN7l2j09wmbyNOi1AKvr1WSmuBJveITouwblnRSdvc\nsYm4YYE0Vb94AG4n7JIfZLKtTN0xvnCo8tYjrdwMJyGfEfMGCQQ9MpOBXAkVVZvP\ne2k4zHNNsfvSc38UNSt7K0HkVuH5BkRBQeskcsyMeu0qK4wQwdtiCoBDAoGBANF7\nFMppYxSW4ir7Jvkh0P8bP/Z7AtaSmkX7iMmUYT+gMFB5EKqFTQjNQgSJxS/uHVDE\nSC5co8WGHnRk7YH2Pp+Ty1fHfXNWyoOOzNEWvg6CFeMHW2o+/qZd4Z5Fep6qCLaa\nFvzWWC2S5YslEaaP8DQ74aAX4o+/TECrxi0z2lllAoGAdRB6qCSyRsI/k4Rkd6Lv\nw00z3lLMsoRIU6QtXaZ5rN335Awyrfr5F3vYxPZbOOOH7uM/GDJeOJmxUJxv+cia\nPQDflpPJZU4VPRJKFjKcb38JzO6C3Gm+po5kpXGuQQA19LgfDeO2DNaiHZOJFrx3\nm1R3Zr/1k491lwokcHETNVkCgYBPLjrZl6Q/8BhlLrG4kbOx+dbfj/euq5NsyHsX\n1uI7bo1Una5TBjfsD8nYdUr3pwWltcui2pl83Ak+7bdo3G8nWnIOJ/WfVzsNJzj7\n/6CvUzR6sBk5u739nJbfgFutBZBtlSkDQPHrqA7j3Ysibl3ZIJlULjMRKrnj6Ans\npCDwkQKBgQCM7gu3p7veYwCZaxqDMz5/GGFUB1My7sK0hcT7/oH61yw3O8pOekee\nuctI1R3NOudn1cs5TAy/aypgLDYTUGQTiBRILeMiZnOrvQQB9cEf7TFgDoRNCcDs\nV/ZWiegVB/WY7H0BkCekuq5bHwjgtJTpvHGqQ9YD7RhE8RSYOhdQ/Q==\n-----END RSA PRIVATE KEY-----\n', cert: '-----BEGIN CERTIFICATE-----\nMIIDBjCCAe4CCQDvLNml6smHlTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJV\nUzETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0\ncyBQdHkgTHRkMB4XDTE0MDEyNTIxMjIxOFoXDTE1MDEyNTIxMjIxOFowRTELMAkG\nA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0\nIFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nANFKslwwqlgyqaDUECv33a9DpBuIFug1Gn8Xbnx/RppF/86Cs4P0hS6z4qc0hiDS\nlrcjL6O5j416qlYBNdCwyN1RVfCEen5wEU/gBfAluRzATxrf7H0FuFuKbrwR5AcV\nkltRL23nIDRCEvYUxrx15Bc5uMSdnvQx6dsaFQI0RAu9weyWxYXOWRhnISsPghZg\nIjcrFNA5gYEHGnNHoNqVqE/mBpk3kI+rEVzuu59scv4QNQ7jegOFgSt8DNzuAZ0x\ntHTW1lBG3u8gG1eYBMquexoSSHmMUb73lQ2l/dC6AKjOHFB9Ouq3IjjdFGwx1diz\n/yWh+Y8wY1Mgpyiy6ObJ5W8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAoSc6Skb4\ng1e0ZqPKXBV2qbx7hlqIyYpubCl1rDiEdVzqYYZEwmst36fJRRrVaFuAM/1DYAmT\nWMhU+yTfA+vCS4tql9b9zUhPw/IDHpBDWyR01spoZFBF/hE1MGNpCSXXsAbmCiVf\naxrIgR2DNketbDxkQx671KwF1+1JOMo9ffXp+OhuRo5NaGIxhTsZ+f/MA4y084Aj\nDI39av50sTRTWWShlN+J7PtdQVA5SZD97oYbeUeL7gI18kAJww9eUdmT0nEjcwKs\nxsQT1fyKbo7AlZBY4KSlUMuGnn0VnAsB9b+LxtXlDfnjyM8bVQx1uAfRo0DO8p/5\n3J5DTjAU55deBQ==\n-----END CERTIFICATE-----\n' }; const server = Hapi.server({ host: '0.0.0.0', port: 0, tls: tlsOptions }); await server.start(); expect(server.info.host).to.equal('0.0.0.0'); expect(server.info.port).to.not.equal(0); await server.stop(); }); it('sets info with defaults when missing hostname and address', () => { const hostname = Os.hostname; Os.hostname = function () { Os.hostname = hostname; return ''; }; const server = Hapi.server({ port: '8000' }); expect(server.info.host).to.equal('localhost'); expect(server.info.uri).to.equal('http://localhost:8000'); }); it('ignored repeated calls', async () => { const server = Hapi.server(); await server.start(); await server.start(); await server.stop(); }); }); describe('_stop()', () => { it('waits to stop until all connections are closed (HTTP)', async () => { const server = Hapi.server(); await server.start(); const socket1 = await internals.socket(server); const socket2 = await internals.socket(server); await Hoek.wait(50); const count1 = await internals.countConnections(server); expect(count1).to.equal(2); expect(server._core.sockets.size).to.equal(2); const stop = server.stop(); socket1.end(); socket2.end(); await stop; await Hoek.wait(10); const count2 = await internals.countConnections(server); expect(count2).to.equal(0); expect(server._core.sockets.size).to.equal(0); }); it('waits to stop until all connections are closed (HTTPS)', async () => { const tlsOptions = { key: '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA0UqyXDCqWDKpoNQQK/fdr0OkG4gW6DUafxdufH9GmkX/zoKz\ng/SFLrPipzSGINKWtyMvo7mPjXqqVgE10LDI3VFV8IR6fnART+AF8CW5HMBPGt/s\nfQW4W4puvBHkBxWSW1EvbecgNEIS9hTGvHXkFzm4xJ2e9DHp2xoVAjREC73B7JbF\nhc5ZGGchKw+CFmAiNysU0DmBgQcac0eg2pWoT+YGmTeQj6sRXO67n2xy/hA1DuN6\nA4WBK3wM3O4BnTG0dNbWUEbe7yAbV5gEyq57GhJIeYxRvveVDaX90LoAqM4cUH06\n6rciON0UbDHV2LP/JaH5jzBjUyCnKLLo5snlbwIDAQABAoIBAQDJm7YC3pJJUcxb\nc8x8PlHbUkJUjxzZ5MW4Zb71yLkfRYzsxrTcyQA+g+QzA4KtPY8XrZpnkgm51M8e\n+B16AcIMiBxMC6HgCF503i16LyyJiKrrDYfGy2rTK6AOJQHO3TXWJ3eT3BAGpxuS\n12K2Cq6EvQLCy79iJm7Ks+5G6EggMZPfCVdEhffRm2Epl4T7LpIAqWiUDcDfS05n\nNNfAGxxvALPn+D+kzcSF6hpmCVrFVTf9ouhvnr+0DpIIVPwSK/REAF3Ux5SQvFuL\njPmh3bGwfRtcC5d21QNrHdoBVSN2UBLmbHUpBUcOBI8FyivAWJhRfKnhTvXMFG8L\nwaXB51IZAoGBAP/E3uz6zCyN7l2j09wmbyNOi1AKvr1WSmuBJveITouwblnRSdvc\nsYm4YYE0Vb94AG4n7JIfZLKtTN0xvnCo8tYjrdwMJyGfEfMGCQQ9MpOBXAkVVZvP\ne2k4zHNNsfvSc38UNSt7K0HkVuH5BkRBQeskcsyMeu0qK4wQwdtiCoBDAoGBANF7\nFMppYxSW4ir7Jvkh0P8bP/Z7AtaSmkX7iMmUYT+gMFB5EKqFTQjNQgSJxS/uHVDE\nSC5co8WGHnRk7YH2Pp+Ty1fHfXNWyoOOzNEWvg6CFeMHW2o+/qZd4Z5Fep6qCLaa\nFvzWWC2S5YslEaaP8DQ74aAX4o+/TECrxi0z2lllAoGAdRB6qCSyRsI/k4Rkd6Lv\nw00z3lLMsoRIU6QtXaZ5rN335Awyrfr5F3vYxPZbOOOH7uM/GDJeOJmxUJxv+cia\nPQDflpPJZU4VPRJKFjKcb38JzO6C3Gm+po5kpXGuQQA19LgfDeO2DNaiHZOJFrx3\nm1R3Zr/1k491lwokcHETNVkCgYBPLjrZl6Q/8BhlLrG4kbOx+dbfj/euq5NsyHsX\n1uI7bo1Una5TBjfsD8nYdUr3pwWltcui2pl83Ak+7bdo3G8nWnIOJ/WfVzsNJzj7\n/6CvUzR6sBk5u739nJbfgFutBZBtlSkDQPHrqA7j3Ysibl3ZIJlULjMRKrnj6Ans\npCDwkQKBgQCM7gu3p7veYwCZaxqDMz5/GGFUB1My7sK0hcT7/oH61yw3O8pOekee\nuctI1R3NOudn1cs5TAy/aypgLDYTUGQTiBRILeMiZnOrvQQB9cEf7TFgDoRNCcDs\nV/ZWiegVB/WY7H0BkCekuq5bHwjgtJTpvHGqQ9YD7RhE8RSYOhdQ/Q==\n-----END RSA PRIVATE KEY-----\n', cert: '-----BEGIN CERTIFICATE-----\nMIIDBjCCAe4CCQDvLNml6smHlTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJV\nUzETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0\ncyBQdHkgTHRkMB4XDTE0MDEyNTIxMjIxOFoXDTE1MDEyNTIxMjIxOFowRTELMAkG\nA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0\nIFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nANFKslwwqlgyqaDUECv33a9DpBuIFug1Gn8Xbnx/RppF/86Cs4P0hS6z4qc0hiDS\nlrcjL6O5j416qlYBNdCwyN1RVfCEen5wEU/gBfAluRzATxrf7H0FuFuKbrwR5AcV\nkltRL23nIDRCEvYUxrx15Bc5uMSdnvQx6dsaFQI0RAu9weyWxYXOWRhnISsPghZg\nIjcrFNA5gYEHGnNHoNqVqE/mBpk3kI+rEVzuu59scv4QNQ7jegOFgSt8DNzuAZ0x\ntHTW1lBG3u8gG1eYBMquexoSSHmMUb73lQ2l/dC6AKjOHFB9Ouq3IjjdFGwx1diz\n/yWh+Y8wY1Mgpyiy6ObJ5W8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAoSc6Skb4\ng1e0ZqPKXBV2qbx7hlqIyYpubCl1rDiEdVzqYYZEwmst36fJRRrVaFuAM/1DYAmT\nWMhU+yTfA+vCS4tql9b9zUhPw/IDHpBDWyR01spoZFBF/hE1MGNpCSXXsAbmCiVf\naxrIgR2DNketbDxkQx671KwF1+1JOMo9ffXp+OhuRo5NaGIxhTsZ+f/MA4y084Aj\nDI39av50sTRTWWShlN+J7PtdQVA5SZD97oYbeUeL7gI18kAJww9eUdmT0nEjcwKs\nxsQT1fyKbo7AlZBY4KSlUMuGnn0VnAsB9b+LxtXlDfnjyM8bVQx1uAfRo0DO8p/5\n3J5DTjAU55deBQ==\n-----END CERTIFICATE-----\n' }; const server = Hapi.server({ tls: tlsOptions }); await server.start(); const socket1 = await internals.socket(server, 'tls'); const socket2 = await internals.socket(server, 'tls'); await Hoek.wait(50); const count1 = await internals.countConnections(server); expect(count1).to.equal(2); expect(server._core.sockets.size).to.equal(2); const stop = server.stop(); socket1.end(); socket2.end(); await stop; await Hoek.wait(10); const count2 = await internals.countConnections(server); expect(count2).to.equal(0); expect(server._core.sockets.size).to.equal(0); }); it('immediately destroys unhandled connections', async () => { const server = Hapi.server(); await server.start(); await internals.socket(server); await internals.socket(server); await Hoek.wait(50); const count1 = await internals.countConnections(server); expect(count1).to.equal(2); const timer = new Hoek.Bench(); await server.stop({ timeout: 100 }); expect(timer.elapsed()).to.be.at.most(110); }); it('waits to destroy handled connections until after the timeout', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.abandon }); await server.start(); const socket = await internals.socket(server); socket.write('GET / HTTP/1.0\r\nHost: test\r\n\r\n'); await Hoek.wait(10); const count1 = await internals.countConnections(server); expect(count1).to.equal(1); const timer = new Hoek.Bench(); await server.stop({ timeout: 20 }); expect(timer.elapsed()).to.be.at.least(19); }); it('waits to destroy connections if they close by themselves', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.abandon }); await server.start(); const socket = await internals.socket(server); socket.write('GET / HTTP/1.0\r\nHost: test\r\n\r\n'); await Hoek.wait(10); const count1 = await internals.countConnections(server); expect(count1).to.equal(1); setTimeout(() => socket.end(), 100); const timer = new Hoek.Bench(); await server.stop({ timeout: 400 }); expect(timer.elapsed()).to.be.below(300); }); it('immediately destroys idle keep-alive connections', { retry: true }, async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => null }); await server.start(); const socket = await internals.socket(server); socket.write('GET / HTTP/1.1\r\nHost: test\r\nConnection: Keep-Alive\r\n\r\n\r\n'); await new Promise((resolve) => socket.on('data', resolve)); const count = await internals.countConnections(server); expect(count).to.equal(1); const timer = new Hoek.Bench(); await server.stop({ timeout: 20 }); expect(timer.elapsed()).to.be.at.most(20); }); it('waits to stop until connections close by themselves when cleanStop is disabled', async () => { const server = Hapi.server({ operations: { cleanStop: false } }); server.route({ method: 'GET', path: '/', handler: (request, h) => h.abandon }); await server.start(); const socket = await internals.socket(server); socket.write('GET / HTTP/1.0\r\nHost: test\r\n\r\n'); await Hoek.wait(10); const count1 = await internals.countConnections(server); expect(count1).to.equal(1); setTimeout(() => socket.end(), 100); const stop = server.stop(); await Hoek.wait(50); const count2 = await internals.countConnections(server); expect(count2).to.equal(1); await Hoek.wait(200); const count3 = await internals.countConnections(server); expect(count3).to.equal(0); await stop; }); it('refuses to handle new incoming requests on persistent connections', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); await server.start(); const agent = new Http.Agent({ keepAlive: true, maxSockets: 1 }); const first = Wreck.get('http://localhost:' + server.info.port + '/', { agent }); const second = Wreck.get('http://localhost:' + server.info.port + '/', { agent }); const { res, payload } = await first; const stop = server.stop(); const err = await expect(second).to.reject(Error); await stop; await Hoek.wait(10); expect(res.headers.connection).to.equal('keep-alive'); expect(payload.toString()).to.equal('ok'); expect(err.code).to.equal('ECONNRESET'); expect(server._core.started).to.equal(false); }); it('allows incoming requests during the stopping phase', async () => { const team = new Teamwork.Team(); const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); server.ext('onPreStop', () => team.work); await server.start(); const stop = server.stop(); const { res, payload } = await Wreck.get(`http://localhost:${server.info.port}`); team.attend(); // Allow server to finalize stop await stop; expect(res.headers.connection).to.equal('close'); expect(payload.toString()).to.equal('ok'); expect(server._core.started).to.equal(false); }); it('finishes in-progress requests and ends connection', async () => { let stop; const handler = async (request) => { stop = server.stop({ timeout: 200 }); await Hoek.wait(0); return 'ok'; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); await server.start(); const agent = new Http.Agent({ keepAlive: true, maxSockets: 1 }); const first = Wreck.get('http://localhost:' + server.info.port + '/', { agent }); const second = Wreck.get('http://localhost:' + server.info.port + '/404', { agent }); const { res, payload } = await first; expect(res.headers.connection).to.equal('close'); expect(payload.toString()).to.equal('ok'); await expect(second).to.reject(); await expect(stop).to.not.reject(); }); it('does not close longpoll HTTPS requests before response (if within timeout)', async () => { const tlsOptions = { key: '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA0UqyXDCqWDKpoNQQK/fdr0OkG4gW6DUafxdufH9GmkX/zoKz\ng/SFLrPipzSGINKWtyMvo7mPjXqqVgE10LDI3VFV8IR6fnART+AF8CW5HMBPGt/s\nfQW4W4puvBHkBxWSW1EvbecgNEIS9hTGvHXkFzm4xJ2e9DHp2xoVAjREC73B7JbF\nhc5ZGGchKw+CFmAiNysU0DmBgQcac0eg2pWoT+YGmTeQj6sRXO67n2xy/hA1DuN6\nA4WBK3wM3O4BnTG0dNbWUEbe7yAbV5gEyq57GhJIeYxRvveVDaX90LoAqM4cUH06\n6rciON0UbDHV2LP/JaH5jzBjUyCnKLLo5snlbwIDAQABAoIBAQDJm7YC3pJJUcxb\nc8x8PlHbUkJUjxzZ5MW4Zb71yLkfRYzsxrTcyQA+g+QzA4KtPY8XrZpnkgm51M8e\n+B16AcIMiBxMC6HgCF503i16LyyJiKrrDYfGy2rTK6AOJQHO3TXWJ3eT3BAGpxuS\n12K2Cq6EvQLCy79iJm7Ks+5G6EggMZPfCVdEhffRm2Epl4T7LpIAqWiUDcDfS05n\nNNfAGxxvALPn+D+kzcSF6hpmCVrFVTf9ouhvnr+0DpIIVPwSK/REAF3Ux5SQvFuL\njPmh3bGwfRtcC5d21QNrHdoBVSN2UBLmbHUpBUcOBI8FyivAWJhRfKnhTvXMFG8L\nwaXB51IZAoGBAP/E3uz6zCyN7l2j09wmbyNOi1AKvr1WSmuBJveITouwblnRSdvc\nsYm4YYE0Vb94AG4n7JIfZLKtTN0xvnCo8tYjrdwMJyGfEfMGCQQ9MpOBXAkVVZvP\ne2k4zHNNsfvSc38UNSt7K0HkVuH5BkRBQeskcsyMeu0qK4wQwdtiCoBDAoGBANF7\nFMppYxSW4ir7Jvkh0P8bP/Z7AtaSmkX7iMmUYT+gMFB5EKqFTQjNQgSJxS/uHVDE\nSC5co8WGHnRk7YH2Pp+Ty1fHfXNWyoOOzNEWvg6CFeMHW2o+/qZd4Z5Fep6qCLaa\nFvzWWC2S5YslEaaP8DQ74aAX4o+/TECrxi0z2lllAoGAdRB6qCSyRsI/k4Rkd6Lv\nw00z3lLMsoRIU6QtXaZ5rN335Awyrfr5F3vYxPZbOOOH7uM/GDJeOJmxUJxv+cia\nPQDflpPJZU4VPRJKFjKcb38JzO6C3Gm+po5kpXGuQQA19LgfDeO2DNaiHZOJFrx3\nm1R3Zr/1k491lwokcHETNVkCgYBPLjrZl6Q/8BhlLrG4kbOx+dbfj/euq5NsyHsX\n1uI7bo1Una5TBjfsD8nYdUr3pwWltcui2pl83Ak+7bdo3G8nWnIOJ/WfVzsNJzj7\n/6CvUzR6sBk5u739nJbfgFutBZBtlSkDQPHrqA7j3Ysibl3ZIJlULjMRKrnj6Ans\npCDwkQKBgQCM7gu3p7veYwCZaxqDMz5/GGFUB1My7sK0hcT7/oH61yw3O8pOekee\nuctI1R3NOudn1cs5TAy/aypgLDYTUGQTiBRILeMiZnOrvQQB9cEf7TFgDoRNCcDs\nV/ZWiegVB/WY7H0BkCekuq5bHwjgtJTpvHGqQ9YD7RhE8RSYOhdQ/Q==\n-----END RSA PRIVATE KEY-----\n', cert: '-----BEGIN CERTIFICATE-----\nMIIDBjCCAe4CCQDvLNml6smHlTANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJV\nUzETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0\ncyBQdHkgTHRkMB4XDTE0MDEyNTIxMjIxOFoXDTE1MDEyNTIxMjIxOFowRTELMAkG\nA1UEBhMCVVMxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0\nIFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nANFKslwwqlgyqaDUECv33a9DpBuIFug1Gn8Xbnx/RppF/86Cs4P0hS6z4qc0hiDS\nlrcjL6O5j416qlYBNdCwyN1RVfCEen5wEU/gBfAluRzATxrf7H0FuFuKbrwR5AcV\nkltRL23nIDRCEvYUxrx15Bc5uMSdnvQx6dsaFQI0RAu9weyWxYXOWRhnISsPghZg\nIjcrFNA5gYEHGnNHoNqVqE/mBpk3kI+rEVzuu59scv4QNQ7jegOFgSt8DNzuAZ0x\ntHTW1lBG3u8gG1eYBMquexoSSHmMUb73lQ2l/dC6AKjOHFB9Ouq3IjjdFGwx1diz\n/yWh+Y8wY1Mgpyiy6ObJ5W8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAoSc6Skb4\ng1e0ZqPKXBV2qbx7hlqIyYpubCl1rDiEdVzqYYZEwmst36fJRRrVaFuAM/1DYAmT\nWMhU+yTfA+vCS4tql9b9zUhPw/IDHpBDWyR01spoZFBF/hE1MGNpCSXXsAbmCiVf\naxrIgR2DNketbDxkQx671KwF1+1JOMo9ffXp+OhuRo5NaGIxhTsZ+f/MA4y084Aj\nDI39av50sTRTWWShlN+J7PtdQVA5SZD97oYbeUeL7gI18kAJww9eUdmT0nEjcwKs\nxsQT1fyKbo7AlZBY4KSlUMuGnn0VnAsB9b+LxtXlDfnjyM8bVQx1uAfRo0DO8p/5\n3J5DTjAU55deBQ==\n-----END CERTIFICATE-----\n' }; const server = Hapi.server({ tls: tlsOptions }); let stop; const handler = async (request) => { stop = server.stop({ timeout: 200 }); await Hoek.wait(150); return 'ok'; }; server.route({ method: 'GET', path: '/', handler }); await server.start(); const agent = new Https.Agent({ keepAlive: true, maxSockets: 1, rejectUnauthorized: false }); const { res, payload } = await Wreck.get('https://localhost:' + server.info.port + '/', { agent }); expect(res.headers.connection).to.equal('close'); expect(payload.toString()).to.equal('ok'); await stop; }); it('removes connection event listeners after it stops', async () => { const server = Hapi.server(); const initial = server.listener.listeners('connection').length; await server.start(); expect(server.listener.listeners('connection').length).to.be.greaterThan(initial); await server.stop(); await server.start(); await server.stop(); expect(server.listener.listeners('connection').length).to.equal(initial); }); it('ignores repeated calls', async () => { const server = Hapi.server(); await server.stop(); await server.stop(); }); it('emits a closing event before the server\'s listener close event is emitted', async () => { const server = Hapi.server(); const events = []; server.events.on('closing', () => events.push('closing')); server.events.on('stop', () => events.push('stop')); server._core.listener.on('close', () => events.push('close')); await server.start(); await server.stop(); expect(events).to.equal(['closing', 'close', 'stop']); }); it('emits a closing event before the close event when there is an active request being processed', async () => { const server = Hapi.server(); const events = []; let stop; const handler = async () => { stop = server.stop({ timeout: 200 }); await Hoek.wait(0); return 'ok'; }; server.route({ method: 'GET', path: '/', handler }); server.events.on('closing', () => events.push('closing')); server.events.on('stop', () => events.push('stop')); server._core.listener.on('close', () => events.push('close')); await server.start(); const agent = new Http.Agent({ keepAlive: true, maxSockets: 1 }); // ongoing active request const first = Wreck.get('http://localhost:' + server.info.port + '/', { agent }); // denied incoming request const second = Wreck.get('http://localhost:' + server.info.port + '/', { agent }); const { res, payload } = await first; expect(res.headers.connection).to.equal('close'); expect(payload.toString()).to.equal('ok'); await expect(second).to.reject(); await expect(stop).to.not.reject(); expect(events).to.equal(['closing', 'close', 'stop']); }); }); describe('_dispatch()', () => { it('rejects request due to high rss load', async () => { const server = Hapi.server({ load: { sampleInterval: 5, maxRssBytes: 1 } }); let buffer; const handler = (request) => { buffer = buffer || Buffer.alloc(2048); return 'ok'; }; const log = server.events.once('log'); server.route({ method: 'GET', path: '/', handler }); await server.start(); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(200); await Hoek.wait(10); const res2 = await server.inject('/'); expect(res2.statusCode).to.equal(503); const [event, tags] = await log; expect(event.channel).to.equal('internal'); expect(event.data.rss > 10000).to.equal(true); expect(tags.load).to.be.true(); await server.stop(); }); it('doesn\'t setup listeners for cleanStop when socket is missing', async () => { const server = Hapi.server(); server.route({ method: 'get', path: '/', handler: (request) => request.raw.res.listenerCount('finish') }); const { result: normalFinishCount } = await server.inject('/'); const { _dispatch } = server._core; server._core._dispatch = (opts) => { const fn = _dispatch.call(server._core, opts); return (req, res) => { req.socket = null; fn(req, res); }; }; const { result: missingSocketFinishCount } = await server.inject('/'); expect(missingSocketFinishCount).to.be.lessThan(normalFinishCount); }); }); describe('inject()', () => { it('keeps the options.credentials object untouched', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => null }); const options = { url: '/', auth: { credentials: { foo: 'bar' }, strategy: 'test' } }; const res = await server.inject(options); expect(res.statusCode).to.equal(204); expect(options.auth.credentials).to.exist(); }); it('sets credentials (with host header)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => null }); const options = { url: '/', auth: { credentials: { foo: 'bar' }, strategy: 'test' }, headers: { host: 'something' } }; const res = await server.inject(options); expect(res.statusCode).to.equal(204); expect(options.auth.credentials).to.exist(); }); it('sets credentials (with authority)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.headers.host }); const options = { url: '/', authority: 'something', auth: { credentials: { foo: 'bar' }, strategy: 'test' } }; const res = await server.inject(options); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('something'); expect(options.auth.credentials).to.exist(); }); it('sets authority', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.headers.host }); const options = { url: '/', authority: 'something' }; const res = await server.inject(options); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('something'); }); it('passes the options.artifacts object', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.artifacts }); const options = { url: '/', auth: { credentials: { foo: 'bar' }, artifacts: { bar: 'baz' }, strategy: 'test' } }; const res = await server.inject(options); expect(res.statusCode).to.equal(200); expect(res.result.bar).to.equal('baz'); expect(options.auth.artifacts).to.exist(); }); it('sets `request.auth.isInjected = true` when `auth` option is defined', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.auth.isInjected }); const options = { url: '/', auth: { credentials: { foo: 'bar' }, strategy: 'test' } }; const res = await server.inject(options); expect(res.statusCode).to.equal(200); expect(res.result).to.be.true(); }); it('sets `request.isInjected = true` for requests created via `server.inject`', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.isInjected }); const options = { url: '/' }; const res = await server.inject(options); expect(res.statusCode).to.equal(200); expect(res.result).to.be.true(); }); it('`request.isInjected` access is read-only', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => { const illegalAssignment = () => { request.isInjected = false; }; expect(illegalAssignment).to.throw('Cannot set property isInjected of [object Object] which has only a getter'); return request.isInjected; } }); const options = { url: '/' }; const res = await server.inject(options); expect(res.statusCode).to.equal(200); expect(res.result).to.be.true(); }); it('sets `request.isInjected = false` for normal request', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.isInjected }); await server.start(); const { payload } = await Wreck.get(`http://localhost:${server.info.port}/`); expect(payload.toString()).to.equal('false'); await server.stop(); }); it('sets app settings', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.app.x }); const options = { url: '/', authority: 'x', // For coverage app: { x: 123 } }; const res = await server.inject(options); expect(res.statusCode).to.equal(200); expect(res.result).to.equal(123); }); it('sets plugins settings', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.plugins.x.y }); const options = { url: '/', authority: 'x', // For coverage plugins: { x: { y: 123 } } }; const res = await server.inject(options); expect(res.statusCode).to.equal(200); expect(res.result).to.equal(123); }); it('returns the request object', async () => { const handler = (request) => { request.app.key = 'value'; return null; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); expect(res.request.app.key).to.equal('value'); }); it('returns the request object for POST', async () => { const payload = { foo: true }; const handler = (request) => { return request.payload; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler }); const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.statusCode).to.equal(200); expect(JSON.parse(res.payload)).to.equal(payload); }); it('returns the request string for POST', async () => { const payload = JSON.stringify({ foo: true }); const handler = (request) => { return request.payload; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler }); const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.statusCode).to.equal(200); expect(res.payload).to.equal(payload); }); it('returns the request stream for POST', async () => { const param = { foo: true }; const payload = new Stream.Readable(); payload.push(JSON.stringify(param)); payload.push(null); const handler = (request) => { return request.payload; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler }); const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.statusCode).to.equal(200); expect(JSON.parse(res.payload)).to.equal(param); }); it('can set a client remoteAddress', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.info.remoteAddress }); const res = await server.inject({ url: '/', remoteAddress: '1.2.3.4' }); expect(res.statusCode).to.equal(200); expect(res.payload).to.equal('1.2.3.4'); }); it('sets a default remoteAddress of 127.0.0.1', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.info.remoteAddress }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.payload).to.equal('127.0.0.1'); }); it('sets correct host header', async () => { const server = Hapi.server({ host: 'example.com', port: 2080 }); server.route({ method: 'GET', path: '/', handler: (request) => request.headers.host }); const res = await server.inject('/'); expect(res.result).to.equal('example.com:2080'); }); }); describe('table()', () => { it('returns an array of the current routes', () => { const server = Hapi.server(); server.route({ path: '/test/', method: 'get', handler: () => null }); server.route({ path: '/test/{p}/end', method: 'get', handler: () => null }); const routes = server.table(); expect(routes.length).to.equal(2); expect(routes[0].path).to.equal('/test/'); }); it('combines global and vhost routes', () => { const server = Hapi.server(); server.route({ path: '/test/', method: 'get', handler: () => null }); server.route({ path: '/test/', vhost: 'one.example.com', method: 'get', handler: () => null }); server.route({ path: '/test/', vhost: 'two.example.com', method: 'get', handler: () => null }); server.route({ path: '/test/{p}/end', method: 'get', handler: () => null }); const routes = server.table(); expect(routes.length).to.equal(4); }); it('combines global and vhost routes and filters based on host', () => { const server = Hapi.server(); server.route({ path: '/test/', method: 'get', handler: () => null }); server.route({ path: '/test/', vhost: 'one.example.com', method: 'get', handler: () => null }); server.route({ path: '/test/', vhost: 'two.example.com', method: 'get', handler: () => null }); server.route({ path: '/test/{p}/end', method: 'get', handler: () => null }); const routes = server.table('one.example.com'); expect(routes.length).to.equal(3); }); it('accepts a list of hosts', () => { const server = Hapi.server(); server.route({ path: '/test/', method: 'get', handler: () => null }); server.route({ path: '/test/', vhost: 'one.example.com', method: 'get', handler: () => null }); server.route({ path: '/test/', vhost: 'two.example.com', method: 'get', handler: () => null }); server.route({ path: '/test/{p}/end', method: 'get', handler: () => null }); const routes = server.table(['one.example.com', 'two.example.com']); expect(routes.length).to.equal(4); }); it('ignores unknown host', () => { const server = Hapi.server(); server.route({ path: '/test/', method: 'get', handler: () => null }); server.route({ path: '/test/', vhost: 'one.example.com', method: 'get', handler: () => null }); server.route({ path: '/test/', vhost: 'two.example.com', method: 'get', handler: () => null }); server.route({ path: '/test/{p}/end', method: 'get', handler: () => null }); const routes = server.table('three.example.com'); expect(routes.length).to.equal(2); }); }); describe('ext()', () => { it('supports adding an array of methods', async () => { const server = Hapi.server(); server.ext('onPreHandler', [ (request, h) => { request.app.x = '1'; return h.continue; }, (request, h) => { request.app.x += '2'; return h.continue; } ]); server.route({ method: 'GET', path: '/', handler: (request) => request.app.x }); const res = await server.inject('/'); expect(res.result).to.equal('12'); }); it('sets bind via options', async () => { const server = Hapi.server(); const preHandler = function (request, h) { request.app.x = this.y; return h.continue; }; server.ext('onPreHandler', preHandler, { bind: { y: 42 } }); server.route({ method: 'GET', path: '/', handler: (request) => request.app.x }); const res = await server.inject('/'); expect(res.result).to.equal(42); }); it('uses server views for ext added via server', async () => { const server = Hapi.server(); await server.register(Vision); server.views({ engines: { html: Handlebars }, path: __dirname + '/templates' }); const preHandler = (request, h) => { return h.view('test').takeover(); }; server.ext('onPreHandler', preHandler); const test = { name: 'test', register: function (plugin, options) { plugin.views({ engines: { html: Handlebars }, path: './no_such_directory_found' }); plugin.route({ path: '/view', method: 'GET', handler: () => null }); } }; await server.register(test); const res = await server.inject('/view'); expect(res.statusCode).to.equal(200); }); it('supports toolkit decorators on empty result', async () => { const server = Hapi.server(); const onRequest = (request, h) => { return h.response().redirect('/elsewhere').takeover(); }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.statusCode).to.equal(302); expect(res.headers.location).to.equal('/elsewhere'); }); it('supports direct toolkit decorators', async () => { const server = Hapi.server(); const onRequest = (request, h) => { return h.redirect('/elsewhere').takeover(); }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.statusCode).to.equal(302); expect(res.headers.location).to.equal('/elsewhere'); }); it('skips extensions once takeover is called', async () => { const server = Hapi.server(); const preResponse1 = (request, h) => { return h.response(1).takeover(); }; server.ext('onPreResponse', preResponse1); let called = false; const preResponse2 = (request) => { called = true; return 2; }; server.ext('onPreResponse', preResponse2); server.route({ method: 'GET', path: '/', handler: () => 0 }); const res = await server.inject({ method: 'GET', url: '/' }); expect(res.result).to.equal(1); expect(called).to.be.false(); }); it('executes all extensions with return values', async () => { const server = Hapi.server(); server.ext('onPreResponse', () => 1); let called = false; const preResponse2 = (request) => { called = true; return 2; }; server.ext('onPreResponse', preResponse2); server.route({ method: 'GET', path: '/', handler: () => 0 }); const res = await server.inject({ method: 'GET', url: '/' }); expect(res.result).to.equal(2); expect(called).to.be.true(); }); describe('onRequest', () => { it('replies with custom response', async () => { const server = Hapi.server(); const onRequest = (request) => { throw Boom.badRequest('boom'); }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.statusCode).to.equal(400); expect(res.result.message).to.equal('boom'); }); it('replies with a view', async () => { const server = Hapi.server(); await server.register(Vision); server.views({ engines: { 'html': Handlebars }, path: __dirname + '/templates' }); const onRequest = (request, h) => { return h.view('test', { message: 'hola!' }).takeover(); }; server.ext('onRequest', onRequest); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject('/'); expect(res.result).to.match(/
\r?\n

hola!<\/h1>\r?\n<\/div>\r?\n/); }); }); describe('onPreResponse', () => { it('replies with custom response', async () => { const server = Hapi.server(); const preRequest = (request, h) => { if (typeof request.response.source === 'string') { throw Boom.badRequest('boom'); } return h.continue; }; server.ext('onPreResponse', preRequest); server.route({ method: 'GET', path: '/text', handler: () => 'ok' }); server.route({ method: 'GET', path: '/obj', handler: () => ({ status: 'ok' }) }); const res1 = await server.inject({ method: 'GET', url: '/text' }); expect(res1.result.message).to.equal('boom'); const res2 = await server.inject({ method: 'GET', url: '/obj' }); expect(res2.result.status).to.equal('ok'); }); it('intercepts 404 responses', async () => { const server = Hapi.server(); const preResponse = (request, h) => { return h.response(request.response.output.statusCode).takeover(); }; server.ext('onPreResponse', preResponse); const res = await server.inject({ method: 'GET', url: '/missing' }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal(404); }); it('intercepts 404 when using directory handler and file is missing', async () => { const server = Hapi.server(); await server.register(Inert); const preResponse = (request) => { const response = request.response; return { isBoom: response.isBoom }; }; server.ext('onPreResponse', preResponse); server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './somewhere', listing: false, index: true } } }); const res = await server.inject('/missing'); expect(res.statusCode).to.equal(200); expect(res.result.isBoom).to.equal(true); }); it('intercepts 404 when using file handler and file is missing', async () => { const server = Hapi.server(); await server.register(Inert); const preResponse = (request) => { const response = request.response; return { isBoom: response.isBoom }; }; server.ext('onPreResponse', preResponse); server.route({ method: 'GET', path: '/{path*}', handler: { file: './somewhere/something.txt' } }); const res = await server.inject('/missing'); expect(res.statusCode).to.equal(200); expect(res.result.isBoom).to.equal(true); }); it('cleans unused file stream when response is overridden', { skip: !Common.hasLsof }, async () => { const server = Hapi.server(); await server.register(Inert); const preResponse = (request) => { return { something: 'else' }; }; server.ext('onPreResponse', preResponse); server.route({ method: 'GET', path: '/{path*}', handler: { directory: { path: './' } } }); const res = await server.inject('/package.json'); expect(res.statusCode).to.equal(200); expect(res.result.something).to.equal('else'); await new Promise((resolve) => { const cmd = ChildProcess.spawn('lsof', ['-p', process.pid]); let lsof = ''; cmd.stdout.on('data', (buffer) => { lsof += buffer.toString(); }); cmd.stdout.on('end', () => { let count = 0; const lines = lsof.split('\n'); for (let i = 0; i < lines.length; ++i) { count += !!lines[i].match(/package.json/); } expect(count).to.equal(0); resolve(); }); cmd.stdin.end(); }); }); it('executes multiple extensions', async () => { const server = Hapi.server(); const preResponse1 = (request, h) => { request.response.source = request.response.source + '1'; return h.continue; }; server.ext('onPreResponse', preResponse1); const preResponse2 = (request, h) => { request.response.source = request.response.source + '2'; return h.continue; }; server.ext('onPreResponse', preResponse2); server.route({ method: 'GET', path: '/', handler: () => '0' }); const res = await server.inject({ method: 'GET', url: '/' }); expect(res.result).to.equal('012'); }); }); }); describe('route()', () => { it('emits route event', async () => { const server = Hapi.server(); const log = server.events.once('route'); server.route({ method: 'GET', path: '/', handler: () => null }); const [route] = await log; expect(route.path).to.equal('/'); }); it('overrides the default notFound handler', async () => { const server = Hapi.server(); server.route({ method: '*', path: '/{p*}', handler: () => 'found' }); const res = await server.inject({ method: 'GET', url: '/page' }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('found'); }); it('responds to HEAD requests for a GET route', async () => { const handler = (request, h) => { return h.response('ok').etag('test').code(205); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res1 = await server.inject({ method: 'GET', url: '/' }); expect(res1.statusCode).to.equal(205); expect(res1.headers['content-type']).to.equal('text/html; charset=utf-8'); expect(res1.headers['content-length']).to.equal(2); expect(res1.headers.etag).to.equal('"test"'); expect(res1.result).to.equal('ok'); const res2 = await server.inject({ method: 'HEAD', url: '/' }); expect(res2.statusCode).to.equal(res1.statusCode); expect(res2.headers['content-type']).to.equal(res1.headers['content-type']); expect(res2.headers['content-length']).to.equal(res1.headers['content-length']); expect(res2.headers.etag).to.equal(res1.headers.etag); expect(res2.result).to.not.exist(); }); it('returns 404 on HEAD requests for non-GET routes', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: () => 'ok' }); const res1 = await server.inject({ method: 'HEAD', url: '/' }); expect(res1.statusCode).to.equal(404); expect(res1.result).to.not.exist(); const res2 = await server.inject({ method: 'HEAD', url: '/not-there' }); expect(res2.statusCode).to.equal(404); expect(res2.result).to.not.exist(); }); it('returns 500 on HEAD requests for failed responses', async () => { const preResponse = (request, h) => { request.response._processors.marshal = function (response, callback) { process.nextTick(callback, new Error('boom!')); }; return h.continue; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); server.ext('onPreResponse', preResponse); const res1 = await server.inject({ method: 'GET', url: '/' }); expect(res1.statusCode).to.equal(500); expect(res1.result).to.exist(); const res2 = await server.inject({ method: 'HEAD', url: '/' }); expect(res2.statusCode).to.equal(res1.statusCode); expect(res2.headers['content-type']).to.equal(res1.headers['content-type']); expect(res2.headers['content-length']).to.equal(res1.headers['content-length']); expect(res2.result).to.not.exist(); }); it('allows methods array', async () => { const server = Hapi.server(); const config = { method: ['GET', 'PUT', 'POST', 'DELETE'], path: '/', handler: (request) => request.route.method }; server.route(config); expect(config.method).to.equal(['GET', 'PUT', 'POST', 'DELETE']); // Ensure config is cloned const res1 = await server.inject({ method: 'HEAD', url: '/' }); expect(res1.statusCode).to.equal(200); const res2 = await server.inject({ method: 'GET', url: '/' }); expect(res2.statusCode).to.equal(200); expect(res2.payload).to.equal('get'); const res3 = await server.inject({ method: 'PUT', url: '/' }); expect(res3.statusCode).to.equal(200); expect(res3.payload).to.equal('put'); const res4 = await server.inject({ method: 'POST', url: '/' }); expect(res4.statusCode).to.equal(200); expect(res4.payload).to.equal('post'); const res5 = await server.inject({ method: 'DELETE', url: '/' }); expect(res5.statusCode).to.equal(200); expect(res5.payload).to.equal('delete'); }); it('adds routes using single and array methods', () => { const server = Hapi.server(); server.route([ { method: 'GET', path: '/api/products', handler: () => null }, { method: 'GET', path: '/api/products/{id}', handler: () => null }, { method: 'POST', path: '/api/products', handler: () => null }, { method: ['PUT', 'PATCH'], path: '/api/products/{id}', handler: () => null }, { method: 'DELETE', path: '/api/products/{id}', handler: () => null } ]); const table = server.table(); const paths = table.map((route) => { const obj = { method: route.method, path: route.path }; return obj; }); expect(table).to.have.length(6); expect(paths).to.only.include([ { method: 'get', path: '/api/products' }, { method: 'get', path: '/api/products/{id}' }, { method: 'post', path: '/api/products' }, { method: 'put', path: '/api/products/{id}' }, { method: 'patch', path: '/api/products/{id}' }, { method: 'delete', path: '/api/products/{id}' } ]); }); it('throws on methods array with id', () => { const server = Hapi.server(); expect(() => { server.route({ method: ['GET', 'PUT', 'POST', 'DELETE'], path: '/', options: { id: 'abc', handler: (request) => request.route.method } }); }).to.throw('Route id abc for path / conflicts with existing path /'); }); }); describe('_defaultRoutes()', () => { it('returns 404 when making a request to a route that does not exist', async () => { const server = Hapi.server(); const res = await server.inject({ method: 'GET', url: '/nope' }); expect(res.statusCode).to.equal(404); }); it('returns 400 on bad request', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/a/{p}', handler: () => null }); const res = await server.inject('/a/%'); expect(res.statusCode).to.equal(400); }); }); describe('load', () => { it('measures loop delay', async () => { const server = Hapi.server({ load: { sampleInterval: 4 } }); const handler = (request) => { const start = Date.now(); while (Date.now() - start < 5) { } return 'ok'; }; server.route({ method: 'GET', path: '/', handler }); await server.start(); await server.inject('/'); expect(server.load.eventLoopDelay).to.be.below(7); await Hoek.wait(0); await server.inject('/'); expect(server.load.eventLoopDelay).to.be.above(0); await Hoek.wait(0); await server.inject('/'); expect(server.load.eventLoopDelay).to.be.above(0); expect(server.load.eventLoopUtilization).to.be.above(0); expect(server.load.heapUsed).to.be.above(1024 * 1024); expect(server.load.rss).to.be.above(1024 * 1024); await server.stop(); }); }); }); internals.countConnections = function (server) { return new Promise((resolve, reject) => { server.listener.getConnections((err, count) => { return (err ? reject(err) : resolve(count)); }); }); }; internals.socket = function (server, mode) { const socket = new Net.Socket(); socket.on('error', Hoek.ignore); if (mode === 'tls') { socket.connect(server.info.port, '127.0.0.1'); return new Promise((resolve) => TLS.connect({ socket, rejectUnauthorized: false }, () => resolve(socket))); } return new Promise((resolve) => socket.connect(server.info.port, '127.0.0.1', () => resolve(socket))); }; ================================================ FILE: test/cors.js ================================================ 'use strict'; const Boom = require('@hapi/boom'); const Code = require('@hapi/code'); const Hapi = require('..'); const Lab = require('@hapi/lab'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('CORS', () => { it('returns 404 on OPTIONS when cors disabled', async () => { const server = Hapi.server({ routes: { cors: false } }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res.statusCode).to.equal(404); }); it('returns OPTIONS response', async () => { const handler = function () { throw Boom.badRequest(); }; const server = Hapi.server({ routes: { cors: true } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res.headers['access-control-allow-origin']).to.equal('http://example.com/'); }); it('returns OPTIONS response (server config)', async () => { const handler = function () { throw Boom.badRequest(); }; const server = Hapi.server({ routes: { cors: true } }); server.route({ method: 'GET', path: '/x', handler }); const res = await server.inject({ method: 'OPTIONS', url: '/x', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res.headers['access-control-allow-origin']).to.equal('http://example.com/'); }); it('returns headers on single route', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/a', handler: () => 'ok', options: { cors: true } }); server.route({ method: 'GET', path: '/b', handler: () => 'ok' }); const res1 = await server.inject({ method: 'OPTIONS', url: '/a', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res1.statusCode).to.equal(200); expect(res1.result).to.be.null(); expect(res1.headers['access-control-allow-origin']).to.equal('http://example.com/'); const res2 = await server.inject({ method: 'OPTIONS', url: '/b', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res2.statusCode).to.equal(200); expect(res2.result.message).to.equal('CORS is disabled for this route'); expect(res2.headers['access-control-allow-origin']).to.not.exist(); }); it('allows headers on multiple routes but not all', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/a', handler: () => 'ok', options: { cors: true } }); server.route({ method: 'GET', path: '/b', handler: () => 'ok', options: { cors: true } }); server.route({ method: 'GET', path: '/c', handler: () => 'ok' }); const res1 = await server.inject({ method: 'OPTIONS', url: '/a', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res1.statusCode).to.equal(200); expect(res1.result).to.be.null(); expect(res1.headers['access-control-allow-origin']).to.equal('http://example.com/'); const res2 = await server.inject({ method: 'OPTIONS', url: '/b', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res2.statusCode).to.equal(200); expect(res2.result).to.be.null(); expect(res2.headers['access-control-allow-origin']).to.equal('http://example.com/'); const res3 = await server.inject({ method: 'OPTIONS', url: '/c', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res3.statusCode).to.equal(200); expect(res3.result.message).to.equal('CORS is disabled for this route'); expect(res3.headers['access-control-allow-origin']).to.not.exist(); }); it('allows same headers on multiple routes with same path', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/a', handler: () => 'ok', options: { cors: true } }); server.route({ method: 'POST', path: '/a', handler: () => 'ok', options: { cors: true } }); const res = await server.inject({ method: 'OPTIONS', url: '/a', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.be.null(); expect(res.headers['access-control-allow-origin']).to.equal('http://example.com/'); }); it('returns headers on single route (overrides defaults)', async () => { const server = Hapi.server({ routes: { cors: { origin: ['b'] } } }); server.route({ method: 'GET', path: '/a', handler: () => 'ok', options: { cors: { origin: ['a'] } } }); server.route({ method: 'GET', path: '/b', handler: () => 'ok' }); const res1 = await server.inject({ method: 'OPTIONS', url: '/a', headers: { origin: 'a', 'access-control-request-method': 'GET' } }); expect(res1.statusCode).to.equal(200); expect(res1.result).to.be.null(); expect(res1.headers['access-control-allow-origin']).to.equal('a'); const res2 = await server.inject({ method: 'OPTIONS', url: '/b', headers: { origin: 'b', 'access-control-request-method': 'GET' } }); expect(res2.statusCode).to.equal(200); expect(res2.result).to.be.null(); expect(res2.headers['access-control-allow-origin']).to.equal('b'); }); it('sets access-control-allow-credentials header', async () => { const server = Hapi.server({ routes: { cors: { credentials: true } } }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject({ url: '/', headers: { origin: 'http://example.com/' } }); expect(res.statusCode).to.equal(204); expect(res.result).to.equal(null); expect(res.headers['access-control-allow-credentials']).to.equal('true'); }); it('combines server defaults with route config', async () => { const server = Hapi.server({ routes: { cors: { origin: ['http://example.com/'] } } }); server.route({ method: 'GET', path: '/', handler: () => null, options: { cors: { credentials: true } } }); const res1 = await server.inject({ url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res1.statusCode).to.equal(204); expect(res1.result).to.equal(null); expect(res1.headers['access-control-allow-credentials']).to.equal('true'); const res2 = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res2.statusCode).to.equal(200); expect(res2.result).to.equal(null); expect(res2.headers['access-control-allow-credentials']).to.equal('true'); const res3 = await server.inject({ url: '/', headers: { origin: 'http://example.org/', 'access-control-request-method': 'GET' } }); expect(res3.statusCode).to.equal(204); expect(res3.result).to.equal(null); expect(res3.headers['access-control-allow-credentials']).to.not.exist(); const res4 = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.org/', 'access-control-request-method': 'GET' } }); expect(res4.statusCode).to.equal(200); expect(res4.result).to.equal({ message: 'CORS error: Origin not allowed' }); expect(res4.headers['access-control-allow-credentials']).to.not.exist(); expect(res4.headers['access-control-allow-origin']).to.not.exist(); }); it('handles request without origin header', async () => { const server = Hapi.server({ port: 8080, routes: { cors: { origin: ['http://*.domain.com'] } } }); server.route({ method: 'GET', path: '/test', handler: () => null }); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(404); expect(res1.headers['access-control-allow-origin']).to.not.exist(); const res2 = await server.inject('/test'); expect(res2.statusCode).to.equal(204); expect(res2.headers['access-control-allow-origin']).to.not.exist(); }); it('handles missing routes', async () => { const server = Hapi.server({ port: 8080, routes: { cors: { origin: ['http://*.domain.com'] } } }); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(404); expect(res1.headers['access-control-allow-origin']).to.not.exist(); const res2 = await server.inject({ url: '/', headers: { origin: 'http://example.domain.com' } }); expect(res2.statusCode).to.equal(404); expect(res2.headers['access-control-allow-origin']).to.exist(); }); it('uses server defaults in onRequest', async () => { const server = Hapi.server({ port: 8080, routes: { cors: { origin: ['http://*.domain.com'] } } }); server.ext('onRequest', (request, h) => { expect(request.info.cors).to.be.null(); // Do not set potentially incorrect information return h.response('skip').takeover(); }); const res1 = await server.inject({ url: '/', headers: { origin: 'http://example.domain.com' } }); expect(res1.statusCode).to.equal(200); expect(res1.headers['access-control-allow-origin']).to.exist(); const res2 = await server.inject({ url: '/', headers: { origin: 'http://example.domain.net' } }); expect(res2.statusCode).to.equal(200); expect(res2.headers['access-control-allow-origin']).to.not.exist(); }); describe('headers()', () => { it('returns CORS origin (route level)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => 'ok', options: { cors: true } }); const res1 = await server.inject({ url: '/', headers: { origin: 'http://example.com/' } }); expect(res1.statusCode).to.equal(200); expect(res1.result).to.exist(); expect(res1.result).to.equal('ok'); expect(res1.headers['access-control-allow-origin']).to.equal('http://example.com/'); const res2 = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res2.statusCode).to.equal(200); expect(res2.result).to.be.null(); expect(res2.headers['access-control-allow-origin']).to.equal('http://example.com/'); }); it('returns CORS origin (GET)', async () => { const server = Hapi.server({ routes: { cors: { origin: ['http://x.example.com', 'http://www.example.com'] } } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ url: '/', headers: { origin: 'http://x.example.com' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.exist(); expect(res.result).to.equal('ok'); expect(res.headers['access-control-allow-origin']).to.equal('http://x.example.com'); }); it('returns CORS origin (OPTIONS)', async () => { const server = Hapi.server({ routes: { cors: { origin: ['http://test.example.com', 'http://www.example.com'] } } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://test.example.com', 'access-control-request-method': 'GET' } }); expect(res.statusCode).to.equal(200); expect(res.payload.length).to.equal(0); expect(res.headers['access-control-allow-origin']).to.equal('http://test.example.com'); }); it('merges CORS access-control-expose-headers header', async () => { const handler = (request, h) => { return h.response('ok').header('access-control-expose-headers', 'something'); }; const server = Hapi.server({ routes: { cors: { additionalExposedHeaders: ['xyz'] } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { origin: 'http://example.com/' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.exist(); expect(res.result).to.equal('ok'); expect(res.headers['access-control-expose-headers']).to.equal('something,WWW-Authenticate,Server-Authorization,xyz'); }); it('returns no CORS headers when route CORS disabled', async () => { const server = Hapi.server({ routes: { cors: { origin: ['http://test.example.com', 'http://www.example.com'] } } }); server.route({ method: 'GET', path: '/', handler: () => 'ok', options: { cors: false } }); const res = await server.inject({ url: '/', headers: { origin: 'http://x.example.com' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.exist(); expect(res.result).to.equal('ok'); expect(res.headers['access-control-allow-origin']).to.not.exist(); }); it('returns matching CORS origin', async () => { const handler = (request, h) => { return h.response('Tada').header('vary', 'x-test'); }; const server = Hapi.server({ compression: { minBytes: 1 }, routes: { cors: { origin: ['http://test.example.com', 'http://www.example.com', 'http://*.a.com'] } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { origin: 'http://www.example.com' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.exist(); expect(res.result).to.equal('Tada'); expect(res.headers['access-control-allow-origin']).to.equal('http://www.example.com'); expect(res.headers.vary).to.equal('x-test,origin,accept-encoding'); }); it('returns origin header when matching against *', async () => { const handler = (request, h) => { return h.response('Tada').header('vary', 'x-test'); }; const server = Hapi.server({ compression: { minBytes: 1 }, routes: { cors: { origin: ['*'] } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { origin: 'http://www.example.com' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.exist(); expect(res.result).to.equal('Tada'); expect(res.headers['access-control-allow-origin']).to.equal('http://www.example.com'); expect(res.headers.vary).to.equal('x-test,origin,accept-encoding'); }); it('returns * origin header when matching against * and origin is ignored', async () => { const handler = (request, h) => { return h.response('Tada').header('vary', 'x-test'); }; const server = Hapi.server({ compression: { minBytes: 1 }, routes: { cors: { origin: 'ignore' } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { origin: 'http://www.example.com' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.exist(); expect(res.result).to.equal('Tada'); expect(res.headers['access-control-allow-origin']).to.equal('*'); expect(res.headers.vary).to.equal('x-test,accept-encoding'); }); it('returns matching CORS origin wildcard', async () => { const handler = (request, h) => { return h.response('Tada').header('vary', 'x-test'); }; const server = Hapi.server({ compression: { minBytes: 1 }, routes: { cors: { origin: ['http://test.example.com', 'http://www.example.com', 'http://*.a.com'] } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { origin: 'http://www.a.com' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.exist(); expect(res.result).to.equal('Tada'); expect(res.headers['access-control-allow-origin']).to.equal('http://www.a.com'); expect(res.headers.vary).to.equal('x-test,origin,accept-encoding'); }); it('returns matching CORS origin wildcard when more than one wildcard', async () => { const handler = (request, h) => { return h.response('Tada').header('vary', 'x-test', true); }; const server = Hapi.server({ compression: { minBytes: 1 }, routes: { cors: { origin: ['http://test.example.com', 'http://www.example.com', 'http://*.b.com', 'http://*.a.com'] } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { origin: 'http://www.a.com' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.exist(); expect(res.result).to.equal('Tada'); expect(res.headers['access-control-allow-origin']).to.equal('http://www.a.com'); expect(res.headers.vary).to.equal('x-test,origin,accept-encoding'); }); it('does not set empty CORS expose headers', async () => { const server = Hapi.server({ routes: { cors: { exposedHeaders: [] } } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res1 = await server.inject({ url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res1.statusCode).to.equal(200); expect(res1.headers['access-control-allow-origin']).to.equal('http://example.com/'); expect(res1.headers['access-control-expose-headers']).to.not.exist(); const res2 = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res2.statusCode).to.equal(200); expect(res2.headers['access-control-allow-origin']).to.equal('http://example.com/'); expect(res2.headers['access-control-expose-headers']).to.not.exist(); }); }); describe('options()', () => { it('ignores OPTIONS route', () => { const server = Hapi.server(); server.route({ method: 'OPTIONS', path: '/', handler: () => null }); expect(server._core.router.special.options).to.not.exist(); }); }); describe('handler()', () => { it('errors on missing origin header', async () => { const server = Hapi.server({ routes: { cors: true } }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { 'access-control-request-method': 'GET' } }); expect(res.statusCode).to.equal(404); expect(res.result.message).to.equal('CORS error: Missing Origin header'); }); it('errors on missing access-control-request-method header', async () => { const server = Hapi.server({ routes: { cors: true } }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.com/' } }); expect(res.statusCode).to.equal(404); expect(res.result.message).to.equal('CORS error: Missing Access-Control-Request-Method header'); }); it('errors on missing route', async () => { const server = Hapi.server({ routes: { cors: true } }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res.statusCode).to.equal(404); }); it('errors on mismatching origin header', async () => { const server = Hapi.server({ routes: { cors: { origin: ['a'] } } }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res.statusCode).to.equal(200); expect(res.result.message).to.equal('CORS error: Origin not allowed'); }); it('matches a wildcard origin if origin is ignored and present', async () => { const server = Hapi.server({ routes: { cors: { origin: 'ignore' } } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://test.example.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'Authorization' } }); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-origin']).to.equal('*'); }); it('matches a wildcard origin if origin is ignored and missing', async () => { const server = Hapi.server({ routes: { cors: { origin: 'ignore' } } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { 'access-control-request-method': 'GET', 'access-control-request-headers': 'Authorization' } }); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-origin']).to.equal('*'); }); it('matches allowed headers', async () => { const server = Hapi.server({ routes: { cors: true } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://test.example.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'Authorization' } }); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-headers']).to.equal('Accept,Authorization,Content-Type,If-None-Match'); }); it('matches allowed headers (case insensitive)', async () => { const server = Hapi.server({ routes: { cors: true } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://test.example.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'authorization' } }); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-headers']).to.equal('Accept,Authorization,Content-Type,If-None-Match'); }); it('matches allowed headers (Origin explicit)', async () => { const server = Hapi.server({ routes: { cors: { additionalHeaders: ['Origin'] } } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://test.example.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'Origin' } }); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-headers']).to.equal('Accept,Authorization,Content-Type,If-None-Match,Origin'); expect(res.headers['access-control-expose-headers']).to.equal('WWW-Authenticate,Server-Authorization'); }); it('responds with configured preflight status code', async () => { const server = Hapi.server({ routes: { cors: { preflightStatusCode: 204 } } }); server.route({ method: 'GET', path: '/204', handler: () => 'ok', options: { cors: true } }); server.route({ method: 'GET', path: '/200', handler: () => 'ok', options: { cors: { preflightStatusCode: 200 } } }); const res1 = await server.inject({ method: 'OPTIONS', url: '/204', headers: { origin: 'http://test.example.com', 'access-control-request-method': 'GET' } }); expect(res1.statusCode).to.equal(204); const res2 = await server.inject({ method: 'OPTIONS', url: '/200', headers: { origin: 'http://test.example.com', 'access-control-request-method': 'GET' } }); expect(res2.statusCode).to.equal(200); }); it('matches allowed headers (Origin implicit)', async () => { const server = Hapi.server({ routes: { cors: true } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://test.example.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'Origin' } }); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-headers']).to.equal('Accept,Authorization,Content-Type,If-None-Match'); }); it('errors on disallowed headers', async () => { const server = Hapi.server({ routes: { cors: true } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://test.example.com', 'access-control-request-method': 'GET', 'access-control-request-headers': 'X' } }); expect(res.statusCode).to.equal(200); expect(res.result.message).to.equal('CORS error: Some headers are not allowed'); }); it('allows credentials', async () => { const server = Hapi.server({ routes: { cors: { credentials: true } } }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject({ method: 'OPTIONS', url: '/', headers: { origin: 'http://example.com/', 'access-control-request-method': 'GET' } }); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-credentials']).to.equal('true'); }); it('correctly finds route when using vhost setting', async () => { const server = Hapi.server({ routes: { cors: true } }); server.route({ method: 'POST', vhost: 'example.com', path: '/', handler: () => null }); const res = await server.inject({ method: 'OPTIONS', url: 'http://example.com:4000/', headers: { origin: 'http://localhost', 'access-control-request-method': 'POST' } }); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-methods']).to.equal('POST'); }); }); describe('headers()', () => { it('skips CORS when missing origin header and wildcard does not ignore origin', async () => { const server = Hapi.server({ routes: { cors: { origin: ['*'] } } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-origin']).to.not.exist(); }); it('uses CORS when missing origin header and wildcard ignores origin', async () => { const server = Hapi.server({ routes: { cors: { origin: 'ignore' } } }); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['access-control-allow-origin']).to.equal('*'); }); }); }); ================================================ FILE: test/file/note.txt ================================================ Test ================================================ FILE: test/handler.js ================================================ 'use strict'; const Boom = require('@hapi/boom'); const Code = require('@hapi/code'); const Hapi = require('..'); const Hoek = require('@hapi/hoek'); const Lab = require('@hapi/lab'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('handler', () => { describe('execute()', () => { it('bypasses onPostHandler when handler calls takeover()', async () => { const server = Hapi.server(); server.ext('onPostHandler', () => 'else'); server.route({ method: 'GET', path: '/', handler: (request, h) => 'something' }); server.route({ method: 'GET', path: '/takeover', handler: (request, h) => h.response('something').takeover() }); const res1 = await server.inject('/'); expect(res1.result).to.equal('else'); const res2 = await server.inject('/takeover'); expect(res2.result).to.equal('something'); }); it('returns 500 on handler exception (same tick)', async () => { const server = Hapi.server({ debug: false }); const handler = (request) => { const a = null; a.b.c; }; server.route({ method: 'GET', path: '/domain', handler }); const res = await server.inject('/domain'); expect(res.statusCode).to.equal(500); }); it('returns 500 on handler exception (next tick await)', async () => { const handler = async (request) => { await Hoek.wait(0); const not = null; not.here; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const log = server.events.once({ name: 'request', channels: 'error' }); const orig = console.error; console.error = function (...args) { console.error = orig; expect(args[0]).to.equal('Debug:'); expect(args[1]).to.equal('internal, implementation, error'); }; const res = await server.inject('/'); expect(res.statusCode).to.equal(500); const [, event] = await log; expect(event.error.message).to.include(['Cannot read prop', 'null', 'here']); }); }); describe('handler()', () => { it('binds handler to route bind object', async () => { const item = { x: 123 }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { handler: function (request) { return this.x; }, bind: item } }); const res = await server.inject('/'); expect(res.result).to.equal(item.x); }); it('binds handler to route bind object (toolkit)', async () => { const item = { x: 123 }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { handler: (request, h) => h.context.x, bind: item } }); const res = await server.inject('/'); expect(res.result).to.equal(item.x); }); it('returns 500 on ext method exception (same tick)', async () => { const server = Hapi.server({ debug: false }); const onRequest = function () { const a = null; a.b.c; }; server.ext('onRequest', onRequest); server.route({ method: 'GET', path: '/domain', handler: () => 'neven gonna happen' }); const res = await server.inject('/domain'); expect(res.statusCode).to.equal(500); }); it('returns 500 on custom function error', async () => { const server = Hapi.server({ debug: false }); const onPreHandler = function (request, h) { request.app.custom = () => { throw new Error('oops'); }; return h.continue; }; server.ext('onPreHandler', onPreHandler); server.route({ method: 'GET', path: '/', handler: (request) => request.app.custom() }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); }); describe('prerequisitesConfig()', () => { it('shows the complete prerequisite pipeline in the response', async () => { const pre1 = (request, h) => { return h.response('Hello').code(444); }; const pre2 = (request) => { return request.pre.m1 + request.pre.m3 + request.pre.m4; }; const pre3 = async (request) => { await Hoek.wait(0); return ' '; }; const pre4 = () => 'World'; const pre5 = (request) => { return request.pre.m2 + (request.pre.m0 === null ? '!' : 'x'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ { method: (request, h) => h.continue, assign: 'm0' }, [ { method: pre1, assign: 'm1' }, { method: pre3, assign: 'm3' }, { method: pre4, assign: 'm4' } ], { method: pre2, assign: 'm2' }, { method: pre5, assign: 'm5' } ], handler: (request) => request.pre.m5 } }); const res = await server.inject('/'); expect(res.result).to.equal('Hello World!'); }); it('allows a single prerequisite', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ { method: () => 'Hello', assign: 'p' } ], handler: (request) => request.pre.p } }); const res = await server.inject('/'); expect(res.result).to.equal('Hello'); }); it('allows an empty prerequisite array', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [], handler: () => 'Hello' } }); const res = await server.inject('/'); expect(res.result).to.equal('Hello'); }); it('takes over response', async () => { const pre1 = () => 'Hello'; const pre2 = (request) => { return request.pre.m1 + request.pre.m3 + request.pre.m4; }; const pre3 = async (request, h) => { await Hoek.wait(0); return h.response(' ').takeover(); }; const pre4 = () => 'World'; const pre5 = (request) => { return request.pre.m2 + '!'; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ [ { method: pre1, assign: 'm1' }, { method: pre3, assign: 'm3' }, { method: pre4, assign: 'm4' } ], { method: pre2, assign: 'm2' }, { method: pre5, assign: 'm5' } ], handler: (request) => request.pre.m5 } }); const res = await server.inject('/'); expect(res.result).to.equal(' '); }); it('returns error if prerequisite returns error', async () => { const pre1 = () => 'Hello'; const pre2 = function () { throw Boom.internal('boom'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ [{ method: pre1, assign: 'm1' }], { method: pre2, assign: 'm2' } ], handler: (request) => request.pre.m1 } }); const res = await server.inject('/'); expect(res.result.statusCode).to.equal(500); }); it('passes wrapped object', async () => { const pre = (request, h) => { return h.response('Hello').code(444); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ { method: pre, assign: 'p' } ], handler: (request) => request.preResponses.p } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(444); }); it('returns 500 if prerequisite throws', async () => { const pre1 = () => 'Hello'; const pre2 = function () { const a = null; a.b.c = 0; }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', options: { pre: [ [{ method: pre1, assign: 'm1' }], { method: pre2, assign: 'm2' } ], handler: (request) => request.pre.m1 } }); const res = await server.inject('/'); expect(res.result.statusCode).to.equal(500); }); it('sets pre failAction to error', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ { method: () => { throw Boom.forbidden(); }, failAction: 'error' } ], handler: () => 'ok' } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(403); }); it('sets pre failAction to ignore', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ { method: () => { throw Boom.forbidden(); }, failAction: 'ignore' } ], handler: () => 'ok' } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); }); it('sets pre failAction to log', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ { assign: 'before', method: () => { throw Boom.forbidden(); }, failAction: 'log' } ], handler: (request) => { if (request.pre.before === request.preResponses.before && request.pre.before instanceof Error) { return 'ok'; } throw new Error(); } } }); let logged; server.events.on({ name: 'request', channels: 'internal' }, (request, event, tags) => { if (tags.pre && tags.error) { logged = event; } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(logged.error.assign).to.equal('before'); }); it('sets pre failAction to method', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ { assign: 'value', method: () => { throw Boom.forbidden(); }, failAction: (request, h, err) => { expect(err.output.statusCode).to.equal(403); return 'failed'; } } ], handler: (request) => (request.pre.value + '!') } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('failed!'); }); it('sets pre failAction to method with takeover', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ { assign: 'value', method: () => { throw Boom.forbidden(); }, failAction: (request, h, err) => { expect(err.output.statusCode).to.equal(403); return h.response('failed').takeover(); } } ], handler: (request) => (request.pre.value + '!') } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('failed'); }); it('binds pre to route bind object', async () => { const item = { x: 123 }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [{ method: function (request) { return this.x; }, assign: 'x' }], handler: (request) => request.pre.x, bind: item } }); const res = await server.inject('/'); expect(res.result).to.equal(item.x); }); it('logs boom error instance as data if handler returns boom error', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { handler: function () { throw Boom.forbidden(); } } }); const log = new Promise((resolve) => { server.events.on({ name: 'request', channels: 'internal' }, (request, event, tags) => { if (tags.handler && tags.error) { resolve({ event, tags }); } }); }); const res = await server.inject('/'); expect(res.statusCode).to.equal(403); const { event } = await log; expect(event.error.isBoom).to.equal(true); expect(event.error.output.statusCode).to.equal(403); expect(event.error.message).to.equal('Forbidden'); expect(event.error.stack).to.exist(); }); }); describe('defaults()', () => { it('returns handler without defaults', async () => { const handler = function (route, options) { return (request) => request.route.settings.app; }; const server = Hapi.server(); server.decorate('handler', 'test', handler); server.route({ method: 'get', path: '/', handler: { test: 'value' } }); const res = await server.inject('/'); expect(res.result).to.equal({}); }); it('returns handler with object defaults', async () => { const handler = function (route, options) { return (request) => request.route.settings.app; }; handler.defaults = { app: { x: 1 } }; const server = Hapi.server(); server.decorate('handler', 'test', handler); server.route({ method: 'get', path: '/', handler: { test: 'value' } }); const res = await server.inject('/'); expect(res.result).to.equal({ x: 1 }); }); it('returns handler with function defaults', async () => { const handler = function (route, options) { return (request) => request.route.settings.app; }; handler.defaults = function (method) { return { app: { x: method } }; }; const server = Hapi.server(); server.decorate('handler', 'test', handler); server.route({ method: 'get', path: '/', handler: { test: 'value' } }); const res = await server.inject('/'); expect(res.result).to.equal({ x: 'get' }); }); it('throws on handler with invalid defaults', () => { const handler = function (route, options) { return (request) => request.route.settings.app; }; handler.defaults = 'invalid'; const server = Hapi.server(); expect(() => { server.decorate('handler', 'test', handler); }).to.throw('Handler defaults property must be an object or function'); }); }); }); ================================================ FILE: test/headers.js ================================================ 'use strict'; const Boom = require('@hapi/boom'); const { Engine: CatboxMemory } = require('@hapi/catbox-memory'); const Code = require('@hapi/code'); const Hapi = require('..'); const Inert = require('@hapi/inert'); const Lab = require('@hapi/lab'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('Headers', () => { describe('cache()', () => { it('sets max-age value (method and route)', async () => { const server = Hapi.server(); const method = function (id) { return { 'id': 'fa0dbda9b1b', 'name': 'John Doe' }; }; server.method('profile', method, { cache: { expiresIn: 120000, generateTimeout: 10 } }); const profileHandler = (request) => { return server.methods.profile(0); }; server.route({ method: 'GET', path: '/profile', options: { handler: profileHandler, cache: { expiresIn: 120000, privacy: 'private' } } }); await server.start(); const res = await server.inject('/profile'); expect(res.headers['cache-control']).to.equal('max-age=120, must-revalidate, private'); await server.stop(); }); it('sets max-age value (expiresAt)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { handler: () => null, cache: { expiresAt: '10:00' } } }); await server.start(); const res = await server.inject('/'); expect(res.headers['cache-control']).to.match(/^max-age=\d+, must-revalidate$/); await server.stop(); }); it('returns no-cache on error', async () => { const handler = () => { throw Boom.badRequest(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { handler, cache: { expiresIn: 120000 } } }); const res = await server.inject('/'); expect(res.headers['cache-control']).to.equal('no-cache'); }); it('returns custom value on error', async () => { const handler = () => { throw Boom.badRequest(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { handler, cache: { otherwise: 'no-store' } } }); const res = await server.inject('/'); expect(res.headers['cache-control']).to.equal('no-store'); }); it('sets cache-control on error with status override', async () => { const handler = () => { throw Boom.badRequest(); }; const server = Hapi.server({ routes: { cache: { statuses: [200, 400] } } }); server.route({ method: 'GET', path: '/', options: { handler, cache: { expiresIn: 120000 } } }); const res = await server.inject('/'); expect(res.headers['cache-control']).to.equal('max-age=120, must-revalidate'); }); it('does not return max-age value when route is not cached', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/item2', options: { handler: () => ({ 'id': '55cf687663', 'name': 'Active Items' }) } }); const res = await server.inject('/item2'); expect(res.headers['cache-control']).to.not.equal('max-age=120, must-revalidate'); }); it('caches using non default cache', async () => { const server = Hapi.server({ cache: { name: 'primary', provider: CatboxMemory } }); const defaults = server.cache({ segment: 'a', expiresIn: 2000, getDecoratedValue: true }); const primary = server.cache({ segment: 'a', expiresIn: 2000, getDecoratedValue: true, cache: 'primary' }); await server.start(); await defaults.set('b', 1); await primary.set('b', 2); const { value: value1 } = await defaults.get('b'); expect(value1).to.equal(1); const { cached: cached2 } = await primary.get('b'); expect(cached2.item).to.equal(2); await server.stop(); }); it('leaves existing cache-control header', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response('text').code(400).header('cache-control', 'some value') }); const res = await server.inject('/'); expect(res.statusCode).to.equal(400); expect(res.headers['cache-control']).to.equal('some value'); }); it('sets cache-control header from ttl without policy', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response('text').ttl(10000) }); const res = await server.inject('/'); expect(res.headers['cache-control']).to.equal('max-age=10, must-revalidate'); }); it('sets cache-control header from ttl with disabled policy', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { cache: false, handler: (request, h) => h.response('text').ttl(10000) } }); const res = await server.inject('/'); expect(res.headers['cache-control']).to.equal('max-age=10, must-revalidate'); }); it('leaves existing cache-control header (ttl)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response('text').ttl(1000).header('cache-control', 'none') }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['cache-control']).to.equal('none'); }); it('includes caching header with 304', async () => { const server = Hapi.server(); await server.register(Inert); server.route({ method: 'GET', path: '/file', handler: { file: __dirname + '/../package.json' }, options: { cache: { expiresIn: 60000 } } }); const res1 = await server.inject('/file'); const res2 = await server.inject({ url: '/file', headers: { 'if-modified-since': res1.headers['last-modified'] } }); expect(res2.statusCode).to.equal(304); expect(res2.headers['cache-control']).to.equal('max-age=60, must-revalidate'); }); it('forbids caching on 304 if 200 is not included', async () => { const server = Hapi.server({ routes: { cache: { statuses: [400] } } }); await server.register(Inert); server.route({ method: 'GET', path: '/file', handler: { file: __dirname + '/../package.json' }, options: { cache: { expiresIn: 60000 } } }); const res1 = await server.inject('/file'); const res2 = await server.inject({ url: '/file', headers: { 'if-modified-since': res1.headers['last-modified'] } }); expect(res2.statusCode).to.equal(304); expect(res2.headers['cache-control']).to.equal('no-cache'); }); }); describe('security()', () => { it('does not set security headers by default', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.not.exist(); expect(res.headers['x-frame-options']).to.not.exist(); expect(res.headers['x-xss-protection']).to.not.exist(); expect(res.headers['x-download-options']).to.not.exist(); expect(res.headers['x-content-type-options']).to.not.exist(); }); it('returns default security headers when security is true', async () => { const server = Hapi.server({ routes: { security: true } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.equal('max-age=15768000'); expect(res.headers['x-frame-options']).to.equal('DENY'); expect(res.headers['x-xss-protection']).to.equal('0'); expect(res.headers['x-download-options']).to.equal('noopen'); expect(res.headers['x-content-type-options']).to.equal('nosniff'); }); it('does not set default security headers when the route sets security false', async () => { const server = Hapi.server({ routes: { security: true } }); server.route({ method: 'GET', path: '/', handler: () => 'Test', options: { security: false } }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.not.exist(); expect(res.headers['x-frame-options']).to.not.exist(); expect(res.headers['x-xss-protection']).to.not.exist(); expect(res.headers['x-download-options']).to.not.exist(); expect(res.headers['x-content-type-options']).to.not.exist(); }); it('does not return hsts header when secuirty.hsts is false', async () => { const server = Hapi.server({ routes: { security: { hsts: false } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.not.exist(); expect(res.headers['x-frame-options']).to.equal('DENY'); expect(res.headers['x-xss-protection']).to.equal('0'); expect(res.headers['x-download-options']).to.equal('noopen'); expect(res.headers['x-content-type-options']).to.equal('nosniff'); }); it('returns only default hsts header when security.hsts is true', async () => { const server = Hapi.server({ routes: { security: { hsts: true } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.equal('max-age=15768000'); }); it('returns correct hsts header when security.hsts is a number', async () => { const server = Hapi.server({ routes: { security: { hsts: 123456789 } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.equal('max-age=123456789'); }); it('returns correct hsts header when security.hsts is an object', async () => { const server = Hapi.server({ routes: { security: { hsts: { maxAge: 123456789, includeSubDomains: true } } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.equal('max-age=123456789; includeSubDomains'); }); it('returns the correct hsts header when security.hsts is an object only sepcifying maxAge', async () => { const server = Hapi.server({ routes: { security: { hsts: { maxAge: 123456789 } } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.equal('max-age=123456789'); }); it('returns correct hsts header when security.hsts is an object only specifying includeSubdomains', async () => { const server = Hapi.server({ routes: { security: { hsts: { includeSubdomains: true } } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.equal('max-age=15768000; includeSubDomains'); }); it('returns correct hsts header when security.hsts is an object only specifying includeSubDomains', async () => { const server = Hapi.server({ routes: { security: { hsts: { includeSubDomains: true } } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.equal('max-age=15768000; includeSubDomains'); }); it('returns correct hsts header when security.hsts is an object only specifying includeSubDomains and preload', async () => { const server = Hapi.server({ routes: { security: { hsts: { includeSubDomains: true, preload: true } } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['strict-transport-security']).to.equal('max-age=15768000; includeSubDomains; preload'); }); it('does not return the xframe header whe security.xframe is false', async () => { const server = Hapi.server({ routes: { security: { xframe: false } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-frame-options']).to.not.exist(); expect(res.headers['strict-transport-security']).to.equal('max-age=15768000'); expect(res.headers['x-xss-protection']).to.equal('0'); expect(res.headers['x-download-options']).to.equal('noopen'); expect(res.headers['x-content-type-options']).to.equal('nosniff'); }); it('returns only default xframe header when security.xframe is true', async () => { const server = Hapi.server({ routes: { security: { xframe: true } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-frame-options']).to.equal('DENY'); }); it('returns correct xframe header when security.xframe is a string', async () => { const server = Hapi.server({ routes: { security: { xframe: 'sameorigin' } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-frame-options']).to.equal('SAMEORIGIN'); }); it('returns correct xframe header when security.xframe is an object', async () => { const server = Hapi.server({ routes: { security: { xframe: { rule: 'allow-from', source: 'http://example.com' } } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-frame-options']).to.equal('ALLOW-FROM http://example.com'); }); it('returns correct xframe header when security.xframe is an object', async () => { const server = Hapi.server({ routes: { security: { xframe: { rule: 'deny' } } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-frame-options']).to.equal('DENY'); }); it('returns sameorigin xframe header when rule is allow-from but source is unspecified', async () => { const server = Hapi.server({ routes: { security: { xframe: { rule: 'allow-from' } } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-frame-options']).to.equal('SAMEORIGIN'); }); it('does not set x-download-options if noOpen is false', async () => { const server = Hapi.server({ routes: { security: { noOpen: false } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-download-options']).to.not.exist(); }); it('does not set x-content-type-options if noSniff is false', async () => { const server = Hapi.server({ routes: { security: { noSniff: false } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-content-type-options']).to.not.exist(); }); it('sets the x-xss-protection header when security.xss is enabled', async () => { const server = Hapi.server({ routes: { security: { xss: 'enabled' } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-xss-protection']).to.equal('1; mode=block'); expect(res.headers['strict-transport-security']).to.equal('max-age=15768000'); expect(res.headers['x-frame-options']).to.equal('DENY'); expect(res.headers['x-download-options']).to.equal('noopen'); expect(res.headers['x-content-type-options']).to.equal('nosniff'); }); it('sets the x-xss-protection header when security.xss is disabled', async () => { const server = Hapi.server({ routes: { security: { xss: 'disabled' } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-xss-protection']).to.equal('0'); expect(res.headers['strict-transport-security']).to.equal('max-age=15768000'); expect(res.headers['x-frame-options']).to.equal('DENY'); expect(res.headers['x-download-options']).to.equal('noopen'); expect(res.headers['x-content-type-options']).to.equal('nosniff'); }); it('does not set the x-xss-protection header when security.xss is false', async () => { const server = Hapi.server({ routes: { security: { xss: false } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['x-xss-protection']).to.not.exist(); expect(res.headers['strict-transport-security']).to.equal('max-age=15768000'); expect(res.headers['x-frame-options']).to.equal('DENY'); expect(res.headers['x-download-options']).to.equal('noopen'); expect(res.headers['x-content-type-options']).to.equal('nosniff'); }); it('does not return the referrer-policy header by default', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['referrer-policy']).to.not.exist(); }); it('does not return the referrer-policy header when security.referrer is false', async () => { const server = Hapi.server({ routes: { security: { referrer: false } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['referrer-policy']).to.not.exist(); }); it('does not allow security.referrer to be true', () => { let err; try { Hapi.server({ routes: { security: { referrer: true } } }); } catch (ex) { err = ex; } expect(err).to.exist(); }); it('returns correct referrer-policy header when security.referrer is a string with a valid value', async () => { const server = Hapi.server({ routes: { security: { referrer: 'strict-origin-when-cross-origin' } } }); server.route({ method: 'GET', path: '/', handler: () => 'Test' }); const res = await server.inject({ url: '/' }); expect(res.result).to.exist(); expect(res.result).to.equal('Test'); expect(res.headers['referrer-policy']).to.equal('strict-origin-when-cross-origin'); }); }); describe('content()', () => { it('does not modify content-type header when charset manually set', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response('text').type('text/plain; charset=ISO-8859-1') }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['content-type']).to.equal('text/plain; charset=ISO-8859-1'); }); it('does not modify content-type header when charset is unset', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response('text').type('text/plain').charset() }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['content-type']).to.equal('text/plain'); }); it('does not modify content-type header when charset is unset (default type)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response('text').charset() }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['content-type']).to.equal('text/html'); }); it('does not set content-type by default on 204 response', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response().code(204) }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); expect(res.headers['content-type']).to.equal(undefined); }); }); }); ================================================ FILE: test/index.js ================================================ 'use strict'; const Code = require('@hapi/code'); const Hapi = require('..'); const Lab = require('@hapi/lab'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('Server', () => { it('supports new Server()', async () => { const server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: () => 'old school' }); const res = await server.inject('/'); expect(res.result).to.equal('old school'); }); }); ================================================ FILE: test/methods.js ================================================ 'use strict'; const Catbox = require('@hapi/catbox'); const { Engine: CatboxMemory } = require('@hapi/catbox-memory'); const Code = require('@hapi/code'); const Hapi = require('..'); const Hoek = require('@hapi/hoek'); const Lab = require('@hapi/lab'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('Methods', () => { it('registers a method', () => { const add = function (a, b) { return a + b; }; const server = Hapi.server(); server.method('add', add); const result = server.methods.add(1, 5); expect(result).to.equal(6); }); it('registers a method (object)', () => { const add = function (a, b) { return a + b; }; const server = Hapi.server(); server.method({ name: 'add', method: add }); const result = server.methods.add(1, 5); expect(result).to.equal(6); }); it('registers a method with leading _', () => { const _add = function (a, b) { return a + b; }; const server = Hapi.server(); server.method('_add', _add); const result = server.methods._add(1, 5); expect(result).to.equal(6); }); it('registers a method with leading $', () => { const $add = function (a, b) { return a + b; }; const server = Hapi.server(); server.method('$add', $add); const result = server.methods.$add(1, 5); expect(result).to.equal(6); }); it('registers a method with _', () => { const _add = function (a, b) { return a + b; }; const server = Hapi.server(); server.method('add_._that', _add); const result = server.methods.add_._that(1, 5); expect(result).to.equal(6); }); it('registers a method with $', () => { const $add = function (a, b) { return a + b; }; const server = Hapi.server(); server.method('add$.$that', $add); const result = server.methods.add$.$that(1, 5); expect(result).to.equal(6); }); it('registers a method (promise)', async () => { const add = function (a, b) { return new Promise((resolve) => resolve(a + b)); }; const server = Hapi.server(); server.method('add', add); const value = await server.methods.add(1, 5); expect(value).to.equal(6); }); it('registers a method with nested name', () => { const add = function (a, b) { return a + b; }; const server = Hapi.server(); server.method('tools.add', add); const result = server.methods.tools.add(1, 5); expect(result).to.equal(6); }); it('registers two methods with shared nested name', () => { const add = function (a, b) { return a + b; }; const sub = function (a, b) { return a - b; }; const server = Hapi.server(); server.method('tools.add', add); server.method('tools.sub', sub); const result1 = server.methods.tools.add(1, 5); expect(result1).to.equal(6); const result2 = server.methods.tools.sub(1, 5); expect(result2).to.equal(-4); }); it('throws when registering a method with nested name twice', () => { const server = Hapi.server(); server.method('tools.add', Hoek.ignore); expect(() => { server.method('tools.add', Hoek.ignore); }).to.throw('Server method function name already exists: tools.add'); }); it('throws when registering a method with name nested through a function', () => { const server = Hapi.server(); server.method('add', Hoek.ignore); expect(() => { server.method('add.another', Hoek.ignore); }).to.throw('Invalid segment another in reach path add.another'); }); it('calls non cached method multiple times', () => { let gen = 0; const method = function (id) { return { id, gen: gen++ }; }; const server = Hapi.server(); server.method('test', method); const result1 = server.methods.test(1); expect(result1.gen).to.equal(0); const result2 = server.methods.test(1); expect(result2.gen).to.equal(1); }); it('caches method value', async () => { let gen = 0; const method = function (id) { return { id, gen: gen++ }; }; const server = Hapi.server(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const result1 = await server.methods.test(1); expect(result1.gen).to.equal(0); const result2 = await server.methods.test(1); expect(result2.gen).to.equal(0); }); it('emits a cache policy event on cached methods with default cache provision', async () => { const method = function (id) { return { id }; }; const server = Hapi.server(); const cachePolicyEvent = server.events.once('cachePolicy'); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); const [policy, cacheName, segment] = await cachePolicyEvent; expect(policy).to.be.instanceOf(Catbox.Policy); expect(cacheName).to.equal(undefined); expect(segment).to.equal('#test'); }); it('emits a cache policy event on cached methods with named cache provision', async () => { const method = function (id) { return { id }; }; const server = Hapi.server(); await server.cache.provision({ provider: CatboxMemory, name: 'named' }); const cachePolicyEvent = server.events.once('cachePolicy'); server.method('test', method, { cache: { cache: 'named', expiresIn: 1000, generateTimeout: 10 } }); const [policy, cacheName, segment] = await cachePolicyEvent; expect(policy).to.be.instanceOf(Catbox.Policy); expect(cacheName).to.equal('named'); expect(segment).to.equal('#test'); }); it('caches method value (async)', async () => { let gen = 0; const method = async function (id) { await Hoek.wait(1); return { id, gen: gen++ }; }; const server = Hapi.server(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const result1 = await server.methods.test(1); expect(result1.gen).to.equal(0); const result2 = await server.methods.test(1); expect(result2.gen).to.equal(0); }); it('caches method value (promise)', async () => { let gen = 0; const method = function (id) { return new Promise((resolve, reject) => { if (id === 2) { return reject(new Error('boom')); } return resolve({ id, gen: gen++ }); }); }; const server = Hapi.server(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const result1 = await server.methods.test(1); expect(result1.gen).to.equal(0); const result2 = await server.methods.test(1); expect(result2.gen).to.equal(0); await expect(server.methods.test(2)).to.reject('boom'); }); it('caches method value (decorated)', async () => { let gen = 0; const method = function (id) { return { id, gen: gen++ }; }; const server = Hapi.server(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10, getDecoratedValue: true } }); await server.initialize(); const { value: result1 } = await server.methods.test(1); expect(result1.gen).to.equal(0); const { value: result2 } = await server.methods.test(1); expect(result2.gen).to.equal(0); }); it('reuses cached method value with custom key function', async () => { let gen = 0; const method = function (id) { return { id, gen: gen++ }; }; const server = Hapi.server(); const generateKey = function (id) { return '' + (id + 1); }; server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 }, generateKey }); await server.initialize(); const result1 = await server.methods.test(1); expect(result1.gen).to.equal(0); const result2 = await server.methods.test(1); expect(result2.gen).to.equal(0); }); it('errors when custom key function return null', async () => { const method = function (id) { return { id }; }; const server = Hapi.server(); const generateKey = function (id) { return null; }; server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 }, generateKey }); await server.initialize(); await expect(server.methods.test(1)).to.reject('Invalid method key when invoking: test'); }); it('does not cache when custom key function returns a non-string', async () => { const method = function (id) { return { id }; }; const server = Hapi.server(); const generateKey = function (id) { return 123; }; server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 }, generateKey }); await server.initialize(); await expect(server.methods.test(1)).to.reject('Invalid method key when invoking: test'); }); it('does not cache value when ttl is 0', async () => { let gen = 0; const method = function (id, flags) { flags.ttl = 0; return { id, gen: gen++ }; }; const server = Hapi.server(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const result1 = await server.methods.test(1); expect(result1.gen).to.equal(0); const result2 = await server.methods.test(1); expect(result2.gen).to.equal(1); }); it('generates new value after cache drop', async () => { let gen = 0; const method = function (id) { return { id, gen: gen++ }; }; const server = Hapi.server(); server.method('dropTest', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const result1 = await server.methods.dropTest(2); expect(result1.gen).to.equal(0); await server.methods.dropTest.cache.drop(2); const result2 = await server.methods.dropTest(2); expect(result2.gen).to.equal(1); }); it('errors on invalid drop key', async () => { let gen = 0; const method = function (id) { return { id, gen: gen++ }; }; const server = Hapi.server(); server.method('dropErrTest', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const invalid = () => { }; await expect(server.methods.dropErrTest.cache.drop(invalid)).to.reject(); }); it('reports cache stats for each method', async () => { const method = function (id) { return { id }; }; const server = Hapi.server(); server.method('test', method, { cache: { generateTimeout: 10 } }); server.method('test2', method, { cache: { generateTimeout: 10 } }); await server.initialize(); server.methods.test(1); expect(server.methods.test.cache.stats.gets).to.equal(1); expect(server.methods.test2.cache.stats.gets).to.equal(0); }); it('throws an error when name is not a string', () => { expect(() => { const server = Hapi.server(); server.method(0, () => { }); }).to.throw('name must be a string'); }); it('throws an error when name is invalid', () => { expect(() => { const server = Hapi.server(); server.method('0', () => { }); }).to.throw('Invalid name: 0'); expect(() => { const server = Hapi.server(); server.method('a..', () => { }); }).to.throw('Invalid name: a..'); expect(() => { const server = Hapi.server(); server.method('a.0', () => { }); }).to.throw('Invalid name: a.0'); expect(() => { const server = Hapi.server(); server.method('.a', () => { }); }).to.throw('Invalid name: .a'); }); it('throws an error when method is not a function', () => { expect(() => { const server = Hapi.server(); server.method('user', 'function'); }).to.throw('method must be a function'); }); it('throws an error when options is not an object', () => { expect(() => { const server = Hapi.server(); server.method('user', () => { }, 'options'); }).to.throw(/Invalid method options \(user\)/); }); it('throws an error when options.generateKey is not a function', () => { expect(() => { const server = Hapi.server(); server.method('user', () => { }, { generateKey: 'function' }); }).to.throw(/Invalid method options \(user\)/); }); it('throws an error when options.cache is not valid', () => { expect(() => { const server = Hapi.server({ cache: CatboxMemory }); server.method('user', () => { }, { cache: { x: 'y', generateTimeout: 10 } }); }).to.throw(/Invalid cache policy configuration/); }); it('throws an error when generateTimeout is not present', () => { const server = Hapi.server(); expect(() => { server.method('test', () => { }, { cache: {} }); }).to.throw('Method caching requires a timeout value in generateTimeout: test'); }); it('allows generateTimeout to be false', () => { const server = Hapi.server(); expect(() => { server.method('test', () => { }, { cache: { generateTimeout: false } }); }).to.not.throw(); }); it('returns timeout when method taking too long using the cache', async () => { const server = Hapi.server({ cache: CatboxMemory }); let gen = 0; const method = async function (id) { await Hoek.wait(50); return { id, gen: ++gen }; }; server.method('user', method, { cache: { expiresIn: 2000, generateTimeout: 30 } }); await server.initialize(); const id = Math.random(); const err = await expect(server.methods.user(id)).to.reject(); expect(err.output.statusCode).to.equal(503); await Hoek.wait(30); const result2 = await server.methods.user(id); expect(result2.id).to.equal(id); expect(result2.gen).to.equal(1); }); it('supports empty key method', async () => { const server = Hapi.server({ cache: CatboxMemory }); let gen = 0; const terms = 'I agree to give my house'; const method = function () { return { gen: gen++, terms }; }; server.method('tos', method, { cache: { expiresIn: 2000, generateTimeout: 10 } }); await server.initialize(); const result1 = await server.methods.tos(); expect(result1.terms).to.equal(terms); expect(result1.gen).to.equal(0); const result2 = await server.methods.tos(); expect(result2.terms).to.equal(terms); expect(result2.gen).to.equal(0); }); it('returns valid results when calling a method (with different keys) using the cache', async () => { const server = Hapi.server({ cache: CatboxMemory }); let gen = 0; const method = function (id) { return { id, gen: ++gen }; }; server.method('user', method, { cache: { expiresIn: 2000, generateTimeout: 10 } }); await server.initialize(); const id1 = Math.random(); const result1 = await server.methods.user(id1); expect(result1.id).to.equal(id1); expect(result1.gen).to.equal(1); const id2 = Math.random(); const result2 = await server.methods.user(id2); expect(result2.id).to.equal(id2); expect(result2.gen).to.equal(2); }); it('errors when key generation fails', async () => { const server = Hapi.server({ cache: CatboxMemory }); const method = function (id) { return { id }; }; server.method([{ name: 'user', method, options: { cache: { expiresIn: 2000, generateTimeout: 10 } } }]); await server.initialize(); const result1 = await server.methods.user(1); expect(result1.id).to.equal(1); const invalid = function () { }; await expect(server.methods.user(invalid)).to.reject('Invalid method key when invoking: user'); }); it('sets method bind without cache', () => { const method = function (id) { return { id, gen: this.gen++ }; }; const server = Hapi.server(); server.method('test', method, { bind: { gen: 7 } }); const result1 = server.methods.test(1); expect(result1.gen).to.equal(7); const result2 = server.methods.test(1); expect(result2.gen).to.equal(8); }); it('sets method bind with cache', async () => { const method = function (id) { return { id, gen: this.gen++ }; }; const server = Hapi.server(); server.method('test', method, { bind: { gen: 7 }, cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const result1 = await server.methods.test(1); expect(result1.gen).to.equal(7); const result2 = await server.methods.test(1); expect(result2.gen).to.equal(7); }); it('shallow copies bind config', async () => { const bind = { gen: 7 }; const method = function (id) { return { id, gen: this.gen++, bound: this === bind }; }; const server = Hapi.server(); server.method('test', method, { bind, cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const result1 = await server.methods.test(1); expect(result1.gen).to.equal(7); expect(result1.bound).to.equal(true); const result2 = await server.methods.test(1); expect(result2.gen).to.equal(7); }); describe('_add()', () => { it('handles sync method', () => { const add = function (a, b) { return a + b; }; const server = Hapi.server(); server.method('add', add); const result = server.methods.add(1, 5); expect(result).to.equal(6); }); it('handles sync method (direct error)', () => { const add = function (a, b) { return new Error('boom'); }; const server = Hapi.server(); server.method('add', add); const result = server.methods.add(1, 5); expect(result).to.be.instanceof(Error); expect(result.message).to.equal('boom'); }); it('handles sync method (direct throw)', () => { const add = function (a, b) { throw new Error('boom'); }; const server = Hapi.server(); server.method('add', add); expect(() => { server.methods.add(1, 5); }).to.throw('boom'); }); it('throws an error if unknown keys are present when making a server method using an object', () => { const fn = function () { }; const server = Hapi.server(); expect(() => { server.method({ name: 'fn', method: fn, cache: {} }); }).to.throw(/^Invalid methodObject options/); }); }); describe('generateKey()', () => { it('handles string argument type', async () => { const method = (id) => id; const server = Hapi.server(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const value = await server.methods.test('x'); expect(value).to.equal('x'); }); it('handles multiple arguments', async () => { const method = (a, b, c) => a + b + c; const server = Hapi.server(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); const value = await server.methods.test('a', 'b', 'c'); expect(value).to.equal('abc'); }); it('errors on invalid argument type', async () => { const method = (id) => id; const server = Hapi.server(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); await server.initialize(); await expect(server.methods.test({})).to.reject('Invalid method key when invoking: test'); }); }); }); ================================================ FILE: test/payload.js ================================================ 'use strict'; const Events = require('events'); const Fs = require('fs'); const Http = require('http'); const Net = require('net'); const Path = require('path'); const Zlib = require('zlib'); const Boom = require('@hapi/boom'); const Code = require('@hapi/code'); const Hapi = require('..'); const Hoek = require('@hapi/hoek'); const Lab = require('@hapi/lab'); const Wreck = require('@hapi/wreck'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('Payload', () => { it('sets payload', async () => { const payload = '{"x":"1","y":"2","z":"3"}'; const handler = (request) => { expect(request.payload).to.exist(); expect(request.payload.z).to.equal('3'); expect(request.mime).to.equal('application/json'); return request.payload; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler } }); const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.result).to.exist(); expect(res.result.x).to.equal('1'); }); it('handles request socket error', async () => { let called = false; const handler = function () { called = true; return null; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler } }); const res = await server.inject({ method: 'POST', url: '/', payload: 'test', simulate: { error: true, end: false } }); expect(res.result).to.exist(); expect(res.result.statusCode).to.equal(500); expect(called).to.be.false(); }); it('handles request socket close', async () => { const handler = function () { throw new Error('never called'); }; const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler } }); const responded = server.ext('onPostResponse'); server.inject({ method: 'POST', url: '/', payload: 'test', simulate: { close: true, end: false } }); const request = await responded; expect(request._isReplied).to.equal(true); expect(request.response.output.statusCode).to.equal(500); }); it('handles aborted request mid-lifecycle step', async (flags) => { let req = null; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: async (request) => { req.destroy(); await request.events.once('disconnect'); return 'ok'; } }); // Register post handler that should not be called let post = 0; server.ext('onPostHandler', () => { ++post; }); flags.onCleanup = () => server.stop(); await server.start(); req = Http.request({ hostname: 'localhost', port: server.info.port, method: 'get' }); req.on('error', Hoek.ignore); req.end(); const [request] = await server.events.once('response'); expect(request.response.isBoom).to.be.true(); expect(request.response.output.statusCode).to.equal(499); expect(request.info.completed).to.be.above(0); expect(request.info.responded).to.equal(0); expect(post).to.equal(0); }); it('handles aborted request', { retry: true }, async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler: () => 'Success', payload: { parse: false } } }); const log = server.events.once('log'); await server.start(); const options = { hostname: 'localhost', port: server.info.port, path: '/', method: 'POST', headers: { 'Content-Length': '10' } }; const req = Http.request(options, (res) => { }); req.on('error', Hoek.ignore); req.write('Hello\n'); setTimeout(() => req.destroy(), 50); const [event] = await log; expect(event.error.message).to.equal('Parse Error'); await server.stop({ timeout: 10 }); }); it('errors when payload too big', async () => { const payload = '{"x":"1","y":"2","z":"3"}'; const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler: () => null, payload: { maxBytes: 10 } } }); const res = await server.inject({ method: 'POST', url: '/', payload, headers: { 'content-length': payload.length } }); expect(res.statusCode).to.equal(413); expect(res.result).to.exist(); expect(res.result.message).to.equal('Payload content length greater than maximum allowed: 10'); }); it('errors when payload too big (implicit length)', async () => { const payload = '{"x":"1","y":"2","z":"3"}'; const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler: () => null, payload: { maxBytes: 10 } } }); const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.statusCode).to.equal(413); expect(res.result).to.exist(); expect(res.result.message).to.equal('Payload content length greater than maximum allowed: 10'); }); it('errors when payload too big (file)', async () => { const payload = '{"x":"1","y":"2","z":"3"}'; const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler: () => null, payload: { output: 'file', maxBytes: 10 } } }); const res = await server.inject({ method: 'POST', url: '/', payload, headers: { 'content-length': payload.length } }); expect(res.statusCode).to.equal(413); expect(res.result).to.exist(); expect(res.result.message).to.equal('Payload content length greater than maximum allowed: 10'); }); it('errors when payload too big (file implicit length)', async () => { const payload = '{"x":"1","y":"2","z":"3"}'; const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler: () => null, payload: { output: 'file', maxBytes: 10 } } }); const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.statusCode).to.equal(413); expect(res.result).to.exist(); expect(res.result.message).to.equal('Payload content length greater than maximum allowed: 10'); }); it('errors when payload contains prototype poisoning', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: (request) => request.payload.x }); const payload = '{"x":"1","y":"2","z":"3","__proto__":{"x":"4"}}'; const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.statusCode).to.equal(400); }); it('ignores when payload contains prototype poisoning', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { payload: { protoAction: 'ignore' }, handler: (request) => request.payload.__proto__ } }); const payload = '{"x":"1","y":"2","z":"3","__proto__":{"x":"4"}}'; const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal({ x: '4' }); }); it('sanitizes when payload contains prototype poisoning', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { payload: { protoAction: 'remove' }, handler: (request) => request.payload.__proto__ } }); const payload = '{"x":"1","y":"2","z":"3","__proto__":{"x":"4"}}'; const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal({}); }); it('returns 413 with response when payload is not consumed', async () => { const payload = Buffer.alloc(10 * 1024 * 1024).toString(); const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler: () => null, payload: { maxBytes: 1024 * 1024 } } }); await server.start(); const uri = 'http://localhost:' + server.info.port; const err = await expect(Wreck.post(uri, { payload })).to.reject(); expect(err.data.res.statusCode).to.equal(413); expect(err.data.payload.toString()).to.equal('{"statusCode":413,"error":"Request Entity Too Large","message":"Payload content length greater than maximum allowed: 1048576"}'); await server.stop(); }); it('handles expect 100-continue', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: (request) => request.payload }); await server.start(); const client = Net.connect(server.info.port); await Events.once(client, 'connect'); client.write('POST / HTTP/1.1\r\nexpect: 100-continue\r\nhost: host\r\naccept-encoding: gzip\r\n' + 'content-type: application/json\r\ncontent-length: 14\r\nConnection: close\r\n\r\n'); const lines = []; client.setEncoding('ascii'); for await (const chunk of client) { if (chunk.startsWith('HTTP/1.1 100 Continue')) { client.write('{"hello":true}'); } else { lines.push(...chunk.split('\r\n')); } } const res = lines.shift(); const payload = lines.pop(); expect(res).to.equal('HTTP/1.1 200 OK'); expect(payload).to.equal('{"hello":true}'); await server.stop(); }); it('does not continue on errors before payload processing', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: (request) => request.payload }); server.ext('onPreAuth', (request, h) => { throw new Boom.forbidden(); }); await server.start(); const client = Net.connect(server.info.port); await Events.once(client, 'connect'); client.write('POST / HTTP/1.1\r\nexpect: 100-continue\r\nhost: host\r\naccept-encoding: gzip\r\n' + 'content-type: application/json\r\ncontent-length: 14\r\nConnection: close\r\n\r\n'); let continued = false; const lines = []; client.setEncoding('ascii'); for await (const chunk of client) { if (chunk.startsWith('HTTP/1.1 100 Continue')) { client.write('{"hello":true}'); continued = true; } else { lines.push(...chunk.split('\r\n')); } } const res = lines.shift(); expect(res).to.equal('HTTP/1.1 403 Forbidden'); expect(continued).to.be.false(); await server.stop(); }); it('handles expect 100-continue on undefined routes', async () => { const server = Hapi.server(); await server.start(); const client = Net.connect(server.info.port); await Events.once(client, 'connect'); client.write('POST / HTTP/1.1\r\nexpect: 100-continue\r\nhost: host\r\naccept-encoding: gzip\r\n' + 'content-type: application/json\r\ncontent-length: 14\r\nConnection: close\r\n\r\n'); let continued = false; const lines = []; client.setEncoding('ascii'); for await (const chunk of client) { if (chunk.startsWith('HTTP/1.1 100 Continue')) { client.write('{"hello":true}'); continued = true; } else { lines.push(...chunk.split('\r\n')); } } const res = lines.shift(); expect(res).to.equal('HTTP/1.1 404 Not Found'); expect(continued).to.be.false(); await server.stop(); }); it('does not continue on custom request.payload', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: (request) => request.payload }); server.ext('onRequest', (request, h) => { request.payload = { custom: true }; return h.continue; }); await server.start(); const client = Net.connect(server.info.port); await Events.once(client, 'connect'); client.write('POST / HTTP/1.1\r\nexpect: 100-continue\r\nhost: host\r\naccept-encoding: gzip\r\n' + 'content-type: application/json\r\ncontent-length: 14\r\nConnection: close\r\n\r\n'); let continued = false; const lines = []; client.setEncoding('ascii'); for await (const chunk of client) { if (chunk.startsWith('HTTP/1.1 100 Continue')) { client.write('{"hello":true}'); continued = true; } else { lines.push(...chunk.split('\r\n')); } } const res = lines.shift(); const payload = lines.pop(); expect(res).to.equal('HTTP/1.1 200 OK'); expect(payload).to.equal('{"custom":true}'); expect(continued).to.be.false(); await server.stop(); }); it('peeks at unparsed data', async () => { let data = null; const ext = (request, h) => { const chunks = []; request.events.on('peek', (chunk, encoding) => { chunks.push(chunk); }); request.events.once('finish', () => { data = Buffer.concat(chunks); }); return h.continue; }; const server = Hapi.server(); server.ext('onRequest', ext); server.route({ method: 'POST', path: '/', options: { handler: () => data, payload: { parse: false } } }); const payload = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'; const res = await server.inject({ method: 'POST', url: '/', payload }); expect(res.result).to.equal(payload); }); it('peeks at unparsed data (finish only)', async () => { let peeked = false; const ext = (request, h) => { request.events.once('finish', () => { peeked = true; }); return h.continue; }; const server = Hapi.server(); server.ext('onRequest', ext); server.route({ method: 'POST', path: '/', options: { handler: () => null, payload: { parse: false } } }); const payload = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'; await server.inject({ method: 'POST', url: '/', payload }); expect(peeked).to.be.true(); }); it('handles gzipped payload', async () => { const message = { 'msg': 'This message is going to be gzipped.' }; const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: (request) => request.payload }); const compressed = await new Promise((resolve) => Zlib.gzip(JSON.stringify(message), (ignore, result) => resolve(result))); const request = { method: 'POST', url: '/', headers: { 'content-type': 'application/json', 'content-encoding': 'gzip', 'content-length': compressed.length }, payload: compressed }; const res = await server.inject(request); expect(res.result).to.exist(); expect(res.result).to.equal(message); }); it('handles deflated payload', async () => { const message = { 'msg': 'This message is going to be gzipped.' }; const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: (request) => request.payload }); const compressed = await new Promise((resolve) => Zlib.deflate(JSON.stringify(message), (ignore, result) => resolve(result))); const request = { method: 'POST', url: '/', headers: { 'content-type': 'application/json', 'content-encoding': 'deflate', 'content-length': compressed.length }, payload: compressed }; const res = await server.inject(request); expect(res.result).to.exist(); expect(res.result).to.equal(message); }); it('handles custom compression', async () => { const message = { 'msg': 'This message is going to be gzipped.' }; const server = Hapi.server({ routes: { payload: { compression: { test: { some: 'options' } } } } }); const decoder = (options) => { expect(options).to.equal({ some: 'options' }); return Zlib.createGunzip(); }; server.decoder('test', decoder); server.route({ method: 'POST', path: '/', handler: (request) => request.payload }); const compressed = await new Promise((resolve) => Zlib.gzip(JSON.stringify(message), (ignore, result) => resolve(result))); const request = { method: 'POST', url: '/', headers: { 'content-type': 'application/json', 'content-encoding': 'test', 'content-length': compressed.length }, payload: compressed }; const res = await server.inject(request); expect(res.result).to.exist(); expect(res.result).to.equal(message); }); it('saves a file after content decoding', async () => { const path = Path.join(__dirname, './file/image.jpg'); const sourceContents = Fs.readFileSync(path); const stats = Fs.statSync(path); const handler = (request) => { const receivedContents = Fs.readFileSync(request.payload.path); Fs.unlinkSync(request.payload.path); expect(receivedContents).to.equal(sourceContents); return request.payload.bytes; }; const compressed = await new Promise((resolve) => Zlib.gzip(sourceContents, (ignore, result) => resolve(result))); const server = Hapi.server(); server.route({ method: 'POST', path: '/file', options: { handler, payload: { output: 'file' } } }); const res = await server.inject({ method: 'POST', url: '/file', payload: compressed, headers: { 'content-encoding': 'gzip' } }); expect(res.result).to.equal(stats.size); }); it('errors saving a file without parse', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/file', options: { handler: Hoek.block, payload: { output: 'file', parse: false, uploads: '/a/b/c/d/not' } } }); const res = await server.inject({ method: 'POST', url: '/file', payload: 'abcde' }); expect(res.statusCode).to.equal(500); }); it('sets parse mode when route method is * and request is POST', async () => { const server = Hapi.server(); server.route({ method: '*', path: '/any', handler: (request) => request.payload.key }); const res = await server.inject({ url: '/any', method: 'POST', payload: { key: '09876' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('09876'); }); it('returns an error on unsupported mime type', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: (request) => request.payload.key }); await server.start(); const options = { headers: { 'Content-Type': 'application/unknown', 'Content-Length': '18' }, payload: '{ "key": "value" }' }; const err = await expect(Wreck.post(`http://localhost:${server.info.port}/?x=4`, options)).to.reject(); expect(err.output.statusCode).to.equal(415); await server.stop({ timeout: 1 }); }); it('ignores unsupported mime type', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler: (request) => request.payload, payload: { failAction: 'ignore' } } }); const res = await server.inject({ method: 'POST', url: '/', payload: 'testing123', headers: { 'content-type': 'application/unknown' } }); expect(res.statusCode).to.equal(204); expect(res.result).to.equal(null); }); it('returns 200 on octet mime type', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: () => 'ok' }); const res = await server.inject({ method: 'POST', url: '/', payload: 'testing123', headers: { 'content-type': 'application/octet-stream' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('ok'); }); it('returns 200 on text mime type', async () => { const handler = (request) => { return request.payload + '+456'; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/text', handler }); const res = await server.inject({ method: 'POST', url: '/text', payload: 'testing123', headers: { 'content-type': 'text/plain' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('testing123+456'); }); it('returns 200 on override mime type', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/override', options: { handler: (request) => request.payload.key, payload: { override: 'application/json' } } }); const res = await server.inject({ method: 'POST', url: '/override', payload: '{"key":"cool"}', headers: { 'content-type': 'text/plain' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('cool'); }); it('returns 200 on text mime type when allowed', async () => { const handler = (request) => { return request.payload + '+456'; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/textOnly', options: { handler, payload: { allow: 'text/plain' } } }); const res = await server.inject({ method: 'POST', url: '/textOnly', payload: 'testing123', headers: { 'content-type': 'text/plain' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('testing123+456'); }); it('returns 415 on non text mime type when disallowed', async () => { const handler = (request) => { return request.payload + '+456'; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/textOnly', options: { handler, payload: { allow: 'text/plain' } } }); const res = await server.inject({ method: 'POST', url: '/textOnly', payload: 'testing123', headers: { 'content-type': 'application/octet-stream' } }); expect(res.statusCode).to.equal(415); }); it('returns 200 on text mime type when allowed (array)', async () => { const handler = (request) => { return request.payload + '+456'; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/textOnlyArray', options: { handler, payload: { allow: ['text/plain'] } } }); const res = await server.inject({ method: 'POST', url: '/textOnlyArray', payload: 'testing123', headers: { 'content-type': 'text/plain' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('testing123+456'); }); it('returns 415 on non text mime type when disallowed (array)', async () => { const handler = (request) => { return request.payload + '+456'; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/textOnlyArray', options: { handler, payload: { allow: ['text/plain'] } } }); const res = await server.inject({ method: 'POST', url: '/textOnlyArray', payload: 'testing123', headers: { 'content-type': 'application/octet-stream' } }); expect(res.statusCode).to.equal(415); }); it('returns parsed multipart data (route)', async () => { const multipartPayload = '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'First\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'Second\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'Third\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="field1"\r\n' + '\r\n' + 'Joe Blow\r\nalmost tricked you!\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="field1"\r\n' + '\r\n' + 'Repeated name segment\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n' + 'Content-Type: text/plain\r\n' + '\r\n' + '... contents of file1.txt ...\r\r\n' + '--AaB03x--\r\n'; const handler = (request) => { const result = {}; const keys = Object.keys(request.payload); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; const value = request.payload[key]; result[key] = value._readableState ? true : value; } return result; }; const server = Hapi.server(); server.route({ method: 'POST', path: '/echo', handler, options: { payload: { multipart: true } } }); const res = await server.inject({ method: 'POST', url: '/echo', payload: multipartPayload, headers: { 'content-type': 'multipart/form-data; boundary=AaB03x' } }); expect(Object.keys(res.result).length).to.equal(3); expect(res.result.field1).to.exist(); expect(res.result.field1.length).to.equal(2); expect(res.result.field1[1]).to.equal('Repeated name segment'); expect(res.result.pics).to.exist(); }); it('returns parsed multipart data (server)', async () => { const multipartPayload = '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'First\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'Second\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'Third\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="field1"\r\n' + '\r\n' + 'Joe Blow\r\nalmost tricked you!\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="field1"\r\n' + '\r\n' + 'Repeated name segment\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n' + 'Content-Type: text/plain\r\n' + '\r\n' + '... contents of file1.txt ...\r\r\n' + '--AaB03x--\r\n'; const handler = (request) => { const result = {}; const keys = Object.keys(request.payload); for (let i = 0; i < keys.length; ++i) { const key = keys[i]; const value = request.payload[key]; result[key] = value._readableState ? true : value; } return result; }; const server = Hapi.server({ routes: { payload: { multipart: true } } }); server.route({ method: 'POST', path: '/echo', handler }); const res = await server.inject({ method: 'POST', url: '/echo', payload: multipartPayload, headers: { 'content-type': 'multipart/form-data; boundary=AaB03x' } }); expect(Object.keys(res.result).length).to.equal(3); expect(res.result.field1).to.exist(); expect(res.result.field1.length).to.equal(2); expect(res.result.field1[1]).to.equal('Repeated name segment'); expect(res.result.pics).to.exist(); }); it('places default limit on max parts in multipart payloads', async () => { const part = '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n\r\n' + 'x\r\n'; const multipartPayload = part.repeat(1001) + '--AaB03x--\r\n'; const server = Hapi.server({ routes: { payload: { multipart: true } } }); server.route({ method: 'POST', path: '/', handler: () => null }); const res = await server.inject({ method: 'POST', url: '/', payload: multipartPayload, headers: { 'content-type': 'multipart/form-data; boundary=AaB03x' } }); expect(res.statusCode).to.equal(400); expect(res.result.message).to.equal('Invalid multipart payload format'); }); it('signals connection close when payload is unconsumed', async () => { const payload = Buffer.alloc(1024); const server = Hapi.server(); server.route({ method: 'POST', path: '/', options: { handler: () => 'ok', payload: { maxBytes: 1024, output: 'stream', parse: false } } }); const res = await server.inject({ method: 'POST', url: '/', payload, headers: { 'content-type': 'application/octet-stream' } }); expect(res.statusCode).to.equal(200); expect(res.headers).to.include({ connection: 'close' }); expect(res.result).to.equal('ok'); }); it('times out when client request taking too long', async () => { const server = Hapi.server({ routes: { payload: { timeout: 50 } } }); server.route({ method: 'POST', path: '/', handler: () => null }); await server.start(); const request = () => { const options = { hostname: '127.0.0.1', port: server.info.port, path: '/', method: 'POST' }; const req = Http.request(options); req.on('error', Hoek.ignore); req.write('{}\n'); setTimeout(() => req.end(), 100); return new Promise((resolve) => req.once('response', resolve)); }; const timer = new Hoek.Bench(); const res = await request(); expect(res.statusCode).to.equal(408); expect(timer.elapsed()).to.be.at.least(50); await server.stop({ timeout: 1 }); }); it('times out when client request taking too long (route override)', async () => { const server = Hapi.server({ routes: { payload: { timeout: false } } }); server.route({ method: 'POST', path: '/', options: { payload: { timeout: 50 }, handler: () => null } }); await server.start(); const request = () => { const options = { hostname: '127.0.0.1', port: server.info.port, path: '/', method: 'POST' }; const req = Http.request(options); req.on('error', Hoek.ignore); req.write('{}\n'); setTimeout(() => req.end(), 100); return new Promise((resolve) => req.once('response', resolve)); }; const timer = new Hoek.Bench(); const res = await request(); expect(res.statusCode).to.equal(408); expect(timer.elapsed()).to.be.at.least(50); await server.stop({ timeout: 1 }); }); it('returns payload when timeout is not triggered', async () => { const server = Hapi.server({ routes: { payload: { timeout: 50 } } }); server.route({ method: 'POST', path: '/', handler: () => 'fast' }); await server.start(); const { res } = await Wreck.post(`http://localhost:${server.info.port}/`); expect(res.statusCode).to.equal(200); await server.stop({ timeout: 1 }); }); it('errors if multipart payload exceeds byte limit', async () => { const multipartPayload = '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'First\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'Second\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'Third\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="field1"\r\n' + '\r\n' + 'Joe Blow\r\nalmost tricked you!\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="field1"\r\n' + '\r\n' + 'Repeated name segment\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n' + 'Content-Type: text/plain\r\n' + '\r\n' + '... contents of file1.txt ...\r\r\n' + '--AaB03x--\r\n'; const server = Hapi.server(); server.route({ method: 'POST', path: '/echo', options: { handler: () => 'result', payload: { output: 'data', parse: true, maxBytes: 5, multipart: true } } }); const res = await server.inject({ method: 'POST', url: '/echo', payload: multipartPayload, simulate: { split: true }, headers: { 'content-length': null, 'content-type': 'multipart/form-data; boundary=AaB03x' } }); expect(res.statusCode).to.equal(400); expect(res.payload.toString()).to.equal('{"statusCode":400,"error":"Bad Request","message":"Invalid multipart payload format"}'); }); it('errors if multipart disabled (default)', async () => { const multipartPayload = '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'First\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'Second\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="x"\r\n' + '\r\n' + 'Third\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="field1"\r\n' + '\r\n' + 'Joe Blow\r\nalmost tricked you!\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="field1"\r\n' + '\r\n' + 'Repeated name segment\r\n' + '--AaB03x\r\n' + 'content-disposition: form-data; name="pics"; filename="file1.txt"\r\n' + 'Content-Type: text/plain\r\n' + '\r\n' + '... contents of file1.txt ...\r\r\n' + '--AaB03x--\r\n'; const server = Hapi.server(); server.route({ method: 'POST', path: '/echo', options: { handler: () => 'result', payload: { output: 'data', parse: true, maxBytes: 5 } } }); const res = await server.inject({ method: 'POST', url: '/echo', payload: multipartPayload, simulate: { split: true }, headers: { 'content-length': null, 'content-type': 'multipart/form-data; boundary=AaB03x' } }); expect(res.statusCode).to.equal(415); }); }); ================================================ FILE: test/request.js ================================================ 'use strict'; const Http = require('http'); const Net = require('net'); const Stream = require('stream'); const Url = require('url'); const Events = require('events'); const Boom = require('@hapi/boom'); const Code = require('@hapi/code'); const Hapi = require('..'); const Hoek = require('@hapi/hoek'); const Joi = require('joi'); const Lab = require('@hapi/lab'); const Teamwork = require('@hapi/teamwork'); const Wreck = require('@hapi/wreck'); const Common = require('./common'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('Request.Generator', () => { it('decorates request multiple times', async () => { const server = Hapi.server(); server.decorate('request', 'x2', () => 2); server.decorate('request', 'abc', () => 1); server.route({ method: 'GET', path: '/', handler: (request) => { return request.x2() + request.abc(); } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal(3); }); it('decorates request with non function method', async () => { const server = Hapi.server(); const symbol = Symbol('abc'); server.decorate('request', 'x2', 2); server.decorate('request', symbol, 1); server.route({ method: 'GET', path: '/', handler: (request) => { return request.x2 + request[symbol]; } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal(3); }); it('does not share decorations between servers via prototypes', async () => { const server1 = Hapi.server(); const server2 = Hapi.server(); const route = { method: 'GET', path: '/', handler: (request) => { return Object.keys(Object.getPrototypeOf(request)); } }; let res; server1.decorate('request', 'x1', 1); server2.decorate('request', 'x2', 2); server1.route(route); server2.route(route); res = await server1.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal(['x1']); res = await server2.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal(['x2']); }); it('decorates symbols when apply=true', async () => { const server = Hapi.server(); const symbol = Symbol('abc'); server.decorate('request', symbol, () => 'foo', { apply: true }); server.route({ method: 'GET', path: '/', handler: (request) => { return request[symbol]; } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('foo'); }); }); describe('Request', () => { it('sets host and hostname', async () => { const server = Hapi.server(); const handler = (request) => { return [request.info.host, request.info.hostname].join('|'); }; server.route({ method: 'GET', path: '/', handler }); const res1 = await server.inject({ url: '/', headers: { host: 'host' } }); expect(res1.payload).to.equal('host|host'); const res2 = await server.inject({ url: '/', headers: { host: 'host:123' } }); expect(res2.payload).to.equal('host:123|host'); const res3 = await server.inject({ url: '/', headers: { host: '127.0.0.1' } }); expect(res3.payload).to.equal('127.0.0.1|127.0.0.1'); const res4 = await server.inject({ url: '/', headers: { host: '127.0.0.1:123' } }); expect(res4.payload).to.equal('127.0.0.1:123|127.0.0.1'); const res5 = await server.inject({ url: '/', headers: { host: '[::1]' } }); expect(res5.payload).to.equal('[::1]|[::1]'); const res6 = await server.inject({ url: '/', headers: { host: '[::1]:123' } }); expect(res6.payload).to.equal('[::1]:123|[::1]'); }); it('sets client address (default)', async (flags) => { const server = Hapi.server(); const handler = (request) => { // Call twice to reuse cached values if (Common.hasIPv6) { // 127.0.0.1 on node v14 and v16, ::1 on node v18 since DNS resolved to IPv6. expect(request.info.remoteAddress).to.match(/^127\.0\.0\.1|::1$/); expect(request.info.remoteAddress).to.match(/^127\.0\.0\.1|::1$/); } else { expect(request.info.remoteAddress).to.equal('127.0.0.1'); expect(request.info.remoteAddress).to.equal('127.0.0.1'); } expect(request.info.remotePort).to.be.above(0); expect(request.info.remotePort).to.be.above(0); return 'ok'; }; server.route({ method: 'get', path: '/', handler }); await server.start(); flags.onCleanup = () => server.stop(); const { payload } = await Wreck.get('http://localhost:' + server.info.port); expect(payload.toString()).to.equal('ok'); }); it('sets client address (ipv4)', async (flags) => { const server = Hapi.server(); const handler = (request) => { Object.defineProperty(request.raw.req.socket, 'remoteAddress', { value: '100.100.100.100' }); return request.info.remoteAddress; }; server.route({ method: 'get', path: '/', handler }); await server.start(); flags.onCleanup = () => server.stop(); const { payload } = await Wreck.get('http://localhost:' + server.info.port); expect(payload.toString()).to.equal('100.100.100.100'); }); it('sets client address (ipv6)', async (flags) => { const server = Hapi.server(); const handler = (request) => { Object.defineProperty(request.raw.req.socket, 'remoteAddress', { value: '::ffff:0:0:0:0:1' }); return request.info.remoteAddress; }; server.route({ method: 'get', path: '/', handler }); await server.start(); flags.onCleanup = () => server.stop(); const { payload } = await Wreck.get('http://localhost:' + server.info.port); expect(payload.toString()).to.equal('::ffff:0:0:0:0:1'); }); it('sets client address (ipv4-mapped ipv6)', async (flags) => { const server = Hapi.server(); const handler = (request) => { Object.defineProperty(request.raw.req.socket, 'remoteAddress', { value: '::ffff:100.100.100.100' }); return request.info.remoteAddress; }; server.route({ method: 'get', path: '/', handler }); await server.start(); flags.onCleanup = () => server.stop(); const { payload } = await Wreck.get('http://localhost:' + server.info.port); expect(payload.toString()).to.equal('100.100.100.100'); }); it('sets client address to nothing when not available', async (flags) => { const server = Hapi.server(); const abortedReqTeam = new Teamwork.Team(); let remoteAddr = 'not executed'; server.route({ method: 'GET', path: '/', options: { handler: async (request, h) => { req.destroy(); while (request.active()) { await Hoek.wait(5); } abortedReqTeam.attend(); remoteAddr = request.info.remoteAddress; return null; } } }); await server.start(); flags.onCleanup = () => server.stop(); const req = Http.get(server.info.uri, Hoek.ignore); req.on('error', Hoek.ignore); await abortedReqTeam.work; expect(remoteAddr).to.equal(undefined); }); it('sets port to nothing when not available', async () => { const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler: (request) => request.info.remotePort === '' }); const res = await server.inject('/'); expect(res.result).to.equal(true); }); it('sets referrer', async () => { const server = Hapi.server(); const handler = (request) => { expect(request.info.referrer).to.equal('http://site.com'); return 'ok'; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { referrer: 'http://site.com' } }); expect(res.result).to.equal('ok'); }); it('sets referer', async () => { const server = Hapi.server(); const handler = (request) => { expect(request.info.referrer).to.equal('http://site.com'); return 'ok'; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { referer: 'http://site.com' } }); expect(res.result).to.equal('ok'); }); it('sets acceptEncoding', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.info.acceptEncoding }); const res = await server.inject({ url: '/', headers: { 'accept-encoding': 'gzip' } }); expect(res.result).to.equal('gzip'); }); it('handles invalid accept encoding header', async () => { const server = Hapi.server({ routes: { log: { collect: true } } }); const handler = (request) => { expect(request.logs[0].error.header).to.equal('a;b'); return request.info.acceptEncoding; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { 'accept-encoding': 'a;b' } }); expect(res.result).to.equal('identity'); }); it('sets headers', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.headers['user-agent'] }); const res = await server.inject('/'); expect(res.payload).to.equal('shot'); }); it('sets host info from :authority header when host header is absent', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => `${request.info.host}|${request.info.hostname}` }); const res = await server.inject({ url: '/', headers: { host: '', ':authority': 'example.com:8080' } }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('example.com:8080|example.com'); }); it('generates unique request id', async () => { const server = Hapi.server(); server._core.requestCounter = { value: 10, min: 10, max: 11 }; server.route({ method: 'GET', path: '/', handler: (request) => request.info.id }); const res1 = await server.inject('/'); expect(res1.result).to.match(/10$/); const res2 = await server.inject('/'); expect(res2.result).to.match(/11$/); const res3 = await server.inject('/'); expect(res3.result).to.match(/10$/); }); it('can serialize request.info with JSON.stringify()', async () => { const server = Hapi.server(); const handler = (request) => { const actual = JSON.stringify(request.info); const expected = JSON.stringify({ acceptEncoding: request.info.acceptEncoding, completed: request.info.completed, cors: request.info.cors, host: request.info.host, hostname: request.info.hostname, id: request.info.id, received: request.info.received, referrer: request.info.referrer, remoteAddress: request.info.remoteAddress, remotePort: request.info.remotePort, responded: request.info.responded }); expect(actual).to.equal(expected); return 'ok'; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/' }); expect(res.result).to.equal('ok'); }); describe('active()', () => { it('exits handler early when request is no longer active', { retry: true }, async (flags) => { let testComplete = false; const onCleanup = []; flags.onCleanup = async () => { testComplete = true; for (const cleanup of onCleanup) { await cleanup(); } }; const server = Hapi.server(); const leaveHandlerTeam = new Teamwork.Team(); server.route({ method: 'GET', path: '/', options: { handler: async (request, h) => { req.destroy(); while (request.active() && !testComplete) { await Hoek.wait(10); } leaveHandlerTeam.attend({ active: request.active(), testComplete }); return null; } } }); await server.start(); onCleanup.unshift(() => server.stop()); const req = Http.get(server.info.uri, Hoek.ignore); req.on('error', Hoek.ignore); const note = await leaveHandlerTeam.work; expect(note).to.equal({ active: false, testComplete: false }); }); }); describe('_execute()', () => { it('returns 400 on invalid path', async () => { const server = Hapi.server(); server.ext('onRequest', (request, h) => { expect(request.url).to.be.null(); expect(request.query).to.equal({}); expect(request.path).to.equal('invalid'); return h.continue; }); const res = await server.inject('invalid'); expect(res.statusCode).to.equal(400); expect(res.result.message).to.startWith('Invalid URL'); }); it('returns boom response on ext error', async () => { const server = Hapi.server(); const ext = (request) => { throw Boom.badRequest(); }; server.ext('onPostHandler', ext); server.route({ method: 'GET', path: '/', handler: () => 'OK' }); const res = await server.inject('/'); expect(res.result.statusCode).to.equal(400); }); it('returns error response on ext error', async () => { const server = Hapi.server(); const ext = (request) => { throw new Error('oops'); }; server.ext('onPostHandler', ext); server.route({ method: 'GET', path: '/', handler: () => 'OK' }); const res = await server.inject('/'); expect(res.result.statusCode).to.equal(500); }); it('returns error response on ext timeout', async () => { const server = Hapi.server(); const responded = server.ext('onPostResponse'); const ext = (request) => { return Hoek.block(); }; server.ext('onPostHandler', ext, { timeout: 100 }); server.route({ method: 'GET', path: '/', handler: () => 'OK' }); const res = await server.inject('/'); expect(res.result.statusCode).to.equal(500); const request = await responded; expect(request.response._error).to.be.an.error('onPostHandler timed out'); }); it('logs error responses on onPostResponse ext error', async () => { const server = Hapi.server(); const ext1 = () => { throw new Error('oops1'); }; server.ext('onPostResponse', ext1); const ext2 = () => { throw new Error('oops2'); }; server.ext('onPostResponse', ext2); server.route({ method: 'GET', path: '/', handler: () => 'OK' }); const log = server.events.few({ name: 'request', channels: 'internal', filter: 'ext', count: 2 }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); const [[, event1], [, event2]] = await log; expect(event1.error).to.be.an.error('oops1'); expect(event2.error).to.be.an.error('oops2'); }); it('handles aborted requests (during response)', async () => { const handler = (request) => { const TestStream = class extends Stream.Readable { _read(size) { if (this.isDone) { return; } this.isDone = true; this.push('success'); this.emit('data', 'success'); } }; const stream = new TestStream(); return stream; }; const server = Hapi.server({ info: { remote: true } }); server.route({ method: 'GET', path: '/', handler }); let disconnected = 0; let info; const onRequest = (request, h) => { request.events.once('disconnect', () => { info = request.info; ++disconnected; }); return h.continue; }; server.ext('onRequest', onRequest); await server.start(); let total = 2; const createConnection = function () { const client = Net.connect(server.info.port, () => { client.write('GET / HTTP/1.1\r\nHost: host\r\n\r\n'); client.write('GET / HTTP/1.1\r\nHost: host\r\n\r\n'); }); client.on('data', () => { --total; client.destroy(); }); }; await new Promise((resolve) => { const check = function () { if (total) { createConnection(); setTimeout(check, 100); } else { expect(disconnected).to.equal(4); // Each connection sends two HTTP requests resolve(); } }; check(); }); await server.stop(); expect(info.remotePort).to.exist(); expect(info.remoteAddress).to.exist(); }); it('handles aborted requests (before response)', { retry: true }, async (flags) => { const server = Hapi.server(); server.route({ method: 'GET', path: '/test', handler: () => null }); const codes = []; server.ext('onPostResponse', (request) => codes.push(Boom.isBoom(request.response) ? request.response.output.statusCode : request.response.statusCode)); const team = new Teamwork.Team(); const onRequest = (request, h) => { request.events.once('disconnect', () => team.attend()); return h.continue; }; server.ext('onRequest', onRequest); let firstRequest = true; const onPreHandler = async (request, h) => { if (firstRequest) { client.destroy(); firstRequest = false; } else { // To avoid timing differences between node versions, ensure that // the second and third requests always experience the disconnect await team.work; } return h.continue; }; server.ext('onPreHandler', onPreHandler); await server.start(); flags.onCleanup = () => server.stop(); const client = Net.connect(server.info.port, () => { client.write('GET /test HTTP/1.1\r\nHost: host\r\n\r\n'); client.write('GET /test HTTP/1.1\r\nHost: host\r\n\r\n'); client.write('GET /test HTTP/1.1\r\nHost: host\r\n\r\n'); }); await team.work; await server.stop(); expect(codes).to.equal([204, 499, 499]); }); it('returns empty params array when none present', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.params }); const res = await server.inject('/'); expect(res.result).to.equal({}); }); it('returns empty params array when none present (not found)', async () => { const server = Hapi.server(); const preResponse = (request) => { return request.params; }; server.ext('onPreResponse', preResponse); const res = await server.inject('/'); expect(res.result).to.equal({}); }); it('does not fail on abort', async () => { const server = Hapi.server(); const team = new Teamwork.Team(); const handler = async (request) => { clientRequest.destroy(); await Hoek.wait(10); team.attend(); throw new Error('fail'); }; server.route({ method: 'GET', path: '/', handler }); await server.start(); const clientRequest = Http.request({ hostname: 'localhost', port: server.info.port, method: 'GET' }); clientRequest.on('error', Hoek.ignore); clientRequest.end(); await team.work; await server.stop(); }); it('does not fail on abort (onPreHandler)', async () => { const server = Hapi.server(); const team = new Teamwork.Team(); server.route({ method: 'GET', path: '/', handler: () => null }); const preHandler = async (request, h) => { clientRequest.destroy(); await Hoek.wait(10); team.attend(); return h.continue; }; server.ext('onPreHandler', preHandler); await server.start(); const clientRequest = Http.request({ hostname: 'localhost', port: server.info.port, method: 'GET' }); clientRequest.on('error', Hoek.ignore); clientRequest.end(); await team.work; await server.stop(); }); it('does not fail on abort with ext', async () => { const handler = async (request) => { clientRequest.destroy(); await Hoek.wait(10); throw new Error('boom'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const preResponse = (request, h) => { return h.continue; }; server.ext('onPreResponse', preResponse); const log = server.events.once('response'); await server.start(); const clientRequest = Http.request({ hostname: 'localhost', port: server.info.port, method: 'GET' }); clientRequest.on('error', Hoek.ignore); clientRequest.end(); await log; await server.stop(); }); it('returns not found on internal only route (external)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/some/route', options: { isInternal: true, handler: () => 'ok' } }); await server.start(); const err = await expect(Wreck.get('http://localhost:' + server.info.port)).to.reject(); expect(err.data.res.statusCode).to.equal(404); expect(err.data.payload.toString()).to.equal('{"statusCode":404,"error":"Not Found","message":"Not Found"}'); await server.stop(); }); it('returns not found on internal only route (inject)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/some/route', options: { isInternal: true, handler: () => 'ok' } }); const res = await server.inject('/some/route'); expect(res.statusCode).to.equal(404); }); it('allows internal only route (inject with allowInternals)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/some/route', options: { isInternal: true, handler: () => 'ok' } }); const res = await server.inject({ url: '/some/route', allowInternals: true }); expect(res.statusCode).to.equal(200); }); it('allows internal only route (inject with allowInternals and authority)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/some/route', options: { isInternal: true, handler: () => 'ok' } }); const res = await server.inject({ url: '/some/route', allowInternals: true, authority: 'server:8000' }); expect(res.statusCode).to.equal(200); }); it('creates arrays from multiple entries', async () => { const server = Hapi.server(); const handler = (request) => { return { a: request.query.a, array: Array.isArray(request.query.a), instance: request.query.a instanceof Array }; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/?a=1&a=2'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal({ a: ['1', '2'], array: true, instance: true }); }); it('supports custom query parser (new object)', async () => { const parser = (query) => { return { hello: query.hi }; }; const server = Hapi.server({ query: { parser } }); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.query.hello } }); const res = await server.inject('/?hi=hola'); expect(res.statusCode).to.equal(200); expect(res.payload).to.equal('hola'); }); it('supports custom query parser (same object)', async () => { const parser = (query) => { query.hello = query.hi; return query; }; const server = Hapi.server({ query: { parser } }); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.query.hello } }); const res = await server.inject('/?hi=hola'); expect(res.statusCode).to.equal(200); expect(res.payload).to.equal('hola'); }); it('returns 500 when custom query parser returns non-object', async () => { const server = Hapi.server({ debug: false, query: { parser: () => 'something' } }); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.query.hello } }); const res = await server.inject('/?hi=hola'); expect(res.statusCode).to.equal(500); expect(res.request.response._error).to.be.an.error('Parsed query must be an object'); }); it('returns 500 when custom query parser returns null', async () => { const server = Hapi.server({ debug: false, query: { parser: () => null } }); server.route({ method: 'GET', path: '/', options: { handler: (request) => request.query.hello } }); const res = await server.inject('/?hi=hola'); expect(res.statusCode).to.equal(500); expect(res.request.response._error).to.be.an.error('Parsed query must be an object'); }); }); describe('_onRequest()', () => { it('errors on non-takeover response', async () => { const server = Hapi.server({ debug: false }); server.ext('onRequest', () => 'something'); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); }); describe('_lifecycle()', () => { it('errors on non-takeover response in pre handler ext', async () => { const server = Hapi.server({ debug: false }); server.ext('onPreHandler', () => 'something'); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('logs thrown errors as boom errors', async () => { const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', options: { handler: function () { // eslint-disable-next-line no-undef NOT_DEFINED_VAR; } } }); const log = new Promise((resolve) => { server.events.on({ name: 'request', channels: 'internal' }, (request, event, tags) => { if (tags.handler && tags.error) { resolve({ event, tags }); } }); }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); const { event } = await log; expect(event.error.isBoom).to.equal(true); expect(event.error.output.statusCode).to.equal(500); expect(event.error.stack).to.exist(); }); }); describe('_postCycle()', () => { it('skips onPreResponse when validation terminates request', { retry: true }, async (flags) => { const server = Hapi.server(); const abortedReqTeam = new Teamwork.Team(); let called = false; server.ext('onPreResponse', (request, h) => { called = true; return h.continue; }); server.route({ method: 'GET', path: '/', options: { handler: (request) => { // Stash raw so that we can access it on response validation Object.assign(request.app, request.raw); return null; }, response: { status: { 200: async (_, { context }) => { req.destroy(); const raw = context.app.request; await Events.once(raw.req, 'aborted'); abortedReqTeam.attend(); } } } } }); await server.start(); flags.onCleanup = () => server.stop(); const req = Http.get(server.info.uri, Hoek.ignore); req.on('error', Hoek.ignore); await abortedReqTeam.work; await server.events.once('response'); expect(called).to.be.false(); }); it('handles continue signal', async () => { const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', options: { handler: () => ({ a: '1' }), validate: { validator: Joi }, response: { failAction: (request, h) => h.continue, schema: { b: Joi.string() } } } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); }); }); describe('_reply()', () => { it('returns a reply with auto end in onPreResponse', async () => { const server = Hapi.server(); server.ext('onPreResponse', (request, h) => h.close); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal(''); }); }); describe('_finalize()', () => { it('generate response event', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); const log = server.events.once('response'); await server.inject('/'); const [request] = await log; expect(request.info.responded).to.be.min(request.info.received); expect(request.info.completed).to.be.min(request.info.responded); expect(request.response.source).to.equal('ok'); expect(request.response.statusCode).to.equal(200); }); it('skips logging error when not the result of a thrown error', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response().code(500) }); let called = false; server.events.once('request', () => { called = true; }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); expect(res.request.response._error).to.not.exist(); expect(called).to.be.false(); }); it('destroys response after server timeout', async () => { const team = new Teamwork.Team(); const handler = async (request) => { await Hoek.wait(100); const stream = new Stream.Readable(); stream._read = function (size) { this.push('value'); this.push(null); }; stream._destroy = () => team.attend(); return stream; }; const server = Hapi.server({ routes: { timeout: { server: 50 } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(503); await team.work; }); it('does not attempt to close error response after server timeout', async () => { const handler = async (request) => { await Hoek.wait(40); throw new Error('after'); }; const server = Hapi.server({ routes: { timeout: { server: 20 } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(503); }); it('emits request-error once', async () => { const server = Hapi.server({ debug: false, routes: { log: { collect: true } } }); let errs = 0; let req = null; server.events.on({ name: 'request', channels: 'error' }, (request, { error }) => { errs++; expect(error).to.exist(); expect(error.message).to.equal('boom2'); req = request; }); const preResponse = (request) => { throw new Error('boom2'); }; server.ext('onPreResponse', preResponse); const handler = (request) => { throw new Error('boom1'); }; server.route({ method: 'GET', path: '/', handler }); const log = server.events.once('response'); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); expect(res.result).to.exist(); expect(res.result.message).to.equal('An internal server error occurred'); await log; expect(errs).to.equal(1); expect(req.logs[1].tags).to.equal(['internal', 'error']); }); it('does not emit request-error when error is replaced with valid response', async () => { const server = Hapi.server({ debug: false }); let errs = 0; server.events.on({ name: 'request', channels: 'error' }, (request, event) => { errs++; }); server.ext('onPreResponse', () => 'ok'); const handler = (request) => { throw new Error('boom1'); }; server.route({ method: 'GET', path: '/', handler }); const log = server.events.once('response'); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('ok'); await log; expect(errs).to.equal(0); }); }); describe('setMethod()', () => { it('changes method with a lowercase version of the value passed in', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => null }); const onRequest = (request, h) => { request.setMethod('POST'); return h.response(request.method).takeover(); }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.payload).to.equal('post'); }); it('errors on missing method', async () => { const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler: () => null }); server.ext('onRequest', (request) => request.setMethod()); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('errors on invalid method type', async () => { const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler: () => null }); server.ext('onRequest', (request) => request.setMethod(42)); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); }); describe('setUrl()', () => { it('sets url, path, and query', async () => { const url = 'http://localhost/page?param1=something'; const server = Hapi.server(); const handler = (request) => { return [request.url.href, request.path, request.query.param1].join('|'); }; server.route({ method: 'GET', path: '/page', handler }); const onRequest = (request, h) => { request.setUrl(url); return h.continue; }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.payload).to.equal(url + '|/page|something'); }); it('sets root url', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.url.pathname }); const onRequest = (request, h) => { request.setUrl('/'); return h.continue; }; server.ext('onRequest', onRequest); const res = await server.inject('/a/b/c'); expect(res.result).to.equal('/'); }); it('updates host info', async () => { const url = 'http://redirected:321/'; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => null }); const onRequest = (request, h) => { const initialHost = request.info.host; request.setUrl(url); return h.response([request.url.href, request.path, initialHost, request.info.host, request.info.hostname].join('|')).takeover(); }; server.ext('onRequest', onRequest); const res = await server.inject({ url: '/', headers: { host: 'initial:123' } }); expect(res.payload).to.equal(url + '|/|initial:123|redirected:321|redirected'); }); it('updates host info when set without port number', async () => { const url = 'http://redirected/'; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => null }); const onRequest = (request, h) => { const initialHost = request.info.host; request.setUrl(url); return h.response([request.url.href, request.path, initialHost, request.info.host, request.info.hostname].join('|')).takeover(); }; server.ext('onRequest', onRequest); const res1 = await server.inject({ url: '/', headers: { host: 'initial:123' } }); const res2 = await server.inject({ url: '/', headers: { host: 'initial' } }); expect(res1.payload).to.equal(url + '|/|initial:123|redirected|redirected'); expect(res2.payload).to.equal(url + '|/|initial|redirected|redirected'); }); it('overrides query string content', async () => { const server = Hapi.server(); const handler = (request) => { return [request.url.href, request.path, request.query.a].join('|'); }; server.route({ method: 'GET', path: '/', handler }); const onRequest = (request, h) => { const uri = request.raw.req.url; const parsed = new Url.URL(uri, 'http://test/'); parsed.searchParams.set('a', 2); request.setUrl(parsed); return h.continue; }; server.ext('onRequest', onRequest); const res = await server.inject('/?a=1'); expect(res.payload).to.equal('http://test/?a=2|/|2'); }); it('normalizes a path', async () => { const rawPath = '/%0%1%2%3%4%5%6%7%8%9%a%b%c%d%e%f%10%11%12%13%14%15%16%17%18%19%1a%1b%1c%1d%1e%1f%20%21%22%23%24%25%26%27%28%29%2a%2b%2c%2d%2e%2f%30%31%32%33%34%35%36%37%38%39%3a%3b%3c%3d%3e%3f%40%41%42%43%44%45%46%47%48%49%4a%4b%4c%4d%4e%4f%50%51%52%53%54%55%56%57%58%59%5a%5b%5c%5d%5e%5f%60%61%62%63%64%65%66%67%68%69%6a%6b%6c%6d%6e%6f%70%71%72%73%74%75%76%77%78%79%7a%7b%7c%7d%7e%7f%80%81%82%83%84%85%86%87%88%89%8a%8b%8c%8d%8e%8f%90%91%92%93%94%95%96%97%98%99%9a%9b%9c%9d%9e%9f%a0%a1%a2%a3%a4%a5%a6%a7%a8%a9%aa%ab%ac%ad%ae%af%b0%b1%b2%b3%b4%b5%b6%b7%b8%b9%ba%bb%bc%bd%be%bf%c0%c1%c2%c3%c4%c5%c6%c7%c8%c9%ca%cb%cc%cd%ce%cf%d0%d1%d2%d3%d4%d5%d6%d7%d8%d9%da%db%dc%dd%de%df%e0%e1%e2%e3%e4%e5%e6%e7%e8%e9%ea%eb%ec%ed%ee%ef%f0%f1%f2%f3%f4%f5%f6%f7%f8%f9%fa%fb%fc%fd%fe%ff%0%1%2%3%4%5%6%7%8%9%A%B%C%D%E%F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F%30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F%40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F%50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F%60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F%70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF'; const normPath = '/%0%1%2%3%4%5%6%7%8%9%a%b%c%d%e%f%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22%23$%25&\'()*+,-.%2F0123456789:;%3C=%3E%3F@ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF%0%1%2%3%4%5%6%7%8%9%A%B%C%D%E%F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22%23$%25&\'()*+,-.%2F0123456789:;%3C=%3E%3F@ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF'; const url = 'http://localhost' + rawPath + '?param1=something'; const normUrl = 'http://localhost' + normPath + '?param1=something'; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => null }); const onRequest = (request, h) => { request.setUrl(url); return h.response([request.url.href, request.path, request.url.searchParams.get('param1')].join('|')).takeover(); }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.payload).to.equal(normUrl + '|' + normPath + '|something'); }); it('errors on empty path', async () => { const server = Hapi.server({ debug: false }); const onRequest = (request, h) => { request.setUrl(''); return h.continue; }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('throws when path is missing', async () => { const server = Hapi.server(); const onRequest = (request, h) => { try { request.setUrl(); } catch (err) { return h.response(err.message).takeover(); } return h.continue; }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.payload).to.equal('Url must be a string or URL object'); }); it('strips trailing slash', async () => { const server = Hapi.server({ router: { stripTrailingSlash: true } }); server.route({ method: 'GET', path: '/test', handler: () => null }); const res1 = await server.inject('/test/'); expect(res1.statusCode).to.equal(204); const res2 = await server.inject('/test'); expect(res2.statusCode).to.equal(204); }); it('does not strip trailing slash on /', async () => { const server = Hapi.server({ router: { stripTrailingSlash: true } }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); }); it('strips trailing slash with query', async () => { const server = Hapi.server({ router: { stripTrailingSlash: true } }); server.route({ method: 'GET', path: '/test', handler: () => null }); const res = await server.inject('/test/?a=b'); expect(res.statusCode).to.equal(204); }); it('clones passed url', async () => { const urlObject = new Url.URL('http:/%41'); let requestUrl; const server = Hapi.server(); const onRequest = (request, h) => { request.setUrl(urlObject); requestUrl = request.url; return h.continue; }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.statusCode).to.equal(404); expect(requestUrl).to.equal(urlObject); expect(requestUrl).to.not.shallow.equal(urlObject); }); it('handles vhost redirection', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', vhost: 'one', handler: () => 'success' }); const onRequest = (request, h) => { request.setUrl('http://one/'); return h.continue; }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.payload).to.equal('success'); }); it('handles hostname in HTTP request resource', async () => { const server = Hapi.server({ debug: false }); const team = new Teamwork.Team(); let hostname; server.route({ method: 'GET', path: '/', handler: (request) => { hostname = request.info.hostname; team.attend(); return null; } }); await server.start(); const socket = Net.createConnection(server.info.port, '127.0.0.1', () => socket.write('GET http://host.com\r\n\r\n')); await team.work; socket.destroy(); await server.stop(); expect(hostname).to.equal('host.com'); }); it('handles url starting with multiple /', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/{p*}', handler: (request) => { return { p: request.params.p, path: request.path, hostname: request.info.hostname.toLowerCase() // Lowercase for OSX tests }; } }); const res = await server.inject('//path'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal({ p: '/path', path: '//path', hostname: server.info.host.toLowerCase() }); }); it('handles escaped path segments', async () => { const server = Hapi.server(); server.route({ path: '/%2F/%2F', method: 'GET', handler: (request) => request.path }); const tests = [ ['/', 404], ['////', 404], ['/%2F/%2F', 200, '/%2F/%2F'], ['/%2F/%2F#x', 200, '/%2F/%2F'], ['/%2F/%2F?a=1#x', 200, '/%2F/%2F'] ]; for (const [uri, code, result] of tests) { const res = await server.inject(uri); expect(res.statusCode).to.equal(code); if (code < 400) { expect(res.result).to.equal(result); } } }); it('handles fragments (no query)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/{p*}', handler: (request) => request.path }); await server.start(); const options = { hostname: 'localhost', port: server.info.port, path: '/path#ignore', method: 'GET' }; const team = new Teamwork.Team(); const req = Http.request(options, (res) => team.attend(res)); req.end(); const res = await team.work; const payload = await Wreck.read(res); expect(payload.toString()).to.equal('/path'); await server.stop(); }); it('handles fragments (with query)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/{p*}', handler: (request) => request.query.a }); await server.start(); const options = { hostname: 'localhost', port: server.info.port, path: '/path?a=1#ignore', method: 'GET' }; const team = new Teamwork.Team(); const req = Http.request(options, (res) => team.attend(res)); req.end(); const res = await team.work; const payload = await Wreck.read(res); expect(payload.toString()).to.equal('1'); await server.stop(); }); it('handles fragments with ? (no query)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/{p*}', handler: (request) => request.path }); await server.start(); const options = { hostname: 'localhost', port: server.info.port, path: '/path#ignore?x', method: 'GET' }; const team = new Teamwork.Team(); const req = Http.request(options, (res) => team.attend(res)); req.end(); const res = await team.work; const payload = await Wreck.read(res); expect(payload.toString()).to.equal('/path'); await server.stop(); }); it('handles absolute URL (proxy)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/{p*}', handler: (request) => request.query.a.join() }); await server.start(); const options = { hostname: 'localhost', port: server.info.port, path: 'http://example.com/path?a=1&a=2#ignore', method: 'GET' }; const team = new Teamwork.Team(); const req = Http.request(options, (res) => team.attend(res)); req.end(); const res = await team.work; const payload = await Wreck.read(res); expect(payload.toString()).to.equal('1,2'); await server.stop(); }); }); describe('url', () => { it('generates URL object lazily', async () => { const server = Hapi.server(); const handler = (request) => { expect(request._url).to.not.exist(); return request.url.pathname; }; server.route({ path: '/test', method: 'GET', handler }); const res = await server.inject('/test?a=1'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('/test'); }); it('generates URL object lazily (no host header)', async () => { const server = Hapi.server(); const handler = (request) => { delete request.info.host; expect(request._url).to.not.exist(); return request.url.pathname; }; server.route({ path: '/test', method: 'GET', handler }); const res = await server.inject('/test?a=1'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('/test'); }); it('generates valid URL when server host is IPv6 and host header is absent', async () => { const server = Hapi.server({ host: '::1' }); const handler = (request) => { delete request.info.host; expect(request._url).to.not.exist(); return request.url.host; }; server.route({ path: '/test', method: 'GET', handler }); const res = await server.inject('/test'); expect(res.statusCode).to.equal(200); expect(res.result).to.match(/^\[::1\]:\d+$/); }); }); describe('_tap()', () => { it('listens to request payload read finish', async () => { let finish; const ext = (request, h) => { finish = request.events.once('finish'); return h.continue; }; const server = Hapi.server(); server.ext('onRequest', ext); server.route({ method: 'POST', path: '/', options: { handler: () => null, payload: { parse: false } } }); const payload = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'; await server.inject({ method: 'POST', url: '/', payload }); await finish; }); it('ignores emitter when created for other events', async () => { const ext = (request, h) => { request.events; return h.continue; }; const server = Hapi.server(); server.ext('onRequest', ext); server.route({ method: 'POST', path: '/', options: { handler: () => null, payload: { parse: false } } }); const payload = '0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789'; await server.inject({ method: 'POST', url: '/', payload }); }); }); describe('log()', () => { it('outputs log data to debug console', async () => { const handler = (request) => { request.log(['implementation'], 'data'); return null; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const log = new Promise((resolve) => { const orig = console.error; console.error = function (...args) { expect(args[0]).to.equal('Debug:'); expect(args[1]).to.equal('implementation'); expect(args[2]).to.equal('\n data'); console.error = orig; resolve(); }; }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); await log; }); it('emits a request event', async () => { const server = Hapi.server(); const handler = async (request) => { const log = server.events.once({ name: 'request', channels: 'app' }); request.log(['test'], 'data'); const [, event, tags] = await log; expect(event).to.contain(['request', 'timestamp', 'tags', 'data', 'channel']); expect(event.data).to.equal('data'); expect(event.channel).to.equal('app'); expect(tags).to.equal({ test: true }); return null; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); }); it('emits a request event (function data + collect)', async () => { const server = Hapi.server({ routes: { log: { collect: true } } }); const handler = async (request) => { const log = server.events.once('request'); request.log(['test'], () => 'data'); const [, event, tags] = await log; expect(event).to.contain(['request', 'timestamp', 'tags', 'data', 'channel']); expect(event.data).to.equal('data'); expect(event.channel).to.equal('app'); expect(tags).to.equal({ test: true }); expect(request.logs[0].data).to.equal('data'); return null; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); }); it('emits a request event (function data)', async () => { const server = Hapi.server(); const handler = async (request) => { const log = server.events.once('request'); request.log(['test'], () => 'data'); const [, event, tags] = await log; expect(event).to.contain(['request', 'timestamp', 'tags', 'data', 'channel']); expect(event.data).to.equal('data'); expect(event.channel).to.equal('app'); expect(tags).to.equal({ test: true }); return null; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); }); it('outputs log to debug console without data', async () => { const handler = (request) => { request.log(['implementation']); return null; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const log = new Promise((resolve) => { const orig = console.error; console.error = function (...args) { expect(args[0]).to.equal('Debug:'); expect(args[1]).to.equal('implementation'); expect(args[2]).to.equal(''); console.error = orig; resolve(); }; }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); await log; }); it('outputs log to debug console with error data', async () => { const handler = (request) => { request.log(['implementation'], new Error('boom')); return null; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const log = new Promise((resolve) => { const orig = console.error; console.error = function (...args) { expect(args[0]).to.equal('Debug:'); expect(args[1]).to.equal('implementation'); expect(args[2]).to.contain('Error: boom'); console.error = orig; resolve(); }; }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); await log; }); it('handles invalid log data object stringify', async () => { const handler = (request) => { const obj = {}; obj.a = obj; request.log(['implementation'], obj); return null; }; const server = Hapi.server({ routes: { log: { collect: true } } }); server.route({ method: 'GET', path: '/', handler }); const log = new Promise((resolve) => { const orig = console.error; console.error = function (...args) { expect(args[0]).to.equal('Debug:'); expect(args[1]).to.equal('implementation'); expect(args[2]).to.match(/Cannot display object: Converting circular structure to JSON/); console.error = orig; resolve(); }; }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); await log; }); it('adds a log event to the request', async () => { const handler = (request) => { request.log('1', 'log event 1'); request.log(['2'], 'log event 2'); request.log(['3', '4']); request.log(['1', '4']); request.log(['2', '3']); request.log(['4']); request.log('4'); return request.logs.map((event) => event.tags).join('|'); }; const server = Hapi.server({ routes: { log: { collect: true } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.payload).to.equal('1|2|3,4|1,4|2,3|4|4'); }); it('does not output events when debug disabled', async () => { const server = Hapi.server({ debug: false }); let i = 0; const orig = console.error; console.error = function () { ++i; }; const handler = (request) => { request.log(['implementation']); return null; }; server.route({ method: 'GET', path: '/', handler }); await server.inject('/'); console.error('nothing'); expect(i).to.equal(1); console.error = orig; }); it('does not output events when debug.request disabled', async () => { const server = Hapi.server({ debug: { request: false } }); let i = 0; const orig = console.error; console.error = function () { ++i; }; const handler = (request) => { request.log(['implementation']); return null; }; server.route({ method: 'GET', path: '/', handler }); await server.inject('/'); console.error('nothing'); expect(i).to.equal(1); console.error = orig; }); it('does not output non-implementation events by default', async () => { const server = Hapi.server(); let i = 0; const orig = console.error; console.error = function () { ++i; }; const handler = (request) => { request.log(['xyz']); return null; }; server.route({ method: 'GET', path: '/', handler }); await server.inject('/'); console.error('nothing'); expect(i).to.equal(1); console.error = orig; }); it('logs nothing', async () => { const server = Hapi.server({ debug: false, routes: { log: { collect: false } } }); const handler = (request) => { expect(request.logs).to.have.length(0); return request.info.acceptEncoding; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { 'accept-encoding': 'a;b' } }); expect(res.result).to.equal('identity'); }); it('logs when only collect is true', async () => { const server = Hapi.server({ debug: false, routes: { log: { collect: true } } }); const handler = (request) => { expect(request.logs).to.have.length(1); return request.info.acceptEncoding; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { 'accept-encoding': 'a;b' } }); expect(res.result).to.equal('identity'); }); }); describe('_setResponse()', () => { it('leaves the response open when the same response is set again', async () => { const server = Hapi.server(); const postHandler = (request) => { return request.response; }; server.ext('onPostHandler', postHandler); const handler = (request) => { const stream = new Stream.Readable(); stream._read = function (size) { this.push('value'); this.push(null); }; return stream; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('value'); }); it('leaves the response open when the same response source is set again', async () => { const server = Hapi.server(); server.ext('onPostHandler', (request) => request.response.source); const handler = (request) => { const stream = new Stream.Readable(); stream._read = function (size) { this.push('value'); this.push(null); }; return stream; }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('value'); }); }); describe('timeout', () => { it('returns server error message when server taking too long', async () => { const handler = async (request) => { await Hoek.wait(100); return 'too slow'; }; const server = Hapi.server({ routes: { timeout: { server: 50 } } }); server.route({ method: 'GET', path: '/timeout', handler }); const timer = new Hoek.Bench(); const res = await server.inject('/timeout'); expect(res.statusCode).to.equal(503); expect(timer.elapsed()).to.be.at.least(49); }); it('returns server error message when server timeout happens during request execution (and handler yields)', async () => { const handler = async (request) => { await Hoek.wait(20); return null; }; const server = Hapi.server({ routes: { timeout: { server: 10 } } }); server.route({ method: 'GET', path: '/', options: { handler } }); const postHandler = (request, h) => { return h.continue; }; server.ext('onPostHandler', postHandler); const res = await server.inject('/'); expect(res.statusCode).to.equal(503); }); it('returns server error message when server timeout is short and already occurs when request executes', async () => { const server = Hapi.server({ routes: { timeout: { server: 2 } } }); server.route({ method: 'GET', path: '/', options: { handler: function () { } } }); const onRequest = async (request, h) => { await Hoek.wait(10); return h.continue; }; server.ext('onRequest', onRequest); const res = await server.inject('/'); expect(res.statusCode).to.equal(503); }); it('handles server handler timeout with onPreResponse ext', async () => { const handler = async (request) => { await Hoek.wait(20); return null; }; const server = Hapi.server({ routes: { timeout: { server: 10 } } }); server.route({ method: 'GET', path: '/', options: { handler } }); const preResponse = (request, h) => { return h.continue; }; server.ext('onPreResponse', preResponse); const res = await server.inject('/'); expect(res.statusCode).to.equal(503); }); it('does not return an error response when server is slow but faster than timeout', async () => { const slowHandler = async (request) => { await Hoek.wait(30); return 'slow'; }; const server = Hapi.server({ routes: { timeout: { server: 50 } } }); server.route({ method: 'GET', path: '/slow', options: { handler: slowHandler } }); const timer = new Hoek.Bench(); const res = await server.inject('/slow'); expect(timer.elapsed()).to.be.at.least(20); expect(res.statusCode).to.equal(200); }); it('creates error response when request is aborted while draining payload', async () => { const server = Hapi.server({ routes: { timeout: { server: false } } }); await server.start(); const log = server.events.once('response'); const ready = new Promise((resolve) => { server.ext('onRequest', (request, h) => { resolve(); return h.continue; }); }); const req = Http.request({ hostname: 'localhost', port: server.info.port, method: 'GET', headers: { 'content-length': 42 } }); req.on('error', Hoek.ignore); req.flushHeaders(); await ready; req.destroy(); const [request] = await log; expect(request.response.output.statusCode).to.equal(499); await server.stop({ timeout: 1 }); }); it('returns an unlogged bad request error when parser fails before request is setup', async () => { const server = Hapi.server({ routes: { timeout: { server: false } } }); await server.start(); let responseCount = 0; server.events.on('response', () => { responseCount += 1; }); const client = Net.connect(server.info.port); const clientEnded = new Promise((resolve, reject) => { let response = ''; client.on('data', (chunk) => { response = response + chunk.toString(); }); client.on('end', () => resolve(response)); client.on('error', reject); }); await new Promise((resolve) => client.on('connect', resolve)); client.write('hello\n\r'); const clientResponse = await clientEnded; expect(clientResponse).to.contain('400 Bad Request'); expect(responseCount).to.equal(0); await server.stop({ timeout: 1 }); }); it('returns normal response when parser fails with bad method after request is setup', async () => { const server = Hapi.server({ routes: { timeout: { server: false } } }); server.route({ path: '/', method: 'GET', handler: () => 'PAYLOAD' }); await server.start(); const log = server.events.once('response'); const client = Net.connect(server.info.port); const clientEnded = Wreck.read(client); await new Promise((resolve) => client.on('connect', resolve)); client.write('GET / HTTP/1.1\r\nHost: test\r\nContent-Length: 0\r\n\r\ninvalid data'); const [request] = await log; expect(request.response.statusCode).to.equal(200); expect(request.response.source).to.equal('PAYLOAD'); const clientResponse = (await clientEnded).toString(); expect(clientResponse).to.contain('HTTP/1.1 200 OK'); const nextResponse = clientResponse.slice(clientResponse.indexOf('PAYLOAD') + 7); expect(nextResponse).to.startWith('HTTP/1.1 400 Bad Request'); await server.stop({ timeout: 1 }); }); it('returns nothing when parser fails with bad method after request is setup and the connection is closed', async () => { const server = Hapi.server({ routes: { timeout: { server: false } } }); server.route({ path: '/', method: 'GET', handler: (request, h) => { request.raw.res.destroy(); return h.abandon; } }); await server.start(); const log = server.events.once('response'); const client = Net.connect(server.info.port); const clientEnded = Wreck.read(client); await new Promise((resolve) => client.on('connect', resolve)); client.write('GET / HTTP/1.1\r\nHost: test\r\nContent-Length: 0\r\n\r\n\r\ninvalid data'); const [request] = await log; expect(request.response.statusCode).to.be.undefined(); const clientResponse = (await clientEnded).toString(); expect(clientResponse).to.equal(''); await server.stop({ timeout: 1 }); }); it('returns a bad request when parser fails after request is setup (cleanStop false)', async () => { const server = Hapi.server({ routes: { timeout: { server: false } }, operations: { cleanStop: false } }); server.route({ path: '/', method: 'GET', handler: Hoek.block }); await server.start(); const client = Net.connect(server.info.port); const clientEnded = new Promise((resolve, reject) => { let response = ''; client.on('data', (chunk) => { response = response + chunk.toString(); }); client.on('end', () => resolve(response)); client.on('error', reject); }); await new Promise((resolve) => client.on('connect', resolve)); client.write('GET / HTTP/1.1\r\nHost: test\nContent-Length: 0\r\n\r\ninvalid data'); const clientResponse = await clientEnded; expect(clientResponse).to.contain('400 Bad Request'); await server.stop({ timeout: 1 }); }); it('returns a bad request for POST request when chunked parsing fails', async () => { const server = Hapi.server({ routes: { timeout: { server: false } } }); server.route({ path: '/', method: 'POST', handler: () => 'ok', options: { payload: { parse: true } } }); await server.start(); const log = server.events.once('response'); const client = Net.connect(server.info.port); const clientEnded = Wreck.read(client); await new Promise((resolve) => client.on('connect', resolve)); client.write('POST / HTTP/1.1\r\nHost: test\r\nTransfer-Encoding: chunked\r\n\r\n'); await Hoek.wait(10); client.write('not chunked\r\n'); const [request] = await log; expect(request.response.statusCode).to.equal(400); expect(request.response.source).to.contain({ error: 'Bad Request' }); const clientResponse = (await clientEnded).toString(); expect(clientResponse).to.contain('400 Bad Request'); await server.stop({ timeout: 1 }); }); it('returns a bad request for POST request when chunked parsing fails (cleanStop false)', async () => { const server = Hapi.server({ routes: { timeout: { server: false } }, operations: { cleanStop: false } }); server.route({ path: '/', method: 'POST', handler: () => 'ok', options: { payload: { parse: true } } }); await server.start(); const client = Net.connect(server.info.port); const clientEnded = Wreck.read(client); await new Promise((resolve) => client.on('connect', resolve)); client.write('POST / HTTP/1.1\r\nHost: test\r\nTransfer-Encoding: chunked\r\n\r\n'); await Hoek.wait(10); client.write('not chunked\r\n'); const clientResponse = (await clientEnded).toString(); expect(clientResponse).to.contain('400 Bad Request'); await server.stop({ timeout: 1 }); }); it('returns a bad request for POST request when chunked parsing fails', async () => { const server = Hapi.server({ routes: { timeout: { server: false } } }); server.route({ path: '/', method: 'POST', handler: () => 'ok', options: { payload: { parse: true } } }); await server.start(); const log = server.events.once('response'); const client = Net.connect(server.info.port); const clientEnded = Wreck.read(client); await new Promise((resolve) => client.on('connect', resolve)); client.write('POST / HTTP/1.1\r\nHost: test\r\nContent-Length: 5\r\n\r\n'); await Hoek.wait(10); client.write('111A1'); // Doesn't work if 'A' is replaced with '1' !?! client.write('\Q\r\n'); // Extra bytes considered to be start of next request client.end(); const [request] = await log; expect(request.response.statusCode).to.equal(400); expect(request.response.source).to.contain({ error: 'Bad Request' }); const clientResponse = (await clientEnded).toString(); expect(clientResponse).to.contain('400 Bad Request'); await server.stop({ timeout: 1 }); }); it('does not return an error when server is responding when the timeout occurs', async () => { let ended = false; const TestStream = class extends Stream.Readable { _read(size) { if (this.isDone) { return; } this.isDone = true; this.push('Hello'); setTimeout(() => { this.push(null); ended = true; }, 150); } }; const handler = (request) => { return new TestStream(); }; const timer = new Hoek.Bench(); const server = Hapi.server({ routes: { timeout: { server: 100 } } }); server.route({ method: 'GET', path: '/', handler }); await server.start(); const { res } = await Wreck.get('http://localhost:' + server.info.port); expect(ended).to.be.true(); expect(timer.elapsed()).to.be.at.least(150); expect(res.statusCode).to.equal(200); await server.stop({ timeout: 1 }); }); it('does not return an error response when server is slower than timeout but response has started', async () => { const streamHandler = (request) => { const TestStream = class extends Stream.Readable { _read(size) { if (this.isDone) { return; } this.isDone = true; setTimeout(() => { this.push('Hello'); }, 30); setTimeout(() => { this.push(null); }, 60); } }; return new TestStream(); }; const server = Hapi.server({ routes: { timeout: { server: 50 } } }); server.route({ method: 'GET', path: '/stream', options: { handler: streamHandler } }); await server.start(); const { res } = await Wreck.get(`http://localhost:${server.info.port}/stream`); expect(res.statusCode).to.equal(200); await server.stop({ timeout: 1 }); }); it('does not return an error response when server takes less than timeout to respond', async () => { const server = Hapi.server({ routes: { timeout: { server: 50 } } }); server.route({ method: 'GET', path: '/fast', handler: () => 'Fast' }); const res = await server.inject('/fast'); expect(res.statusCode).to.equal(200); }); it('handles race condition between equal client and server timeouts', async (flags) => { const onCleanup = []; flags.onCleanup = async () => { for (const cleanup of onCleanup) { await cleanup(); } }; const server = Hapi.server({ routes: { timeout: { server: 100 }, payload: { timeout: 100 } } }); server.route({ method: 'POST', path: '/timeout', options: { handler: Hoek.block } }); await server.start(); onCleanup.unshift(() => server.stop()); const timer = new Hoek.Bench(); const options = { hostname: 'localhost', port: server.info.port, path: '/timeout', method: 'POST' }; const req = Http.request(options); onCleanup.unshift(() => req.destroy()); req.write('\n'); const [res] = await Events.once(req, 'response'); expect([503, 408]).to.contain(res.statusCode); expect(timer.elapsed()).to.be.at.least(80); await Events.once(req, 'close'); // Ensures that req closes without error }); }); describe('event()', () => { it('does not emit request error on normal close', async () => { const server = Hapi.server(); const events = []; server.events.on('request', (request, event, tags) => events.push(tags)); server.route({ method: 'GET', path: '/', handler: () => 'ok' }); await server.start(); const { payload } = await Wreck.get('http://localhost:' + server.info.port); expect(payload.toString()).to.equal('ok'); await server.stop(); expect(events).to.have.length(0); }); }); }); ================================================ FILE: test/response.js ================================================ 'use strict'; const Events = require('events'); const Http = require('http'); const Path = require('path'); const Stream = require('stream'); const Code = require('@hapi/code'); const Handlebars = require('handlebars'); const LegacyReadableStream = require('legacy-readable-stream'); const Hapi = require('..'); const Inert = require('@hapi/inert'); const Lab = require('@hapi/lab'); const Vision = require('@hapi/vision'); const Response = require('../lib/response'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('Response', () => { it('returns a response', async () => { const handler = (request, h) => { return h.response('text') .type('text/plain') .charset('ISO-8859-1') .ttl(1000) .header('set-cookie', 'abc=123') .state('sid', 'abcdefg123456') .state('other', 'something', { isSecure: true }) .unstate('x') .header('Content-Type', 'text/plain; something=something') .header('vary', 'x-control') .header('combo', 'o') .header('combo', 'k', { append: true, separator: '-' }) .header('combo', 'bad', { override: false }) .code(200) .message('Super'); }; const server = Hapi.server({ compression: { minBytes: 1 } }); server.route({ method: 'GET', path: '/', options: { handler, cache: { expiresIn: 9999 } } }); server.state('sid', { encoding: 'base64' }); server.state('always', { autoValue: 'present' }); const postHandler = (request, h) => { h.state('test', '123'); h.unstate('empty', { path: '/path' }); return h.continue; }; server.ext('onPostHandler', postHandler); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.exist(); expect(res.result).to.equal('text'); expect(res.statusMessage).to.equal('Super'); expect(res.headers['cache-control']).to.equal('max-age=1, must-revalidate, private'); expect(res.headers['content-type']).to.equal('text/plain; something=something; charset=ISO-8859-1'); expect(res.headers['set-cookie']).to.equal(['abc=123', 'sid=YWJjZGVmZzEyMzQ1Ng==; Secure; HttpOnly; SameSite=Strict', 'other=something; Secure; HttpOnly; SameSite=Strict', 'x=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Strict', 'test=123; Secure; HttpOnly; SameSite=Strict', 'empty=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Strict; Path=/path', 'always=present; Secure; HttpOnly; SameSite=Strict']); expect(res.headers.vary).to.equal('x-control,accept-encoding'); expect(res.headers.combo).to.equal('o-k'); }); it('sets content-type charset (trailing semi column)', async () => { const handler = (request, h) => { return h.response('text').header('Content-Type', 'text/plain; something=something;'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['content-type']).to.equal('text/plain; something=something; charset=utf-8'); }); describe('_setSource()', () => { it('returns an empty string response', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => '' }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); expect(res.headers['content-length']).to.not.exist(); expect(res.headers['content-type']).to.equal('text/html; charset=utf-8'); expect(res.result).to.equal(null); expect(res.payload).to.equal(''); }); it('returns a null response', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); expect(res.headers['content-length']).to.not.exist(); expect(res.headers['content-type']).to.not.exist(); expect(res.result).to.equal(null); expect(res.payload).to.equal(''); }); it('returns a stream', async () => { const handler = (request) => { const stream = new Stream.Readable({ read() { this.push('x'); this.push(null); } }); return stream; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('x'); expect(res.statusCode).to.equal(200); expect(res.headers['content-type']).to.equal('application/octet-stream'); }); }); describe('code()', () => { it('sets manual code regardless of emptyStatusCode override', async () => { const server = Hapi.server({ routes: { response: { emptyStatusCode: 200 } } }); server.route({ method: 'GET', path: '/', handler: (request, h) => h.response().code(204) }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); }); }); describe('header()', () => { it('appends to set-cookie header', async () => { const handler = (request, h) => { return h.response('ok').header('set-cookie', 'A').header('set-cookie', 'B', { append: true }); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['set-cookie']).to.equal(['A', 'B']); }); it('sets null header', async () => { const handler = (request, h) => { return h.response('ok').header('set-cookie', null); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['set-cookie']).to.not.exist(); }); it('throws error on non-ascii value', async () => { const handler = (request, h) => { return h.response('ok').header('set-cookie', decodeURIComponent('%E0%B4%8Aset-cookie:%20foo=bar')); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('throws error on non-ascii value (header name)', async () => { const handler = (request, h) => { const badName = decodeURIComponent('%E0%B4%8Aset-cookie:%20foo=bar'); return h.response('ok').header(badName, 'value'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('throws error on non-ascii value (buffer)', async () => { const handler = (request, h) => { return h.response('ok').header('set-cookie', Buffer.from(decodeURIComponent('%E0%B4%8Aset-cookie:%20foo=bar'))); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); }); describe('created()', () => { it('returns a response (created)', async () => { const handler = (request, h) => { return h.response({ a: 1 }).created('/special'); }; const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler }); const res = await server.inject({ method: 'POST', url: '/' }); expect(res.result).to.equal({ a: 1 }); expect(res.statusCode).to.equal(201); expect(res.headers.location).to.equal('/special'); expect(res.headers['cache-control']).to.equal('no-cache'); }); it('returns error on created with GET', async () => { const handler = (request, h) => { return h.response().created('/something'); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('does not return an error on created with PUT', async () => { const handler = (request, h) => { return h.response({ a: 1 }).created(); }; const server = Hapi.server(); server.route({ method: 'PUT', path: '/', handler }); const res = await server.inject({ method: 'PUT', url: '/' }); expect(res.result).to.equal({ a: 1 }); expect(res.statusCode).to.equal(201); }); it('does not return an error on created with PATCH', async () => { const handler = (request, h) => { return h.response({ a: 1 }).created(); }; const server = Hapi.server(); server.route({ method: 'PATCH', path: '/', handler }); const res = await server.inject({ method: 'PATCH', url: '/' }); expect(res.result).to.equal({ a: 1 }); expect(res.statusCode).to.equal(201); }); }); describe('state()', () => { it('returns an error on bad cookie', async () => { const handler = (request, h) => { return h.response('text').state(';sid', 'abcdefg123456'); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.exist(); expect(res.statusCode).to.equal(500); expect(res.result.message).to.equal('An internal server error occurred'); expect(res.headers['set-cookie']).to.not.exist(); }); }); describe('unstate()', () => { it('allows options', async () => { const handler = (request, h) => { return h.response().unstate('session', { path: '/unset', isSecure: true }); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); expect(res.headers['set-cookie']).to.equal(['session=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; SameSite=Strict; Path=/unset']); }); }); describe('vary()', () => { it('sets Vary header with single value', async () => { const handler = (request, h) => { return h.response('ok').vary('x'); }; const server = Hapi.server({ compression: { minBytes: 1 } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('ok'); expect(res.statusCode).to.equal(200); expect(res.headers.vary).to.equal('x,accept-encoding'); }); it('sets Vary header with multiple values', async () => { const handler = (request, h) => { return h.response('ok').vary('x').vary('y'); }; const server = Hapi.server({ compression: { minBytes: 1 } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('ok'); expect(res.statusCode).to.equal(200); expect(res.headers.vary).to.equal('x,y,accept-encoding'); }); it('sets Vary header with *', async () => { const handler = (request, h) => { return h.response('ok').vary('*'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('ok'); expect(res.statusCode).to.equal(200); expect(res.headers.vary).to.equal('*'); }); it('leaves Vary header with * on additional values', async () => { const handler = (request, h) => { return h.response('ok').vary('*').vary('x'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('ok'); expect(res.statusCode).to.equal(200); expect(res.headers.vary).to.equal('*'); }); it('drops other Vary header values when set to *', async () => { const handler = (request, h) => { return h.response('ok').vary('x').vary('*'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('ok'); expect(res.statusCode).to.equal(200); expect(res.headers.vary).to.equal('*'); }); it('sets Vary header with multiple similar and identical values', async () => { const handler = (request, h) => { return h.response('ok').vary('x').vary('xyz').vary('xy').vary('x'); }; const server = Hapi.server({ compression: { minBytes: 1 } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('ok'); expect(res.statusCode).to.equal(200); expect(res.headers.vary).to.equal('x,xyz,xy,accept-encoding'); }); }); describe('etag()', () => { it('sets etag', async () => { const handler = (request, h) => { return h.response('ok').etag('abc'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers.etag).to.equal('"abc"'); }); it('sets weak etag', async () => { const handler = (request, h) => { return h.response('ok').etag('abc', { weak: true }); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers.etag).to.equal('W/"abc"'); }); it('ignores varyEtag when etag header is removed', async () => { const handler = (request, h) => { const response = h.response('ok').etag('abc').vary('x'); delete response.headers.etag; return response; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers.etag).to.not.exist(); }); it('leaves etag header when varyEtag is false', async () => { const handler = (request, h) => { return h.response('ok').etag('abc', { vary: false }).vary('x'); }; const server = Hapi.server({ compression: { minBytes: 1 } }); server.route({ method: 'GET', path: '/', handler }); const res1 = await server.inject('/'); expect(res1.statusCode).to.equal(200); expect(res1.headers.etag).to.equal('"abc"'); const res2 = await server.inject({ url: '/', headers: { 'if-none-match': '"abc-gzip"', 'accept-encoding': 'gzip' } }); expect(res2.statusCode).to.equal(200); expect(res2.headers.etag).to.equal('"abc"'); }); it('applies varyEtag when returning 304 due to if-modified-since match', async () => { const mdate = new Date().toUTCString(); const handler = (request, h) => { return h.response('ok').etag('abc').header('last-modified', mdate); }; const server = Hapi.server({ compression: { minBytes: 1 } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject({ url: '/', headers: { 'if-modified-since': mdate, 'accept-encoding': 'gzip' } }); expect(res.statusCode).to.equal(304); expect(res.headers.etag).to.equal('"abc-gzip"'); }); }); describe('passThrough()', () => { it('passes stream headers and code through', async () => { const TestStream = class extends Stream.Readable { constructor() { super(); this.statusCode = 299; this.headers = { xcustom: 'some value', 'content-type': 'something/special' }; } _read(size) { if (this.isDone) { return; } this.isDone = true; this.push('x'); this.push(null); } }; const handler = (request) => { return new TestStream(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('x'); expect(res.statusCode).to.equal(299); expect(res.headers.xcustom).to.equal('some value'); expect(res.headers['content-type']).to.equal('something/special'); }); it('excludes connection header and connection options', async () => { const upstreamConnectionHeader = 'x-test, x-test-also'; const TestStream = class extends Stream.Readable { constructor() { super(); this.statusCode = 200; this.headers = { connection: upstreamConnectionHeader, 'x-test': 'something', 'x-test-also': 'also' }; } _read(size) { if (this.isDone) { return; } this.isDone = true; this.push('x'); this.push(null); } }; const handler = (request) => { return new TestStream(); }; const server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('x'); expect(res.statusCode).to.equal(200); expect(res.headers.connection).to.not.equal(upstreamConnectionHeader); expect(res.headers['x-test']).to.not.exist(); expect(res.headers['x-test-also']).to.not.exist(); }); it('excludes stream headers and code when passThrough is false', async () => { const TestStream = class extends Stream.Readable { constructor() { super(); this.statusCode = 299; this.headers = { xcustom: 'some value' }; } _read(size) { if (this.isDone) { return; } this.isDone = true; this.push('x'); this.push(null); } }; const handler = (request, h) => { return h.response(new TestStream()).passThrough(false); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('x'); expect(res.statusCode).to.equal(200); expect(res.headers.xcustom).to.not.exist(); }); it('ignores stream headers when empty', async () => { const TestStream = class extends Stream.Readable { constructor() { super(); this.statusCode = 299; this.headers = {}; } _read(size) { if (this.isDone) { return; } this.isDone = true; this.push('x'); this.push(null); } }; const handler = (request) => { return new TestStream(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('x'); expect(res.statusCode).to.equal(299); expect(res.headers.xcustom).to.not.exist(); }); it('retains local headers with stream headers pass-through', async () => { const TestStream = class extends Stream.Readable { constructor() { super(); this.headers = { xcustom: 'some value', 'set-cookie': 'a=1' }; } _read(size) { if (this.isDone) { return; } this.isDone = true; this.push('x'); this.push(null); } }; const handler = (request, h) => { return h.response(new TestStream()).header('xcustom', 'other value').state('b', '2'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('x'); expect(res.headers.xcustom).to.equal('other value'); expect(res.headers['set-cookie']).to.equal(['a=1', 'b=2; Secure; HttpOnly; SameSite=Strict']); }); }); describe('replacer()', () => { it('errors when called on wrong type', async () => { const handler = (request, h) => { return h.response('x').replacer(['x']); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); }); describe('compressed()', () => { it('errors on missing encoding', async () => { const handler = (request, h) => { return h.response('x').compressed(); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('errors on invalid encoding', async () => { const handler = (request, h) => { return h.response('x').compressed(123); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); }); describe('spaces()', () => { it('errors when called on wrong type', async () => { const handler = (request, h) => { return h.response('x').spaces(2); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); }); describe('suffix()', () => { it('errors when called on wrong type', async () => { const handler = (request, h) => { return h.response('x').suffix('x'); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); }); describe('escape()', () => { it('returns 200 when called with true', async () => { const handler = (request, h) => { return h.response({ x: 'x' }).escape(true); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); }); it('errors when called on wrong type', async () => { const handler = (request, h) => { return h.response('x').escape('x'); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); }); describe('type()', () => { it('returns a file in the response with the correct headers using custom mime type', async () => { const server = Hapi.server({ routes: { files: { relativeTo: Path.join(__dirname, '../') } } }); await server.register(Inert); const handler = (request, h) => { return h.file('./LICENSE.md').type('application/example'); }; server.route({ method: 'GET', path: '/file', handler }); const res = await server.inject('/file'); expect(res.headers['content-type']).to.equal('application/example'); }); }); describe('charset()', () => { it('sets charset with default type', async () => { const handler = (request, h) => { return h.response('text').charset('abc'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['content-type']).to.equal('text/html; charset=abc'); }); it('sets charset with default type in onPreResponse', async () => { const onPreResponse = (request, h) => { request.response.charset('abc'); return h.continue; }; const server = Hapi.server(); server.ext('onPreResponse', onPreResponse); server.route({ method: 'GET', path: '/', handler: () => 'text' }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['content-type']).to.equal('text/html; charset=abc'); }); it('sets type inside marshal', async () => { const handler = (request) => { const marshal = (response) => { if (!response.headers['content-type']) { response.type('text/html'); } return response.source.value; }; return request.generateResponse({ value: 'text' }, { variety: 'test', marshal }); }; const onPreResponse = (request, h) => { request.response.charset('abc'); return h.continue; }; const server = Hapi.server(); server.ext('onPreResponse', onPreResponse); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.headers['content-type']).to.equal('text/html; charset=abc'); }); }); describe('redirect()', () => { it('returns a redirection response', async () => { const handler = (request, h) => { return h.response('Please wait while we send your elsewhere').redirect('/example'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('http://example.org/'); expect(res.result).to.exist(); expect(res.headers.location).to.equal('/example'); expect(res.statusCode).to.equal(302); }); it('returns a redirection response using verbose call', async () => { const handler = (request, h) => { return h.response('We moved!').redirect().location('/examplex'); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.exist(); expect(res.result).to.equal('We moved!'); expect(res.headers.location).to.equal('/examplex'); expect(res.statusCode).to.equal(302); }); it('returns a 301 redirection response', async () => { const handler = (request, h) => { return h.response().redirect('example').permanent().rewritable(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(301); }); it('returns a 302 redirection response', async () => { const handler = (request, h) => { return h.response().redirect('example').temporary().rewritable(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(302); }); it('returns a 307 redirection response', async () => { const handler = (request, h) => { return h.response().redirect('example').temporary().rewritable(false); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(307); }); it('returns a 308 redirection response', async () => { const handler = (request, h) => { return h.response().redirect('example').permanent().rewritable(false); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(308); }); it('returns a 301 redirection response (reversed methods)', async () => { const handler = (request, h) => { return h.response().redirect('example').rewritable().permanent(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(301); }); it('returns a 302 redirection response (reversed methods)', async () => { const handler = (request, h) => { return h.response().redirect('example').rewritable().temporary(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(302); }); it('returns a 307 redirection response (reversed methods)', async () => { const handler = (request, h) => { return h.response().redirect('example').rewritable(false).temporary(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(307); }); it('returns a 308 redirection response (reversed methods)', async () => { const handler = (request, h) => { return h.response().redirect('example').rewritable(false).permanent(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(308); }); it('returns a 302 redirection response (flip flop)', async () => { const handler = (request, h) => { return h.response().redirect('example').permanent().temporary(); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(302); }); }); describe('_marshal()', () => { it('emits request-error when view file for handler not found', async () => { const server = Hapi.server({ debug: false }); await server.register(Vision); server.views({ engines: { 'html': Handlebars }, path: __dirname }); const log = server.events.once({ name: 'request', channels: 'error' }); server.route({ method: 'GET', path: '/{param}', handler: { view: 'templates/invalid' } }); const res = await server.inject('/hello'); expect(res.statusCode).to.equal(500); expect(res.result).to.exist(); expect(res.result.message).to.equal('An internal server error occurred'); const [, event] = await log; expect(event.error.message).to.contain('The partial x could not be found: The partial x could not be found'); }); it('returns a formatted response (spaces)', async () => { const handler = (request) => { return { a: 1, b: 2, '<': '&' }; }; const server = Hapi.server({ routes: { json: { space: 4, suffix: '\n', escape: true } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.payload).to.equal('{\n \"a\": 1,\n \"b\": 2,\n \"\\u003c\": \"\\u0026\"\n}\n'); }); it('returns a formatted response (replacer and spaces', async () => { const handler = (request) => { return { a: 1, b: 2, '<': '&' }; }; const server = Hapi.server({ routes: { json: { replacer: ['a', '<'], space: 4, suffix: '\n', escape: true } } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.payload).to.equal('{\n \"a\": 1,\n \"\\u003c\": \"\\u0026\"\n}\n'); }); it('returns a response with options', async () => { const handler = (request, h) => { return h.response({ a: 1, b: 2, '<': '&' }).type('application/x-test').spaces(2).replacer(['a']).suffix('\n').escape(false); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.payload).to.equal('{\n \"a\": 1\n}\n'); expect(res.headers['content-type']).to.equal('application/x-test'); }); it('returns a response with options (different order)', async () => { const handler = (request, h) => { return h.response({ a: 1, b: 2, '<': '&' }).type('application/x-test').escape(false).replacer(['a']).suffix('\n').spaces(2); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.payload).to.equal('{\n \"a\": 1\n}\n'); expect(res.headers['content-type']).to.equal('application/x-test'); }); it('captures object which cannot be stringify', async () => { const handler = (request) => { const obj = {}; obj.a = obj; return obj; }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('errors on non-readable stream response', async () => { const streamHandler = (request, h) => { const stream = new Stream(); stream.writable = true; return h.response(stream); }; const writableHandler = (request, h) => { const writable = new Stream.Writable(); writable._write = function () { }; return h.response(writable); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/stream', handler: streamHandler }); server.route({ method: 'GET', path: '/writable', handler: writableHandler }); await server.initialize(); const log1 = server.events.once({ name: 'request', channels: 'error' }); const res1 = await server.inject('/stream'); expect(res1.statusCode).to.equal(500); const [, event1] = await log1; expect(event1.error).to.be.an.error('Cannot reply with a stream-like object that is not an instance of Stream.Readable'); const log2 = server.events.once({ name: 'request', channels: 'error' }); const res2 = await server.inject('/writable'); expect(res2.statusCode).to.equal(500); const [, event2] = await log2; expect(event2.error).to.be.an.error('Cannot reply with a stream-like object that is not an instance of Stream.Readable'); }); it('errors on an http client stream response', async () => { const streamHandler = (request, h) => { const req = Http.get(request.server.info.uri); req.abort(); return h.response(req); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/stream', handler: streamHandler }); const log = server.events.once({ name: 'request', channels: 'error' }); await server.initialize(); const res = await server.inject('/stream'); expect(res.statusCode).to.equal(500); const [, event] = await log; expect(event.error).to.be.an.error('Cannot reply with a stream-like object that is not an instance of Stream.Readable'); }); it('errors on a legacy readable stream response', async () => { const streamHandler = () => { const stream = new LegacyReadableStream.Readable(); stream._read = function (size) { const chunk = new Array(size).join('x'); setTimeout(() => { this.push(chunk); }, 10); }; return stream; }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/stream', handler: streamHandler }); const log = server.events.once({ name: 'request', channels: 'error' }); await server.initialize(); const res = await server.inject('/stream'); expect(res.statusCode).to.equal(500); const [, event] = await log; expect(event.error).to.be.an.error('Cannot reply with a stream-like object that is not an instance of Stream.Readable'); }); it('errors on objectMode stream response', async () => { const TestStream = class extends Stream.Readable { constructor() { super({ objectMode: true }); } _read(size) { if (this.isDone) { return; } this.isDone = true; this.push({ x: 1 }); this.push({ y: 1 }); this.push(null); } }; const handler = (request, h) => { return h.response(new TestStream()); }; const server = Hapi.server({ debug: false }); server.route({ method: 'GET', path: '/', handler }); const log = server.events.once({ name: 'request', channels: 'error' }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); const [, event] = await log; expect(event.error).to.be.an.error('Cannot reply with stream in object mode'); }); }); describe('_prepare()', () => { it('boomifies response prepare error', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => { const prepare = () => { throw new Error('boom'); }; return request.generateResponse('nothing', { variety: 'special', marshal: null, prepare, close: null }); } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(500); }); it('is only called once for returned responses', async () => { let calls = 0; const pre = (request, h) => { const prepare = (response) => { ++calls; return response; }; return request.generateResponse(null, { prepare }); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { pre: [ { method: pre, assign: 'p' } ], handler: (request) => request.preResponses.p } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); expect(calls).to.equal(1); }); }); describe('_tap()', () => { it('peeks into the response stream', async () => { const server = Hapi.server(); let output = ''; server.route({ method: 'GET', path: '/', handler: (request, h) => { const response = h.response('1234567890'); response.events.on('peek', (chunk, encoding) => { output += chunk.toString(); }); response.events.once('finish', () => { output += '!'; }); return response; } }); await server.inject('/'); expect(output).to.equal('1234567890!'); }); it('peeks into the response stream (finish only)', async () => { const server = Hapi.server(); let output = false; server.route({ method: 'GET', path: '/', handler: (request, h) => { const response = h.response('1234567890'); response.events.once('finish', () => { output = true; }); return response; } }); await server.inject('/'); expect(output).to.be.true(); }); it('peeks into the response stream (empty)', async () => { const server = Hapi.server(); let output = ''; server.route({ method: 'GET', path: '/', handler: (request, h) => { const response = h.response(null); response.events.on('peek', (chunk, encoding) => { }); response.events.once('finish', () => { output += '!'; }); return response; } }); await server.inject('/'); expect(output).to.equal('!'); }); it('peeks into the response stream (empty 304)', async () => { const server = Hapi.server(); let output = ''; server.route({ method: 'GET', path: '/', handler: (request, h) => { const response = h.response(null).code(304); response.events.on('peek', (chunk, encoding) => { }); response.events.once('finish', () => { output += '!'; }); return response; } }); await server.inject('/'); expect(output).to.equal('!'); }); }); describe('_close()', () => { it('calls custom close processor', async () => { let closed = false; const close = function (response) { closed = true; }; const handler = (request) => { return request.generateResponse(null, { close }); }; const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler }); await server.inject('/'); expect(closed).to.be.true(); }); it('logs custom close processor error', async () => { const close = function (response) { throw new Error('oops'); }; const handler = (request) => { return request.generateResponse(null, { close }); }; const server = Hapi.server(); const log = server.events.once('request'); server.route({ method: 'GET', path: '/', handler }); await server.inject('/'); const [, event] = await log; expect(event.tags).to.equal(['response', 'cleanup', 'error']); expect(event.error).to.be.an.error('oops'); }); }); describe('Peek', () => { it('taps into pass-through stream', async () => { // Source const Source = class extends Stream.Readable { constructor(values) { super(); this.data = values; this.pos = 0; } _read(/* size */) { if (this.pos === this.data.length) { this.push(null); return; } this.push(this.data[this.pos++]); } }; // Target const Target = class extends Stream.Writable { constructor() { super(); this.data = []; } _write(chunk, encoding, callback) { this.data.push(chunk.toString()); return callback(); } }; // Peek const emitter = new Events.EventEmitter(); const peek = new Response.Peek(emitter); const chunks = ['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx']; const source = new Source(chunks); const target = new Target(); const seen = []; emitter.on('peek', (update) => { const chunk = update[0]; seen.push(chunk.toString()); }); const finish = new Promise((resolve) => { emitter.once('finish', () => { expect(seen).to.equal(chunks); expect(target.data).to.equal(chunks); resolve(); }); }); source.pipe(peek).pipe(target); await finish; }); }); }); ================================================ FILE: test/route.js ================================================ 'use strict'; const Path = require('path'); const Code = require('@hapi/code'); const Hapi = require('..'); const Inert = require('@hapi/inert'); const Joi = require('joi'); const Lab = require('@hapi/lab'); const Subtext = require('@hapi/subtext'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('Route', () => { it('registers with options function', async () => { const server = Hapi.server(); server.bind({ a: 1 }); server.app.b = 2; server.route({ method: 'GET', path: '/', options: function (srv) { const a = this.a; return { handler: () => a + srv.app.b }; } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal(3); }); it('registers with config', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', config: { handler: () => 'ok' } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('ok'); }); it('throws an error when a route is missing a path', () => { expect(() => { const server = Hapi.server(); server.route({ method: 'GET', handler: () => null }); }).to.throw(/"path" is required/); }); it('throws an error when a route is missing a method', () => { expect(() => { const server = Hapi.server(); server.route({ path: '/', handler: () => null }); }).to.throw(/"method" is required/); }); it('throws an error when a route has a malformed method name', () => { expect(() => { const server = Hapi.server(); server.route({ method: '"GET"', path: '/', handler: () => null }); }).to.throw(/Invalid route options/); }); it('throws an error when a route uses the HEAD method', () => { expect(() => { const server = Hapi.server(); server.route({ method: 'HEAD', path: '/', handler: () => null }); }).to.throw('Cannot set HEAD route: /'); }); it('throws an error when a route is missing a handler', () => { expect(() => { const server = Hapi.server(); server.route({ path: '/test', method: 'put' }); }).to.throw('Missing or undefined handler: PUT /test'); }); it('throws when handler is missing in config', () => { const server = Hapi.server(); expect(() => { server.route({ method: 'GET', path: '/', options: {} }); }).to.throw('Missing or undefined handler: GET /'); }); it('throws when path has trailing slash and server set to strip', () => { const server = Hapi.server({ router: { stripTrailingSlash: true } }); expect(() => { server.route({ method: 'GET', path: '/test/', handler: () => null }); }).to.throw('Path cannot end with a trailing slash when configured to strip: GET /test/'); }); it('allows / when path has trailing slash and server set to strip', () => { const server = Hapi.server({ router: { stripTrailingSlash: true } }); expect(() => { server.route({ method: 'GET', path: '/', handler: () => null }); }).to.not.throw(); }); it('sets route plugins and app settings', async () => { const handler = (request) => (request.route.settings.app.x + request.route.settings.plugins.x.y); const server = Hapi.server(); server.route({ method: 'GET', path: '/', options: { handler, app: { x: 'o' }, plugins: { x: { y: 'k' } } } }); const res = await server.inject('/'); expect(res.result).to.equal('ok'); }); it('throws when validation is set without payload parsing', () => { const server = Hapi.server(); expect(() => { server.route({ method: 'POST', path: '/', handler: () => null, options: { validate: { payload: {}, validator: Joi }, payload: { parse: false } } }); }).to.throw('Route payload must be set to \'parse\' when payload validation enabled: POST /'); }); it('throws when validation is set without path parameters', () => { const server = Hapi.server(); expect(() => { server.route({ method: 'POST', path: '/', handler: () => null, options: { validate: { params: {} } } }); }).to.throw('Cannot set path parameters validations without path parameters: POST /'); }); it('ignores payload when overridden', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: (request) => request.payload }); server.ext('onRequest', (request, h) => { request.payload = 'x'; return h.continue; }); const res = await server.inject({ method: 'POST', url: '/', payload: 'y' }); expect(res.statusCode).to.equal(200); expect(res.result).to.equal('x'); }); it('ignores payload parsing errors', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: () => 'ok', options: { payload: { parse: true, failAction: 'ignore' } } }); const res = await server.inject({ method: 'POST', url: '/', payload: '{a:"abc"}' }); expect(res.statusCode).to.equal(200); }); it('logs payload parsing errors', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: () => 'ok', options: { payload: { parse: true, failAction: 'log' } } }); let logged; server.events.on({ name: 'request', channels: 'internal' }, (request, event, tags) => { if (tags.payload && tags.error) { logged = event; } }); const res = await server.inject({ method: 'POST', url: '/', payload: '{a:"abc"}' }); expect(res.statusCode).to.equal(200); expect(logged).to.be.an.object(); expect(logged.error).to.be.an.error('Invalid request payload JSON format'); expect(logged.error.data).to.be.an.error(SyntaxError, /at position 1/); }); it('returns payload parsing errors', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: () => 'ok', options: { payload: { parse: true, failAction: 'error' } } }); const res = await server.inject({ method: 'POST', url: '/', payload: '{a:"abc"}' }); expect(res.statusCode).to.equal(400); expect(res.result.message).to.equal('Invalid request payload JSON format'); }); it('replaces payload parsing errors with custom handler', async () => { const server = Hapi.server(); server.route({ method: 'POST', path: '/', handler: () => 'ok', options: { payload: { parse: true, failAction: function (request, h, error) { return h.response('This is a custom error').code(418).takeover(); } } } }); const res = await server.inject({ method: 'POST', url: '/', payload: '{a:"abc"}' }); expect(res.statusCode).to.equal(418); expect(res.result).to.equal('This is a custom error'); }); it('throws when validation is set on GET', () => { const server = Hapi.server(); expect(() => { server.route({ method: 'GET', path: '/', handler: () => null, options: { validate: { payload: {} } } }); }).to.throw('Cannot validate HEAD or GET request payload: GET /'); }); it('throws when payload parsing is set on GET', () => { const server = Hapi.server(); expect(() => { server.route({ method: 'GET', path: '/', handler: () => null, options: { payload: { parse: true } } }); }).to.throw('Cannot set payload settings on HEAD or GET request: GET /'); }); it('ignores validation on * route when request is GET', async () => { const server = Hapi.server(); server.validator(Joi); server.route({ method: '*', path: '/', handler: () => null, options: { validate: { payload: { a: Joi.required() } } } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); }); it('ignores validation on * route when request is HEAD', async () => { const server = Hapi.server(); server.validator(Joi); server.route({ method: '*', path: '/', handler: () => null, options: { validate: { payload: { a: Joi.required() } } } }); const res = await server.inject({ url: '/', method: 'HEAD' }); expect(res.statusCode).to.equal(204); }); it('skips payload on * route when request is HEAD', async (flags) => { const orig = Subtext.parse; let called = false; Subtext.parse = () => { called = true; }; flags.onCleanup = () => { Subtext.parse = orig; }; const server = Hapi.server(); server.route({ method: '*', path: '/', handler: () => null }); const res = await server.inject({ url: '/', method: 'HEAD' }); expect(res.statusCode).to.equal(204); expect(called).to.be.false(); }); it('throws error when the default routes payload validation is set without payload parsing', () => { expect(() => { Hapi.server({ routes: { validate: { payload: {}, validator: Joi }, payload: { parse: false } } }); }).to.throw('Route payload must be set to \'parse\' when payload validation enabled'); }); it('throws error when the default routes state validation is set without state parsing', () => { expect(() => { Hapi.server({ routes: { validate: { state: {}, validator: Joi }, state: { parse: false } } }); }).to.throw('Route state must be set to \'parse\' when state validation enabled'); }); it('ignores default validation on GET', async () => { const server = Hapi.server({ routes: { validate: { payload: { a: Joi.required() }, validator: Joi } } }); server.route({ method: 'GET', path: '/', handler: () => null }); const res = await server.inject('/'); expect(res.statusCode).to.equal(204); }); it('shallow copies route config bind', async () => { const server = Hapi.server(); const context = { key: 'is ' }; let count = 0; Object.defineProperty(context, 'test', { enumerable: true, configurable: true, get: function () { ++count; } }); const handler = function (request) { return this.key + (this === context); }; server.route({ method: 'GET', path: '/', handler, options: { bind: context } }); const res = await server.inject('/'); expect(res.result).to.equal('is true'); expect(count).to.equal(0); }); it('shallow copies route config bind (server.bind())', async () => { const server = Hapi.server(); const context = { key: 'is ' }; let count = 0; Object.defineProperty(context, 'test', { enumerable: true, configurable: true, get: function () { ++count; } }); const handler = function (request) { return this.key + (this === context); }; server.bind(context); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('is true'); expect(count).to.equal(0); }); it('shallow copies route config bind (connection defaults)', async () => { const context = { key: 'is ' }; const server = Hapi.server({ routes: { bind: context } }); let count = 0; Object.defineProperty(context, 'test', { enumerable: true, configurable: true, get: function () { ++count; } }); const handler = function (request) { return this.key + (this === context); }; server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('is true'); expect(count).to.equal(0); }); it('shallow copies route config bind (server defaults)', async () => { const context = { key: 'is ' }; let count = 0; Object.defineProperty(context, 'test', { enumerable: true, configurable: true, get: function () { ++count; } }); const handler = function (request) { return this.key + (this === context); }; const server = Hapi.server({ routes: { bind: context } }); server.route({ method: 'GET', path: '/', handler }); const res = await server.inject('/'); expect(res.result).to.equal('is true'); expect(count).to.equal(0); }); it('overrides server relativeTo', async () => { const server = Hapi.server(); await server.register(Inert); const handler = (request, h) => h.file('./package.json'); server.route({ method: 'GET', path: '/file', handler, options: { files: { relativeTo: Path.join(__dirname, '../') } } }); const res = await server.inject('/file'); expect(res.payload).to.contain('hapi'); }); it('allows payload timeout more then socket timeout', () => { expect(() => { Hapi.server({ routes: { payload: { timeout: 60000 }, timeout: { socket: 12000 } } }); }).to.not.throw(); }); it('allows payload timeout more then socket timeout (node default)', () => { expect(() => { Hapi.server({ routes: { payload: { timeout: 6000000 } } }); }).to.not.throw(); }); it('allows server timeout more then socket timeout', () => { expect(() => { Hapi.server({ routes: { timeout: { server: 60000, socket: 12000 } } }); }).to.not.throw(); }); it('allows server timeout more then socket timeout (node default)', () => { expect(() => { Hapi.server({ routes: { timeout: { server: 6000000 } } }); }).to.not.throw(); }); it('ignores large server timeout when socket timeout disabled', () => { expect(() => { Hapi.server({ routes: { timeout: { server: 6000000, socket: false } } }); }).to.not.throw(); }); describe('extensions', () => { it('combine connection extensions (route last)', async () => { const server = Hapi.server(); const onRequest = (request, h) => { request.app.x = '1'; return h.continue; }; server.ext('onRequest', onRequest); const preAuth = (request, h) => { request.app.x += '2'; return h.continue; }; server.ext('onPreAuth', preAuth); const postAuth = (request, h) => { request.app.x += '3'; return h.continue; }; server.ext('onPostAuth', postAuth); const preHandler = (request, h) => { request.app.x += '4'; return h.continue; }; server.ext('onPreHandler', preHandler); const postHandler = (request, h) => { request.response.source += '5'; return h.continue; }; server.ext('onPostHandler', postHandler); const preResponse = (request, h) => { request.response.source += '6'; return h.continue; }; server.ext('onPreResponse', preResponse); server.route({ method: 'GET', path: '/', handler: (request) => request.app.x }); const res = await server.inject('/'); expect(res.result).to.equal('123456'); }); it('combine connection extensions (route first)', async () => { const server = Hapi.server(); server.route({ method: 'GET', path: '/', handler: (request) => request.app.x }); const onRequest = (request, h) => { request.app.x = '1'; return h.continue; }; server.ext('onRequest', onRequest); const preAuth = (request, h) => { request.app.x += '2'; return h.continue; }; server.ext('onPreAuth', preAuth); const postAuth = (request, h) => { request.app.x += '3'; return h.continue; }; server.ext('onPostAuth', postAuth); const preHandler = (request, h) => { request.app.x += '4'; return h.continue; }; server.ext('onPreHandler', preHandler); const postHandler = (request, h) => { request.response.source += '5'; return h.continue; }; server.ext('onPostHandler', postHandler); const preResponse = (request, h) => { request.response.source += '6'; return h.continue; }; server.ext('onPreResponse', preResponse); const res = await server.inject('/'); expect(res.result).to.equal('123456'); }); it('combine connection extensions (route middle)', async () => { const server = Hapi.server(); const onRequest = (request, h) => { request.app.x = '1'; return h.continue; }; server.ext('onRequest', onRequest); const preAuth = (request, h) => { request.app.x += '2'; return h.continue; }; server.ext('onPreAuth', preAuth); const postAuth = (request, h) => { request.app.x += '3'; return h.continue; }; server.ext('onPostAuth', postAuth); server.route({ method: 'GET', path: '/', handler: (request) => request.app.x }); const preHandler = (request, h) => { request.app.x += '4'; return h.continue; }; server.ext('onPreHandler', preHandler); const postHandler = (request, h) => { request.response.source += '5'; return h.continue; }; server.ext('onPostHandler', postHandler); const preResponse = (request, h) => { request.response.source += '6'; return h.continue; }; server.ext('onPreResponse', preResponse); const res = await server.inject('/'); expect(res.result).to.equal('123456'); }); it('combine connection extensions (mixed sources)', async () => { const server = Hapi.server(); const preAuth1 = (request, h) => { request.app.x = '1'; return h.continue; }; server.ext('onPreAuth', preAuth1); server.route({ method: 'GET', path: '/', options: { ext: { onPreAuth: { method: (request, h) => { request.app.x += '2'; return h.continue; } } }, handler: (request) => request.app.x } }); const preAuth3 = (request, h) => { request.app.x += '3'; return h.continue; }; server.ext('onPreAuth', preAuth3); server.route({ method: 'GET', path: '/a', handler: (request) => request.app.x }); const res1 = await server.inject('/'); expect(res1.result).to.equal('123'); const res2 = await server.inject('/a'); expect(res2.result).to.equal('13'); }); it('skips inner extensions when not found', async () => { const server = Hapi.server(); let state = ''; const onRequest = (request, h) => { state += 1; return h.continue; }; server.ext('onRequest', onRequest); const preAuth = (request) => { state += 2; return 'ok'; }; server.ext('onPreAuth', preAuth); const preResponse = (request, h) => { state += 3; return h.continue; }; server.ext('onPreResponse', preResponse); const res = await server.inject('/'); expect(res.statusCode).to.equal(404); expect(state).to.equal('13'); }); }); describe('rules', () => { it('compiles rules into config', async () => { const server = Hapi.server(); server.validator(Joi); const processor = (rules) => { if (!rules) { return null; } return { validate: { query: { x: rules.x } } }; }; server.rules(processor); server.route({ path: '/1', method: 'GET', handler: () => null, rules: { x: Joi.number().valid(1) } }); server.route({ path: '/2', method: 'GET', handler: () => null, rules: { x: Joi.number().valid(2) } }); server.route({ path: '/3', method: 'GET', handler: () => null }); expect((await server.inject('/1?x=1')).statusCode).to.equal(204); expect((await server.inject('/1?x=2')).statusCode).to.equal(400); expect((await server.inject('/2?x=1')).statusCode).to.equal(400); expect((await server.inject('/2?x=2')).statusCode).to.equal(204); expect((await server.inject('/3?x=1')).statusCode).to.equal(204); expect((await server.inject('/3?x=2')).statusCode).to.equal(204); }); it('compiles rules into config (route info)', async () => { const server = Hapi.server(); const processor = (rules, { method, path }) => { return { app: { method, path, x: rules.x } }; }; server.rules(processor); server.route({ path: '/1', method: 'GET', handler: (request) => request.route.settings.app, rules: { x: 1 } }); expect((await server.inject('/1')).result).to.equal({ x: 1, path: '/1', method: 'get' }); }); it('compiles rules into config (validate)', () => { const server = Hapi.server(); server.validator(Joi); const processor = (rules) => { return { validate: { query: { x: rules.x } } }; }; server.rules(processor, { validate: { schema: { x: Joi.number().required() } } }); server.route({ path: '/1', method: 'GET', handler: () => null, rules: { x: 1 } }); expect(() => server.route({ path: '/2', method: 'GET', handler: () => null, rules: { x: 'y' } })).to.throw(/must be a number/); }); it('compiles rules into config (validate + options)', () => { const server = Hapi.server(); server.validator(Joi); const processor = (rules) => { return { validate: { query: { x: rules.x } } }; }; server.rules(processor, { validate: { schema: { x: Joi.number().required() }, options: { allowUnknown: false } } }); server.route({ path: '/1', method: 'GET', handler: () => null, rules: { x: 1 } }); expect(() => server.route({ path: '/2', method: 'GET', handler: () => null, rules: { x: 1, y: 2 } })).to.throw(/is not allowed/); }); it('cascades rules into configs', async () => { const handler = (request) => { return request.route.settings.app.x + ':' + Object.keys(request.route.settings.app).join('').slice(0, -1); }; const p1 = { name: 'p1', register: async (srv) => { const processor = (rules) => { return { app: { x: '1+' + rules.x, 1: true } }; }; srv.rules(processor); await srv.register(p3); srv.route({ path: '/1', method: 'GET', handler, rules: { x: 1 } }); } }; const p2 = { name: 'p2', register: (srv) => { const processor = (rules) => { return { app: { x: '2+' + rules.x, 2: true } }; }; srv.rules(processor); srv.route({ path: '/2', method: 'GET', handler, rules: { x: 2 } }); } }; const p3 = { name: 'p3', register: async (srv) => { const processor = (rules) => { return { app: { x: '3+' + rules.x, 3: true } }; }; srv.rules(processor); await srv.register(p4); srv.route({ path: '/3', method: 'GET', handler, rules: { x: 3 } }); } }; const p4 = { name: 'p4', register: async (srv) => { await srv.register(p5); srv.route({ path: '/4', method: 'GET', handler, rules: { x: 4 } }); } }; const p5 = { name: 'p5', register: (srv) => { const processor = (rules) => { return { app: { x: '5+' + rules.x, 5: true } }; }; srv.rules(processor); srv.route({ path: '/5', method: 'GET', handler, rules: { x: 5 } }); srv.route({ path: '/6', method: 'GET', handler, rules: { x: 6 }, config: { app: { x: '7' } } }); } }; const server = Hapi.server(); const processor0 = (rules) => { return { app: { x: '0+' + rules.x, 0: true } }; }; server.rules(processor0); await server.register([p1, p2]); server.route({ path: '/0', method: 'GET', handler, rules: { x: 0 } }); expect((await server.inject('/0')).result).to.equal('0+0:0'); expect((await server.inject('/1')).result).to.equal('1+1:01'); expect((await server.inject('/2')).result).to.equal('2+2:02'); expect((await server.inject('/3')).result).to.equal('3+3:013'); expect((await server.inject('/4')).result).to.equal('3+4:013'); expect((await server.inject('/5')).result).to.equal('5+5:0135'); expect((await server.inject('/6')).result).to.equal('7:0135'); }); }); describe('drain()', () => { it('drains the request payload on 404', async () => { const server = Hapi.server(); const res = await server.inject({ method: 'POST', url: '/nope', payload: 'something' }); expect(res.statusCode).to.equal(404); expect(res.raw.req._readableState.ended).to.be.true(); }); }); }); ================================================ FILE: test/security.js ================================================ 'use strict'; const Code = require('@hapi/code'); const Hapi = require('..'); const Lab = require('@hapi/lab'); const internals = {}; const { describe, it } = exports.lab = Lab.script(); const expect = Code.expect; describe('security', () => { it('handles missing routes', async () => { const server = Hapi.server({ port: 8080, routes: { security: { xframe: true } } }); const res = await server.inject('/'); expect(res.statusCode).to.equal(404); expect(res.headers['x-frame-options']).to.exist(); }); it('blocks response splitting through the request.create method', async () => { const server = Hapi.server(); const handler = (request, h) => h.response('Moved').created('/item/' + request.payload.name); server.route({ method: 'POST', path: '/item', handler }); const res = await server.inject({ method: 'POST', url: '/item', payload: '{"name": "foobar\r\nContent-Length: \r\n\r\nHTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 19\r\n\r\nShazam"}', headers: { 'Content-Type': 'application/json' } }); expect(res.statusCode).to.equal(400); }); it('prevents xss with invalid content types', async () => { const server = Hapi.server(); server.state('encoded', { encoding: 'iron' }); server.route({ method: 'POST', path: '/', handler: () => 'Success' }); const res = await server.inject({ method: 'POST', url: '/', payload: '{"something":"something"}', headers: { 'content-type': ';' } }); expect(res.result.message).to.not.contain('script'); }); it('prevents xss with invalid cookie values in the request', async () => { const server = Hapi.server(); server.state('encoded', { encoding: 'iron' }); server.route({ method: 'POST', path: '/', handler: () => 'Success' }); const res = await server.inject({ method: 'POST', url: '/', payload: '{"something":"something"}', headers: { cookie: 'encoded="";' } }); expect(res.result.message).to.not.contain('=value;' } }); expect(res.result.message).to.not.contain('