fix(custom-widgets): harden v2 authoring

This commit is contained in:
Thomas Camlong committed 2026-07-20 22:16:18 +02:00
1 parent ee832ad3c6
commit 7c66c912e7
171 files changed
+20311 -50527

No files matched your search

+197 -157
View File
@@ -1,21 +1,21 @@
import { Parser } from "acorn";
import jsx from "acorn-jsx";
import {
customJsxBindableComponentNames,
customJsxComponentByName,
customJsxSupportedPropsByName,
enabledCustomJsxComponents,
} from "../core/component-registry";
import {
CUSTOM_JSX_BLOCKED_PROPERTIES,
CUSTOM_JSX_LIMITS,
CUSTOM_JSX_URL_PROPS,
isBlockedCustomJsxProp,
isBlockedCustomJsxLexicalBinding,
normalizeCustomJsxProperty,
} from "./policy";
import type { AstNode } from "./analyzer-ast";
import { containsEscapingCallback, nodeOf, nodesOf, staticPropertyName } from "./analyzer-ast";
import { nodeOf, nodesOf, staticPropertyName } from "./analyzer-ast";
import { analyzeCustomJsxElement } from "./analyzer-jsx";
import { isStaticallyCallableBinding, RESERVED_LOCAL_BINDINGS, ROOT_BINDINGS } from "./analyzer-language";
import {
CUSTOM_JSX_BINARY_OPERATORS,
CUSTOM_JSX_CALLBACK_METHODS,
CUSTOM_JSX_SAFE_VALUE_METHODS,
} from "./safe-language-policy";
export interface CustomJsxTemplateDiagnostic {
severity: "error" | "warning";
@@ -26,66 +26,6 @@ export interface CustomJsxTemplateDiagnostic {
}
const JsxParser = Parser.extend(jsx());
const enabledComponentNames = enabledCustomJsxComponents.map((component) => component.name);
function closestComponentName(value: string): string | undefined {
let closest: { name: string; distance: number } | undefined;
for (const name of enabledComponentNames) {
const distance = editDistance(value.toLowerCase(), name.toLowerCase());
if (!closest || distance < closest.distance) closest = { name, distance };
}
return closest && closest.distance <= Math.max(2, Math.floor(value.length / 3)) ? closest.name : undefined;
}
function editDistance(left: string, right: string): number {
const previous = Array.from({ length: right.length + 1 }, (_, index) => index);
for (let leftIndex = 1; leftIndex <= left.length; leftIndex += 1) {
const current = [leftIndex];
for (let rightIndex = 1; rightIndex <= right.length; rightIndex += 1) {
current[rightIndex] = Math.min(
(current[rightIndex - 1] ?? 0) + 1,
(previous[rightIndex] ?? 0) + 1,
(previous[rightIndex - 1] ?? 0) + (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),
);
}
previous.splice(0, previous.length, ...current);
}
return previous[right.length] ?? Math.max(left.length, right.length);
}
const rootBindings = new Set([
"Array",
"Boolean",
"Date",
"Infinity",
"JSON",
"Math",
"NaN",
"Number",
"Object",
"String",
"data",
"options",
"inputs",
"status",
"decodeURIComponent",
"encodeURIComponent",
"isFinite",
"isNaN",
"parseFloat",
"parseInt",
"undefined",
]);
function tagName(node: AstNode): string | null {
if (node.type === "JSXIdentifier") return String(node.name ?? "");
if (node.type !== "JSXMemberExpression") return null;
const object = nodeOf(node.object);
const property = nodeOf(node.property);
const left = object ? tagName(object) : null;
const right = property ? tagName(property) : null;
return left && right ? `${left}.${right}` : null;
}
export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDiagnostic[] {
const diagnostics: CustomJsxTemplateDiagnostic[] = [];
@@ -112,7 +52,116 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
return depth <= CUSTOM_JSX_LIMITS.astDepth && operations <= CUSTOM_JSX_LIMITS.operations;
};
const visit = (node: AstNode, depth: number, bindings: ReadonlySet<string>): void => {
let visit: (node: AstNode, depth: number, bindings: ReadonlySet<string>) => void;
const visitArrow = (node: AstNode, depth: number, bindings: ReadonlySet<string>) => {
if (node.async || node.generator) {
add(node, "CALLBACK_VALUE_NOT_ALLOWED: Async and generator callbacks are not supported");
return;
}
const callbackBindings = new Set(bindings);
const parameterNames = new Set<string>();
for (const parameter of nodesOf(node.params)) {
if (parameter.type !== "Identifier") {
add(parameter, "INVALID_LOCAL_DECLARATION: Callback parameters must be identifiers");
continue;
}
const name = String(parameter.name);
if (isBlockedCustomJsxLexicalBinding(name)) {
add(parameter, `INVALID_LOCAL_DECLARATION: '${name}' is not a safe callback parameter name`);
continue;
}
if (RESERVED_LOCAL_BINDINGS.has(name)) {
add(parameter, `RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
continue;
}
if (parameterNames.has(name)) {
add(parameter, `DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
continue;
}
parameterNames.add(name);
callbackBindings.add(name);
}
const body = nodeOf(node.body);
if (!body) return;
if (body.type === "BlockStatement") visitSafeBlock(body, depth + 1, callbackBindings);
else visit(body, depth + 1, callbackBindings);
};
const visitSafeBlock = (block: AstNode, depth: number, bindings: ReadonlySet<string>) => {
if (!checkBudget(block, depth)) return;
const statements = nodesOf(block.body);
const finalStatement = statements.at(-1);
if (statements.length === 0 || finalStatement?.type !== "ReturnStatement" || !nodeOf(finalStatement.argument)) {
add(block, "BLOCK_REQUIRES_FINAL_RETURN: A safe block must end with exactly one value-returning return");
}
if (statements.length < 2) {
add(block, "INVALID_LOCAL_DECLARATION: A safe block requires at least one const before its final return");
}
let scopedBindings = new Set(bindings);
const localNames = new Set<string>();
statements.forEach((statement, statementIndex) => {
if (!checkBudget(statement, depth + 1)) return;
const isFinal = statementIndex === statements.length - 1;
if (statement.type === "ReturnStatement") {
if (!isFinal) {
add(statement, "BLOCK_REQUIRES_FINAL_RETURN: Return is only allowed as the final statement");
return;
}
const argument = nodeOf(statement.argument);
if (argument) visit(argument, depth + 1, scopedBindings);
return;
}
if (statement.type !== "VariableDeclaration") {
add(statement, `UNSUPPORTED_BLOCK_STATEMENT: '${statement.type}' is not allowed in a safe block`);
return;
}
if (statement.kind !== "const") {
add(statement, "INVALID_LOCAL_DECLARATION: Only immutable const declarations are allowed");
return;
}
for (const declaration of nodesOf(statement.declarations)) {
if (!checkBudget(declaration, depth + 2)) continue;
const identifier = nodeOf(declaration.id);
if (declaration.type !== "VariableDeclarator" || identifier?.type !== "Identifier") {
add(declaration, "INVALID_LOCAL_DECLARATION: Local declarations require a simple identifier");
continue;
}
const name = String(identifier.name);
if (isBlockedCustomJsxLexicalBinding(name)) {
add(identifier, `INVALID_LOCAL_DECLARATION: '${name}' is not a safe local binding name`);
continue;
}
if (RESERVED_LOCAL_BINDINGS.has(name)) {
add(identifier, `RESERVED_LOCAL_BINDING: '${name}' cannot be shadowed`);
continue;
}
if (localNames.has(name)) {
add(identifier, `DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
continue;
}
const initializer = nodeOf(declaration.init);
if (!initializer) {
add(declaration, `LOCAL_BINDING_REQUIRES_INITIALIZER: '${name}' requires an initializer`);
continue;
}
if (
initializer.type === "ArrowFunctionExpression" ||
initializer.type === "FunctionExpression" ||
isStaticallyCallableBinding(initializer)
) {
add(initializer, "CALLBACK_VALUE_NOT_ALLOWED: Functions cannot be stored in local bindings");
continue;
}
visit(initializer, depth + 1, scopedBindings);
localNames.add(name);
scopedBindings = new Set(scopedBindings).add(name);
}
});
};
visit = (node: AstNode, depth: number, bindings: ReadonlySet<string>): void => {
if (!checkBudget(node, depth)) return;
switch (node.type) {
@@ -128,67 +177,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
nodesOf(node.children).forEach((child) => visit(child, depth + 1, bindings));
return;
case "JSXElement": {
const opening = nodeOf(node.openingElement);
if (!opening) {
add(node, "Invalid JSX element");
return;
}
const nameNode = nodeOf(opening.name);
const name = nameNode ? tagName(nameNode) : null;
const descriptor = name ? customJsxComponentByName.get(name) : undefined;
if (descriptor?.safety === "denied") {
add(
opening,
`BLOCKED_CAPABILITY: '${name}' is not available${descriptor.reason ? ` because it ${descriptor.reason.toLowerCase()}` : ""}`,
);
} else if (!descriptor) {
const suggestion = name ? closestComponentName(name) : undefined;
add(
opening,
name
? `UNKNOWN_COMPONENT: '${name}' is not available${suggestion ? `. Did you mean '${suggestion}'?` : ""}`
: "UNKNOWN_COMPONENT: Invalid JSX component name",
);
}
for (const attribute of nodesOf(opening.attributes)) {
if (attribute.type === "JSXSpreadAttribute") {
const argument = nodeOf(attribute.argument);
if (argument) visit(argument, depth + 1, bindings);
continue;
}
if (attribute.type !== "JSXAttribute") {
add(attribute, `Unsupported JSX attribute '${attribute.type}'`);
continue;
}
const attributeNameNode = nodeOf(attribute.name);
const attributeName = attributeNameNode?.type === "JSXIdentifier" ? String(attributeNameNode.name) : "";
if (isBlockedCustomJsxProp(attributeName)) {
add(attribute, `BLOCKED_CAPABILITY: Prop '${attributeName}' is not allowed`);
} else if (name && attributeName !== "bind" && !customJsxSupportedPropsByName.get(name)?.has(attributeName)) {
add(attribute, `UNKNOWN_MANTINE_PROP: '${attributeName}' on ${name} will be passed through`, "warning");
} else if (name && attributeName === "bind" && !customJsxBindableComponentNames.has(name)) {
add(attribute, `BINDING_UNAVAILABLE: '${name}' does not have a declarative binding adapter`, "warning");
}
const value = nodeOf(attribute.value);
if (
CUSTOM_JSX_URL_PROPS.has(attributeName) &&
value?.type === "Literal" &&
typeof value.value === "string" &&
!isSafeLiteralUrl(value.value)
) {
add(attribute, `INVALID_PROP_VALUE: '${attributeName}' contains an unsafe URL`);
}
if (value?.type === "JSXExpressionContainer") {
const expression = nodeOf(value.expression);
if (expression && containsEscapingCallback(expression)) {
add(attribute, `BLOCKED_CAPABILITY: Callback prop '${attributeName}' is not allowed`);
} else if (expression && expression.type !== "JSXEmptyExpression") {
visit(expression, depth + 1, bindings);
}
}
}
nodesOf(node.children).forEach((child) => visit(child, depth + 1, bindings));
analyzeCustomJsxElement(node, depth, bindings, { add, visit, visitArrow });
return;
}
case "JSXText":
@@ -248,6 +237,9 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
return;
case "BinaryExpression":
case "LogicalExpression": {
if (node.type === "BinaryExpression" && !CUSTOM_JSX_BINARY_OPERATORS.has(String(node.operator))) {
add(node, `Binary operator '${String(node.operator)}' is not supported`);
}
const left = nodeOf(node.left);
const right = nodeOf(node.right);
if (left) visit(left, depth + 1, bindings);
@@ -275,27 +267,70 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
}
case "CallExpression": {
const callee = nodeOf(node.callee);
const arguments_ = nodesOf(node.arguments);
if (callee?.type === "ArrowFunctionExpression") {
if (nodesOf(callee.params).length > 0) {
add(callee, "CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions cannot declare parameters");
}
if (arguments_.length > 0) {
add(node, "CALLBACK_VALUE_NOT_ALLOWED: Inline derived-value functions must be called without arguments");
}
visitArrow(callee, depth + 1, bindings);
arguments_.forEach((argument) => visit(argument, depth + 1, bindings));
return;
}
if (callee) visit(callee, depth + 1, bindings);
nodesOf(node.arguments).forEach((argument) => {
const property = callee?.type === "MemberExpression" ? nodeOf(callee.property) : null;
const method = property?.type === "Identifier" ? String(property.name) : staticPropertyName(property);
if (
callee &&
!isStaticallyCallableBinding(callee) &&
(callee.type !== "MemberExpression" || !method || !CUSTOM_JSX_SAFE_VALUE_METHODS.has(method))
) {
add(callee, "CALL_TARGET_NOT_ALLOWED: Only documented safe helpers and value methods can be called");
}
if (method && CUSTOM_JSX_CALLBACK_METHODS.has(method)) {
const callback = arguments_[0];
if (!callback) {
add(node, `CALLBACK_VALUE_NOT_ALLOWED: '${method}' requires a callback`);
} else if (["reduce", "sort"].includes(method) && callback.type !== "ArrowFunctionExpression") {
add(callback, `CALLBACK_VALUE_NOT_ALLOWED: '${method}' requires an inline arrow callback`);
} else if (callback.type !== "ArrowFunctionExpression" && !isStaticallyCallableBinding(callback)) {
add(callback, `CALLBACK_VALUE_NOT_ALLOWED: '${method}' requires an inline arrow or safe helper callback`);
}
}
arguments_.forEach((argument, argumentIndex) => {
if (argument.type === "SpreadElement") add(argument, "Spread call arguments are not supported");
else visit(argument, depth + 1, bindings);
else if (
argument.type === "ArrowFunctionExpression" &&
argumentIndex === 0 &&
method &&
CUSTOM_JSX_CALLBACK_METHODS.has(method)
) {
visitArrow(argument, depth + 1, bindings);
} else if (argument.type === "ArrowFunctionExpression") {
add(argument, "CALLBACK_VALUE_NOT_ALLOWED: Callback arguments are only allowed in the first callback slot");
} else visit(argument, depth + 1, bindings);
});
return;
}
case "ArrowFunctionExpression": {
if (node.async || node.generator || node.expression === false) {
add(node, "Only synchronous expression-bodied arrow callbacks are supported");
return;
}
const callbackBindings = new Set(bindings);
for (const parameter of nodesOf(node.params)) {
if (parameter.type !== "Identifier") add(parameter, "Callback parameters must be identifiers");
else callbackBindings.add(String(parameter.name));
}
const body = nodeOf(node.body);
if (body) visit(body, depth + 1, callbackBindings);
add(
node,
"CALLBACK_VALUE_NOT_ALLOWED: Callbacks are only allowed in safe collection methods and trusted slots",
);
return;
}
case "BlockStatement":
add(node, "UNSUPPORTED_BLOCK_STATEMENT: Blocks are only allowed as safe callback or IIFE bodies");
return;
case "AssignmentExpression":
case "UpdateExpression":
case "NewExpression":
case "AwaitExpression":
case "YieldExpression":
add(node, `UNSUPPORTED_BLOCK_STATEMENT: '${node.type}' is not allowed in safe expressions`);
return;
case "TemplateLiteral":
nodesOf(node.expressions).forEach((expression) => visit(expression, depth + 1, bindings));
return;
@@ -315,27 +350,32 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
sourceType: "module",
locations: true,
}) as unknown as AstNode;
visit(program, 0, rootBindings);
visit(program, 0, ROOT_BINDINGS);
} catch (error) {
const parseError = error as Error & { pos?: number; loc?: { line?: number; column?: number } };
const parseIndex = Math.max(0, (parseError.pos ?? 2) - 2);
const missingInitializer = [...template.matchAll(/(?:\bconst|,)\s+([A-Za-z_$][\w$]*)\s*;/gu)].find((match) => {
const semicolon = (match.index ?? 0) + match[0].length - 1;
return Math.abs(semicolon - parseIndex) <= 1;
});
const duplicateCandidate = /Identifier '([^']+)' has already been declared/iu.exec(parseError.message);
const duplicateBinding = duplicateCandidate;
const message = missingInitializer
? `LOCAL_BINDING_REQUIRES_INITIALIZER: '${missingInitializer[1]}' requires an initializer`
: duplicateBinding
? `DUPLICATE_LOCAL_BINDING: '${duplicateBinding[1]}' is already declared`
: parseError.message;
diagnostics.push({
severity: "error",
message: parseError.message,
message,
index: Math.max(0, (parseError.pos ?? 2) - 2),
line: parseError.loc?.line ?? 1,
column: Math.max(1, (parseError.loc?.column ?? 2) - 1),
column: Math.max(
1,
(parseError.loc?.column ?? 0) + (parseError.loc?.line === 1 || parseError.loc?.line === undefined ? -1 : 1),
),
});
}
return diagnostics;
}
function isSafeLiteralUrl(value: string) {
if (value.startsWith("#") || (value.startsWith("/") && !value.startsWith("//"))) return true;
try {
const url = new URL(value);
return (url.protocol === "http:" || url.protocol === "https:") && !url.username && !url.password;
} catch {
return false;
}
}