Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions next.config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { withPayload } from "@payloadcms/next/withPayload";
import type { NextConfig } from "next";
import { securityHeaders } from "./src/lib/security/headers";

const storageEndpoint = process.env.S3_ENDPOINT;

const nextConfig: NextConfig = {
cacheComponents: true,
poweredByHeader: false,
headers: async () => securityHeaders,
images: {
remotePatterns: storageEndpoint ? [new URL(`${storageEndpoint}/**`)] : [],
},
Expand Down
8 changes: 6 additions & 2 deletions src/app/(frontend)/music/_components/Bandcamp.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import { IFrameProps } from "@/utils/types";
import { safeEmbedSrc, safeHttpsUrl } from "@/utils/safeUrl";

export default function Bandcamp({ src, href, title }: IFrameProps) {
const safeSrc = safeEmbedSrc(src, "bandcamp");
if (!safeSrc) return null;

return (
<iframe
src={src}
src={safeSrc}
seamless
width="1000"
height="120"
className="w-full h-full rounded-lg"
title={`Bandcamp player for ${title}`}
>
<a href={href}>{title}</a>
<a href={safeHttpsUrl(href)}>{title}</a>
</iframe>
);
}
6 changes: 5 additions & 1 deletion src/app/(frontend)/music/_components/Spotify.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { IFrameProps } from "@/utils/types";
import { safeEmbedSrc } from "@/utils/safeUrl";

export default function Spotify({ src, title }: IFrameProps) {
const safeSrc = safeEmbedSrc(src, "spotify");
if (!safeSrc) return null;

return (
<div className="aspect-video">
<iframe
src={src}
src={safeSrc}
title={title}
width="1000"
height="352"
Expand Down
6 changes: 5 additions & 1 deletion src/app/(frontend)/music/_components/Youtube.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { IFrameProps } from "@/utils/types";
import { safeEmbedSrc } from "@/utils/safeUrl";

export default function Youtube({ src, title }: IFrameProps) {
const safeSrc = safeEmbedSrc(src, "youtube");
if (!safeSrc) return null;

return (
<iframe
src={src}
src={safeSrc}
title={title}
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowFullScreen
Expand Down
5 changes: 4 additions & 1 deletion src/app/(frontend)/tour/_components/TourDate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,17 @@ import { TourDateType } from "@/utils/types";
import { useLanguage } from "@/context/LanguageContext";
import Button from "@/components/ui/Button";
import clsx from "clsx";
import { safeHttpsUrl } from "@/utils/safeUrl";

interface TourDateProps {
tourDate: TourDateType;
inPast: boolean;
}

export default function TourDate({ tourDate, inPast }: TourDateProps) {
const { eventDate, venue, location, locationUrl, ticketUrl } = tourDate;
const { eventDate, venue, location } = tourDate;
const locationUrl = safeHttpsUrl(tourDate.locationUrl);
const ticketUrl = safeHttpsUrl(tourDate.ticketUrl);
const { isFrench } = useLanguage();
const unavailable = isFrench ? "Indisponible" : "Unavailable";

Expand Down
22 changes: 3 additions & 19 deletions src/lib/payload/validators.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,14 @@
import type { TextFieldSingleValidation } from "payload";

const httpsUrl = (value: string): URL | null => {
try {
const url = new URL(value);
return url.protocol === "https:" ? url : null;
} catch {
return null;
}
};
import { embedHosts, parseHttpsUrl, type EmbedType } from "@/utils/safeUrl";

export const optionalHttpsUrl: TextFieldSingleValidation = (value) => {
if (!value) return true;
return httpsUrl(value) ? true : "Must be a link starting with https://";
return parseHttpsUrl(value) ? true : "Must be a link starting with https://";
};

const embedHosts = {
youtube: ["www.youtube.com", "www.youtube-nocookie.com"],
spotify: ["open.spotify.com"],
bandcamp: ["bandcamp.com"],
} as const;

type EmbedType = keyof typeof embedHosts;

export const embedSrc: TextFieldSingleValidation = (value, { siblingData }) => {
if (!value) return "Required";
const url = httpsUrl(value);
const url = parseHttpsUrl(value);
if (!url) return "Must be a link starting with https://";
const type = (siblingData as { type?: EmbedType }).type;
const hosts: readonly string[] = type
Expand Down
86 changes: 86 additions & 0 deletions src/lib/security/headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import type { NextConfig } from "next";
import { embedHosts } from "../../utils/safeUrl";

type Directives = Record<string, string[]>;
type HeaderRule = Awaited<
ReturnType<NonNullable<NextConfig["headers"]>>
>[number];

const CSP_HEADER = "Content-Security-Policy";

const storage = process.env.S3_ENDPOINT
? [new URL(process.env.S3_ENDPOINT).origin]
: [];
const isDev = process.env.NODE_ENV !== "production";
const embedOrigins = Object.values(embedHosts)
.flat()
.map((host) => `https://${host}`);

const baseDirectives: Directives = {
"default-src": ["'self'"],
// Next.js inlines its bootstrap scripts, and static pages can't carry a nonce.
"script-src": [
"'self'",
"'unsafe-inline'",
...(isDev ? ["'unsafe-eval'"] : []),
],
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", "data:", "blob:", ...storage],
"font-src": ["'self'", "data:"],
"media-src": ["'self'", ...storage],
"connect-src": ["'self'"],
"frame-src": embedOrigins,
"object-src": ["'none'"],
"base-uri": ["'self'"],
"form-action": ["'self'"],
"frame-ancestors": ["'none'"],
};

/** Extra allowances for one top-level path; every other path gets the base policy. */
const routePolicies: { path: string; extra: Directives }[] = [
{
path: "admin",
extra: {
"img-src": ["https://www.gravatar.com"],
"connect-src": storage,
"frame-src": ["'self'"],
},
},
];

const buildPolicy = (extra: Directives = {}): string =>
Object.entries(baseDirectives)
.map(([name, values]) =>
[name, ...values, ...(extra[name] ?? [])].join(" ")
)
.join("; ");

const cspHeader = (extra?: Directives) => ({
key: CSP_HEADER,
value: buildPolicy(extra),
});

const scopedPaths = routePolicies.map(({ path }) => `${path}(?:/|$)`);

export const securityHeaders: HeaderRule[] = [
{
source: "/:path*",
headers: [
{ key: "X-Frame-Options", value: "DENY" },
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{
key: "Permissions-Policy",
value:
"camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()",
},
],
},
...routePolicies.map(({ path, extra }) => ({
source: `/${path}/:path*`,
headers: [cspHeader(extra)],
})),
{
source: `/:path((?!${scopedPaths.join("|")}).*)`,
headers: [cspHeader()],
},
];
28 changes: 28 additions & 0 deletions src/utils/safeUrl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export const embedHosts = {
youtube: ["www.youtube.com", "www.youtube-nocookie.com"],
spotify: ["open.spotify.com"],
bandcamp: ["bandcamp.com"],
} as const;

export type EmbedType = keyof typeof embedHosts;

export const parseHttpsUrl = (value: string): URL | null => {
try {
const url = new URL(value);
return url.protocol === "https:" ? url : null;
} catch {
return null;
}
};

export const safeHttpsUrl = (value?: string): string | undefined =>
value && parseHttpsUrl(value) ? value : undefined;

export const safeEmbedSrc = (
value: string | undefined,
type: EmbedType
): string | undefined => {
const url = value ? parseHttpsUrl(value) : null;
const hosts: readonly string[] = embedHosts[type];
return url && hosts.includes(url.hostname) ? value : undefined;
};
Loading