astro-helmet 1.2.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) Ryan Voitiskis
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -21,6 +21,8 @@ Install `astro-helmet` using npm:
21
21
  npm i astro-helmet
22
22
  ```
23
23
 
24
+ `astro-helmet` supports Astro 4, 5, 6, and 7.
25
+
24
26
  ## Usage
25
27
 
26
28
  In your Layout component, import `astro-helmet` and pass an object of `headItems` to the `Helmet` component.
@@ -54,7 +56,7 @@ Any attribute can be added to a head item. Simply provide the attribute as a key
54
56
 
55
57
  `'innerHTML', 'priority', 'tagName'` are reserved keys and cannot be used as attributes.
56
58
 
57
- To add content to a tag, use the `innerHTML` key. This will render the content inside the tag.
59
+ To add content to a tag, use the `innerHTML` key. This will render the content inside the tag. Only pass trusted content to `innerHTML`; it is intended for code and markup that your application controls, such as inline scripts, inline styles, and `noscript` fallbacks.
58
60
 
59
61
  To control the order of head items, use the `priority` key.
60
62
 
@@ -176,6 +178,8 @@ Meta items later in the array replace earlier items. Meta tags without any of th
176
178
 
177
179
  `title` and `base` items are also deduplicated, with the last item in the array taking precedence.
178
180
 
181
+ At least one merged `HeadItems` object must provide a non-empty `title`; otherwise `renderHead()` will throw.
182
+
179
183
  ### Props
180
184
 
181
185
  The `Helmet` component takes two props:
@@ -186,6 +190,7 @@ interface Props {
186
190
  options?: {
187
191
  omitHeadTags?: boolean
188
192
  applyPriority?: (tag: Tag) => Required<Tag>
193
+ csp?: boolean
189
194
  }
190
195
  }
191
196
  ```
@@ -287,6 +292,16 @@ function applyPriority(tag: Tag): Required<Tag> {
287
292
  }
288
293
  ```
289
294
 
295
+ #### `csp`
296
+
297
+ Set `options.csp` to `true` to register inline script/style hashes and external script/style sources with Astro's CSP runtime API.
298
+
299
+ ```astro
300
+ <Helmet {headItems} options={{ csp: true }} />
301
+ ```
302
+
303
+ Leave this disabled unless your Astro project has `security.csp` configured. Astro warns when `Astro.csp` is accessed without CSP enabled, so `astro-helmet` keeps CSP registration opt-in.
304
+
290
305
  Provide a custom `applyPriority()` function to reorder head items as needed.
291
306
 
292
307
  ## Defaults
package/index.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ declare const Helmet: (props: {
2
+ headItems: HeadItems | HeadItems[]
3
+ options?: {
4
+ omitHeadTags?: boolean
5
+ applyPriority?: (tag: Tag) => Required<Tag>
6
+ csp?: boolean
7
+ }
8
+ }) => unknown
9
+
10
+ export default Helmet
11
+
12
+ type TagName =
13
+ | 'title'
14
+ | 'base'
15
+ | 'meta'
16
+ | 'link'
17
+ | 'style'
18
+ | 'script'
19
+ | 'noscript'
20
+
21
+ type BaseItem = {
22
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
+ [key: string]: any
24
+ priority?: number
25
+ }
26
+
27
+ type ContentItem = BaseItem & {
28
+ innerHTML?: string
29
+ }
30
+
31
+ export type Tag = (BaseItem | ContentItem) & {
32
+ tagName: TagName
33
+ priority?: number
34
+ }
35
+
36
+ export type JsonLdItem = {
37
+ '@type': string
38
+ /** Automatically injected - do not provide. */
39
+ '@context'?: never
40
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
+ [key: string]: any
42
+ }
43
+
44
+ export type HeadItems = {
45
+ title?: string
46
+ base?: BaseItem[]
47
+ meta?: BaseItem[]
48
+ link?: BaseItem[]
49
+ style?: ContentItem[]
50
+ script?: ContentItem[]
51
+ noscript?: ContentItem[]
52
+ jsonLd?: JsonLdItem | JsonLdItem[]
53
+ }
package/package.json CHANGED
@@ -1,16 +1,21 @@
1
1
  {
2
2
  "name": "astro-helmet",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "type": "module",
5
5
  "description": "A document head manager for astro.",
6
6
  "author": "Ryan Voitiskis <ryanvoitiskis@pm.me> (https://ryanvoitiskis.com/)",
7
7
  "license": "ISC",
8
8
  "exports": {
9
- ".": "./index.ts"
9
+ ".": {
10
+ "types": "./index.d.ts",
11
+ "default": "./index.ts"
12
+ }
10
13
  },
14
+ "types": "./index.d.ts",
11
15
  "files": [
12
16
  "src",
13
- "index.ts"
17
+ "index.ts",
18
+ "index.d.ts"
14
19
  ],
15
20
  "keywords": [
16
21
  "astro",
@@ -30,24 +35,24 @@
30
35
  "release": "semantic-release"
31
36
  },
32
37
  "devDependencies": {
33
- "@astrojs/check": "^0.9.8",
34
- "@eslint/js": "^9.39.2",
38
+ "@astrojs/check": "^0.9.9",
39
+ "@eslint/js": "^10.0.1",
35
40
  "@semantic-release/changelog": "^6.0.3",
36
41
  "@semantic-release/git": "^10.0.1",
37
- "@semantic-release/github": "^11.0.1",
38
- "@semantic-release/npm": "^12.0.1",
39
- "@vitest/coverage-v8": "^4.1.2",
40
- "astro": "^6.1.3",
41
- "eslint": "^9.39.2",
42
- "prettier": "^3.4.2",
42
+ "@semantic-release/github": "^12.0.9",
43
+ "@semantic-release/npm": "^13.1.5",
44
+ "@vitest/coverage-v8": "^4.1.10",
45
+ "astro": "^7.0.6",
46
+ "eslint": "^10.6.0",
47
+ "prettier": "^3.9.4",
43
48
  "prettier-plugin-astro": "^0.14.1",
44
- "semantic-release": "^24.2.0",
45
- "typescript": "^5.7.2",
46
- "typescript-eslint": "^8.55.0",
47
- "vitest": "^4.1.2"
49
+ "semantic-release": "^25.0.5",
50
+ "typescript": "^6.0.3",
51
+ "typescript-eslint": "^8.63.0",
52
+ "vitest": "^4.1.10"
48
53
  },
49
54
  "peerDependencies": {
50
- "astro": "^4.0.0 || ^5.0.0 || ^6.0.0"
55
+ "astro": "^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
51
56
  },
52
57
  "repository": {
53
58
  "type": "git",
package/src/Helmet.astro CHANGED
@@ -10,7 +10,7 @@ interface Props {
10
10
  }
11
11
  }
12
12
 
13
- const { headItems, options = {} } = Astro.props
13
+ const { headItems, options = {} } = Astro.props as Props
14
14
  const { applyPriority, omitHeadTags = false, csp: cspEnabled = false } = options
15
15
  const head = renderHead(headItems, applyPriority)
16
16
 
@@ -24,8 +24,8 @@ const csp = cspEnabled
24
24
  csp?: {
25
25
  insertScriptHash(hash: string): void
26
26
  insertStyleHash(hash: string): void
27
- insertScriptResource(url: string): void
28
- insertStyleResource(url: string): void
27
+ insertScriptResource(resource: string): void
28
+ insertStyleResource(resource: string): void
29
29
  }
30
30
  }).csp
31
31
  : undefined
@@ -41,8 +41,27 @@ if (csp) {
41
41
  }
42
42
 
43
43
  for (const { type, url } of getExternalResources(headItems)) {
44
- if (type === 'script') csp.insertScriptResource(url)
45
- else csp.insertStyleResource(url)
44
+ const resource = getCspSource(url)
45
+ if (!resource) continue
46
+ if (type === 'script') csp.insertScriptResource(resource)
47
+ else csp.insertStyleResource(resource)
48
+ }
49
+ }
50
+
51
+ function getCspSource(url: string): string | undefined {
52
+ const trimmed = url.trim()
53
+ if (!trimmed) return undefined
54
+ if (trimmed.startsWith('//')) return new URL(`https:${trimmed}`).origin
55
+ if (trimmed.startsWith('/') || trimmed.startsWith('./')) return "'self'"
56
+
57
+ try {
58
+ const parsed = new URL(trimmed)
59
+ if (parsed.protocol === 'http:' || parsed.protocol === 'https:')
60
+ return parsed.origin
61
+ if (parsed.protocol === 'data:' || parsed.protocol === 'blob:')
62
+ return parsed.protocol
63
+ } catch {
64
+ return "'self'"
46
65
  }
47
66
  }
48
67
  ---
package/src/main.ts CHANGED
@@ -75,7 +75,7 @@ export function renderHead(
75
75
  const tags: Tag[] = Object.entries(rest).flatMap(([tagName, tagItems]) =>
76
76
  tagItems.map((item) => ({ ...item, tagName }) as Tag)
77
77
  )
78
- tags.push({ tagName: 'title', innerHTML: items.title })
78
+ tags.push({ tagName: 'title', innerHTML: escapeHtml(items.title) })
79
79
  tags.push(...getDefaultTags(tags))
80
80
 
81
81
  for (const item of items.jsonLd) {
@@ -244,31 +244,34 @@ function escapeJsonLd(json: string): string {
244
244
  }
245
245
 
246
246
  function deduplicateMetaItems(metaItems: BaseItem[]): BaseItem[] {
247
- const keyless: BaseItem[] = []
248
- const metaMap = new Map<string, BaseItem[]>()
247
+ const deduplicated: BaseItem[] = []
248
+ const itemIndexByKey = new Map<string, number>()
249
249
 
250
250
  for (const meta of metaItems) {
251
- const key = meta.property || meta.name || meta['http-equiv'] || (meta.charset ? 'charset' : null)
252
- if (key) metaMap.set(key, (metaMap.get(key) || []).concat(meta))
253
- else keyless.push(meta)
251
+ const key = getMetaDeduplicationKey(meta)
252
+ if (!key) {
253
+ deduplicated.push(meta)
254
+ continue
255
+ }
256
+
257
+ const existingIndex = itemIndexByKey.get(key)
258
+ if (existingIndex === undefined) {
259
+ itemIndexByKey.set(key, deduplicated.length)
260
+ deduplicated.push(meta)
261
+ } else {
262
+ deduplicated[existingIndex] = meta
263
+ }
254
264
  }
255
265
 
256
- return [
257
- ...keyless,
258
- ...Array.from(metaMap.values()).flatMap(deduplicateByMedia)
259
- ]
266
+ return deduplicated
260
267
  }
261
268
 
262
- function deduplicateByMedia(items: BaseItem[]): BaseItem[] {
263
- if (items.length === 1) return items
264
-
265
- const uniqueItems = new Map<string, BaseItem>()
266
- items.forEach((item) => {
267
- const mediaKey = item.media || ''
268
- uniqueItems.set(mediaKey, item)
269
- })
270
-
271
- return Array.from(uniqueItems.values())
269
+ function getMetaDeduplicationKey(meta: BaseItem): string | undefined {
270
+ const media = String(meta.media || '')
271
+ if (meta.property) return `property:${meta.property}:${media}`
272
+ if (meta.name) return `name:${meta.name}:${media}`
273
+ if (meta['http-equiv']) return `http-equiv:${meta['http-equiv']}:${media}`
274
+ if (meta.charset) return `charset::${media}`
272
275
  }
273
276
 
274
277
  function renderHeadTag(item: BaseItem | ContentItem): string {
@@ -283,6 +286,7 @@ function renderHeadTag(item: BaseItem | ContentItem): string {
283
286
  export function renderAttrs(item: BaseItem | ContentItem): string {
284
287
  return Object.entries(item)
285
288
  .filter(([key]) => !['innerHTML', 'priority', 'tagName'].includes(key))
289
+ .filter(([key]) => isValidAttributeName(key))
286
290
  .map(([key, value]) => {
287
291
  if (typeof value === 'boolean') return value ? key : ''
288
292
  else if (value === null || value === undefined) return ''
@@ -292,6 +296,10 @@ export function renderAttrs(item: BaseItem | ContentItem): string {
292
296
  .join(' ')
293
297
  }
294
298
 
299
+ function isValidAttributeName(key: string): boolean {
300
+ return /^[^\s"'<>/=]+$/.test(key)
301
+ }
302
+
295
303
  function escapeHtml(str: string): string {
296
304
  const escapeMap: Record<string, string> = {
297
305
  '"': '&quot;',