Repository navigation
Expand file tree
/
Copy pathnext.config.ts
More file actions
385 lines (376 loc) · 21.2 KB
/
Copy pathnext.config.ts
File metadata and controls
385 lines (376 loc) · 21.2 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import type { NextConfig } from 'next'
import { writeFileSync } from 'fs'
import withPWAInit from "@ducanh2912/next-pwa"
const withPWA = withPWAInit({
dest: "public",
// * NOT next-pwa's own registration: components/ServiceWorkerRegister.tsx calls
// * window.workbox.register() in a top-level window only, so the /demo that
// * pulse.ciphera.net's home page frames never installs the dashboard's worker.
register: false,
disable: process.env.NODE_ENV === "development",
// * The tracker must NOT be in the SW precache.
// * Workbox aborts the ENTIRE install when any one precache fetch fails, and
// * script.js is exactly the kind of URL content blockers kill — one blocked
// * fetch turned into a dead service worker for that visitor (observed
// * 01-09-2026, Vemetric comparison audit §10). The tracker is for CUSTOMER
// * sites anyway; the dashboard shell never imports it.
// *
// * 🔴 EVERY ENTRY NEEDS ITS LEADING `!`. next-pwa appends these to its own
// * fast-glob list after `**/*`, so a bare "script.js" is one more POSITIVE
// * pattern — it matched a file `**/*` had already matched, and excluded
// * nothing. Measured 27-09-2026: all three files were still selected for the
// * precache until the `!` was added. __tests__/pwa-precache.test.ts runs the
// * real glob over these patterns so a bare entry fails a test.
// *
// * workers/**: the analytics-import worker (scripts/build-worker.mjs). It is
// * fetched by path when an import starts, and a precached copy would outlive
// * the deploy that replaced it.
publicExcludes: ["!script.js", "!workers/**"],
// * 🔴 ...AND out of the RUNTIME cache. next-pwa's default runtime caching
// * answers every `*.js` request StaleWhileRevalidate ("static-js-assets", 24 h),
// * and a dedicated worker's script fetch goes through the page's service
// * worker — so without this rule the first import after a deploy would run the
// * PREVIOUS build's worker, served from cache, while the cache refreshed behind
// * it. Custom rules are registered ahead of the defaults, and the first match
// * wins. `extendDefaultRuntimeCaching` keeps every default rule as it was.
extendDefaultRuntimeCaching: true,
workboxOptions: {
runtimeCaching: [
{
urlPattern: /\/workers\/import\.js$/i,
handler: "NetworkOnly",
options: { cacheName: "import-worker" },
},
// * End-to-end encrypted team names (design §6.5, review L3): a person's sealed key and a
// * team's directory are ciphertext, but nothing of the feature may sit in Cache Storage, and a
// * stale directory must never feed the reconcile. The default `cross-origin` rule would keep
// * them NetworkFirst for an hour. The same holds for the team-emails directory (design §16.3).
// * 🔴 A FUNCTION, NOT A REGEXP: Workbox matches a RegExp against
// * a cross-origin URL only when the match starts at index 0 of the full URL, so a path pattern
// * would match nothing on the API's origin, silently. It is serialised into the worker, so it
// * may not refer to anything outside itself.
{
urlPattern: ({ url }: { url: URL }) =>
/^\/api\/v1\/(?:me\/team-key|organizations\/[^/]+\/team-(?:names|emails))$/.test(url.pathname),
handler: "NetworkOnly",
options: { cacheName: "team-names" },
},
],
},
})
// * ═══ /_next/static/* IS SERVED FROM ITS OWN CDN ZONE ═══
// *
// * WHY: pulse.ciphera.net moves to Bunny Magic Containers, and an MC rollout is
// * PROGRESSIVE — ~10-15 minutes across its region set. Next.js HTML references
// * content-hashed chunks, so a mixed-version fleet 404s in BOTH directions: old HTML
// * asking an already-updated region for a chunk it no longer has, AND new HTML asking
// * a not-yet-updated one. Simply not purging static only ever covered the first case.
// * At 1489 real req/h that is hundreds of sessions per deploy — which is why this is a
// * PREREQUISITE for the MC migration, not an optimisation (frontends plan §3.5).
// *
// * Chunks now come from a storage-backed zone that KEEPS EVERY BUILD'S OUTPUT, so the
// * URL a given HTML references is always resolvable whichever app version answers.
// *
// * 🔴 The upload in .woodpecker/deploy.yml runs BEFORE the rollout and FAILS the deploy
// * if it cannot complete. That ordering is load-bearing: with a prefix set, an image
// * whose assets were never uploaded serves a page where EVERY chunk 404s.
// *
// * ⚠️ DEFAULTS TO EMPTY ON PURPOSE. An unset build arg degrades to serving assets from
// * the app itself — the site works, it just loses the decoupling. The alternative
// * (baking the production URL in as the default, which is what `help` did) would make a
// * STAGING build silently serve PRODUCTION chunks, i.e. a different build's JavaScript.
// * Safe degradation beats a wrong default. The pipeline asserts the prefix actually shipped, so
// * "silently off" is caught rather than trusted: production against the live HTML after deploy,
// * staging against the built image before the rollout (.woodpecker/deploy.yml).
const ASSET_PREFIX = process.env['NEXT_PUBLIC_ASSET_PREFIX'] ?? ''
// * ═══ SERVER ACTIONS MUST ACCEPT THIS APP'S OWN PUBLIC HOST ═══
// *
// * Next answers a Server Action only if the request's `Origin` host equals the host the pod was
// * asked for (x-forwarded-host, else Host), or is listed in experimental.serverActions.allowedOrigins.
// * Otherwise it logs "does not match origin header ... Aborting the action." and answers 500
// * "Invalid Server Actions request." This app's five actions (app/actions/auth.ts) carry the
// * sign-in code exchange and the session read that every page load makes, so a refusal here is a
// * dashboard that cannot sign in and cannot prime its Bearer.
// *
// * Behind a reverse proxy that presents the ORIGIN'S OWN NAME as Host (the staging app sits behind
// * one), the browser's Origin is the public host and the pod sees another, so the two never match.
// * The public host is what is registered as the OAuth redirect_uri and baked in as the app URL,
// * so it is read from the one place that already says so, NEXT_PUBLIC_APP_URL, and no new setting
// * exists to drift from it.
// *
// * In production this lists the production host and is a NO-OP: the Host the edge forwards already
// * equals it. A standalone build embeds the resolved config in server.js, so the value is fixed at
// * build time. Unset or unparsable gives [] (Next's own default), never a guess.
// *
// * lib/__tests__/server-actions-origins.test.ts holds the derivation.
const APP_HOST = (() => {
try {
return new URL(process.env['NEXT_PUBLIC_APP_URL'] ?? '').host
} catch {
return ''
}
})()
// * The zone that serves those chunks. Kept as a constant because it appears in FOUR CSP
// * directives and a typo in any one of them is a blank page, not an error.
// * ⚠️ It is a `.b-cdn.net` host, so it is NOT covered by the `https://*.ciphera.net`
// * already present in connect-src — every directive needs it spelled out.
const ASSET_CDN = 'https://ciphera-app-static.b-cdn.net'
// * CSP directives — restrict resource loading to known origins.
// *
// * ONE function builds every CSP this app sends, parameterised by the single directive that
// * differs: who may frame the page. A second hand-written copy for /demo would drift from
// * this one the first time a source is added to either, and the page that drifted would be
// * the one inside the marketing page's frame.
function buildCsp(frameAncestors: "'none'" | "'self'"): string {
return [
"default-src 'self'",
// Next.js requires 'unsafe-inline' for its bootstrap scripts; 'unsafe-eval' only in dev (HMR).
// 'wasm-unsafe-eval' lets the browser compile/instantiate the @ciphera-net/tessera OPAQUE
// WASM core (settings re-auth) — without it WebAssembly.instantiate is CSP-blocked and the
// re-auth ceremony fails at runtime. It permits WASM compilation only, not arbitrary eval.
// 🔴 ASSET_CDN is a DELIBERATE WIDENING of script-src. It is our own zone and serves
// nothing but build output, but it does mean a compromise of that bucket is script
// execution on the authenticated dashboard. That is precisely why it is a DEDICATED
// storage zone with its own write credential (Woodpecker org secret
// `app_static_storage_password`) rather than the shared cdn.ciphera.net assets bucket:
// the credential used for routine image uploads must not gain script execution here.
`script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://js.ciphera.net https://api.help.ciphera.net ${ASSET_CDN}${process.env.NODE_ENV === 'development' ? " 'unsafe-eval'" : ''}`,
`style-src 'self' 'unsafe-inline' ${ASSET_CDN}`,
// * google/gstatic were only ever here for favicons — those now go through
// * the same-origin /api/favicon proxy, and CSP enforces that nothing
// * regresses to loading them from Google directly.
"img-src 'self' data: blob: https://ciphera.net https://captcha.ciphera.net https://*.cartocdn.com https://cdn.ciphera.net",
// next/font emits its woff2 files under /_next/static/media, so they move with the rest.
`font-src 'self' ${ASSET_CDN}`,
`connect-src 'self' https://*.ciphera.net wss://*.ciphera.net https://ciphera.net https://cdn.jsdelivr.net https://*.cartocdn.com ${ASSET_CDN}${process.env.NODE_ENV === 'development' ? ' http://localhost:* ws://localhost:*' : ''}`,
"worker-src 'self' blob:",
// 🔴 FRAMING NEEDS PERMISSION ON BOTH SIDES, AND MISSING EITHER IS SILENT.
// `frame-ancestors` on id.ciphera.net says who may frame IT; `frame-src` here
// says what THIS page may frame. Measured 10-09-2026: with the identity
// provider correctly relaxed and the allowlist correctly served, the
// vault-key hand-off still timed out — because this line did not name it, and
// a blocked frame simply never loads. The key-bridge design named only the
// first half; this is the second.
"frame-src https://api.help.ciphera.net https://id.ciphera.net",
// * Nothing may frame Pulse, except Pulse itself on /demo. X-Frame-Options: DENY (below)
// * already says so to every current browser; this is the CSP form the MCP consent page's
// * threat model names (T3, clickjacking the Allow button — PULSE-41), and the one that
// * wins where both are honoured.
// * 'none' is the answer for every route but one: the marketing home page frames /demo
// * (PUL-34, D9), and /demo alone answers 'self' (the demo header rule below).
`frame-ancestors ${frameAncestors}`,
"object-src 'none'",
"base-uri 'self'",
"form-action 'self' https://*.ciphera.net",
].join('; ')
}
const CSP = buildCsp("'none'")
// * The same policy for /demo: only the frame-ancestors directive differs.
const DEMO_CSP = buildCsp("'self'")
const BUILD_ID = Date.now().toString()
writeFileSync('public/build-id.json', JSON.stringify({ buildId: BUILD_ID }))
const nextConfig: NextConfig = {
env: {
NEXT_PUBLIC_BUILD_ID: BUILD_ID,
},
reactStrictMode: true,
// * No `X-Powered-By: Next.js`. The cluster's ingress stripped it on the way out; served
// * from anywhere else, nothing would, so the app stops sending it.
poweredByHeader: false,
// * Production only — `next dev` must keep serving its own assets, and an empty
// * prefix must stay a no-op rather than emitting `//_next/...`.
...(process.env.NODE_ENV === 'production' && ASSET_PREFIX ? { assetPrefix: ASSET_PREFIX } : {}),
// * Enable standalone output for production deployment
output: 'standalone',
// * Privacy-first: Disable analytics and telemetry
productionBrowserSourceMaps: false,
// * `next build` does not type-check. The test lane (.woodpecker/test.yml, `npm run type-check`) checks every pull
// * request, as a required check, and every push to main. The build's own pass repeated that work, and it was the
// * build step's memory peak: on 15-11-2026 the step was killed at its 3 GiB limit three times in a row, each time
// * in "Running TypeScript" right after the compile finished (.woodpecker/push.yml, next-build).
typescript: { ignoreBuildErrors: true },
experimental: {
optimizePackageImports: ['@phosphor-icons/react'],
// * See APP_HOST above.
serverActions: { allowedOrigins: APP_HOST ? [APP_HOST] : [] },
},
// @ciphera-net/tessera ships a WASM OPAQUE core (settings re-auth). Keep it out of
// the server bundle — it is a client-only SDK loaded via init() in the browser — so
// the server build never tries to bundle the .wasm binary.
serverExternalPackages: ['@ciphera-net/tessera'],
// Turbopack (next dev) path: stub Node's `fs` for the BROWSER bundle only. The
// SDK's isomorphic loader references a Node WASM target (`require('fs')`) that is
// never reached client-side (isNode() === false) but is still traversed by the
// bundler. A `turbopack` block is also required to pair with the webpack fallback
// below — a webpack config without one is a hard build error in Next 16.
turbopack: {
resolveAlias: {
fs: { browser: './lib/tessera-fs-stub.js' },
},
},
// Webpack path (next build --webpack — Pulse's production build): enable
// asyncWebAssembly + emit tessera_bg.wasm as a static asset, and stub `fs` for the
// browser bundle (mirrors the Turbopack alias above).
webpack: (config) => {
config.experiments = { ...config.experiments, asyncWebAssembly: true, layers: true }
config.module.rules.push({ test: /\.wasm$/, type: 'asset/resource' })
config.resolve = config.resolve || {}
config.resolve.fallback = { ...config.resolve.fallback, fs: false }
return config
},
images: {
remotePatterns: [
// * `www.google.com/s2/favicons**` was removed 13-08-2026. It was the last
// * standing permission for Google in this app: favicons have gone through
// * the same-origin `/api/favicon` proxy (rendered `unoptimized`) for
// * months, so the pattern granted nothing that was in use — but it left
// * the door open for an <Image src> pointing straight at Google to start
// * working again without tripping CSP review. See app/api/favicon/route.ts.
{
protocol: 'https',
hostname: 'ciphera.net',
},
{
protocol: 'https' as const,
hostname: 'cdn.ciphera.net',
},
],
},
async headers() {
return [
{
// * Prevent CDN/browser from serving stale HTML after deploys.
// * Static assets (/_next/static/*) are content-hashed and cached separately by Next.js.
// * /api/favicon sets its own long-lived Cache-Control (the CDN must cache
// * it, or every favicon render becomes an origin hit + upstream fetch).
source: '/((?!_next/static|_next/image|api/favicon).*)',
headers: [
{ key: 'Cache-Control', value: 'no-cache, must-revalidate' },
],
},
{
source: '/(.*)',
headers: [
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{
// * `browsing-topics=()` is the current opt-out. It replaced
// * `interest-cohort=()`, which named the withdrawn FLoC proposal — no
// * browser has recognised that feature since, and Chrome logged
// * "Unrecognized feature: 'interest-cohort'" on every page load.
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=(), browsing-topics=()',
},
{ key: 'X-XSS-Protection', value: '1; mode=block' },
// * The marketing split (PULSE-158, plan §6): pulse.ciphera.net is served by
// * TWO apps behind one Ingress, and the route test proves each path reaches the
// * right one by this header. The marketing app sends `website`.
{ key: 'x-pulse-app', value: 'dashboard' },
// ⚠️ AUTHORITATIVE COPY IS AT THE EDGE, NOT HERE.
// Traefik's `security-headers` middleware (applied to every router via
// `default-chain`, see Infra/Kubernetes/addons/20-traefik/middlewares.yaml)
// sets this header and OVERWRITES whatever the app sends. This value is kept
// in sync with it so the file does not describe a policy we do not ship; it is
// defence-in-depth for any path that ever bypasses that middleware.
//
// It previously read `max-age=63072000; includeSubDomains; preload`, which was
// dead config: the wire has always carried max-age=31536000 and no `preload`.
// 🔴 Do NOT re-add `preload` here. Preload is a one-way commitment recorded as
// an explicit owner decision at middlewares.yaml (`stsPreload: false`); adding
// it in this file changes nothing on the wire and only re-creates the illusion.
{
key: 'Strict-Transport-Security',
value: 'max-age=31536000; includeSubDomains',
},
{ key: 'Content-Security-Policy', value: CSP },
],
},
// * /demo is the only page that may be framed, and only by its own origin: the marketing
// * home page (pulse.ciphera.net's hero, PUL-34 D9) shows it inside the device. Both
// * headers, because each is what some browser honours.
// *
// * 🔴 ORDER IS THE MECHANISM. Next applies every matching rule in the order listed and a
// * later rule's header REPLACES an earlier rule's of the same key (resolve-routes.js:
// * `resHeaders[key] = value`, measured on next 16.1.6; set-cookie alone appends). So this
// * block must stay AFTER the catch-all above, must repeat each key spelled exactly as
// * above (keys are case-sensitive in that map, so a differently-cased twin would be a
// * second header, not a replacement), and must carry the WHOLE CSP, not the directive.
// * lib/__tests__/csp-frame-ancestors.test.ts evaluates these rules the way Next does.
// * `/demo` and `/demo/:path*` are listed separately so the bare path never depends on how
// * `:path*` treats an empty tail.
{
source: '/demo',
headers: [
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
{ key: 'Content-Security-Policy', value: DEMO_CSP },
],
},
{
source: '/demo/:path*',
headers: [
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
{ key: 'Content-Security-Policy', value: DEMO_CSP },
],
},
{
// * PULSE-133: a report page's URL is its secret (/r/<token>). noindex keeps it
// * out of search. The ingress overwrites Referrer-Policy with the site-wide
// * value (measured on staging, 29-09-2026), so the policy that actually holds
// * is the no-referrer <meta> in app/r/[token]/layout.tsx; this header only
// * helps where the app's own header reaches the browser.
source: '/r/:path*',
headers: [
{ key: 'Referrer-Policy', value: 'no-referrer' },
{ key: 'X-Robots-Tag', value: 'noindex, nofollow' },
],
},
]
},
async redirects() {
return [
// /docs was rewritten to a third-party documentation host that answered 404 for every path. The product's
// documentation is docs.ciphera.net/pulse; the old paths do not map onto it, so every one lands on its start.
{ source: '/docs', destination: 'https://docs.ciphera.net/pulse', permanent: true },
{ source: '/docs/:path*', destination: 'https://docs.ciphera.net/pulse', permanent: true },
{
source: '/dashboard',
destination: '/',
permanent: true,
},
// PageSpeed became Performance. The old path is BOOKMARKABLE and is linked
// from notification emails already delivered, so it has to keep resolving —
// a rename that 404s the previous URL is a rename that loses the reader.
//
// The name went because it was Google's: "PageSpeed" IS PageSpeed Insights,
// and this instrument stopped calling Google's API at the 14-08-2026 cutover
// to a self-hosted Lighthouse. It also described one of the four categories
// it reports (performance, accessibility, best practices, SEO).
{
source: '/sites/:id/pagespeed',
destination: '/sites/:id/performance',
permanent: true,
},
{
source: '/sites/:id/pagespeed/:path*',
destination: '/sites/:id/performance/:path*',
permanent: true,
},
// The in-app inbox went on 20-10-2026: Pulse notifications are email-only.
// `/notifications` is bookmarkable and older emails fell back to it, so it
// keeps resolving, to the page that controls those emails. Only the page
// route: the API's /notifications/preferences is a different host and path.
{
source: '/notifications',
destination: '/settings/account/notifications',
permanent: true,
},
// NOTE: the former `/integrations/:slug` → docs.ciphera.net redirects were
// removed. They shadowed the real per-integration guide pages
// (app/integrations/[slug]) and pointed at a defunct host (docs moved to
// help.ciphera.net). Each guide page now links out to help.ciphera.net
// via the registry's docsSlug.
]
},
}
export default withPWA(nextConfig)