tempest-react-sdk 0.75.0 → 0.77.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.
Files changed (147) hide show
  1. package/README.md +4 -2
  2. package/bin/create-tempest-app.e2e.test.mjs +112 -0
  3. package/bin/create-tempest-app.mjs +69 -28
  4. package/bin/lib/component/generate.mjs +191 -0
  5. package/bin/lib/component/generate.test.mjs +336 -0
  6. package/bin/lib/openapi/escape.mjs +210 -0
  7. package/bin/lib/openapi/generate.hostile.test.mjs +592 -0
  8. package/bin/lib/openapi/generate.mjs +93 -17
  9. package/bin/lib/openapi/schema-to-zod.mjs +41 -4
  10. package/bin/tempest.mjs +184 -3
  11. package/dist/auth/create-tempest-auth.cjs +1 -1
  12. package/dist/auth/create-tempest-auth.cjs.map +1 -1
  13. package/dist/auth/create-tempest-auth.js +127 -55
  14. package/dist/auth/create-tempest-auth.js.map +1 -1
  15. package/dist/auth/refresh-queue.cjs +1 -1
  16. package/dist/auth/refresh-queue.cjs.map +1 -1
  17. package/dist/auth/refresh-queue.js +13 -6
  18. package/dist/auth/refresh-queue.js.map +1 -1
  19. package/dist/br/pix.cjs +1 -1
  20. package/dist/br/pix.cjs.map +1 -1
  21. package/dist/br/pix.js +72 -62
  22. package/dist/br/pix.js.map +1 -1
  23. package/dist/br.d.ts +12 -4
  24. package/dist/components/Chat/ChatAttachments.cjs +1 -1
  25. package/dist/components/Chat/ChatAttachments.cjs.map +1 -1
  26. package/dist/components/Chat/ChatAttachments.js +46 -38
  27. package/dist/components/Chat/ChatAttachments.js.map +1 -1
  28. package/dist/components/Markdown/markdown-parse.cjs +7 -5
  29. package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
  30. package/dist/components/Markdown/markdown-parse.js +151 -87
  31. package/dist/components/Markdown/markdown-parse.js.map +1 -1
  32. package/dist/components/Toast/Toast.module.cjs +1 -1
  33. package/dist/components/Toast/Toast.module.cjs.map +1 -1
  34. package/dist/components/Toast/Toast.module.js +7 -3
  35. package/dist/components/Toast/Toast.module.js.map +1 -1
  36. package/dist/components/Toast/ToastProvider.cjs +1 -1
  37. package/dist/components/Toast/ToastProvider.cjs.map +1 -1
  38. package/dist/components/Toast/ToastProvider.js +77 -51
  39. package/dist/components/Toast/ToastProvider.js.map +1 -1
  40. package/dist/data/create-data-provider.cjs +1 -1
  41. package/dist/data/create-data-provider.cjs.map +1 -1
  42. package/dist/data/create-data-provider.js +32 -21
  43. package/dist/data/create-data-provider.js.map +1 -1
  44. package/dist/http/api-client.cjs +1 -1
  45. package/dist/http/api-client.cjs.map +1 -1
  46. package/dist/http/api-client.js +81 -73
  47. package/dist/http/api-client.js.map +1 -1
  48. package/dist/http/errors.cjs +1 -1
  49. package/dist/http/errors.cjs.map +1 -1
  50. package/dist/http/errors.js +39 -35
  51. package/dist/http/errors.js.map +1 -1
  52. package/dist/neural.cjs +2 -0
  53. package/dist/neural.cjs.map +1 -0
  54. package/dist/neural.d.ts +110 -0
  55. package/dist/neural.js +48 -0
  56. package/dist/neural.js.map +1 -0
  57. package/dist/oauth/callback.cjs +2 -0
  58. package/dist/oauth/callback.cjs.map +1 -0
  59. package/dist/oauth/callback.js +42 -0
  60. package/dist/oauth/callback.js.map +1 -0
  61. package/dist/oauth/use-oauth-callback.cjs +1 -1
  62. package/dist/oauth/use-oauth-callback.cjs.map +1 -1
  63. package/dist/oauth/use-oauth-callback.js +13 -20
  64. package/dist/oauth/use-oauth-callback.js.map +1 -1
  65. package/dist/push/use-push-subscription.cjs +1 -1
  66. package/dist/push/use-push-subscription.cjs.map +1 -1
  67. package/dist/push/use-push-subscription.js +42 -42
  68. package/dist/push/use-push-subscription.js.map +1 -1
  69. package/dist/push/web-push-client.cjs +1 -1
  70. package/dist/push/web-push-client.cjs.map +1 -1
  71. package/dist/push/web-push-client.js +23 -3
  72. package/dist/push/web-push-client.js.map +1 -1
  73. package/dist/query/offline-persistence.cjs +1 -1
  74. package/dist/query/offline-persistence.cjs.map +1 -1
  75. package/dist/query/offline-persistence.js +68 -23
  76. package/dist/query/offline-persistence.js.map +1 -1
  77. package/dist/styles/component/Toast.css +6 -1
  78. package/dist/styles/feedback.css +6 -1
  79. package/dist/styles.css +1 -1
  80. package/dist/sw/background-sync.cjs +1 -1
  81. package/dist/sw/background-sync.cjs.map +1 -1
  82. package/dist/sw/background-sync.js +271 -60
  83. package/dist/sw/background-sync.js.map +1 -1
  84. package/dist/sw/cache-inspect.cjs.map +1 -1
  85. package/dist/sw/cache-inspect.js.map +1 -1
  86. package/dist/sw/cache.cjs +1 -1
  87. package/dist/sw/cache.cjs.map +1 -1
  88. package/dist/sw/cache.js +91 -64
  89. package/dist/sw/cache.js.map +1 -1
  90. package/dist/sw/credential-headers.cjs +2 -0
  91. package/dist/sw/credential-headers.cjs.map +1 -0
  92. package/dist/sw/credential-headers.js +17 -0
  93. package/dist/sw/credential-headers.js.map +1 -0
  94. package/dist/sw/session-data.cjs +2 -0
  95. package/dist/sw/session-data.cjs.map +1 -0
  96. package/dist/sw/session-data.js +17 -0
  97. package/dist/sw/session-data.js.map +1 -0
  98. package/dist/sw.cjs +1 -1
  99. package/dist/sw.d.ts +271 -23
  100. package/dist/sw.js +7 -5
  101. package/dist/telemetry/app-error-owner.cjs +2 -0
  102. package/dist/telemetry/app-error-owner.cjs.map +1 -0
  103. package/dist/telemetry/app-error-owner.js +18 -0
  104. package/dist/telemetry/app-error-owner.js.map +1 -0
  105. package/dist/telemetry/app-error-queue.cjs +1 -1
  106. package/dist/telemetry/app-error-queue.cjs.map +1 -1
  107. package/dist/telemetry/app-error-queue.js +19 -14
  108. package/dist/telemetry/app-error-queue.js.map +1 -1
  109. package/dist/telemetry/app-error-reporter.cjs +1 -1
  110. package/dist/telemetry/app-error-reporter.cjs.map +1 -1
  111. package/dist/telemetry/app-error-reporter.js +75 -34
  112. package/dist/telemetry/app-error-reporter.js.map +1 -1
  113. package/dist/telemetry/app-error-transport.cjs +1 -1
  114. package/dist/telemetry/app-error-transport.cjs.map +1 -1
  115. package/dist/telemetry/app-error-transport.js +16 -3
  116. package/dist/telemetry/app-error-transport.js.map +1 -1
  117. package/dist/tempest-react-sdk.cjs +1 -1
  118. package/dist/tempest-react-sdk.d.ts +979 -62
  119. package/dist/tempest-react-sdk.js +160 -156
  120. package/dist/utils/csv.cjs +3 -3
  121. package/dist/utils/csv.cjs.map +1 -1
  122. package/dist/utils/csv.js +16 -13
  123. package/dist/utils/csv.js.map +1 -1
  124. package/dist/utils/safe-url.cjs +2 -0
  125. package/dist/utils/safe-url.cjs.map +1 -0
  126. package/dist/utils/safe-url.js +39 -0
  127. package/dist/utils/safe-url.js.map +1 -0
  128. package/dist/vite/tempest-csp.cjs +2 -2
  129. package/dist/vite/tempest-csp.cjs.map +1 -1
  130. package/dist/vite/tempest-csp.js +118 -63
  131. package/dist/vite/tempest-csp.js.map +1 -1
  132. package/dist/vite.d.ts +21 -5
  133. package/dist/webrtc/peer-link.cjs +1 -1
  134. package/dist/webrtc/peer-link.cjs.map +1 -1
  135. package/dist/webrtc/peer-link.js +2 -10
  136. package/dist/webrtc/peer-link.js.map +1 -1
  137. package/dist/webrtc/peer-mesh.cjs +1 -1
  138. package/dist/webrtc/peer-mesh.cjs.map +1 -1
  139. package/dist/webrtc/peer-mesh.js +110 -72
  140. package/dist/webrtc/peer-mesh.js.map +1 -1
  141. package/package.json +11 -1
  142. package/template-pwa/src/pwa.tsx +22 -0
  143. package/template-pwa/src/sw.ts +27 -14
  144. package/dist/components/Markdown/markdown-url.cjs +0 -2
  145. package/dist/components/Markdown/markdown-url.cjs.map +0 -1
  146. package/dist/components/Markdown/markdown-url.js +0 -28
  147. package/dist/components/Markdown/markdown-url.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"safe-url.cjs","names":[],"sources":["../../src/utils/safe-url.ts"],"sourcesContent":["/**\n * URL vetting for every `href` and `src` the SDK fills from somebody else's data:\n * links and images in rendered Markdown, and the file row of a chat attachment.\n *\n * This is a security boundary. Text that arrives from a user — a comment, a ticket\n * description, a chat attachment — reaches the DOM as a real `href`, and\n * `javascript:alert(1)` in a link is script execution on click. React 19 replaces\n * a `javascript:` href with a throwing stub, but the peer range admits React 18,\n * which only warns: measured with react-dom 18.3.1, `renderToStaticMarkup` wrote\n * `href=\"javascript:...\"` verbatim, and clicking it ran the script in Chromium 153\n * and Firefox 155 — `download` on the anchor did not stop it (#447). So the\n * scheme is checked against an allowlist rather than a blocklist: a blocklist has\n * to enumerate `javascript:`, `JaVaScRiPt:`, `java\\tscript:`, `&#106;avascript:`\n * and whatever comes next, and misses the one nobody thought of.\n */\n\n/** Schemes a link may use. Anything else is dropped. */\nconst LINK_SCHEMES = new Set([\"http:\", \"https:\", \"mailto:\", \"tel:\", \"sms:\"]);\n\n/**\n * Schemes a fetched resource — an attachment, a download — may use.\n *\n * `blob:` is here because an app shows a message while its upload is still in\n * flight by pointing at `URL.createObjectURL(file)`. A blob URL is same-origin\n * bytes the page already holds; it cannot run code by being followed.\n */\nconst RESOURCE_SCHEMES = new Set([\"http:\", \"https:\", \"blob:\"]);\n\n/**\n * Image `data:` types that are safe to inline.\n *\n * `svg+xml` is deliberately absent: an SVG is a document, it can carry `<script>`\n * and event handlers, and browsers execute them when it loads from a `data:` URL in\n * some contexts. The raster formats cannot carry code.\n */\nconst IMAGE_DATA_TYPES = /^data:image\\/(png|jpe?g|gif|webp|avif|bmp);base64,[a-z0-9+/=\\s]+$/i;\n\n/**\n * Strip the characters a scheme can be smuggled through.\n *\n * `java\\tscript:` and `java\\nscript:` are both parsed as `javascript:` by browsers,\n * and a leading control character defeats a naive `startsWith` check.\n */\nfunction normalize(raw: string): string {\n // eslint-disable-next-line no-control-regex -- stripping control characters is the point\n return raw.replace(/[\\u0000-\\u0020\\u007F]/g, \"\").trim();\n}\n\n/**\n * The scheme of a normalized URL, lower-cased with its colon, or `null` for a\n * relative URL.\n */\nfunction schemeOf(url: string): string | null {\n if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) return null;\n return url.slice(0, url.indexOf(\":\") + 1).toLowerCase();\n}\n\n/**\n * The href to render, or `null` when the URL must not be linked.\n *\n * Relative URLs (`/docs`, `./x`, `#anchor`, `foo/bar`) are kept: they cannot carry\n * a scheme, so they cannot execute anything, and dropping them would break every\n * in-app link. Protocol-relative (`//host/path`) inherits the page scheme and is\n * kept for the same reason.\n *\n * @example\n * safeLinkUrl(\"https://x.dev\"); // \"https://x.dev\"\n * safeLinkUrl(\"java\\tscript:alert(1)\"); // null\n *\n * @param raw - URL as written in the Markdown.\n * @returns A safe href, or `null`.\n */\nexport function safeLinkUrl(raw: string): string | null {\n const url = normalize(raw);\n if (!url) return null;\n const scheme = schemeOf(url);\n return scheme === null || LINK_SCHEMES.has(scheme) ? url : null;\n}\n\n/**\n * The `src` to render for an image, or `null`.\n *\n * Accepts what {@link safeLinkUrl} accepts, plus raster `data:image/...;base64`.\n *\n * @example\n * safeImageUrl(\"data:image/png;base64,iVBORw0KGgo=\"); // kept\n * safeImageUrl(\"data:image/svg+xml;base64,PHN2Zz4=\"); // null\n *\n * @param raw - URL as written in the Markdown.\n * @returns A safe src, or `null`.\n */\nexport function safeImageUrl(raw: string): string | null {\n const url = normalize(raw);\n if (!url) return null;\n if (IMAGE_DATA_TYPES.test(url)) return url;\n if (/^data:/i.test(url)) return null;\n return safeLinkUrl(url);\n}\n\n/**\n * The URL to fetch or download an attachment from, or `null`.\n *\n * The allowlist is `http:`, `https:`, `blob:`, relative URLs and the raster\n * `data:image/` types {@link safeImageUrl} accepts. A file row is an `<a href\n * download>`, and the `download` attribute does not stop a `javascript:` href\n * from running (measured in Chromium 153 and Firefox 155, #447), so the scheme\n * has to be checked before the anchor exists. `mailto:`/`tel:` are left out: an\n * attachment is bytes, not a contact.\n *\n * The scheme is judged on the normalized form, but the URL comes back **as given**:\n * normalizing deletes every space, and `/files/relatório final.pdf` is a real\n * attachment path. Returning the original is safe because the normalization only\n * removes characters, a superset of what the browser's URL parser strips, so it\n * can never hide a scheme the browser would see.\n *\n * @example\n * const href = safeAttachmentUrl(attachment.url);\n * return href ? <a href={href} download>{name}</a> : <span>{name}</span>;\n *\n * @param raw - URL as the sender supplied it.\n * @returns A safe URL, or `null` when it must not reach an `href`.\n */\nexport function safeAttachmentUrl(raw: string): string | null {\n const url = normalize(raw);\n if (!url) return null;\n if (IMAGE_DATA_TYPES.test(url)) return raw;\n const scheme = schemeOf(url);\n return scheme === null || RESOURCE_SCHEMES.has(scheme) ? raw : null;\n}\n"],"mappings":"AAiBA,IAAM,EAAe,IAAI,IAAI,CAAC,QAAS,SAAU,UAAW,OAAQ,MAAM,CAAC,EASrE,EAAmB,IAAI,IAAI,CAAC,QAAS,SAAU,OAAO,CAAC,EASvD,EAAmB,qEAQzB,SAAS,EAAU,EAAqB,CAEpC,OAAO,EAAI,QAAQ,yBAA0B,EAAE,CAAC,CAAC,KAAK,CAC1D,CAMA,SAAS,EAAS,EAA4B,CAE1C,MADK,uBAAuB,KAAK,CAAG,EAC7B,EAAI,MAAM,EAAG,EAAI,QAAQ,GAAG,EAAI,CAAC,CAAC,CAAC,YAAY,EADR,IAElD,CAiBA,SAAgB,EAAY,EAA4B,CACpD,IAAM,EAAM,EAAU,CAAG,EACzB,GAAI,CAAC,EAAK,OAAO,KACjB,IAAM,EAAS,EAAS,CAAG,EAC3B,OAAO,IAAW,MAAQ,EAAa,IAAI,CAAM,EAAI,EAAM,IAC/D,CAcA,SAAgB,EAAa,EAA4B,CACrD,IAAM,EAAM,EAAU,CAAG,EAIzB,OAHK,EACD,EAAiB,KAAK,CAAG,EAAU,EACnC,UAAU,KAAK,CAAG,EAAU,KACzB,EAAY,CAAG,EAHL,IAIrB,CAyBA,SAAgB,EAAkB,EAA4B,CAC1D,IAAM,EAAM,EAAU,CAAG,EACzB,GAAI,CAAC,EAAK,OAAO,KACjB,GAAI,EAAiB,KAAK,CAAG,EAAG,OAAO,EACvC,IAAM,EAAS,EAAS,CAAG,EAC3B,OAAO,IAAW,MAAQ,EAAiB,IAAI,CAAM,EAAI,EAAM,IACnE"}
@@ -0,0 +1,39 @@
1
+ //#region src/utils/safe-url.ts
2
+ var e = /* @__PURE__ */ new Set([
3
+ "http:",
4
+ "https:",
5
+ "mailto:",
6
+ "tel:",
7
+ "sms:"
8
+ ]), t = /* @__PURE__ */ new Set([
9
+ "http:",
10
+ "https:",
11
+ "blob:"
12
+ ]), n = /^data:image\/(png|jpe?g|gif|webp|avif|bmp);base64,[a-z0-9+/=\s]+$/i;
13
+ function r(e) {
14
+ return e.replace(/[\u0000-\u0020\u007F]/g, "").trim();
15
+ }
16
+ function i(e) {
17
+ return /^[a-z][a-z0-9+.-]*:/i.test(e) ? e.slice(0, e.indexOf(":") + 1).toLowerCase() : null;
18
+ }
19
+ function a(t) {
20
+ let n = r(t);
21
+ if (!n) return null;
22
+ let a = i(n);
23
+ return a === null || e.has(a) ? n : null;
24
+ }
25
+ function o(e) {
26
+ let t = r(e);
27
+ return t ? n.test(t) ? t : /^data:/i.test(t) ? null : a(t) : null;
28
+ }
29
+ function s(e) {
30
+ let a = r(e);
31
+ if (!a) return null;
32
+ if (n.test(a)) return e;
33
+ let o = i(a);
34
+ return o === null || t.has(o) ? e : null;
35
+ }
36
+ //#endregion
37
+ export { s as safeAttachmentUrl, o as safeImageUrl, a as safeLinkUrl };
38
+
39
+ //# sourceMappingURL=safe-url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"safe-url.js","names":[],"sources":["../../src/utils/safe-url.ts"],"sourcesContent":["/**\n * URL vetting for every `href` and `src` the SDK fills from somebody else's data:\n * links and images in rendered Markdown, and the file row of a chat attachment.\n *\n * This is a security boundary. Text that arrives from a user — a comment, a ticket\n * description, a chat attachment — reaches the DOM as a real `href`, and\n * `javascript:alert(1)` in a link is script execution on click. React 19 replaces\n * a `javascript:` href with a throwing stub, but the peer range admits React 18,\n * which only warns: measured with react-dom 18.3.1, `renderToStaticMarkup` wrote\n * `href=\"javascript:...\"` verbatim, and clicking it ran the script in Chromium 153\n * and Firefox 155 — `download` on the anchor did not stop it (#447). So the\n * scheme is checked against an allowlist rather than a blocklist: a blocklist has\n * to enumerate `javascript:`, `JaVaScRiPt:`, `java\\tscript:`, `&#106;avascript:`\n * and whatever comes next, and misses the one nobody thought of.\n */\n\n/** Schemes a link may use. Anything else is dropped. */\nconst LINK_SCHEMES = new Set([\"http:\", \"https:\", \"mailto:\", \"tel:\", \"sms:\"]);\n\n/**\n * Schemes a fetched resource — an attachment, a download — may use.\n *\n * `blob:` is here because an app shows a message while its upload is still in\n * flight by pointing at `URL.createObjectURL(file)`. A blob URL is same-origin\n * bytes the page already holds; it cannot run code by being followed.\n */\nconst RESOURCE_SCHEMES = new Set([\"http:\", \"https:\", \"blob:\"]);\n\n/**\n * Image `data:` types that are safe to inline.\n *\n * `svg+xml` is deliberately absent: an SVG is a document, it can carry `<script>`\n * and event handlers, and browsers execute them when it loads from a `data:` URL in\n * some contexts. The raster formats cannot carry code.\n */\nconst IMAGE_DATA_TYPES = /^data:image\\/(png|jpe?g|gif|webp|avif|bmp);base64,[a-z0-9+/=\\s]+$/i;\n\n/**\n * Strip the characters a scheme can be smuggled through.\n *\n * `java\\tscript:` and `java\\nscript:` are both parsed as `javascript:` by browsers,\n * and a leading control character defeats a naive `startsWith` check.\n */\nfunction normalize(raw: string): string {\n // eslint-disable-next-line no-control-regex -- stripping control characters is the point\n return raw.replace(/[\\u0000-\\u0020\\u007F]/g, \"\").trim();\n}\n\n/**\n * The scheme of a normalized URL, lower-cased with its colon, or `null` for a\n * relative URL.\n */\nfunction schemeOf(url: string): string | null {\n if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) return null;\n return url.slice(0, url.indexOf(\":\") + 1).toLowerCase();\n}\n\n/**\n * The href to render, or `null` when the URL must not be linked.\n *\n * Relative URLs (`/docs`, `./x`, `#anchor`, `foo/bar`) are kept: they cannot carry\n * a scheme, so they cannot execute anything, and dropping them would break every\n * in-app link. Protocol-relative (`//host/path`) inherits the page scheme and is\n * kept for the same reason.\n *\n * @example\n * safeLinkUrl(\"https://x.dev\"); // \"https://x.dev\"\n * safeLinkUrl(\"java\\tscript:alert(1)\"); // null\n *\n * @param raw - URL as written in the Markdown.\n * @returns A safe href, or `null`.\n */\nexport function safeLinkUrl(raw: string): string | null {\n const url = normalize(raw);\n if (!url) return null;\n const scheme = schemeOf(url);\n return scheme === null || LINK_SCHEMES.has(scheme) ? url : null;\n}\n\n/**\n * The `src` to render for an image, or `null`.\n *\n * Accepts what {@link safeLinkUrl} accepts, plus raster `data:image/...;base64`.\n *\n * @example\n * safeImageUrl(\"data:image/png;base64,iVBORw0KGgo=\"); // kept\n * safeImageUrl(\"data:image/svg+xml;base64,PHN2Zz4=\"); // null\n *\n * @param raw - URL as written in the Markdown.\n * @returns A safe src, or `null`.\n */\nexport function safeImageUrl(raw: string): string | null {\n const url = normalize(raw);\n if (!url) return null;\n if (IMAGE_DATA_TYPES.test(url)) return url;\n if (/^data:/i.test(url)) return null;\n return safeLinkUrl(url);\n}\n\n/**\n * The URL to fetch or download an attachment from, or `null`.\n *\n * The allowlist is `http:`, `https:`, `blob:`, relative URLs and the raster\n * `data:image/` types {@link safeImageUrl} accepts. A file row is an `<a href\n * download>`, and the `download` attribute does not stop a `javascript:` href\n * from running (measured in Chromium 153 and Firefox 155, #447), so the scheme\n * has to be checked before the anchor exists. `mailto:`/`tel:` are left out: an\n * attachment is bytes, not a contact.\n *\n * The scheme is judged on the normalized form, but the URL comes back **as given**:\n * normalizing deletes every space, and `/files/relatório final.pdf` is a real\n * attachment path. Returning the original is safe because the normalization only\n * removes characters, a superset of what the browser's URL parser strips, so it\n * can never hide a scheme the browser would see.\n *\n * @example\n * const href = safeAttachmentUrl(attachment.url);\n * return href ? <a href={href} download>{name}</a> : <span>{name}</span>;\n *\n * @param raw - URL as the sender supplied it.\n * @returns A safe URL, or `null` when it must not reach an `href`.\n */\nexport function safeAttachmentUrl(raw: string): string | null {\n const url = normalize(raw);\n if (!url) return null;\n if (IMAGE_DATA_TYPES.test(url)) return raw;\n const scheme = schemeOf(url);\n return scheme === null || RESOURCE_SCHEMES.has(scheme) ? raw : null;\n}\n"],"mappings":";AAiBA,IAAM,oBAAe,IAAI,IAAI;CAAC;CAAS;CAAU;CAAW;CAAQ;AAAM,CAAC,GASrE,oBAAmB,IAAI,IAAI;CAAC;CAAS;CAAU;AAAO,CAAC,GASvD,IAAmB;AAQzB,SAAS,EAAU,GAAqB;CAEpC,OAAO,EAAI,QAAQ,0BAA0B,EAAE,CAAC,CAAC,KAAK;AAC1D;AAMA,SAAS,EAAS,GAA4B;CAE1C,OADK,uBAAuB,KAAK,CAAG,IAC7B,EAAI,MAAM,GAAG,EAAI,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,IADR;AAElD;AAiBA,SAAgB,EAAY,GAA4B;CACpD,IAAM,IAAM,EAAU,CAAG;CACzB,IAAI,CAAC,GAAK,OAAO;CACjB,IAAM,IAAS,EAAS,CAAG;CAC3B,OAAO,MAAW,QAAQ,EAAa,IAAI,CAAM,IAAI,IAAM;AAC/D;AAcA,SAAgB,EAAa,GAA4B;CACrD,IAAM,IAAM,EAAU,CAAG;CAIzB,OAHK,IACD,EAAiB,KAAK,CAAG,IAAU,IACnC,UAAU,KAAK,CAAG,IAAU,OACzB,EAAY,CAAG,IAHL;AAIrB;AAyBA,SAAgB,EAAkB,GAA4B;CAC1D,IAAM,IAAM,EAAU,CAAG;CACzB,IAAI,CAAC,GAAK,OAAO;CACjB,IAAI,EAAiB,KAAK,CAAG,GAAG,OAAO;CACvC,IAAM,IAAS,EAAS,CAAG;CAC3B,OAAO,MAAW,QAAQ,EAAiB,IAAI,CAAM,IAAI,IAAM;AACnE"}
@@ -1,3 +1,3 @@
1
- let e=require("node:crypto");var t=new Set([`frame-ancestors`,`report-uri`,`sandbox`]),n=[{module:/[\\/]forms[\\/]use-viacep\.(?:[cm]?js|tsx?)$/,origin:`https://viacep.com.br`,from:`tempest-react-sdk useViaCEP`}],r=/^(?:https?|wss?):\/\//i,i=/^((?:https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?)(?:[/?#].*)?$/i;function a(e,t){let n=e.trim();if(n.startsWith(`/`)&&!n.startsWith(`//`))return;let a=i.exec(n);if(a)return a[1].toLowerCase();if(r.test(n))try{let e=new URL(n);return`${e.protocol}//${e.host}`}catch{throw Error(`tempestCsp: ${t} is not a valid URL: "${e}"`)}throw Error(`tempestCsp: ${t} must be an absolute http(s)/ws(s) URL or a root-relative path, got "${e}"`)}function o(e){let t={};for(let n of e.split(`;`)){let[e,...r]=n.trim().split(/\s+/);if(!e)continue;let i=e.toLowerCase();i in t||(t[i]=r)}return t}function s(e,n){return Object.entries(e).filter(([e])=>n===`header`||!t.has(e)).map(([e,t])=>[e,...t].join(` `)).join(`; `)}function c(e,t){let n=e.filter(e=>e!==`'none'`||t.length===0);for(let e of t)n.includes(e)||n.push(e);return n.length===0?[`'none'`]:n}function l(t){return`'sha256-${(0,e.createHash)(`sha256`).update(t,`utf8`).digest(`base64`)}'`}function u(e){return e.replace(/&#39;|&#x27;|&apos;/gi,`'`).replace(/&quot;/gi,`"`).replace(/&amp;/gi,`&`)}function d(e){let t={};for(let n of e.matchAll(/([^\s=<>/]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g))t[n[1].toLowerCase()]=u(n[2]??n[3]??n[4]??``);return t}function f(e){let t=[...e.matchAll(/<meta\b[^>]*>/gi)].filter(e=>d(e[0])[`http-equiv`]?.toLowerCase()===`content-security-policy`);if(t.length===0)return{html:e};if(t.length>1)throw Error(`tempestCsp: index.html declares more than one Content-Security-Policy <meta>; merge them into one`);let n=t[0];return{html:e.slice(0,n.index)+e.slice(n.index+n[0].length).replace(/^[ \t]*\r?\n/,``),declared:o(d(n[0]).content??``)}}function p(e,t){let n=RegExp(`<${t}\\b([^>]*)>([\\s\\S]*?)</${t}>`,`gi`),r=[];for(let i of e.matchAll(n)){let e=d(`<x ${i[1]}>`);if(t===`script`&&`src`in e||i[2].length===0)continue;let n=l(i[2]);r.includes(n)||r.push(n)}return r}function m(e,t){let n=`<meta http-equiv="Content-Security-Policy" content="${t.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`)}" />`,r=/<meta\b[^>]*\bcharset\s*=[^>]*>/i.exec(e),i=/<head\b[^>]*>/i.exec(e),a=r!==null&&i!==null&&/<(?:script|link|style)\b/i.test(e.slice(i.index,r.index)),o=r&&i&&r.index>i.index&&!a?r:i;if(!o)return`${n}\n${e}`;let s=o.index+o[0].length;return`${e.slice(0,s)}\n ${n}${e.slice(s)}`}function h(e){let t=[];for(let n of Object.values(e.bundle??{}))n.type===`chunk`&&t.push(...n.moduleIds??Object.keys(n.modules??{}));return t}function g(e={}){let{connect:t=[],env:i=!0,sockets:o=!0,wasm:l=!0,inlineStyles:u=!0,directives:d={},dev:g=!0,log:_=!0,onPolicy:v}=e,y,b=[],x=``;function S(e,t,n){t===void 0||e.some(e=>e.origin===t)||e.push({origin:t,from:n})}function C(e){let n=[],o=e.env??{},s=[e.envPrefix??`VITE_`].flat();if(i===!0)for(let[e,t]of Object.entries(o))s.some(t=>e.startsWith(t))&&typeof t==`string`&&r.test(t.trim())&&S(n,a(t,`env ${e}`),`env ${e}`);else if(Array.isArray(i))for(let t of i){let r=o[t];if(typeof r!=`string`||r.trim()===``){e.logger.warn(`tempestCsp: env ${t} is empty — nothing added to connect-src`);continue}S(n,a(r,`env ${t}`),`env ${t}`)}return t.forEach((t,r)=>{if(!t||t.trim()===``){e.logger.warn(`tempestCsp: connect[${r}] is empty — skipped, nothing added to connect-src`);return}S(n,a(t,`connect[${r}]`),`connect[${r}]`)}),n}function w(e){let t=[...e];if(!o)return t;for(let{origin:n}of e){let e=n.replace(/^http(s?):/i,`ws$1:`);e!==n&&S(t,e,`sockets (${n})`)}return t}function T(e,t){let n=e?[`'self'`,e]:[`'self'`],r={"default-src":[...n],"script-src":l?[...n,`'wasm-unsafe-eval'`]:[...n],"style-src":u||t?[...n,`'unsafe-inline'`]:[...n],"img-src":[...n,`data:`,`blob:`],"font-src":[...n,`data:`],"media-src":[...n,`blob:`],"connect-src":[`'self'`,`blob:`,`data:`],"worker-src":[...n,`blob:`],"manifest-src":[...n],"object-src":[`'none'`],"base-uri":[`'self'`],"form-action":[`'self'`]};for(let[e,t]of Object.entries(d)){let n=e.toLowerCase();t===!1?delete r[n]:r[n]=c(r[n]??[],t)}return r}return{name:`tempest-csp`,configResolved(e){y=e,b=C(e)},transformIndexHtml:{order:`post`,handler(e,t){let i=y?.command===`serve`;if(i&&!g)return e;let o=w(b),l=y?.base??`/`,u=r.test(l)?a(l,`base`):void 0;u&&S(o,u,`base`);let d=i?[]:h(t);for(let e of n)(i||d.some(t=>e.module.test(t)))&&S(o,e.origin,e.from);let C=o,{html:E,declared:D={}}=f(e),O=T(u,i);`script-src`in D||(O[`script-src`]=c(O[`script-src`]??[],p(E,`script`))),!(`style-src`in D)&&!O[`style-src`]?.includes(`'unsafe-inline'`)&&(O[`style-src`]=c(O[`style-src`]??[],p(E,`style`)));let k={...O};for(let[e,t]of Object.entries(D))k[e]=t;k[`connect-src`]=c(k[`connect-src`]??[`'self'`],C.map(e=>e.origin));let A={directives:k,meta:s(k,`meta`),header:s(k,`header`),connect:C,command:i?`serve`:`build`};if(_&&y&&A.header!==x){x=A.header;let e=C.map(e=>` ${e.origin} ← ${e.from}`);y.logger.info([`tempest-csp: connect-src ${k[`connect-src`].join(` `)}`,...e.length>0?e:[` (no cross-origin endpoint: only 'self')`]].join(`
2
- `))}return v?.(A),m(E,A.meta)}}}}exports.cspOrigin=a,exports.parseCsp=o,exports.serializeCsp=s,exports.tempestCsp=g;
1
+ let e=require("node:crypto");var t=new Set([`frame-ancestors`,`report-uri`,`sandbox`]),n=[{module:/[\\/]forms[\\/]use-viacep\.(?:[cm]?js|tsx?)$/,origin:`https://viacep.com.br`,from:`tempest-react-sdk useViaCEP`}],r={"script-src-elem":[`script-src`,`default-src`],"script-src-attr":[`script-src`,`default-src`],"style-src-elem":[`style-src`,`default-src`],"style-src-attr":[`style-src`,`default-src`],"worker-src":[`child-src`,`script-src`,`default-src`],"frame-src":[`child-src`,`default-src`],"fenced-frame-src":[`frame-src`,`child-src`,`default-src`],"child-src":[`default-src`],"connect-src":[`default-src`],"font-src":[`default-src`],"img-src":[`default-src`],"manifest-src":[`default-src`],"media-src":[`default-src`],"object-src":[`default-src`],"prefetch-src":[`default-src`],"script-src":[`default-src`],"style-src":[`default-src`]};function i(e,t){for(let n of r[t]??[])if(n in e)return e[n]}var a=/^(?:https?|wss?):\/\//i,o=/^((?:https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?)(?:[/?#].*)?$/i;function s(e,t){let n=e.trim();if(n.startsWith(`/`)&&!n.startsWith(`//`))return;let r=o.exec(n);if(r)return r[1].toLowerCase();if(a.test(n))try{let e=new URL(n);return`${e.protocol}//${e.host}`}catch{throw Error(`tempestCsp: ${t} is not a valid URL: "${e}"`)}throw Error(`tempestCsp: ${t} must be an absolute http(s)/ws(s) URL or a root-relative path, got "${e}"`)}function c(e){let t={};for(let n of e.split(`;`)){let[e,...r]=n.trim().split(/\s+/);if(!e)continue;let i=e.toLowerCase();i in t||(t[i]=r)}return t}function l(e,n){return Object.entries(e).filter(([e])=>n===`header`||!t.has(e)).map(([e,t])=>[e,...t].join(` `)).join(`; `)}function u(e,t){let n=e.filter(e=>e!==`'none'`||t.length===0);for(let e of t)n.includes(e)||n.push(e);return n.length===0?[`'none'`]:n}function d(t){return`'sha256-${(0,e.createHash)(`sha256`).update(t,`utf8`).digest(`base64`)}'`}function f(e){return e.replace(/&#39;|&#x27;|&apos;/gi,`'`).replace(/&quot;/gi,`"`).replace(/&amp;/gi,`&`)}function p(e){let t={};for(let n of e.matchAll(/([^\s=<>/]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g))t[n[1].toLowerCase()]=f(n[2]??n[3]??n[4]??``);return t}function m(e){let t=[...e.matchAll(/<meta\b[^>]*>/gi)].filter(e=>p(e[0])[`http-equiv`]?.toLowerCase()===`content-security-policy`);if(t.length===0)return{html:e};if(t.length>1)throw Error(`tempestCsp: index.html declares more than one Content-Security-Policy <meta>; merge them into one`);let n=t[0];return{html:e.slice(0,n.index)+e.slice(n.index+n[0].length).replace(/^[ \t]*\r?\n/,``),declared:c(p(n[0]).content??``)}}function h(e,t){let n=RegExp(`<${t}\\b([^>]*)>([\\s\\S]*?)</${t}>`,`gi`),r=[];for(let i of e.matchAll(n)){let e=p(`<x ${i[1]}>`);if(t===`script`&&`src`in e||i[2].length===0)continue;let n=d(i[2]);r.includes(n)||r.push(n)}return r}function g(e,t){let n=`<meta http-equiv="Content-Security-Policy" content="${t.replace(/&/g,`&amp;`).replace(/"/g,`&quot;`)}" />`,r=/<meta\b[^>]*\bcharset\s*=[^>]*>/i.exec(e),i=/<head\b[^>]*>/i.exec(e),a=r!==null&&i!==null&&/<(?:script|link|style)\b/i.test(e.slice(i.index,r.index)),o=r&&i&&r.index>i.index&&!a?r:i;if(!o)return`${n}\n${e}`;let s=o.index+o[0].length;return`${e.slice(0,s)}\n ${n}${e.slice(s)}`}function _(e){let t=[];for(let n of Object.values(e.bundle??{}))n.type===`chunk`&&t.push(...n.moduleIds??Object.keys(n.modules??{}));return t}function v(e={}){let{connect:t=[],env:r=!0,sockets:o=!0,wasm:c=!0,inlineStyles:d=!0,directives:f={},dev:p=!0,log:v=!0,onPolicy:y}=e,b=Object.fromEntries(Object.entries(f).map(([e,t])=>[e.toLowerCase(),t])),x,S=[],C=``;function w(e,t,n){t===void 0||e.some(e=>e.origin===t)||e.push({origin:t,from:n})}function T(e){let n=[],i=e.env??{},o=[e.envPrefix??`VITE_`].flat();if(r===!0)for(let[e,t]of Object.entries(i))o.some(t=>e.startsWith(t))&&typeof t==`string`&&a.test(t.trim())&&w(n,s(t,`env ${e}`),`env ${e}`);else if(Array.isArray(r))for(let t of r){let r=i[t];if(typeof r!=`string`||r.trim()===``){e.logger.warn(`tempestCsp: env ${t} is empty — nothing added to connect-src`);continue}w(n,s(r,`env ${t}`),`env ${t}`)}return t.forEach((t,r)=>{if(!t||t.trim()===``){e.logger.warn(`tempestCsp: connect[${r}] is empty — skipped, nothing added to connect-src`);return}w(n,s(t,`connect[${r}]`),`connect[${r}]`)}),n}function E(e){let t=[...e];if(!o)return t;for(let{origin:n}of e){let e=n.replace(/^http(s?):/i,`ws$1:`);e!==n&&w(t,e,`sockets (${n})`)}return t}function D(e,t){let n=e?[`'self'`,e]:[`'self'`],r={"default-src":[...n],"script-src":c?[...n,`'wasm-unsafe-eval'`]:[...n],"style-src":d||t?[...n,`'unsafe-inline'`]:[...n],"img-src":[...n,`data:`,`blob:`],"font-src":[...n,`data:`],"media-src":[...n,`blob:`],"connect-src":[`'self'`,`blob:`,`data:`],"worker-src":[...n,`blob:`],"manifest-src":[...n],"object-src":[`'none'`],"base-uri":[`'self'`],"form-action":[`'self'`]};for(let[e,t]of Object.entries(b))t===!1?delete r[e]:r[e]=u(r[e]??[],t);return r}function O(e,t){let n={};for(let[r,a]of Object.entries(e)){if(r in t){n[r]=t[r];continue}let e=i(t,r),o=b[r];e===void 0?n[r]=a:Array.isArray(o)?n[r]=u(e,o):a.length===1&&a[0]===`'none'`&&(n[r]=a)}for(let[e,r]of Object.entries(t))n[e]??=r;for(let[e,r]of Object.entries(b)){if(!(e in t))continue;if(r===!1){delete n[e];continue}let i=r.filter(n=>!t[e].includes(n));i.length>0&&x?.logger.warn(`tempestCsp: index.html declares ${e}, so directives["${e}"] is not added to it (${i.join(` `)}); the plugin never loosens a declared policy — add them to the <meta> instead`)}return n}function k(e,t,n){if(!n||!x||n.includes(`'unsafe-inline'`)&&!n.some(e=>/^'(?:sha\d{3}|nonce)-/.test(e)))return;let r=h(e,`script`).filter(e=>!n.includes(e));r.length!==0&&x.logger.warn(`tempestCsp: the Content-Security-Policy declared in index.html blocks ${r.length} inline <script> (${t} ${n.join(` `)}); the plugin never loosens a declared policy, so add ${r.join(` `)} to ${t}`)}return{name:`tempest-csp`,configResolved(e){x=e,S=T(e)},transformIndexHtml:{order:`post`,handler(e,t){let r=x?.command===`serve`;if(r&&!p)return e;let o=E(S),c=x?.base??`/`,d=a.test(c)?s(c,`base`):void 0;d&&w(o,d,`base`);let f=r?[]:_(t);for(let e of n)(r||f.some(t=>e.module.test(t)))&&w(o,e.origin,e.from);let b=o,{html:T,declared:A={}}=m(e),j=D(d,r),M=e=>!(e in A)&&i(A,e)===void 0;M(`script-src`)&&!(`script-src-elem`in A)&&(j[`script-src`]=u(j[`script-src`]??[],h(T,`script`))),M(`style-src`)&&!(`style-src-elem`in A)&&!j[`style-src`]?.includes(`'unsafe-inline'`)&&(j[`style-src`]=u(j[`style-src`]??[],h(T,`style`)));let N=O(j,A),P=b.map(e=>e.origin),F=i(A,`connect-src`),I=N[`connect-src`]??F;I?.length===1&&I[0]===`'none'`&&(`connect-src`in A||F!==void 0)?P.length>0&&x?.logger.warn(`tempestCsp: index.html declares connect-src 'none'${`connect-src`in A?``:` (through default-src)`}, so these origins stay out and requests to them will be blocked: ${P.join(` `)}`):(`connect-src`in N||P.length>0||F===void 0)&&(N[`connect-src`]=u(I??[`'self'`],P));let L=`script-src-elem`in A?`script-src-elem`:`script-src`;k(T,L,N[L]??i(A,L));let R={directives:N,meta:l(N,`meta`),header:l(N,`header`),connect:b,command:r?`serve`:`build`};if(v&&x&&R.header!==C){C=R.header;let e=b.map(e=>` ${e.origin} ← ${e.from}`);x.logger.info([`tempest-csp: connect-src ${(N[`connect-src`]??F??[]).join(` `)}`,...e.length>0?e:[` (no cross-origin endpoint: only 'self')`]].join(`
2
+ `))}return y?.(R),g(T,R.meta)}}}}exports.cspOrigin=s,exports.parseCsp=c,exports.serializeCsp=l,exports.tempestCsp=v;
3
3
  //# sourceMappingURL=tempest-csp.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"tempest-csp.cjs","names":[],"sources":["../../src/vite/tempest-csp.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { IndexHtmlTransformContext, Plugin, ResolvedConfig } from \"vite\";\n\nimport type { TempestVitePlugin } from \"./tempest-pwa-manifest\";\n\n/** Options for {@link tempestCsp}. */\nexport interface TempestCspOptions {\n /**\n * Endpoints the app calls at runtime, as full URLs. Only the origin\n * (`scheme://host[:port]`) enters `connect-src`: a source expression with a path\n * matches that path alone, so `https://idp/realms/x` would still block\n * `https://idp/realms/x/protocol/openid-connect/token`.\n *\n * Empty entries (`undefined`, `null`, `false`, `\"\"`) are skipped with a build\n * warning instead of leaving a hole in the directive, so passing an env var\n * that is not set is safe. A root-relative path (`/api`) is same-origin and\n * already covered by `'self'`. Anything else that is not an absolute\n * `http(s)`/`ws(s)` URL throws at config time — failing the build, not\n * production. A wildcard host (`https://*.example.com`) is kept as written.\n */\n connect?: ReadonlyArray<string | null | undefined | false>;\n /**\n * Read origins from the same environment the runtime reads. `true` (the\n * default) adds every variable Vite exposes to `import.meta.env` (the\n * `envPrefix` ones, `VITE_` by default) whose value is an absolute\n * `http(s)`/`ws(s)` URL. This is the structural bridge: an origin added to\n * `.env` for a new runtime call lands in the policy with no second list to\n * keep in sync. Pass a list of names to include exactly those — a name that\n * resolves to nothing is reported as a build warning — or `false` to rely on\n * {@link TempestCspOptions.connect} alone.\n */\n env?: boolean | readonly string[];\n /**\n * Also allow the WebSocket twin of every `http(s)` origin (`https://api` →\n * `wss://api`). Measured in Chromium (23/09/2026): `connect-src https://api`\n * blocks `new WebSocket(\"wss://api\")`, while `'self'` does cover a same-origin\n * `ws:` — so an app that derives its socket URL from the API URL breaks\n * without this. Default `true`.\n */\n sockets?: boolean;\n /**\n * Add `'wasm-unsafe-eval'` to `script-src`, which `onnxruntime-web` (the\n * `/vision` and `/tabular` subpaths) needs to compile its WebAssembly. Without\n * it `WebAssembly.compile` throws a `CompileError` naming `script-src`.\n * It grants WebAssembly compilation only, not `eval`. Default `true`.\n */\n wasm?: boolean;\n /**\n * Add `'unsafe-inline'` to `style-src`. React's `style` prop does **not** need\n * it — it writes through the CSSOM, which CSP does not govern (measured in\n * Chromium, 23/09/2026). What needs it is a `<style>` element or a `style=\"\"`\n * attribute, and the SDK's own `applyTheme` injects a `<style>`. Pass `false`\n * when the app never calls `applyTheme`; inline `<style>` blocks in\n * `index.html` are then hashed instead. Always on under `vite dev`, whose CSS\n * injection is a `<style>` element. Default `true`.\n */\n inlineStyles?: boolean;\n /**\n * Extra sources per directive, merged into the defaults (`{ \"img-src\":\n * [\"https://tiles.example.com\"] }`), or `false` to drop a directive.\n * `frame-ancestors`, `report-uri` and `sandbox` are ignored by browsers when\n * delivered by `<meta>`, so they reach {@link TempestCspPolicy.header} only.\n */\n directives?: Readonly<Record<string, readonly string[] | false>>;\n /**\n * Apply the policy under `vite dev` too. Default `true`: the failure this\n * plugin exists for is \"works in dev, blocked in production\", and a policy\n * enforced in dev moves every missing origin to the first page load on the\n * developer's machine. Dev differs from build only in `style-src\n * 'unsafe-inline'` and in allowing every SDK-known origin (see\n * {@link TempestCspPolicy.connect}), because the dev server cannot know which\n * modules the page will load.\n */\n dev?: boolean;\n /** Print the resolved `connect-src` and where each origin came from. Default `true`. */\n log?: boolean;\n /**\n * Receive the resolved policy — for asserting it in a test, or for writing the\n * same policy as an HTTP header (the only channel for `frame-ancestors`).\n */\n onPolicy?: (policy: TempestCspPolicy) => void;\n}\n\n/** One origin in `connect-src` and the input that put it there. */\nexport interface TempestCspSource {\n /** The source expression, e.g. `https://api.example.com`. */\n origin: string;\n /** Where it came from: `env VITE_API_URL`, `connect[0]`, `sockets`, `base` or an SDK module. */\n from: string;\n}\n\n/** The policy {@link tempestCsp} resolved for one `index.html`. */\nexport interface TempestCspPolicy {\n /** Every directive and its sources, including the header-only ones. */\n directives: Record<string, string[]>;\n /** The policy as written into the `<meta http-equiv>` tag. */\n meta: string;\n /** The full policy for a `Content-Security-Policy` response header. */\n header: string;\n /** Every origin added to `connect-src`, with its provenance. */\n connect: TempestCspSource[];\n /** `\"serve\"` under `vite dev`, `\"build\"` under `vite build`. */\n command: \"serve\" | \"build\";\n}\n\n/**\n * Directives a browser ignores when the policy arrives by `<meta>` (CSP3 §3.3),\n * printing a console warning for each.\n */\nconst HEADER_ONLY_DIRECTIVES: ReadonlySet<string> = new Set([\n \"frame-ancestors\",\n \"report-uri\",\n \"sandbox\",\n]);\n\n/**\n * Origins the SDK itself calls, keyed by the module that calls them. In a build\n * the origin enters only when the module is in the bundle; in dev always.\n */\nconst SDK_ORIGINS: ReadonlyArray<{ module: RegExp; origin: string; from: string }> = [\n {\n module: /[\\\\/]forms[\\\\/]use-viacep\\.(?:[cm]?js|tsx?)$/,\n origin: \"https://viacep.com.br\",\n from: \"tempest-react-sdk useViaCEP\",\n },\n];\n\nconst ABSOLUTE_URL = /^(?:https?|wss?):\\/\\//i;\nconst WILDCARD_SOURCE = /^((?:https?|wss?):\\/\\/\\*\\.[a-z0-9.-]+(?::\\d+)?)(?:[/?#].*)?$/i;\n\n/**\n * Reduce a URL to the origin a CSP source expression should carry.\n *\n * @param value - The URL as the app configured it.\n * @param from - Its provenance, quoted in the error.\n * @returns The origin, or `undefined` for a root-relative path (covered by `'self'`).\n * @throws {Error} When the value is neither an absolute `http(s)`/`ws(s)` URL nor a path.\n */\nexport function cspOrigin(value: string, from: string): string | undefined {\n const trimmed = value.trim();\n if (trimmed.startsWith(\"/\") && !trimmed.startsWith(\"//\")) return undefined;\n const wildcard = WILDCARD_SOURCE.exec(trimmed);\n if (wildcard) return wildcard[1]!.toLowerCase();\n if (ABSOLUTE_URL.test(trimmed)) {\n try {\n const url = new URL(trimmed);\n return `${url.protocol}//${url.host}`;\n } catch {\n throw new Error(`tempestCsp: ${from} is not a valid URL: \"${value}\"`);\n }\n }\n throw new Error(\n `tempestCsp: ${from} must be an absolute http(s)/ws(s) URL or a root-relative path, got \"${value}\"`,\n );\n}\n\n/**\n * Parse a serialized policy into directives, lowercasing names. A repeated\n * directive keeps its first occurrence, as browsers do.\n *\n * @param policy - A `Content-Security-Policy` value.\n * @returns Directive name → sources.\n */\nexport function parseCsp(policy: string): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const part of policy.split(\";\")) {\n const [name, ...sources] = part.trim().split(/\\s+/);\n if (!name) continue;\n const key = name.toLowerCase();\n if (!(key in out)) out[key] = sources;\n }\n return out;\n}\n\n/**\n * Serialize directives into a policy string, dropping header-only directives\n * when the target is a `<meta>` tag.\n *\n * @param directives - Directive name → sources.\n * @param target - `\"meta\"` or `\"header\"`.\n * @returns The policy value.\n */\nexport function serializeCsp(\n directives: Readonly<Record<string, readonly string[]>>,\n target: \"meta\" | \"header\",\n): string {\n return Object.entries(directives)\n .filter(([name]) => target === \"header\" || !HEADER_ONLY_DIRECTIVES.has(name))\n .map(([name, sources]) => [name, ...sources].join(\" \"))\n .join(\"; \");\n}\n\nfunction union(base: readonly string[], extra: readonly string[]): string[] {\n const out = base.filter((source) => source !== \"'none'\" || extra.length === 0);\n for (const source of extra) if (!out.includes(source)) out.push(source);\n return out.length === 0 ? [\"'none'\"] : out;\n}\n\nfunction sha256(content: string): string {\n return `'sha256-${createHash(\"sha256\").update(content, \"utf8\").digest(\"base64\")}'`;\n}\n\nfunction decodeEntities(value: string): string {\n return value\n .replace(/&#39;|&#x27;|&apos;/gi, \"'\")\n .replace(/&quot;/gi, '\"')\n .replace(/&amp;/gi, \"&\");\n}\n\nfunction readAttributes(tag: string): Record<string, string> {\n const out: Record<string, string> = {};\n const pattern = /([^\\s=<>/]+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/g;\n for (const match of tag.matchAll(pattern)) {\n out[match[1]!.toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n return out;\n}\n\n/**\n * Find the policy `index.html` already declares and remove its tag, so the merged\n * policy replaces it instead of stacking a second one (two policies are\n * intersected by the browser, so the stricter would win silently).\n *\n * @throws {Error} When the page declares more than one CSP `<meta>`: merging an\n * intersection into a union would weaken it, so the plugin refuses.\n */\nfunction extractMetaPolicy(html: string): { html: string; declared?: Record<string, string[]> } {\n const tags = [...html.matchAll(/<meta\\b[^>]*>/gi)].filter(\n (match) =>\n readAttributes(match[0])[\"http-equiv\"]?.toLowerCase() === \"content-security-policy\",\n );\n if (tags.length === 0) return { html };\n if (tags.length > 1) {\n throw new Error(\n \"tempestCsp: index.html declares more than one Content-Security-Policy <meta>; merge them into one\",\n );\n }\n const tag = tags[0]!;\n return {\n html:\n html.slice(0, tag.index) +\n html.slice(tag.index! + tag[0].length).replace(/^[ \\t]*\\r?\\n/, \"\"),\n declared: parseCsp(readAttributes(tag[0]).content ?? \"\"),\n };\n}\n\nfunction inlineHashes(html: string, element: \"script\" | \"style\"): string[] {\n const pattern = new RegExp(`<${element}\\\\b([^>]*)>([\\\\s\\\\S]*?)</${element}>`, \"gi\");\n const hashes: string[] = [];\n for (const match of html.matchAll(pattern)) {\n const attributes = readAttributes(`<x ${match[1]}>`);\n if (element === \"script\" && \"src\" in attributes) continue;\n if (match[2]!.length === 0) continue;\n const hash = sha256(match[2]!);\n if (!hashes.includes(hash)) hashes.push(hash);\n }\n return hashes;\n}\n\n/**\n * Write the policy tag where it governs the whole page. A `<meta>` CSP applies\n * only to what follows it, so it goes right after `<meta charset>` — unless a\n * resource precedes the charset, as the React Refresh preamble does under\n * `vite dev` (`head-prepend`), in which case it goes right after `<head>`.\n */\nfunction insertMeta(html: string, policy: string): string {\n const escaped = policy.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n const tag = `<meta http-equiv=\"Content-Security-Policy\" content=\"${escaped}\" />`;\n const charset = /<meta\\b[^>]*\\bcharset\\s*=[^>]*>/i.exec(html);\n const head = /<head\\b[^>]*>/i.exec(html);\n const resourceFirst =\n charset !== null &&\n head !== null &&\n /<(?:script|link|style)\\b/i.test(html.slice(head.index, charset.index));\n const anchor = charset && head && charset.index > head.index && !resourceFirst ? charset : head;\n if (!anchor) return `${tag}\\n${html}`;\n const at = anchor.index + anchor[0].length;\n return `${html.slice(0, at)}\\n ${tag}${html.slice(at)}`;\n}\n\nfunction bundleModuleIds(ctx: IndexHtmlTransformContext): string[] {\n const ids: string[] = [];\n for (const output of Object.values(ctx.bundle ?? {})) {\n if (output.type !== \"chunk\") continue;\n ids.push(...(output.moduleIds ?? Object.keys(output.modules ?? {})));\n }\n return ids;\n}\n\n/**\n * Vite plugin that writes a Content-Security-Policy `<meta>` into `index.html`\n * and derives `connect-src` from the origins the app actually calls.\n *\n * It exists because of how a missing origin fails: the request is blocked\n * before a connection opens, so there is no entry in the Network tab, nothing in\n * the server log, `curl` succeeds, and the app sees `TypeError: Failed to\n * fetch` — indistinguishable from offline, DNS or CORS. And a hand-written CSP\n * plugin is usually `apply: \"build\"`, so it only fails in production. This\n * plugin closes both ends:\n *\n * - origins come from the same `import.meta.env` the runtime reads\n * ({@link TempestCspOptions.env}), reduced to `scheme://host[:port]`, with\n * empty values skipped — no second list to drift;\n * - the policy is enforced under `vite dev` as well ({@link TempestCspOptions.dev});\n * - the build prints every origin and its provenance.\n *\n * Defaults cover what the SDK's stack needs and nothing more: `'self'`\n * everywhere, `'wasm-unsafe-eval'` for ONNX Runtime, `blob:` for workers, object\n * URLs and media, `data:` for images and fonts, `object-src 'none'`,\n * `base-uri 'self'`, `form-action 'self'`. Inline `<script>` blocks left in\n * `index.html` (a `themeInitScript()` anti-flash script, say) are allowed by\n * SHA-256 hash, never by `'unsafe-inline'`.\n *\n * An existing CSP `<meta>` in `index.html` is merged, not overwritten: every\n * directive it declares is kept verbatim — the plugin never loosens a choice the\n * app wrote — except `connect-src`, which gains the resolved origins, since\n * that is the list the plugin exists to maintain. Directives it does not declare\n * come from the defaults.\n *\n * @param options - See {@link TempestCspOptions}.\n * @returns A Vite plugin, to be placed in `plugins`. It runs as a `post` HTML\n * transform, so a plugin that rewrites inline scripts after it would\n * invalidate the hashes.\n *\n * @example\n * // vite.config.ts\n * import { createViteConfig, tempestCsp } from \"tempest-react-sdk/vite\";\n *\n * export default createViteConfig({\n * plugins: [tempestCsp({ connect: [\"https://sso.example.com/realms/app\"] })],\n * });\n */\nexport function tempestCsp(options: TempestCspOptions = {}): TempestVitePlugin {\n const {\n connect = [],\n env = true,\n sockets = true,\n wasm = true,\n inlineStyles = true,\n directives: extra = {},\n dev = true,\n log = true,\n onPolicy,\n } = options;\n\n let config: ResolvedConfig | undefined;\n let resolved: TempestCspSource[] = [];\n let lastLogged = \"\";\n\n function add(list: TempestCspSource[], origin: string | undefined, from: string): void {\n if (origin === undefined || list.some((source) => source.origin === origin)) return;\n list.push({ origin, from });\n }\n\n function resolveSources(resolvedConfig: ResolvedConfig): TempestCspSource[] {\n const list: TempestCspSource[] = [];\n const values: Record<string, unknown> = resolvedConfig.env ?? {};\n const prefixes = [resolvedConfig.envPrefix ?? \"VITE_\"].flat();\n if (env === true) {\n for (const [name, value] of Object.entries(values)) {\n if (!prefixes.some((prefix) => name.startsWith(prefix))) continue;\n if (typeof value !== \"string\" || !ABSOLUTE_URL.test(value.trim())) continue;\n add(list, cspOrigin(value, `env ${name}`), `env ${name}`);\n }\n } else if (Array.isArray(env)) {\n for (const name of env) {\n const value = values[name];\n if (typeof value !== \"string\" || value.trim() === \"\") {\n resolvedConfig.logger.warn(\n `tempestCsp: env ${name} is empty — nothing added to connect-src`,\n );\n continue;\n }\n add(list, cspOrigin(value, `env ${name}`), `env ${name}`);\n }\n }\n connect.forEach((value, index) => {\n if (!value || value.trim() === \"\") {\n resolvedConfig.logger.warn(\n `tempestCsp: connect[${index}] is empty — skipped, nothing added to connect-src`,\n );\n return;\n }\n add(list, cspOrigin(value, `connect[${index}]`), `connect[${index}]`);\n });\n return list;\n }\n\n function withSockets(list: readonly TempestCspSource[]): TempestCspSource[] {\n const out = [...list];\n if (!sockets) return out;\n for (const { origin } of list) {\n const twin = origin.replace(/^http(s?):/i, \"ws$1:\");\n if (twin !== origin) add(out, twin, `sockets (${origin})`);\n }\n return out;\n }\n\n function defaults(baseOrigin: string | undefined, serve: boolean): Record<string, string[]> {\n const self = baseOrigin ? [\"'self'\", baseOrigin] : [\"'self'\"];\n const policy: Record<string, string[]> = {\n \"default-src\": [...self],\n \"script-src\": wasm ? [...self, \"'wasm-unsafe-eval'\"] : [...self],\n \"style-src\": inlineStyles || serve ? [...self, \"'unsafe-inline'\"] : [...self],\n \"img-src\": [...self, \"data:\", \"blob:\"],\n \"font-src\": [...self, \"data:\"],\n \"media-src\": [...self, \"blob:\"],\n \"connect-src\": [\"'self'\", \"blob:\", \"data:\"],\n \"worker-src\": [...self, \"blob:\"],\n \"manifest-src\": [...self],\n \"object-src\": [\"'none'\"],\n \"base-uri\": [\"'self'\"],\n \"form-action\": [\"'self'\"],\n };\n for (const [name, sources] of Object.entries(extra)) {\n const key = name.toLowerCase();\n if (sources === false) delete policy[key];\n else policy[key] = union(policy[key] ?? [], sources);\n }\n return policy;\n }\n\n const plugin: Plugin = {\n name: \"tempest-csp\",\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n resolved = resolveSources(resolvedConfig);\n },\n transformIndexHtml: {\n order: \"post\",\n handler(source, ctx) {\n const serve = config?.command === \"serve\";\n if (serve && !dev) return source;\n\n const connectSources = withSockets(resolved);\n const base = config?.base ?? \"/\";\n const baseOrigin = ABSOLUTE_URL.test(base) ? cspOrigin(base, \"base\") : undefined;\n if (baseOrigin) add(connectSources, baseOrigin, \"base\");\n const moduleIds = serve ? [] : bundleModuleIds(ctx);\n for (const known of SDK_ORIGINS) {\n if (serve || moduleIds.some((id) => known.module.test(id))) {\n add(connectSources, known.origin, known.from);\n }\n }\n const allSources = connectSources;\n\n const { html, declared = {} } = extractMetaPolicy(source);\n const policy = defaults(baseOrigin, serve);\n if (!(\"script-src\" in declared)) {\n policy[\"script-src\"] = union(\n policy[\"script-src\"] ?? [],\n inlineHashes(html, \"script\"),\n );\n }\n if (\n !(\"style-src\" in declared) &&\n !policy[\"style-src\"]?.includes(\"'unsafe-inline'\")\n ) {\n policy[\"style-src\"] = union(\n policy[\"style-src\"] ?? [],\n inlineHashes(html, \"style\"),\n );\n }\n const merged: Record<string, string[]> = { ...policy };\n for (const [name, sources] of Object.entries(declared)) merged[name] = sources;\n merged[\"connect-src\"] = union(\n merged[\"connect-src\"] ?? [\"'self'\"],\n allSources.map((entry) => entry.origin),\n );\n\n const result: TempestCspPolicy = {\n directives: merged,\n meta: serializeCsp(merged, \"meta\"),\n header: serializeCsp(merged, \"header\"),\n connect: allSources,\n command: serve ? \"serve\" : \"build\",\n };\n\n if (log && config && result.header !== lastLogged) {\n lastLogged = result.header;\n const lines = allSources.map((entry) => ` ${entry.origin} ← ${entry.from}`);\n config.logger.info(\n [\n `tempest-csp: connect-src ${merged[\"connect-src\"].join(\" \")}`,\n ...(lines.length > 0\n ? lines\n : [\" (no cross-origin endpoint: only 'self')\"]),\n ].join(\"\\n\"),\n );\n }\n onPolicy?.(result);\n return insertMeta(html, result.meta);\n },\n },\n };\n\n return plugin as TempestVitePlugin;\n}\n"],"mappings":"6BA6GA,IAAM,EAA8C,IAAI,IAAI,CACxD,kBACA,aACA,SACJ,CAAC,EAMK,EAA+E,CACjF,CACI,OAAQ,+CACR,OAAQ,wBACR,KAAM,6BACV,CACJ,EAEM,EAAe,yBACf,EAAkB,gEAUxB,SAAgB,EAAU,EAAe,EAAkC,CACvE,IAAM,EAAU,EAAM,KAAK,EAC3B,GAAI,EAAQ,WAAW,GAAG,GAAK,CAAC,EAAQ,WAAW,IAAI,EAAG,OAC1D,IAAM,EAAW,EAAgB,KAAK,CAAO,EAC7C,GAAI,EAAU,OAAO,EAAS,EAAE,CAAE,YAAY,EAC9C,GAAI,EAAa,KAAK,CAAO,EACzB,GAAI,CACA,IAAM,EAAM,IAAI,IAAI,CAAO,EAC3B,MAAO,GAAG,EAAI,SAAS,IAAI,EAAI,MACnC,MAAQ,CACJ,MAAU,MAAM,eAAe,EAAK,wBAAwB,EAAM,EAAE,CACxE,CAEJ,MAAU,MACN,eAAe,EAAK,uEAAuE,EAAM,EACrG,CACJ,CASA,SAAgB,EAAS,EAA0C,CAC/D,IAAM,EAAgC,CAAC,EAC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,EAClC,EAAW,IAAK,GAAU,EAAM,MAAM,CAC1C,EAEA,IAAM,EAA2B,CAC7B,WAAY,EACZ,KAAM,EAAa,EAAQ,MAAM,EACjC,OAAQ,EAAa,EAAQ,QAAQ,EACrC,QAAS,EACT,QAAS,EAAQ,QAAU,OAC/B,EAEA,GAAI,GAAO,GAAU,EAAO,SAAW,EAAY,CAC/C,EAAa,EAAO,OACpB,IAAM,EAAQ,EAAW,IAAK,GAAU,KAAK,EAAM,OAAO,MAAM,EAAM,MAAM,EAC5E,EAAO,OAAO,KACV,CACI,4BAA4B,EAAO,cAAc,CAAC,KAAK,GAAG,IAC1D,GAAI,EAAM,OAAS,EACb,EACA,CAAC,2CAA2C,CACtD,CAAC,CAAC,KAAK;CAAI,CACf,CACJ,CAEA,OADA,IAAW,CAAM,EACV,EAAW,EAAM,EAAO,IAAI,CACvC,CACJ,CAGG,CACX"}
1
+ {"version":3,"file":"tempest-csp.cjs","names":[],"sources":["../../src/vite/tempest-csp.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { IndexHtmlTransformContext, Plugin, ResolvedConfig } from \"vite\";\n\nimport type { TempestVitePlugin } from \"./tempest-pwa-manifest\";\n\n/** Options for {@link tempestCsp}. */\nexport interface TempestCspOptions {\n /**\n * Endpoints the app calls at runtime, as full URLs. Only the origin\n * (`scheme://host[:port]`) enters `connect-src`: a source expression with a path\n * matches that path alone, so `https://idp/realms/x` would still block\n * `https://idp/realms/x/protocol/openid-connect/token`.\n *\n * Empty entries (`undefined`, `null`, `false`, `\"\"`) are skipped with a build\n * warning instead of leaving a hole in the directive, so passing an env var\n * that is not set is safe. A root-relative path (`/api`) is same-origin and\n * already covered by `'self'`. Anything else that is not an absolute\n * `http(s)`/`ws(s)` URL throws at config time — failing the build, not\n * production. A wildcard host (`https://*.example.com`) is kept as written.\n */\n connect?: ReadonlyArray<string | null | undefined | false>;\n /**\n * Read origins from the same environment the runtime reads. `true` (the\n * default) adds every variable Vite exposes to `import.meta.env` (the\n * `envPrefix` ones, `VITE_` by default) whose value is an absolute\n * `http(s)`/`ws(s)` URL. This is the structural bridge: an origin added to\n * `.env` for a new runtime call lands in the policy with no second list to\n * keep in sync. Pass a list of names to include exactly those — a name that\n * resolves to nothing is reported as a build warning — or `false` to rely on\n * {@link TempestCspOptions.connect} alone.\n */\n env?: boolean | readonly string[];\n /**\n * Also allow the WebSocket twin of every `http(s)` origin (`https://api` →\n * `wss://api`). Measured in Chromium (23/09/2026): `connect-src https://api`\n * blocks `new WebSocket(\"wss://api\")`, while `'self'` does cover a same-origin\n * `ws:` — so an app that derives its socket URL from the API URL breaks\n * without this. Default `true`.\n */\n sockets?: boolean;\n /**\n * Add `'wasm-unsafe-eval'` to `script-src`, which `onnxruntime-web` (the\n * `/vision` and `/tabular` subpaths) needs to compile its WebAssembly. Without\n * it `WebAssembly.compile` throws a `CompileError` naming `script-src`.\n * It grants WebAssembly compilation only, not `eval`. Default `true`.\n */\n wasm?: boolean;\n /**\n * Add `'unsafe-inline'` to `style-src`. React's `style` prop does **not** need\n * it — it writes through the CSSOM, which CSP does not govern (measured in\n * Chromium, 23/09/2026). What needs it is a `<style>` element or a `style=\"\"`\n * attribute, and the SDK's own `applyTheme` injects a `<style>`. Pass `false`\n * when the app never calls `applyTheme`; inline `<style>` blocks in\n * `index.html` are then hashed instead. Always on under `vite dev`, whose CSS\n * injection is a `<style>` element. Default `true`.\n */\n inlineStyles?: boolean;\n /**\n * Extra sources per directive, merged into the defaults (`{ \"img-src\":\n * [\"https://tiles.example.com\"] }`), or `false` to drop a directive.\n * `frame-ancestors`, `report-uri` and `sandbox` are ignored by browsers when\n * delivered by `<meta>`, so they reach {@link TempestCspPolicy.header} only.\n */\n directives?: Readonly<Record<string, readonly string[] | false>>;\n /**\n * Apply the policy under `vite dev` too. Default `true`: the failure this\n * plugin exists for is \"works in dev, blocked in production\", and a policy\n * enforced in dev moves every missing origin to the first page load on the\n * developer's machine. Dev differs from build only in `style-src\n * 'unsafe-inline'` and in allowing every SDK-known origin (see\n * {@link TempestCspPolicy.connect}), because the dev server cannot know which\n * modules the page will load.\n */\n dev?: boolean;\n /** Print the resolved `connect-src` and where each origin came from. Default `true`. */\n log?: boolean;\n /**\n * Receive the resolved policy — for asserting it in a test, or for writing the\n * same policy as an HTTP header (the only channel for `frame-ancestors`).\n */\n onPolicy?: (policy: TempestCspPolicy) => void;\n}\n\n/** One origin in `connect-src` and the input that put it there. */\nexport interface TempestCspSource {\n /** The source expression, e.g. `https://api.example.com`. */\n origin: string;\n /** Where it came from: `env VITE_API_URL`, `connect[0]`, `sockets`, `base` or an SDK module. */\n from: string;\n}\n\n/** The policy {@link tempestCsp} resolved for one `index.html`. */\nexport interface TempestCspPolicy {\n /** Every directive and its sources, including the header-only ones. */\n directives: Record<string, string[]>;\n /** The policy as written into the `<meta http-equiv>` tag. */\n meta: string;\n /** The full policy for a `Content-Security-Policy` response header. */\n header: string;\n /** Every origin added to `connect-src`, with its provenance. */\n connect: TempestCspSource[];\n /** `\"serve\"` under `vite dev`, `\"build\"` under `vite build`. */\n command: \"serve\" | \"build\";\n}\n\n/**\n * Directives a browser ignores when the policy arrives by `<meta>` (CSP3 §3.3),\n * printing a console warning for each.\n */\nconst HEADER_ONLY_DIRECTIVES: ReadonlySet<string> = new Set([\n \"frame-ancestors\",\n \"report-uri\",\n \"sandbox\",\n]);\n\n/**\n * Origins the SDK itself calls, keyed by the module that calls them. In a build\n * the origin enters only when the module is in the bundle; in dev always.\n */\nconst SDK_ORIGINS: ReadonlyArray<{ module: RegExp; origin: string; from: string }> = [\n {\n module: /[\\\\/]forms[\\\\/]use-viacep\\.(?:[cm]?js|tsx?)$/,\n origin: \"https://viacep.com.br\",\n from: \"tempest-react-sdk useViaCEP\",\n },\n];\n\n/**\n * Where each fetch directive falls back when a policy does not declare it, in\n * order. Ported from CSP3 §6.8.3, \"Get fetch directive fallback list\"\n * (https://w3c.github.io/webappsec-csp/#directive-fallback-list, checked\n * 11/10/2026), which lists twelve effective directives: `script-src-elem`,\n * `script-src-attr`, `style-src-elem`, `style-src-attr`, `worker-src`,\n * `connect-src`, `manifest-src`, `object-src`, `frame-src`, `media-src`,\n * `font-src` and `img-src`. Four more are listed here on purpose:\n *\n * - `script-src`, `style-src` and `child-src` are never an effective directive,\n * but every chain that reaches them continues to `default-src`;\n * - `fenced-frame-src` comes from the Fenced Frame spec, which extends the\n * `frame-src` chain;\n * - `prefetch-src` was in earlier CSP3 drafts (→ `default-src`) and is gone from\n * the current one; a browser that still resolves it does so through\n * `default-src`, so it is treated as inherited.\n *\n * A directive absent from this map does not fall back at all (`base-uri`,\n * `form-action`, `frame-ancestors`, …): leaving it out of a policy allows\n * everything, so adding it only ever restricts.\n */\nconst CSP_FALLBACK: Readonly<Record<string, readonly string[]>> = {\n \"script-src-elem\": [\"script-src\", \"default-src\"],\n \"script-src-attr\": [\"script-src\", \"default-src\"],\n \"style-src-elem\": [\"style-src\", \"default-src\"],\n \"style-src-attr\": [\"style-src\", \"default-src\"],\n \"worker-src\": [\"child-src\", \"script-src\", \"default-src\"],\n \"frame-src\": [\"child-src\", \"default-src\"],\n \"fenced-frame-src\": [\"frame-src\", \"child-src\", \"default-src\"],\n \"child-src\": [\"default-src\"],\n \"connect-src\": [\"default-src\"],\n \"font-src\": [\"default-src\"],\n \"img-src\": [\"default-src\"],\n \"manifest-src\": [\"default-src\"],\n \"media-src\": [\"default-src\"],\n \"object-src\": [\"default-src\"],\n \"prefetch-src\": [\"default-src\"],\n \"script-src\": [\"default-src\"],\n \"style-src\": [\"default-src\"],\n};\n\n/**\n * The sources a declared policy already applies to a directive it does not\n * name, by walking {@link CSP_FALLBACK}.\n *\n * @param declared - The policy the app declared.\n * @param name - A directive the app did not declare.\n * @returns The inherited sources, or `undefined` when nothing governs the directive.\n */\nfunction inheritedSources(\n declared: Readonly<Record<string, string[]>>,\n name: string,\n): string[] | undefined {\n for (const parent of CSP_FALLBACK[name] ?? []) {\n if (parent in declared) return declared[parent];\n }\n return undefined;\n}\n\nconst ABSOLUTE_URL = /^(?:https?|wss?):\\/\\//i;\nconst WILDCARD_SOURCE = /^((?:https?|wss?):\\/\\/\\*\\.[a-z0-9.-]+(?::\\d+)?)(?:[/?#].*)?$/i;\n\n/**\n * Reduce a URL to the origin a CSP source expression should carry.\n *\n * @param value - The URL as the app configured it.\n * @param from - Its provenance, quoted in the error.\n * @returns The origin, or `undefined` for a root-relative path (covered by `'self'`).\n * @throws {Error} When the value is neither an absolute `http(s)`/`ws(s)` URL nor a path.\n */\nexport function cspOrigin(value: string, from: string): string | undefined {\n const trimmed = value.trim();\n if (trimmed.startsWith(\"/\") && !trimmed.startsWith(\"//\")) return undefined;\n const wildcard = WILDCARD_SOURCE.exec(trimmed);\n if (wildcard) return wildcard[1]!.toLowerCase();\n if (ABSOLUTE_URL.test(trimmed)) {\n try {\n const url = new URL(trimmed);\n return `${url.protocol}//${url.host}`;\n } catch {\n throw new Error(`tempestCsp: ${from} is not a valid URL: \"${value}\"`);\n }\n }\n throw new Error(\n `tempestCsp: ${from} must be an absolute http(s)/ws(s) URL or a root-relative path, got \"${value}\"`,\n );\n}\n\n/**\n * Parse a serialized policy into directives, lowercasing names. A repeated\n * directive keeps its first occurrence, as browsers do.\n *\n * @param policy - A `Content-Security-Policy` value.\n * @returns Directive name → sources.\n */\nexport function parseCsp(policy: string): Record<string, string[]> {\n const out: Record<string, string[]> = {};\n for (const part of policy.split(\";\")) {\n const [name, ...sources] = part.trim().split(/\\s+/);\n if (!name) continue;\n const key = name.toLowerCase();\n if (!(key in out)) out[key] = sources;\n }\n return out;\n}\n\n/**\n * Serialize directives into a policy string, dropping header-only directives\n * when the target is a `<meta>` tag.\n *\n * @param directives - Directive name → sources.\n * @param target - `\"meta\"` or `\"header\"`.\n * @returns The policy value.\n */\nexport function serializeCsp(\n directives: Readonly<Record<string, readonly string[]>>,\n target: \"meta\" | \"header\",\n): string {\n return Object.entries(directives)\n .filter(([name]) => target === \"header\" || !HEADER_ONLY_DIRECTIVES.has(name))\n .map(([name, sources]) => [name, ...sources].join(\" \"))\n .join(\"; \");\n}\n\nfunction union(base: readonly string[], extra: readonly string[]): string[] {\n const out = base.filter((source) => source !== \"'none'\" || extra.length === 0);\n for (const source of extra) if (!out.includes(source)) out.push(source);\n return out.length === 0 ? [\"'none'\"] : out;\n}\n\nfunction sha256(content: string): string {\n return `'sha256-${createHash(\"sha256\").update(content, \"utf8\").digest(\"base64\")}'`;\n}\n\nfunction decodeEntities(value: string): string {\n return value\n .replace(/&#39;|&#x27;|&apos;/gi, \"'\")\n .replace(/&quot;/gi, '\"')\n .replace(/&amp;/gi, \"&\");\n}\n\nfunction readAttributes(tag: string): Record<string, string> {\n const out: Record<string, string> = {};\n const pattern = /([^\\s=<>/]+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/g;\n for (const match of tag.matchAll(pattern)) {\n out[match[1]!.toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? \"\");\n }\n return out;\n}\n\n/**\n * Find the policy `index.html` already declares and remove its tag, so the merged\n * policy replaces it instead of stacking a second one (two policies are\n * intersected by the browser, so the stricter would win silently).\n *\n * @throws {Error} When the page declares more than one CSP `<meta>`: merging an\n * intersection into a union would weaken it, so the plugin refuses.\n */\nfunction extractMetaPolicy(html: string): { html: string; declared?: Record<string, string[]> } {\n const tags = [...html.matchAll(/<meta\\b[^>]*>/gi)].filter(\n (match) =>\n readAttributes(match[0])[\"http-equiv\"]?.toLowerCase() === \"content-security-policy\",\n );\n if (tags.length === 0) return { html };\n if (tags.length > 1) {\n throw new Error(\n \"tempestCsp: index.html declares more than one Content-Security-Policy <meta>; merge them into one\",\n );\n }\n const tag = tags[0]!;\n return {\n html:\n html.slice(0, tag.index) +\n html.slice(tag.index! + tag[0].length).replace(/^[ \\t]*\\r?\\n/, \"\"),\n declared: parseCsp(readAttributes(tag[0]).content ?? \"\"),\n };\n}\n\nfunction inlineHashes(html: string, element: \"script\" | \"style\"): string[] {\n const pattern = new RegExp(`<${element}\\\\b([^>]*)>([\\\\s\\\\S]*?)</${element}>`, \"gi\");\n const hashes: string[] = [];\n for (const match of html.matchAll(pattern)) {\n const attributes = readAttributes(`<x ${match[1]}>`);\n if (element === \"script\" && \"src\" in attributes) continue;\n if (match[2]!.length === 0) continue;\n const hash = sha256(match[2]!);\n if (!hashes.includes(hash)) hashes.push(hash);\n }\n return hashes;\n}\n\n/**\n * Write the policy tag where it governs the whole page. A `<meta>` CSP applies\n * only to what follows it, so it goes right after `<meta charset>` — unless a\n * resource precedes the charset, as the React Refresh preamble does under\n * `vite dev` (`head-prepend`), in which case it goes right after `<head>`.\n */\nfunction insertMeta(html: string, policy: string): string {\n const escaped = policy.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\");\n const tag = `<meta http-equiv=\"Content-Security-Policy\" content=\"${escaped}\" />`;\n const charset = /<meta\\b[^>]*\\bcharset\\s*=[^>]*>/i.exec(html);\n const head = /<head\\b[^>]*>/i.exec(html);\n const resourceFirst =\n charset !== null &&\n head !== null &&\n /<(?:script|link|style)\\b/i.test(html.slice(head.index, charset.index));\n const anchor = charset && head && charset.index > head.index && !resourceFirst ? charset : head;\n if (!anchor) return `${tag}\\n${html}`;\n const at = anchor.index + anchor[0].length;\n return `${html.slice(0, at)}\\n ${tag}${html.slice(at)}`;\n}\n\nfunction bundleModuleIds(ctx: IndexHtmlTransformContext): string[] {\n const ids: string[] = [];\n for (const output of Object.values(ctx.bundle ?? {})) {\n if (output.type !== \"chunk\") continue;\n ids.push(...(output.moduleIds ?? Object.keys(output.modules ?? {})));\n }\n return ids;\n}\n\n/**\n * Vite plugin that writes a Content-Security-Policy `<meta>` into `index.html`\n * and derives `connect-src` from the origins the app actually calls.\n *\n * It exists because of how a missing origin fails: the request is blocked\n * before a connection opens, so there is no entry in the Network tab, nothing in\n * the server log, `curl` succeeds, and the app sees `TypeError: Failed to\n * fetch` — indistinguishable from offline, DNS or CORS. And a hand-written CSP\n * plugin is usually `apply: \"build\"`, so it only fails in production. This\n * plugin closes both ends:\n *\n * - origins come from the same `import.meta.env` the runtime reads\n * ({@link TempestCspOptions.env}), reduced to `scheme://host[:port]`, with\n * empty values skipped — no second list to drift;\n * - the policy is enforced under `vite dev` as well ({@link TempestCspOptions.dev});\n * - the build prints every origin and its provenance.\n *\n * Defaults cover what the SDK's stack needs and nothing more: `'self'`\n * everywhere, `'wasm-unsafe-eval'` for ONNX Runtime, `blob:` for workers, object\n * URLs and media, `data:` for images and fonts, `object-src 'none'`,\n * `base-uri 'self'`, `form-action 'self'`. Inline `<script>` blocks left in\n * `index.html` (a `themeInitScript()` anti-flash script, say) are allowed by\n * SHA-256 hash, never by `'unsafe-inline'`.\n *\n * An existing CSP `<meta>` in `index.html` is merged, not overwritten, and the\n * merge never loosens what the app wrote:\n *\n * - a directive it declares is kept verbatim, except `connect-src`, which gains\n * the resolved origins (the list the plugin exists to maintain) unless it is\n * `'none'` — declared or inherited from `default-src` — in which case the\n * origins stay out and each one is reported as a build warning. Sources in\n * {@link TempestCspOptions.directives} for a declared directive are not added\n * (a build warning names them); `false` there removes it;\n * - a fetch directive it does not declare but already governs through the CSP3\n * fallback chain (§6.8.3 — `img-src` → `default-src`,\n * `worker-src` → `child-src` → `script-src` → `default-src`) is left out, so it\n * keeps falling back. Filling it from the defaults would replace a\n * `default-src 'none'` with `'self' data: blob:`. No inline-script hash and no\n * `'wasm-unsafe-eval'` is added to it, and an inline `<script>` is judged by a\n * declared `script-src-elem` before `script-src`; `connect-src` starts from the inherited\n * value, and so does any directive passed in {@link TempestCspOptions.directives};\n * - a default that is exactly `'none'` (`object-src`), or a directive that does\n * not fall back (`base-uri`, `form-action`), is still added: it can only\n * restrict;\n * - a directive nothing in the declared policy governs comes from the defaults.\n *\n * @param options - See {@link TempestCspOptions}.\n * @returns A Vite plugin, to be placed in `plugins`. It runs as a `post` HTML\n * transform, so a plugin that rewrites inline scripts after it would\n * invalidate the hashes.\n *\n * @example\n * // vite.config.ts\n * import { createViteConfig, tempestCsp } from \"tempest-react-sdk/vite\";\n *\n * export default createViteConfig({\n * plugins: [tempestCsp({ connect: [\"https://sso.example.com/realms/app\"] })],\n * });\n */\nexport function tempestCsp(options: TempestCspOptions = {}): TempestVitePlugin {\n const {\n connect = [],\n env = true,\n sockets = true,\n wasm = true,\n inlineStyles = true,\n directives: extra = {},\n dev = true,\n log = true,\n onPolicy,\n } = options;\n\n const configured: Record<string, readonly string[] | false> = Object.fromEntries(\n Object.entries(extra).map(([name, sources]) => [name.toLowerCase(), sources]),\n );\n let config: ResolvedConfig | undefined;\n let resolved: TempestCspSource[] = [];\n let lastLogged = \"\";\n\n function add(list: TempestCspSource[], origin: string | undefined, from: string): void {\n if (origin === undefined || list.some((source) => source.origin === origin)) return;\n list.push({ origin, from });\n }\n\n function resolveSources(resolvedConfig: ResolvedConfig): TempestCspSource[] {\n const list: TempestCspSource[] = [];\n const values: Record<string, unknown> = resolvedConfig.env ?? {};\n const prefixes = [resolvedConfig.envPrefix ?? \"VITE_\"].flat();\n if (env === true) {\n for (const [name, value] of Object.entries(values)) {\n if (!prefixes.some((prefix) => name.startsWith(prefix))) continue;\n if (typeof value !== \"string\" || !ABSOLUTE_URL.test(value.trim())) continue;\n add(list, cspOrigin(value, `env ${name}`), `env ${name}`);\n }\n } else if (Array.isArray(env)) {\n for (const name of env) {\n const value = values[name];\n if (typeof value !== \"string\" || value.trim() === \"\") {\n resolvedConfig.logger.warn(\n `tempestCsp: env ${name} is empty — nothing added to connect-src`,\n );\n continue;\n }\n add(list, cspOrigin(value, `env ${name}`), `env ${name}`);\n }\n }\n connect.forEach((value, index) => {\n if (!value || value.trim() === \"\") {\n resolvedConfig.logger.warn(\n `tempestCsp: connect[${index}] is empty — skipped, nothing added to connect-src`,\n );\n return;\n }\n add(list, cspOrigin(value, `connect[${index}]`), `connect[${index}]`);\n });\n return list;\n }\n\n function withSockets(list: readonly TempestCspSource[]): TempestCspSource[] {\n const out = [...list];\n if (!sockets) return out;\n for (const { origin } of list) {\n const twin = origin.replace(/^http(s?):/i, \"ws$1:\");\n if (twin !== origin) add(out, twin, `sockets (${origin})`);\n }\n return out;\n }\n\n function defaults(baseOrigin: string | undefined, serve: boolean): Record<string, string[]> {\n const self = baseOrigin ? [\"'self'\", baseOrigin] : [\"'self'\"];\n const policy: Record<string, string[]> = {\n \"default-src\": [...self],\n \"script-src\": wasm ? [...self, \"'wasm-unsafe-eval'\"] : [...self],\n \"style-src\": inlineStyles || serve ? [...self, \"'unsafe-inline'\"] : [...self],\n \"img-src\": [...self, \"data:\", \"blob:\"],\n \"font-src\": [...self, \"data:\"],\n \"media-src\": [...self, \"blob:\"],\n \"connect-src\": [\"'self'\", \"blob:\", \"data:\"],\n \"worker-src\": [...self, \"blob:\"],\n \"manifest-src\": [...self],\n \"object-src\": [\"'none'\"],\n \"base-uri\": [\"'self'\"],\n \"form-action\": [\"'self'\"],\n };\n for (const [name, sources] of Object.entries(configured)) {\n if (sources === false) delete policy[name];\n else policy[name] = union(policy[name] ?? [], sources);\n }\n return policy;\n }\n\n /**\n * Merge the defaults, the declared policy and the configured\n * {@link TempestCspOptions.directives}, never loosening what was declared. A\n * declared directive is kept verbatim: configured sources for it are not\n * added — adding would loosen the app's policy — and each ignored source is\n * reported as a build warning, while a configured `false` removes it, since\n * removing is an explicit choice. An inherited directive (see\n * {@link inheritedSources}) is omitted unless the default is `'none'` or the\n * config adds sources, which then extend the inherited value instead of the\n * defaults.\n */\n function mergePolicy(\n policy: Readonly<Record<string, string[]>>,\n declared: Readonly<Record<string, string[]>>,\n ): Record<string, string[]> {\n const merged: Record<string, string[]> = {};\n for (const [name, sources] of Object.entries(policy)) {\n if (name in declared) {\n merged[name] = declared[name]!;\n continue;\n }\n const inherited = inheritedSources(declared, name);\n const added = configured[name];\n if (inherited === undefined) merged[name] = sources;\n else if (Array.isArray(added)) merged[name] = union(inherited, added);\n else if (sources.length === 1 && sources[0] === \"'none'\") merged[name] = sources;\n }\n for (const [name, sources] of Object.entries(declared)) merged[name] ??= sources;\n for (const [name, sources] of Object.entries(configured)) {\n if (!(name in declared)) continue;\n if (sources === false) {\n delete merged[name];\n continue;\n }\n const ignored = sources.filter((source) => !declared[name]!.includes(source));\n if (ignored.length > 0) {\n config?.logger.warn(\n `tempestCsp: index.html declares ${name}, so directives[\"${name}\"] is not added to it ` +\n `(${ignored.join(\" \")}); the plugin never loosens a declared policy — add them to the <meta> instead`,\n );\n }\n }\n return merged;\n }\n\n /**\n * Report every inline `<script>` the final policy blocks. It only happens when\n * the app's declared policy governs `script-src` — directly or through\n * `default-src` — since the plugin then adds no hash, and the symptom would\n * otherwise be a script that silently never runs (under `vite dev`, the React\n * Refresh preamble, which takes the page down with it).\n *\n * `<script>` elements are governed by `script-src-elem` when the policy has\n * one, so that is the directive judged and named.\n *\n * @param html - The page, without its CSP `<meta>`.\n * @param directive - `\"script-src-elem\"` when declared, else `\"script-src\"`.\n * @param effective - The sources the browser will apply to inline `<script>`\n * elements, or `undefined` when no directive governs them.\n */\n function warnBlockedInlineScripts(\n html: string,\n directive: string,\n effective: readonly string[] | undefined,\n ): void {\n if (!effective || !config) return;\n const unsafeInline =\n effective.includes(\"'unsafe-inline'\") &&\n !effective.some((source) => /^'(?:sha\\d{3}|nonce)-/.test(source));\n if (unsafeInline) return;\n const blocked = inlineHashes(html, \"script\").filter((hash) => !effective.includes(hash));\n if (blocked.length === 0) return;\n config.logger.warn(\n `tempestCsp: the Content-Security-Policy declared in index.html blocks ${blocked.length} inline <script> ` +\n `(${directive} ${effective.join(\" \")}); the plugin never loosens a declared policy, so add ${blocked.join(\" \")} to ${directive}`,\n );\n }\n\n const plugin: Plugin = {\n name: \"tempest-csp\",\n configResolved(resolvedConfig) {\n config = resolvedConfig;\n resolved = resolveSources(resolvedConfig);\n },\n transformIndexHtml: {\n order: \"post\",\n handler(source, ctx) {\n const serve = config?.command === \"serve\";\n if (serve && !dev) return source;\n\n const connectSources = withSockets(resolved);\n const base = config?.base ?? \"/\";\n const baseOrigin = ABSOLUTE_URL.test(base) ? cspOrigin(base, \"base\") : undefined;\n if (baseOrigin) add(connectSources, baseOrigin, \"base\");\n const moduleIds = serve ? [] : bundleModuleIds(ctx);\n for (const known of SDK_ORIGINS) {\n if (serve || moduleIds.some((id) => known.module.test(id))) {\n add(connectSources, known.origin, known.from);\n }\n }\n const allSources = connectSources;\n\n const { html, declared = {} } = extractMetaPolicy(source);\n const policy = defaults(baseOrigin, serve);\n const filled = (name: string): boolean =>\n !(name in declared) && inheritedSources(declared, name) === undefined;\n if (filled(\"script-src\") && !(\"script-src-elem\" in declared)) {\n policy[\"script-src\"] = union(\n policy[\"script-src\"] ?? [],\n inlineHashes(html, \"script\"),\n );\n }\n if (\n filled(\"style-src\") &&\n !(\"style-src-elem\" in declared) &&\n !policy[\"style-src\"]?.includes(\"'unsafe-inline'\")\n ) {\n policy[\"style-src\"] = union(\n policy[\"style-src\"] ?? [],\n inlineHashes(html, \"style\"),\n );\n }\n const merged = mergePolicy(policy, declared);\n const origins = allSources.map((entry) => entry.origin);\n const inheritedConnect = inheritedSources(declared, \"connect-src\");\n const declaredConnect = merged[\"connect-src\"] ?? inheritedConnect;\n const declaredNone =\n declaredConnect?.length === 1 &&\n declaredConnect[0] === \"'none'\" &&\n (\"connect-src\" in declared || inheritedConnect !== undefined);\n if (declaredNone) {\n if (origins.length > 0) {\n config?.logger.warn(\n `tempestCsp: index.html declares connect-src 'none'${\"connect-src\" in declared ? \"\" : \" (through default-src)\"}, ` +\n `so these origins stay out and requests to them will be blocked: ${origins.join(\" \")}`,\n );\n }\n } else if (\n \"connect-src\" in merged ||\n origins.length > 0 ||\n inheritedConnect === undefined\n ) {\n merged[\"connect-src\"] = union(declaredConnect ?? [\"'self'\"], origins);\n }\n\n const scriptElem = \"script-src-elem\" in declared ? \"script-src-elem\" : \"script-src\";\n warnBlockedInlineScripts(\n html,\n scriptElem,\n merged[scriptElem] ?? inheritedSources(declared, scriptElem),\n );\n\n const result: TempestCspPolicy = {\n directives: merged,\n meta: serializeCsp(merged, \"meta\"),\n header: serializeCsp(merged, \"header\"),\n connect: allSources,\n command: serve ? \"serve\" : \"build\",\n };\n\n if (log && config && result.header !== lastLogged) {\n lastLogged = result.header;\n const lines = allSources.map((entry) => ` ${entry.origin} ← ${entry.from}`);\n config.logger.info(\n [\n `tempest-csp: connect-src ${(merged[\"connect-src\"] ?? inheritedConnect ?? []).join(\" \")}`,\n ...(lines.length > 0\n ? lines\n : [\" (no cross-origin endpoint: only 'self')\"]),\n ].join(\"\\n\"),\n );\n }\n onPolicy?.(result);\n return insertMeta(html, result.meta);\n },\n },\n };\n\n return plugin as TempestVitePlugin;\n}\n"],"mappings":"6BA6GA,IAAM,EAA8C,IAAI,IAAI,CACxD,kBACA,aACA,SACJ,CAAC,EAMK,EAA+E,CACjF,CACI,OAAQ,+CACR,OAAQ,wBACR,KAAM,6BACV,CACJ,EAuBM,EAA4D,CAC9D,kBAAmB,CAAC,aAAc,aAAa,EAC/C,kBAAmB,CAAC,aAAc,aAAa,EAC/C,iBAAkB,CAAC,YAAa,aAAa,EAC7C,iBAAkB,CAAC,YAAa,aAAa,EAC7C,aAAc,CAAC,YAAa,aAAc,aAAa,EACvD,YAAa,CAAC,YAAa,aAAa,EACxC,mBAAoB,CAAC,YAAa,YAAa,aAAa,EAC5D,YAAa,CAAC,aAAa,EAC3B,cAAe,CAAC,aAAa,EAC7B,WAAY,CAAC,aAAa,EAC1B,UAAW,CAAC,aAAa,EACzB,eAAgB,CAAC,aAAa,EAC9B,YAAa,CAAC,aAAa,EAC3B,aAAc,CAAC,aAAa,EAC5B,eAAgB,CAAC,aAAa,EAC9B,aAAc,CAAC,aAAa,EAC5B,YAAa,CAAC,aAAa,CAC/B,EAUA,SAAS,EACL,EACA,EACoB,CACpB,IAAK,IAAM,KAAU,EAAa,IAAS,CAAC,EACxC,GAAI,KAAU,EAAU,OAAO,EAAS,EAGhD,CAEA,IAAM,EAAe,yBACf,EAAkB,gEAUxB,SAAgB,EAAU,EAAe,EAAkC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AO,GAAU,EAAO,SAAW,EAAY,CAC/C,EAAa,EAAO,OACpB,IAAM,EAAQ,EAAW,IAAK,GAAU,KAAK,EAAM,OAAO,MAAM,EAAM,MAAM,EAC5E,EAAO,OAAO,KACV,CACI,6BAA6B,EAAO,gBAAkB,GAAoB,CAAC,EAAA,CAAG,KAAK,GAAG,IACtF,GAAI,EAAM,OAAS,EACb,EACA,CAAC,2CAA2C,CACtD,CAAC,CAAC,KAAK;CAAI,CACf,CACJ,CAEA,OADA,IAAW,CAAM,EACV,EAAW,EAAM,EAAO,IAAI,CACvC,CACJ,CAGG,CACX"}
@@ -8,13 +8,43 @@ var t = /* @__PURE__ */ new Set([
8
8
  module: /[\\/]forms[\\/]use-viacep\.(?:[cm]?js|tsx?)$/,
9
9
  origin: "https://viacep.com.br",
10
10
  from: "tempest-react-sdk useViaCEP"
11
- }], r = /^(?:https?|wss?):\/\//i, i = /^((?:https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?)(?:[/?#].*)?$/i;
12
- function a(e, t) {
11
+ }], r = {
12
+ "script-src-elem": ["script-src", "default-src"],
13
+ "script-src-attr": ["script-src", "default-src"],
14
+ "style-src-elem": ["style-src", "default-src"],
15
+ "style-src-attr": ["style-src", "default-src"],
16
+ "worker-src": [
17
+ "child-src",
18
+ "script-src",
19
+ "default-src"
20
+ ],
21
+ "frame-src": ["child-src", "default-src"],
22
+ "fenced-frame-src": [
23
+ "frame-src",
24
+ "child-src",
25
+ "default-src"
26
+ ],
27
+ "child-src": ["default-src"],
28
+ "connect-src": ["default-src"],
29
+ "font-src": ["default-src"],
30
+ "img-src": ["default-src"],
31
+ "manifest-src": ["default-src"],
32
+ "media-src": ["default-src"],
33
+ "object-src": ["default-src"],
34
+ "prefetch-src": ["default-src"],
35
+ "script-src": ["default-src"],
36
+ "style-src": ["default-src"]
37
+ };
38
+ function i(e, t) {
39
+ for (let n of r[t] ?? []) if (n in e) return e[n];
40
+ }
41
+ var a = /^(?:https?|wss?):\/\//i, o = /^((?:https?|wss?):\/\/\*\.[a-z0-9.-]+(?::\d+)?)(?:[/?#].*)?$/i;
42
+ function s(e, t) {
13
43
  let n = e.trim();
14
44
  if (n.startsWith("/") && !n.startsWith("//")) return;
15
- let a = i.exec(n);
16
- if (a) return a[1].toLowerCase();
17
- if (r.test(n)) try {
45
+ let r = o.exec(n);
46
+ if (r) return r[1].toLowerCase();
47
+ if (a.test(n)) try {
18
48
  let e = new URL(n);
19
49
  return `${e.protocol}//${e.host}`;
20
50
  } catch {
@@ -22,7 +52,7 @@ function a(e, t) {
22
52
  }
23
53
  throw Error(`tempestCsp: ${t} must be an absolute http(s)/ws(s) URL or a root-relative path, got "${e}"`);
24
54
  }
25
- function o(e) {
55
+ function c(e) {
26
56
  let t = {};
27
57
  for (let n of e.split(";")) {
28
58
  let [e, ...r] = n.trim().split(/\s+/);
@@ -32,97 +62,97 @@ function o(e) {
32
62
  }
33
63
  return t;
34
64
  }
35
- function s(e, n) {
65
+ function l(e, n) {
36
66
  return Object.entries(e).filter(([e]) => n === "header" || !t.has(e)).map(([e, t]) => [e, ...t].join(" ")).join("; ");
37
67
  }
38
- function c(e, t) {
68
+ function u(e, t) {
39
69
  let n = e.filter((e) => e !== "'none'" || t.length === 0);
40
70
  for (let e of t) n.includes(e) || n.push(e);
41
71
  return n.length === 0 ? ["'none'"] : n;
42
72
  }
43
- function l(t) {
73
+ function d(t) {
44
74
  return `'sha256-${e("sha256").update(t, "utf8").digest("base64")}'`;
45
75
  }
46
- function u(e) {
76
+ function f(e) {
47
77
  return e.replace(/&#39;|&#x27;|&apos;/gi, "'").replace(/&quot;/gi, "\"").replace(/&amp;/gi, "&");
48
78
  }
49
- function d(e) {
79
+ function p(e) {
50
80
  let t = {};
51
- for (let n of e.matchAll(/([^\s=<>/]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)) t[n[1].toLowerCase()] = u(n[2] ?? n[3] ?? n[4] ?? "");
81
+ for (let n of e.matchAll(/([^\s=<>/]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)) t[n[1].toLowerCase()] = f(n[2] ?? n[3] ?? n[4] ?? "");
52
82
  return t;
53
83
  }
54
- function f(e) {
55
- let t = [...e.matchAll(/<meta\b[^>]*>/gi)].filter((e) => d(e[0])["http-equiv"]?.toLowerCase() === "content-security-policy");
84
+ function m(e) {
85
+ let t = [...e.matchAll(/<meta\b[^>]*>/gi)].filter((e) => p(e[0])["http-equiv"]?.toLowerCase() === "content-security-policy");
56
86
  if (t.length === 0) return { html: e };
57
87
  if (t.length > 1) throw Error("tempestCsp: index.html declares more than one Content-Security-Policy <meta>; merge them into one");
58
88
  let n = t[0];
59
89
  return {
60
90
  html: e.slice(0, n.index) + e.slice(n.index + n[0].length).replace(/^[ \t]*\r?\n/, ""),
61
- declared: o(d(n[0]).content ?? "")
91
+ declared: c(p(n[0]).content ?? "")
62
92
  };
63
93
  }
64
- function p(e, t) {
94
+ function h(e, t) {
65
95
  let n = RegExp(`<${t}\\b([^>]*)>([\\s\\S]*?)</${t}>`, "gi"), r = [];
66
96
  for (let i of e.matchAll(n)) {
67
- let e = d(`<x ${i[1]}>`);
97
+ let e = p(`<x ${i[1]}>`);
68
98
  if (t === "script" && "src" in e || i[2].length === 0) continue;
69
- let n = l(i[2]);
99
+ let n = d(i[2]);
70
100
  r.includes(n) || r.push(n);
71
101
  }
72
102
  return r;
73
103
  }
74
- function m(e, t) {
104
+ function g(e, t) {
75
105
  let n = `<meta http-equiv="Content-Security-Policy" content="${t.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}" />`, r = /<meta\b[^>]*\bcharset\s*=[^>]*>/i.exec(e), i = /<head\b[^>]*>/i.exec(e), a = r !== null && i !== null && /<(?:script|link|style)\b/i.test(e.slice(i.index, r.index)), o = r && i && r.index > i.index && !a ? r : i;
76
106
  if (!o) return `${n}\n${e}`;
77
107
  let s = o.index + o[0].length;
78
108
  return `${e.slice(0, s)}\n ${n}${e.slice(s)}`;
79
109
  }
80
- function h(e) {
110
+ function _(e) {
81
111
  let t = [];
82
112
  for (let n of Object.values(e.bundle ?? {})) n.type === "chunk" && t.push(...n.moduleIds ?? Object.keys(n.modules ?? {}));
83
113
  return t;
84
114
  }
85
- function g(e = {}) {
86
- let { connect: t = [], env: i = !0, sockets: o = !0, wasm: l = !0, inlineStyles: u = !0, directives: d = {}, dev: g = !0, log: _ = !0, onPolicy: v } = e, y, b = [], x = "";
87
- function S(e, t, n) {
115
+ function v(e = {}) {
116
+ let { connect: t = [], env: r = !0, sockets: o = !0, wasm: c = !0, inlineStyles: d = !0, directives: f = {}, dev: p = !0, log: v = !0, onPolicy: y } = e, b = Object.fromEntries(Object.entries(f).map(([e, t]) => [e.toLowerCase(), t])), x, S = [], C = "";
117
+ function w(e, t, n) {
88
118
  t === void 0 || e.some((e) => e.origin === t) || e.push({
89
119
  origin: t,
90
120
  from: n
91
121
  });
92
122
  }
93
- function C(e) {
94
- let n = [], o = e.env ?? {}, s = [e.envPrefix ?? "VITE_"].flat();
95
- if (i === !0) for (let [e, t] of Object.entries(o)) s.some((t) => e.startsWith(t)) && typeof t == "string" && r.test(t.trim()) && S(n, a(t, `env ${e}`), `env ${e}`);
96
- else if (Array.isArray(i)) for (let t of i) {
97
- let r = o[t];
123
+ function T(e) {
124
+ let n = [], i = e.env ?? {}, o = [e.envPrefix ?? "VITE_"].flat();
125
+ if (r === !0) for (let [e, t] of Object.entries(i)) o.some((t) => e.startsWith(t)) && typeof t == "string" && a.test(t.trim()) && w(n, s(t, `env ${e}`), `env ${e}`);
126
+ else if (Array.isArray(r)) for (let t of r) {
127
+ let r = i[t];
98
128
  if (typeof r != "string" || r.trim() === "") {
99
129
  e.logger.warn(`tempestCsp: env ${t} is empty — nothing added to connect-src`);
100
130
  continue;
101
131
  }
102
- S(n, a(r, `env ${t}`), `env ${t}`);
132
+ w(n, s(r, `env ${t}`), `env ${t}`);
103
133
  }
104
134
  return t.forEach((t, r) => {
105
135
  if (!t || t.trim() === "") {
106
136
  e.logger.warn(`tempestCsp: connect[${r}] is empty — skipped, nothing added to connect-src`);
107
137
  return;
108
138
  }
109
- S(n, a(t, `connect[${r}]`), `connect[${r}]`);
139
+ w(n, s(t, `connect[${r}]`), `connect[${r}]`);
110
140
  }), n;
111
141
  }
112
- function w(e) {
142
+ function E(e) {
113
143
  let t = [...e];
114
144
  if (!o) return t;
115
145
  for (let { origin: n } of e) {
116
146
  let e = n.replace(/^http(s?):/i, "ws$1:");
117
- e !== n && S(t, e, `sockets (${n})`);
147
+ e !== n && w(t, e, `sockets (${n})`);
118
148
  }
119
149
  return t;
120
150
  }
121
- function T(e, t) {
151
+ function D(e, t) {
122
152
  let n = e ? ["'self'", e] : ["'self'"], r = {
123
153
  "default-src": [...n],
124
- "script-src": l ? [...n, "'wasm-unsafe-eval'"] : [...n],
125
- "style-src": u || t ? [...n, "'unsafe-inline'"] : [...n],
154
+ "script-src": c ? [...n, "'wasm-unsafe-eval'"] : [...n],
155
+ "style-src": d || t ? [...n, "'unsafe-inline'"] : [...n],
126
156
  "img-src": [
127
157
  ...n,
128
158
  "data:",
@@ -141,49 +171,74 @@ function g(e = {}) {
141
171
  "base-uri": ["'self'"],
142
172
  "form-action": ["'self'"]
143
173
  };
144
- for (let [e, t] of Object.entries(d)) {
145
- let n = e.toLowerCase();
146
- t === !1 ? delete r[n] : r[n] = c(r[n] ?? [], t);
147
- }
174
+ for (let [e, t] of Object.entries(b)) t === !1 ? delete r[e] : r[e] = u(r[e] ?? [], t);
148
175
  return r;
149
176
  }
177
+ function O(e, t) {
178
+ let n = {};
179
+ for (let [r, a] of Object.entries(e)) {
180
+ if (r in t) {
181
+ n[r] = t[r];
182
+ continue;
183
+ }
184
+ let e = i(t, r), o = b[r];
185
+ e === void 0 ? n[r] = a : Array.isArray(o) ? n[r] = u(e, o) : a.length === 1 && a[0] === "'none'" && (n[r] = a);
186
+ }
187
+ for (let [e, r] of Object.entries(t)) n[e] ??= r;
188
+ for (let [e, r] of Object.entries(b)) {
189
+ if (!(e in t)) continue;
190
+ if (r === !1) {
191
+ delete n[e];
192
+ continue;
193
+ }
194
+ let i = r.filter((n) => !t[e].includes(n));
195
+ i.length > 0 && x?.logger.warn(`tempestCsp: index.html declares ${e}, so directives["${e}"] is not added to it (${i.join(" ")}); the plugin never loosens a declared policy — add them to the <meta> instead`);
196
+ }
197
+ return n;
198
+ }
199
+ function k(e, t, n) {
200
+ if (!n || !x || n.includes("'unsafe-inline'") && !n.some((e) => /^'(?:sha\d{3}|nonce)-/.test(e))) return;
201
+ let r = h(e, "script").filter((e) => !n.includes(e));
202
+ r.length !== 0 && x.logger.warn(`tempestCsp: the Content-Security-Policy declared in index.html blocks ${r.length} inline <script> (${t} ${n.join(" ")}); the plugin never loosens a declared policy, so add ${r.join(" ")} to ${t}`);
203
+ }
150
204
  return {
151
205
  name: "tempest-csp",
152
206
  configResolved(e) {
153
- y = e, b = C(e);
207
+ x = e, S = T(e);
154
208
  },
155
209
  transformIndexHtml: {
156
210
  order: "post",
157
211
  handler(e, t) {
158
- let i = y?.command === "serve";
159
- if (i && !g) return e;
160
- let o = w(b), l = y?.base ?? "/", u = r.test(l) ? a(l, "base") : void 0;
161
- u && S(o, u, "base");
162
- let d = i ? [] : h(t);
163
- for (let e of n) (i || d.some((t) => e.module.test(t))) && S(o, e.origin, e.from);
164
- let C = o, { html: E, declared: D = {} } = f(e), O = T(u, i);
165
- "script-src" in D || (O["script-src"] = c(O["script-src"] ?? [], p(E, "script"))), !("style-src" in D) && !O["style-src"]?.includes("'unsafe-inline'") && (O["style-src"] = c(O["style-src"] ?? [], p(E, "style")));
166
- let k = { ...O };
167
- for (let [e, t] of Object.entries(D)) k[e] = t;
168
- k["connect-src"] = c(k["connect-src"] ?? ["'self'"], C.map((e) => e.origin));
169
- let A = {
170
- directives: k,
171
- meta: s(k, "meta"),
172
- header: s(k, "header"),
173
- connect: C,
174
- command: i ? "serve" : "build"
212
+ let r = x?.command === "serve";
213
+ if (r && !p) return e;
214
+ let o = E(S), c = x?.base ?? "/", d = a.test(c) ? s(c, "base") : void 0;
215
+ d && w(o, d, "base");
216
+ let f = r ? [] : _(t);
217
+ for (let e of n) (r || f.some((t) => e.module.test(t))) && w(o, e.origin, e.from);
218
+ let b = o, { html: T, declared: A = {} } = m(e), j = D(d, r), M = (e) => !(e in A) && i(A, e) === void 0;
219
+ M("script-src") && !("script-src-elem" in A) && (j["script-src"] = u(j["script-src"] ?? [], h(T, "script"))), M("style-src") && !("style-src-elem" in A) && !j["style-src"]?.includes("'unsafe-inline'") && (j["style-src"] = u(j["style-src"] ?? [], h(T, "style")));
220
+ let N = O(j, A), P = b.map((e) => e.origin), F = i(A, "connect-src"), I = N["connect-src"] ?? F;
221
+ I?.length === 1 && I[0] === "'none'" && ("connect-src" in A || F !== void 0) ? P.length > 0 && x?.logger.warn(`tempestCsp: index.html declares connect-src 'none'${"connect-src" in A ? "" : " (through default-src)"}, so these origins stay out and requests to them will be blocked: ${P.join(" ")}`) : ("connect-src" in N || P.length > 0 || F === void 0) && (N["connect-src"] = u(I ?? ["'self'"], P));
222
+ let L = "script-src-elem" in A ? "script-src-elem" : "script-src";
223
+ k(T, L, N[L] ?? i(A, L));
224
+ let R = {
225
+ directives: N,
226
+ meta: l(N, "meta"),
227
+ header: l(N, "header"),
228
+ connect: b,
229
+ command: r ? "serve" : "build"
175
230
  };
176
- if (_ && y && A.header !== x) {
177
- x = A.header;
178
- let e = C.map((e) => ` ${e.origin} ← ${e.from}`);
179
- y.logger.info([`tempest-csp: connect-src ${k["connect-src"].join(" ")}`, ...e.length > 0 ? e : [" (no cross-origin endpoint: only 'self')"]].join("\n"));
231
+ if (v && x && R.header !== C) {
232
+ C = R.header;
233
+ let e = b.map((e) => ` ${e.origin} ← ${e.from}`);
234
+ x.logger.info([`tempest-csp: connect-src ${(N["connect-src"] ?? F ?? []).join(" ")}`, ...e.length > 0 ? e : [" (no cross-origin endpoint: only 'self')"]].join("\n"));
180
235
  }
181
- return v?.(A), m(E, A.meta);
236
+ return y?.(R), g(T, R.meta);
182
237
  }
183
238
  }
184
239
  };
185
240
  }
186
241
  //#endregion
187
- export { a as cspOrigin, o as parseCsp, s as serializeCsp, g as tempestCsp };
242
+ export { s as cspOrigin, c as parseCsp, l as serializeCsp, v as tempestCsp };
188
243
 
189
244
  //# sourceMappingURL=tempest-csp.js.map