@stacksjs/server 0.75.695 → 0.75.701
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/security-headers.d.ts +2 -3
- package/dist/security-headers.js +1 -1
- package/package.json +13 -13
|
@@ -38,9 +38,8 @@ export declare function isEmbeddablePath(pathname: string, rules: EmbeddableRule
|
|
|
38
38
|
* cannot be mutated, so it is rebuilt and returned - the same shape
|
|
39
39
|
* `stacks-router.ts` already uses for this case.
|
|
40
40
|
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
* specific.
|
|
41
|
+
* Existing security headers take precedence. A generated document nonce
|
|
42
|
+
* makes the HTML response private and uncacheable.
|
|
44
43
|
*/
|
|
45
44
|
export declare function applyViewSecurityHeaders(req: Request, response: Response, rules: EmbeddableRules | ViewSecurityRules): Response | undefined;
|
|
46
45
|
/** Test helper - reset the cached env-derived flag. */
|
package/dist/security-headers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";const HSTS_DEFAULT="max-age=31536000; includeSubDomains";const PERMISSIONS_POLICY_DEFAULT={"browsing-topics":"()",usb:"()",serial:"()",hid:"()",bluetooth:"()",midi:"()"};export function servesHttpsPublicly(appUrl){if(!appUrl)return false;let url;try{url=new URL(appUrl.includes("://")?appUrl:`https://${appUrl}`)}catch{return false}if(url.protocol!=="https:")return false;const host=url.hostname.replace(/^\[|\]$/g,"");return!(host==="localhost"||host.endsWith(".localhost")||host.endsWith(".test")||host==="::1"||/^127\.\d+\.\d+\.\d+$/.test(host))}export function resolveViewSecurityRules(security,appUrl){const rules=resolveEmbeddableRules(security?.embeddable);const hsts=security?.hsts;rules.hsts=hsts===false?null:typeof hsts==="string"?hsts:servesHttpsPublicly(appUrl)?HSTS_DEFAULT:null;const coop=security?.crossOriginOpenerPolicy;rules.crossOriginOpenerPolicy=coop===false?null:coop||"same-origin-allow-popups";const permissions=security?.permissionsPolicy;rules.permissionsPolicy=permissions===false?null:Object.entries({...PERMISSIONS_POLICY_DEFAULT,...permissions}).map(([feature,allow])=>`${feature}=${allow}`).join(", ");const csp=security?.csp;rules.csp=!csp?null:csp===true||csp==="report-only"?{reportOnly:csp==="report-only",directives:{}}:{reportOnly:csp.reportOnly===true,directives:csp.directives??{},reportUri:csp.reportUri};return rules}const PAGE_CSP_DEFAULTS={"default-src":["'self'"],"script-src":["'self'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","blob:","https:"],"font-src":["'self'","data:"],"connect-src":["'self'"],"object-src":["'none'"],"base-uri":["'self'"],"form-action":["'self'"],"frame-ancestors":["'self'"]};export function pageContentSecurityPolicy(directives,nonce,embeddable,reportUri){const merged={...PAGE_CSP_DEFAULTS,...directives};if(embeddable&&!directives["frame-ancestors"])merged["frame-ancestors"]=false;const parts=[];for(const[name,sources]of Object.entries(merged)){if(sources===false)continue;const list=name==="script-src"?[...sources,`'nonce-${nonce}'`]:sources;parts.push(list.length>0?`${name} ${list.join(" ")}`:name)}if(reportUri)parts.push(`report-uri ${reportUri}`);return parts.join("; ")}function newNonce(){return Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64")}function withPageCsp(response,csp,embeddable){const header=csp.reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy";if(!/^text\/html\b/i.test(response.headers.get("Content-Type")??"")||response.headers.has("Content-Security-Policy")||response.headers.has("Content-Security-Policy-Report-Only"))return response;const nonce=newNonce();const rewritten=new HTMLRewriter().on("script",{element(element){element.setAttribute("nonce",nonce)}}).transform(response);const headers=new Headers(rewritten.headers);headers.set(header,pageContentSecurityPolicy(csp.directives,nonce,embeddable,csp.reportUri));headers.delete("Content-Length");return new Response(rewritten.body,{status:response.status,statusText:response.statusText,headers})}let _isDisabledCache;function isDisabled(){if(_isDisabledCache!==undefined)return _isDisabledCache;_isDisabledCache=process.env.STACKS_SECURITY_HEADERS_DISABLE==="true";return _isDisabledCache}export function resolveEmbeddableRules(input){const paths=[];const prefixes=[];for(const raw of input??[]){const entry=String(raw).trim();if(!entry||!entry.startsWith("/"))continue;if(entry.endsWith("/")&&entry.length>1){if(!prefixes.includes(entry))prefixes.push(entry);continue}if(!paths.includes(entry))paths.push(entry)}return{paths,prefixes}}function matchesPrefix(pathname,prefix){return pathname.startsWith(prefix)||pathname===prefix.slice(0,-1)}export function isEmbeddablePath(pathname,rules){if(rules.paths.includes(pathname))return true;return rules.prefixes.some((prefix)=>matchesPrefix(pathname,prefix))}export function applyViewSecurityHeaders(req,response,rules){if(isDisabled())return;const embeddable=isEmbeddablePath(new URL(req.url).pathname,rules);const wanted=[["X-Content-Type-Options","nosniff"],["Referrer-Policy","strict-origin-when-cross-origin"]];if(!embeddable)wanted.push(["X-Frame-Options","SAMEORIGIN"]);const view=rules;if(view.hsts)wanted.push(["Strict-Transport-Security",view.hsts]);if(view.crossOriginOpenerPolicy)wanted.push(["Cross-Origin-Opener-Policy",view.crossOriginOpenerPolicy]);if(view.permissionsPolicy)wanted.push(["Permissions-Policy",view.permissionsPolicy]);const missing=wanted.filter(([name])=>!response.headers.has(name));let secured;if(missing.length>0){try{for(const[name,value]of missing)response.headers.set(name,value)}catch{const headers=new Headers(response.headers);for(const[name,value]of missing)headers.set(name,value);secured=new Response(response.body,{status:response.status,statusText:response.statusText,headers})}}if(!view.csp)return secured;const current=secured??response;const withCsp=withPageCsp(current,view.csp,embeddable);return withCsp===current?secured:withCsp}export function __resetViewSecurityHeadersCache(){_isDisabledCache=undefined}
|
|
1
|
+
import process from"node:process";const HSTS_DEFAULT="max-age=31536000; includeSubDomains";const PERMISSIONS_POLICY_DEFAULT={"browsing-topics":"()",usb:"()",serial:"()",hid:"()",bluetooth:"()",midi:"()"};export function servesHttpsPublicly(appUrl){if(!appUrl)return false;let url;try{url=new URL(appUrl.includes("://")?appUrl:`https://${appUrl}`)}catch{return false}if(url.protocol!=="https:")return false;const host=url.hostname.replace(/^\[|\]$/g,"");return!(host==="localhost"||host.endsWith(".localhost")||host.endsWith(".test")||host==="::1"||/^127\.\d+\.\d+\.\d+$/.test(host))}export function resolveViewSecurityRules(security,appUrl){const rules=resolveEmbeddableRules(security?.embeddable);const hsts=security?.hsts;rules.hsts=hsts===false?null:typeof hsts==="string"?hsts:servesHttpsPublicly(appUrl)?HSTS_DEFAULT:null;const coop=security?.crossOriginOpenerPolicy;rules.crossOriginOpenerPolicy=coop===false?null:coop||"same-origin-allow-popups";const permissions=security?.permissionsPolicy;rules.permissionsPolicy=permissions===false?null:Object.entries({...PERMISSIONS_POLICY_DEFAULT,...permissions}).map(([feature,allow])=>`${feature}=${allow}`).join(", ");const csp=security?.csp;rules.csp=!csp?null:csp===true||csp==="report-only"?{reportOnly:csp==="report-only",directives:{}}:{reportOnly:csp.reportOnly===true,directives:csp.directives??{},reportUri:csp.reportUri};return rules}const PAGE_CSP_DEFAULTS={"default-src":["'self'"],"script-src":["'self'"],"style-src":["'self'","'unsafe-inline'"],"img-src":["'self'","data:","blob:","https:"],"font-src":["'self'","data:"],"connect-src":["'self'"],"object-src":["'none'"],"base-uri":["'self'"],"form-action":["'self'"],"frame-ancestors":["'self'"]};export function pageContentSecurityPolicy(directives,nonce,embeddable,reportUri){const merged={...PAGE_CSP_DEFAULTS,...directives};if(embeddable&&!directives["frame-ancestors"])merged["frame-ancestors"]=false;const parts=[];for(const[name,sources]of Object.entries(merged)){if(sources===false)continue;const list=name==="script-src"?[...sources,`'nonce-${nonce}'`]:sources;parts.push(list.length>0?`${name} ${list.join(" ")}`:name)}if(reportUri)parts.push(`report-uri ${reportUri}`);return parts.join("; ")}function newNonce(){return Buffer.from(crypto.getRandomValues(new Uint8Array(16))).toString("base64")}function withPageCsp(response,csp,embeddable){const header=csp.reportOnly?"Content-Security-Policy-Report-Only":"Content-Security-Policy";if(!/^text\/html\b/i.test(response.headers.get("Content-Type")??"")||response.headers.has("Content-Security-Policy")||response.headers.has("Content-Security-Policy-Report-Only"))return response;const nonce=newNonce();const rewritten=new HTMLRewriter().on("script",{element(element){element.setAttribute("nonce",nonce)}}).transform(response);const headers=new Headers(rewritten.headers);headers.set(header,pageContentSecurityPolicy(csp.directives,nonce,embeddable,csp.reportUri));headers.set("Cache-Control","private, no-store");headers.delete("Content-Length");return new Response(rewritten.body,{status:response.status,statusText:response.statusText,headers})}let _isDisabledCache;function isDisabled(){if(_isDisabledCache!==undefined)return _isDisabledCache;_isDisabledCache=process.env.STACKS_SECURITY_HEADERS_DISABLE==="true";return _isDisabledCache}export function resolveEmbeddableRules(input){const paths=[];const prefixes=[];for(const raw of input??[]){const entry=String(raw).trim();if(!entry||!entry.startsWith("/"))continue;if(entry.endsWith("/")&&entry.length>1){if(!prefixes.includes(entry))prefixes.push(entry);continue}if(!paths.includes(entry))paths.push(entry)}return{paths,prefixes}}function matchesPrefix(pathname,prefix){return pathname.startsWith(prefix)||pathname===prefix.slice(0,-1)}export function isEmbeddablePath(pathname,rules){if(rules.paths.includes(pathname))return true;return rules.prefixes.some((prefix)=>matchesPrefix(pathname,prefix))}export function applyViewSecurityHeaders(req,response,rules){if(isDisabled())return;const embeddable=isEmbeddablePath(new URL(req.url).pathname,rules);const wanted=[["X-Content-Type-Options","nosniff"],["Referrer-Policy","strict-origin-when-cross-origin"]];if(!embeddable)wanted.push(["X-Frame-Options","SAMEORIGIN"]);const view=rules;if(view.hsts)wanted.push(["Strict-Transport-Security",view.hsts]);if(view.crossOriginOpenerPolicy)wanted.push(["Cross-Origin-Opener-Policy",view.crossOriginOpenerPolicy]);if(view.permissionsPolicy)wanted.push(["Permissions-Policy",view.permissionsPolicy]);const missing=wanted.filter(([name])=>!response.headers.has(name));let secured;if(missing.length>0){try{for(const[name,value]of missing)response.headers.set(name,value)}catch{const headers=new Headers(response.headers);for(const[name,value]of missing)headers.set(name,value);secured=new Response(response.body,{status:response.status,statusText:response.statusText,headers})}}if(!view.csp)return secured;const current=secured??response;const withCsp=withPageCsp(current,view.csp,embeddable);return withCsp===current?secured:withCsp}export function __resetViewSecurityHeadersCache(){_isDisabledCache=undefined}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/server",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.701",
|
|
6
6
|
"description": "Local development and production-ready.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -58,22 +58,22 @@
|
|
|
58
58
|
"prepublishOnly": "bun run build"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@stacksjs/auth": "0.75.
|
|
61
|
+
"@stacksjs/auth": "0.75.701",
|
|
62
62
|
"@stacksjs/bun-router": "^0.1.24",
|
|
63
|
-
"@stacksjs/config": "0.75.
|
|
64
|
-
"@stacksjs/events": "0.75.
|
|
65
|
-
"@stacksjs/i18n": "0.75.
|
|
66
|
-
"@stacksjs/logging": "0.75.
|
|
67
|
-
"@stacksjs/orm": "0.75.
|
|
68
|
-
"@stacksjs/path": "0.75.
|
|
69
|
-
"@stacksjs/payments": "0.75.
|
|
70
|
-
"@stacksjs/router": "0.75.
|
|
71
|
-
"@stacksjs/storage": "0.75.
|
|
72
|
-
"@stacksjs/stx": "^0.2.
|
|
63
|
+
"@stacksjs/config": "0.75.701",
|
|
64
|
+
"@stacksjs/events": "0.75.701",
|
|
65
|
+
"@stacksjs/i18n": "0.75.701",
|
|
66
|
+
"@stacksjs/logging": "0.75.701",
|
|
67
|
+
"@stacksjs/orm": "0.75.701",
|
|
68
|
+
"@stacksjs/path": "0.75.701",
|
|
69
|
+
"@stacksjs/payments": "0.75.701",
|
|
70
|
+
"@stacksjs/router": "0.75.701",
|
|
71
|
+
"@stacksjs/storage": "0.75.701",
|
|
72
|
+
"@stacksjs/stx": "^0.2.948",
|
|
73
73
|
"bun-plugin-auto-imports": "^0.4.4"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
|
-
"@stacksjs/validation": "0.75.
|
|
76
|
+
"@stacksjs/validation": "0.75.701",
|
|
77
77
|
"better-dx": "^0.2.39"
|
|
78
78
|
}
|
|
79
79
|
}
|