astro-helmet 1.4.0-beta.2 → 1.4.0-beta.3

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/README.md CHANGED
@@ -60,7 +60,7 @@ Any attribute can be added to a head item. Simply provide the attribute as a key
60
60
 
61
61
  `'innerHTML', 'textContent', 'priority', 'tagName', 'key'` are reserved keys and cannot be used as attributes.
62
62
 
63
- To add content to a tag, prefer `textContent`. For `<script>` and `<style>`, `textContent` preserves the code text while escaping closing-tag sequences such as `</script>`. For tags like `<noscript>`, `textContent` is HTML-escaped.
63
+ To add content to a tag, prefer `textContent`. For `<script>` and `<style>`, `textContent` preserves the code text while escaping closing-tag sequences such as `</script>`. Script text that contains the HTML parser sequence `<!--` followed by `<script>` is rejected because it can consume the rest of the document; use an external script instead. For tags like `<noscript>`, `textContent` is HTML-escaped.
64
64
 
65
65
  Use `innerHTML` only when you intentionally need raw, trusted markup. Do not pass CMS or user-provided strings into `innerHTML` or inline event-handler attributes.
66
66
 
@@ -79,6 +79,8 @@ See `applyPriority()` in the [Options](#options) section for more information on
79
79
 
80
80
  Resource helpers return ordinary `link` or `script` items. They are optional, but they make common performance-sensitive tags harder to mistype.
81
81
 
82
+ `modulepreload()` accepts the standardized `as` destinations. Browser support beyond the default JavaScript module destination is still emerging, so verify non-script module types in your target browsers.
83
+
82
84
  ```ts
83
85
  import {
84
86
  externalScript,
@@ -209,7 +211,7 @@ const headItems: HeadItems = {
209
211
 
210
212
  ### JSON-LD / Structured Data
211
213
 
212
- Use the `jsonLd` property to add [JSON-LD structured data](https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data) to your pages. `@context` is set to `https://schema.org` automatically, `JSON.stringify()` is handled internally, and `</script>` sequences in values are escaped.
214
+ Use the `jsonLd` property to add [JSON-LD structured data](https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data) to your pages. `@context` is set to `https://schema.org` automatically, `JSON.stringify()` is handled internally, and less-than characters in values are escaped as JSON Unicode sequences so embedded data cannot change the HTML parser state.
213
215
 
214
216
  ```ts
215
217
  const headItems: HeadItems = {
@@ -344,7 +346,7 @@ const issues = validateHeadItems(headItems, {
344
346
  })
345
347
  ```
346
348
 
347
- Validation returns structured issues with `code`, `severity`, `message`, `tagName`, and `path`. It checks for common mistakes such as missing titles/descriptions, duplicate or relative canonicals, invalid preloads, preloads without a usable source, responsive image preloads that use width descriptors without `imagesizes`, font preloads without `crossorigin`, incomplete Open Graph basics, relative Open Graph/Twitter image URLs, raw `innerHTML`, inline event attributes, JSON-LD serialization errors, and optional missing SRI on external scripts/styles.
349
+ Validation returns structured issues with `code`, `severity`, `message`, `tagName`, and `path`. It checks for common mistakes such as missing or empty titles/descriptions, empty or relative canonicals, invalid preload and module-preload destinations, preloads without a usable source, responsive image preloads that use width descriptors without `imagesizes`, font preloads without `crossorigin`, incomplete or empty Open Graph basics, relative Open Graph/Twitter image URLs, raw `innerHTML`, unsafe script parser sequences, inline event attributes, JSON-LD serialization errors, and optional missing SRI on external scripts/styles.
348
350
 
349
351
  Set `requireOpenGraphImage: true` if every shareable page in your project should provide `og:image`. By default, image-less website pages are allowed so dev validation does not warn on simple pages that still have useful `og:title`, `og:type`, and `og:url` tags.
350
352
 
@@ -428,7 +430,7 @@ Astro CSP is available in Astro 6 and newer. In Astro 4 and 5 this option is a n
428
430
  - External `<script src>`.
429
431
  - Stylesheet links.
430
432
  - `rel="preload"` links with `as="script"` or `as="style"`.
431
- - `rel="modulepreload"` links as script resources.
433
+ - `rel="modulepreload"` links with script-like destinations as script resources and `as="style"` as a style resource. JSON and text module destinations are not registered because Astro's helper API does not expose their `connect-src` directives.
432
434
 
433
435
  It does not infer broader CSP directives from icons, images, fonts, analytics endpoints, or connection hints.
434
436
 
package/index.d.ts CHANGED
@@ -34,8 +34,11 @@ export type {
34
34
  JsonLdItem,
35
35
  LinkItem,
36
36
  MetaItem,
37
+ ModulePreloadAs,
38
+ ModulePreloadOptions,
37
39
  NoscriptItem,
38
40
  OpenGraphOptions,
41
+ PreloadAs,
39
42
  PreloadFontOptions,
40
43
  PreloadImageOptions,
41
44
  PreloadOptions,
package/index.ts CHANGED
@@ -29,8 +29,11 @@ export type {
29
29
  JsonLdItem,
30
30
  LinkItem,
31
31
  MetaItem,
32
+ ModulePreloadAs,
33
+ ModulePreloadOptions,
32
34
  NoscriptItem,
33
35
  OpenGraphOptions,
36
+ PreloadAs,
34
37
  PreloadFontOptions,
35
38
  PreloadImageOptions,
36
39
  PreloadOptions,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro-helmet",
3
- "version": "1.4.0-beta.2",
3
+ "version": "1.4.0-beta.3",
4
4
  "type": "module",
5
5
  "description": "A document head manager for astro.",
6
6
  "author": "Ryan Voitiskis <ryanvoitiskis@pm.me> (https://ryanvoitiskis.com/)",
@@ -29,14 +29,19 @@
29
29
  ],
30
30
  "scripts": {
31
31
  "test": "vitest",
32
- "coverage": "vitest run --coverage",
32
+ "test:browser": "playwright test",
33
+ "coverage": "vitest run --coverage --coverage.thresholds.statements=95 --coverage.thresholds.branches=90 --coverage.thresholds.functions=95 --coverage.thresholds.lines=95",
33
34
  "typecheck": "astro check",
34
35
  "lint": "eslint .",
36
+ "lint:package": "publint --pack npm --strict && attw --pack . --profile esm-only",
37
+ "verify": "npm run lint && npm run typecheck && npm run coverage && npm run lint:package && npm pack --dry-run && npm audit --audit-level=moderate",
35
38
  "release": "semantic-release"
36
39
  },
37
40
  "devDependencies": {
41
+ "@arethetypeswrong/cli": "^0.18.5",
38
42
  "@astrojs/check": "^0.9.9",
39
43
  "@eslint/js": "^10.0.1",
44
+ "@playwright/test": "^1.61.1",
40
45
  "@semantic-release/changelog": "^6.0.3",
41
46
  "@semantic-release/git": "^10.0.1",
42
47
  "@semantic-release/github": "^12.0.9",
@@ -44,8 +49,10 @@
44
49
  "@vitest/coverage-v8": "^4.1.10",
45
50
  "astro": "^7.0.6",
46
51
  "eslint": "^10.6.0",
52
+ "parse5": "^8.0.1",
47
53
  "prettier": "^3.9.4",
48
54
  "prettier-plugin-astro": "^0.14.1",
55
+ "publint": "^0.3.21",
49
56
  "semantic-release": "^25.0.5",
50
57
  "typescript": "^6.0.3",
51
58
  "typescript-eslint": "^8.63.0",
package/src/main.ts CHANGED
@@ -5,18 +5,32 @@ const DEFAULT_VIEWPORT = {
5
5
  }
6
6
 
7
7
  const VALID_PRELOAD_AS_VALUES = new Set([
8
- 'audio',
9
- 'document',
10
- 'embed',
11
8
  'fetch',
12
9
  'font',
13
10
  'image',
14
- 'object',
15
- 'provider',
16
11
  'script',
17
12
  'style',
18
- 'track',
19
- 'video',
13
+ 'track'
14
+ ])
15
+
16
+ const VALID_MODULE_PRELOAD_AS_VALUES = new Set([
17
+ 'audioworklet',
18
+ 'json',
19
+ 'paintworklet',
20
+ 'script',
21
+ 'serviceworker',
22
+ 'sharedworker',
23
+ 'style',
24
+ 'text',
25
+ 'worker'
26
+ ])
27
+
28
+ const SCRIPT_LIKE_MODULE_PRELOAD_AS_VALUES = new Set([
29
+ 'audioworklet',
30
+ 'paintworklet',
31
+ 'script',
32
+ 'serviceworker',
33
+ 'sharedworker',
20
34
  'worker'
21
35
  ])
22
36
 
@@ -46,6 +60,20 @@ export type CrossOrigin = 'anonymous' | 'use-credentials' | ''
46
60
 
47
61
  export type FetchPriority = 'high' | 'low' | 'auto'
48
62
 
63
+ export type ModulePreloadAs =
64
+ | 'audioworklet'
65
+ | 'json'
66
+ | 'paintworklet'
67
+ | 'script'
68
+ | 'serviceworker'
69
+ | 'sharedworker'
70
+ | 'style'
71
+ | 'text'
72
+ | 'worker'
73
+
74
+ export type PreloadAs =
75
+ 'fetch' | 'font' | 'image' | 'script' | 'style' | 'track'
76
+
49
77
  export type ReferrerPolicy =
50
78
  | 'no-referrer'
51
79
  | 'no-referrer-when-downgrade'
@@ -103,7 +131,6 @@ export type HeadValidationSeverity = 'warning' | 'error'
103
131
  export type HeadValidationCode =
104
132
  | 'missing-title'
105
133
  | 'missing-description'
106
- | 'duplicate-canonical'
107
134
  | 'relative-canonical'
108
135
  | 'canonical-with-noindex'
109
136
  | 'invalid-url'
@@ -112,12 +139,13 @@ export type HeadValidationCode =
112
139
  | 'missing-preload-as'
113
140
  | 'responsive-image-missing-sizes'
114
141
  | 'font-preload-missing-crossorigin'
115
- | 'modulepreload-with-as'
142
+ | 'invalid-modulepreload-as'
116
143
  | 'preconnect-missing-href'
117
144
  | 'dns-prefetch-missing-href'
118
145
  | 'sri-missing-crossorigin'
119
146
  | 'missing-sri'
120
147
  | 'unsafe-inner-html'
148
+ | 'unsafe-script-text'
121
149
  | 'unsafe-event-attribute'
122
150
  | 'missing-og-required'
123
151
  | 'relative-og-url'
@@ -147,7 +175,11 @@ export type ResourceHintOptions = Omit<LinkItem, 'rel' | 'href' | 'as'> & {
147
175
  }
148
176
 
149
177
  export type PreloadOptions = ResourceHintOptions & {
150
- as: string
178
+ as: PreloadAs
179
+ }
180
+
181
+ export type ModulePreloadOptions = ResourceHintOptions & {
182
+ as?: ModulePreloadAs
151
183
  }
152
184
 
153
185
  export type PreloadFontOptions = ResourceHintOptions & {
@@ -465,7 +497,11 @@ export function getExternalResources(
465
497
  if (hasRel(link, 'stylesheet') && link.href)
466
498
  result.push({ type: 'style', url: toUrlString(link.href) })
467
499
  else if (hasRel(link, 'modulepreload') && link.href) {
468
- result.push({ type: 'script', url: toUrlString(link.href) })
500
+ const as = normaliseAttrValue(link.as).toLowerCase() || 'script'
501
+ if (as === 'style')
502
+ result.push({ type: 'style', url: toUrlString(link.href) })
503
+ else if (SCRIPT_LIKE_MODULE_PRELOAD_AS_VALUES.has(as))
504
+ result.push({ type: 'script', url: toUrlString(link.href) })
469
505
  } else if (hasRel(link, 'preload') && link.href) {
470
506
  if (attrEquals(link.as, 'script'))
471
507
  result.push({ type: 'script', url: toUrlString(link.href) })
@@ -538,7 +574,7 @@ export function preloadImage(
538
574
 
539
575
  export function modulepreload(
540
576
  href: string | URL,
541
- options: ResourceHintOptions = {}
577
+ options: ModulePreloadOptions = {}
542
578
  ): LinkItem {
543
579
  return { ...options, rel: 'modulepreload', href: toUrlString(href) }
544
580
  }
@@ -658,7 +694,10 @@ export function validateHeadItems(
658
694
 
659
695
  if (
660
696
  validationOptions.requireDescription &&
661
- !items.meta.some((meta) => attrEquals(meta.name, 'description'))
697
+ !items.meta.some(
698
+ (meta) =>
699
+ attrEquals(meta.name, 'description') && hasNonEmptyAttr(meta, 'content')
700
+ )
662
701
  ) {
663
702
  issues.push({
664
703
  code: 'missing-description',
@@ -687,6 +726,7 @@ function validateMetaItems(
687
726
  options: HeadValidationOptions
688
727
  ): void {
689
728
  const ogProperties = new Set<string>()
729
+ const populatedOgProperties = new Set<string>()
690
730
 
691
731
  metaItems.forEach((meta, index) => {
692
732
  validateUnsafeAttributes(meta, 'meta', `meta[${index}]`, issues, options)
@@ -694,7 +734,10 @@ function validateMetaItems(
694
734
  const name = normaliseAttrValue(meta.name).toLowerCase()
695
735
  const content = normaliseAttrValue(meta.content)
696
736
 
697
- if (property.startsWith('og:')) ogProperties.add(property)
737
+ if (property.startsWith('og:')) {
738
+ ogProperties.add(property)
739
+ if (content) populatedOgProperties.add(property)
740
+ }
698
741
 
699
742
  const ogUrlValid =
700
743
  property === 'og:url'
@@ -748,7 +791,8 @@ function validateMetaItems(
748
791
 
749
792
  const hasActiveOpenGraph =
750
793
  ogProperties.size > 1 ||
751
- [...ogProperties].some((property) => property !== 'og:type')
794
+ [...ogProperties].some((property) => property !== 'og:type') ||
795
+ (ogProperties.has('og:type') && !populatedOgProperties.has('og:type'))
752
796
 
753
797
  if (hasActiveOpenGraph) {
754
798
  const requiredProperties = [
@@ -758,7 +802,7 @@ function validateMetaItems(
758
802
  ...(options.requireOpenGraphImage ? ['og:image'] : [])
759
803
  ]
760
804
  for (const property of requiredProperties) {
761
- if (!ogProperties.has(property)) {
805
+ if (!populatedOgProperties.has(property)) {
762
806
  issues.push({
763
807
  code: 'missing-og-required',
764
808
  severity: 'warning',
@@ -777,8 +821,6 @@ function validateLinkItems(
777
821
  options: HeadValidationOptions,
778
822
  hasNoindex: boolean
779
823
  ): void {
780
- let canonicalCount = 0
781
-
782
824
  linkItems.forEach((link, index) => {
783
825
  validateUnsafeAttributes(link, 'link', `link[${index}]`, issues, options)
784
826
  const rels = getRelTokens(link)
@@ -786,16 +828,33 @@ function validateLinkItems(
786
828
  const path = `link[${index}]`
787
829
 
788
830
  if (rels.includes('canonical')) {
789
- canonicalCount += 1
790
- const hrefValid = validateUrlValue(href, 'link', path, issues, options)
791
- if (href && hrefValid && isRelativeUrl(href)) {
831
+ if (!href) {
792
832
  issues.push({
793
- code: 'relative-canonical',
833
+ code: 'invalid-url',
794
834
  severity: 'warning',
795
835
  tagName: 'link',
796
836
  path,
797
- message: 'Canonical links should be absolute URLs.'
837
+ message: 'Canonical links need a non-empty absolute HTTP(S) URL.'
798
838
  })
839
+ } else {
840
+ const hrefValid = validateUrlValue(href, 'link', path, issues, options)
841
+ if (hrefValid && isRelativeUrl(href)) {
842
+ issues.push({
843
+ code: 'relative-canonical',
844
+ severity: 'warning',
845
+ tagName: 'link',
846
+ path,
847
+ message: 'Canonical links should be absolute URLs.'
848
+ })
849
+ } else if (hrefValid && !isAbsoluteHttpUrl(href)) {
850
+ issues.push({
851
+ code: 'invalid-url',
852
+ severity: 'warning',
853
+ tagName: 'link',
854
+ path,
855
+ message: 'Canonical links must use an absolute HTTP(S) URL.'
856
+ })
857
+ }
799
858
  }
800
859
 
801
860
  if (hasNoindex) {
@@ -832,13 +891,16 @@ function validateLinkItems(
832
891
  if (rels.includes('preload')) validatePreload(link, issues, path)
833
892
 
834
893
  if (rels.includes('modulepreload') && hasNonEmptyAttr(link, 'as')) {
835
- issues.push({
836
- code: 'modulepreload-with-as',
837
- severity: 'warning',
838
- tagName: 'link',
839
- path,
840
- message: 'modulepreload does not use an as attribute.'
841
- })
894
+ const as = normaliseAttrValue(link.as).toLowerCase()
895
+ if (!VALID_MODULE_PRELOAD_AS_VALUES.has(as)) {
896
+ issues.push({
897
+ code: 'invalid-modulepreload-as',
898
+ severity: 'warning',
899
+ tagName: 'link',
900
+ path,
901
+ message: `modulepreload as="${as}" is not a standard destination.`
902
+ })
903
+ }
842
904
  }
843
905
 
844
906
  validateSubresourceIntegrity(
@@ -850,16 +912,6 @@ function validateLinkItems(
850
912
  isSriRelevantLink(link)
851
913
  )
852
914
  })
853
-
854
- if (canonicalCount > 1) {
855
- issues.push({
856
- code: 'duplicate-canonical',
857
- severity: 'warning',
858
- tagName: 'link',
859
- path: 'link[rel="canonical"]',
860
- message: 'Multiple canonical links were provided; the last one wins.'
861
- })
862
- }
863
915
  }
864
916
 
865
917
  function validatePreload(
@@ -937,7 +989,6 @@ function validateScriptItems(
937
989
  ): void {
938
990
  scriptItems.forEach((script, index) => {
939
991
  const path = `script[${index}]`
940
- validateUnsafeAttributes(script, 'script', path, issues, options)
941
992
  validateSubresourceIntegrity(script, 'script', path, issues, options, true)
942
993
  })
943
994
  }
@@ -951,6 +1002,20 @@ function validateContentItems(
951
1002
  items.forEach((item, index) => {
952
1003
  const path = `${tagName}[${index}]`
953
1004
  validateUnsafeAttributes(item, tagName, path, issues, options)
1005
+ if (
1006
+ tagName === 'script' &&
1007
+ item.textContent !== undefined &&
1008
+ hasUnsafeScriptTextContent(String(item.textContent))
1009
+ ) {
1010
+ issues.push({
1011
+ code: 'unsafe-script-text',
1012
+ severity: 'error',
1013
+ tagName,
1014
+ path,
1015
+ message:
1016
+ 'script.textContent contains an HTML parser sequence that can consume the rest of the document. Use an external script instead.'
1017
+ })
1018
+ }
954
1019
  if (options.warnOnInnerHTML !== false && item.innerHTML !== undefined) {
955
1020
  issues.push({
956
1021
  code: 'unsafe-inner-html',
@@ -1342,6 +1407,15 @@ function isRelativeUrl(value: string): boolean {
1342
1407
  }
1343
1408
  }
1344
1409
 
1410
+ function isAbsoluteHttpUrl(value: string): boolean {
1411
+ try {
1412
+ const url = new URL(value)
1413
+ return url.protocol === 'http:' || url.protocol === 'https:'
1414
+ } catch {
1415
+ return false
1416
+ }
1417
+ }
1418
+
1345
1419
  function isExternalHttpUrl(value: string, baseUrl?: string | URL): boolean {
1346
1420
  let url: URL
1347
1421
  try {
@@ -1361,7 +1435,7 @@ function isExternalHttpUrl(value: string, baseUrl?: string | URL): boolean {
1361
1435
  }
1362
1436
 
1363
1437
  function escapeJsonLd(json: string): string {
1364
- return json.replace(/<\//gi, '<\\/')
1438
+ return json.replace(/</g, '\\u003c')
1365
1439
  }
1366
1440
 
1367
1441
  function deduplicateMetaItems(metaItems: BaseItem[]): BaseItem[] {
@@ -1526,9 +1600,18 @@ function getTagContent(item: BaseItem | ContentItem): string {
1526
1600
  }
1527
1601
 
1528
1602
  function escapeRawText(content: string, tagName: 'script' | 'style'): string {
1603
+ if (tagName === 'script' && hasUnsafeScriptTextContent(content)) {
1604
+ throw new Error(
1605
+ 'script.textContent contains an HTML parser sequence that can consume the rest of the document. Use an external script or trusted innerHTML instead.'
1606
+ )
1607
+ }
1529
1608
  return content.replace(new RegExp(`</${tagName}`, 'gi'), `<\\/${tagName}`)
1530
1609
  }
1531
1610
 
1611
+ function hasUnsafeScriptTextContent(content: string): boolean {
1612
+ return /<!--[\s\S]*<script(?=[\t\n\f />])/i.test(content)
1613
+ }
1614
+
1532
1615
  function hasAttr(item: BaseItem | ContentItem, key: string): boolean {
1533
1616
  return item[key] !== null && item[key] !== undefined
1534
1617
  }