@hyperfrontend/server/policypolicy
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.
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:
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 checks the four fields it reads the way 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:
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 | Content-Security-Policy holding one frame-ancestors directive, plus X-Frame-Options when the list is empty, 'none' or 'self' alone |
permissionsPolicy | One Permissions-Policy header; no rule at all for an empty record |
isolation | Cross-Origin-Opener-Policy: same-origin, the declared Cross-Origin-Embedder-Policy, and Cross-Origin-Resource-Policy: cross-origin |
expandHeaderPolicy places them in that order, ahead of the authored 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 is declared, every authored rule that sets Content-Security-Policy, in any letter case, is checked:
- A rule whose value names no
frame-ancestorsdirective 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 that is empty or /, and a suffix that is empty, exclude none, so a rule carrying only those is judged as a rule for every path. 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 returns every problem of a config at once, each with a stable code, the path it was found at and a full sentence. 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, then 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 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 | What the config field expands into, with an optional scope |
permissionsPolicy | What the config field expands into, with an optional scope |
crossOriginIsolation | What the isolation field expands into, with an optional scope |
contentSecurityPolicy | Four default directives, any authored ones, and frame-ancestors from its embedders, last |
nosniff | X-Content-Type-Options: nosniff |
referrerPolicy | Referrer-Policy, strict-origin-when-cross-origin unless told otherwise |
strictTransportSecurity | Strict-Transport-Security; it takes no scope, because the header covers the whole host |
immutableAssets | Cache-Control: public, max-age=31536000, immutable under a prefix |
The scope is a prefix, a suffix or both, matched the way a rule's are. The defaults of 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 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 tells whether one source lets any origin through, and 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( rules: unknown, path: string, headers: Readonly< Record< string, string>>): Record< string, string>
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
Returns
Record< string, string>Example
Reading what a page and an asset are sent
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' }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
unknownExample
Checking a list before it is published
checkEmbedders(["'self'", 'https://host.example']) // => []
checkEmbedders(['host.example']).map((issue) => issue.code) // => ['embedder-scheme-missing']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
unknownExample
Checking a record before it is published
checkPermissionsPolicy({ camera: [], geolocation: ['self'] }) // => []
checkPermissionsPolicy({ camera: ["'self'"] }).map((issue) => issue.code) // => ['permissions-policy-keyword-quoted']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
unknownExample
Listing what a tool should report about a config
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( options: ContentSecurityPolicyOptions, scope?: RuleScope): ServeHeaderRule
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
ServeHeaderRuleExample
Allowing WebAssembly on the pages one host may frame
contentSecurityPolicy(
{ embedders: ['https://host.example'], directives: { 'script-src': ["'self'", "'wasm-unsafe-eval'"] } },
{ suffix: '.html' }
)crossOriginIsolation( coep: "require-corp" | "credentialless", scope?: RuleScope): ServeHeaderRule
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
Returns
ServeHeaderRuleExample
Isolating one application of a site
crossOriginIsolation('credentialless', { prefix: '/app/' })hf-serve.config.* files type-checked authoring.Parameters
| Name | Type | Description |
|---|---|---|
§config | ServeConfig | The static-server configuration object. |
Returns
ServeConfigExample
Authoring a typed `hf-serve.config.ts`
export default defineServeConfig({ root: 'dist/site', headers: [{ headers: { 'X-Content-Type-Options': 'nosniff' } }] })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
Returns
ServeHeaderRuleExample
Letting one host frame every page
embedders(["'self'", 'https://host.example'])
// => { headers: { 'Content-Security-Policy': "frame-ancestors 'self' https://host.example" } }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
unknownExample
Expanding the policy of a page one host may frame
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' } },
// ]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
stringExample
Writing the directive for a page two sites may frame
frameAncestors(["'self'", 'https://host.example']) // => "frame-ancestors 'self' https://host.example"
frameAncestors([]) // => "frame-ancestors 'none'"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
unknownExample
Reading who may frame a response
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") // => []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
ServeHeaderRuleExample
Caching a build's hashed assets
immutableAssets('/assets/')
// => { prefix: '/assets/', headers: { 'Cache-Control': 'public, max-age=31536000, immutable' } }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
unknownExample
Expanding a declared isolation
isolationRules('require-corp')/ 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.
Returns
booleantrue when neither bound excludes a path.Example
Telling a rule for the whole site from one for its pages
matchesEveryPath({ prefix: '/' }) // => true
matchesEveryPath({ suffix: '.html' }) // => falseX-Content-Type-Options: nosniff.Parameters
Returns
ServeHeaderRuleExample
Sending the header on every path
nosniff() // => { headers: { 'X-Content-Type-Options': 'nosniff' } }permissionsPolicy( features: Readonly< Record< string, unknown>>, scope?: RuleScope): ServeHeaderRule
Permissions-Policy header listing the features in the order the record gives them. An empty record builds a rule that sets no header.Parameters
Returns
ServeHeaderRuleExample
Disabling the camera and keeping geolocation for this origin
permissionsPolicy({ camera: [], geolocation: ['self'] })
// => { headers: { 'Permissions-Policy': 'camera=(), geolocation=(self)' } }, 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
booleantrue when the expression names no particular host.Example
Telling an open source from a wildcard over one site
permitsEveryOrigin('https://*') // => true
permitsEveryOrigin('https://*.host.example') // => falseReferrer-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
ServeHeaderRuleExample
Sending no referrer from a private area
referrerPolicy('no-referrer', { prefix: '/private/' })
// => { prefix: '/private/', headers: { 'Referrer-Policy': 'no-referrer' } }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
ServeHeaderRuleExample
Keeping a host and its subdomains on HTTPS for two years
strictTransportSecurity({ maxAge: 63072000, includeSubDomains: true, preload: true })
// => { headers: { 'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload' } }prefix/suffix strings, a headers record of values Node can send, and no other field.Parameters
Returns
ServeHeaderRuleExample
Validating a single header rule
const rule = validateHeaderRule({ suffix: '.html', headers: { 'Cache-Control': 'no-cache' } }, 0, '/p/hf-serve.config.json')Parameters
Returns
ServeConfigExample
Validating a loaded serve config
const config = validateServeConfig({ root: 'dist/site' }, '/p/hf-serve.config.json')◈ Interfaces
Properties
readonly embedders:unknownThe origins allowed to frame the response, written last as the frame-ancestors directive; an empty list allows none.Properties
readonly path:stringWhere the problem sits in the config, such as embedders[2]; empty when the config itself is at fault.hf-serve.config.*: concrete root, listen address, and header rules.Properties
readonly sourcePath?:stringAbsolute path of the config file that was loaded, absent when serving with pure defaults.prefix (when given) and ends with suffix (when given); a scope with neither, like no scope at all, matches every path.Properties
hf-serve.config.* file.Properties
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< string, string[ ]>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.log?:booleanWhether 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.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
◆ Types
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.type EmbedderSource = stringtype HeaderPolicy = Pick< ServeConfig, "embedders" | "permissionsPolicy" | "isolation" | "headers">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"Referrer-Policy header takes.type ReferrerPolicyValue = "no-referrer" | "no-referrer-when-downgrade" | "origin" | "origin-when-cross-origin" | "same-origin" | "strict-origin" | "strict-origin-when-cross-origin" | "unsafe-url"