This commit is contained in:
badblocks 2026-07-10 00:21:45 -07:00
parent 6e7977997e
commit 2155d410a8
Signed by: badblocks
SSH key fingerprint: SHA256:hEcM6BP4hKm9F7WsomNuXSBpPn2BSDnFzPSl3y1NerQ
21 changed files with 280 additions and 197 deletions

View file

@ -1,7 +1,29 @@
import { defineMiddleware } from "astro:middleware";
import { getActionContext } from "astro:actions";
import type { APIContext, MiddlewareNext } from "astro";
export const onRequest = defineMiddleware(async (context, next) => {
// htmz -> frame-ancestors 'self' & X-Frame-Options SAMEORIGIN
// astro -> 'unsafe-inline'
const SECURITY_HEADERS: Record<string, string> = {
"Content-Security-Policy": [
"default-src 'self'",
"script-src 'self' 'unsafe-inline'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https://badblocks.goatcounter.com",
"font-src 'self'",
"connect-src 'self' https://badblocks.goatcounter.com https://api.iconify.design",
"object-src 'none'",
"frame-ancestors 'self'",
"base-uri 'self'",
"form-action 'self'",
].join("; "),
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "SAMEORIGIN",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=()",
};
async function handle(context: APIContext, next: MiddlewareNext) {
if (context.isPrerendered) return next();
const { action, setActionResult, serializeActionResult } =
@ -10,10 +32,11 @@ export const onRequest = defineMiddleware(async (context, next) => {
const currentAction = await context.session?.get("currentAction");
if (currentAction) {
const { actionName, actionResult } = JSON.parse(currentAction);
setActionResult(actionName, actionResult);
context.session?.delete("currentAction");
try {
const { actionName, actionResult } = JSON.parse(currentAction);
setActionResult(actionName, actionResult);
} catch {}
return next();
}
@ -39,13 +62,14 @@ export const onRequest = defineMiddleware(async (context, next) => {
context.session?.set("contactFormDraft", draft);
const referer = context.request.headers.get("Referer");
if (!referer) {
throw new Error(
"Internal: Referer unexpectedly missing from Action POST request.",
);
}
return context.redirect(referer);
let redirectPath = context.originPathname;
try {
const referer = new URL(context.request.headers.get("Referer") ?? "");
if (referer.origin === context.url.origin) {
redirectPath = referer.pathname;
}
} catch {}
return context.redirect(redirectPath);
}
context.session?.delete("contactFormDraft");
@ -53,4 +77,12 @@ export const onRequest = defineMiddleware(async (context, next) => {
}
return next();
}
export const onRequest = defineMiddleware(async (context, next) => {
const response = await handle(context, next);
for (const [header, value] of Object.entries(SECURITY_HEADERS)) {
response.headers.set(header, value);
}
return response;
});