# policy Describes what a static server sends, as data: the serve-config authoring shape and its validators, the header policy fields and presets, and the fold that turns ordered header rules into one response's headers. This entry imports no Node.js built-in, so a browser bundle, a build step or a lint rule can author, check and read a serve config without loading the HTTP stack. ```ts import { defineServeConfig, validateServeConfig } from '@hyperfrontend/server/policy' const config = defineServeConfig({ root: 'dist/site', embedders: ["'self'", 'https://host.example'], permissionsPolicy: { camera: [], geolocation: ['self'] }, isolation: 'require-corp', headers: [{ suffix: '.html', headers: { 'Cache-Control': 'no-cache' } }], }) validateServeConfig(config, 'serve.config.json') ``` ## Usage A config's policy fields expand into ordered header rules, and the rules fold into the headers of one path. The fold is the one the static server runs, so what it returns is what a response carries: ```ts import { applyHeaderRules, expandHeaderPolicy } from '@hyperfrontend/server/policy' const rules = expandHeaderPolicy({ embedders: ["'self'", 'https://host.example'], permissionsPolicy: { camera: [], geolocation: ['self'] }, isolation: 'require-corp', headers: [{ suffix: '.html', headers: { 'Cache-Control': 'no-cache' } }], }) applyHeaderRules(rules, '/index.html') // { // 'Content-Security-Policy': "frame-ancestors 'self' https://host.example", // 'Permissions-Policy': 'camera=(), geolocation=(self)', // 'Cross-Origin-Opener-Policy': 'same-origin', // 'Cross-Origin-Embedder-Policy': 'require-corp', // 'Cross-Origin-Resource-Policy': 'cross-origin', // 'Cache-Control': 'no-cache', // } ``` [`expandHeaderPolicy`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-expandHeaderPolicy) checks the four fields it reads the way [`validateServeConfig`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-validateServeConfig) does and throws the same sentences, one per line, so no rule is built from a policy that never passed a validator. Any other field of the value is left unread, which lets a whole serve config be handed over. A config written in TypeScript, or a service that builds its own rules, can compose the presets instead of spelling header values: ```ts import { contentSecurityPolicy, defineServeConfig, immutableAssets, nosniff, referrerPolicy } from '@hyperfrontend/server/policy' const embedders = ["'self'", 'https://host.example'] export default defineServeConfig({ embedders, headers: [ nosniff(), referrerPolicy(), contentSecurityPolicy({ embedders, directives: { 'img-src': ["'self'", 'data:'] } }, { suffix: '.html' }), immutableAssets('/assets/'), ], }) ``` ## Configuration ### Policy fields Three fields of a serve config declare an intent and expand into one rule each. The rule matches every path. | Field | Expands into | | ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | [`embedders`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeConfig-prop-embedders) | `Content-Security-Policy` holding one `frame-ancestors` directive, plus `X-Frame-Options` when the list is empty, `'none'` or `'self'` alone | | [`permissionsPolicy`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeConfig-prop-permissionsPolicy) | One `Permissions-Policy` header; no rule at all for an empty record | | [`isolation`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeConfig-prop-isolation) | `Cross-Origin-Opener-Policy: same-origin`, the declared `Cross-Origin-Embedder-Policy`, and `Cross-Origin-Resource-Policy: cross-origin` | [`expandHeaderPolicy`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-expandHeaderPolicy) places them in that order, ahead of the authored [`headers`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeConfig-prop-headers) rules, so an authored rule still overrides any header a field set. ### Embedders An entry is `'self'`, `'none'` as the only entry, or `scheme://host` with an optional leading `*.` label and an optional port. Sources are written in the order given, and an empty list writes `frame-ancestors 'none'`. A port of `*` and a custom scheme such as `tauri://localhost` are accepted. | Refused | Why | | -------------------------------------------------------- | -------------------------------------------------------------------- | | A bare `*`, a scheme alone (`https:`), a host of `*` | Each permits every origin | | A host without a scheme | Its scheme would follow the served page's | | Any path, a trailing `/` included | An ancestor is matched by its origin, so a deeper path never matches | | Uppercase, `'SELF'` included | The string in the config is the string on the wire | | A non-ASCII host | Write an internationalised name in its punycode form | | `https://*.app` | A wildcard over a single label covers a whole top-level domain | | A trailing dot, IPv6 brackets, an underscore, user info | Outside the grammar | | A keyword without its single quotes, or in double quotes | A keyword is written `'self'` or `'none'` | | `'none'` beside another entry | It must be the only entry | An IPv4 literal is accepted because the grammar admits it. The Content Security Policy specification says an IP host matches no ancestor and browsers differ, so test one before relying on it. ### Permissions policy Each key is a feature name in lowercase letters, digits and hyphens. A name no browser knows is accepted, since browsers ignore it. | Allowlist | Header member | | ---------------------------------- | --------------------------------------- | | `[]` | `camera=()`, which disables the feature | | `['self']` | `camera=(self)` | | `['*']` | `camera=*` | | `['self', 'https://maps.example']` | `camera=(self "https://maps.example")` | The keyword and the wildcard are written without quotes, as the header writes them (`['self']`, `['*']`), and the wildcard must be the only entry. An origin follows the embedders grammar. The field restricts what the served documents may do, whatever an embedder delegates to them. It is not a list of the features a document asks for. ### A rule that sets the policy header The fold replaces a header's whole value, and `frame-ancestors` does not fall back to `default-src`. So once [`embedders`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeConfig-prop-embedders) is declared, every authored rule that sets `Content-Security-Policy`, in any letter case, is checked: - A rule whose value names no `frame-ancestors` directive is refused, bounded or not: the paths it matches would be framable by any origin. - A rule that matches every path is refused unless its directive lists exactly the declared sources, in the same order. Otherwise the field would decide nothing. - A rule bounded by a prefix or suffix may list sources of its own, which is how one area of a site is given a narrower or wider list. `Content-Security-Policy-Report-Only` is never checked. A rule is refused instead of having the directive appended to it, so what a rule writes is always what is sent. A directive counts only when a browser would enforce it. One that holds any character other than ASCII whitespace and visible ASCII is discarded whole by a browser, so it is read as absent: a no-break space pasted beside the directive, or a host that is not in its punycode form, gets the rule refused as one that names no `frame-ancestors`. A bound counts only when it excludes a path. A [`prefix`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeHeaderRule-prop-prefix) that is empty or `/`, and a [`suffix`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeHeaderRule-prop-suffix) that is empty, exclude none, so a rule carrying only those is judged as a rule for every path. [`matchesEveryPath`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-matchesEveryPath) is that test. The fold compares a bound with the path it is handed, letter for letter. The static server hands it the path of the file it serves in the spelling the file system stores, not the spelling of the request: on a volume that ignores letter case, `/HOST/index.html` reaches the file `host/index.html` and is sent the headers of a rule bounded by `/host/`, and so is a request that names the directory by a Windows short name. Write a bound the way the directory lists the name. A request that reaches no file, such as a redirect, a 404 or a 405, is matched by its path as requested. ### Problems [`checkServeConfig`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-checkServeConfig) returns every problem of a config at once, each with a stable code, the path it was found at and a full sentence. [`validateServeConfig`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-validateServeConfig) throws the same sentences, one per line, each opening with the config's path. The order is fixed: the scalar fields and the rules first, then a hole in the rule list and any header value Node.js would refuse to send, then [`embedders`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeConfig-prop-embedders), then [`permissionsPolicy`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeConfig-prop-permissionsPolicy), then rules at odds with the embedders, then unknown fields. A field the config does not take is a problem, at the top level and inside a rule, so a mistyped [`prefix`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeHeaderRule-prop-prefix) cannot leave a rule matching every path. `$schema` is the one extra field accepted. A header value is refused when Node.js would refuse to send it: a control character other than a tab, or any character above U+00FF. A header name is a token of letters, digits and the punctuation HTTP allows. Both are checked when the config loads, so a pasted typographic quote is a load error and not a 500 on every matching request. A hole in a list, as a doubled comma leaves in a config written in TypeScript, is an entry of the wrong type. ## Presets Each preset returns one header rule. A preset given a refused value throws one error with a line per problem. | Preset | Sets | | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`embedders`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-embedders) | What the config field expands into, with an optional scope | | [`permissionsPolicy`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-permissionsPolicy) | What the config field expands into, with an optional scope | | [`crossOriginIsolation`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-crossOriginIsolation) | What the [`isolation`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-ServeConfig-prop-isolation) field expands into, with an optional scope | | [`contentSecurityPolicy`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-contentSecurityPolicy) | Four default directives, any authored ones, and `frame-ancestors` from its embedders, last | | [`nosniff`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-nosniff) | `X-Content-Type-Options: nosniff` | | [`referrerPolicy`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-referrerPolicy) | `Referrer-Policy`, `strict-origin-when-cross-origin` unless told otherwise | | [`strictTransportSecurity`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-strictTransportSecurity) | `Strict-Transport-Security`; it takes no scope, because the header covers the whole host | | [`immutableAssets`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-immutableAssets) | `Cache-Control: public, max-age=31536000, immutable` under a prefix | The scope is a [`prefix`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-RuleScope-prop-prefix), a [`suffix`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-RuleScope-prop-suffix) or both, matched the way a rule's are. The defaults of [`contentSecurityPolicy`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-contentSecurityPolicy) are `default-src 'self'`, `script-src 'self'`, `object-src 'none'` and `base-uri 'self'`; an authored directive of the same name takes the default's place. Its embedders are required, since there is no safe guess for who may frame a page. [`frameAncestorsOf`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-frameAncestorsOf) reads the source lists a `Content-Security-Policy` value declares, one per comma-separated policy and none for a directive a browser would discard. [`permitsEveryOrigin`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-permitsEveryOrigin) tells whether one source lets any origin through, and [`matchesEveryPath`](https://www.hyperfrontend.dev/docs/libraries/server/policy/#api-matchesEveryPath) whether a rule's bounds exclude no path. Together they let a tool judge a policy it did not write. ## API Reference ### Functions #### applyHeaderRules ```typescript function applyHeaderRules(rules: unknown, path: string, headers: Readonly>): Record ``` Folds ordered header rules over a response's headers for one path. A rule applies when the path starts with its prefix and ends with its suffix, an absent bound matching everything. Each header of an applying rule replaces the header of the same name, compared without regard to case, so a later rule overrides an earlier one a header at a time and no header is sent under two spellings. A header keeps the position it first took. A rule's `Content-Length`, `Content-Encoding` or `ETag` is skipped, since those describe the body. **Parameters** | Name | Type | Description | | --- | --- | --- | | `rules` | `unknown` | The rules, in the order they are applied. | | `path` | `string` | The path being answered, starting with `/`. | | `headers` | `Readonly>` | The headers the response already carries; none when omitted. (default: `{}`) | **Returns** `Record`: A new header record; the one passed in is left as it was. **Example: Reading what a page and an asset are sent** ```typescript const rules = [{ headers: { 'Cache-Control': 'no-cache' } }, { prefix: '/assets/', headers: { 'Cache-Control': 'immutable' } }] applyHeaderRules(rules, '/index.html') // => { 'Cache-Control': 'no-cache' } applyHeaderRules(rules, '/assets/app.js') // => { 'Cache-Control': 'immutable' } ``` #### checkEmbedders ```typescript function checkEmbedders(value: unknown): unknown ``` Checks a value as the `embedders` field of a serve config: the origins allowed to frame what the server sends. An entry is `'self'`, `'none'` as the only entry, or `scheme://host` with an optional leading `*.` label and an optional port, in lowercase ASCII with no path. Each entry is reported at most once, and no message repeats the entry it is about. A hole in the list is an entry that is no string. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `unknown` | The candidate list. | **Returns** `unknown`: Every problem found, in list order; empty when the list is sound. **Example: Checking a list before it is published** ```typescript checkEmbedders(["'self'", 'https://host.example']) // => [] checkEmbedders(['host.example']).map((issue) => issue.code) // => ['embedder-scheme-missing'] ``` #### checkPermissionsPolicy ```typescript function checkPermissionsPolicy(value: unknown): unknown ``` Checks a value as the `permissionsPolicy` field of a serve config: for each browser feature, the origins allowed to use it in the documents the server sends. A feature name is lowercase letters, digits and hyphens. Its allowlist is an array of `self`, `*` as the only entry, or `scheme://host` origins; an empty array disables the feature. A name no browser knows is accepted, since browsers ignore it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `unknown` | The candidate record. | **Returns** `unknown`: Every problem found, in authored order; empty when the record is sound. **Example: Checking a record before it is published** ```typescript checkPermissionsPolicy({ camera: [], geolocation: ['self'] }) // => [] checkPermissionsPolicy({ camera: ["'self'"] }).map((issue) => issue.code) // => ['permissions-policy-keyword-quoted'] ``` #### checkServeConfig ```typescript function checkServeConfig(value: unknown): unknown ``` Collects every problem of an unknown value as a ServeConfig, where validateServeConfig throws them. Problems come in a fixed order: `root`, `port`, `host`, `log`, `isolation`, `headers` and each rule; then any hole in the rule list and any header value Node would refuse to send; then `embedders`; then `permissionsPolicy`; then any rule that undoes the declared embedders, judged only when the rules and the embedders are themselves sound; then unknown fields, of the config and of each rule. `$schema` is the one extra field a config may carry. A value that is no object reports that alone. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `unknown` | The loaded config value. | **Returns** `unknown`: The problems, each with a stable code, a path and a full sentence; empty when the config is sound. **Example: Listing what a tool should report about a config** ```typescript checkServeConfig({ port: 0, embedders: ['host.example'] }).map((issue) => issue.message) // => ['"port" must be an integer between 1 and 65535.', 'embedders[0] must start with a scheme and "://", as in https://host.example.'] ``` #### contentSecurityPolicy ```typescript function contentSecurityPolicy(options: ContentSecurityPolicyOptions, scope?: RuleScope): ServeHeaderRule ``` Builds the header rule for a whole `Content-Security-Policy`: four default directives that load from the page's own origin, the authored directives, and `frame-ancestors` from the declared embedders, always last. An authored directive that names a default takes the default's position, and a new one follows the defaults in authored order. `X-Frame-Options` is added when the embedders list is empty, `'none'` or `'self'` alone. The embedders are required: there is no safe guess for who may frame a page. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `ContentSecurityPolicyOptions` | The embedders and any directives beyond the defaults. | | `scope?` | `RuleScope` | The paths the rule applies to; every path when omitted. | **Returns** `ServeHeaderRule`: The rule. **Example: Allowing WebAssembly on the pages one host may frame** ```typescript contentSecurityPolicy( { embedders: ['https://host.example'], directives: { 'script-src': ["'self'", "'wasm-unsafe-eval'"] } }, { suffix: '.html' } ) ``` #### crossOriginIsolation ```typescript function crossOriginIsolation(coep: "require-corp" | "credentialless", scope?: RuleScope): ServeHeaderRule ``` Builds the header rule that makes a document cross-origin isolated: `Cross-Origin-Opener-Policy: same-origin`, the chosen `Cross-Origin-Embedder-Policy`, and `Cross-Origin-Resource-Policy: cross-origin`, which keeps the origin embeddable by hosts elsewhere. It writes the headers a config's `isolation` field expands into, and adds the scope the field cannot carry. **Parameters** | Name | Type | Description | | --- | --- | --- | | `coep` | `"require-corp" \| "credentialless"` | The embedder policy that completes the isolation. | | `scope?` | `RuleScope` | The paths the rule applies to; every path when omitted. | **Returns** `ServeHeaderRule`: The rule. **Example: Isolating one application of a site** ```typescript crossOriginIsolation('credentialless', { prefix: '/app/' }) ``` #### defineServeConfig ```typescript function defineServeConfig(config: ServeConfig): ServeConfig ``` Identity helper that gives `hf-serve.config.*` files type-checked authoring. **Parameters** | Name | Type | Description | | --- | --- | --- | | `config` | `ServeConfig` | The static-server configuration object. | **Returns** `ServeConfig`: The same configuration object, narrowed to ServeConfig. **Example: Authoring a typed `hf-serve.config.ts`** ```typescript export default defineServeConfig({ root: 'dist/site', headers: [{ headers: { 'X-Content-Type-Options': 'nosniff' } }] }) ``` #### embedders ```typescript function embedders(sources: unknown, scope?: RuleScope): ServeHeaderRule ``` Builds the header rule that restricts who may frame a response: a `Content-Security-Policy` holding one `frame-ancestors` directive, followed by `X-Frame-Options` when the list is empty, `'none'` or `'self'` alone. The policy holds nothing else, so a later rule that sets the header replaces it whole; use `contentSecurityPolicy` when the response needs other directives too. **Parameters** | Name | Type | Description | | --- | --- | --- | | `sources` | `unknown` | The origins allowed to frame the response. | | `scope?` | `RuleScope` | The paths the rule applies to; every path when omitted. | **Returns** `ServeHeaderRule`: The rule. **Example: Letting one host frame every page** ```typescript embedders(["'self'", 'https://host.example']) // => { headers: { 'Content-Security-Policy': "frame-ancestors 'self' https://host.example" } } ``` #### expandHeaderPolicy ```typescript function expandHeaderPolicy(policy: HeaderPolicy): unknown ``` Expands a header policy into the ordered rules a server folds over each response: the rule for `embedders`, the rule for `permissionsPolicy`, the rule for `isolation`, then the authored rules. Each declared field becomes one rule that matches every path, and an empty permissions policy becomes none. The declared fields lead so that an authored rule still overrides any header they set. The one thing an authored rule may not do is undo the embedders: a rule that sets `Content-Security-Policy` without a `frame-ancestors` directive, or an unbounded rule whose directive lists other sources, is refused. The four fields are checked the way a serve config's are, so a policy that never passed a validator is refused here with the same sentences and no rule is built from it. Any other field of the value is left unread. **Parameters** | Name | Type | Description | | --- | --- | --- | | `policy` | `HeaderPolicy` | The policy fields of a serve config. | **Returns** `unknown`: The rules, in the order they are applied. **Example: Expanding the policy of a page one host may frame** ```typescript expandHeaderPolicy({ embedders: ['https://host.example'], isolation: 'require-corp' }) // => [ // { headers: { 'Content-Security-Policy': 'frame-ancestors https://host.example' } }, // { headers: { 'Cross-Origin-Opener-Policy': 'same-origin', 'Cross-Origin-Embedder-Policy': 'require-corp', 'Cross-Origin-Resource-Policy': 'cross-origin' } }, // ] ``` #### frameAncestors ```typescript function frameAncestors(sources: unknown): string ``` Writes a `frame-ancestors` directive from a list of embedders, in the order the list gives them. An empty list writes `'none'`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `sources` | `unknown` | The origins allowed to frame the response. | **Returns** `string`: The directive, with no trailing semicolon. **Example: Writing the directive for a page two sites may frame** ```typescript frameAncestors(["'self'", 'https://host.example']) // => "frame-ancestors 'self' https://host.example" frameAncestors([]) // => "frame-ancestors 'none'" ``` #### frameAncestorsOf ```typescript function frameAncestorsOf(policy: string): unknown ``` Reads the `frame-ancestors` source list of each policy in a `Content-Security-Policy` header value. A comma separates whole policies, and a browser enforces every one of them, so the result holds one list per policy that names the directive. The name is matched without regard to case, and the first occurrence in a policy wins, as it does in a browser. A value in which no policy names the directive restricts no embedder and reads as an empty result. A directive holding any character other than ASCII whitespace and visible ASCII is read as absent, because a browser discards it whole: a no-break space beside the name or a host that is not in its punycode form leaves the response framable by any origin. **Parameters** | Name | Type | Description | | --- | --- | --- | | `policy` | `string` | The header value. | **Returns** `unknown`: One source list per comma-separated policy that names the directive. **Example: Reading who may frame a response** ```typescript frameAncestorsOf("default-src 'self'; frame-ancestors 'self' https://host.example") // => [["'self'", 'https://host.example']] frameAncestorsOf("default-src 'self'") // => [] frameAncestorsOf("frame-ancestors 'self' https://b\u00fccher.example") // => [] ``` #### immutableAssets ```typescript function immutableAssets(prefix: string): ServeHeaderRule ``` Builds the header rule that lets a browser keep everything under a prefix for a year without asking again: `Cache-Control: public, max-age=31536000, immutable`. Use it for files whose name changes whenever their content does. **Parameters** | Name | Type | Description | | --- | --- | --- | | `prefix` | `string` | The path the files sit under, such as `/assets/`. | **Returns** `ServeHeaderRule`: The rule, bounded by the prefix. **Example: Caching a build's hashed assets** ```typescript immutableAssets('/assets/') // => { prefix: '/assets/', headers: { 'Cache-Control': 'public, max-age=31536000, immutable' } } ``` #### isolationRules ```typescript function isolationRules(isolation: "require-corp" | "credentialless"): unknown ``` Expands a declared isolation into the header rule that produces it. `Cross-Origin-Opener-Policy: same-origin` and the chosen `Cross-Origin-Embedder-Policy` are what make the document cross-origin isolated; `Cross-Origin-Resource-Policy: cross-origin` keeps the origin embeddable by hosts elsewhere. **Parameters** | Name | Type | Description | | --- | --- | --- | | `isolation` | `"require-corp" \| "credentialless"` | The declared COEP value, or `undefined` when none was declared. | **Returns** `unknown`: A single-element rule list applied to every path, or an empty list. **Example: Expanding a declared isolation** ```typescript isolationRules('require-corp') ``` #### matchesEveryPath ```typescript function matchesEveryPath(scope: RuleScope): boolean ``` Reports whether a scope leaves every path matched, which is how the fold reads it: no prefix, an empty one or `/` excludes nothing, and neither does no suffix or an empty one. A header rule is read by its bounds alone. A rule that only looks bounded replaces a header on the whole site, so it is judged as a rule for every path wherever one is. **Parameters** | Name | Type | Description | | --- | --- | --- | | `scope` | `RuleScope` | The bounds of a header rule, or the rule itself. | **Returns** `boolean`: `true` when neither bound excludes a path. **Example: Telling a rule for the whole site from one for its pages** ```typescript matchesEveryPath({ prefix: '/' }) // => true matchesEveryPath({ suffix: '.html' }) // => false ``` #### nosniff ```typescript function nosniff(scope?: RuleScope): ServeHeaderRule ``` Builds the header rule that stops a browser from guessing a response's content type: `X-Content-Type-Options: nosniff`. **Parameters** | Name | Type | Description | | --- | --- | --- | | `scope?` | `RuleScope` | The paths the rule applies to; every path when omitted. | **Returns** `ServeHeaderRule`: The rule. **Example: Sending the header on every path** ```typescript nosniff() // => { headers: { 'X-Content-Type-Options': 'nosniff' } } ``` #### permissionsPolicy ```typescript function permissionsPolicy(features: Readonly>, scope?: RuleScope): ServeHeaderRule ``` Builds the header rule that restricts which browser features a document may use: one `Permissions-Policy` header listing the features in the order the record gives them. An empty record builds a rule that sets no header. **Parameters** | Name | Type | Description | | --- | --- | --- | | `features` | `Readonly>` | For each feature, the origins allowed to use it; an empty array disables the feature. | | `scope?` | `RuleScope` | The paths the rule applies to; every path when omitted. | **Returns** `ServeHeaderRule`: The rule. **Example: Disabling the camera and keeping geolocation for this origin** ```typescript permissionsPolicy({ camera: [], geolocation: ['self'] }) // => { headers: { 'Permissions-Policy': 'camera=(), geolocation=(self)' } } ``` #### permitsEveryOrigin ```typescript function permitsEveryOrigin(source: string): boolean ``` Reports whether a source expression lets any origin through: a bare `*`, a scheme on its own such as `https:`, or a host that is `*`. Letter case is ignored, since a browser reads a source without regard to it. **Parameters** | Name | Type | Description | | --- | --- | --- | | `source` | `string` | One source expression, as written in a policy. | **Returns** `boolean`: `true` when the expression names no particular host. **Example: Telling an open source from a wildcard over one site** ```typescript permitsEveryOrigin('https://*') // => true permitsEveryOrigin('https://*.host.example') // => false ``` #### referrerPolicy ```typescript function referrerPolicy(value: ReferrerPolicyValue, scope?: RuleScope): ServeHeaderRule ``` Builds the header rule that limits what a request from the page tells the next site about where it came from: one `Referrer-Policy` header. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `ReferrerPolicyValue` | The policy; the origin alone on a cross-origin request when omitted. (default: `'strict-origin-when-cross-origin'`) | | `scope?` | `RuleScope` | The paths the rule applies to; every path when omitted. | **Returns** `ServeHeaderRule`: The rule. **Example: Sending no referrer from a private area** ```typescript referrerPolicy('no-referrer', { prefix: '/private/' }) // => { prefix: '/private/', headers: { 'Referrer-Policy': 'no-referrer' } } ``` #### strictTransportSecurity ```typescript function strictTransportSecurity(options: StrictTransportSecurityOptions): ServeHeaderRule ``` Builds the header rule that tells a browser to reach the host over HTTPS only: one `Strict-Transport-Security` header. The rule takes no scope, because a browser applies the header to the whole host whichever response carried it. Send it only from a server reached over HTTPS; a browser ignores it on plain HTTP. **Parameters** | Name | Type | Description | | --- | --- | --- | | `options` | `StrictTransportSecurityOptions` | The lifetime, and whether subdomains and preloading are included. | **Returns** `ServeHeaderRule`: The rule, matching every path. **Example: Keeping a host and its subdomains on HTTPS for two years** ```typescript strictTransportSecurity({ maxAge: 63072000, includeSubDomains: true, preload: true }) // => { headers: { 'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload' } } ``` #### validateHeaderRule ```typescript function validateHeaderRule(value: unknown, index: number, sourcePath: string): ServeHeaderRule ``` Validates one header rule, asserting optional `prefix`/`suffix` strings, a `headers` record of values Node can send, and no other field. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `unknown` | The candidate header rule. | | `index` | `number` | The rule's index, used to locate problems in the error message. | | `sourcePath` | `string` | The file the rule came from, used in the error message. | **Returns** `ServeHeaderRule`: The validated header rule. **Example: Validating a single header rule** ```typescript const rule = validateHeaderRule({ suffix: '.html', headers: { 'Cache-Control': 'no-cache' } }, 0, '/p/hf-serve.config.json') ``` #### validateServeConfig ```typescript function validateServeConfig(value: unknown, sourcePath: string): ServeConfig ``` Validates an unknown value as a ServeConfig. **Parameters** | Name | Type | Description | | --- | --- | --- | | `value` | `unknown` | The loaded config value. | | `sourcePath` | `string` | The config path, used in error messages. | **Returns** `ServeConfig`: The validated config. **Example: Validating a loaded serve config** ```typescript const config = validateServeConfig({ root: 'dist/site' }, '/p/hf-serve.config.json') ``` ### Interfaces #### ContentSecurityPolicyOptions What a contentSecurityPolicy rule is built from. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly embedders` | `unknown` | The origins allowed to frame the response, written last as the `frame-ancestors` directive; an empty list allows none. | | `readonly directives?` | `Readonly>` | Directives to add, or to put in place of a default of the same name; an empty list writes the bare directive name. | #### PolicyIssue One problem found in a serve config, located and worded for the person who wrote the config. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly code` | `PolicyIssueCode` | The kind of problem. | | `readonly path` | `string` | Where the problem sits in the config, such as `embedders[2]`; empty when the config itself is at fault. | | `readonly message` | `string` | The whole sentence a tool prints, which names the path itself. | #### ResolvedServeConfig A fully-resolved `hf-serve.config.*`: concrete root, listen address, and header rules. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly root` | `string` | Absolute directory served as the site root. | | `readonly port` | `number` | Port the server listens on. | | `readonly host?` | `string` | Interface the server binds; every interface when `undefined`. | | `readonly headers` | `unknown` | Ordered header rules, later rules overriding earlier ones per header. | | `readonly log` | `boolean` | Whether each request is access-logged. | | `readonly sourcePath?` | `string` | Absolute path of the config file that was loaded, absent when serving with pure defaults. | #### RuleScope The paths a preset's header rule applies to. A rule matches when the path starts with `prefix` (when given) and ends with `suffix` (when given); a scope with neither, like no scope at all, matches every path. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly prefix?` | `string` | Path prefix the rule applies under, e.g. `/app/`. | | `readonly suffix?` | `string` | Path suffix the rule applies to, e.g. `.html`. | #### ServeConfig Type-checked authoring shape for an `hf-serve.config.*` file. **Properties** | Name | Type | Description | | --- | --- | --- | | `root?` | `string` | Directory served as the site root. | | `port?` | `number` | Port the server listens on. | | `host?` | `string` | Interface the server binds; every interface when omitted. | | `isolation?` | `"require-corp" \| "credentialless"` | Cross-origin isolation applied to every response, expanded into `Cross-Origin-Opener-Policy: same-origin`, the matching `Cross-Origin-Embedder-Policy`, and `Cross-Origin-Resource-Policy: cross-origin`. Declaring it here rather than spelling the headers by hand keeps the intent legible and reviewable. The expansion is placed before the `headers` rules, so an explicit rule still overrides any of the three. An isolated origin severs the opener of any window opened onto it unless that opener is both same-origin and itself isolated, so a page served this way keeps a working `window.opener` only when a same-origin isolated page opens it. | | `embedders?` | `string[]` | The origins allowed to frame every response, expanded into a `Content-Security-Policy` holding one `frame-ancestors` directive. An empty list allows none. `X-Frame-Options` is sent beside it when the list is empty, `'none'` or `'self'` alone. The expansion is placed ahead of every other rule, so a later rule may scope a different list to a prefix or suffix. A rule that sets `Content-Security-Policy` must carry a `frame-ancestors` directive of its own, since the header is replaced whole; a rule that matches every path must list exactly the sources declared here. A source is refused when it would permit every origin (`*`, a scheme on its own, a `*` host), carries a path, lacks a scheme, or is not lowercase ASCII. An IPv4 literal is accepted, though browsers differ on whether it ever matches. | | `permissionsPolicy?` | `Record` | The browser features the served documents may use, expanded into one `Permissions-Policy` header. Each key is a feature name and each value the origins allowed to use it: `[]` disables the feature, `['self']` keeps it for this origin, `['*']` allows every origin, and `scheme://host` entries name others. This restricts what a document can do whatever its embedder delegates; it is not the list of features a document asks its embedder for. The expansion is placed after the one for `embedders` and ahead of the one for `isolation`. | | `headers?` | `ServeHeaderRule[]` | Ordered header rules, later rules overriding earlier ones per header. | | `log?` | `boolean` | Whether each request is access-logged: one line per request, written to the log sink the server is given and nowhere when it is given none. | #### ServeHeaderRule One ordered header rule for the static server: response headers applied to every request whose path matches the rule. A rule matches when the path starts with `prefix` (when given) and ends with `suffix` (when given); a rule with neither matches everything. Rules are applied in order and later rules override earlier ones one header at a time. **Properties** | Name | Type | Description | | --- | --- | --- | | `prefix?` | `string` | Path prefix the rule applies under, e.g. `/fish-`; matches everything when omitted. | | `suffix?` | `string` | Path suffix the rule applies to, e.g. `.html`; matches everything when omitted. | | `headers` | `Record` | Header names and values the rule sets. | #### StrictTransportSecurityOptions What a strictTransportSecurity rule is built from. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly maxAge` | `number` | How long, in whole seconds, a browser keeps to HTTPS for the host; zero retires the policy. | | `readonly includeSubDomains?` | `boolean` | Whether the policy covers every subdomain of the host as well. | | `readonly preload?` | `boolean` | Whether the host asks to be built into browsers' preload lists, which needs the subdomains and a lifetime of a year or more. | ### Types #### EmbedderSource One origin allowed to frame what a server sends, as a `frame-ancestors` source: `'self'`, `'none'` as the only entry of its list, or `scheme://host` with an optional leading `*.` label and an optional port, in lowercase ASCII with no path. ```typescript type EmbedderSource = string ``` #### HeaderPolicy The fields of a serve config that decide response headers: everything a server needs to build its ordered header rules, and nothing about where it listens or what it serves. ```typescript type HeaderPolicy = Pick ``` #### PolicyIssueCode What kind of problem a PolicyIssue reports, stable across releases so a tool can branch on it. ```typescript type PolicyIssueCode = "config-not-object" | "root-invalid" | "port-invalid" | "host-invalid" | "log-invalid" | "isolation-invalid" | "headers-not-array" | "rule-not-object" | "rule-prefix-invalid" | "rule-suffix-invalid" | "rule-headers-not-object" | "header-name-invalid" | "header-value-not-string" | "header-value-control-character" | "header-value-not-latin1" | "embedders-not-array" | "embedder-not-string" | "embedder-empty" | "embedder-control-character" | "embedder-separator" | "embedder-whitespace" | "embedder-not-ascii" | "embedder-not-lowercase" | "embedder-none-not-alone" | "embedder-keyword-unquoted" | "embedder-keyword-unknown" | "embedder-permits-every-origin" | "embedder-scheme-missing" | "embedder-has-path" | "embedder-port-invalid" | "embedder-wildcard-too-broad" | "embedder-malformed" | "embedders-dropped-by-rule" | "embedders-contradicted-by-rule" | "permissions-policy-not-object" | "permissions-policy-name-invalid" | "permissions-policy-allowlist-not-array" | "permissions-policy-entry-not-string" | "permissions-policy-wildcard-not-alone" | "permissions-policy-keyword-quoted" | "permissions-policy-origin-invalid" | "unknown-field" | "rule-unknown-field" ``` #### ReferrerPolicyValue A value the `Referrer-Policy` header takes. ```typescript type ReferrerPolicyValue = "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url" ``` --- Canonical page: https://www.hyperfrontend.dev/docs/libraries/server/policy/ This file: https://www.hyperfrontend.dev/docs/libraries/server/policy.md Documentation index: https://www.hyperfrontend.dev/llms.txt