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
5 changes: 4 additions & 1 deletion layers/content-core/utils/content/fetchContentAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import type { ContentRepository } from './repository'

type Fetcher = <T>(url: string, options: { query: { args: string } }) => Promise<T>

// Nuxt 4.7 types `$fetch` so strictly that it no longer overlaps this narrow call shape.
const defaultFetcher = $fetch as unknown as Fetcher

/**
* The browser's {@link ContentRepository}: every method asks the server route
* instead of querying a SQLite copy in WebAssembly, so a client-side
Expand All @@ -13,7 +16,7 @@ type Fetcher = <T>(url: string, options: { query: { args: string } }) => Promise
* are equal URLs and the edge can cache them. The route answers `{ result }`
* because a bare `null` would not survive as a body.
*/
export function createFetchContentAdapter(fetcher: Fetcher = $fetch as Fetcher): ContentRepository {
export function createFetchContentAdapter(fetcher: Fetcher = defaultFetcher): ContentRepository {
const repository: Record<string, (...args: unknown[]) => Promise<unknown>> = {}
for (const method of CONTENT_METHODS satisfies readonly ContentMethod[]) {
repository[method] = async (...args) => {
Expand Down
12 changes: 9 additions & 3 deletions nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,11 @@ export default defineNuxtConfig({
// responses and polling for old assets, none of which this site serves.
aiReady: false,
skewProtection: false,
typescript: {
// @nuxt/content hands its collection types to `nitro.typescript`, which
// the Nitro v3 server project no longer reads.
serverTsConfig: { include: ['./content/types.d.ts'] }
},
modules: [
'@vueuse/nuxt',
'nuxt-link-checker',
Expand Down Expand Up @@ -456,8 +461,10 @@ export default defineNuxtConfig({
},
nitro: {
preset: "cloudflare_module",
externals: {
inline: ["@nuxt/content"]
prerender: {
// The Nitro 3 prerenderer serves no public assets, so the dump
// handler 404s; the Worker answers from its ASSETS binding.
ignore: [/^\/__nuxt_content\//]
},
cloudflare: {
deployConfig: true,
Expand Down Expand Up @@ -494,7 +501,6 @@ export default defineNuxtConfig({
// cached HTML could point at another build's chunks. What is
// cached, and for how long, is decided by the routeRules
// headers alone (see AGENTS.md, "Caching and SEO signals").
// @ts-expect-error Nitro's bundled wrangler types predate `cache`.
cache: {
enabled: true
},
Expand Down
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,17 @@
"@nuxtjs/sitemap": "9.2.0",
"@resvg/resvg-wasm": "2.6.2",
"@tailwindcss/vite": "^4.1.17",
"@unhead/vue": "^3.0.0",
"@unhead/vue": "^3.5.2",
"@vue/test-utils": "^2.4.11",
"@vueuse/core": "^15.0.0",
"@vueuse/nuxt": "15.1.0",
"cheerio": "^1.0.0",
"eslint": "^10.0.0",
"eslint-plugin-vuejs-accessibility": "^2.5.0",
"happy-dom": "^21.0.0",
"nitro": "3.0.260429-beta",
"nuxt": "^4.2.1",
"lru-cache": "^11.2.6",
"nitro": "3.0.261103-rc",
"nuxt": "^4.7.0",
"nuxt-og-image": "7.2.1",
"nuxt-posthog": "1.6.3",
"nuxt-schema-org": "7.1.2",
Expand Down
2,244 changes: 1,352 additions & 892 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

24 changes: 24 additions & 0 deletions server/plugins/cloudflare-assets-binding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Gives sub-requests the Worker's bindings.
*
* @nuxt/content refills an empty D1 database by fetching its dump through
* `serverFetch`, which Nitro 3 runs as a fresh request without the
* `cloudflare` runtime context. The dump handler then finds no ASSETS binding
* and answers 404, so the first render of a new deploy fails. `env` from
* `cloudflare:workers` is the same binding set the outer request carries.
*/
type Runtime = { cloudflare?: { env?: unknown } }
type RuntimeRequest = { runtime?: Runtime }

const specifier = 'cloudflare:workers'

export default defineNitroPlugin(async (nitroApp) => {
const load = () => import(/* @vite-ignore */ specifier).then(m => m.env as unknown)
const env = await load().catch(() => undefined)
if (!env) return
nitroApp.hooks.hook('request', (event) => {
const req = event.req as unknown as RuntimeRequest
if (req.runtime?.cloudflare?.env) return
req.runtime = { ...req.runtime, cloudflare: { ...req.runtime?.cloudflare, env } }
})
})
26 changes: 8 additions & 18 deletions server/plugins/error-response-headers.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import type { H3Event } from 'h3'

/**
* Error responses are neither indexed nor cached.
*
Expand All @@ -16,28 +14,20 @@ import type { H3Event } from 'h3'
* `releaseDate`, so errors get an explicit `no-store` for the edge and for
* browsers.
*
* Two hooks, because an error reaches the client by two routes: a thrown
* error runs through Nitro's `error` hook and the error handler, and never
* through `beforeResponse`; a handler that sets an error status and returns
* normally runs through `beforeResponse` only. The `error` hook fires before
* the error handler writes its response, so headers set there are still sent.
* One hook, Nitro's `response`: it sees the final response whether a handler
* returned an error status or threw and the error handler built it.
*
* Cloudflare's own error pages (1101, 1102) are produced outside the Worker
* and can carry no header from here.
*/
const markError = (event: H3Event) => {
setResponseHeader(event, 'X-Robots-Tag', 'noindex')
setResponseHeader(event, 'cloudflare-cdn-cache-control', 'no-store')
setResponseHeader(event, 'Cache-Control', 'no-store')
const markError = (headers: Headers) => {
headers.set('X-Robots-Tag', 'noindex')
headers.set('cloudflare-cdn-cache-control', 'no-store')
headers.set('Cache-Control', 'no-store')
}

export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('error', (error, { event }) => {
const status = (error as { statusCode?: number }).statusCode ?? 500
if (event && status >= 400) markError(event)
})

nitroApp.hooks.hook('beforeResponse', (event) => {
if (getResponseStatus(event) >= 400) markError(event)
nitroApp.hooks.hook('response', (res) => {
if (res.status >= 400) markError(res.headers)
})
})
20 changes: 6 additions & 14 deletions server/plugins/security-headers.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,14 @@
import type { H3Event } from 'h3'

/**
* Every response carries the baseline security headers, errors included.
*
* Two hooks for the same reason as error-response-headers.ts: a thrown error
* never reaches `beforeResponse`, and a handler that returns an error status
* normally reaches nothing else. The headers are static, so they do not touch
* One `response` hook sees the final response whether a handler returned it or
* the error handler built it. The headers are static, so they do not touch
* edge caching, and nothing here reads the request.
*/
const apply = (event: H3Event) => {
for (const [name, value] of Object.entries(SECURITY_HEADERS)) {
setResponseHeader(event, name, value)
}
}

export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('error', (_error, { event }) => {
if (event) apply(event)
nitroApp.hooks.hook('response', (res) => {
for (const [name, value] of Object.entries(SECURITY_HEADERS)) {
res.headers.set(name, value)
}
})
nitroApp.hooks.hook('beforeResponse', apply)
})
8 changes: 4 additions & 4 deletions server/plugins/strip-cacheable-cookies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@
const CACHEABLE = /^\/(?:(?:en|de)(?:\/|$)|robots\.txt$)/

export default defineNitroPlugin((nitroApp) => {
nitroApp.hooks.hook('beforeResponse', (event) => {
if (getResponseStatus(event) !== 200) return
if (!CACHEABLE.test(event.path.split('?')[0]!)) return
removeResponseHeader(event, 'set-cookie')
nitroApp.hooks.hook('response', (res, event) => {
if (res.status !== 200) return
if (!CACHEABLE.test(new URL(event.req.url).pathname)) return
res.headers.delete('set-cookie')
})
})
32 changes: 14 additions & 18 deletions tests/architecture/security-headers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,20 @@ type Hook = (...args: unknown[]) => void
/** Loads the plugin against stubbed Nitro globals; returns the hooks it registers. */
async function loadPlugin() {
const hooks = new Map<string, Hook>()
const sent: Record<string, string> = {}
vi.resetModules()
vi.stubGlobal('SECURITY_HEADERS', SECURITY_HEADERS)
vi.stubGlobal('setResponseHeader', (_event: unknown, name: string, value: string) => {
sent[name] = value
})
vi.stubGlobal('defineNitroPlugin', (plugin: (app: unknown) => void) => plugin)
const { default: plugin } = await import('../../server/plugins/security-headers')
const hook = (name: string, fn: Hook) => hooks.set(name, fn)
;(plugin as (app: unknown) => void)({ hooks: { hook } })
return { hooks, sent }
return { hooks }
}

const respond = async (status: number) => {
const { hooks } = await loadPlugin()
const res = new Response(null, { status })
hooks.get('response')!(res, {})
return Object.fromEntries(res.headers)
}

afterEach(() => {
Expand Down Expand Up @@ -105,22 +108,15 @@ describe('content security policy source list', () => {
})

describe('security-headers plugin', () => {
it('applies every header before a normal response', async () => {
const { hooks, sent } = await loadPlugin()
hooks.get('beforeResponse')!({})
expect(sent).toEqual(SECURITY_HEADERS)
})
const lower = ([name, value]: [string, string]) => [name.toLowerCase(), value]
const expected = Object.fromEntries(Object.entries(SECURITY_HEADERS).map(lower))

it('applies every header to a thrown error', async () => {
const { hooks, sent } = await loadPlugin()
hooks.get('error')!(new Error('boom'), { event: {} })
expect(sent).toEqual(SECURITY_HEADERS)
it('applies every header to a normal response', async () => {
expect(await respond(200)).toEqual(expected)
})

it('does nothing for an error outside a request', async () => {
const { hooks, sent } = await loadPlugin()
hooks.get('error')!(new Error('boom'), {})
expect(sent).toEqual({})
it('applies every header to an error response', async () => {
expect(await respond(500)).toEqual(expected)
})

it('never sets a cookie or cache directive, so edge caching stays as it is', () => {
Expand Down
45 changes: 15 additions & 30 deletions tests/design-system/person-link.spec.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,41 @@
// @vitest-environment happy-dom
import { mount } from '@vue/test-utils'
// @vitest-environment nuxt
import { mountSuspended } from '@nuxt/test-utils/runtime'
import { describe, expect, it } from 'vitest'
import { defineComponent, h } from 'vue'
import PersonLink from '../../layers/base/components/PersonLink.vue'

const NuxtLink = defineComponent({
props: { to: { type: String, required: true } },
setup(props, { slots }) {
return () => h('a', { href: props.to }, slots.default?.())
},
})
const NuxtImg = defineComponent({
props: { src: { type: String, required: true }, alt: { type: String, default: '' } },
setup(props) {
return () => h('img', { src: props.src, alt: props.alt })
},
})

const render = (props: Record<string, unknown>) => mount(PersonLink, {
const render = (props: Record<string, unknown>) => mountSuspended(PersonLink, {
props: { name: 'TheMeinerLP', to: '/de/team/themeinerlp', ...props },
global: { stubs: { NuxtLink, NuxtImg } },
})

describe('PersonLink', () => {
it('links the name to the given path', () => {
const link = render({}).get('a')
it('links the name to the given path', async () => {
const link = (await render({})).get('a')
expect(link.text(), 'link text').toBe('TheMeinerLP')
expect(link.attributes('href'), 'link target').toBe('/de/team/themeinerlp')
})

it('renders a single link even with avatar and role', () => {
const wrapper = render({ avatar: '/a.png', role: 'Admin' })
it('renders a single link even with avatar and role', async () => {
const wrapper = await render({ avatar: '/a.png', role: 'Admin' })
expect(wrapper.findAll('a')).toHaveLength(1)
})

it('shows the avatar with the name as alternative text', () => {
const img = render({ avatar: '/a.png' }).get('img')
it('shows the avatar with the name as alternative text', async () => {
const img = (await render({ avatar: '/a.png' })).get('img')
expect(img.attributes('src')).toBe('/a.png')
expect(img.attributes('alt')).toBe('TheMeinerLP')
})

it('omits the avatar when none is given', () => {
expect(render({}).find('img').exists()).toBe(false)
it('omits the avatar when none is given', async () => {
expect((await render({})).find('img').exists()).toBe(false)
})

it('shows the role as plain text outside the link', () => {
const wrapper = render({ role: 'Admin' })
it('shows the role as plain text outside the link', async () => {
const wrapper = await render({ role: 'Admin' })
expect(wrapper.text()).toContain('Admin')
expect(wrapper.get('a').text()).toBe('TheMeinerLP')
})

it('omits the role line when none is given', () => {
expect(render({}).find('p').exists()).toBe(false)
it('omits the role line when none is given', async () => {
expect((await render({})).find('p').exists()).toBe(false)
})
})
Loading
Loading