Visitar URL original
fix(unhead): escape control characters in JSON template parameters by henricop Β· Pull Request #1039 Β· unjs/unhead Β· GitHub
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
7 changes: 1 addition & 6 deletions packages/unhead/src/utils/templateParams.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import type { TemplateParams } from '../types'

const BACKSLASH_RE = /\\/g
const LT_RE = /</g
const DOUBLE_QUOTE_RE = /"/g
const TOKEN_RE = /%\w+(?:\.\w+)?/g

const SepSub = '%separator'
Expand All @@ -24,10 +22,7 @@ function sub(p: TemplateParams, token: string, isJson = false) {
// numbers are kept, including 0, while null and false still render as empty
const str = typeof val === 'number' ? String(val) : String(val || '')
return isJson
? str
.replace(BACKSLASH_RE, '\\\\')
.replace(LT_RE, '\\u003C')
.replace(DOUBLE_QUOTE_RE, '\\"')
? JSON.stringify(str).slice(1, -1).replace(LT_RE, '\\u003C')
: str
}
return undefined
Expand Down
29 changes: 29 additions & 0 deletions packages/unhead/test/unit/server/templateParams.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,39 @@
import type { Script } from '../../../src/types'
import { describe, it } from 'vitest'

import { TemplateParamsPlugin } from '../../../src/plugins'
import { renderSSRHead } from '../../../src/server'
import { processTemplateParams } from '../../../src/utils'
import { createServerHeadWithContext } from '../../util'

describe('ssr templateParams', () => {
for (const type of ['application/json', 'application/ld+json'] as const) {
it.each(Array.from({ length: 32 }, (_, code) => code))(`escapes control character %i in ${type} template parameters`, (code) => {
const value = `before${String.fromCharCode(code)}after"\\</script>`
const head = createServerHeadWithContext({ plugins: [TemplateParamsPlugin] })
const script: Script = {
type,
innerHTML: { value: '%value' },
}
head.push({
script: [{ ...script, processTemplateParams: true }],
templateParams: { value },
})

const { headTags } = renderSSRHead(head)
const json = headTags.match(/<script[^>]*>([\s\S]*?)<\/script>/)?.[1]

expect(json).toBeDefined()
expect(JSON.parse(json!)).toEqual({ value })
expect(json).not.toContain('</script>')
})
}

it('preserves control characters in plain-text template parameters', () => {
expect(processTemplateParams('Before %value after', { value: 'line1\nline2' }))
.toBe('Before line1\nline2 after')
})

it('basic', async () => {
const head = createServerHeadWithContext({
plugins: [TemplateParamsPlugin],
Expand Down
Loading