tempest-react-sdk 0.77.0 → 0.78.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/lib/alias/collect.mjs +20 -3
- package/bin/lib/alias/index.mjs +12 -1
- package/bin/lib/alias/index.test.mjs +24 -0
- package/bin/lib/css/analyze.test.mjs +21 -1
- package/bin/lib/css/collect.mjs +14 -0
- package/bin/lib/css/extract.mjs +63 -5
- package/bin/lib/css/extract.test.mjs +110 -1
- package/bin/lib/css/fix.e2e.test.mjs +50 -0
- package/bin/lib/css/index.mjs +6 -1
- package/bin/lib/fs/contain.mjs +50 -0
- package/bin/lib/icons/generate.mjs +28 -3
- package/bin/lib/icons/generate.test.mjs +57 -1
- package/bin/lib/openapi/escape.mjs +20 -6
- package/bin/lib/openapi/generate.encode.test.mjs +120 -0
- package/bin/lib/openapi/generate.hostile.test.mjs +38 -9
- package/bin/lib/openapi/generate.mjs +41 -6
- package/bin/lib/openapi/generate.test.mjs +7 -2
- package/bin/lib/openapi/schema-to-zod.mjs +5 -3
- package/bin/tempest-gen.test.mjs +188 -0
- package/bin/tempest.mjs +120 -44
- package/dist/auth/create-tempest-auth.cjs +1 -1
- package/dist/auth/create-tempest-auth.cjs.map +1 -1
- package/dist/auth/create-tempest-auth.js +186 -113
- package/dist/auth/create-tempest-auth.js.map +1 -1
- package/dist/br/pix.cjs +1 -1
- package/dist/br/pix.cjs.map +1 -1
- package/dist/br/pix.js +30 -27
- package/dist/br/pix.js.map +1 -1
- package/dist/br.d.ts +11 -4
- package/dist/components/CodeBlock/CodeBlock.cjs +1 -1
- package/dist/components/CodeBlock/CodeBlock.cjs.map +1 -1
- package/dist/components/CodeBlock/CodeBlock.js +1 -1
- package/dist/components/CodeBlock/CodeBlock.js.map +1 -1
- package/dist/components/CodeBlock/tokenize.cjs +1 -1
- package/dist/components/CodeBlock/tokenize.cjs.map +1 -1
- package/dist/components/CodeBlock/tokenize.js +54 -25
- package/dist/components/CodeBlock/tokenize.js.map +1 -1
- package/dist/components/Markdown/markdown-parse.cjs +6 -6
- package/dist/components/Markdown/markdown-parse.cjs.map +1 -1
- package/dist/components/Markdown/markdown-parse.js +91 -74
- package/dist/components/Markdown/markdown-parse.js.map +1 -1
- package/dist/http/resumable-upload.cjs +1 -1
- package/dist/http/resumable-upload.cjs.map +1 -1
- package/dist/http/resumable-upload.js +141 -105
- package/dist/http/resumable-upload.js.map +1 -1
- package/dist/http/retry.cjs +1 -1
- package/dist/http/retry.cjs.map +1 -1
- package/dist/http/retry.js +5 -6
- package/dist/http/retry.js.map +1 -1
- package/dist/sw/background-sync.cjs +1 -1
- package/dist/sw/background-sync.cjs.map +1 -1
- package/dist/sw/background-sync.js +32 -31
- package/dist/sw/background-sync.js.map +1 -1
- package/dist/sw/credential-headers.cjs.map +1 -1
- package/dist/sw/credential-headers.js.map +1 -1
- package/dist/sw.d.ts +46 -8
- package/dist/telemetry/app-error-reporter.cjs +1 -1
- package/dist/telemetry/app-error-reporter.cjs.map +1 -1
- package/dist/telemetry/app-error-reporter.js +1 -1
- package/dist/telemetry/app-error-reporter.js.map +1 -1
- package/dist/tempest-react-sdk.cjs +1 -1
- package/dist/tempest-react-sdk.d.ts +214 -12
- package/dist/tempest-react-sdk.js +119 -119
- package/dist/utils/csv.cjs +3 -3
- package/dist/utils/csv.cjs.map +1 -1
- package/dist/utils/csv.js +11 -10
- package/dist/utils/csv.js.map +1 -1
- package/dist/{telemetry/app-error-owner.cjs → utils/owner-fingerprint.cjs} +2 -2
- package/dist/utils/owner-fingerprint.cjs.map +1 -0
- package/dist/{telemetry/app-error-owner.js → utils/owner-fingerprint.js} +3 -3
- package/dist/utils/owner-fingerprint.js.map +1 -0
- package/dist/vite/tempest-csp.cjs +2 -2
- package/dist/vite/tempest-csp.cjs.map +1 -1
- package/dist/vite/tempest-csp.js +69 -58
- package/dist/vite/tempest-csp.js.map +1 -1
- package/dist/vite.d.ts +5 -3
- package/package.json +1 -1
- package/dist/telemetry/app-error-owner.cjs.map +0 -1
- package/dist/telemetry/app-error-owner.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tempest-csp.js","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(/'|'|'/gi, \"'\")\n .replace(/"/gi, '\"')\n .replace(/&/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, \"&\").replace(/\"/g, \""\");\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":";;AA6GA,IAAM,oBAA8C,IAAI,IAAI;CACxD;CACA;CACA;AACJ,CAAC,GAMK,IAA+E,CACjF;CACI,QAAQ;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"],"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\n/**\n * Compare a source with a CSP keyword (`'self'`, `'none'`, `'unsafe-inline'`…).\n * Keywords are ASCII case-insensitive (CSP3 §2.3.1), so `'NONE'` is `'none'`.\n *\n * @param source - A source expression as written.\n * @param keyword - The keyword, quoted and lowercase.\n * @returns Whether the source is that keyword.\n */\nfunction isKeyword(source: string, keyword: string): boolean {\n return source.toLowerCase() === keyword;\n}\n\n/**\n * Whether a source list matches nothing: CSP3 §6.7.2.5 gives \"does not match\"\n * for an empty list and for one that holds only `'none'` — in any letter case.\n *\n * @param sources - The directive's sources.\n * @returns `true` for `[]`, `['none']`, `['NONE']`, `['none', 'None']`.\n */\nfunction matchesNothing(sources: readonly string[]): boolean {\n return sources.every((source) => isKeyword(source, \"'none'\"));\n}\n\n/**\n * Lowercase the algorithm (or `nonce`) prefix of a hash or nonce source,\n * leaving the case-sensitive base64 value alone, so `'SHA256-…'` compares\n * equal to the `'sha256-…'` the plugin computes.\n *\n * @param source - A source expression as written.\n * @returns The source with a normalized prefix.\n */\nfunction normalizeHashSource(source: string): string {\n return source.replace(/^'(?:sha\\d{3}|nonce)-/i, (prefix) => prefix.toLowerCase());\n}\n\nfunction union(base: readonly string[], extra: readonly string[]): string[] {\n const out = base.filter((source) => !isKeyword(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(/'|'|'/gi, \"'\")\n .replace(/"/gi, '\"')\n .replace(/&/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, \"&\").replace(/\"/g, \""\");\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\n * matches nothing — `'none'` in any letter case, or an empty list, declared or\n * inherited from `default-src` — in which case the origins stay out and each\n * one is reported as a build warning. Keywords are compared case-insensitively\n * throughout, as browsers do. 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 > 0 && matchesNothing(sources)) 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 normalized = effective.map(normalizeHashSource);\n const unsafeInline =\n effective.some((source) => isKeyword(source, \"'unsafe-inline'\")) &&\n !normalized.some((source) => /^'(?:sha\\d{3}|nonce)-/.test(source));\n if (unsafeInline) return;\n const blocked = inlineHashes(html, \"script\").filter((hash) => !normalized.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\"]?.some((source) => isKeyword(source, \"'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 !== undefined &&\n matchesNothing(declaredConnect) &&\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 ${declaredConnect.join(\" \") || \"with no source\"}${\"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":";;AA6GA,IAAM,oBAA8C,IAAI,IAAI;CACxD;CACA;CACA;AACJ,CAAC,GAMK,IAA+E,CACjF;CACI,QAAQ;CACR,QAAQ;CACR,MAAM;AACV,CACJ,GAuBM,IAA4D;CAC9D,mBAAmB,CAAC,cAAc,aAAa;CAC/C,mBAAmB,CAAC,cAAc,aAAa;CAC/C,kBAAkB,CAAC,aAAa,aAAa;CAC7C,kBAAkB,CAAC,aAAa,aAAa;CAC7C,cAAc;EAAC;EAAa;EAAc;CAAa;CACvD,aAAa,CAAC,aAAa,aAAa;CACxC,oBAAoB;EAAC;EAAa;EAAa;CAAa;CAC5D,aAAa,CAAC,aAAa;CAC3B,eAAe,CAAC,aAAa;CAC7B,YAAY,CAAC,aAAa;CAC1B,WAAW,CAAC,aAAa;CACzB,gBAAgB,CAAC,aAAa;CAC9B,aAAa,CAAC,aAAa;CAC3B,cAAc,CAAC,aAAa;CAC5B,gBAAgB,CAAC,aAAa;CAC9B,cAAc,CAAC,aAAa;CAC5B,aAAa,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GAChD,IAAmB,EAAiB,GAAU,aAAa,GAC3D,IAAkB,EAAO,kBAAkB;IAKjD,AAHI,MAAoB,KAAA,KACpB,EAAe,CAAe,MAC7B,iBAAiB,KAAY,MAAqB,KAAA,KAE/C,EAAQ,SAAS,KACjB,GAAQ,OAAO,KACX,+CAA+C,EAAgB,KAAK,GAAG,KAAK,mBAAmB,iBAAiB,IAAW,KAAK,yBAAyB,oEAClF,EAAQ,KAAK,GAAG,GAC3F,KAGJ,iBAAiB,KACjB,EAAQ,SAAS,KACjB,MAAqB,KAAA,OAErB,EAAO,iBAAiB,EAAM,KAAmB,CAAC,QAAQ,GAAG,CAAO;IAGxE,IAAM,IAAa,qBAAqB,IAAW,oBAAoB;IACvE,EACI,GACA,GACA,EAAO,MAAe,EAAiB,GAAU,CAAU,CAC/D;IAEA,IAAM,IAA2B;KAC7B,YAAY;KACZ,MAAM,EAAa,GAAQ,MAAM;KACjC,QAAQ,EAAa,GAAQ,QAAQ;KACrC,SAAS;KACT,SAAS,IAAQ,UAAU;IAC/B;IAEA,IAAI,KAAO,KAAU,EAAO,WAAW,GAAY;KAC/C,IAAa,EAAO;KACpB,IAAM,IAAQ,EAAW,KAAK,MAAU,KAAK,EAAM,OAAO,MAAM,EAAM,MAAM;KAC5E,EAAO,OAAO,KACV,CACI,6BAA6B,EAAO,kBAAkB,KAAoB,CAAC,EAAA,CAAG,KAAK,GAAG,KACtF,GAAI,EAAM,SAAS,IACb,IACA,CAAC,2CAA2C,CACtD,CAAC,CAAC,KAAK,IAAI,CACf;IACJ;IAEA,OADA,IAAW,CAAM,GACV,EAAW,GAAM,EAAO,IAAI;GACvC;EACJ;CAGG;AACX"}
|
package/dist/vite.d.ts
CHANGED
|
@@ -117,9 +117,11 @@ export declare interface StyleManifest {
|
|
|
117
117
|
* merge never loosens what the app wrote:
|
|
118
118
|
*
|
|
119
119
|
* - a directive it declares is kept verbatim, except `connect-src`, which gains
|
|
120
|
-
* the resolved origins (the list the plugin exists to maintain) unless it
|
|
121
|
-
* `'none'`
|
|
122
|
-
*
|
|
120
|
+
* the resolved origins (the list the plugin exists to maintain) unless it
|
|
121
|
+
* matches nothing — `'none'` in any letter case, or an empty list, declared or
|
|
122
|
+
* inherited from `default-src` — in which case the origins stay out and each
|
|
123
|
+
* one is reported as a build warning. Keywords are compared case-insensitively
|
|
124
|
+
* throughout, as browsers do. Sources in
|
|
123
125
|
* {@link TempestCspOptions.directives} for a declared directive are not added
|
|
124
126
|
* (a build warning names them); `false` there removes it;
|
|
125
127
|
* - a fetch directive it does not declare but already governs through the CSP3
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"app-error-owner.cjs","names":[],"sources":["../../src/telemetry/app-error-owner.ts"],"sourcesContent":["/**\n * FNV-1a 32-bit offset basis, the seed of the first half of the fingerprint.\n *\n * Ported from the FNV specification (Fowler/Noll/Vo, `offset_basis` for 32 bits).\n */\nexport const FNV_OFFSET_BASIS_32 = 0x811c9dc5;\n\n/**\n * FNV-1a 32-bit prime.\n *\n * Ported from the FNV specification (Fowler/Noll/Vo, `FNV_prime` for 32 bits).\n */\nexport const FNV_PRIME_32 = 0x01000193;\n\n/**\n * Seed of the second half of the fingerprint: the basis with every bit\n * flipped, so the two halves are independent hashes of the same text.\n */\nconst SECOND_SEED = ~FNV_OFFSET_BASIS_32 >>> 0;\n\n/**\n * Hash `text` with FNV-1a from `seed`.\n *\n * @param text - What to hash, read as UTF-16 code units.\n * @param seed - Starting value.\n * @returns The 32-bit hash as an unsigned integer.\n */\nfunction fnv1a(text: string, seed: number): number {\n let hash = seed;\n for (let index = 0; index < text.length; index += 1) {\n hash ^= text.charCodeAt(index);\n hash = Math.imul(hash, FNV_PRIME_32);\n }\n return hash >>> 0;\n}\n\n/**\n * A 64-bit one-way fingerprint of `text`, as 16 hex characters.\n *\n * Not a cryptographic hash, and it does not need to be: it only has to tell\n * two signed-in identities apart on one device, and it must not let anyone\n * holding the stored queue send as the user. Sixty-four bits cannot be turned\n * back into a bearer token, and two different users colliding on one browser\n * is a one-in-2^64 event. A synchronous hash is what lets `report()` stamp the\n * owner without awaiting `crypto.subtle`.\n *\n * @param text - The principal or token to fingerprint.\n * @returns Sixteen lowercase hex characters.\n */\nexport function fingerprintAppErrorOwner(text: string): string {\n const first = fnv1a(text, FNV_OFFSET_BASIS_32).toString(16).padStart(8, \"0\");\n const second = fnv1a(text, SECOND_SEED).toString(16).padStart(8, \"0\");\n return `${first}${second}`;\n}\n\n/**\n * Turn a principal or a token into the fingerprint a queue entry stores.\n *\n * The prefix keeps the two sources from ever matching each other: a report\n * stamped from a principal is never taken for one stamped from a token.\n *\n * Only a non-empty string or a finite number is an identity. Anything else —\n * notably the `Promise` an `async` getter returns from untyped JS — reads as\n * nobody, because stringifying it would give every user the same\n * `\"[object Promise]\"` fingerprint.\n *\n * @param source - `\"p\"` for a principal from `getPrincipal`, `\"t\"` for a token.\n * @param value - The identity, or nothing when nobody is signed in.\n * @returns `\"<source>:<fingerprint>\"`, or `null` when `value` is no identity.\n */\nexport function appErrorOwner(source: \"p\" | \"t\", value: unknown): string | null {\n const text =\n typeof value === \"string\"\n ? value\n : typeof value === \"number\" && Number.isFinite(value)\n ? String(value)\n : \"\";\n return text ? `${source}:${fingerprintAppErrorOwner(text)}` : null;\n}\n"],"mappings":"AAKA,IAAa,EAAsB,WAOtB,EAAe,SAe5B,SAAS,EAAM,EAAc,EAAsB,CAC/C,IAAI,EAAO,EACX,IAAK,IAAI,EAAQ,EAAG,EAAQ,EAAK,OAAQ,GAAS,EAC9C,GAAQ,EAAK,WAAW,CAAK,EAC7B,EAAO,KAAK,KAAK,EAAM,CAAY,EAEvC,OAAO,IAAS,CACpB,CAeA,SAAgB,EAAyB,EAAsB,CAG3D,MAAO,GAFO,EAAM,EAAM,CAAmB,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAE9D,IADK,EAAM,EAAM,UAAW,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,EAAG,GAC/C,GACtB,CAiBA,SAAgB,EAAc,EAAmB,EAA+B,CAC5E,IAAM,EACF,OAAO,GAAU,SACX,EACA,OAAO,GAAU,UAAY,OAAO,SAAS,CAAK,EAChD,OAAO,CAAK,EACZ,GACZ,OAAO,EAAO,GAAG,EAAO,GAAG,EAAyB,CAAI,IAAM,IAClE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"app-error-owner.js","names":[],"sources":["../../src/telemetry/app-error-owner.ts"],"sourcesContent":["/**\n * FNV-1a 32-bit offset basis, the seed of the first half of the fingerprint.\n *\n * Ported from the FNV specification (Fowler/Noll/Vo, `offset_basis` for 32 bits).\n */\nexport const FNV_OFFSET_BASIS_32 = 0x811c9dc5;\n\n/**\n * FNV-1a 32-bit prime.\n *\n * Ported from the FNV specification (Fowler/Noll/Vo, `FNV_prime` for 32 bits).\n */\nexport const FNV_PRIME_32 = 0x01000193;\n\n/**\n * Seed of the second half of the fingerprint: the basis with every bit\n * flipped, so the two halves are independent hashes of the same text.\n */\nconst SECOND_SEED = ~FNV_OFFSET_BASIS_32 >>> 0;\n\n/**\n * Hash `text` with FNV-1a from `seed`.\n *\n * @param text - What to hash, read as UTF-16 code units.\n * @param seed - Starting value.\n * @returns The 32-bit hash as an unsigned integer.\n */\nfunction fnv1a(text: string, seed: number): number {\n let hash = seed;\n for (let index = 0; index < text.length; index += 1) {\n hash ^= text.charCodeAt(index);\n hash = Math.imul(hash, FNV_PRIME_32);\n }\n return hash >>> 0;\n}\n\n/**\n * A 64-bit one-way fingerprint of `text`, as 16 hex characters.\n *\n * Not a cryptographic hash, and it does not need to be: it only has to tell\n * two signed-in identities apart on one device, and it must not let anyone\n * holding the stored queue send as the user. Sixty-four bits cannot be turned\n * back into a bearer token, and two different users colliding on one browser\n * is a one-in-2^64 event. A synchronous hash is what lets `report()` stamp the\n * owner without awaiting `crypto.subtle`.\n *\n * @param text - The principal or token to fingerprint.\n * @returns Sixteen lowercase hex characters.\n */\nexport function fingerprintAppErrorOwner(text: string): string {\n const first = fnv1a(text, FNV_OFFSET_BASIS_32).toString(16).padStart(8, \"0\");\n const second = fnv1a(text, SECOND_SEED).toString(16).padStart(8, \"0\");\n return `${first}${second}`;\n}\n\n/**\n * Turn a principal or a token into the fingerprint a queue entry stores.\n *\n * The prefix keeps the two sources from ever matching each other: a report\n * stamped from a principal is never taken for one stamped from a token.\n *\n * Only a non-empty string or a finite number is an identity. Anything else —\n * notably the `Promise` an `async` getter returns from untyped JS — reads as\n * nobody, because stringifying it would give every user the same\n * `\"[object Promise]\"` fingerprint.\n *\n * @param source - `\"p\"` for a principal from `getPrincipal`, `\"t\"` for a token.\n * @param value - The identity, or nothing when nobody is signed in.\n * @returns `\"<source>:<fingerprint>\"`, or `null` when `value` is no identity.\n */\nexport function appErrorOwner(source: \"p\" | \"t\", value: unknown): string | null {\n const text =\n typeof value === \"string\"\n ? value\n : typeof value === \"number\" && Number.isFinite(value)\n ? String(value)\n : \"\";\n return text ? `${source}:${fingerprintAppErrorOwner(text)}` : null;\n}\n"],"mappings":";AAKA,IAAa,IAAsB,YAOtB,IAAe;AAe5B,SAAS,EAAM,GAAc,GAAsB;CAC/C,IAAI,IAAO;CACX,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAK,QAAQ,KAAS,GAE9C,AADA,KAAQ,EAAK,WAAW,CAAK,GAC7B,IAAO,KAAK,KAAK,GAAM,CAAY;CAEvC,OAAO,MAAS;AACpB;AAeA,SAAgB,EAAyB,GAAsB;CAG3D,OAAO,GAFO,EAAM,GAAM,CAAmB,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAE9D,IADK,EAAM,GAAM,UAAW,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAC/C;AACtB;AAiBA,SAAgB,EAAc,GAAmB,GAA+B;CAC5E,IAAM,IACF,OAAO,KAAU,WACX,IACA,OAAO,KAAU,YAAY,OAAO,SAAS,CAAK,IAChD,OAAO,CAAK,IACZ;CACZ,OAAO,IAAO,GAAG,EAAO,GAAG,EAAyB,CAAI,MAAM;AAClE"}
|