Renamed the Web package as Infrastructure (#25)
This PR contains the work done to rename the _Web_ package as _Infrastructure_, to provide a clear naming and purpose to this particular package within the project. To provide further details about the work: * Infrastructure * Asset fingerprinting: an FNV-1a token derived from the static files directory, appended as ?v= to asset URLs so deploys bust caches; pre-rendered pages also revalidate via weak ETags. * New middlewares: fixed-window RateLimitMiddleware (per-client budgets keyed by trusted X-Forwarded-For or remote address) and VaryMiddleware (Accept-Encoding on every response); SecurityHeadersMiddleware now also stamps error responses. * Auto-generated HEAD endpoints, cache max-age configuration, and Docker build/Compose refinements. * Protocols and scaffolding: Asset/AssetExtension, the Page protocol (viewport, stylesheets, scripts, versioned URLs), and LocalizedRequestContext. * Rate limiter's counter store swapped from an actor to a Mutex (no executor hop per request) with amortized batch eviction instead of O(n²) scans under client floods. * FingerprintAssets reports unreadable files to a logger instead of silently producing a token that never busts their cache. Reviewed-on: rock-n-code/loud-amsterdam#25 Co-authored-by: Javier Cicchelli <javier@rock-n-code.com> Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit is contained in:
@@ -26,6 +26,8 @@ func application(
|
||||
logger: logger
|
||||
)
|
||||
let fluent = persistence()
|
||||
|
||||
let fingerprintAssets = FingerprintAssets(logger: logger)
|
||||
let prepareDB = PrepareDB()
|
||||
|
||||
await prepareDB(for: fluent)
|
||||
@@ -33,8 +35,10 @@ func application(
|
||||
var app = Application(
|
||||
router: router(
|
||||
staticFilesPath: reader.staticFilesPath,
|
||||
assetVersion: fingerprintAssets(reader.staticFilesPath),
|
||||
cacheControl: reader.cacheControl,
|
||||
compressionMinResponseSize: reader.compressionMinResponseSize,
|
||||
rateLimit: reader.rateLimit,
|
||||
securityHeaders: reader.securityHeaders,
|
||||
logLevel: reader.logLevel,
|
||||
probe: Probe(fluent: fluent)
|
||||
@@ -117,25 +121,31 @@ private func logger(
|
||||
/// Builds the application's router.
|
||||
///
|
||||
/// Registers the request-logging middleware, the security-headers middleware that stamps the given `securityHeaders` onto every response, the
|
||||
/// response-compression middleware that compresses responses larger than `minimumResponseSizeToCompress` when the client advertises support,
|
||||
/// the localization middleware that negotiates the request's language from its `Accept-Language` header, the not-found middleware that serves the
|
||||
/// error page, and the static file middleware that serves the contents of `staticFilesPath` (tagging responses with the given `cacheControl`
|
||||
/// directives), then adds the `RootController` routes that render the landing page and the `HealthController` routes that serve the health check.
|
||||
/// vary middleware that marks every response as varying on `Accept-Encoding`, the response-compression middleware that compresses responses
|
||||
/// larger than `minimumResponseSizeToCompress` when the client advertises support, the localization middleware that negotiates the request's
|
||||
/// language from its `Accept-Language` header, the not-found middleware that serves the error page, and the static file middleware that serves the
|
||||
/// contents of `staticFilesPath` (tagging responses with the given `cacheControl` directives), then adds the `RootController` routes that
|
||||
/// render the landing page, the `SubscriptionController` routes that register newsletter subscriptions, and the `HealthController` routes
|
||||
/// that serve the health check.
|
||||
///
|
||||
/// The security-headers middleware sits just inside request logging so it covers every response that reaches a client — the landing page, the compressed
|
||||
/// responses, the rendered error page, and the served static files.
|
||||
/// - Parameters:
|
||||
/// - staticFilesPath: the folder, relative to the working directory, the static files are served from.
|
||||
/// - assetVersion: the version token the pages append to their asset URLs, or `nil` to leave them unversioned.
|
||||
/// - cacheControl: the cache-control directives applied to the served static files.
|
||||
/// - compressionMinResponseSize: the minimum response body size, in bytes, before compression is applied.
|
||||
/// - rateLimit: the rate limit applied to the subscription endpoint.
|
||||
/// - securityHeaders: the security headers applied to every response.
|
||||
/// - logLevel: the level the request-logging middleware logs at.
|
||||
/// - probe: the probe consulted by the `HealthController` readiness route.
|
||||
/// - Returns: the configured router.
|
||||
private func router(
|
||||
staticFilesPath: String,
|
||||
assetVersion: String?,
|
||||
cacheControl: CacheControl,
|
||||
compressionMinResponseSize: Int,
|
||||
rateLimit: RateLimitMiddleware<AppRequestContext>.Configuration,
|
||||
securityHeaders: SecurityHeadersMiddleware<AppRequestContext>.Configuration,
|
||||
logLevel: Logger.Level,
|
||||
probe: Probe
|
||||
@@ -152,11 +162,14 @@ private func router(
|
||||
SecurityHeadersMiddleware(
|
||||
configuration: securityHeaders
|
||||
)
|
||||
VaryMiddleware()
|
||||
ResponseCompressionMiddleware(
|
||||
minimumResponseSizeToCompress: compressionMinResponseSize
|
||||
)
|
||||
LocalizationMiddleware()
|
||||
NotFoundMiddleware()
|
||||
NotFoundMiddleware(
|
||||
assetVersion: assetVersion
|
||||
)
|
||||
FileMiddleware(
|
||||
staticFilesPath,
|
||||
cacheControl: cacheControl
|
||||
@@ -164,7 +177,9 @@ private func router(
|
||||
}
|
||||
|
||||
router.addController {
|
||||
RootController<AppRequestContext>()
|
||||
RootController<AppRequestContext>(
|
||||
assetVersion: assetVersion
|
||||
)
|
||||
HealthController<AppRequestContext>(
|
||||
probe: probe
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Configuration
|
||||
import Hummingbird
|
||||
import Infrastructure
|
||||
import Logging
|
||||
import Persistence
|
||||
import WebsiteLibrary
|
||||
@@ -15,9 +16,16 @@ package extension ConfigReader {
|
||||
|
||||
/// The `Cache-Control` policy applied to static files, grouped by media type.
|
||||
///
|
||||
/// The max-ages are read from the `cache.maxAge.text`, `cache.maxAge.image`, and `cache.maxAge.default` keys. Text files (CSS,
|
||||
/// JavaScript, plain text) additionally require revalidation once stale; images and everything else are served public with their max-age alone.
|
||||
/// The max-ages are read from the `cache.maxAge.asset`, `cache.maxAge.text`, `cache.maxAge.image`, and
|
||||
/// `cache.maxAge.default` keys. Stylesheets and scripts are referenced through fingerprinted URLs (see `FingerprintAssets`) and
|
||||
/// fonts are immutable subset files, so all three are served long-lived and `immutable` — a deploy busts them by changing the URL, never by
|
||||
/// revalidation. The remaining text files (e.g. `robots.txt`) keep their unversioned URLs and require revalidation once stale; images and
|
||||
/// everything else are served public with their max-age alone. The groups match in order, so the specific types precede the `text` category.
|
||||
var cacheControl: CacheControl {
|
||||
let maxAgeAsset = int(
|
||||
forKey: .Cache.maxAgeAsset,
|
||||
default: .Cache.maxAgeAsset
|
||||
)
|
||||
let maxAgeDefault = int(
|
||||
forKey: .Cache.maxAgeDefault,
|
||||
default: .Cache.maxAgeDefault
|
||||
@@ -32,6 +40,9 @@ package extension ConfigReader {
|
||||
)
|
||||
|
||||
return .init([
|
||||
(.textCss, [.public, .maxAge(maxAgeAsset), .immutable]),
|
||||
(.textJavascript, [.public, .maxAge(maxAgeAsset), .immutable]),
|
||||
(.font, [.public, .maxAge(maxAgeAsset), .immutable]),
|
||||
(.text, [.public, .maxAge(maxAgeText), .mustRevalidate]),
|
||||
(.image, [.public, .maxAge(maxAgeImage)]),
|
||||
(.init(type: .any), [.public, .maxAge(maxAgeDefault)]),
|
||||
@@ -110,6 +121,28 @@ package extension ConfigReader {
|
||||
)
|
||||
}
|
||||
|
||||
/// The rate limit applied to the subscription endpoint, built from the `rateLimit.*` keys.
|
||||
///
|
||||
/// `rateLimit.limit` requests are admitted per client per `rateLimit.window` seconds. When
|
||||
/// `rateLimit.trustForwardedFor` is set, clients are keyed by the first `X-Forwarded-For` entry —
|
||||
/// enable it only behind a reverse proxy that sets the header, since clients can forge it otherwise.
|
||||
var rateLimit: RateLimitMiddleware<AppRequestContext>.Configuration {
|
||||
.init(
|
||||
limit: int(
|
||||
forKey: .RateLimit.limit,
|
||||
default: .RateLimit.limit
|
||||
),
|
||||
window: .seconds(int(
|
||||
forKey: .RateLimit.window,
|
||||
default: .RateLimit.window
|
||||
)),
|
||||
trustForwardedFor: bool(
|
||||
forKey: .RateLimit.trustForwardedFor,
|
||||
default: false
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// The security headers middleware configuration, built from the `security.*` keys.
|
||||
///
|
||||
/// Every header value has a default except `Strict-Transport-Security`, which is only sent when `security.strictTransportSecurity`
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import Infrastructure
|
||||
|
||||
/// A static file shipped with the website service.
|
||||
///
|
||||
/// Each case identifies a file name stored under the static files root (the `Resources/Static`
|
||||
/// directory) and served by Hummingbird's `FileMiddleware` middleware. A name can be available
|
||||
/// with more than one extension (see ``fileExtensions``), each resolving to its own file.
|
||||
enum StaticFile: CaseIterable, Sendable {
|
||||
enum StaticFile: Asset, CaseIterable {
|
||||
/// The `apple-touch-icon.png` icon.
|
||||
case appleTouchIcon
|
||||
/// The `css/error.css` stylesheet and `js/error.js` script for the not-found page.
|
||||
@@ -28,30 +30,6 @@ enum StaticFile: CaseIterable, Sendable {
|
||||
case sitemap
|
||||
}
|
||||
|
||||
// MARK: - Enumerations
|
||||
|
||||
extension StaticFile {
|
||||
/// A file extension used by a ``StaticFile``.
|
||||
enum Extension: String, Sendable {
|
||||
/// A Cascading Style Sheets file.
|
||||
case css
|
||||
/// A JavaScript file.
|
||||
case js
|
||||
/// A Portable Network Graphics image.
|
||||
case png
|
||||
/// A Windows icon image.
|
||||
case ico
|
||||
/// A Scalable Vector Graphics image.
|
||||
case svg
|
||||
/// A plain text file.
|
||||
case txt
|
||||
/// A web application manifest file.
|
||||
case webmanifest
|
||||
/// An Extensible Markup Language file.
|
||||
case xml
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Extensions
|
||||
|
||||
extension StaticFile {
|
||||
@@ -59,7 +37,7 @@ extension StaticFile {
|
||||
// MARK: Computed
|
||||
|
||||
/// The file extensions the file is available with.
|
||||
var fileExtensions: [Extension] {
|
||||
var fileExtensions: [AssetExtension] {
|
||||
switch self {
|
||||
case .appleTouchIcon,
|
||||
.icon192,
|
||||
@@ -92,79 +70,4 @@ extension StaticFile {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Methods
|
||||
|
||||
/// Resolves the file's path against the given base directory.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - basePath: the directory the static files are served from.
|
||||
/// - fileExtension: the extension of the file to resolve.
|
||||
/// - Returns: the path to the file, relative to the `basePath` path.
|
||||
func path(
|
||||
relativeTo basePath: String,
|
||||
for fileExtension: Extension
|
||||
) -> String {
|
||||
let relativePath = relativePath(for: fileExtension)
|
||||
|
||||
guard !basePath.isEmpty else {
|
||||
return relativePath
|
||||
}
|
||||
|
||||
return "\(basePath)/\(relativePath)"
|
||||
}
|
||||
|
||||
/// Resolves the file's path relative to the static files root (e.g. `"css/shared.css"`).
|
||||
///
|
||||
/// This also matches the URL path the file is served at by `FileMiddleware`.
|
||||
///
|
||||
/// - Parameter fileExtension: the extension of the file to resolve.
|
||||
/// - Returns: the path to the file, relative to the static files root.
|
||||
func relativePath(
|
||||
for fileExtension: Extension
|
||||
) -> String {
|
||||
let file = "\(fileName).\(fileExtension.rawValue)"
|
||||
|
||||
return fileExtension.subdirectory
|
||||
.map { "\($0)/\(file)" } ?? file
|
||||
}
|
||||
|
||||
/// Resolves the absolute URL path the file is served at (e.g. `"/css/shared.css"`).
|
||||
///
|
||||
/// - Parameter fileExtension: the extension of the file to resolve.
|
||||
/// - Returns: the path to use in `href` and `src` attributes.
|
||||
func urlPath(
|
||||
for fileExtension: Extension
|
||||
) -> String {
|
||||
"/\(relativePath(for: fileExtension))"
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension StaticFile.Extension {
|
||||
|
||||
// MARK: Computed
|
||||
|
||||
/// The file's content type.
|
||||
var contentType: String {
|
||||
switch self {
|
||||
case .css: "text/css"
|
||||
case .js: "text/javascript"
|
||||
case .png: "image/png"
|
||||
case .ico: "image/vnd.microsoft.icon"
|
||||
case .svg: "image/svg+xml"
|
||||
case .txt: "text/plain"
|
||||
case .webmanifest: "application/manifest+json"
|
||||
case .xml: "application/xml"
|
||||
}
|
||||
}
|
||||
|
||||
/// The sub-directory within the static root that holds files with this extension, if any.
|
||||
var subdirectory: String? {
|
||||
switch self {
|
||||
case .css: "css"
|
||||
case .js: "js"
|
||||
default: nil
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import Elementary
|
||||
import Foundation
|
||||
import Infrastructure
|
||||
import Localization
|
||||
|
||||
/// The site-wide defaults shared by every page of the website.
|
||||
extension Page {
|
||||
|
||||
// MARK: Computed
|
||||
|
||||
/// The document language, derived from the page's locale and falling back to the default language.
|
||||
var lang: String {
|
||||
locale.language.languageCode?.identifier
|
||||
?? LanguageList(bundle: .module).default
|
||||
}
|
||||
|
||||
/// The icon, manifest, and theme colour metadata shared by every page of the website.
|
||||
@HTMLBuilder
|
||||
var metadata: some HTML {
|
||||
link(
|
||||
.rel(.icon),
|
||||
.href(StaticFile.favicon.urlPath(
|
||||
for: .ico,
|
||||
version: assetVersion
|
||||
)),
|
||||
.custom(
|
||||
name: "sizes",
|
||||
value: "any"
|
||||
)
|
||||
)
|
||||
link(
|
||||
.rel(.icon),
|
||||
.href(StaticFile.icon.urlPath(
|
||||
for: .svg,
|
||||
version: assetVersion
|
||||
)),
|
||||
.custom(
|
||||
name: "type",
|
||||
value: "image/svg+xml"
|
||||
)
|
||||
)
|
||||
link(
|
||||
.rel("apple-touch-icon"),
|
||||
.href(StaticFile.appleTouchIcon.urlPath(
|
||||
for: .png,
|
||||
version: assetVersion
|
||||
))
|
||||
)
|
||||
link(
|
||||
.rel("manifest"),
|
||||
.href(StaticFile.site.urlPath(
|
||||
for: .webmanifest,
|
||||
version: assetVersion
|
||||
))
|
||||
)
|
||||
meta(
|
||||
.name("theme-color"),
|
||||
.content("#fafafa")
|
||||
)
|
||||
meta(
|
||||
.name("theme-color"),
|
||||
.content("#0c0710"),
|
||||
.custom(
|
||||
name: "media",
|
||||
value: "(prefers-color-scheme: dark)"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import Elementary
|
||||
import Foundation
|
||||
import Infrastructure
|
||||
import Localization
|
||||
|
||||
/// The HTML page rendered for a not-found response, with its text localized to a given locale.
|
||||
@@ -7,6 +8,9 @@ struct ErrorPage {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The version token appended to the page's asset URLs, or `nil` to leave them unversioned.
|
||||
let assetVersion: String?
|
||||
|
||||
/// The locale the page content is localized to.
|
||||
let locale: Locale
|
||||
|
||||
@@ -16,10 +20,15 @@ struct ErrorPage {
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a not-found page localized to the given locale.
|
||||
/// - Parameter locale: the locale the page content is localized to.
|
||||
/// - Parameters:
|
||||
/// - locale: the locale the page content is localized to.
|
||||
/// - assetVersion: the version token appended to the page's asset URLs, or `nil` (the
|
||||
/// default) to leave them unversioned.
|
||||
init(
|
||||
locale: Locale
|
||||
locale: Locale,
|
||||
assetVersion: String? = nil
|
||||
) {
|
||||
self.assetVersion = assetVersion
|
||||
self.locale = locale
|
||||
self.localize = .init(bundle: .module)
|
||||
}
|
||||
@@ -40,12 +49,12 @@ extension ErrorPage: Page {
|
||||
}
|
||||
}
|
||||
|
||||
var scripts: [StaticFile] {
|
||||
[.error, .shared]
|
||||
var scripts: [any Asset] {
|
||||
[StaticFile.error, StaticFile.shared]
|
||||
}
|
||||
|
||||
var stylesheets: [StaticFile] {
|
||||
[.shared, .error]
|
||||
var stylesheets: [any Asset] {
|
||||
[StaticFile.shared, StaticFile.error]
|
||||
}
|
||||
|
||||
var title: String {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import Elementary
|
||||
import Foundation
|
||||
import Infrastructure
|
||||
import Localization
|
||||
|
||||
/// The website's landing page, with its text localized to a given locale.
|
||||
@@ -7,6 +8,9 @@ struct IndexPage {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The version token appended to the page's asset URLs, or `nil` to leave them unversioned.
|
||||
let assetVersion: String?
|
||||
|
||||
/// The locale the page content is localized to.
|
||||
let locale: Locale
|
||||
|
||||
@@ -16,10 +20,15 @@ struct IndexPage {
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a landing page localized to the given locale.
|
||||
/// - Parameter locale: the locale the page content is localized to.
|
||||
/// - Parameters:
|
||||
/// - locale: the locale the page content is localized to.
|
||||
/// - assetVersion: the version token appended to the page's asset URLs, or `nil` (the
|
||||
/// default) to leave them unversioned.
|
||||
init(
|
||||
locale: Locale
|
||||
locale: Locale,
|
||||
assetVersion: String? = nil
|
||||
) {
|
||||
self.assetVersion = assetVersion
|
||||
self.locale = locale
|
||||
self.localize = .init(bundle: .module)
|
||||
}
|
||||
@@ -38,12 +47,12 @@ extension IndexPage: Page {
|
||||
}
|
||||
}
|
||||
|
||||
var scripts: [StaticFile] {
|
||||
[.index, .shared]
|
||||
var scripts: [any Asset] {
|
||||
[StaticFile.index, StaticFile.shared]
|
||||
}
|
||||
|
||||
var stylesheets: [StaticFile] {
|
||||
[.shared, .index]
|
||||
var stylesheets: [any Asset] {
|
||||
[StaticFile.shared, StaticFile.index]
|
||||
}
|
||||
|
||||
var title: String {
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
import Elementary
|
||||
import Foundation
|
||||
import Localization
|
||||
|
||||
/// A page of the website: an HTML document with the shared scaffolding assembled around the page's content.
|
||||
///
|
||||
/// A conforming page supplies its locale, its localized title, the stylesheets and scripts it needs, and its content; the protocol assembles the rest of the
|
||||
/// document around them: the metadata, stylesheet, icon, and manifest links in the head, the content followed by the script tags in the body, and the
|
||||
/// document language derived from the locale.
|
||||
protocol Page: HTMLDocument, Sendable {
|
||||
|
||||
// MARK: Associated types
|
||||
|
||||
/// The type of the page's markup.
|
||||
associatedtype Content: HTML
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The page's markup, rendered before the ``scripts``.
|
||||
@HTMLBuilder
|
||||
var content: Content { get }
|
||||
|
||||
/// The locale the page content is localized to.
|
||||
var locale: Locale { get }
|
||||
|
||||
/// The scripts loaded at the end of the document body, in order.
|
||||
var scripts: [StaticFile] { get }
|
||||
|
||||
/// The stylesheets linked in the document head, in order.
|
||||
var stylesheets: [StaticFile] { get }
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Implementations
|
||||
|
||||
extension Page {
|
||||
|
||||
// MARK: Computed
|
||||
|
||||
/// The page ``content`` followed by its ``scripts``.
|
||||
@HTMLBuilder
|
||||
var body: some HTML {
|
||||
content
|
||||
for file in scripts {
|
||||
script(.src(file.urlPath(for: .js))) {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The metadata, ``stylesheets``, icon, and manifest links placed in the document head.
|
||||
///
|
||||
/// The charset declaration is omitted: Elementary's `HTMLDocument` scaffolding already
|
||||
/// emits `<meta charset="UTF-8">` before this markup, and HTML5 allows only one.
|
||||
@HTMLBuilder
|
||||
var head: some HTML {
|
||||
meta(
|
||||
.name(.viewport),
|
||||
.content("width=device-width, initial-scale=1")
|
||||
)
|
||||
for file in stylesheets {
|
||||
link(
|
||||
.rel(.stylesheet),
|
||||
.href(file.urlPath(for: .css))
|
||||
)
|
||||
}
|
||||
link(
|
||||
.rel(.icon),
|
||||
.href(StaticFile.favicon.urlPath(for: .ico)),
|
||||
.custom(
|
||||
name: "sizes",
|
||||
value: "any"
|
||||
)
|
||||
)
|
||||
link(
|
||||
.rel(.icon),
|
||||
.href(StaticFile.icon.urlPath(for: .svg)),
|
||||
.custom(
|
||||
name: "type",
|
||||
value: "image/svg+xml"
|
||||
)
|
||||
)
|
||||
link(
|
||||
.rel("apple-touch-icon"),
|
||||
.href(StaticFile.appleTouchIcon.urlPath(for: .png))
|
||||
)
|
||||
link(
|
||||
.rel("manifest"),
|
||||
.href(StaticFile.site.urlPath(for: .webmanifest))
|
||||
)
|
||||
meta(
|
||||
.name("theme-color"),
|
||||
.content("#fafafa")
|
||||
)
|
||||
meta(
|
||||
.name("theme-color"),
|
||||
.content("#0c0710"),
|
||||
.custom(
|
||||
name: "media",
|
||||
value: "(prefers-color-scheme: dark)"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
/// The document language, derived from the page's locale and falling back to the default language.
|
||||
var lang: String {
|
||||
locale.language.languageCode?.identifier
|
||||
?? LanguageList(bundle: .module).default
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import Elementary
|
||||
import HTTPTypes
|
||||
import Hummingbird
|
||||
import NIOCore
|
||||
|
||||
/// A pre-rendered HTTP response for a fully static HTML page.
|
||||
///
|
||||
/// The document is rendered to bytes once, at initialization, and every ``response()`` reuses those
|
||||
/// bytes — along with a fixed status and precomputed headers — instead of re-rendering. This suits
|
||||
/// pages whose markup never changes between requests, such as the landing page and the not-found
|
||||
/// page, avoiding a per-request Elementary render on hot paths.
|
||||
///
|
||||
/// ``LocalizedHTMLCollectionResponse`` builds on this type, caching one instance per supported language.
|
||||
///
|
||||
/// The body is written as an unsized stream (no `Content-Length`), mirroring `HTMLResponse`, so the
|
||||
/// response-compression middleware downstream treats it exactly as it would a freshly rendered page.
|
||||
struct CachedHTMLResponse: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The page rendered to bytes once.
|
||||
private let buffer: ByteBuffer
|
||||
/// The headers applied to every response, precomputed once.
|
||||
private let headers: HTTPFields
|
||||
/// The status applied to every response.
|
||||
private let status: HTTPResponse.Status
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Renders the given document to bytes once.
|
||||
/// - Parameters:
|
||||
/// - status: the status applied to every response. Defaults to `.ok`.
|
||||
/// - additionalHeaders: extra headers merged onto every response, alongside the content type.
|
||||
/// Used to carry per-language signals such as `Content-Language` and `Vary`.
|
||||
/// - document: the static HTML document to render and cache.
|
||||
init(
|
||||
status: HTTPResponse.Status = .ok,
|
||||
additionalHeaders: HTTPFields = [:],
|
||||
document: some HTMLDocument
|
||||
) {
|
||||
var headers: HTTPFields = [
|
||||
.contentType: "text/html; charset=utf-8"
|
||||
]
|
||||
|
||||
for field in additionalHeaders {
|
||||
headers[field.name] = field.value
|
||||
}
|
||||
|
||||
self.status = status
|
||||
self.headers = headers
|
||||
self.buffer = .init(string: document.render())
|
||||
}
|
||||
|
||||
// MARK: Methods
|
||||
|
||||
/// Builds a response from the cached, pre-rendered bytes.
|
||||
///
|
||||
/// Mirrors the `text/html; charset=utf-8` content type `HTMLResponse` produces, and leaves the
|
||||
/// `Content-Length` unset so small pages remain eligible for compression.
|
||||
/// - Returns: the response carrying the cached HTML body.
|
||||
func response() -> Response {
|
||||
Response(
|
||||
status: status,
|
||||
headers: headers,
|
||||
body: .init { [buffer] writer in
|
||||
try await writer.write(buffer)
|
||||
try await writer.finish(nil)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
-65
@@ -1,65 +0,0 @@
|
||||
import Elementary
|
||||
import Foundation
|
||||
import HTTPTypes
|
||||
import Hummingbird
|
||||
import Localization
|
||||
|
||||
/// A per-language collection of pre-rendered HTML responses.
|
||||
///
|
||||
/// At initialization it renders the document once for each language the bundle's ``LanguageList``
|
||||
/// reports and caches the bytes, mirroring ``CachedHTMLResponse``'s render-once model but keyed by
|
||||
/// language. Each cached response carries a `Content-Language` header and `Vary: Accept-Language`, so
|
||||
/// shared caches key on the negotiated language instead of serving one language to everyone.
|
||||
struct LocalizedHTMLCollectionResponse: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The supported languages and default language, derived from the module's String Catalog.
|
||||
private let list: LanguageList
|
||||
|
||||
/// The pre-rendered responses, keyed by language identifier.
|
||||
private let responses: [String: CachedHTMLResponse]
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Renders the document once per supported language.
|
||||
/// - Parameters:
|
||||
/// - status: the status applied to every response. Defaults to `.ok`.
|
||||
/// - document: builds the document to render for a given locale.
|
||||
init<Document: HTMLDocument>(
|
||||
status: HTTPResponse.Status = .ok,
|
||||
document: (Locale) -> Document
|
||||
) {
|
||||
self.list = .init(bundle: .module)
|
||||
self.responses = list.all
|
||||
.reduce(into: [:]) { responses, language in
|
||||
responses[language] = CachedHTMLResponse(
|
||||
status: status,
|
||||
additionalHeaders: [
|
||||
.contentLanguage: language,
|
||||
.vary: "Accept-Language",
|
||||
],
|
||||
document: document(.init(identifier: language))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Methods
|
||||
|
||||
/// Builds the response for the given language, falling back to the default language.
|
||||
/// - Parameter language: the negotiated language identifier.
|
||||
/// - Returns: the cached response for the language, the default language's response when the
|
||||
/// language is unavailable, or a `500 Internal Server Error` if neither is cached.
|
||||
func response(
|
||||
for language: String
|
||||
) -> Response {
|
||||
guard
|
||||
let response = responses[language] ?? responses[list.default]
|
||||
else {
|
||||
return .init(status: .internalServerError)
|
||||
}
|
||||
|
||||
return response.response()
|
||||
}
|
||||
|
||||
}
|
||||
+8
-18
@@ -1,26 +1,13 @@
|
||||
import Hummingbird
|
||||
|
||||
/// A request context that carries the language negotiated for the request.
|
||||
///
|
||||
/// ``LocalizationMiddleware`` resolves the visitor's preferred language from the `Accept-Language`
|
||||
/// header and stores it here, so downstream controllers and middleware can serve the matching
|
||||
/// localization without re-reading the header.
|
||||
public protocol LocalizedRequestContext: RequestContext {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The language identifier negotiated for the request.
|
||||
var language: String { get set }
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Context
|
||||
import Infrastructure
|
||||
import NIOCore
|
||||
|
||||
/// The website's request context.
|
||||
///
|
||||
/// Extends the core request storage with the negotiated language, defaulting to the default
|
||||
/// supported language until ``LocalizationMiddleware`` resolves it from the request.
|
||||
public struct WebsiteRequestContext: LocalizedRequestContext {
|
||||
/// supported language until ``LocalizationMiddleware`` resolves it from the request, and with
|
||||
/// the connected client's address, so ``RateLimitMiddleware`` can key its budgets per client.
|
||||
public struct WebsiteRequestContext: LocalizedRequestContext, RemoteAddressRequestContext {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
@@ -28,6 +15,8 @@ public struct WebsiteRequestContext: LocalizedRequestContext {
|
||||
public var coreContext: CoreRequestContextStorage
|
||||
/// The language identifier negotiated for the request.
|
||||
public var language: String
|
||||
/// The address of the connected client, captured from the source channel.
|
||||
public let remoteAddress: SocketAddress?
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
@@ -38,6 +27,7 @@ public struct WebsiteRequestContext: LocalizedRequestContext {
|
||||
) {
|
||||
self.coreContext = .init(source: source)
|
||||
self.language = .empty
|
||||
self.remoteAddress = source.channel.remoteAddress
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import Foundation
|
||||
import Hummingbird
|
||||
import Infrastructure
|
||||
|
||||
@@ -24,9 +25,16 @@ public struct RootController<Context: LocalizedRequestContext> {
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a root controller.
|
||||
public init() {
|
||||
self.responses = .init {
|
||||
IndexPage(locale: $0)
|
||||
/// - Parameter assetVersion: the version token appended to the page's asset URLs, or `nil`
|
||||
/// (the default) to leave them unversioned.
|
||||
public init(
|
||||
assetVersion: String? = nil
|
||||
) {
|
||||
self.responses = .init(bundle: .module) {
|
||||
IndexPage(
|
||||
locale: $0,
|
||||
assetVersion: assetVersion
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +78,10 @@ private extension RootController {
|
||||
request: Request,
|
||||
context: Context
|
||||
) -> Response {
|
||||
responses.response(for: context.language)
|
||||
responses.response(
|
||||
for: context.language,
|
||||
request: request
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+12
-1
@@ -3,7 +3,9 @@ import Configuration
|
||||
extension AbsoluteConfigKey {
|
||||
/// A namespace for the static files cache configuration keys, as absolute keys.
|
||||
public enum Cache {
|
||||
/// The absolute configuration key for the max-age, in seconds, applied to text-based static files.
|
||||
/// The absolute configuration key for the max-age, in seconds, applied to fingerprinted assets and fonts.
|
||||
public static let maxAgeAsset: AbsoluteConfigKey = .init(.Cache.maxAgeAsset)
|
||||
/// The absolute configuration key for the max-age, in seconds, applied to unversioned text-based static files.
|
||||
public static let maxAgeText: AbsoluteConfigKey = .init(.Cache.maxAgeText)
|
||||
/// The absolute configuration key for the max-age, in seconds, applied to image static files.
|
||||
public static let maxAgeImage: AbsoluteConfigKey = .init(.Cache.maxAgeImage)
|
||||
@@ -50,6 +52,15 @@ extension AbsoluteConfigKey {
|
||||
/// The absolute configuration key for the minimum log level.
|
||||
public static let level: AbsoluteConfigKey = .init(.Log.level)
|
||||
}
|
||||
/// A namespace for the rate limit configuration keys, as absolute keys.
|
||||
public enum RateLimit {
|
||||
/// The absolute configuration key for the number of requests admitted per client per window.
|
||||
public static let limit: AbsoluteConfigKey = .init(.RateLimit.limit)
|
||||
/// The absolute configuration key for the window length, in seconds.
|
||||
public static let window: AbsoluteConfigKey = .init(.RateLimit.window)
|
||||
/// The absolute configuration key for keying clients by the first `X-Forwarded-For` entry.
|
||||
public static let trustForwardedFor: AbsoluteConfigKey = .init(.RateLimit.trustForwardedFor)
|
||||
}
|
||||
/// A namespace for the path configuration keys, as absolute keys.
|
||||
public enum Path {
|
||||
/// The absolute configuration key for the directory the static files are served from.
|
||||
|
||||
@@ -3,7 +3,9 @@ import Configuration
|
||||
extension ConfigKey {
|
||||
/// A namespace for the static files cache configuration keys.
|
||||
public enum Cache {
|
||||
/// The configuration key for the max-age, in seconds, applied to text-based static files (CSS, JavaScript, plain text).
|
||||
/// The configuration key for the max-age, in seconds, applied to fingerprinted assets (CSS, JavaScript) and fonts.
|
||||
public static let maxAgeAsset: ConfigKey = "cache.maxAge.asset"
|
||||
/// The configuration key for the max-age, in seconds, applied to unversioned text-based static files (e.g. plain text).
|
||||
public static let maxAgeText: ConfigKey = "cache.maxAge.text"
|
||||
/// The configuration key for the max-age, in seconds, applied to image static files (ICO, PNG, SVG).
|
||||
public static let maxAgeImage: ConfigKey = "cache.maxAge.image"
|
||||
@@ -50,6 +52,15 @@ extension ConfigKey {
|
||||
/// The configuration key for the minimum log level.
|
||||
public static let level: ConfigKey = "log.level"
|
||||
}
|
||||
/// A namespace for the rate limit configuration keys.
|
||||
public enum RateLimit {
|
||||
/// The configuration key for the number of requests admitted per client per window.
|
||||
public static let limit: ConfigKey = "rateLimit.limit"
|
||||
/// The configuration key for the window length, in seconds.
|
||||
public static let window: ConfigKey = "rateLimit.window"
|
||||
/// The configuration key for keying clients by the first `X-Forwarded-For` entry (enable only behind a trusted proxy).
|
||||
public static let trustForwardedFor: ConfigKey = "rateLimit.trustForwardedFor"
|
||||
}
|
||||
/// A namespace for the path configuration keys.
|
||||
public enum Path {
|
||||
/// The configuration key for the directory the static files are served from.
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import HTTPTypes
|
||||
|
||||
extension HTTPField.Name {
|
||||
/// The `Permissions-Policy` field name (not provided as a standard `HTTPField.Name`).
|
||||
static let permissionsPolicy = Self("Permissions-Policy")!
|
||||
/// The `Referrer-Policy` field name (not provided as a standard `HTTPField.Name`).
|
||||
static let referrerPolicy = Self("Referrer-Policy")!
|
||||
/// The `X-Frame-Options` field name (not provided as a standard `HTTPField.Name`).
|
||||
static let frameOptions = Self("X-Frame-Options")!
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
extension Int {
|
||||
/// A namespace for the cache's default configuration values.
|
||||
public enum Cache {
|
||||
/// The default max-age, in seconds, applied to text-based static files (1 hour).
|
||||
/// The default max-age, in seconds, applied to fingerprinted assets and fonts (1 year).
|
||||
public static let maxAgeAsset = 31_536_000
|
||||
/// The default max-age, in seconds, applied to unversioned text-based static files (1 hour).
|
||||
public static let maxAgeText = 3_600
|
||||
/// The default max-age, in seconds, applied to image static files (1 week).
|
||||
public static let maxAgeImage = 604_800
|
||||
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import Foundation
|
||||
import Infrastructure
|
||||
|
||||
public extension LocalizationMiddleware {
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a localization middleware that negotiates against the module's String Catalog languages.
|
||||
init() {
|
||||
self.init(bundle: .module)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import Foundation
|
||||
import Infrastructure
|
||||
|
||||
public extension NotFoundMiddleware {
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a not-found middleware that renders the website's error page, localized to the module's String Catalog languages.
|
||||
/// - Parameter assetVersion: the version token appended to the page's asset URLs, or `nil` (the default) to leave them unversioned.
|
||||
init(
|
||||
assetVersion: String? = nil
|
||||
) {
|
||||
self.init(bundle: .module) {
|
||||
ErrorPage(
|
||||
locale: $0,
|
||||
assetVersion: assetVersion
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -23,27 +23,6 @@ extension String {
|
||||
/// The directory, relative to the working directory, that the website's static files are served from.
|
||||
public static let staticResources = "Resources/Static"
|
||||
}
|
||||
/// A namespace for the security headers' default configuration values.
|
||||
///
|
||||
/// `Strict-Transport-Security` is intentionally absent: it is only safe over HTTPS and is
|
||||
/// "sticky" in browsers, so it stays off unless explicitly configured in production.
|
||||
public enum Security {
|
||||
/// The default `Content-Security-Policy`.
|
||||
///
|
||||
/// Restricts every resource to the site's own origin (`default-src 'self'`), blocks plugins
|
||||
/// (`object-src 'none'`), pins the document base URL (`base-uri 'self'`), and forbids framing
|
||||
/// (`frame-ancestors 'none'`). Both pages link external stylesheets, so no inline-style
|
||||
/// exception is required.
|
||||
public static let contentSecurityPolicy = "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
|
||||
/// The default `X-Content-Type-Options` (disables MIME sniffing).
|
||||
public static let contentTypeOptions = "nosniff"
|
||||
/// The default `X-Frame-Options` (forbids framing the page).
|
||||
public static let frameOptions = "DENY"
|
||||
/// The default `Referrer-Policy`.
|
||||
public static let referrerPolicy = "strict-origin-when-cross-origin"
|
||||
/// The default `Permissions-Policy` (denies access to powerful browser features the site does not use).
|
||||
public static let permissionsPolicy = "accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()"
|
||||
}
|
||||
/// A namespace for the server string constants.
|
||||
public enum Server {
|
||||
/// The website server's name.
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
import HTTPTypes
|
||||
import Hummingbird
|
||||
import Localization
|
||||
|
||||
/// Resolves the visitor's preferred language and records it on the request context.
|
||||
///
|
||||
/// Placed ahead of the localized responders in the middleware chain, it reads the request's
|
||||
/// `Accept-Language` header, negotiates the best supported match (falling back to the default
|
||||
/// language), and stores it on the context's ``LocalizedRequestContext/language``.
|
||||
///
|
||||
/// The request is otherwise passed through untouched — the URL and routing are not affected — so
|
||||
/// each page is served at its existing path and varies its content by header.
|
||||
public struct LocalizationMiddleware<Context: LocalizedRequestContext> {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// Negotiates the request's language from its `Accept-Language` header.
|
||||
private let negotiate: Negotiate
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a localization middleware that negotiates against the module's String Catalog languages.
|
||||
public init() {
|
||||
self.negotiate = .init(bundle: .module)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - RouterMiddleware
|
||||
|
||||
extension LocalizationMiddleware: RouterMiddleware {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// Negotiates the request's language and records it on the context before passing it down.
|
||||
/// - Parameters:
|
||||
/// - request: the incoming request.
|
||||
/// - context: the context the request is resolved against.
|
||||
/// - next: the next responder in the middleware chain.
|
||||
/// - Returns: the downstream response.
|
||||
/// - Throws: any error thrown downstream.
|
||||
public func handle(
|
||||
_ request: Request,
|
||||
context: Context,
|
||||
next: (Request, Context) async throws -> Response
|
||||
) async throws -> Response {
|
||||
var context = context
|
||||
|
||||
context.language = negotiate(
|
||||
acceptLanguage: request.headers[.acceptLanguage]
|
||||
)
|
||||
|
||||
return try await next(request, context)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import Hummingbird
|
||||
|
||||
/// Serves a custom error page for requests that match neither a route nor a static file.
|
||||
///
|
||||
/// Placed ahead of `FileMiddleware` in the middleware chain, it catches the `.notFound` error
|
||||
/// that bubbles up when no file exists for the requested path and responds with the rendered
|
||||
/// ``ErrorPage`` and a `404 Not Found` status. The page is served in the language stored on the
|
||||
/// context by ``LocalizationMiddleware``, falling back to the default language.
|
||||
public struct NotFoundMiddleware<Context: LocalizedRequestContext> {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The error page, rendered once per supported language and reused for every not-found response.
|
||||
private let responses: LocalizedHTMLCollectionResponse
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a not-found middleware.
|
||||
public init() {
|
||||
self.responses = .init(
|
||||
status: .notFound
|
||||
) {
|
||||
ErrorPage(locale: $0)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - RouterMiddleware
|
||||
|
||||
extension NotFoundMiddleware: RouterMiddleware {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// Passes the request down the chain, rendering the error page if it results in a not-found
|
||||
/// response.
|
||||
///
|
||||
/// Any error other than `.notFound` is rethrown unchanged.
|
||||
/// - Parameters:
|
||||
/// - request: the incoming request.
|
||||
/// - context: the context the request is resolved against.
|
||||
/// - next: the next responder in the middleware chain.
|
||||
/// - Returns: the downstream response, or the rendered ``ErrorPage`` with a `404 Not Found` status.
|
||||
/// - Throws: any non-not-found error thrown downstream.
|
||||
public func handle(
|
||||
_ request: Request,
|
||||
context: Context,
|
||||
next: (Request, Context) async throws -> Response
|
||||
) async throws -> Response {
|
||||
do {
|
||||
return try await next(request, context)
|
||||
}
|
||||
catch let error {
|
||||
guard
|
||||
let responseError = error as? any HTTPResponseError,
|
||||
responseError.status == .notFound
|
||||
else {
|
||||
throw error
|
||||
}
|
||||
|
||||
return responses.response(
|
||||
for: context.language
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
import HTTPTypes
|
||||
import Hummingbird
|
||||
|
||||
/// Stamps a set of security-related HTTP headers onto every response.
|
||||
///
|
||||
/// Placed at (or near) the top of the middleware chain, it adds the configured headers to whatever
|
||||
/// response bubbles back up — the rendered landing page, the ``ErrorPage`` produced by
|
||||
/// ``NotFoundMiddleware``, and every static file served by `FileMiddleware` — so the browser applies
|
||||
/// the strict, hardened interpretation of the content instead of its lenient legacy defaults.
|
||||
///
|
||||
/// The headers are precomputed once from the ``Configuration`` at initialization and reused for
|
||||
/// every request, so the per-request cost is a handful of header copies.
|
||||
public struct SecurityHeadersMiddleware<Context: RequestContext> {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The precomputed headers applied to every response.
|
||||
private let fields: HTTPFields
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a security-headers middleware.
|
||||
/// - Parameter configuration: the headers applied to every response. Defaults to a hardened
|
||||
/// baseline suitable for a static site, with `Strict-Transport-Security` left off (see
|
||||
/// ``Configuration``).
|
||||
public init(
|
||||
configuration: Configuration = .init()
|
||||
) {
|
||||
self.fields = configuration.fields
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - RouterMiddleware
|
||||
|
||||
extension SecurityHeadersMiddleware: RouterMiddleware {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
/// Passes the request down the chain and stamps the configured security headers onto the
|
||||
/// response on the way back up.
|
||||
///
|
||||
/// Existing values for the same header names are replaced so downstream middleware cannot leave
|
||||
/// a weaker policy in place.
|
||||
/// - Parameters:
|
||||
/// - request: the incoming request.
|
||||
/// - context: the context the request is resolved against.
|
||||
/// - next: the next responder in the middleware chain.
|
||||
/// - Returns: the downstream response with the security headers applied.
|
||||
/// - Throws: any error thrown downstream.
|
||||
public func handle(
|
||||
_ request: Request,
|
||||
context: Context,
|
||||
next: (Request, Context) async throws -> Response
|
||||
) async throws -> Response {
|
||||
var response = try await next(request, context)
|
||||
|
||||
for field in fields {
|
||||
response.headers[field.name] = field.value
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private extension SecurityHeadersMiddleware.Configuration {
|
||||
|
||||
// MARK: Computed
|
||||
|
||||
/// The configuration expressed as the headers to apply, omitting any whose value is `nil`.
|
||||
var fields: HTTPFields {
|
||||
var fields = HTTPFields()
|
||||
|
||||
fields[.contentSecurityPolicy] = contentSecurityPolicy
|
||||
fields[.xContentTypeOptions] = contentTypeOptions
|
||||
fields[.frameOptions] = frameOptions
|
||||
fields[.referrerPolicy] = referrerPolicy
|
||||
fields[.permissionsPolicy] = permissionsPolicy
|
||||
fields[.strictTransportSecurity] = strictTransportSecurity
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
extension SecurityHeadersMiddleware {
|
||||
/// The set of security headers a ``SecurityHeadersMiddleware`` applies.
|
||||
///
|
||||
/// Each property maps to a single response header. A `nil` value omits that header entirely,
|
||||
/// which is how `Strict-Transport-Security` stays disabled by default: it is only safe to send
|
||||
/// over HTTPS and is "sticky" in browsers, so it must stay off in plain-HTTP development and be
|
||||
/// switched on (via configuration) only in TLS-terminated production.
|
||||
public struct Configuration: Sendable {
|
||||
|
||||
// MARK: Properties
|
||||
|
||||
/// The `Content-Security-Policy` value (controls which sources the browser will load).
|
||||
public let contentSecurityPolicy: String?
|
||||
/// The `X-Content-Type-Options` value (disables MIME sniffing when set to `nosniff`).
|
||||
public let contentTypeOptions: String?
|
||||
/// The `X-Frame-Options` value (controls whether the page may be framed).
|
||||
public let frameOptions: String?
|
||||
/// The `Referrer-Policy` value (controls how much referrer information is shared).
|
||||
public let referrerPolicy: String?
|
||||
/// The `Permissions-Policy` value (gates access to powerful browser features).
|
||||
public let permissionsPolicy: String?
|
||||
/// The `Strict-Transport-Security` value, or `nil` to omit the header (the default).
|
||||
public let strictTransportSecurity: String?
|
||||
|
||||
// MARK: Initializers
|
||||
|
||||
/// Creates a security-headers configuration.
|
||||
///
|
||||
/// Every parameter defaults to the hardened baseline defined in `String.Security`, except
|
||||
/// `strictTransportSecurity`, which defaults to `nil` (omitted). Pass `nil` for any header
|
||||
/// to drop it from the response.
|
||||
/// - Parameters:
|
||||
/// - contentSecurityPolicy: the `Content-Security-Policy` value.
|
||||
/// - contentTypeOptions: the `X-Content-Type-Options` value.
|
||||
/// - frameOptions: the `X-Frame-Options` value.
|
||||
/// - referrerPolicy: the `Referrer-Policy` value.
|
||||
/// - permissionsPolicy: the `Permissions-Policy` value.
|
||||
/// - strictTransportSecurity: the `Strict-Transport-Security` value, or `nil` to omit it.
|
||||
public init(
|
||||
contentSecurityPolicy: String? = String.Security.contentSecurityPolicy,
|
||||
contentTypeOptions: String? = String.Security.contentTypeOptions,
|
||||
frameOptions: String? = String.Security.frameOptions,
|
||||
referrerPolicy: String? = String.Security.referrerPolicy,
|
||||
permissionsPolicy: String? = String.Security.permissionsPolicy,
|
||||
strictTransportSecurity: String? = nil
|
||||
) {
|
||||
self.contentSecurityPolicy = contentSecurityPolicy
|
||||
self.contentTypeOptions = contentTypeOptions
|
||||
self.frameOptions = frameOptions
|
||||
self.referrerPolicy = referrerPolicy
|
||||
self.permissionsPolicy = permissionsPolicy
|
||||
self.strictTransportSecurity = strictTransportSecurity
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user