fix: block stored HTML injection and lint against raw HTML sinks (#9129)
This commit is contained in:
1 parent
15e3c6ac87
commit
cc7e4e0f7c
38 files changed
+676
-247
No files matched your search
@@ -12,9 +12,19 @@ inputs:
|
||||
runs:
|
||||
using: composite
|
||||
steps:
|
||||
# pipx tools install through `uv tool install`, and their venvs link to the Python that uv
|
||||
# picked. When the runner has no matching system Python (ubuntu-26.04 has none for semgrep),
|
||||
# uv downloads one to ~/.local/share/uv, which the mise cache does not hold. A later cache hit
|
||||
# then restores a venv whose interpreter is gone. Keep uv's Pythons inside the cached mise dir.
|
||||
- name: Keep uv-managed Pythons in the mise cache
|
||||
shell: bash
|
||||
run: echo "UV_PYTHON_INSTALL_DIR=${XDG_DATA_HOME:-$HOME/.local/share}/mise/uv-python" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Install tools with mise
|
||||
uses: jdx/mise-action@v5
|
||||
with:
|
||||
# v1 caches can hold pipx venvs that link to an uncached uv Python (see the step above)
|
||||
cache_key_prefix: mise-v2
|
||||
# renovate: datasource=github-releases depName=jdx/mise extractVersion=^v(?<version>.+)$
|
||||
version: 2026.11.3
|
||||
install_args: ${{ inputs.tools }}
|
||||
|
||||
@@ -105,7 +105,7 @@ jobs:
|
||||
run: |
|
||||
mise run py:mypy
|
||||
|
||||
- name: Semgrep (authz rules)
|
||||
- name: Semgrep (authz and XSS rules)
|
||||
if: matrix.Database == 'sqlite'
|
||||
run: |
|
||||
mise run py:semgrep
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# Test cases for xss.yml. Run with `mise run py:semgrep`.
|
||||
import json
|
||||
|
||||
import jinja2
|
||||
from fastapi import Response
|
||||
from fastapi.responses import HTMLResponse
|
||||
from jinja2 import Environment, Template
|
||||
from markupsafe import Markup
|
||||
|
||||
from mealie.routes.spa import script_safe_json
|
||||
|
||||
|
||||
def templates(source: str):
|
||||
# ruleid: mealie-jinja-autoescape
|
||||
Template(source)
|
||||
|
||||
# ruleid: mealie-jinja-autoescape
|
||||
jinja2.Environment(loader=None)
|
||||
|
||||
# ruleid: mealie-jinja-autoescape
|
||||
Template(source, autoescape=False)
|
||||
|
||||
# ok: mealie-jinja-autoescape
|
||||
Template(source, autoescape=True)
|
||||
|
||||
# ok: mealie-jinja-autoescape
|
||||
Environment(loader=None, autoescape=True)
|
||||
|
||||
|
||||
def script_tags(schema: dict, name: str):
|
||||
# ruleid: mealie-script-tag-json
|
||||
a = f"""<script type="application/ld+json">{json.dumps(schema)}</script>"""
|
||||
|
||||
# ruleid: mealie-script-tag-json
|
||||
b = f"<script>var name = {name};</script>"
|
||||
|
||||
# ok: mealie-script-tag-json
|
||||
c = f"""<script type="application/ld+json">{script_safe_json(schema)}</script>"""
|
||||
|
||||
return a, b, c
|
||||
|
||||
|
||||
def responses(name: str):
|
||||
# ruleid: mealie-html-response-fstring
|
||||
HTMLResponse(f"<h1>{name}</h1>")
|
||||
|
||||
# ruleid: mealie-html-response-fstring
|
||||
Response(f"<h1>{name}</h1>", media_type="text/html")
|
||||
|
||||
# ruleid: mealie-html-response-fstring
|
||||
Markup(f"<b>{name}</b>")
|
||||
|
||||
# ok: mealie-html-response-fstring
|
||||
Response(f'{{"name": "{name}"}}', media_type="application/json")
|
||||
@@ -0,0 +1,39 @@
|
||||
rules:
|
||||
- id: mealie-jinja-autoescape
|
||||
languages: [python]
|
||||
severity: ERROR
|
||||
message: >-
|
||||
Pass `autoescape=True` to jinja2. Without it every `{{ value }}` is written into the HTML as-is,
|
||||
so any user text that reaches the template becomes markup.
|
||||
patterns:
|
||||
- pattern-either:
|
||||
- pattern: jinja2.Template(...)
|
||||
- pattern: jinja2.Environment(...)
|
||||
- pattern-not: jinja2.Template(..., autoescape=True, ...)
|
||||
- pattern-not: jinja2.Environment(..., autoescape=True, ...)
|
||||
|
||||
- id: mealie-script-tag-json
|
||||
languages: [python]
|
||||
severity: ERROR
|
||||
message: >-
|
||||
Serialize data placed inside a <script> element with `script_safe_json()` from mealie/routes/spa.
|
||||
`json.dumps` leaves `</script>` and `<!--` intact, so a recipe field can close the element and
|
||||
inject markup.
|
||||
paths:
|
||||
include:
|
||||
- /mealie/routes/
|
||||
patterns:
|
||||
- pattern-regex: (?i)<script\b[^>]*>[^<]*\{(?!script_safe_json\()
|
||||
|
||||
- id: mealie-html-response-fstring
|
||||
languages: [python]
|
||||
severity: ERROR
|
||||
message: >-
|
||||
Don't build an HTML response from an f-string. Build the document with BeautifulSoup (which
|
||||
escapes text and attributes), or use a jinja2 template with autoescape.
|
||||
pattern-either:
|
||||
- pattern: fastapi.responses.HTMLResponse(f"...", ...)
|
||||
- pattern: starlette.responses.HTMLResponse(f"...", ...)
|
||||
- pattern: fastapi.Response(f"...", ..., media_type="text/html", ...)
|
||||
- pattern: fastapi.Response(content=f"...", ..., media_type="text/html", ...)
|
||||
- pattern: markupsafe.Markup(f"...")
|
||||
@@ -10,8 +10,7 @@
|
||||
v-if="qrCodeToken"
|
||||
class="d-flex flex-column align-center"
|
||||
>
|
||||
<!-- eslint-disable-next-line vue/no-v-html -->
|
||||
<div class="qr-code" v-html="qrCodeSvg" />
|
||||
<img class="qr-code" :src="qrCodeDataUrl" :alt="$t('recipe-share.scan-qr-code')">
|
||||
<p class="text-center text-medium-emphasis mt-3">
|
||||
{{ $t("recipe-share.scan-qr-code") }}
|
||||
</p>
|
||||
@@ -243,12 +242,14 @@ async function shareRecipe(token: string) {
|
||||
// ============================================================
|
||||
// QR Code
|
||||
|
||||
const qrCodeSvg = computed(() => qrCodeToken.value ? renderSVG(getTokenLink(qrCodeToken.value)) : "");
|
||||
const qrCodeDataUrl = computed(() => qrCodeToken.value
|
||||
? `data:image/svg+xml;charset=utf-8,${encodeURIComponent(renderSVG(getTokenLink(qrCodeToken.value)))}`
|
||||
: "");
|
||||
|
||||
async function downloadQrCode() {
|
||||
// Rasterize the SVG so the download opens in any photo viewer
|
||||
const image = new Image();
|
||||
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(qrCodeSvg.value)}`;
|
||||
image.src = qrCodeDataUrl.value;
|
||||
await image.decode();
|
||||
|
||||
const size = 1024;
|
||||
@@ -271,13 +272,9 @@ async function downloadQrCode() {
|
||||
|
||||
<style scoped>
|
||||
.qr-code {
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.qr-code :deep(svg) {
|
||||
display: block;
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
height: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -20,8 +20,7 @@
|
||||
{{ recipe.description }}
|
||||
</div>
|
||||
<template v-if="listItem && listItemDescriptions[index]">
|
||||
<!-- eslint-disable-next-line vue/no-v-html -->
|
||||
<div v-html="listItemDescriptions[index]" />
|
||||
<SafeInlineHtml :html="listItemDescriptions[index]" />
|
||||
</template>
|
||||
</template>
|
||||
<template #append>
|
||||
@@ -36,7 +35,6 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import DOMPurify from "dompurify";
|
||||
import RecipeCardLineItem from "./RecipeCardLineItem.vue";
|
||||
import { useFraction } from "~/composables/recipes/use-fraction";
|
||||
import type { ShoppingListItemOut } from "~/lib/api/types/household";
|
||||
@@ -85,13 +83,6 @@ const attrs = computed(() => {
|
||||
};
|
||||
});
|
||||
|
||||
function sanitizeHTML(rawHtml: string) {
|
||||
return DOMPurify.sanitize(rawHtml, {
|
||||
USE_PROFILES: { html: true },
|
||||
ALLOWED_TAGS: ["strong", "sup"],
|
||||
});
|
||||
}
|
||||
|
||||
const listItemDescriptions = computed<string[]>(() => {
|
||||
if (
|
||||
props.recipes.length === 1 // we don't need to specify details if there's only one recipe ref
|
||||
@@ -140,7 +131,7 @@ const listItemDescriptions = computed<string[]>(() => {
|
||||
listItemDescription += `, ${itemRef.recipeNote}`;
|
||||
}
|
||||
|
||||
listItemDescriptions.push(sanitizeHTML(listItemDescription));
|
||||
listItemDescriptions.push(listItemDescription);
|
||||
}
|
||||
|
||||
return listItemDescriptions;
|
||||
|
||||
+2
-1
@@ -9,7 +9,7 @@
|
||||
:label="$t('recipe.original-url')"
|
||||
/>
|
||||
<v-btn
|
||||
v-else-if="recipe.orgURL && !isCookMode"
|
||||
v-else-if="isHttpUrl(recipe.orgURL) && !isCookMode"
|
||||
:hover="false"
|
||||
:ripple="false"
|
||||
variant="flat"
|
||||
@@ -84,6 +84,7 @@
|
||||
<script setup lang="ts">
|
||||
import { usePageState } from "~/composables/recipe-page/shared-state";
|
||||
import type { RecipeOut } from "~/lib/api/types/recipe";
|
||||
import { isHttpUrl } from "~/lib/validators/url";
|
||||
|
||||
const recipe = defineModel<RecipeOut>({ required: true });
|
||||
const { isEditForm, isCookMode } = usePageState(recipe.value.slug);
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
<!-- eslint-disable vue/no-v-html -->
|
||||
<template>
|
||||
<div :class="dense ? 'wrapper' : 'wrapper pa-3'">
|
||||
<section>
|
||||
@@ -34,8 +33,7 @@
|
||||
<v-icon start>
|
||||
{{ $globals.icons.potSteam }}
|
||||
</v-icon>
|
||||
<!-- eslint-disable-next-line vue/no-v-html -->
|
||||
<span v-html="recipeYield" />
|
||||
<SafeInlineHtml :html="recipeYield" />
|
||||
</div>
|
||||
</div>
|
||||
<v-row class="d-flex justify-start">
|
||||
@@ -88,11 +86,9 @@
|
||||
:key="`ingredient-${ingredientIndex}`"
|
||||
class="ingredient-cell"
|
||||
>
|
||||
<!-- eslint-disable-next-line vue/no-v-html -->
|
||||
<p
|
||||
class="ingredient-body"
|
||||
v-html="parseText(ingredient)"
|
||||
/>
|
||||
<p class="ingredient-body">
|
||||
<SafeInlineHtml :html="parseText(ingredient)" />
|
||||
</p>
|
||||
<!-- paper has nothing to tap, so what the menu holds on screen is spelled out here -->
|
||||
<SafeMarkdown
|
||||
v-if="preferences.showSubstitutions && substitutionSummary(ingredient)"
|
||||
@@ -158,11 +154,9 @@
|
||||
v-for="(ingredient, ingredientIndex) in stepLinkedIngredients.get(`${sectionIndex}-${stepIndex}`) ?? []"
|
||||
:key="`ingredient-${ingredientIndex}`"
|
||||
>
|
||||
<!-- eslint-disable-next-line vue/no-v-html -->
|
||||
<p
|
||||
class="ingredient-body"
|
||||
v-html="parseText(ingredient)"
|
||||
/>
|
||||
<p class="ingredient-body">
|
||||
<SafeInlineHtml :html="parseText(ingredient)" />
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
@@ -223,7 +217,6 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import DOMPurify from "dompurify";
|
||||
import RecipeTimeCard from "~/components/Domain/Recipe/RecipeTimeCard.vue";
|
||||
import { useStaticRoutes } from "~/composables/api";
|
||||
import type { RecipeOut, RecipeIngredient, RecipeStep } from "~/lib/api/types/recipe";
|
||||
@@ -259,12 +252,6 @@ const { recipeImage } = useStaticRoutes();
|
||||
const { imageKey } = usePageState(props.recipe.slug);
|
||||
const { labels } = useNutritionLabels();
|
||||
|
||||
function sanitizeHTML(rawHtml: string) {
|
||||
return DOMPurify.sanitize(rawHtml, {
|
||||
USE_PROFILES: { html: true },
|
||||
ALLOWED_TAGS: ["strong", "sup"],
|
||||
});
|
||||
}
|
||||
const servingsDisplay = computed(() => {
|
||||
const { scaledAmountDisplay } = useScaledAmount(props.recipe.recipeYieldQuantity, props.scale);
|
||||
return scaledAmountDisplay || props.recipe.recipeYield
|
||||
@@ -282,10 +269,10 @@ const yieldDisplay = computed(() => {
|
||||
|
||||
const recipeYield = computed(() => {
|
||||
if (servingsDisplay.value && yieldDisplay.value) {
|
||||
return sanitizeHTML(`${yieldDisplay.value}; ${servingsDisplay.value}`);
|
||||
return `${yieldDisplay.value}; ${servingsDisplay.value}`;
|
||||
}
|
||||
else {
|
||||
return sanitizeHTML(yieldDisplay.value || servingsDisplay.value);
|
||||
return yieldDisplay.value || servingsDisplay.value;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -33,8 +33,7 @@
|
||||
>
|
||||
{{ $globals.icons.edit }}
|
||||
</v-icon>
|
||||
<!-- eslint-disable-next-line vue/no-v-html -->
|
||||
<span v-html="yieldDisplay" />
|
||||
<SafeInlineHtml :html="yieldDisplay" />
|
||||
</v-card>
|
||||
</template>
|
||||
<span> {{ $t("recipe.edit-scale") }} </span>
|
||||
@@ -55,8 +54,7 @@
|
||||
>
|
||||
{{ $globals.icons.edit }}
|
||||
</v-icon>
|
||||
<!-- eslint-disable-next-line vue/no-v-html -->
|
||||
<span v-html="yieldDisplay" />
|
||||
<SafeInlineHtml :html="yieldDisplay" />
|
||||
</v-card>
|
||||
</template>
|
||||
<v-card min-width="300px">
|
||||
|
||||
@@ -17,15 +17,13 @@
|
||||
</v-icon>
|
||||
<p class="my-0 opacity-80">
|
||||
<span class="font-weight-bold">{{ $t("recipe.yield") }}</span><br>
|
||||
<!-- eslint-disable-next-line vue/no-v-html -->
|
||||
<span v-html="yieldDisplay" />
|
||||
<SafeInlineHtml :html="yieldDisplay" />
|
||||
</p>
|
||||
</v-row>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import DOMPurify from "dompurify";
|
||||
import { useScaledAmount } from "~/composables/recipes/use-scaled-amount";
|
||||
|
||||
interface Props {
|
||||
@@ -41,13 +39,6 @@ const props = withDefaults(defineProps<Props>(), {
|
||||
color: "accent custom-transparent",
|
||||
});
|
||||
|
||||
function sanitizeHTML(rawHtml: string) {
|
||||
return DOMPurify.sanitize(rawHtml, {
|
||||
USE_PROFILES: { html: true },
|
||||
ALLOWED_TAGS: ["strong", "sup"],
|
||||
});
|
||||
}
|
||||
|
||||
const yieldDisplay = computed<string>(() => {
|
||||
const components: string[] = [];
|
||||
|
||||
@@ -61,6 +52,6 @@ const yieldDisplay = computed<string>(() => {
|
||||
components.push(text);
|
||||
}
|
||||
|
||||
return sanitizeHTML(components.join(" "));
|
||||
return components.join(" ");
|
||||
});
|
||||
</script>
|
||||
@@ -21,6 +21,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useDropZone } from "@vueuse/core";
|
||||
import { isHttpUrl } from "~/lib/validators/url";
|
||||
|
||||
defineProps({
|
||||
disabled: {
|
||||
@@ -42,16 +43,6 @@ const el = ref<HTMLDivElement>();
|
||||
*/
|
||||
const IMG_SRC = /<img\b[^>]*?\ssrc\s*=\s*["']([^"']+)["']/i;
|
||||
|
||||
function isHttpUrl(value: string) {
|
||||
try {
|
||||
const { protocol } = new URL(value);
|
||||
return protocol === "http:" || protocol === "https:";
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isImageDataUrl(value: string) {
|
||||
return /^data:image\//i.test(value);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<template>
|
||||
<span v-html="value" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { sanitizeInlineHtml } from "~/lib/sanitize";
|
||||
|
||||
// For short inline text, user text included, such as yields and ingredient lines. Only fraction
|
||||
// and emphasis tags survive and all attributes are removed. Use <SafeMarkdown> for markdown.
|
||||
const props = defineProps<{
|
||||
html?: string | null;
|
||||
}>();
|
||||
|
||||
const value = computed(() => sanitizeInlineHtml(props.html));
|
||||
</script>
|
||||
@@ -1,12 +1,10 @@
|
||||
<template>
|
||||
<!-- eslint-disable-next-line vue/no-v-html is safe here because all HTML is sanitized with DOMPurify in setup() -->
|
||||
<div v-html="value" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { PropType } from "vue";
|
||||
import { marked } from "marked";
|
||||
import { sanitizeMarkdownHtml } from "~/lib/sanitize/markdown";
|
||||
import { renderMarkdown } from "~/lib/sanitize";
|
||||
|
||||
const props = defineProps({
|
||||
source: {
|
||||
@@ -17,10 +15,7 @@ const props = defineProps({
|
||||
|
||||
const { $appInfo } = useNuxtApp();
|
||||
|
||||
const value = computed(() => {
|
||||
const rawHtml = marked.parse(props.source || "", { async: false, breaks: true });
|
||||
return sanitizeMarkdownHtml(rawHtml, $appInfo?.allowedIframeHosts ?? []);
|
||||
});
|
||||
const value = computed(() => renderMarkdown(props.source, $appInfo?.allowedIframeHosts ?? []));
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -59,10 +59,12 @@ describe("parseIngredientText", () => {
|
||||
expect(result).contain("1 1/2");
|
||||
});
|
||||
|
||||
test("sanitizes html", () => {
|
||||
const ingredient = createRecipeIngredient({ note: "<script>alert('foo')</script>" });
|
||||
// Callers render this through <SafeInlineHtml> or <SafeMarkdown>, which sanitize. Escaping here
|
||||
// would put "<" into clipboard copies and parser input.
|
||||
test("returns user text unescaped", () => {
|
||||
const ingredient = createRecipeIngredient({ note: "<b>x</b> & y" });
|
||||
|
||||
expect(parseIngredientText(ingredient)).not.toContain("<script>");
|
||||
expect(parseIngredientText(ingredient)).toContain("<b>x</b> & y");
|
||||
});
|
||||
|
||||
test("referenced recipe links navigate in the current page", () => {
|
||||
@@ -231,7 +233,7 @@ describe("parseIngredientText", () => {
|
||||
food: { id: "1", name: "salt" },
|
||||
});
|
||||
|
||||
expect(parseIngredientText(ingredient)).toEqual("< 0.001 cup salt");
|
||||
expect(parseIngredientText(ingredient)).toEqual("< 0.001 cup salt");
|
||||
});
|
||||
|
||||
test("fraction below minimum denominator shows < 1/10", () => {
|
||||
@@ -241,7 +243,7 @@ describe("parseIngredientText", () => {
|
||||
food: { id: "1", name: "salt" },
|
||||
});
|
||||
|
||||
expect(parseIngredientText(ingredient)).toEqual("< <sup>1</sup><span>⁄</span><sub>10</sub> cup salt");
|
||||
expect(parseIngredientText(ingredient)).toEqual("< <sup>1</sup><span>⁄</span><sub>10</sub> cup salt");
|
||||
});
|
||||
|
||||
test("fraction below minimum denominator without formatting shows < 1/10", () => {
|
||||
@@ -251,7 +253,7 @@ describe("parseIngredientText", () => {
|
||||
food: { id: "1", name: "salt" },
|
||||
});
|
||||
|
||||
expect(parseIngredientText(ingredient, 1, false)).toEqual("< 1/10 cup salt");
|
||||
expect(parseIngredientText(ingredient, 1, false)).toEqual("< 1/10 cup salt");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import DOMPurify from "isomorphic-dompurify";
|
||||
import { useFraction } from "./use-fraction";
|
||||
import { useLocales } from "../use-locales";
|
||||
import type { IngredientFoodCreate, IngredientUnitCreate, IngredientFoodOut, IngredientFoodSummary, IngredientUnitOut, RecipeDraft, RecipeIngredient } from "~/lib/api/types/recipe";
|
||||
@@ -8,13 +7,6 @@ const { frac } = useFraction();
|
||||
const FRAC_MIN_DENOM = 10;
|
||||
const DECIMAL_PRECISION = 3;
|
||||
|
||||
export function sanitizeIngredientHTML(rawHtml: string) {
|
||||
return DOMPurify.sanitize(rawHtml, {
|
||||
USE_PROFILES: { html: true },
|
||||
ALLOWED_TAGS: ["b", "q", "i", "strong", "sup"],
|
||||
});
|
||||
}
|
||||
|
||||
export function useFoodName(food: IngredientFoodCreate | IngredientFoodOut | IngredientFoodSummary | undefined, usePlural: boolean) {
|
||||
if (!food) {
|
||||
return "";
|
||||
@@ -45,7 +37,7 @@ function useRecipeLink(recipe: RecipeDraft | undefined, groupSlug: string | unde
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return `<a href="/g/${groupSlug}/r/${recipe.slug}">${recipe.name}</a>`;
|
||||
return `<a href="/g/${encodeURIComponent(groupSlug)}/r/${encodeURIComponent(recipe.slug)}">${recipe.name}</a>`;
|
||||
}
|
||||
|
||||
type ParsedIngredientText = {
|
||||
@@ -140,10 +132,10 @@ export function useIngredientTextParser() {
|
||||
const ingName = referencedRecipe ? referencedRecipe.name || "" : useFoodName(food || undefined, usePluralFood);
|
||||
|
||||
return {
|
||||
quantity: returnQty ? sanitizeIngredientHTML(returnQty) : undefined,
|
||||
unit: unitName && quantity ? sanitizeIngredientHTML(unitName) : undefined,
|
||||
name: ingName ? sanitizeIngredientHTML(ingName) : undefined,
|
||||
note: note ? sanitizeIngredientHTML(note) : undefined,
|
||||
quantity: returnQty || undefined,
|
||||
unit: unitName && quantity ? unitName : undefined,
|
||||
name: ingName || undefined,
|
||||
note: note || undefined,
|
||||
recipeLink: useRecipeLink(referencedRecipe || undefined, groupSlug),
|
||||
};
|
||||
};
|
||||
@@ -151,8 +143,7 @@ export function useIngredientTextParser() {
|
||||
function parseIngredientText(ingredient: RecipeIngredient, scale = 1, includeFormating = true): string {
|
||||
const { quantity, unit, name, note } = useParsedIngredientText(ingredient, scale, includeFormating);
|
||||
|
||||
const text = `${quantity || ""} ${unit || ""} ${name || ""} ${note || ""}`.replace(/ {2,}/g, " ").trim();
|
||||
return sanitizeIngredientHTML(text);
|
||||
return `${quantity || ""} ${unit || ""} ${name || ""} ${note || ""}`.replace(/ {2,}/g, " ").trim();
|
||||
};
|
||||
|
||||
function ingredientToParserString(ingredient: RecipeIngredient): string {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
// The only module allowed to import dompurify or marked (enforced in eslint.config.mjs).
|
||||
// Render user HTML through <SafeMarkdown> or <SafeInlineHtml> instead of calling these from a page.
|
||||
export { sanitizeInlineHtml } from "./inline";
|
||||
export { renderMarkdown, sanitizeMarkdownHtml } from "./markdown";
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { sanitizeInlineHtml } from "./inline";
|
||||
|
||||
// Payload from GHSA-h73g-85mv-f42f: a full-screen overlay with a phishing link.
|
||||
const OVERLAY_PAYLOAD = `<div style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:999999;background:#fff">
|
||||
<p>This recipe has been removed. <a href="https://attacker.example/login">Click here</a>.</p>
|
||||
</div><a name="recipe"></a><img src="https://attacker.example/beacon.png">`;
|
||||
|
||||
describe("sanitizeInlineHtml", () => {
|
||||
test("returns empty string for nullish input", () => {
|
||||
expect(sanitizeInlineHtml(null)).toEqual("");
|
||||
expect(sanitizeInlineHtml(undefined)).toEqual("");
|
||||
expect(sanitizeInlineHtml("")).toEqual("");
|
||||
});
|
||||
|
||||
test("keeps fraction formatting", () => {
|
||||
expect(sanitizeInlineHtml("1<sup>1</sup><span>⁄</span><sub>2</sub>")).toEqual(
|
||||
"1<sup>1</sup><span>⁄</span><sub>2</sub>",
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps emphasis tags", () => {
|
||||
expect(sanitizeInlineHtml("<strong>a</strong> <b>b</b> <i>c</i> <q>d</q>")).toEqual(
|
||||
"<strong>a</strong> <b>b</b> <i>c</i> <q>d</q>",
|
||||
);
|
||||
});
|
||||
|
||||
test("strips block elements, links, images, and styles from the overlay payload", () => {
|
||||
const html = sanitizeInlineHtml(OVERLAY_PAYLOAD);
|
||||
for (const fragment of ["<div", "<p", "<a", "<img", "style", "href", "position", "attacker.example"]) {
|
||||
expect(html).not.toContain(fragment);
|
||||
}
|
||||
expect(html).toContain("This recipe has been removed.");
|
||||
});
|
||||
|
||||
test("drops attributes on allowed tags", () => {
|
||||
expect(sanitizeInlineHtml("<span class=\"position-fixed\" style=\"color:red\" onclick=\"x()\">a</span>")).toEqual(
|
||||
"<span>a</span>",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import createDOMPurify from "dompurify";
|
||||
|
||||
const INLINE_ALLOWED_TAGS = ["b", "i", "q", "em", "strong", "sup", "sub", "span"];
|
||||
|
||||
const purifier = createDOMPurify(window);
|
||||
|
||||
/**
|
||||
* Sanitizes a short run of inline HTML, such as an ingredient line or a recipe yield, where the
|
||||
* only markup we emit is fraction formatting and basic emphasis.
|
||||
*
|
||||
* Every attribute is dropped, so user text can't bring its own `style`, `class`, or links.
|
||||
*/
|
||||
export function sanitizeInlineHtml(rawHtml: string | null | undefined): string {
|
||||
if (!rawHtml) {
|
||||
return "";
|
||||
}
|
||||
|
||||
// Don't add USE_PROFILES here: DOMPurify replaces ALLOWED_TAGS with the whole profile when it's set.
|
||||
return purifier.sanitize(rawHtml, {
|
||||
ALLOWED_TAGS: INLINE_ALLOWED_TAGS,
|
||||
ALLOWED_ATTR: [],
|
||||
});
|
||||
}
|
||||
@@ -34,6 +34,30 @@ describe("sanitizeMarkdownHtml", () => {
|
||||
expect(html).not.toContain("<button");
|
||||
});
|
||||
|
||||
test("strips class attributes so utility classes can't build an overlay", () => {
|
||||
const html = sanitizeMarkdownHtml("<div class=\"position-fixed top-0 left-0 w-100 h-screen bg-white\">x</div>");
|
||||
expect(html).not.toContain("class");
|
||||
expect(html).not.toContain("position-fixed");
|
||||
});
|
||||
|
||||
test("strips positioning styles and keeps allowed ones", () => {
|
||||
const html = sanitizeMarkdownHtml("<div style=\"position:fixed;top:0;z-index:999999;color:red\">x</div>");
|
||||
expect(html).not.toContain("position");
|
||||
expect(html).not.toContain("z-index");
|
||||
expect(html).toContain("color:red");
|
||||
});
|
||||
|
||||
test("prefixes name attributes to prevent DOM clobbering", () => {
|
||||
const html = sanitizeMarkdownHtml("<a name=\"recipe\"></a><img name=\"config\" src=\"/x.png\">");
|
||||
expect(html).toContain("name=\"user-content-recipe\"");
|
||||
expect(html).toContain("name=\"user-content-config\"");
|
||||
});
|
||||
|
||||
test("strips javascript: links", () => {
|
||||
const html = sanitizeMarkdownHtml("<a href=\"javascript:alert(1)\">x</a>");
|
||||
expect(html).not.toContain("javascript");
|
||||
});
|
||||
|
||||
test("strips iframes when no allowed hosts are configured", () => {
|
||||
const html = sanitizeMarkdownHtml("<iframe src=\"https://evil.example/x\"></iframe>", []);
|
||||
expect(html).not.toContain("<iframe");
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
import DOMPurify from "isomorphic-dompurify";
|
||||
|
||||
enum DOMPurifyHook {
|
||||
UponSanitizeAttribute = "uponSanitizeAttribute",
|
||||
AfterSanitizeAttributes = "afterSanitizeAttributes",
|
||||
}
|
||||
import createDOMPurify from "dompurify";
|
||||
import { marked } from "marked";
|
||||
|
||||
const ALLOWED_STYLE_PROPERTIES = [
|
||||
"background-color", "color", "font-style", "font-weight", "text-decoration", "text-align",
|
||||
@@ -11,13 +7,15 @@ const ALLOWED_STYLE_PROPERTIES = [
|
||||
|
||||
const BASE_ALLOWED_TAGS = [
|
||||
"strong", "em", "b", "i", "u", "p", "code", "pre", "samp", "kbd", "var", "sub", "sup", "dfn", "cite",
|
||||
"small", "address", "hr", "br", "id", "div", "span", "h1", "h2", "h3", "h4", "h5", "h6",
|
||||
"small", "address", "hr", "br", "div", "span", "h1", "h2", "h3", "h4", "h5", "h6",
|
||||
"ul", "ol", "li", "dl", "dt", "dd", "abbr", "a", "img", "blockquote",
|
||||
"del", "ins", "table", "thead", "tbody", "tfoot", "tr", "th", "td", "colgroup",
|
||||
];
|
||||
|
||||
// No `class`: Vuetify's utility classes (position-fixed, top-0, w-100, h-screen, bg-white, ...)
|
||||
// are enough to build a full-screen overlay out of user content, which the style filter can't stop.
|
||||
const BASE_ALLOWED_ATTR = [
|
||||
"href", "src", "alt", "height", "width", "class", "title",
|
||||
"href", "src", "alt", "height", "width", "title",
|
||||
"cite", "datetime", "name", "abbr", "target", "border", "start", "style",
|
||||
];
|
||||
|
||||
@@ -50,6 +48,28 @@ function isAllowedIframeSrc(src: string, allowedHosts: string[]): boolean {
|
||||
});
|
||||
}
|
||||
|
||||
// A private instance, so these hooks never apply to other sanitizers.
|
||||
const purifier = createDOMPurify(window);
|
||||
|
||||
// Sanitizing is synchronous, so the hooks can read the current call's host list from here.
|
||||
let currentIframeHosts: string[] = [];
|
||||
|
||||
purifier.addHook("uponSanitizeAttribute", (_node, data) => {
|
||||
if (data.attrName === "style") {
|
||||
const styles = data.attrValue.split(";").filter((style) => {
|
||||
const [property] = style.split(":");
|
||||
return ALLOWED_STYLE_PROPERTIES.includes(property.trim().toLowerCase());
|
||||
});
|
||||
data.attrValue = styles.join(";");
|
||||
}
|
||||
});
|
||||
|
||||
purifier.addHook("afterSanitizeAttributes", (node) => {
|
||||
if (node.nodeName === "IFRAME" && !isAllowedIframeSrc(node.getAttribute("src") || "", currentIframeHosts)) {
|
||||
node.parentNode?.removeChild(node);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Sanitizes pre-rendered HTML (from markdown) for display in user content such as recipe
|
||||
* instructions, notes, and descriptions.
|
||||
@@ -66,33 +86,23 @@ export function sanitizeMarkdownHtml(rawHtml: string | null | undefined, allowed
|
||||
}
|
||||
|
||||
const allowIframe = allowedIframeHosts.length > 0;
|
||||
currentIframeHosts = allowedIframeHosts;
|
||||
|
||||
DOMPurify.addHook(DOMPurifyHook.UponSanitizeAttribute, (_node, data) => {
|
||||
if (data.attrName === "style") {
|
||||
const styles = data.attrValue.split(";").filter((style) => {
|
||||
const [property] = style.split(":");
|
||||
return ALLOWED_STYLE_PROPERTIES.includes(property.trim().toLowerCase());
|
||||
});
|
||||
data.attrValue = styles.join(";");
|
||||
}
|
||||
});
|
||||
|
||||
if (allowIframe) {
|
||||
DOMPurify.addHook(DOMPurifyHook.AfterSanitizeAttributes, (node) => {
|
||||
if (node.nodeName === "IFRAME" && !isAllowedIframeSrc(node.getAttribute("src") || "", allowedIframeHosts)) {
|
||||
node.parentNode?.removeChild(node);
|
||||
}
|
||||
try {
|
||||
return purifier.sanitize(rawHtml, {
|
||||
ALLOWED_TAGS: allowIframe ? [...BASE_ALLOWED_TAGS, "iframe"] : BASE_ALLOWED_TAGS,
|
||||
ALLOWED_ATTR: allowIframe ? [...BASE_ALLOWED_ATTR, ...IFRAME_ALLOWED_ATTR] : BASE_ALLOWED_ATTR,
|
||||
// Prefixes `name` values with "user-content-" so user content can't clobber window/document globals.
|
||||
SANITIZE_NAMED_PROPS: true,
|
||||
});
|
||||
}
|
||||
|
||||
const sanitized = DOMPurify.sanitize(rawHtml, {
|
||||
ALLOWED_TAGS: allowIframe ? [...BASE_ALLOWED_TAGS, "iframe"] : BASE_ALLOWED_TAGS,
|
||||
ALLOWED_ATTR: allowIframe ? [...BASE_ALLOWED_ATTR, ...IFRAME_ALLOWED_ATTR] : BASE_ALLOWED_ATTR,
|
||||
});
|
||||
|
||||
Object.values(DOMPurifyHook).forEach((hook) => {
|
||||
DOMPurify.removeHook(hook);
|
||||
});
|
||||
|
||||
return sanitized;
|
||||
finally {
|
||||
currentIframeHosts = [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Renders user-supplied markdown to sanitized HTML. See `sanitizeMarkdownHtml` for what survives. */
|
||||
export function renderMarkdown(source: string | null | undefined, allowedIframeHosts: string[] = []): string {
|
||||
const rawHtml = marked.parse(source || "", { async: false, breaks: true });
|
||||
return sanitizeMarkdownHtml(rawHtml, allowedIframeHosts);
|
||||
}
|
||||
@@ -1,2 +1,3 @@
|
||||
export { scorePassword } from "./password";
|
||||
export { isHttpUrl } from "./url";
|
||||
export { required, email, whitespace, url, urlOptional, minLength, maxLength } from "./inputs";
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isHttpUrl } from "./url";
|
||||
import { useGlobalI18n } from "~/composables/use-global-i18n";
|
||||
|
||||
const EMAIL_REGEX
|
||||
@@ -20,17 +21,7 @@ export function whitespace(v: string | null | undefined) {
|
||||
|
||||
export function url(v: string | undefined | null) {
|
||||
const i18n = useGlobalI18n();
|
||||
if (!v) {
|
||||
return i18n.t("validators.invalid-url");
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = new URL(v);
|
||||
return (parsed.protocol === "http:" || parsed.protocol === "https:") || i18n.t("validators.invalid-url");
|
||||
}
|
||||
catch {
|
||||
return i18n.t("validators.invalid-url");
|
||||
}
|
||||
return isHttpUrl(v) || i18n.t("validators.invalid-url");
|
||||
}
|
||||
|
||||
export function urlOptional(v: string | undefined | null) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { isHttpUrl } from "./url";
|
||||
|
||||
describe("isHttpUrl", () => {
|
||||
test.each(["https://example.com/recipe", "http://example.com", "HTTPS://EXAMPLE.COM"])("accepts %s", (url) => {
|
||||
expect(isHttpUrl(url)).toBe(true);
|
||||
});
|
||||
|
||||
test.each([
|
||||
null,
|
||||
undefined,
|
||||
"",
|
||||
"javascript:alert(1)",
|
||||
" javascript:alert(1)",
|
||||
"JaVaScRiPt:alert(1)",
|
||||
"java\tscript:alert(1)",
|
||||
"data:text/html,<script>alert(1)</script>",
|
||||
"vbscript:msgbox(1)",
|
||||
"/relative/path",
|
||||
"example.com",
|
||||
])("rejects %s", (url) => {
|
||||
expect(isHttpUrl(url)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* True only for absolute http(s) URLs. Use it before binding user-supplied URLs to `href` or
|
||||
* `src`, since Vue doesn't block `javascript:` or `data:` there.
|
||||
*/
|
||||
export function isHttpUrl(value: string | null | undefined): boolean {
|
||||
if (!value) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const { protocol } = new URL(value);
|
||||
return protocol === "http:" || protocol === "https:";
|
||||
}
|
||||
catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
Vendored
+2
@@ -33,6 +33,7 @@ import type LanguageDialog from "@/components/global/LanguageDialog.vue";
|
||||
import type MarkdownEditor from "@/components/global/MarkdownEditor.vue";
|
||||
import type RecipeJsonEditor from "@/components/global/RecipeJsonEditor.vue";
|
||||
import type ReportTable from "@/components/global/ReportTable.vue";
|
||||
import type SafeInlineHtml from "@/components/global/SafeInlineHtml.vue";
|
||||
import type SafeMarkdown from "@/components/global/SafeMarkdown.vue";
|
||||
import type StatsCards from "@/components/global/StatsCards.vue";
|
||||
import type ToggleState from "@/components/global/ToggleState.vue";
|
||||
@@ -76,6 +77,7 @@ declare module "vue" {
|
||||
MarkdownEditor: typeof MarkdownEditor;
|
||||
RecipeJsonEditor: typeof RecipeJsonEditor;
|
||||
ReportTable: typeof ReportTable;
|
||||
SafeInlineHtml: typeof SafeInlineHtml;
|
||||
SafeMarkdown: typeof SafeMarkdown;
|
||||
StatsCards: typeof StatsCards;
|
||||
ToggleState: typeof ToggleState;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
// `pnpm lint:security`: fails when a raw-HTML rule is broken anywhere, even behind an inline disable.
|
||||
import path from "node:path";
|
||||
import { createSecurityLinter, PROTECTED_RULES } from "./security.mjs";
|
||||
|
||||
const results = await createSecurityLinter(process.cwd()).lintFiles(["."]);
|
||||
|
||||
const problems = results.flatMap(result => result.messages
|
||||
.filter(message => PROTECTED_RULES.has(message.ruleId))
|
||||
.map(message => `${path.relative(process.cwd(), result.filePath)}:${message.line}:${message.column} ${message.ruleId} ${message.message}`));
|
||||
|
||||
if (problems.length > 0) {
|
||||
console.error(problems.join("\n"));
|
||||
console.error(
|
||||
`\n${problems.length} raw-HTML rule violation(s). These rules ignore inline eslint comments. Render HTML `
|
||||
+ "with <SafeMarkdown> or <SafeInlineHtml>, or add a reviewed file override in eslint.config.mjs.",
|
||||
);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// @vitest-environment node
|
||||
import path from "node:path";
|
||||
import { beforeAll, describe, expect, test } from "vitest";
|
||||
import { createSecurityLinter, PROTECTED_RULES } from "./security.mjs";
|
||||
|
||||
// The same linter `pnpm lint:security` runs: protected rules only, inline config ignored.
|
||||
const eslint = createSecurityLinter(path.resolve(__dirname, ".."));
|
||||
|
||||
async function securityErrors(code: string, filePath: string): Promise<string[]> {
|
||||
const [result] = await eslint.lintText(code, { filePath });
|
||||
return result!.messages
|
||||
.filter(message => message.ruleId && PROTECTED_RULES.has(message.ruleId))
|
||||
.map(message => message.ruleId!);
|
||||
}
|
||||
|
||||
const vue = (template: string, script = "const x = \"\";") =>
|
||||
`<template>\n ${template}\n</template>\n\n<script setup lang="ts">\n${script}\n</script>\n`;
|
||||
|
||||
const COMPONENT = "app/components/Domain/Foo.vue";
|
||||
const SCRIPT = "app/composables/foo.ts";
|
||||
|
||||
describe("raw HTML lint rules", () => {
|
||||
// The first lint loads the whole Nuxt config and its parsers.
|
||||
beforeAll(() => securityErrors(vue("<div />"), "app/components/Domain/Warmup.vue"), 60_000);
|
||||
|
||||
test("flags v-html in an ordinary component", async () => {
|
||||
expect(await securityErrors(vue("<div v-html=\"x\" />"), COMPONENT)).toEqual(["vue/no-v-html"]);
|
||||
});
|
||||
|
||||
test.each(["SafeMarkdown.vue", "SafeInlineHtml.vue"])("allows v-html in %s", async (file) => {
|
||||
expect(await securityErrors(vue("<span v-html=\"x\" />"), `app/components/global/${file}`)).toEqual([]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
[":innerHTML", "<div :innerHTML=\"x\" />", "vue/no-restricted-v-bind"],
|
||||
[":srcdoc", "<iframe :srcdoc=\"x\" />", "vue/no-restricted-v-bind"],
|
||||
["object v-bind", "<div v-bind=\"{ innerHTML: x }\" />", "vue/no-restricted-syntax"],
|
||||
])("flags %s in templates", async (_name, template, rule) => {
|
||||
expect(await securityErrors(vue(template), COMPONENT)).toEqual([rule]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["document.body.innerHTML = \"x\";"],
|
||||
["document.body[\"outerHTML\"] = \"x\";"],
|
||||
["document.createElement(\"iframe\").srcdoc = \"x\";"],
|
||||
["document.body.insertAdjacentHTML(\"beforeend\", \"x\");"],
|
||||
["document.body.setHTMLUnsafe(\"x\");"],
|
||||
["document.write(\"x\");"],
|
||||
["export const config = { USE_PROFILES: { html: true } };"],
|
||||
["export const f = (x: string) => h(\"div\", { innerHTML: x });"],
|
||||
["export const f = (x: string) => ({ \"innerHTML\": `<b>${x}</b>` });"],
|
||||
["export const f = (x: string) => new DOMParser().parseFromString(x, \"text/html\");"],
|
||||
["export const load = () => import(\"dompurify\");"],
|
||||
["export const load = () => import(\"marked/lib/marked.esm.js\");"],
|
||||
])("flags raw HTML sink: %s", async (code) => {
|
||||
expect(await securityErrors(`${code}\n`, SCRIPT)).toEqual(["no-restricted-syntax"]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["export const script = { innerHTML: \"console.log(1)\" };"],
|
||||
["export const script = { innerHTML: `console.log(1)` };"],
|
||||
])("allows a constant innerHTML prop: %s", async (code) => {
|
||||
expect(await securityErrors(`${code}\n`, SCRIPT)).toEqual([]);
|
||||
});
|
||||
|
||||
test.each(["dompurify", "isomorphic-dompurify", "marked"])("restricts importing %s to lib/sanitize", async (pkg) => {
|
||||
const code = `import x from "${pkg}";\n\nexport default x;\n`;
|
||||
expect(await securityErrors(code, SCRIPT)).toEqual(["no-restricted-imports"]);
|
||||
expect(await securityErrors(code, "app/lib/sanitize/foo.ts")).toEqual([]);
|
||||
});
|
||||
|
||||
test.each(["dompurify/dist/purify.es.mjs", "marked/lib/marked.esm.js"])("restricts importing subpath %s to lib/sanitize", async (specifier) => {
|
||||
const code = `import x from "${specifier}";\n\nexport default x;\n`;
|
||||
expect(await securityErrors(code, SCRIPT)).toEqual(["no-restricted-imports"]);
|
||||
expect(await securityErrors(code, "app/lib/sanitize/foo.ts")).toEqual([]);
|
||||
});
|
||||
|
||||
test("allows a package that only shares a sanitizer's name prefix", async () => {
|
||||
const code = "export const load = () => import(\"marked-highlight\");\n";
|
||||
expect(await securityErrors(code, SCRIPT)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inline eslint comments can't hide raw HTML rules", () => {
|
||||
test.each([
|
||||
["next-line disable", "<div>\n <!-- eslint-disable-next-line vue/no-v-html -->\n <div v-html=\"x\" />\n </div>"],
|
||||
["file-wide disable", "<!-- eslint-disable -->\n <div v-html=\"x\" />"],
|
||||
["rule config comment", "<!-- eslint vue/no-v-html: \"off\" -->\n <div v-html=\"x\" />"],
|
||||
])("template %s", async (_name, template) => {
|
||||
expect(await securityErrors(vue(template), COMPONENT)).toEqual(["vue/no-v-html"]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["/* eslint-disable */"],
|
||||
["// eslint-disable-next-line no-restricted-syntax -- trust me"],
|
||||
["/* eslint no-restricted-syntax: 0 */"],
|
||||
])("script %s", async (comment) => {
|
||||
expect(await securityErrors(`${comment}\ndocument.body.innerHTML = "x";\n`, SCRIPT)).toEqual(["no-restricted-syntax"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import { ESLint } from "eslint";
|
||||
|
||||
// Rules that keep raw HTML out of the DOM. Every past HTML-injection bug in the frontend sat behind
|
||||
// an inline `eslint-disable vue/no-v-html`, so these may only be relaxed by file in eslint.config.mjs.
|
||||
export const PROTECTED_RULES = new Set([
|
||||
"vue/no-v-html",
|
||||
"vue/no-restricted-v-bind",
|
||||
"vue/no-restricted-syntax",
|
||||
"no-restricted-imports",
|
||||
"no-restricted-syntax",
|
||||
]);
|
||||
|
||||
/**
|
||||
* An ESLint instance that runs only the protected rules and ignores every inline config comment
|
||||
* (`eslint-disable*`, `/* eslint rule: off *\/`, ...), so no comment can hide a violation.
|
||||
*/
|
||||
export function createSecurityLinter(cwd) {
|
||||
return new ESLint({
|
||||
cwd,
|
||||
overrideConfig: { linterOptions: { noInlineConfig: true, reportUnusedDisableDirectives: "off" } },
|
||||
ruleFilter: ({ ruleId }) => PROTECTED_RULES.has(ruleId),
|
||||
});
|
||||
}
|
||||
+101
-22
@@ -2,27 +2,106 @@
|
||||
import stylistic from "@stylistic/eslint-plugin";
|
||||
import withNuxt from "./.nuxt/eslint.config.mjs";
|
||||
|
||||
export default withNuxt({
|
||||
plugins: {
|
||||
"@stylistic": stylistic,
|
||||
const USE_SAFE_COMPONENTS = "Render HTML with <SafeMarkdown> (markdown) or <SafeInlineHtml> (inline text).";
|
||||
|
||||
// Properties and calls that parse a string as HTML.
|
||||
const HTML_PROPS = "/^(innerHTML|outerHTML|srcdoc)$/";
|
||||
const HTML_CALLS = "/^(insertAdjacentHTML|createContextualFragment|setHTMLUnsafe|parseHTMLUnsafe)$/";
|
||||
|
||||
const SANITIZER_PACKAGES = ["dompurify", "isomorphic-dompurify", "marked"];
|
||||
// A sanitizer package or any of its subpaths, but not packages like marked-highlight.
|
||||
const SANITIZER_SPECIFIER = `/^(${SANITIZER_PACKAGES.join("|")})($|[^\\w-])/`;
|
||||
|
||||
// Raw-HTML sinks, checked in scripts and (via vue/no-restricted-syntax) in template expressions.
|
||||
// Rendering goes through the two Safe components, which sanitize with ~/lib/sanitize.
|
||||
// `pnpm lint:security` enforces these even behind inline eslint comments (see eslint-rules/).
|
||||
const RAW_HTML_SYNTAX = [
|
||||
{
|
||||
// .name covers `el.innerHTML`, .value covers `el["innerHTML"]`.
|
||||
selector: `AssignmentExpression:matches([left.property.name=${HTML_PROPS}], [left.property.value=${HTML_PROPS}])`,
|
||||
message: `Don't assign innerHTML/outerHTML/srcdoc. ${USE_SAFE_COMPONENTS}`,
|
||||
},
|
||||
rules: {
|
||||
"@stylistic/max-statements-per-line": "off",
|
||||
"@stylistic/no-tabs": ["error"],
|
||||
"@stylistic/no-mixed-spaces-and-tabs": ["error", "smart-tabs"],
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"import/no-extraneous-dependencies": ["error"],
|
||||
"vue/first-attribute-linebreak": "error",
|
||||
"vue/html-closing-bracket-newline": "error",
|
||||
"vue/max-attributes-per-line": [
|
||||
"error",
|
||||
{
|
||||
singleline: 5,
|
||||
multiline: 1,
|
||||
},
|
||||
],
|
||||
"vue/no-mutating-props": "error",
|
||||
"vue/no-v-html": "error",
|
||||
"vue/component-api-style": ["error", ["script-setup"]],
|
||||
{
|
||||
// Catches render-function props and template `v-bind="{ innerHTML: x }"`. Constant strings
|
||||
// (e.g. the inline head script in nuxt.config.ts) can't carry user input.
|
||||
selector: `Property:matches([key.name=${HTML_PROPS}], [key.value=${HTML_PROPS}])`
|
||||
+ ":not([value.type='Literal'])"
|
||||
+ ":not([value.type='TemplateLiteral'][value.expressions.length=0])",
|
||||
message: `Don't pass a computed innerHTML/outerHTML/srcdoc prop. ${USE_SAFE_COMPONENTS}`,
|
||||
},
|
||||
});
|
||||
{
|
||||
selector: `CallExpression:matches([callee.property.name=${HTML_CALLS}], [callee.name=${HTML_CALLS}])`,
|
||||
message: `Don't parse HTML strings into the DOM. ${USE_SAFE_COMPONENTS}`,
|
||||
},
|
||||
{
|
||||
selector: "CallExpression[callee.object.name='document'][callee.property.name=/^(write|writeln)$/]",
|
||||
message: `Don't use document.write. ${USE_SAFE_COMPONENTS}`,
|
||||
},
|
||||
{
|
||||
selector: "NewExpression[callee.name='DOMParser']",
|
||||
message: `Don't parse HTML strings with DOMParser. ${USE_SAFE_COMPONENTS}`,
|
||||
},
|
||||
{
|
||||
// no-restricted-imports only sees static imports.
|
||||
selector: `ImportExpression[source.value=${SANITIZER_SPECIFIER}]`,
|
||||
message: `Import from ~/lib/sanitize instead. ${USE_SAFE_COMPONENTS}`,
|
||||
},
|
||||
{
|
||||
// DOMPurify replaces ALLOWED_TAGS with the full profile when USE_PROFILES is set.
|
||||
selector: "Property:matches([key.name='USE_PROFILES'], [key.value='USE_PROFILES'])",
|
||||
message: "Don't use DOMPurify USE_PROFILES: it overrides ALLOWED_TAGS. Use ~/lib/sanitize.",
|
||||
},
|
||||
];
|
||||
|
||||
const SANITIZER_IMPORTS = {
|
||||
paths: SANITIZER_PACKAGES.map(name => ({
|
||||
name,
|
||||
message: `Import from ~/lib/sanitize instead. ${USE_SAFE_COMPONENTS}`,
|
||||
})),
|
||||
patterns: [{
|
||||
group: SANITIZER_PACKAGES.map(name => `${name}/*`),
|
||||
message: `Import from ~/lib/sanitize instead. ${USE_SAFE_COMPONENTS}`,
|
||||
}],
|
||||
};
|
||||
|
||||
export default withNuxt(
|
||||
{
|
||||
plugins: {
|
||||
"@stylistic": stylistic,
|
||||
},
|
||||
rules: {
|
||||
"@stylistic/max-statements-per-line": "off",
|
||||
"@stylistic/no-tabs": ["error"],
|
||||
"@stylistic/no-mixed-spaces-and-tabs": ["error", "smart-tabs"],
|
||||
"@typescript-eslint/no-explicit-any": "off",
|
||||
"import/no-extraneous-dependencies": ["error"],
|
||||
"vue/first-attribute-linebreak": "error",
|
||||
"vue/html-closing-bracket-newline": "error",
|
||||
"vue/max-attributes-per-line": [
|
||||
"error",
|
||||
{
|
||||
singleline: 5,
|
||||
multiline: 1,
|
||||
},
|
||||
],
|
||||
"vue/no-mutating-props": "error",
|
||||
"vue/no-v-html": "error",
|
||||
"vue/no-restricted-v-bind": ["error", {
|
||||
argument: `${HTML_PROPS}i`,
|
||||
message: USE_SAFE_COMPONENTS,
|
||||
}],
|
||||
"vue/component-api-style": ["error", ["script-setup"]],
|
||||
"no-restricted-syntax": ["error", ...RAW_HTML_SYNTAX],
|
||||
"vue/no-restricted-syntax": ["error", ...RAW_HTML_SYNTAX],
|
||||
"no-restricted-imports": ["error", SANITIZER_IMPORTS],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ["app/lib/sanitize/**"],
|
||||
rules: { "no-restricted-imports": "off" },
|
||||
},
|
||||
{
|
||||
files: ["app/components/global/SafeMarkdown.vue", "app/components/global/SafeInlineHtml.vue"],
|
||||
rules: { "vue/no-v-html": "off" },
|
||||
},
|
||||
);
|
||||
@@ -8,7 +8,8 @@
|
||||
"start": "nuxt start",
|
||||
"generate": "nuxt generate --spa",
|
||||
"lint:js": "eslint .",
|
||||
"lint": "pnpm lint:js",
|
||||
"lint:security": "node eslint-rules/check-security-rules.mjs",
|
||||
"lint": "pnpm lint:security && pnpm lint:js",
|
||||
"lint:log": "pnpm lint:js --debug",
|
||||
"test": "vitest",
|
||||
"test:ci": "vitest --watch=false",
|
||||
@@ -30,7 +31,6 @@
|
||||
"date-fns": "^4.1.0",
|
||||
"dompurify": "^3.4.7",
|
||||
"fuse.js": "^7.1.0",
|
||||
"isomorphic-dompurify": "^3.4.0",
|
||||
"json-editor-vue": "^0.18.1",
|
||||
"marked": "^15.0.12",
|
||||
"nuxt": "^4.4.6",
|
||||
@@ -58,6 +58,7 @@
|
||||
"eslint-plugin-format": "^1.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.3",
|
||||
"eslint-plugin-vue": "^10.10.0",
|
||||
"jsdom": "^29.1.1",
|
||||
"lint-staged": "^15.4.3",
|
||||
"prettier": "^3.5.2",
|
||||
"sass-embedded": "^1.85.1",
|
||||
|
||||
Generated
+3
-15
@@ -196,9 +196,6 @@ importers:
|
||||
fuse.js:
|
||||
specifier: ^7.1.0
|
||||
version: 7.5.0
|
||||
isomorphic-dompurify:
|
||||
specifier: ^3.4.0
|
||||
version: 3.19.0
|
||||
json-editor-vue:
|
||||
specifier: ^0.18.1
|
||||
version: 0.18.1(@typescript-eslint/types@8.72.1)(vue@3.5.45(typescript@5.9.3))
|
||||
@@ -275,6 +272,9 @@ importers:
|
||||
eslint-plugin-vue:
|
||||
specifier: ^10.10.0
|
||||
version: 10.12.0(@stylistic/eslint-plugin@5.10.0(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2)))(@typescript-eslint/parser@8.72.1(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2)(typescript@5.9.3))(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(vue-eslint-parser@10.4.2(eslint@10.14.0(jiti@2.7.0)(supports-color@10.2.2))(supports-color@10.2.2))
|
||||
jsdom:
|
||||
specifier: ^29.1.1
|
||||
version: 29.1.1
|
||||
lint-staged:
|
||||
specifier: ^15.4.3
|
||||
version: 15.5.2(supports-color@10.2.2)
|
||||
@@ -4770,10 +4770,6 @@ packages:
|
||||
resolution: {integrity: sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
isomorphic-dompurify@3.19.0:
|
||||
resolution: {integrity: sha512-ynZ/6cVv4Trpt1FEd5TkHsHtLs+y/YQGb+ocIIVRdc+DkiYRbxlEL/IiSeSeQXwopQcG5FhoeIUJa1l26IgSpw==}
|
||||
engines: {node: ^20.19.0 || ^22.13.0 || >=24.0.0}
|
||||
|
||||
istanbul-lib-coverage@3.2.2:
|
||||
resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}
|
||||
engines: {node: '>=8'}
|
||||
@@ -11875,14 +11871,6 @@ snapshots:
|
||||
|
||||
isexe@4.0.0: {}
|
||||
|
||||
isomorphic-dompurify@3.19.0:
|
||||
dependencies:
|
||||
dompurify: 3.4.17
|
||||
jsdom: 29.1.1
|
||||
transitivePeerDependencies:
|
||||
- '@noble/hashes'
|
||||
- canvas
|
||||
|
||||
istanbul-lib-coverage@3.2.2: {}
|
||||
|
||||
istanbul-lib-report@3.0.1:
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import html
|
||||
import json
|
||||
import pathlib
|
||||
from dataclasses import dataclass
|
||||
@@ -27,10 +26,7 @@ from mealie.schema.user.user import PrivateUser
|
||||
class MetaTag:
|
||||
hid: str
|
||||
property_name: str
|
||||
content: str
|
||||
|
||||
def __post_init__(self):
|
||||
self.content = escape(self.content) # escape HTML to prevent XSS attacks
|
||||
content: str # raw text; BeautifulSoup escapes attribute values when it serializes
|
||||
|
||||
|
||||
class SPAStaticFiles(StaticFiles):
|
||||
@@ -73,15 +69,17 @@ __app_settings = get_app_settings()
|
||||
__contents = ""
|
||||
|
||||
|
||||
def escape(content: Any) -> Any:
|
||||
if isinstance(content, str):
|
||||
return html.escape(content)
|
||||
elif isinstance(content, list | tuple | set):
|
||||
return [escape(item) for item in content]
|
||||
elif isinstance(content, dict):
|
||||
return {escape(k): escape(v) for k, v in content.items()}
|
||||
else:
|
||||
return content
|
||||
_SCRIPT_JSON_ESCAPES = {ord("<"): "\\u003c", ord(">"): "\\u003e", ord("&"): "\\u0026"}
|
||||
|
||||
|
||||
def script_safe_json(data: Any) -> str:
|
||||
"""
|
||||
Serializes `data` as JSON that is safe to place inside a <script> element.
|
||||
|
||||
Escaping `<`, `>` and `&` as JSON unicode escapes means no value can close the element with
|
||||
`</script>` or open a comment, and JSON parsers still read back the original text.
|
||||
"""
|
||||
return json.dumps(jsonable_encoder(data)).translate(_SCRIPT_JSON_ESCAPES)
|
||||
|
||||
|
||||
def inject_meta(contents: str, tags: list[MetaTag]) -> str:
|
||||
@@ -138,7 +136,7 @@ def iso_duration(seconds: int | None) -> str | None:
|
||||
|
||||
|
||||
def inject_recipe_json(contents: str, schema: dict) -> str:
|
||||
schema_as_html_tag = f"""<script type="application/ld+json">{json.dumps(jsonable_encoder(schema))}</script>"""
|
||||
schema_as_html_tag = f"""<script type="application/ld+json">{script_safe_json(schema)}</script>"""
|
||||
return contents.replace("</head>", schema_as_html_tag + "\n</head>", 1)
|
||||
|
||||
|
||||
@@ -146,7 +144,9 @@ def content_with_meta(group_slug: str, recipe: RecipeOut) -> str:
|
||||
# Inject meta tags
|
||||
recipe_url = f"{__app_settings.BASE_URL}/g/{group_slug}/r/{recipe.slug}"
|
||||
if recipe.image:
|
||||
image_url = f"{__app_settings.BASE_URL}/api/media/recipes/{recipe.id}/images/original.webp?version={escape(recipe.image)}"
|
||||
image_url = (
|
||||
f"{__app_settings.BASE_URL}/api/media/recipes/{recipe.id}/images/original.webp?version={recipe.image}"
|
||||
)
|
||||
else:
|
||||
image_url = "https://raw.githubusercontent.com/mealie-recipes/mealie/9571816ac4eed5beacfc0abf6c03eff1427fd0eb/frontend/static/icons/android-chrome-512x512.png"
|
||||
|
||||
@@ -165,30 +165,25 @@ def content_with_meta(group_slug: str, recipe: RecipeOut) -> str:
|
||||
if ing.note:
|
||||
s = f"{s}, {ing.note}" if s else ing.note
|
||||
|
||||
ingredients.append(escape(s))
|
||||
ingredients.append(s)
|
||||
|
||||
nutrition: dict[str, str | None] = recipe.nutrition.model_dump(by_alias=True) if recipe.nutrition else {}
|
||||
for k, v in nutrition.items():
|
||||
if v:
|
||||
nutrition[k] = escape(v)
|
||||
|
||||
as_schema_org: dict[str, Any] = {
|
||||
"@context": "https://schema.org",
|
||||
"@type": "Recipe",
|
||||
"name": escape(recipe.name),
|
||||
"description": escape(recipe.description),
|
||||
"name": recipe.name,
|
||||
"description": recipe.description,
|
||||
"image": [image_url],
|
||||
"datePublished": recipe.created_at,
|
||||
"prepTime": iso_duration(recipe.prep_time_seconds),
|
||||
"cookTime": iso_duration(recipe.perform_time_seconds),
|
||||
"totalTime": iso_duration(recipe.total_time_seconds),
|
||||
"recipeYield": escape(recipe.recipe_yield_display),
|
||||
"recipeYield": recipe.recipe_yield_display,
|
||||
"recipeIngredient": ingredients,
|
||||
"recipeInstructions": [escape(i.text) for i in recipe.recipe_instructions]
|
||||
if recipe.recipe_instructions
|
||||
else [],
|
||||
"recipeCategory": [escape(c.name) for c in recipe.recipe_category] if recipe.recipe_category else [],
|
||||
"keywords": [escape(t.name) for t in recipe.tags] if recipe.tags else [],
|
||||
"recipeInstructions": [i.text for i in recipe.recipe_instructions] if recipe.recipe_instructions else [],
|
||||
"recipeCategory": [c.name for c in recipe.recipe_category] if recipe.recipe_category else [],
|
||||
"keywords": [t.name for t in recipe.tags] if recipe.tags else [],
|
||||
"nutrition": nutrition,
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ class EmailTemplate(BaseModel):
|
||||
button_text: str
|
||||
|
||||
def render_html(self, template: Path) -> str:
|
||||
tmpl = Template(template.read_text())
|
||||
tmpl = Template(template.read_text(), autoescape=True)
|
||||
|
||||
return tmpl.render(data=self.model_dump())
|
||||
|
||||
|
||||
@@ -117,9 +117,10 @@ description = "Type check Python code"
|
||||
run = "uv run mypy mealie"
|
||||
|
||||
[tasks."py:semgrep"]
|
||||
description = "Run the authz semgrep rules in .semgrep and their tests"
|
||||
description = "Run the authz and XSS semgrep rules in .semgrep and their tests"
|
||||
run = [
|
||||
"semgrep scan --test --metrics off --config .semgrep/authz.yml .semgrep/authz.py",
|
||||
"semgrep scan --test --metrics off --config .semgrep/xss.yml .semgrep/xss.py",
|
||||
"semgrep scan --error --metrics off --config .semgrep mealie",
|
||||
]
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"main": "index.js",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@playwright/test": "^1.60.0",
|
||||
"@playwright/test": "^1.64.1",
|
||||
"@types/node": "^24.12.4"
|
||||
},
|
||||
"scripts": {},
|
||||
|
||||
Generated
+16
-26
@@ -9,35 +9,30 @@ importers:
|
||||
.:
|
||||
devDependencies:
|
||||
'@playwright/test':
|
||||
specifier: ^1.60.0
|
||||
version: 1.60.0
|
||||
specifier: ^1.64.1
|
||||
version: 1.64.1
|
||||
'@types/node':
|
||||
specifier: ^24.12.4
|
||||
version: 24.12.4
|
||||
|
||||
packages:
|
||||
|
||||
'@playwright/test@1.60.0':
|
||||
resolution: {integrity: sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==}
|
||||
engines: {node: '>=18'}
|
||||
'@playwright/test@1.64.1':
|
||||
resolution: {integrity: sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
'@types/node@24.12.4':
|
||||
resolution: {integrity: sha512-GUUEShf+PBCGW2KaXwcIt3Yk+e3pkKwWKb9GSyM9WQVE+ep2jzmHdGsHzu4wgcZy5fN9FBdVzjpBQsYlpfpgLA==}
|
||||
|
||||
fsevents@2.3.2:
|
||||
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
|
||||
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
|
||||
os: [darwin]
|
||||
|
||||
playwright-core@1.60.0:
|
||||
resolution: {integrity: sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==}
|
||||
engines: {node: '>=18'}
|
||||
playwright-core@1.64.1:
|
||||
resolution: {integrity: sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
playwright@1.60.0:
|
||||
resolution: {integrity: sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==}
|
||||
engines: {node: '>=18'}
|
||||
playwright@1.64.1:
|
||||
resolution: {integrity: sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
undici-types@7.16.0:
|
||||
@@ -45,23 +40,18 @@ packages:
|
||||
|
||||
snapshots:
|
||||
|
||||
'@playwright/test@1.60.0':
|
||||
'@playwright/test@1.64.1':
|
||||
dependencies:
|
||||
playwright: 1.60.0
|
||||
playwright: 1.64.1
|
||||
|
||||
'@types/node@24.12.4':
|
||||
dependencies:
|
||||
undici-types: 7.16.0
|
||||
|
||||
fsevents@2.3.2:
|
||||
optional: true
|
||||
playwright-core@1.64.1: {}
|
||||
|
||||
playwright-core@1.60.0: {}
|
||||
|
||||
playwright@1.60.0:
|
||||
playwright@1.64.1:
|
||||
dependencies:
|
||||
playwright-core: 1.60.0
|
||||
optionalDependencies:
|
||||
fsevents: 2.3.2
|
||||
playwright-core: 1.64.1
|
||||
|
||||
undici-types@7.16.0: {}
|
||||
@@ -294,15 +294,18 @@ async def test_spa_service_shared_recipe_with_meta_invalid_data(unique_user: Tes
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"malicious_content, malicious_strings",
|
||||
"malicious_content",
|
||||
[
|
||||
("<script>alert('XSS');</script>", ["<script>", "alert('XSS')"]),
|
||||
("<img src=x onerror=alert('XSS')>", ["<img", "onerror=alert('XSS')"]),
|
||||
("<div onmouseover=alert('XSS')>Hover me</div>", ["<div", "onmouseover=alert('XSS')"]),
|
||||
("<a href='javascript:alert(\"XSS\")'>Click me</a>", ["<a", 'javascript:alert("XSS")']),
|
||||
"<script>alert('XSS');</script>",
|
||||
"</script><script>alert('XSS')</script>",
|
||||
"<img src=x onerror=alert('XSS')>",
|
||||
"<div onmouseover=alert('XSS')>Hover me</div>",
|
||||
"<a href='javascript:alert(\"XSS\")'>Click me</a>",
|
||||
"\" onload=\"alert('XSS')",
|
||||
"<!-- Mac & Cheese -->",
|
||||
],
|
||||
)
|
||||
def test_spa_escapes_malicious_recipe_data(unique_user: TestUser, malicious_content: str, malicious_strings: list[str]):
|
||||
def test_spa_escapes_malicious_recipe_data(unique_user: TestUser, malicious_content: str):
|
||||
recipe = build_recipe(
|
||||
user_id=unique_user.user_id,
|
||||
group_id=unique_user.group_id,
|
||||
@@ -313,6 +316,19 @@ def test_spa_escapes_malicious_recipe_data(unique_user: TestUser, malicious_cont
|
||||
settings=RecipeSettings(),
|
||||
)
|
||||
|
||||
response = spa.content_with_meta(unique_user.group_id, recipe)
|
||||
for string in malicious_strings:
|
||||
assert string not in response
|
||||
soup = BeautifulSoup(spa.content_with_meta(unique_user.group_id, recipe), "html.parser")
|
||||
|
||||
# The payload must stay text: no new elements, no event-handler attributes, one script (the JSON-LD).
|
||||
assert {tag.name for tag in soup.find_all(True)} <= {"html", "head", "body", "meta", "script"}
|
||||
assert not [attr for tag in soup.find_all(True) for attr in tag.attrs if attr.lower().startswith("on")]
|
||||
scripts = soup.find_all("script")
|
||||
assert len(scripts) == 1
|
||||
assert scripts[0].get("type") == "application/ld+json"
|
||||
|
||||
# ...and it must round-trip unchanged, not double-escaped.
|
||||
schema = json.loads(scripts[0].text)
|
||||
assert schema["name"] == malicious_content
|
||||
assert schema["description"] == malicious_content
|
||||
og_title = soup.find("meta", attrs={"property": "og:title"})
|
||||
assert og_title is not None
|
||||
assert og_title["content"] == malicious_content
|
||||
@@ -0,0 +1,19 @@
|
||||
from mealie.services.email.email_service import EmailService, EmailTemplate
|
||||
|
||||
|
||||
def test_email_template_escapes_values():
|
||||
template = EmailTemplate(
|
||||
subject="subject",
|
||||
header_text="<b>header</b>",
|
||||
message_top="<img src=x onerror=alert(1)>",
|
||||
message_bottom="bottom",
|
||||
button_link='https://example.com/reset?token=a&next="x"',
|
||||
button_text="Reset",
|
||||
)
|
||||
|
||||
html = template.render_html(EmailService().default_template)
|
||||
|
||||
assert "<b>header</b>" not in html
|
||||
assert "<b>header</b>" in html
|
||||
assert "<img src=x" not in html
|
||||
assert 'href="https://example.com/reset?token=a&next="x""' in html
|
||||
Reference in new issue
Block a user