Repository navigation
feat(content-signal): publish HTTP policy headers #363
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
harlan-zw
wants to merge
4
commits into
main
Choose a base branch
from
feat/content-signal-headers
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+367
β2
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
f803972
feat(content-signal): publish HTTP policy headers
harlan-zw 8684251
chore: ignore local Cloudflare build metadata
harlan-zw 814305d
fix(content-signal): preserve signal-free scoped groups
harlan-zw eac93b5
fix(content-signal): check the final static rule budget
harlan-zw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -57,3 +57,4 @@ Temporary Items | |
|
|
||
| # PR Lens writes its previews here. They are rebuilt on demand. | ||
| .pr-lens/ | ||
| .wrangler/ | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| /** Add the fallback first, so explicit Cloudflare rules can detach it before setting their policy. */ | ||
| export function mergeContentSignalHeaders(contents: string, pattern: string, policy: string, limit: number | null = 100): string { | ||
| const blocks = contents.split(/(?=^[^\s#])/m) | ||
| // A site's own catch-all policy or removal is authoritative. | ||
| const isBroad = (block: string) => block.split(/\r?\n/, 1)[0] === pattern | ||
| const broad = blocks.filter(isBroad) | ||
| if (broad.some(block => /^\s+(?:content-signal\s*:|!\s*content-signal\s*$)/im.test(block))) | ||
| return contents | ||
| const explicit = blocks.filter(block => !isBroad(block)).map((block) => { | ||
| if (!/^\s+content-signal\s*:/im.test(block) || /^\s+!\s*content-signal\s*$/im.test(block)) | ||
| return block | ||
| return block.replace(/^(\s+)(content-signal\s*:)/im, '$1! Content-Signal\n$1$2') | ||
| }).join('') | ||
| const fallback = broad.length | ||
| ? broad.map(block => `${block.replace(/^([^\r\n]*)(?:\r?\n|$)/, `$1\n Content-Signal: ${policy}\n`).trimEnd()}\n\n`).join('') | ||
| : `${pattern}\n Content-Signal: ${policy}\n\n` | ||
| const merged = `${fallback}${explicit}` | ||
| if (limit !== null) | ||
| assertContentSignalHeaderBudget(merged, limit) | ||
| return merged | ||
| } | ||
|
|
||
| export function countStaticHeaderRules(contents: string): number { | ||
| return contents.split(/\r?\n/).filter(line => /^[^\s#]/.test(line)).length | ||
| } | ||
|
|
||
| /** Policy rules cannot be dropped to make a deployment fit. */ | ||
| export function assertContentSignalHeaderBudget(contents: string, limit = 100): void { | ||
| const total = countStaticHeaderRules(contents) | ||
| if (total > limit) | ||
| throw new Error(`Content-Signal fallback exceeds Cloudflare's ${limit}-rule header limit (${total}). Use a shared header rule or reduce other rules.`) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import { getResponseHeader, setHeader } from '#nuxtseo/h3' | ||
| import { defineNitroPlugin } from '#nuxtseo/nitro' | ||
| import { useRuntimeConfigNuxtRobots } from '../composables/useRuntimeConfigNuxtRobots' | ||
|
|
||
| export default defineNitroPlugin((nitro) => { | ||
| nitro.hooks.hook('beforeResponse', (event) => { | ||
| const { contentSignalHeader } = useRuntimeConfigNuxtRobots(event) | ||
| if (contentSignalHeader && getResponseHeader(event, 'content-signal') === undefined) | ||
| setHeader(event, 'Content-Signal', contentSignalHeader) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| import { createResolver } from '@nuxt/kit' | ||
| import { fetch, setup } from '@nuxt/test-utils' | ||
| import { describe, expect, it } from 'vitest' | ||
|
|
||
| const { resolve } = createResolver(import.meta.url) | ||
|
|
||
| await setup({ | ||
| rootDir: resolve('../fixtures/basic'), | ||
| build: true, | ||
| server: true, | ||
| nuxtConfig: { | ||
| robots: { groups: [{ userAgent: '*', contentSignal: 'ai-train=no, search=yes, ai-input=yes' }] }, | ||
| routeRules: { '/about': { headers: { 'CONTENT-SIGNAL': 'search=no' } } }, | ||
| }, | ||
| }) | ||
|
|
||
| describe('content-Signal response headers', () => { | ||
| it('publishes the wildcard robots policy', async () => { | ||
| const response = await fetch('/') | ||
| expect(response.headers.get('content-signal')).toBe('ai-train=no, search=yes, ai-input=yes') | ||
| }) | ||
|
|
||
| it('preserves an explicit route policy in any casing', async () => { | ||
| const response = await fetch('/about') | ||
| expect(response.headers.get('content-signal')).toBe('search=no') | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import { createResolver } from '@nuxt/kit' | ||
| import { setup } from '@nuxt/test-utils' | ||
| import { describe, expect, it } from 'vitest' | ||
| import { readHeadersFile } from './utils/headers' | ||
|
|
||
| const { resolve } = createResolver(import.meta.url) | ||
|
|
||
| await setup({ rootDir: resolve('../fixtures/content-signal-budget'), build: true, server: false }) | ||
|
|
||
| describe('content-Signal header budget', () => { | ||
| it('allows a later compiler to trim optional rules before checking the final budget', () => { | ||
| const contents = readHeadersFile() | ||
| expect(contents.split('\n').filter(line => /^[^\s#]/.test(line))).toHaveLength(100) | ||
| expect(contents).toContain('Content-Signal: ai-train=no') | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| import { createResolver } from '@nuxt/kit' | ||
| import { $fetch, fetch, setup } from '@nuxt/test-utils' | ||
| import { describe, expect, it } from 'vitest' | ||
|
|
||
| const { resolve } = createResolver(import.meta.url) | ||
|
|
||
| await setup({ | ||
| rootDir: resolve('../fixtures/basic'), | ||
| build: true, | ||
| server: true, | ||
| nuxtConfig: { | ||
| robots: { | ||
| groups: [ | ||
| { userAgent: '*', contentSignal: 'ai-train=no' }, | ||
| { userAgent: 'GPTBot', contentSignal: 'ai-train=yes' }, | ||
| ], | ||
| }, | ||
| }, | ||
| }) | ||
|
|
||
| describe('user-agent Content Signal policies', () => { | ||
| it('keeps scoped policies in robots.txt without flattening them into HTTP', async () => { | ||
| const response = await fetch('/') | ||
| const robots = await $fetch<string>('/robots.txt') | ||
|
|
||
| expect(response.headers.get('content-signal')).toBeNull() | ||
| expect(robots).toMatch(/User-agent: \*\nContent-Signal: ai-train=no/) | ||
| expect(robots).toMatch(/User-agent: GPTBot\nContent-Signal: ai-train=yes/) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { createResolver } from '@nuxt/kit' | ||
| import { setup } from '@nuxt/test-utils' | ||
| import { describe, expect, it } from 'vitest' | ||
| import { readHeadersFile } from './utils/headers' | ||
|
|
||
| const { resolve } = createResolver(import.meta.url) | ||
|
|
||
| await setup({ | ||
| rootDir: resolve('../fixtures/content-signal-headers'), | ||
| build: true, | ||
| server: false, | ||
| }) | ||
|
|
||
| function readPolicy(path: string) { | ||
| const headers = new Headers() | ||
| let matches = false | ||
| for (const line of readHeadersFile().split('\n')) { | ||
| if (!line.trim()) | ||
| continue | ||
| if (!/^\s/.test(line)) { | ||
| matches = new RegExp(`^${line.trim().replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*')}$`).test(path) | ||
| continue | ||
| } | ||
| if (!matches) | ||
| continue | ||
| if (/^\s*!\s*content-signal\s*$/i.test(line)) | ||
| headers.delete('content-signal') | ||
| const value = line.trim().match(/^content-signal:(.*)$/i) | ||
| if (value) | ||
| headers.append('content-signal', value[1]!.trim()) | ||
| } | ||
| return headers.get('content-signal') | ||
| } | ||
|
|
||
| describe('cloudflare static Content-Signal headers', () => { | ||
| it('serves the wildcard policy without calling the server', () => { | ||
| expect(readPolicy('/docs/')).toBe('ai-train=no, search=yes') | ||
| expect(readPolicy('/docs/policy.md')).toBe('ai-train=no, search=yes') | ||
| expect(readPolicy('/elsewhere')).toBeNull() | ||
| }) | ||
|
|
||
| it('keeps the explicit static policy without joining the default', () => { | ||
| expect(readPolicy('/docs/api/data.json')).toBe('search=no') | ||
| }) | ||
|
|
||
| it('preserves an explicit header removal', () => { | ||
| expect(readPolicy('/docs/removed/page')).toBeNull() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import { readFile, writeFile } from 'node:fs/promises' | ||
| import { resolve } from 'node:path' | ||
| import { fileURLToPath } from 'node:url' | ||
| import { useNuxt } from '@nuxt/kit' | ||
|
|
||
| export default defineNuxtConfig({ | ||
| extends: ['../static-headers'], | ||
| alias: { '@nuxtjs/robots/util': fileURLToPath(new URL('../../../src/util.ts', import.meta.url)) }, | ||
| robots: { robotsTxt: false, groups: [{ userAgent: '*', contentSignal: 'ai-train=no' }] }, | ||
| nitro: { preset: 'cloudflare-module', cloudflare: { deployConfig: true } }, | ||
| hooks: { | ||
| 'nitro:build:before': (nitro) => { | ||
| nitro.hooks.hook('compiled', () => writeFile(resolve(nitro.options.output.publicDir, '_headers'), | ||
| Array.from({ length: 100 }, (_, index) => `/page-${index}\n X-Page: ${index}\n`).join('\n'))) | ||
| }, | ||
| 'modules:done': () => { | ||
| if (process.env.NUXT_TEST_SKIP_HEADER_TRIM === 'true') | ||
| return | ||
| const nuxt = useNuxt() | ||
| nuxt.hook('nitro:build:before', (nitro) => { | ||
| nitro.hooks.hook('compiled', async () => { | ||
| const path = resolve(nitro.options.output.publicDir, '_headers') | ||
| const headers = await readFile(path, 'utf8') | ||
| if (!headers.includes('Content-Signal: ai-train=no')) | ||
| throw new Error('The later compiler must observe the generated policy.') | ||
| await writeFile(path, headers.replace('/page-99\n X-Page: 99\n', '')) | ||
| }) | ||
| }) | ||
| }, | ||
| }, | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.