@hyperfrontend/server/policy

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.

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.

FieldExpands into
embeddersContent-Security-Policy holding one frame-ancestors directive, plus X-Frame-Options when the list is empty, 'none' or 'self' alone
permissionsPolicyOne Permissions-Policy header; no rule at all for an empty record
isolationCross-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.

RefusedWhy
A bare *, a scheme alone (https:), a host of *Each permits every origin
A host without a schemeIts scheme would follow the served page's
Any path, a trailing / includedAn ancestor is matched by its origin, so a deeper path never matches
Uppercase, 'SELF' includedThe string in the config is the string on the wire
A non-ASCII hostWrite an internationalised name in its punycode form
https://*.appA wildcard over a single label covers a whole top-level domain
A trailing dot, IPv6 brackets, an underscore, user infoOutside the grammar
A keyword without its single quotes, or in double quotesA keyword is written 'self' or 'none'
'none' beside another entryIt 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.

AllowlistHeader 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-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 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.

PresetSets
embeddersWhat the config field expands into, with an optional scope
permissionsPolicyWhat the config field expands into, with an optional scope
crossOriginIsolationWhat the isolation field expands into, with an optional scope
contentSecurityPolicyFour default directives, any authored ones, and frame-ancestors from its embedders, last
nosniffX-Content-Type-Options: nosniff
referrerPolicyReferrer-Policy, strict-origin-when-cross-origin unless told otherwise
strictTransportSecurityStrict-Transport-Security; it takes no scope, because the header covers the whole host
immutableAssetsCache-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

§function

applyHeaderRules(rules: unknown, path: string, headers: Readonly<Record<string, string>>): Record<string, string>

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
NameTypeDescription
§rules
unknownThe rules, in the order they are applied.
§path
stringThe path being answered, starting with /.
§headers
Readonly<Record<string, string>>The headers the response already carries; none when omitted.(default: {})
Returns
Record<string, string>
A new header record; the one passed in is left as it was.
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' }
§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
NameTypeDescription
§value
unknownThe candidate list.
Returns
unknown
Every problem found, in list order; empty when the list is sound.
Example

Checking a list before it is published

checkEmbedders(["'self'", 'https://host.example']) // => []
checkEmbedders(['host.example']).map((issue) => issue.code) // => ['embedder-scheme-missing']
§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
NameTypeDescription
§value
unknownThe candidate record.
Returns
unknown
Every problem found, in authored order; empty when the record is sound.
Example

Checking a record before it is published

checkPermissionsPolicy({ camera: [], geolocation: ['self'] }) // => []
checkPermissionsPolicy({ camera: ["'self'"] }).map((issue) => issue.code) // => ['permissions-policy-keyword-quoted']
§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
NameTypeDescription
§value
unknownThe 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

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.']
§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
NameTypeDescription
§options
ContentSecurityPolicyOptionsThe embedders and any directives beyond the defaults.
§scope?
RuleScopeThe paths the rule applies to; every path when omitted.
Returns
Example

Allowing WebAssembly on the pages one host may frame

contentSecurityPolicy(
  { embedders: ['https://host.example'], directives: { 'script-src': ["'self'", "'wasm-unsafe-eval'"] } },
  { suffix: '.html' }
)
§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
NameTypeDescription
§coep
"require-corp" | "credentialless"The embedder policy that completes the isolation.
§scope?
RuleScopeThe paths the rule applies to; every path when omitted.
Returns
Example

Isolating one application of a site

crossOriginIsolation('credentialless', { prefix: '/app/' })
§function

defineServeConfig(config: ServeConfig): ServeConfig

Identity helper that gives hf-serve.config.* files type-checked authoring.
Parameters
NameTypeDescription
§config
ServeConfigThe static-server configuration object.
Returns
ServeConfig
The same configuration object, narrowed to ServeConfig.
Example

Authoring a typed `hf-serve.config.ts`

export default defineServeConfig({ root: 'dist/site', headers: [{ headers: { 'X-Content-Type-Options': 'nosniff' } }] })
§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
NameTypeDescription
§sources
unknownThe origins allowed to frame the response.
§scope?
RuleScopeThe paths the rule applies to; every path when omitted.
Returns
Example

Letting one host frame every page

embedders(["'self'", 'https://host.example'])
// => { headers: { 'Content-Security-Policy': "frame-ancestors 'self' https://host.example" } }
§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
NameTypeDescription
§policy
HeaderPolicyThe 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

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' } },
// ]
§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
NameTypeDescription
§sources
unknownThe 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

frameAncestors(["'self'", 'https://host.example']) // => "frame-ancestors 'self' https://host.example"
frameAncestors([]) // => "frame-ancestors 'none'"
§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
NameTypeDescription
§policy
stringThe header value.
Returns
unknown
One source list per comma-separated policy that names the directive.
Example

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") // => []
§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
NameTypeDescription
§prefix
stringThe path the files sit under, such as /assets/.
Returns
ServeHeaderRule
The rule, bounded by the prefix.
Example

Caching a build's hashed assets

immutableAssets('/assets/')
// => { prefix: '/assets/', headers: { 'Cache-Control': 'public, max-age=31536000, immutable' } }
§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
NameTypeDescription
§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

isolationRules('require-corp')
§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
NameTypeDescription
§scope
RuleScopeThe 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

matchesEveryPath({ prefix: '/' }) // => true
matchesEveryPath({ suffix: '.html' }) // => false
§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
NameTypeDescription
§scope?
RuleScopeThe paths the rule applies to; every path when omitted.
Returns
Example

Sending the header on every path

nosniff() // => { headers: { 'X-Content-Type-Options': 'nosniff' } }
§function

permissionsPolicy(features: Readonly<Record<string, unknown>>, 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
NameTypeDescription
§features
Readonly<Record<string, unknown>>For each feature, the origins allowed to use it; an empty array disables the feature.
§scope?
RuleScopeThe paths the rule applies to; every path when omitted.
Returns
Example

Disabling the camera and keeping geolocation for this origin

permissionsPolicy({ camera: [], geolocation: ['self'] })
// => { headers: { 'Permissions-Policy': 'camera=(), geolocation=(self)' } }
§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
NameTypeDescription
§source
stringOne 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

permitsEveryOrigin('https://*') // => true
permitsEveryOrigin('https://*.host.example') // => false
§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
NameTypeDescription
§value
ReferrerPolicyValueThe policy; the origin alone on a cross-origin request when omitted.(default: 'strict-origin-when-cross-origin')
§scope?
RuleScopeThe paths the rule applies to; every path when omitted.
Returns
Example

Sending no referrer from a private area

referrerPolicy('no-referrer', { prefix: '/private/' })
// => { prefix: '/private/', headers: { 'Referrer-Policy': 'no-referrer' } }
§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
NameTypeDescription
§options
StrictTransportSecurityOptionsThe 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

strictTransportSecurity({ maxAge: 63072000, includeSubDomains: true, preload: true })
// => { headers: { 'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload' } }
§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
NameTypeDescription
§value
unknownThe candidate header rule.
§index
numberThe rule's index, used to locate problems in the error message.
§sourcePath
stringThe file the rule came from, used in the error message.
Returns
ServeHeaderRule
The validated header rule.
Example

Validating a single header rule

const rule = validateHeaderRule({ suffix: '.html', headers: { 'Cache-Control': 'no-cache' } }, 0, '/p/hf-serve.config.json')
§function

validateServeConfig(value: unknown, sourcePath: string): ServeConfig

Validates an unknown value as a ServeConfig.
Parameters
NameTypeDescription
§value
unknownThe loaded config value.
§sourcePath
stringThe config path, used in error messages.
Returns
ServeConfig
The validated config.
Example

Validating a loaded serve config

const config = validateServeConfig({ root: 'dist/site' }, '/p/hf-serve.config.json')

◈ Interfaces

§interface

ContentSecurityPolicyOptions

What a contentSecurityPolicy rule is built from.
Properties
§readonly embedders:unknownThe origins allowed to frame the response, written last as the frame-ancestors directive; an empty list allows none.
§readonly directives?:Readonly<Record<string, unknown>>Directives to add, or to put in place of a default of the same name; an empty list writes the bare directive name.
§interface

PolicyIssue

One problem found in a serve config, located and worded for the person who wrote the config.
Properties
§readonly code:PolicyIssueCodeThe kind of problem.
§readonly path:stringWhere the problem sits in the config, such as embedders[2]; empty when the config itself is at fault.
§readonly message:stringThe whole sentence a tool prints, which names the path itself.
§interface

ResolvedServeConfig

A fully-resolved hf-serve.config.*: concrete root, listen address, and header rules.
Properties
§readonly root:stringAbsolute directory served as the site root.
§readonly port:numberPort the server listens on.
§readonly host?:stringInterface the server binds; every interface when undefined.
§readonly headers:unknownOrdered header rules, later rules overriding earlier ones per header.
§readonly log:booleanWhether each request is access-logged.
§readonly sourcePath?:stringAbsolute path of the config file that was loaded, absent when serving with pure defaults.
§interface

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
§readonly prefix?:stringPath prefix the rule applies under, e.g. /app/.
§readonly suffix?:stringPath suffix the rule applies to, e.g. .html.
§interface

ServeConfig

Type-checked authoring shape for an hf-serve.config.* file.
Properties
§root?:stringDirectory served as the site root.
§port?:numberPort the server listens on.
§host?:stringInterface 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<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.
§headers?:ServeHeaderRule[]Ordered header rules, later rules overriding earlier ones per header.
§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.
§interface

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
§prefix?:stringPath prefix the rule applies under, e.g. /fish-; matches everything when omitted.
§suffix?:stringPath suffix the rule applies to, e.g. .html; matches everything when omitted.
§headers:Record<string, string>Header names and values the rule sets.
§interface

StrictTransportSecurityOptions

What a strictTransportSecurity rule is built from.
Properties
§readonly maxAge:numberHow long, in whole seconds, a browser keeps to HTTPS for the host; zero retires the policy.
§readonly includeSubDomains?:booleanWhether the policy covers every subdomain of the host as well.
§readonly preload?:booleanWhether the host asks to be built into browsers' preload lists, which needs the subdomains and a lifetime of a year or more.

◆ Types

§type

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.
type EmbedderSource = string
§type

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.
type HeaderPolicy = Pick<ServeConfig, "embedders" | "permissionsPolicy" | "isolation" | "headers">
§type

PolicyIssueCode

What kind of problem a PolicyIssue reports, stable across releases so a tool can branch on it.
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"
§type

ReferrerPolicyValue

A value the 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"