Repository navigation
Expand file tree
/
Copy pathnext.config.ts
More file actions
272 lines (254 loc) · 10.1 KB
/
Copy pathnext.config.ts
File metadata and controls
272 lines (254 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import path from "node:path";
import type { NextConfig } from "next";
import createNextIntlPlugin from "next-intl/plugin";
import { ensureBuildVersionFiles } from "./scripts/build-version";
const IS_MOCK = process.env.PETDEX_MOCK === "1";
const IS_MOCK_AUTH = IS_MOCK || process.env.PETDEX_MOCK_AUTH === "1";
const CANONICAL_R2_PUBLIC_HOST = "assets.petdex.dev";
const WORKERS_DEV_R2_PUBLIC_HOST = "petdex-assets.raillyhugo.workers.dev";
const LEGACY_R2_PUBLIC_HOST = "pub-94495283df974cfea5e98d6a9e3fa462.r2.dev";
ensureBuildVersionFiles();
function r2PublicHost(): string {
if (!process.env.R2_PUBLIC_BASE) return CANONICAL_R2_PUBLIC_HOST;
try {
const host = new URL(process.env.R2_PUBLIC_BASE).hostname;
if (host === WORKERS_DEV_R2_PUBLIC_HOST || host === LEGACY_R2_PUBLIC_HOST) {
return CANONICAL_R2_PUBLIC_HOST;
}
return host;
} catch {
return CANONICAL_R2_PUBLIC_HOST;
}
}
function r2PublicSource(): string {
if (!process.env.R2_PUBLIC_BASE) return `https://${CANONICAL_R2_PUBLIC_HOST}`;
try {
const parsed = new URL(process.env.R2_PUBLIC_BASE);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
return `https://${CANONICAL_R2_PUBLIC_HOST}`;
}
if (
parsed.hostname === WORKERS_DEV_R2_PUBLIC_HOST ||
parsed.hostname === LEGACY_R2_PUBLIC_HOST
) {
return `https://${CANONICAL_R2_PUBLIC_HOST}`;
}
return parsed.origin;
} catch {
return `https://${CANONICAL_R2_PUBLIC_HOST}`;
}
}
const r2PublicHostValue = r2PublicHost();
// assets.petdex.dev is the only asset host we serve from. The legacy
// pub-*.r2.dev and *.workers.dev hosts are dead; stored URLs pointing at
// them are rewritten to the canonical host at runtime via
// toCurrentR2PublicUrl, so they never need to be allowed here.
const r2PublicSources = Array.from(
new Set([`https://${CANONICAL_R2_PUBLIC_HOST}`, r2PublicSource()]),
).join(" ");
// Content-Security-Policy. Blocks inline <script> sources we didn't ship,
// caps img / connect / frame ancestors. The `unsafe-inline` allowance for
// styles is required by Next/Tailwind during hydration; for scripts we
// keep 'unsafe-inline' as well because Next embeds RSC payloads inline,
// but with our same-origin CSRF guard + JSON-LD escape this is acceptable.
//
// Hosts allowed:
// - self for everything we render
// - clerk.petdex.dev + *.clerk.com / *.clerk.accounts.dev for
// the Clerk client SDK
// - vercel-scripts / vitals for Vercel analytics
// - R2 public bucket + Clerk image hosts + social avatar hosts for sprites
// and avatars
const cspDirectives = [
"default-src 'self'",
"base-uri 'self'",
"object-src 'none'",
"form-action 'self'",
"frame-ancestors 'none'",
// Clerk renders the sign-up CAPTCHA inside an iframe served from
// challenges.cloudflare.com (Turnstile). Without it on frame-src and
// its bootstrap script on script-src, the CAPTCHA fails to load and
// the user can't create an account.
"frame-src 'self' https://challenges.cloudflare.com https://*.clerk.com https://*.clerk.accounts.dev https://accounts.petdex.dev https://clerk.petdex.dev",
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://clerk.petdex.dev https://accounts.petdex.dev https://*.clerk.com https://*.clerk.accounts.dev https://challenges.cloudflare.com https://va.vercel-scripts.com https://vercel.live",
"style-src 'self' 'unsafe-inline'",
`img-src 'self' data: blob: ${r2PublicSources} https://img.clerk.com https://images.clerk.dev https://avatars.githubusercontent.com https://pbs.twimg.com https://storage.googleapis.com`,
`media-src 'self' ${r2PublicSources}`,
"font-src 'self' data:",
// R2 reads via pub-*.r2.dev, R2 PUT uploads via the account-specific
// S3 endpoint (*.r2.cloudflarestorage.com). Both must be on the
// connect-src allowlist or browser fetch / XHR fail with a generic
// network error (root cause of issues #22-#80+).
`connect-src 'self' https://clerk.petdex.dev https://accounts.petdex.dev https://*.clerk.com https://*.clerk.accounts.dev https://api.clerk.com https://api.github.com https://challenges.cloudflare.com ${r2PublicSources} https://*.r2.cloudflarestorage.com https://va.vercel-scripts.com https://vitals.vercel-insights.com`,
"worker-src 'self' blob:",
"manifest-src 'self'",
"upgrade-insecure-requests",
].join("; ");
const securityHeaders = [
// 2 years HSTS + subdomains. preload-ready when we want to submit to
// hstspreload.org.
{
key: "Strict-Transport-Security",
value: "max-age=63072000; includeSubDomains",
},
// Block clickjacking. Modern frame-ancestors lives in CSP but we keep
// the legacy header for older browsers.
{ key: "X-Frame-Options", value: "DENY" },
// Stop MIME sniffing — a pet.json that's secretly HTML won't be
// executed as HTML by the browser.
{ key: "X-Content-Type-Options", value: "nosniff" },
// Conservative referrer to avoid leaking pet detail URLs to ad nets.
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
// Lock down powerful APIs. We don't use any of these.
{
key: "Permissions-Policy",
value:
"camera=(), microphone=(), geolocation=(), interest-cohort=(), payment=(), usb=(), magnetometer=(), gyroscope=(), accelerometer=()",
},
// CSP — see directives above.
{ key: "Content-Security-Policy", value: cspDirectives },
// Cross-origin protections.
{ key: "Cross-Origin-Opener-Policy", value: "same-origin" },
];
const versionJsonHeaders = [
{
key: "Cache-Control",
value: "public, max-age=0, s-maxage=600, must-revalidate",
},
];
const publicHtmlCacheHeaders = [
{
key: "Cloudflare-CDN-Cache-Control",
value:
"public, max-age=300, stale-while-revalidate=86400, stale-if-error=86400",
},
];
const publicStaticHtmlPaths = [
"/about",
"/brand",
"/built-with",
"/collections",
"/community",
"/create",
"/docs",
"/download",
"/leaderboard",
"/legal/takedown",
"/legal/telemetry",
"/requests",
];
const publicHtmlCacheSources = [
"/",
"/:locale(en|es|zh)",
...publicStaticHtmlPaths.flatMap((source) => [
source,
`/:locale(en|es|zh)${source}`,
]),
"/pets/:slug",
"/:locale(en|es|zh)/pets/:slug",
"/collections/:slug",
"/:locale(en|es|zh)/collections/:slug",
"/kind/:kind",
"/:locale(en|es|zh)/kind/:kind",
"/vibe/:vibe",
"/:locale(en|es|zh)/vibe/:vibe",
];
const mockRoot = path.resolve(__dirname, "src/lib/mock");
const nextConfig: NextConfig = {
experimental: {
// TypeScript 7 dropped the compiler API Next reads for its dev-time
// type checking, so `bun dev` crashed on boot after the 6-to-7 bump
// in #580. This is the escape hatch Next's own error names: it drives
// `tsc` as a CLI instead of importing its API.
useTypeScriptCli: true,
},
// Hide the framework banner on every response.
poweredByHeader: false,
images: {
remotePatterns: [
{ protocol: "https", hostname: CANONICAL_R2_PUBLIC_HOST },
{ protocol: "https", hostname: r2PublicHostValue },
{ protocol: "https", hostname: "img.clerk.com" },
{ protocol: "https", hostname: "images.clerk.dev" },
{ protocol: "https", hostname: "avatars.githubusercontent.com" },
{ protocol: "https", hostname: "pbs.twimg.com" },
{ protocol: "https", hostname: "storage.googleapis.com" },
],
},
// Server-only modules that don't survive Turbopack/webpack bundling:
// - @electric-sql/pglite (mock mode) — native wasm + workers
// - ali-oss — uses urllib's dynamic require('proxy-agent') for an
// optional dependency that the bundler can't resolve and treats
// as fatal. Marking ali-oss external lets the server runtime do
// the require() lazily, where the missing optional is harmless.
serverExternalPackages: [
"ali-oss",
...(IS_MOCK ? ["@electric-sql/pglite"] : []),
],
async headers() {
return [
{
source: "/version.json",
headers: versionJsonHeaders,
},
// The client router fetches these same URLs with an `RSC: 1` header
// and gets the React flight payload back. Cloudflare keys the cache on
// the URL alone and ignores `Vary: rsc`, so an edge-cacheable flight
// response gets served to the next browser as the page body. Only the
// HTML document may carry the CDN cache header.
...publicHtmlCacheSources.map((source) => ({
source,
missing: [{ type: "header" as const, key: "rsc" }],
headers: publicHtmlCacheHeaders,
})),
{
source: "/:path*",
headers: securityHeaders,
},
];
},
async redirects() {
return [
{
source: "/:path*",
has: [{ type: "host", value: "petdex.crafter.run" }],
destination: "https://petdex.dev/:path*",
permanent: true,
},
{
source: "/:path*",
has: [{ type: "host", value: "www.petdex.crafter.run" }],
destination: "https://petdex.dev/:path*",
permanent: true,
},
];
},
// In mock auth mode, redirect every Clerk import to in-process mocks
// so contributors can boot without a Clerk backend secret. We set both
// webpack and turbopack aliases since `next dev` defaults to turbopack
// on recent versions.
...(IS_MOCK_AUTH
? {
turbopack: {
// Turbopack expects relative paths (with leading "./") rooted at
// the project. Absolute paths get re-resolved as file paths
// under cwd and 404. See nextjs/issues/turbopack-aliases.
resolveAlias: {
"@clerk/nextjs/server": "./src/lib/mock/clerk-server.ts",
"@clerk/nextjs": "./src/lib/mock/clerk-client.tsx",
},
},
webpack: (config: { resolve?: { alias?: Record<string, string> } }) => {
config.resolve = config.resolve ?? {};
config.resolve.alias = {
...(config.resolve.alias ?? {}),
"@clerk/nextjs/server$": path.join(mockRoot, "clerk-server.ts"),
"@clerk/nextjs$": path.join(mockRoot, "clerk-client.tsx"),
};
return config;
},
}
: {}),
};
const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");
export default withNextIntl(nextConfig);