diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 000000000..fcadb2cf9
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1 @@
+* text eol=lf
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index 203f3c889..58dacf882 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -1,6 +1,106 @@
version: 2
updates:
-- package-ecosystem: "github-actions"
- directory: "/"
- schedule:
- interval: "weekly"
+ # GitHub Actions: weekly, grouped. SHA-pinning means most updates are just
+ # noise unless a real CVE lands; weekly cadence is plenty.
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
+ groups:
+ actions:
+ patterns:
+ - '*'
+ # Main npm tree (build, test, lint tooling). Weekly + grouped minor/patch so
+ # routine bumps land in one reviewable PR; majors stay separate.
+ - package-ecosystem: npm
+ directory: /
+ schedule:
+ interval: weekly
+ groups:
+ dev-dependencies:
+ patterns:
+ - '*'
+ update-types:
+ - minor
+ - patch
+ # Consumer-shape verification harnesses under typescript/. These exist to
+ # catch packaging regressions, not to ship code - group them all together
+ # so we don't get six separate PRs every time @types/node bumps.
+ - package-ecosystem: npm
+ directory: /typescript
+ schedule:
+ interval: weekly
+ groups:
+ typescript-harness:
+ patterns:
+ - '*'
+ - package-ecosystem: npm
+ directory: /typescript/esm
+ schedule:
+ interval: weekly
+ groups:
+ typescript-harness:
+ patterns:
+ - '*'
+ - package-ecosystem: npm
+ directory: /typescript/esm-with-no-types
+ schedule:
+ interval: weekly
+ groups:
+ typescript-harness:
+ patterns:
+ - '*'
+ - package-ecosystem: npm
+ directory: /typescript/esm-with-specific-types
+ schedule:
+ interval: weekly
+ groups:
+ typescript-harness:
+ patterns:
+ - '*'
+ # Legacy-browser harness: intentionally frozen old Playwright builds used
+ # only to exercise DOMPurify against older engines. They are never shipped
+ # and never updated (bumping them defeats the purpose). This entry exists
+ # solely to stop Dependabot trying - and failing - to open security-update
+ # PRs for them: open-pull-requests-limit 0 disables version PRs, and the
+ # ignore suppresses the playwright security-update attempts. NOTE: this only
+ # quiets Dependabot. OpenSSF Scorecard scans the lockfile via OSV separately
+ # and needs a root osv-scanner.toml entry to clear GHSA-7mvr-c777-76hp.
+ - package-ecosystem: npm
+ directory: /test/legacy-playwright
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 0
+ ignore:
+ - dependency-name: playwright
+ # ---------------------------------------------------------------------
+ # 2.x LTS branch. Dependabot watches exactly one branch per entry, so
+ # the entries above (without target-branch) apply only to main. Mirror
+ # the actions and root-npm entries here so 2.x receives routine
+ # dependency updates too. The /typescript/... entries are not mirrored:
+ # those harnesses don't exist on 2.x. Security updates (driven by GHSA
+ # matches) reach 2.x automatically and bypass group settings, so an
+ # incoming CVE patch lands as its own PR rather than being bundled
+ # with the weekly grouped batch.
+ # ---------------------------------------------------------------------
+ - package-ecosystem: github-actions
+ directory: /
+ target-branch: '2.x'
+ schedule:
+ interval: weekly
+ groups:
+ actions:
+ patterns:
+ - '*'
+ - package-ecosystem: npm
+ directory: /
+ target-branch: '2.x'
+ schedule:
+ interval: weekly
+ groups:
+ dev-dependencies:
+ patterns:
+ - '*'
+ update-types:
+ - minor
+ - patch
diff --git a/.github/workflows/build-and-test-skip.yml b/.github/workflows/build-and-test-skip.yml
new file mode 100644
index 000000000..a0123ed6c
--- /dev/null
+++ b/.github/workflows/build-and-test-skip.yml
@@ -0,0 +1,70 @@
+name: Build & Test
+
+# Companion workflow for build-and-test.yml.
+#
+# Background: GitHub's required-status-check system leaves PRs stuck in
+# "Waiting for status to be reported" when the workflow that would provide
+# the check is skipped via paths-ignore. GitHub's own documented workaround
+# is to define a twin workflow with the SAME workflow name and SAME job
+# names, gated on the INVERSE path filter, that does nothing but succeed.
+#
+# https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/troubleshooting-required-status-checks#handling-skipped-but-required-checks
+#
+# RULES FOR EDITING THIS FILE:
+#
+# 1. The top-level `name:` must match build-and-test.yml exactly. GitHub
+# identifies required checks by (workflow name, job name) tuple.
+#
+# 2. The `install` job's matrix and name must produce the SAME check
+# names as build-and-test.yml: "install (20.x)", "install (22.x)",
+# "install (24.x)", "install (25.x)", "install (26.x)".
+#
+# 3. The `paths` list below must be the INVERSE of the `paths-ignore`
+# list in build-and-test.yml. If you exclude a path there, include it
+# here (and vice versa). Mismatched lists = the real tests are
+# skipped AND this passthrough doesn't fire = PR hangs.
+#
+# 4. Every job is a no-op that exits 0. Do NOT add real work here - this
+# file exists purely to satisfy the required-check machinery.
+
+on:
+ pull_request:
+ paths:
+ - '**/*.md'
+ - 'demos/**'
+ - 'website/**'
+ - 'LICENSE'
+ - '.gitattributes'
+ - '.editorconfig'
+ - '.prettierrc'
+ - '.nvmrc'
+ - '.gitignore'
+ - '.husky/**'
+ - 'osv-scanner.toml'
+ - '.github/ISSUE_TEMPLATE.md'
+ - '.github/PULL_REQUEST_TEMPLATE.md'
+ - '.github/FUNDING.yml'
+ - '.github/dependabot.yml'
+ - '.github/workflows/codeql-analysis.yml'
+ - '.github/workflows/dependency-review.yml'
+ - '.github/workflows/fuzz.yml'
+ - '.github/workflows/scorecard.yml'
+ - '.github/workflows/sign-release.yml'
+ - '.github/workflows/slsa-provenance.yml'
+ - '.github/workflows/legacy-browsers.yml'
+
+permissions:
+ contents: read
+
+jobs:
+ install:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ node-version: [20.x, 22.x, 24.x, 25.x, 26.x]
+ steps:
+ - name: No-op (docs-only change, real tests skipped)
+ run: |
+ echo "Skipping build & test - change only touched documentation or"
+ echo "metadata files (see paths-ignore in build-and-test.yml)."
+ echo "Reporting success so the required status check doesn't hang."
diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml
index 97a99114c..5e40746ab 100644
--- a/.github/workflows/build-and-test.yml
+++ b/.github/workflows/build-and-test.yml
@@ -1,47 +1,208 @@
-name: Build and Test
+name: Build & Test
-# The event triggers are configured as following:
-# - on `main` -> trigger the workflow on every push
-# - on any pull request -> trigger the workflow
-# This is to avoid running the workflow twice on pull requests.
on:
push:
branches:
- main
- 3.x
- 2.x
+ # Skip on docs-only / metadata-only pushes. Keep this list in SYNC with
+ # build-and-test-skip.yml - that companion workflow reports success for
+ # the same required-check names when this one is skipped, otherwise PRs
+ # that only touch docs would hang forever on "Waiting for status to be
+ # reported" (GitHub's well-known paths-filter + required-check gotcha).
+ paths-ignore:
+ - '**/*.md'
+ - 'demos/**'
+ - 'website/**'
+ - 'LICENSE'
+ - '.gitattributes'
+ - '.editorconfig'
+ - '.prettierrc'
+ - '.nvmrc'
+ - '.gitignore'
+ - '.husky/**'
+ - 'osv-scanner.toml'
+ - '.github/ISSUE_TEMPLATE.md'
+ - '.github/PULL_REQUEST_TEMPLATE.md'
+ - '.github/FUNDING.yml'
+ - '.github/dependabot.yml'
+ - '.github/workflows/codeql-analysis.yml'
+ - '.github/workflows/dependency-review.yml'
+ - '.github/workflows/fuzz.yml'
+ - '.github/workflows/scorecard.yml'
+ - '.github/workflows/sign-release.yml'
+ - '.github/workflows/slsa-provenance.yml'
+ - '.github/workflows/legacy-browsers.yml'
pull_request:
+ paths-ignore:
+ - '**/*.md'
+ - 'demos/**'
+ - 'website/**'
+ - 'LICENSE'
+ - '.gitattributes'
+ - '.editorconfig'
+ - '.prettierrc'
+ - '.nvmrc'
+ - '.gitignore'
+ - '.husky/**'
+ - 'osv-scanner.toml'
+ - '.github/ISSUE_TEMPLATE.md'
+ - '.github/PULL_REQUEST_TEMPLATE.md'
+ - '.github/FUNDING.yml'
+ - '.github/dependabot.yml'
+ - '.github/workflows/codeql-analysis.yml'
+ - '.github/workflows/dependency-review.yml'
+ - '.github/workflows/fuzz.yml'
+ - '.github/workflows/scorecard.yml'
+ - '.github/workflows/sign-release.yml'
+ - '.github/workflows/slsa-provenance.yml'
+ - '.github/workflows/legacy-browsers.yml'
+
+permissions:
+ contents: read
+
+# Cancel superseded runs on the same PR to save minutes on rapid pushes.
+# Pushes to protected branches are NOT cancelled - we want full CI history
+# for every merged commit.
+concurrency:
+ group: build-test-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
+ # Fast feedback: lint, build, dist-sync and jsdom across all supported
+ # Node versions. The full three-engine browser suite runs once, on the
+ # primary Node version only - browser behaviour is Node-independent, so
+ # repeating it per Node entry added cost without coverage.
+ # Runs on every push and every PR.
install:
runs-on: ubuntu-latest
strategy:
matrix:
- node-version: [18.x, 19.x, 20.x, 21.x, 22.x, 23.x]
+ node-version: [20.x, 22.x, 24.x, 25.x, 26.x]
steps:
+ - name: Harden the runner (Audit all outbound calls)
+ uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4
+ with:
+ egress-policy: audit
+
- name: Checkout
- uses: actions/checkout@v6
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
+ with:
+ persist-credentials: false
+
- name: Setup Node.js ${{ matrix.node-version }}
- uses: actions/setup-node@v6
+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: ${{ matrix.node-version }}
- cache: 'npm'
+ cache: npm
+
- name: Install Dependencies
- run: npm ci
+ run: npm ci --ignore-scripts
+
+ # All three engines, but only on the primary Node version (the same
+ # one the browser-matrix job uses). DOMPurify's security posture
+ # depends on per-engine HTML parser behaviour being exercised on
+ # every PR - but the browsers don't care which Node drives them, so
+ # installing and running 3 engines x 5 Node versions repeated the
+ # same suite 15 times. This gate keeps the full per-engine coverage
+ # once per PR and drops the 12 redundant runs.
+ - name: Install Playwright Browsers
+ if: matrix.node-version == '25.x'
+ run: ./node_modules/.bin/playwright install --with-deps chromium firefox webkit
+
- name: Build
run: npm run build
+
+ - name: Verify dist/ matches src/
+ run: |
+ if ! git diff --quiet dist/; then
+ echo "::error::dist/ is out of sync with src/. The husky pre-commit hook should have rebuilt dist/ before commit. Did you commit without running 'npm install' first (which wires up the hook), or bypass hooks with --no-verify?"
+ echo "--- dist/ diff ---"
+ git diff --stat dist/
+ git diff dist/ | head -100
+ exit 1
+ fi
+ echo "dist/ matches src/ ✓"
+
- name: Lint
run: npm run lint
- - name: Test
- uses: GabrielBB/xvfb-action@v1.7
- with:
- run: npm run test:ci
- env:
- TEST_BROWSERSTACK: ${{ startsWith(matrix.node-version, '22') }}
- TEST_PROBE_ONLY: ${{ github.ref != 'refs/heads/main' && github.ref != 'refs/heads/2.x' }}
- BS_USERNAME: ${{ secrets.BS_USERNAME }}
- BS_ACCESSKEY: ${{ secrets.BS_ACCESSKEY }}
+
+ - name: Test (jsdom + full browser matrix)
+ if: matrix.node-version == '25.x'
+ run: npm run test:ci
+
+ - name: Test (jsdom)
+ if: matrix.node-version != '25.x'
+ run: npm run test:jsdom
+
+ - name: Upload Playwright report
+ if: failure() && matrix.node-version == '25.x'
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: playwright-report-node-${{ matrix.node-version }}
+ path: playwright-report/
+ retention-days: 7
+
- name: Verify TypeScript
run: npm run verify-typescript
+
+ # Browser diversity: chromium + firefox + webkit across Ubuntu, macOS, and
+ # Windows. Catches OS-specific rendering quirks (e.g. macOS WebKit ≈ real
+ # Safari engine, Windows font shaping, Linux-specific parser paths).
+ #
+ # Only runs on release branches (main, 2.x, 3.x) to conserve runner minutes.
+ # PRs get full three-engine coverage on a single Node version from the
+ # "install" job above, which is sufficient for catching regressions.
+ browser-matrix:
+ if: github.event_name == 'push'
+ runs-on: ${{ matrix.os }}
+
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+
+ steps:
+ - name: Harden the runner (Audit all outbound calls)
+ uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4
+ with:
+ egress-policy: audit
+
+ - name: Checkout
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
+ with:
+ persist-credentials: false
+
+ - name: Setup Node.js 25.x
+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
+ with:
+ node-version: 25.x
+ cache: npm
+
+ - name: Install Dependencies
+ run: npm ci --ignore-scripts
+
+ - name: Install Playwright Browsers (Linux)
+ if: runner.os == 'Linux'
+ run: ./node_modules/.bin/playwright install --with-deps chromium firefox webkit
+
+ - name: Install Playwright Browsers (macOS / Windows)
+ if: runner.os != 'Linux'
+ run: ./node_modules/.bin/playwright install chromium firefox webkit
+
+ - name: Build
+ run: npm run build
+
+ - name: Run browser tests (all engines)
+ run: npm run test:browser
+
+ - name: Upload Playwright report
+ if: failure()
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: playwright-report-${{ matrix.os }}
+ path: playwright-report/
+ retention-days: 7
diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
index 39ee2a380..bd50c1093 100644
--- a/.github/workflows/codeql-analysis.yml
+++ b/.github/workflows/codeql-analysis.yml
@@ -2,15 +2,25 @@ name: "CodeQL"
on:
push:
- branches: [main]
+ branches: [main, 3.x, 2.x]
pull_request:
- # The branches below must be a subset of the branches above
- branches: [main]
+ # Must match 'push' so PRs targeting release branches also get scanned.
+ # The ruleset requires CodeQL as a status check on main, 3.x, and 2.x;
+ # without these in pull_request, PRs to 3.x/2.x would wait forever for
+ # a required check that never fires.
+ branches: [main, 3.x, 2.x]
schedule:
- cron: '0 19 * * 4'
+permissions:
+ contents: read
+
jobs:
analyze:
+ permissions:
+ actions: read # for github/codeql-action/init to get workflow details
+ contents: read # for actions/checkout to fetch code
+ security-events: write # for github/codeql-action/autobuild to send a status report
name: Analyze
runs-on: ubuntu-latest
@@ -24,28 +34,30 @@ jobs:
# https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
steps:
- - name: Checkout repository
- uses: actions/checkout@v6
+ - name: Harden the runner (Audit all outbound calls)
+ uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4
with:
- # We must fetch at least the immediate parents so that if this is
- # a pull request then we can checkout the head.
- fetch-depth: 2
+ egress-policy: audit
- # If this run was triggered by a pull request event, then checkout
- # the head of the pull request instead of the merge commit.
- - run: git checkout HEAD^2
- if: ${{ github.event_name == 'pull_request' }}
+ - name: Checkout repository
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
+ with:
+ persist-credentials: false
+ # Default fetch-depth is fine. The old 'git checkout HEAD^2' dance
+ # from legacy CodeQL templates is no longer needed - modern
+ # codeql-action handles PR head checkout itself, and under this
+ # repo's linear-history ruleset PRs aren't two-parent merges anyway.
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
- uses: github/codeql-action/init@v4
+ uses: github/codeql-action/init@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
with:
languages: ${{ matrix.language }}
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
- uses: github/codeql-action/autobuild@v4
+ uses: github/codeql-action/autobuild@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
# ℹ️ Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
@@ -59,4 +71,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v4
+ uses: github/codeql-action/analyze@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml
new file mode 100644
index 000000000..203adb95c
--- /dev/null
+++ b/.github/workflows/dependency-review.yml
@@ -0,0 +1,39 @@
+# Dependency Review Action
+#
+# This Action will scan dependency manifest files that change as part of a Pull Request,
+# surfacing known-vulnerable versions of the packages declared or updated in the PR.
+# Once installed, if the workflow run is marked as required,
+# PRs introducing known-vulnerable packages will be blocked from merging.
+#
+# Source repository: https://github.com/actions/dependency-review-action
+name: 'Dependency Review'
+on: [pull_request]
+
+permissions:
+ contents: read
+
+jobs:
+ dependency-review:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Harden the runner (Audit all outbound calls)
+ uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4
+ with:
+ egress-policy: audit
+
+ - name: 'Checkout Repository'
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
+ with:
+ persist-credentials: false
+ - name: 'Dependency Review'
+ uses: actions/dependency-review-action@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0
+ with:
+ # Block PRs that introduce high/critical CVEs. Lower-severity findings
+ # still surface in the PR comment but don't block merge - consistent
+ # with the policy documented in osv-scanner.toml, which already
+ # suppresses dev-tooling CVEs that don't affect the distributed
+ # runtime.
+ fail-on-severity: high
+ # Only post the summary comment when something actually needs
+ # attention - cuts PR-comment noise on clean dependency bumps.
+ comment-summary-in-pr: on-failure
diff --git a/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml
new file mode 100644
index 000000000..222841cb8
--- /dev/null
+++ b/.github/workflows/fuzz.yml
@@ -0,0 +1,45 @@
+name: Fuzz
+
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+ schedule:
+ - cron: '23 3 * * *'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ fuzz:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ node-version: [20.x, 24.x, 26.x]
+ steps:
+ - name: Harden the runner
+ uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4
+ with:
+ egress-policy: audit
+
+ - name: Checkout
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
+ with:
+ persist-credentials: false
+
+ - name: Setup Node.js
+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
+ with:
+ node-version: ${{ matrix.node-version }}
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci --ignore-scripts
+
+ - name: Build
+ run: npm run build
+
+ - name: Run fuzzing
+ run: FUZZ_RUNS=300 npm run test:fuzz
diff --git a/.github/workflows/legacy-browsers.yml b/.github/workflows/legacy-browsers.yml
new file mode 100644
index 000000000..70c000d5e
--- /dev/null
+++ b/.github/workflows/legacy-browsers.yml
@@ -0,0 +1,102 @@
+name: Legacy Browsers
+
+# Old-engine coverage, Playwright-only (no external grid). Each matrix row pins a
+# Playwright RELEASE, which is a matched Chromium/Firefox/WebKit snapshot from
+# that era (exact versions below). It drives the same served QUnit suite as the
+# main browser job, in library mode via test/browser/legacy-runner.js.
+#
+# Playwright Chromium Firefox WebKit approx age
+# 1.50.1 133 134 18.2 ~1.5 years
+# 1.44.1 125 125 17.4 ~2 years
+# 1.40.0 120 119 17.4 ~2.5 years
+# 1.35.1 115 113 16.4 ~3 years
+# 1.30.0 110 108 16.4 ~3.5 years
+# Playwright's floor is ~1.10 (Chromium ~89 / Firefox ~85 / WebKit ~14.1, 2021);
+# nothing older is reachable without a grid.
+#
+# Non-blocking by design (continue-on-error): early-warning on push to main, plus
+# weekly drift detection, plus on-demand pre-release pre-flight. It never runs on
+# pull_request, so it is not a required check and does not touch the
+# build-and-test-skip.yml mirroring.
+
+on:
+ push:
+ # Only the lines that carry the Playwright test harness (server.js +
+ # legacy-runner.js + the QUnit page globals). 2.x predates the Playwright
+ # migration and runs its own legacy coverage, so it is deliberately excluded.
+ branches: [main, 3.x]
+ paths-ignore:
+ - '**/*.md'
+ - 'demos/**'
+ - 'website/**'
+ schedule:
+ - cron: '0 6 * * 1' # Mondays 06:00 UTC
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: legacy-browsers-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ legacy-browsers:
+ # ubuntu-22.04 (not -latest): every pinned Playwright here predates Ubuntu
+ # 24.04's renamed apt packages, so each release's own `install --with-deps`
+ # resolves cleanly on 22.04. The runner OS does not affect the browser engine
+ # under test (the engine is a downloaded binary), so this costs no coverage.
+ # If 22.04 is ever retired, move the oldest rows to a pinned container image.
+ runs-on: ubuntu-22.04
+ continue-on-error: true
+
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { pw: playwright-1-50-1, node: '20.x' } # Chromium 133 / FF 134 / WebKit 18.2
+ - { pw: playwright-1-44-1, node: '20.x' } # Chromium 125 / FF 125 / WebKit 17.4 (~2 yrs)
+ - { pw: playwright-1-40-0, node: '18.x' } # Chromium 120 / FF 119 / WebKit 17.4
+ - { pw: playwright-1-35-1, node: '18.x' } # Chromium 115 / FF 113 / WebKit 16.4
+ - { pw: playwright-1-30-0, node: '18.x' } # Chromium 110 / FF 108 / WebKit 16.4
+
+ steps:
+ - name: Harden the runner (Audit all outbound calls)
+ uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4
+ with:
+ egress-policy: audit
+
+ - name: Checkout
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
+ with:
+ persist-credentials: false
+
+ - name: Setup Node.js ${{ matrix.node }}
+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
+ with:
+ node-version: ${{ matrix.node }}
+ cache: npm
+
+ # No build step: dist/ is committed and kept in sync with src/ by
+ # build-and-test.yml, so the legacy job tests the artifact that actually
+ # ships. The root npm ci only needs to provide qunit + jquery for the
+ # served page. (EBADENGINE warnings on the Node 18 rows are harmless: we
+ # serve static assets and run the pinned Playwright, never the >=20 build
+ # toolchain.)
+ - name: Install Dependencies
+ run: npm ci --ignore-scripts
+
+ # The older Playwright snapshots are pinned by integrity hash in
+ # test/legacy-playwright/package-lock.json (each is an npm alias to an
+ # exact version), so `npm ci` installs hash-verified tarballs rather than
+ # whatever the registry currently serves for that version.
+ - name: Install pinned legacy Playwright snapshots
+ working-directory: test/legacy-playwright
+ run: npm ci --ignore-scripts
+
+ - name: Install browsers for ${{ matrix.pw }}
+ run: node test/legacy-playwright/node_modules/${{ matrix.pw }}/cli.js install --with-deps chromium firefox webkit
+
+ # legacy-runner.js self-starts test/browser/server.js and stops it on exit.
+ - name: Run suite on legacy engines
+ run: PW_MODULE="$GITHUB_WORKSPACE/test/legacy-playwright/node_modules/${{ matrix.pw }}" node test/browser/legacy-runner.js
diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml
new file mode 100644
index 000000000..28f0cf396
--- /dev/null
+++ b/.github/workflows/scorecard.yml
@@ -0,0 +1,95 @@
+# This workflow uses actions that are not certified by GitHub. They are provided
+# by a third-party and are governed by separate terms of service, privacy
+# policy, and support documentation.
+
+name: Scorecard supply-chain security
+on:
+ # For Branch-Protection check. Only the default branch is supported. See
+ # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection
+ branch_protection_rule:
+ # To guarantee Maintained check is occasionally updated. See
+ # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained
+ # Daily (was weekly): if any run catches a commit mid-CodeQL-scan, the next
+ # run corrects it within a day instead of leaving a stale reading for a week.
+ schedule:
+ - cron: '24 17 * * *'
+ # NOTE: the 'push: [main]' trigger was intentionally removed. It made this
+ # workflow run at merge time, racing the CodeQL scan of the just-merged
+ # commit. Scorecard would query for a SAST run before CodeQL had finished
+ # producing one, reporting that commit as unchecked (e.g. 29/30). Running
+ # only on schedule + branch_protection_rule means evaluation happens well
+ # after CodeQL has completed, so merges no longer move the score.
+
+# Declare default permissions as read only.
+permissions: read-all
+
+jobs:
+ analysis:
+ name: Scorecard analysis
+ runs-on: ubuntu-latest
+ # `publish_results: true` only works when run from the default branch.
+ # (The previous 'pull_request' clause here was dead code - this workflow
+ # doesn't trigger on pull_request events.)
+ if: github.event.repository.default_branch == github.ref_name
+ # A job-level permissions block REPLACES the top-level 'read-all' default
+ # entirely - anything not listed here is set to 'none'. The reads below are
+ # required for Scorecard to enumerate commits/PRs and detect the CodeQL
+ # check runs that the SAST check looks for. With them commented out, the
+ # job effectively had no read access and relied entirely on SCORECARD_TOKEN.
+ permissions:
+ security-events: write # upload SARIF to the code-scanning dashboard
+ id-token: write # publish results to the OpenSSF REST API
+ contents: read # read commit history (the SAST evaluation window)
+ actions: read # read workflow runs
+ checks: read # read CodeQL check runs (the SAST signal)
+ pull-requests: read # map merged commits to their PRs
+
+ steps:
+ - name: Harden the runner (Audit all outbound calls)
+ uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4
+ with:
+ egress-policy: audit
+
+ - name: "Checkout code"
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
+ with:
+ persist-credentials: false
+
+ - name: "Run analysis"
+ uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3
+ with:
+ results_file: results.sarif
+ results_format: sarif
+ # (Optional) "write" PAT token. Uncomment the `repo_token` line below if:
+ # - you want to enable the Branch-Protection check on a *public* repository, or
+ # - you are installing Scorecard on a *private* repository
+ # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action?tab=readme-ov-file#authentication-with-fine-grained-pat-optional.
+ repo_token: ${{ secrets.SCORECARD_TOKEN }}
+
+ # Public repositories:
+ # - Publish results to OpenSSF REST API for easy access by consumers
+ # - Allows the repository to include the Scorecard badge.
+ # - See https://github.com/ossf/scorecard-action#publishing-results.
+ # For private repositories:
+ # - `publish_results` will always be set to `false`, regardless
+ # of the value entered here.
+ publish_results: true
+
+ # (Optional) Uncomment file_mode if you have a .gitattributes with files marked export-ignore
+ # file_mode: git
+
+ # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
+ # format to the repository Actions tab.
+ - name: "Upload artifact"
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: SARIF file
+ path: results.sarif
+ retention-days: 5
+
+ # Upload the results to GitHub's code scanning dashboard (optional).
+ # Commenting out will disable upload of results to your repo's Code Scanning dashboard
+ - name: "Upload to code-scanning"
+ uses: github/codeql-action/upload-sarif@8aad20d150bbac5944a9f9d289da16a4b0d87c1e # v4.36.2
+ with:
+ sarif_file: results.sarif
diff --git a/.github/workflows/sign-release.yml b/.github/workflows/sign-release.yml
new file mode 100644
index 000000000..d2dd8052c
--- /dev/null
+++ b/.github/workflows/sign-release.yml
@@ -0,0 +1,28 @@
+name: Sign Release
+on:
+ release:
+ types: [published]
+
+permissions:
+ contents: read
+
+jobs:
+ sign:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write # to attach .sigstore bundles to the release
+ id-token: write # OIDC for keyless signing
+ steps:
+ - uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4
+ with:
+ egress-policy: audit
+ - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
+ with:
+ persist-credentials: false
+ - uses: sigstore/gh-action-sigstore-python@5b79a39c381910c090341a2c9b0bf022c8b387e1 # v3.0.1
+ with:
+ inputs: dist/purify.min.js dist/purify.js
+ # Re-uploads signed artefacts to the release that triggered this run.
+ # Without this flag, .sigstore bundles are generated but dropped at
+ # job end - the release page gets nothing.
+ release-signing-artifacts: true
diff --git a/.github/workflows/slsa-provenance.yml b/.github/workflows/slsa-provenance.yml
new file mode 100644
index 000000000..14dcd337d
--- /dev/null
+++ b/.github/workflows/slsa-provenance.yml
@@ -0,0 +1,40 @@
+name: SLSA Provenance
+on:
+ release:
+ types: [published]
+
+permissions:
+ contents: read
+
+jobs:
+ provenance:
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ id-token: write
+ attestations: write
+ steps:
+ - uses: step-security/harden-runner@9af89fc71515a100421586dfdb3dc9c984fbf411 # v2.19.4
+ with:
+ egress-policy: audit
+ - uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3
+ with:
+ ref: ${{ github.event.release.tag_name }}
+ persist-credentials: false
+ - uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
+ with:
+ node-version: 22
+ - run: npm ci --ignore-scripts
+ - run: npm run build
+ - id: attest
+ uses: actions/attest-build-provenance@a2bbfa25375fe432b6a289bc6b6cd05ecd0c4c32 # v4.1.0
+ with:
+ subject-path: 'dist/purify.js,dist/purify.min.js,dist/purify.cjs.js,dist/purify.es.mjs'
+ - name: Upload provenance to release
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ BUNDLE_PATH: ${{ steps.attest.outputs.bundle-path }}
+ TAG: ${{ github.event.release.tag_name }}
+ run: |
+ cp "$BUNDLE_PATH" "${TAG}.intoto.jsonl"
+ gh release upload "$TAG" "${TAG}.intoto.jsonl" --clobber
diff --git a/.gitignore b/.gitignore
index 971101f7b..c1f32505b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,13 @@ yarn-error.log
nbproject/private/private.properties
nbproject/project.properties
nbproject/private/private.xml
+
+# Playwright generated output
+test-results/
+playwright-report/
+
+# Local code coverage (npm run coverage) - not committed
+.nyc_output/
+coverage/
+dist/purify.cov.cjs.js
+dist/purify.cov.cjs.js.map
diff --git a/.husky/pre-commit b/.husky/pre-commit
new file mode 100644
index 000000000..91a6687ae
--- /dev/null
+++ b/.husky/pre-commit
@@ -0,0 +1,3 @@
+npm run lint
+npm run build
+npm run commit-amend-build
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
new file mode 100644
index 000000000..723e338d3
--- /dev/null
+++ b/.pre-commit-config.yaml
@@ -0,0 +1,18 @@
+repos:
+- repo: https://github.com/gitleaks/gitleaks
+ rev: v8.16.3
+ hooks:
+ - id: gitleaks
+- repo: https://github.com/jumanjihouse/pre-commit-hooks
+ rev: 3.0.0
+ hooks:
+ - id: shellcheck
+- repo: https://github.com/pre-commit/mirrors-eslint
+ rev: v8.38.0
+ hooks:
+ - id: eslint
+- repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v4.4.0
+ hooks:
+ - id: end-of-file-fixer
+ - id: trailing-whitespace
diff --git a/.settings/.gitignore b/.settings/.gitignore
deleted file mode 100644
index f2978546f..000000000
--- a/.settings/.gitignore
+++ /dev/null
@@ -1,5 +0,0 @@
-/.jsdtscope
-/org.eclipse.ltk.core.refactoring.prefs
-/org.eclipse.wst.common.project.facet.core.xml
-/org.eclipse.wst.jsdt.ui.superType.container
-/org.eclipse.wst.jsdt.ui.superType.name
diff --git a/CODEOWNERS b/CODEOWNERS
new file mode 100644
index 000000000..2818ed8d8
--- /dev/null
+++ b/CODEOWNERS
@@ -0,0 +1,3 @@
+# .github/CODEOWNERS
+# All changes require review from a core maintainer
+* @x00mario
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 000000000..e0d15c3d9
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,42 @@
+# Code of Conduct
+
+## Our Pledge
+
+We want this project to be a welcoming and productive place for everyone who
+takes part in it, regardless of background or experience. The guiding principle
+is simple: **be nice, be reasonable, argue from logic and evidence, and act in
+good faith.**
+
+## Expected Behavior
+
+- Be kind and respectful in all interactions.
+- Assume good faith in others and extend the same in return.
+- Keep discussion logical, on-topic, and grounded in evidence.
+- Give and accept constructive feedback gracefully.
+- Take responsibility for mistakes and learn from them.
+
+## Unacceptable Behavior
+
+- Harassment, insults, or personal attacks.
+- Discriminatory, demeaning, or hateful comments.
+- Deliberately bad-faith argument, trolling, or disruption.
+- Publishing others' private information without their consent.
+- Any conduct that would reasonably be considered inappropriate in a
+ professional setting.
+
+## Scope
+
+This Code of Conduct applies within all project spaces — issues, pull requests,
+discussions, and code — and in any public space when an individual is
+representing the project.
+
+## Enforcement
+
+Instances of unacceptable behavior may be reported to the maintainers at
+**mario@cure53.de**. All reports will be reviewed and handled in good
+faith and with discretion.
+
+Maintainers are responsible for clarifying the standards above and may take any
+action they deem appropriate, including editing or removing contributions and
+comments, or temporarily or permanently banning any contributor for behavior
+they consider inappropriate. Final decisions always rest with the core maintainer.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 000000000..4aa1528e3
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,23 @@
+# Contributions
+
+Thank you for your interest in contributing to DOMPurify.
+
+## Eligibility for Pull Requests
+
+A pull request is considered eligible for inclusion only if it satisfies all of the following requirements:
+
+1. **Linter passes**
+ - The proposed changes must satisfy the project's linting requirements.
+
+2. **All tests pass**
+ - The full test suite must pass without regressions.
+
+3. **Manual review by the core maintainer**
+ - Every pull request is subject to manual review by the core maintainer.
+ - Passing automated checks alone does not guarantee acceptance.
+
+## Notes
+
+- Submissions that do not pass linting or tests are not eligible for merging.
+- Final acceptance is at the discretion of the core maintainer after manual review.
+- Maintaining code quality, security, and project consistency takes precedence over feature additions.
diff --git a/CONTRIBUTIONS.md b/CONTRIBUTIONS.md
new file mode 100644
index 000000000..4aa1528e3
--- /dev/null
+++ b/CONTRIBUTIONS.md
@@ -0,0 +1,23 @@
+# Contributions
+
+Thank you for your interest in contributing to DOMPurify.
+
+## Eligibility for Pull Requests
+
+A pull request is considered eligible for inclusion only if it satisfies all of the following requirements:
+
+1. **Linter passes**
+ - The proposed changes must satisfy the project's linting requirements.
+
+2. **All tests pass**
+ - The full test suite must pass without regressions.
+
+3. **Manual review by the core maintainer**
+ - Every pull request is subject to manual review by the core maintainer.
+ - Passing automated checks alone does not guarantee acceptance.
+
+## Notes
+
+- Submissions that do not pass linting or tests are not eligible for merging.
+- Final acceptance is at the discretion of the core maintainer after manual review.
+- Maintaining code quality, security, and project consistency takes precedence over feature additions.
diff --git a/LICENSE b/LICENSE
index 3887d27ad..d64569567 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,13 +1,3 @@
-DOMPurify
-Copyright 2025 Dr.-Ing. Mario Heiderich, Cure53
-
-DOMPurify is free software; you can redistribute it and/or modify it under the
-terms of either:
-
-a) the Apache License Version 2.0, or
-b) the Mozilla Public License Version 2.0
-
------------------------------------------------------------------------------
Apache License
Version 2.0, January 2004
@@ -210,359 +200,3 @@ b) the Mozilla Public License Version 2.0
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-
------------------------------------------------------------------------------
-Mozilla Public License, version 2.0
-
-1. Definitions
-
-1.1. “Contributor”
-
- means each individual or legal entity that creates, contributes to the
- creation of, or owns Covered Software.
-
-1.2. “Contributor Version”
-
- means the combination of the Contributions of others (if any) used by a
- Contributor and that particular Contributor’s Contribution.
-
-1.3. “Contribution”
-
- means Covered Software of a particular Contributor.
-
-1.4. “Covered Software”
-
- means Source Code Form to which the initial Contributor has attached the
- notice in Exhibit A, the Executable Form of such Source Code Form, and
- Modifications of such Source Code Form, in each case including portions
- thereof.
-
-1.5. “Incompatible With Secondary Licenses”
- means
-
- a. that the initial Contributor has attached the notice described in
- Exhibit B to the Covered Software; or
-
- b. that the Covered Software was made available under the terms of version
- 1.1 or earlier of the License, but not also under the terms of a
- Secondary License.
-
-1.6. “Executable Form”
-
- means any form of the work other than Source Code Form.
-
-1.7. “Larger Work”
-
- means a work that combines Covered Software with other material, in a separate
- file or files, that is not Covered Software.
-
-1.8. “License”
-
- means this document.
-
-1.9. “Licensable”
-
- means having the right to grant, to the maximum extent possible, whether at the
- time of the initial grant or subsequently, any and all of the rights conveyed by
- this License.
-
-1.10. “Modifications”
-
- means any of the following:
-
- a. any file in Source Code Form that results from an addition to, deletion
- from, or modification of the contents of Covered Software; or
-
- b. any new file in Source Code Form that contains any Covered Software.
-
-1.11. “Patent Claims” of a Contributor
-
- means any patent claim(s), including without limitation, method, process,
- and apparatus claims, in any patent Licensable by such Contributor that
- would be infringed, but for the grant of the License, by the making,
- using, selling, offering for sale, having made, import, or transfer of
- either its Contributions or its Contributor Version.
-
-1.12. “Secondary License”
-
- means either the GNU General Public License, Version 2.0, the GNU Lesser
- General Public License, Version 2.1, the GNU Affero General Public
- License, Version 3.0, or any later versions of those licenses.
-
-1.13. “Source Code Form”
-
- means the form of the work preferred for making modifications.
-
-1.14. “You” (or “Your”)
-
- means an individual or a legal entity exercising rights under this
- License. For legal entities, “You” includes any entity that controls, is
- controlled by, or is under common control with You. For purposes of this
- definition, “control” means (a) the power, direct or indirect, to cause
- the direction or management of such entity, whether by contract or
- otherwise, or (b) ownership of more than fifty percent (50%) of the
- outstanding shares or beneficial ownership of such entity.
-
-
-2. License Grants and Conditions
-
-2.1. Grants
-
- Each Contributor hereby grants You a world-wide, royalty-free,
- non-exclusive license:
-
- a. under intellectual property rights (other than patent or trademark)
- Licensable by such Contributor to use, reproduce, make available,
- modify, display, perform, distribute, and otherwise exploit its
- Contributions, either on an unmodified basis, with Modifications, or as
- part of a Larger Work; and
-
- b. under Patent Claims of such Contributor to make, use, sell, offer for
- sale, have made, import, and otherwise transfer either its Contributions
- or its Contributor Version.
-
-2.2. Effective Date
-
- The licenses granted in Section 2.1 with respect to any Contribution become
- effective for each Contribution on the date the Contributor first distributes
- such Contribution.
-
-2.3. Limitations on Grant Scope
-
- The licenses granted in this Section 2 are the only rights granted under this
- License. No additional rights or licenses will be implied from the distribution
- or licensing of Covered Software under this License. Notwithstanding Section
- 2.1(b) above, no patent license is granted by a Contributor:
-
- a. for any code that a Contributor has removed from Covered Software; or
-
- b. for infringements caused by: (i) Your and any other third party’s
- modifications of Covered Software, or (ii) the combination of its
- Contributions with other software (except as part of its Contributor
- Version); or
-
- c. under Patent Claims infringed by Covered Software in the absence of its
- Contributions.
-
- This License does not grant any rights in the trademarks, service marks, or
- logos of any Contributor (except as may be necessary to comply with the
- notice requirements in Section 3.4).
-
-2.4. Subsequent Licenses
-
- No Contributor makes additional grants as a result of Your choice to
- distribute the Covered Software under a subsequent version of this License
- (see Section 10.2) or under the terms of a Secondary License (if permitted
- under the terms of Section 3.3).
-
-2.5. Representation
-
- Each Contributor represents that the Contributor believes its Contributions
- are its original creation(s) or it has sufficient rights to grant the
- rights to its Contributions conveyed by this License.
-
-2.6. Fair Use
-
- This License is not intended to limit any rights You have under applicable
- copyright doctrines of fair use, fair dealing, or other equivalents.
-
-2.7. Conditions
-
- Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
- Section 2.1.
-
-
-3. Responsibilities
-
-3.1. Distribution of Source Form
-
- All distribution of Covered Software in Source Code Form, including any
- Modifications that You create or to which You contribute, must be under the
- terms of this License. You must inform recipients that the Source Code Form
- of the Covered Software is governed by the terms of this License, and how
- they can obtain a copy of this License. You may not attempt to alter or
- restrict the recipients’ rights in the Source Code Form.
-
-3.2. Distribution of Executable Form
-
- If You distribute Covered Software in Executable Form then:
-
- a. such Covered Software must also be made available in Source Code Form,
- as described in Section 3.1, and You must inform recipients of the
- Executable Form how they can obtain a copy of such Source Code Form by
- reasonable means in a timely manner, at a charge no more than the cost
- of distribution to the recipient; and
-
- b. You may distribute such Executable Form under the terms of this License,
- or sublicense it under different terms, provided that the license for
- the Executable Form does not attempt to limit or alter the recipients’
- rights in the Source Code Form under this License.
-
-3.3. Distribution of a Larger Work
-
- You may create and distribute a Larger Work under terms of Your choice,
- provided that You also comply with the requirements of this License for the
- Covered Software. If the Larger Work is a combination of Covered Software
- with a work governed by one or more Secondary Licenses, and the Covered
- Software is not Incompatible With Secondary Licenses, this License permits
- You to additionally distribute such Covered Software under the terms of
- such Secondary License(s), so that the recipient of the Larger Work may, at
- their option, further distribute the Covered Software under the terms of
- either this License or such Secondary License(s).
-
-3.4. Notices
-
- You may not remove or alter the substance of any license notices (including
- copyright notices, patent notices, disclaimers of warranty, or limitations
- of liability) contained within the Source Code Form of the Covered
- Software, except that You may alter any license notices to the extent
- required to remedy known factual inaccuracies.
-
-3.5. Application of Additional Terms
-
- You may choose to offer, and to charge a fee for, warranty, support,
- indemnity or liability obligations to one or more recipients of Covered
- Software. However, You may do so only on Your own behalf, and not on behalf
- of any Contributor. You must make it absolutely clear that any such
- warranty, support, indemnity, or liability obligation is offered by You
- alone, and You hereby agree to indemnify every Contributor for any
- liability incurred by such Contributor as a result of warranty, support,
- indemnity or liability terms You offer. You may include additional
- disclaimers of warranty and limitations of liability specific to any
- jurisdiction.
-
-4. Inability to Comply Due to Statute or Regulation
-
- If it is impossible for You to comply with any of the terms of this License
- with respect to some or all of the Covered Software due to statute, judicial
- order, or regulation then You must: (a) comply with the terms of this License
- to the maximum extent possible; and (b) describe the limitations and the code
- they affect. Such description must be placed in a text file included with all
- distributions of the Covered Software under this License. Except to the
- extent prohibited by statute or regulation, such description must be
- sufficiently detailed for a recipient of ordinary skill to be able to
- understand it.
-
-5. Termination
-
-5.1. The rights granted under this License will terminate automatically if You
- fail to comply with any of its terms. However, if You become compliant,
- then the rights granted under this License from a particular Contributor
- are reinstated (a) provisionally, unless and until such Contributor
- explicitly and finally terminates Your grants, and (b) on an ongoing basis,
- if such Contributor fails to notify You of the non-compliance by some
- reasonable means prior to 60 days after You have come back into compliance.
- Moreover, Your grants from a particular Contributor are reinstated on an
- ongoing basis if such Contributor notifies You of the non-compliance by
- some reasonable means, this is the first time You have received notice of
- non-compliance with this License from such Contributor, and You become
- compliant prior to 30 days after Your receipt of the notice.
-
-5.2. If You initiate litigation against any entity by asserting a patent
- infringement claim (excluding declaratory judgment actions, counter-claims,
- and cross-claims) alleging that a Contributor Version directly or
- indirectly infringes any patent, then the rights granted to You by any and
- all Contributors for the Covered Software under Section 2.1 of this License
- shall terminate.
-
-5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
- license agreements (excluding distributors and resellers) which have been
- validly granted by You or Your distributors under this License prior to
- termination shall survive termination.
-
-6. Disclaimer of Warranty
-
- Covered Software is provided under this License on an “as is” basis, without
- warranty of any kind, either expressed, implied, or statutory, including,
- without limitation, warranties that the Covered Software is free of defects,
- merchantable, fit for a particular purpose or non-infringing. The entire
- risk as to the quality and performance of the Covered Software is with You.
- Should any Covered Software prove defective in any respect, You (not any
- Contributor) assume the cost of any necessary servicing, repair, or
- correction. This disclaimer of warranty constitutes an essential part of this
- License. No use of any Covered Software is authorized under this License
- except under this disclaimer.
-
-7. Limitation of Liability
-
- Under no circumstances and under no legal theory, whether tort (including
- negligence), contract, or otherwise, shall any Contributor, or anyone who
- distributes Covered Software as permitted above, be liable to You for any
- direct, indirect, special, incidental, or consequential damages of any
- character including, without limitation, damages for lost profits, loss of
- goodwill, work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses, even if such party shall have been
- informed of the possibility of such damages. This limitation of liability
- shall not apply to liability for death or personal injury resulting from such
- party’s negligence to the extent applicable law prohibits such limitation.
- Some jurisdictions do not allow the exclusion or limitation of incidental or
- consequential damages, so this exclusion and limitation may not apply to You.
-
-8. Litigation
-
- Any litigation relating to this License may be brought only in the courts of
- a jurisdiction where the defendant maintains its principal place of business
- and such litigation shall be governed by laws of that jurisdiction, without
- reference to its conflict-of-law provisions. Nothing in this Section shall
- prevent a party’s ability to bring cross-claims or counter-claims.
-
-9. Miscellaneous
-
- This License represents the complete agreement concerning the subject matter
- hereof. If any provision of this License is held to be unenforceable, such
- provision shall be reformed only to the extent necessary to make it
- enforceable. Any law or regulation which provides that the language of a
- contract shall be construed against the drafter shall not be used to construe
- this License against a Contributor.
-
-
-10. Versions of the License
-
-10.1. New Versions
-
- Mozilla Foundation is the license steward. Except as provided in Section
- 10.3, no one other than the license steward has the right to modify or
- publish new versions of this License. Each version will be given a
- distinguishing version number.
-
-10.2. Effect of New Versions
-
- You may distribute the Covered Software under the terms of the version of
- the License under which You originally received the Covered Software, or
- under the terms of any subsequent version published by the license
- steward.
-
-10.3. Modified Versions
-
- If you create software not governed by this License, and you want to
- create a new license for such software, you may create and use a modified
- version of this License if you rename the license and remove any
- references to the name of the license steward (except to note that such
- modified license differs from this License).
-
-10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
- If You choose to distribute Source Code Form that is Incompatible With
- Secondary Licenses under the terms of this version of the License, the
- notice described in Exhibit B of this License must be attached.
-
-Exhibit A - Source Code Form License Notice
-
- This Source Code Form is subject to the
- terms of the Mozilla Public License, v.
- 2.0. If a copy of the MPL was not
- distributed with this file, You can
- obtain one at
- http://mozilla.org/MPL/2.0/.
-
-If it is not possible or desirable to put the notice in a particular file, then
-You may include the notice in a location (such as a LICENSE file in a relevant
-directory) where a recipient would be likely to look for such a notice.
-
-You may add additional accurate notices of copyright ownership.
-
-Exhibit B - “Incompatible With Secondary Licenses” Notice
-
- This Source Code Form is “Incompatible
- With Secondary Licenses”, as defined by
- the Mozilla Public License, v. 2.0.
-
diff --git a/LICENSE-MPL b/LICENSE-MPL
new file mode 100644
index 000000000..14e2f777f
--- /dev/null
+++ b/LICENSE-MPL
@@ -0,0 +1,373 @@
+Mozilla Public License Version 2.0
+==================================
+
+1. Definitions
+--------------
+
+1.1. "Contributor"
+ means each individual or legal entity that creates, contributes to
+ the creation of, or owns Covered Software.
+
+1.2. "Contributor Version"
+ means the combination of the Contributions of others (if any) used
+ by a Contributor and that particular Contributor's Contribution.
+
+1.3. "Contribution"
+ means Covered Software of a particular Contributor.
+
+1.4. "Covered Software"
+ means Source Code Form to which the initial Contributor has attached
+ the notice in Exhibit A, the Executable Form of such Source Code
+ Form, and Modifications of such Source Code Form, in each case
+ including portions thereof.
+
+1.5. "Incompatible With Secondary Licenses"
+ means
+
+ (a) that the initial Contributor has attached the notice described
+ in Exhibit B to the Covered Software; or
+
+ (b) that the Covered Software was made available under the terms of
+ version 1.1 or earlier of the License, but not also under the
+ terms of a Secondary License.
+
+1.6. "Executable Form"
+ means any form of the work other than Source Code Form.
+
+1.7. "Larger Work"
+ means a work that combines Covered Software with other material, in
+ a separate file or files, that is not Covered Software.
+
+1.8. "License"
+ means this document.
+
+1.9. "Licensable"
+ means having the right to grant, to the maximum extent possible,
+ whether at the time of the initial grant or subsequently, any and
+ all of the rights conveyed by this License.
+
+1.10. "Modifications"
+ means any of the following:
+
+ (a) any file in Source Code Form that results from an addition to,
+ deletion from, or modification of the contents of Covered
+ Software; or
+
+ (b) any new file in Source Code Form that contains any Covered
+ Software.
+
+1.11. "Patent Claims" of a Contributor
+ means any patent claim(s), including without limitation, method,
+ process, and apparatus claims, in any patent Licensable by such
+ Contributor that would be infringed, but for the grant of the
+ License, by the making, using, selling, offering for sale, having
+ made, import, or transfer of either its Contributions or its
+ Contributor Version.
+
+1.12. "Secondary License"
+ means either the GNU General Public License, Version 2.0, the GNU
+ Lesser General Public License, Version 2.1, the GNU Affero General
+ Public License, Version 3.0, or any later versions of those
+ licenses.
+
+1.13. "Source Code Form"
+ means the form of the work preferred for making modifications.
+
+1.14. "You" (or "Your")
+ means an individual or a legal entity exercising rights under this
+ License. For legal entities, "You" includes any entity that
+ controls, is controlled by, or is under common control with You. For
+ purposes of this definition, "control" means (a) the power, direct
+ or indirect, to cause the direction or management of such entity,
+ whether by contract or otherwise, or (b) ownership of more than
+ fifty percent (50%) of the outstanding shares or beneficial
+ ownership of such entity.
+
+2. License Grants and Conditions
+--------------------------------
+
+2.1. Grants
+
+Each Contributor hereby grants You a world-wide, royalty-free,
+non-exclusive license:
+
+(a) under intellectual property rights (other than patent or trademark)
+ Licensable by such Contributor to use, reproduce, make available,
+ modify, display, perform, distribute, and otherwise exploit its
+ Contributions, either on an unmodified basis, with Modifications, or
+ as part of a Larger Work; and
+
+(b) under Patent Claims of such Contributor to make, use, sell, offer
+ for sale, have made, import, and otherwise transfer either its
+ Contributions or its Contributor Version.
+
+2.2. Effective Date
+
+The licenses granted in Section 2.1 with respect to any Contribution
+become effective for each Contribution on the date the Contributor first
+distributes such Contribution.
+
+2.3. Limitations on Grant Scope
+
+The licenses granted in this Section 2 are the only rights granted under
+this License. No additional rights or licenses will be implied from the
+distribution or licensing of Covered Software under this License.
+Notwithstanding Section 2.1(b) above, no patent license is granted by a
+Contributor:
+
+(a) for any code that a Contributor has removed from Covered Software;
+ or
+
+(b) for infringements caused by: (i) Your and any other third party's
+ modifications of Covered Software, or (ii) the combination of its
+ Contributions with other software (except as part of its Contributor
+ Version); or
+
+(c) under Patent Claims infringed by Covered Software in the absence of
+ its Contributions.
+
+This License does not grant any rights in the trademarks, service marks,
+or logos of any Contributor (except as may be necessary to comply with
+the notice requirements in Section 3.4).
+
+2.4. Subsequent Licenses
+
+No Contributor makes additional grants as a result of Your choice to
+distribute the Covered Software under a subsequent version of this
+License (see Section 10.2) or under the terms of a Secondary License (if
+permitted under the terms of Section 3.3).
+
+2.5. Representation
+
+Each Contributor represents that the Contributor believes its
+Contributions are its original creation(s) or it has sufficient rights
+to grant the rights to its Contributions conveyed by this License.
+
+2.6. Fair Use
+
+This License is not intended to limit any rights You have under
+applicable copyright doctrines of fair use, fair dealing, or other
+equivalents.
+
+2.7. Conditions
+
+Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
+in Section 2.1.
+
+3. Responsibilities
+-------------------
+
+3.1. Distribution of Source Form
+
+All distribution of Covered Software in Source Code Form, including any
+Modifications that You create or to which You contribute, must be under
+the terms of this License. You must inform recipients that the Source
+Code Form of the Covered Software is governed by the terms of this
+License, and how they can obtain a copy of this License. You may not
+attempt to alter or restrict the recipients' rights in the Source Code
+Form.
+
+3.2. Distribution of Executable Form
+
+If You distribute Covered Software in Executable Form then:
+
+(a) such Covered Software must also be made available in Source Code
+ Form, as described in Section 3.1, and You must inform recipients of
+ the Executable Form how they can obtain a copy of such Source Code
+ Form by reasonable means in a timely manner, at a charge no more
+ than the cost of distribution to the recipient; and
+
+(b) You may distribute such Executable Form under the terms of this
+ License, or sublicense it under different terms, provided that the
+ license for the Executable Form does not attempt to limit or alter
+ the recipients' rights in the Source Code Form under this License.
+
+3.3. Distribution of a Larger Work
+
+You may create and distribute a Larger Work under terms of Your choice,
+provided that You also comply with the requirements of this License for
+the Covered Software. If the Larger Work is a combination of Covered
+Software with a work governed by one or more Secondary Licenses, and the
+Covered Software is not Incompatible With Secondary Licenses, this
+License permits You to additionally distribute such Covered Software
+under the terms of such Secondary License(s), so that the recipient of
+the Larger Work may, at their option, further distribute the Covered
+Software under the terms of either this License or such Secondary
+License(s).
+
+3.4. Notices
+
+You may not remove or alter the substance of any license notices
+(including copyright notices, patent notices, disclaimers of warranty,
+or limitations of liability) contained within the Source Code Form of
+the Covered Software, except that You may alter any license notices to
+the extent required to remedy known factual inaccuracies.
+
+3.5. Application of Additional Terms
+
+You may choose to offer, and to charge a fee for, warranty, support,
+indemnity or liability obligations to one or more recipients of Covered
+Software. However, You may do so only on Your own behalf, and not on
+behalf of any Contributor. You must make it absolutely clear that any
+such warranty, support, indemnity, or liability obligation is offered by
+You alone, and You hereby agree to indemnify every Contributor for any
+liability incurred by such Contributor as a result of warranty, support,
+indemnity or liability terms You offer. You may include additional
+disclaimers of warranty and limitations of liability specific to any
+jurisdiction.
+
+4. Inability to Comply Due to Statute or Regulation
+---------------------------------------------------
+
+If it is impossible for You to comply with any of the terms of this
+License with respect to some or all of the Covered Software due to
+statute, judicial order, or regulation then You must: (a) comply with
+the terms of this License to the maximum extent possible; and (b)
+describe the limitations and the code they affect. Such description must
+be placed in a text file included with all distributions of the Covered
+Software under this License. Except to the extent prohibited by statute
+or regulation, such description must be sufficiently detailed for a
+recipient of ordinary skill to be able to understand it.
+
+5. Termination
+--------------
+
+5.1. The rights granted under this License will terminate automatically
+if You fail to comply with any of its terms. However, if You become
+compliant, then the rights granted under this License from a particular
+Contributor are reinstated (a) provisionally, unless and until such
+Contributor explicitly and finally terminates Your grants, and (b) on an
+ongoing basis, if such Contributor fails to notify You of the
+non-compliance by some reasonable means prior to 60 days after You have
+come back into compliance. Moreover, Your grants from a particular
+Contributor are reinstated on an ongoing basis if such Contributor
+notifies You of the non-compliance by some reasonable means, this is the
+first time You have received notice of non-compliance with this License
+from such Contributor, and You become compliant prior to 30 days after
+Your receipt of the notice.
+
+5.2. If You initiate litigation against any entity by asserting a patent
+infringement claim (excluding declaratory judgment actions,
+counter-claims, and cross-claims) alleging that a Contributor Version
+directly or indirectly infringes any patent, then the rights granted to
+You by any and all Contributors for the Covered Software under Section
+2.1 of this License shall terminate.
+
+5.3. In the event of termination under Sections 5.1 or 5.2 above, all
+end user license agreements (excluding distributors and resellers) which
+have been validly granted by You or Your distributors under this License
+prior to termination shall survive termination.
+
+************************************************************************
+* *
+* 6. Disclaimer of Warranty *
+* ------------------------- *
+* *
+* Covered Software is provided under this License on an "as is" *
+* basis, without warranty of any kind, either expressed, implied, or *
+* statutory, including, without limitation, warranties that the *
+* Covered Software is free of defects, merchantable, fit for a *
+* particular purpose or non-infringing. The entire risk as to the *
+* quality and performance of the Covered Software is with You. *
+* Should any Covered Software prove defective in any respect, You *
+* (not any Contributor) assume the cost of any necessary servicing, *
+* repair, or correction. This disclaimer of warranty constitutes an *
+* essential part of this License. No use of any Covered Software is *
+* authorized under this License except under this disclaimer. *
+* *
+************************************************************************
+
+************************************************************************
+* *
+* 7. Limitation of Liability *
+* -------------------------- *
+* *
+* Under no circumstances and under no legal theory, whether tort *
+* (including negligence), contract, or otherwise, shall any *
+* Contributor, or anyone who distributes Covered Software as *
+* permitted above, be liable to You for any direct, indirect, *
+* special, incidental, or consequential damages of any character *
+* including, without limitation, damages for lost profits, loss of *
+* goodwill, work stoppage, computer failure or malfunction, or any *
+* and all other commercial damages or losses, even if such party *
+* shall have been informed of the possibility of such damages. This *
+* limitation of liability shall not apply to liability for death or *
+* personal injury resulting from such party's negligence to the *
+* extent applicable law prohibits such limitation. Some *
+* jurisdictions do not allow the exclusion or limitation of *
+* incidental or consequential damages, so this exclusion and *
+* limitation may not apply to You. *
+* *
+************************************************************************
+
+8. Litigation
+-------------
+
+Any litigation relating to this License may be brought only in the
+courts of a jurisdiction where the defendant maintains its principal
+place of business and such litigation shall be governed by laws of that
+jurisdiction, without reference to its conflict-of-law provisions.
+Nothing in this Section shall prevent a party's ability to bring
+cross-claims or counter-claims.
+
+9. Miscellaneous
+----------------
+
+This License represents the complete agreement concerning the subject
+matter hereof. If any provision of this License is held to be
+unenforceable, such provision shall be reformed only to the extent
+necessary to make it enforceable. Any law or regulation which provides
+that the language of a contract shall be construed against the drafter
+shall not be used to construe this License against a Contributor.
+
+10. Versions of the License
+---------------------------
+
+10.1. New Versions
+
+Mozilla Foundation is the license steward. Except as provided in Section
+10.3, no one other than the license steward has the right to modify or
+publish new versions of this License. Each version will be given a
+distinguishing version number.
+
+10.2. Effect of New Versions
+
+You may distribute the Covered Software under the terms of the version
+of the License under which You originally received the Covered Software,
+or under the terms of any subsequent version published by the license
+steward.
+
+10.3. Modified Versions
+
+If you create software not governed by this License, and you want to
+create a new license for such software, you may create and use a
+modified version of this License if you rename the license and remove
+any references to the name of the license steward (except to note that
+such modified license differs from this License).
+
+10.4. Distributing Source Code Form that is Incompatible With Secondary
+Licenses
+
+If You choose to distribute Source Code Form that is Incompatible With
+Secondary Licenses under the terms of this version of the License, the
+notice described in Exhibit B of this License must be attached.
+
+Exhibit A - Source Code Form License Notice
+-------------------------------------------
+
+ This Source Code Form is subject to the terms of the Mozilla Public
+ License, v. 2.0. If a copy of the MPL was not distributed with this
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+If it is not possible or desirable to put the notice in a particular
+file, then You may include the notice in a location (such as a LICENSE
+file in a relevant directory) where a recipient would be likely to look
+for such a notice.
+
+You may add additional accurate notices of copyright ownership.
+
+Exhibit B - "Incompatible With Secondary Licenses" Notice
+---------------------------------------------------------
+
+ This Source Code Form is "Incompatible With Secondary Licenses", as
+ defined by the Mozilla Public License, v. 2.0.
diff --git a/README.md b/README.md
index 4f29074e9..066e0f0c5 100644
--- a/README.md
+++ b/README.md
@@ -1,22 +1,26 @@
# DOMPurify
-[](http://badge.fury.io/js/dompurify)  [](https://www.npmjs.com/package/dompurify)  [](https://github.com/cure53/DOMPurify/network/dependents) [](https://cloudback.it)
+[](https://www.npmjs.com/package/dompurify) [](https://github.com/cure53/DOMPurify/blob/main/LICENSE) [](https://www.npmjs.com/package/dompurify) [](https://github.com/cure53/DOMPurify/network/dependents)  [](https://cloudback.it)
+
+[](https://www.bestpractices.dev/projects/12162) [](https://github.com/cure53/DOMPurify/actions/workflows/build-and-test.yml) [](https://scorecard.dev/viewer/?uri=github.com/cure53/DOMPurify) [](https://badge.socket.dev/npm/package/dompurify/latest) [](https://security.snyk.io/package/npm/dompurify)
DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG.
-It's also very simple to use and get started with. DOMPurify was [started in February 2014](https://github.com/cure53/DOMPurify/commit/a630922616927373485e0e787ab19e73e3691b2b) and, meanwhile, has reached version **v3.3.1**.
+It's also very simple to use and get started with. DOMPurify was [started in February 2014](https://github.com/cure53/DOMPurify/commit/a630922616927373485e0e787ab19e73e3691b2b) and, meanwhile, has reached version **v3.4.10**.
+
+DOMPurify runs as JavaScript and works in all modern browsers (Safari (10+), Opera (15+), Edge, Firefox and Chrome - as well as almost anything else using Blink, Gecko or WebKit). It doesn't break on MSIE or other legacy browsers. It simply does nothing.
-DOMPurify is written in JavaScript and works in all modern browsers (Safari (10+), Opera (15+), Edge, Firefox and Chrome - as well as almost anything else using Blink, Gecko or WebKit). It doesn't break on MSIE or other legacy browsers. It simply does nothing.
+**Note that [DOMPurify v2.5.9](https://github.com/cure53/DOMPurify/releases/tag/2.5.9) is the latest version supporting MSIE. For important security updates compatible with MSIE, please use the [2.x branch](https://github.com/cure53/DOMPurify/tree/2.x).**
-**Note that [DOMPurify v2.5.8](https://github.com/cure53/DOMPurify/releases/tag/2.5.8) is the latest version supporting MSIE. For important security updates compatible with MSIE, please use the [2.x branch](https://github.com/cure53/DOMPurify/tree/2.x).**
+Our automated tests cover 9 browser/OS combinations on the current engines (Chromium, Firefox, and WebKit across Ubuntu, macOS, and Windows) on every push, and a separate matrix re-runs the suite on older engine snapshots (back to roughly Chromium 110, Firefox 108 and WebKit 16.4, around three years old) so regressions on outdated browsers get caught too. We also run Node.js v20, v22, v24, v25 and v26 with DOMPurify on [jsdom](https://github.com/jsdom/jsdom). Older Node versions are known to work as well, but hey... no guarantees.
-Our automated tests cover [28 different browsers](https://github.com/cure53/DOMPurify/blob/main/test/karma.custom-launchers.config.js#L5) right now, more to come. We also cover Node.js v18.x, v19.x, v20.x, v21.x, v22.x and v23.x, running DOMPurify on [jsdom](https://github.com/jsdom/jsdom). Older Node versions are known to work as well, but hey... no guarantees.
+DOMPurify is written by security people who have vast background in web attacks and XSS. Fear not. For more details please also read about our [Security Goals & Threat Model](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model). Please, read it. Like, really. And if you enjoy the gory details, the [Attack Classes & Bypass History](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History) page catalogs the parser-mutation, namespace, clobbering, and template tricks DOMPurify defends against.
-DOMPurify is written by security people who have vast background in web attacks and XSS. Fear not. For more details please also read about our [Security Goals & Threat Model](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model). Please, read it. Like, really.
+The DOMPurify project inspired the creation of the [HTML Sanitizer API](https://wicg.github.io/sanitizer-api/#sanitizer), which is already shipping in [many browsers](https://developer.mozilla.org/en-US/docs/Web/API/HTML_Sanitizer_API#browser_compatibility).
## What does it do?
-DOMPurify sanitizes HTML and prevents XSS attacks. You can feed DOMPurify with string full of dirty HTML and it will return a string (unless configured otherwise) with clean HTML. DOMPurify will strip out everything that contains dangerous HTML and thereby prevent XSS attacks and other nastiness. It's also damn bloody fast. We use the technologies the browser provides and turn them into an XSS filter. The faster your browser, the faster DOMPurify will be.
+DOMPurify sanitizes HTML and prevents XSS attacks. You can feed DOMPurify with e.g. a string full of dirty HTML and it will return a string (unless configured otherwise) with clean HTML. DOMPurify will strip out everything that contains dangerous HTML and thereby prevent XSS attacks and other nastiness. It's also damn bloody fast. We use the technologies the browser provides and turn them into an XSS filter. The faster your browser, the faster DOMPurify will be.
## How do I use it?
@@ -57,7 +61,7 @@ const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });
### Is there any foot-gun potential?
-Well, please note, if you _first_ sanitize HTML and then modify it _afterwards_, you might easily **void the effects of sanitization**. If you feed the sanitized markup to another library _after_ sanitization, please be certain that the library doesn't mess around with the HTML on its own.
+Well, please note, if you _first_ sanitize HTML and then modify it _afterwards_, you might easily **void the effects of sanitization**. If you feed the sanitized markup to another library _after_ sanitization, please be certain that the library doesn't mess around with the HTML on its own. See the [Security Goals & Threat Model](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model) for safe-usage recipes and the tags/attributes worth thinking twice about, and [Attack Classes & Bypass History](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History) for why post-processing and changing the markup context defeat sanitization.
### Okay, makes sense, let's move on
@@ -65,13 +69,13 @@ After sanitizing your markup, you can also have a look at the property `DOMPurif
### Running DOMPurify on the server
-DOMPurify technically also works server-side with Node.js. Our support strives to follow the [Node.js release cycle](https://nodejs.org/en/about/releases/).
+DOMPurify technically also works server-side with Node.js. Our support strives to follow the [Node.js release cycle](https://nodejs.org/en/about/previous-releases).
Running DOMPurify on the server requires a DOM to be present, which is probably no surprise. Usually, [jsdom](https://github.com/jsdom/jsdom) is the tool of choice and we **strongly recommend** to use the latest version of _jsdom_.
Why? Because older versions of _jsdom_ are known to be buggy in ways that result in XSS _even if_ DOMPurify does everything 100% correctly. There are **known attack vectors** in, e.g. _jsdom v19.0.0_ that are fixed in _jsdom v20.0.0_ - and we really recommend to keep _jsdom_ up to date because of that.
-Please also be aware that tools like [happy-dom](https://github.com/capricorn86/happy-dom) exist but **are not considered safe** at this point. Combining DOMPurify with _happy-dom_ is currently not recommended and will likely lead to XSS.
+Please also be aware that tools like [happy-dom](https://github.com/capricorn86/happy-dom) exist but **are not considered safe** at this point. Combining DOMPurify with _happy-dom_ is currently not recommended and will likely lead to XSS. For background on why the server-side DOM you choose is part of your trusted computing base, see [Attack Classes & Bypass History](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History).
Other than that, you are fine to use DOMPurify on the server. Probably. This really depends on _jsdom_ or whatever DOM you utilize server-side. If you can live with that, this is how you get it to work:
@@ -137,6 +141,8 @@ DOMPurify.sanitize('
```
+These are just a taste. For the full taxonomy of attack classes these samples come from - mutation XSS, namespace confusion, DOM clobbering, rawtext breakouts, and more - see [Attack Classes & Bypass History](https://github.com/cure53/DOMPurify/wiki/Attack-Classes-&-Bypass-History).
+
## What is supported?
DOMPurify currently supports HTML5, SVG and MathML. DOMPurify per default allows CSS, HTML custom data attributes. DOMPurify also supports the Shadow DOM - and sanitizes DOM templates recursively. DOMPurify also allows you to sanitize HTML for being used with the jQuery `$()` and `elm.html()` API without any known problems.
@@ -155,92 +161,117 @@ When `DOMPurify.sanitize` is used in an environment where the Trusted Types API
Note that in order to create a policy in `trustedTypes` using DOMPurify, `RETURN_TRUSTED_TYPE: false` is required, as `createHTML` expects a normal string, not `TrustedHTML`. The example below shows this.
```js
-window.trustedTypes!.createPolicy('default', {
+window.trustedTypes.createPolicy('default', {
createHTML: (to_escape) =>
DOMPurify.sanitize(to_escape, { RETURN_TRUSTED_TYPE: false }),
});
```
+When no `TRUSTED_TYPES_POLICY` is supplied, DOMPurify attempts to create its own internal Trusted Types policy named `dompurify`. If your page already defines its own policy together with a strict CSP (for example `trusted-types my-organization`) that does not allow a policy named `dompurify`, this attempt is blocked by the browser and logs a `TrustedTypes policy dompurify could not be created.` warning along with a CSP violation.
+
+To stop DOMPurify from creating its internal fallback policy, pass `TRUSTED_TYPES_POLICY: null`. This is the right choice when you call `DOMPurify.sanitize` from inside your own policy's `createHTML`, and it means you do not have to add `dompurify` to your CSP's `trusted-types` allowlist.
+
+```js
+window.trustedTypes.createPolicy('my-organization', {
+ createHTML: (input) =>
+ DOMPurify.sanitize(input, { TRUSTED_TYPES_POLICY: null }),
+});
+```
+
+Do **not** pass your own wrapping policy back to DOMPurify as its `TRUSTED_TYPES_POLICY` (for example via `DOMPurify.setConfig({ TRUSTED_TYPES_POLICY: myPolicy })`) when that policy's `createHTML` already calls `DOMPurify.sanitize`. That is circular by definition - sanitizing would call the policy, which sanitizes by calling DOMPurify again - and DOMPurify will throw a descriptive `TypeError` to prevent the infinite recursion. Your own policy should call DOMPurify; DOMPurify should not be configured to call your policy.
+
## Can I configure DOMPurify?
Yes. The included default configuration values are pretty good already - but you can of course override them. Check out the [`/demos`](https://github.com/cure53/DOMPurify/tree/main/demos) folder to see a bunch of examples on how you can [customize DOMPurify](https://github.com/cure53/DOMPurify/tree/main/demos#what-is-this).
+Before you widen the allow-list (`ADD_TAGS`, `ADD_ATTR`, `CUSTOM_ELEMENT_HANDLING`, …) or relax a default, it's worth skimming the [tags and attributes to think twice about](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model#dangerous-tags-and-attributes-think-twice-before-allow-listing) - a few are dangerous in non-obvious ways.
+
### General settings
+
```js
// strip {{ ... }}, ${ ... } and <% ... %> to make output safe for template systems
// be careful please, this mode is not recommended for production usage.
// allowing template parsing in user-controlled HTML is not advised at all.
// only use this mode if there is really no alternative.
-const clean = DOMPurify.sanitize(dirty, {SAFE_FOR_TEMPLATES: true});
-
+const clean = DOMPurify.sanitize(dirty, { SAFE_FOR_TEMPLATES: true });
// change how e.g. comments containing risky HTML characters are treated.
// be very careful, this setting should only be set to `false` if you really only handle
// HTML and nothing else, no SVG, MathML or the like.
// Otherwise, changing from `true` to `false` will lead to XSS in this or some other way.
-const clean = DOMPurify.sanitize(dirty, {SAFE_FOR_XML: false});
+const clean = DOMPurify.sanitize(dirty, { SAFE_FOR_XML: false });
```
### Control our allow-lists and block-lists
+
```js
// allow only elements, very strict
-const clean = DOMPurify.sanitize(dirty, {ALLOWED_TAGS: ['b']});
+const clean = DOMPurify.sanitize(dirty, { ALLOWED_TAGS: ['b'] });
// allow only and with style attributes
-const clean = DOMPurify.sanitize(dirty, {ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style']});
+const clean = DOMPurify.sanitize(dirty, {
+ ALLOWED_TAGS: ['b', 'q'],
+ ALLOWED_ATTR: ['style'],
+});
// allow all safe HTML elements but neither SVG nor MathML
// note that the USE_PROFILES setting will override the ALLOWED_TAGS setting
// so don't use them together
-const clean = DOMPurify.sanitize(dirty, {USE_PROFILES: {html: true}});
+const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });
// allow all safe SVG elements and SVG Filters, no HTML or MathML
-const clean = DOMPurify.sanitize(dirty, {USE_PROFILES: {svg: true, svgFilters: true}});
+const clean = DOMPurify.sanitize(dirty, {
+ USE_PROFILES: { svg: true, svgFilters: true },
+});
// allow all safe MathML elements and SVG, but no SVG Filters
-const clean = DOMPurify.sanitize(dirty, {USE_PROFILES: {mathMl: true, svg: true}});
+const clean = DOMPurify.sanitize(dirty, {
+ USE_PROFILES: { mathMl: true, svg: true },
+});
// change the default namespace from HTML to something different
-const clean = DOMPurify.sanitize(dirty, {NAMESPACE: 'http://www.w3.org/2000/svg'});
+const clean = DOMPurify.sanitize(dirty, {
+ NAMESPACE: 'http://www.w3.org/2000/svg',
+});
// leave all safe HTML as it is and add
diff --git a/demos/basic-demo.html b/demos/basic-demo.html
index e5b02cadf..bdedf7628 100644
--- a/demos/basic-demo.html
+++ b/demos/basic-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Basic usage
diff --git a/demos/config-demo.html b/demos/config-demo.html
index c56e0caee..f24c5cbef 100644
--- a/demos/config-demo.html
+++ b/demos/config-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Config usage
diff --git a/demos/hooks-demo.html b/demos/hooks-demo.html
index 15ab3cc20..3f4dc4e0a 100644
--- a/demos/hooks-demo.html
+++ b/demos/hooks-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Hooks
diff --git a/demos/hooks-link-proxy-demo.html b/demos/hooks-link-proxy-demo.html
index 7a7019e5b..122cad569 100644
--- a/demos/hooks-link-proxy-demo.html
+++ b/demos/hooks-link-proxy-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Hook to proxy all links
diff --git a/demos/hooks-mentaljs-demo.html b/demos/hooks-mentaljs-demo.html
index 5f4ddd730..62f5e0a79 100644
--- a/demos/hooks-mentaljs-demo.html
+++ b/demos/hooks-mentaljs-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Hook to sandbox JavaScript via MentalJS
@@ -34,10 +36,14 @@
DOMPurify.addHook('uponSanitizeElement', (node, data) => {
if (data.tagName === 'script') {
const script = node.textContent;
+ // Note: we never remove the
diff --git a/demos/hooks-node-removal2-demo.html b/demos/hooks-node-removal2-demo.html
index 1350f910e..33769a64a 100644
--- a/demos/hooks-node-removal2-demo.html
+++ b/demos/hooks-node-removal2-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Hook to remove an element and its content
@@ -52,7 +54,7 @@
// Clean HTML string and write into our DIV
const clean = DOMPurify.sanitize(dirty);
- document.getElementById('sanitized').innerText = clean;
+ document.getElementById('sanitized').textContent = clean;
diff --git a/demos/hooks-proxy-demo.html b/demos/hooks-proxy-demo.html
index d6f976863..4cadec886 100644
--- a/demos/hooks-proxy-demo.html
+++ b/demos/hooks-proxy-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Hook to proxy all HTTP leaks including CSS
@@ -71,6 +73,11 @@
DOMPurify.addHook('uponSanitizeElement', (node, data) => {
if (data.tagName === 'style') {
const output = [];
+ // Some DOM implementations (e.g. jsdom) do not
+ // populate .sheet for styles in the inert document
+ if (!node.sheet) {
+ return;
+ }
addCSSRules(output, node.sheet.cssRules);
node.textContent = output.join("\n");
}
diff --git a/demos/hooks-removal-demo.html b/demos/hooks-removal-demo.html
index da9675a2b..75abfead1 100644
--- a/demos/hooks-removal-demo.html
+++ b/demos/hooks-removal-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Adding and removing hooks
diff --git a/demos/hooks-sanitize-css-demo.html b/demos/hooks-sanitize-css-demo.html
index a2b91fdf8..566d88885 100644
--- a/demos/hooks-sanitize-css-demo.html
+++ b/demos/hooks-sanitize-css-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Hook to sanitize CSS
@@ -75,6 +77,11 @@
DOMPurify.addHook('uponSanitizeElement', function(node, data) {
if (data.tagName === 'style') {
let output = [];
+ // Some DOM implementations (e.g. jsdom) do not
+ // populate .sheet for styles in the inert document
+ if (!node.sheet) {
+ return;
+ }
addCSSRules(output, node.sheet.cssRules);
node.textContent = output.join("\n");
}
diff --git a/demos/hooks-scheme-allowlist.html b/demos/hooks-scheme-allowlist.html
index 8eb7411fc..d4b993821 100644
--- a/demos/hooks-scheme-allowlist.html
+++ b/demos/hooks-scheme-allowlist.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Hook to allowlist safe URI schemes
diff --git a/demos/hooks-svg-demo.html b/demos/hooks-svg-demo.html
new file mode 100644
index 000000000..e1f86588d
--- /dev/null
+++ b/demos/hooks-svg-demo.html
@@ -0,0 +1,47 @@
+
+
+
+
+ DOMPurify demo: Sanitize SVGs shown via an img tag
+
+
+
+
+
+
+
+
+
+
diff --git a/demos/hooks-target-blank-demo.html b/demos/hooks-target-blank-demo.html
index cfa64efcf..8956ac1e6 100644
--- a/demos/hooks-target-blank-demo.html
+++ b/demos/hooks-target-blank-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Hook to open all links in a new window
diff --git a/demos/trusted-types-demo.html b/demos/trusted-types-demo.html
index f90004957..0f8baaf41 100644
--- a/demos/trusted-types-demo.html
+++ b/demos/trusted-types-demo.html
@@ -1,6 +1,8 @@
-
+
+
+ DOMPurify demo: Trusted Types
' + dirty + '';
}
- const dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;
+ const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;
/*
* Use the DOMParser API by default, fallback later if needs be
* DOMParser not work for svg when has multiple root element.
@@ -892,29 +1305,254 @@ function createDOMPurify() {
// eslint-disable-next-line no-bitwise
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);
};
+ /**
+ * Replace template expression syntax (mustache, ERB, template
+ * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub
+ * sites. Order matters: mustache, then ERB, then template literal.
+ *
+ * @param value the string to scrub
+ * @returns the scrubbed string
+ */
+ const _stripTemplateExpressions = function _stripTemplateExpressions(value) {
+ value = stringReplace(value, MUSTACHE_EXPR$1, ' ');
+ value = stringReplace(value, ERB_EXPR$1, ' ');
+ value = stringReplace(value, TMPLIT_EXPR$1, ' ');
+ return value;
+ };
+ /**
+ * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the
+ * character data of an element subtree. Used as the final safety net for
+ * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions
+ * which only form after text-node normalization (e.g. fragments split across
+ * stripped elements) cannot survive into a template-evaluating framework.
+ *
+ * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`
+ * in place rather than round-tripping through innerHTML. This preserves
+ * descendant node references (important for IN_PLACE callers), avoids a
+ * serialize/reparse cycle, and reads literal character data — which means
+ * `<%...%>` in text content matches the ERB regex against its real bytes
+ * instead of the HTML-entity-escaped form innerHTML would produce.
+ *
+ * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for
+ * attributes is performed during the per-node `_sanitizeAttributes` pass.
+ *
+ * @param node The root element whose character data should be scrubbed.
+ */
+ const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {
+ var _node$querySelectorAl;
+ node.normalize();
+ const walker = createNodeIterator.call(node.ownerDocument || node, node,
+ // eslint-disable-next-line no-bitwise
+ NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);
+ let currentNode = walker.nextNode();
+ while (currentNode) {
+ currentNode.data = _stripTemplateExpressions(currentNode.data);
+ currentNode = walker.nextNode();
+ }
+ // NodeIterator does not descend into .content per the DOM spec,
+ // so we must explicitly recurse into each template's content fragment,
+ // mirroring the approach used by _sanitizeShadowDOM.
+ const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');
+ if (templates) {
+ arrayForEach(templates, tmpl => {
+ if (_isDocumentFragment(tmpl.content)) {
+ _scrubTemplateExpressions2(tmpl.content);
+ }
+ });
+ }
+ };
/**
* _isClobbered
*
+ * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML
+ * interface with [LegacyOverrideBuiltIns]; a descendant element with a
+ * `name` attribute matching a prototype property shadows that property
+ * on direct reads. We use this check at the IN_PLACE entry-point and
+ * during attribute sanitization to refuse clobbered forms.
+ *
* @param element element to check for clobbering attacks
* @return true if clobbered, false if safe
*/
const _isClobbered = function _isClobbered(element) {
- return element instanceof HTMLFormElement && (typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' || !(element.attributes instanceof NamedNodeMap) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function');
+ // Realm-independent tag-name probe. If we can't determine the tag
+ // name at all, we can't reason about clobbering — return false
+ // (the caller's other defences still apply).
+ const realTagName = getNodeName ? getNodeName(element) : null;
+ if (typeof realTagName !== 'string') {
+ return false;
+ }
+ if (transformCaseFunc(realTagName) !== 'form') {
+ return false;
+ }
+ return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||
+ // Realm-safe NamedNodeMap detection: equality against the cached
+ // prototype getter. Clobbered .attributes (e.g. )
+ // makes the direct read diverge from the cached read; a clean form
+ // (same-realm OR foreign-realm) has both reads pointing at the same
+ // canonical NamedNodeMap.
+ element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||
+ // NodeType clobbering probe. Cached Node.prototype.nodeType getter
+ // returns the integer 1 for any Element regardless of realm; direct
+ // read on a clobbered form (e.g. ) returns
+ // the named child element. Cheap addition — nodeType is read from
+ // an internal slot, no serialization cost — and removes a residual
+ // clobbering surface used by several mXSS / PI / comment branches
+ // in _sanitizeElements that compare currentNode.nodeType directly.
+ element.nodeType !== getNodeType(element) ||
+ // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named
+ // "childNodes" shadows the prototype getter. Direct reads of
+ // form.childNodes from a clobbered form return the named child
+ // instead of the real NodeList, so any walk that reads it directly
+ // skips the form's real children. Compare the direct read to the
+ // cached Node.prototype getter — when the form's named-property
+ // getter intercepts the read, the two values differ and we flag
+ // the form. This catches every clobbering child type (input,
+ // select, etc.) regardless of whether the named child happens to
+ // carry a numeric .length, which a typeof-based probe would miss
+ // (e.g. HTMLSelectElement.length is a defined unsigned-long).
+ element.childNodes !== getChildNodes(element);
+ };
+ /**
+ * Checks whether the given value is a DocumentFragment from any realm.
+ *
+ * The realm-independent replacement reads `nodeType` through the cached
+ * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE
+ * constant (11). nodeType is a numeric value resolved from the node's
+ * internal slot, identical across realms for the same kind of node.
+ *
+ * @param value object to check
+ * @return true if value is a DocumentFragment-shaped node from any realm
+ */
+ const _isDocumentFragment = function _isDocumentFragment(value) {
+ if (!getNodeType || typeof value !== 'object' || value === null) {
+ return false;
+ }
+ try {
+ return getNodeType(value) === NODE_TYPE.documentFragment;
+ } catch (_) {
+ return false;
+ }
};
/**
- * Checks whether the given object is a DOM node.
+ * Checks whether the given object is a DOM node, including nodes that
+ * originate from a different window/realm (e.g. an iframe's
+ * contentDocument). The previous `value instanceof Node` check was
+ * realm-bound: nodes from a different window failed it, causing
+ * sanitize() to silently stringify them and reset IN_PLACE to false,
+ * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.
*
* @param value object to check whether it's a DOM node
- * @return true is object is a DOM node
+ * @return true if value is a DOM node from any realm
*/
const _isNode = function _isNode(value) {
- return typeof Node === 'function' && value instanceof Node;
+ if (!getNodeType || typeof value !== 'object' || value === null) {
+ return false;
+ }
+ try {
+ return typeof getNodeType(value) === 'number';
+ } catch (_) {
+ return false;
+ }
};
function _executeHooks(hooks, currentNode, data) {
+ if (hooks.length === 0) {
+ return;
+ }
arrayForEach(hooks, hook => {
hook.call(DOMPurify, currentNode, data, CONFIG);
});
}
+ /**
+ * Structural-threat checks that condemn a node regardless of the
+ * allowlists: mXSS via namespace confusion, risky CSS construction,
+ * processing instructions, markup-bearing comments. Pure predicate;
+ * the caller removes. Check order is load-bearing.
+ *
+ * @param currentNode the node to inspect
+ * @param tagName the node's transformCaseFunc'd tag name
+ * @return true if the node must be removed
+ */
+ const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {
+ /* Detect mXSS attempts abusing namespace confusion */
+ if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {
+ return true;
+ }
+ /* Remove risky CSS construction leading to mXSS */
+ if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {
+ return true;
+ }
+ /* Remove any occurrence of processing instructions */
+ if (currentNode.nodeType === NODE_TYPE.processingInstruction) {
+ return true;
+ }
+ /* Remove any kind of possibly harmful comments */
+ if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {
+ return true;
+ }
+ return false;
+ };
+ /**
+ * Handle a node whose tag is forbidden or not allowlisted: keep
+ * allowed custom elements (false return exits _sanitizeElements
+ * early - namespace/fallback checks and the afterSanitizeElements
+ * hook are intentionally skipped for kept custom elements), else
+ * hoist content per KEEP_CONTENT and remove.
+ *
+ * @param currentNode the disallowed node
+ * @param tagName the node's transformCaseFunc'd tag name
+ * @return true if the node was removed, false if kept
+ */
+ const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {
+ /* Check if we have a custom element to handle */
+ if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {
+ return false;
+ }
+ if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {
+ return false;
+ }
+ }
+ /* Keep content except for bad-listed elements.
+ Use the cached prototype getters exclusively — the previous code
+ had `|| currentNode.parentNode` / `|| currentNode.childNodes`
+ fallbacks, but the cached getters always return the canonical
+ value (or null for a real parent-less node), so the fallback
+ path was dead in safe cases and a clobbering surface in unsafe
+ ones. Falsy cached results stay falsy; the `if (childNodes &&
+ parentNode)` check already gates correctly. */
+ if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {
+ const parentNode = getParentNode(currentNode);
+ const childNodes = getChildNodes(currentNode);
+ if (childNodes && parentNode) {
+ const childCount = childNodes.length;
+ /* In-place: hoist the *original* children so the iterator visits
+ and sanitises them through the same allowlist pass as every other
+ node. The caller built the tree in the live document, so the
+ originals carry already-queued resource events (``,
+ `