feat(custom-widgets): complete JSX v2
This commit is contained in:
263 files changed
+65503
-17816
No files matched your search
@@ -0,0 +1,66 @@
|
||||
export interface AstNode {
|
||||
type: string;
|
||||
start?: number;
|
||||
loc?: { start?: { line?: number; column?: number } };
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export const nodeOf = (value: unknown): AstNode | null =>
|
||||
value !== null && typeof value === "object" && typeof (value as { type?: unknown }).type === "string"
|
||||
? (value as AstNode)
|
||||
: null;
|
||||
|
||||
export const nodesOf = (value: unknown): AstNode[] =>
|
||||
Array.isArray(value) ? value.map(nodeOf).filter((node): node is AstNode => node !== null) : [];
|
||||
|
||||
export const staticPropertyName = (node: AstNode | null): string | undefined => {
|
||||
if (!node) return undefined;
|
||||
if (node.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number")) {
|
||||
return String(node.value);
|
||||
}
|
||||
if (node.type === "BinaryExpression" && node.operator === "+") {
|
||||
const left = staticPropertyName(nodeOf(node.left));
|
||||
const right = staticPropertyName(nodeOf(node.right));
|
||||
return left === undefined || right === undefined ? undefined : left + right;
|
||||
}
|
||||
if (node.type === "TemplateLiteral" && Array.isArray(node.expressions) && node.expressions.length === 0) {
|
||||
return (node.quasis as Array<{ value?: { cooked?: unknown } }> | undefined)
|
||||
?.map((quasi) => String(quasi.value?.cooked ?? ""))
|
||||
.join("");
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const callbackCollectionMethods = new Set(["every", "filter", "find", "findIndex", "map", "reduce", "some", "sort"]);
|
||||
|
||||
export function containsEscapingCallback(node: AstNode): boolean {
|
||||
if (node.type === "ArrowFunctionExpression") return true;
|
||||
if (node.type === "CallExpression") {
|
||||
const callee = nodeOf(node.callee);
|
||||
if (callee && containsEscapingCallback(callee)) return true;
|
||||
const property = callee?.type === "MemberExpression" ? nodeOf(callee.property) : null;
|
||||
const method = property?.type === "Identifier" ? String(property.name) : staticPropertyName(property);
|
||||
return nodesOf(node.arguments).some((argument) => {
|
||||
if (argument.type !== "ArrowFunctionExpression" || !method || !callbackCollectionMethods.has(method)) {
|
||||
return containsEscapingCallback(argument);
|
||||
}
|
||||
const body = nodeOf(argument.body);
|
||||
return body ? containsEscapingCallback(body) : false;
|
||||
});
|
||||
}
|
||||
return containsEscapingCallbackChildren(node);
|
||||
}
|
||||
|
||||
function containsEscapingCallbackChildren(node: AstNode): boolean {
|
||||
return Object.entries(node).some(([key, value]) => {
|
||||
if (["loc", "start", "end", "type"].includes(key)) return false;
|
||||
if (Array.isArray(value)) {
|
||||
return value.some((entry) => {
|
||||
const child = nodeOf(entry);
|
||||
return child ? containsEscapingCallback(child) : false;
|
||||
});
|
||||
}
|
||||
const child = nodeOf(value);
|
||||
return child ? containsEscapingCallback(child) : false;
|
||||
});
|
||||
}
|
||||
@@ -1,20 +1,21 @@
|
||||
import { Parser } from "acorn";
|
||||
import jsx from "acorn-jsx";
|
||||
|
||||
import { customJsxComponentByName, customJsxSupportedPropsByName } from "../core/component-registry";
|
||||
import {
|
||||
customJsxBindableComponentNames,
|
||||
customJsxComponentByName,
|
||||
customJsxSupportedPropsByName,
|
||||
enabledCustomJsxComponents,
|
||||
} from "../core/component-registry";
|
||||
import {
|
||||
CUSTOM_JSX_BLOCKED_PROPERTIES,
|
||||
CUSTOM_JSX_BLOCKED_PROPS,
|
||||
CUSTOM_JSX_LIMITS,
|
||||
CUSTOM_JSX_URL_PROPS,
|
||||
isBlockedCustomJsxProp,
|
||||
normalizeCustomJsxProperty,
|
||||
} from "./policy";
|
||||
|
||||
interface AstNode {
|
||||
type: string;
|
||||
start?: number;
|
||||
loc?: { start?: { line?: number; column?: number } };
|
||||
[key: string]: unknown;
|
||||
}
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { containsEscapingCallback, nodeOf, nodesOf, staticPropertyName } from "./analyzer-ast";
|
||||
|
||||
export interface CustomJsxTemplateDiagnostic {
|
||||
severity: "error" | "warning";
|
||||
@@ -25,6 +26,32 @@ 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",
|
||||
@@ -38,6 +65,9 @@ const rootBindings = new Set([
|
||||
"Object",
|
||||
"String",
|
||||
"data",
|
||||
"options",
|
||||
"state",
|
||||
"status",
|
||||
"decodeURIComponent",
|
||||
"encodeURIComponent",
|
||||
"isFinite",
|
||||
@@ -47,31 +77,15 @@ const rootBindings = new Set([
|
||||
"undefined",
|
||||
]);
|
||||
|
||||
const nodeOf = (value: unknown): AstNode | null =>
|
||||
value !== null && typeof value === "object" && typeof (value as { type?: unknown }).type === "string"
|
||||
? (value as AstNode)
|
||||
: null;
|
||||
|
||||
const nodesOf = (value: unknown): AstNode[] =>
|
||||
Array.isArray(value) ? value.map(nodeOf).filter((node): node is AstNode => node !== null) : [];
|
||||
|
||||
const staticPropertyName = (node: AstNode | null): string | undefined => {
|
||||
if (!node) return undefined;
|
||||
if (node.type === "Literal" && (typeof node.value === "string" || typeof node.value === "number")) {
|
||||
return String(node.value);
|
||||
}
|
||||
if (node.type === "BinaryExpression" && node.operator === "+") {
|
||||
const left = staticPropertyName(nodeOf(node.left));
|
||||
const right = staticPropertyName(nodeOf(node.right));
|
||||
return left === undefined || right === undefined ? undefined : left + right;
|
||||
}
|
||||
if (node.type === "TemplateLiteral" && Array.isArray(node.expressions) && node.expressions.length === 0) {
|
||||
return (node.quasis as Array<{ value?: { cooked?: unknown } }> | undefined)
|
||||
?.map((quasi) => String(quasi.value?.cooked ?? ""))
|
||||
.join("");
|
||||
}
|
||||
return 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[] = [];
|
||||
@@ -98,16 +112,6 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
return depth <= CUSTOM_JSX_LIMITS.astDepth && operations <= CUSTOM_JSX_LIMITS.operations;
|
||||
};
|
||||
|
||||
const 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;
|
||||
};
|
||||
|
||||
const visit = (node: AstNode, depth: number, bindings: ReadonlySet<string>): void => {
|
||||
if (!checkBudget(node, depth)) return;
|
||||
|
||||
@@ -132,8 +136,19 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
const nameNode = nodeOf(opening.name);
|
||||
const name = nameNode ? tagName(nameNode) : null;
|
||||
const descriptor = name ? customJsxComponentByName.get(name) : undefined;
|
||||
if (!descriptor || descriptor.safety === "denied") {
|
||||
add(opening, name ? `Component '${name}' is not available` : "Invalid JSX component name");
|
||||
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)) {
|
||||
@@ -148,19 +163,29 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
}
|
||||
const attributeNameNode = nodeOf(attribute.name);
|
||||
const attributeName = attributeNameNode?.type === "JSXIdentifier" ? String(attributeNameNode.name) : "";
|
||||
const supportedProps = name ? customJsxSupportedPropsByName.get(name) : undefined;
|
||||
if (
|
||||
(/^on/i.test(attributeName) && !supportedProps?.has(attributeName)) ||
|
||||
CUSTOM_JSX_BLOCKED_PROPS.has(attributeName)
|
||||
) {
|
||||
add(attribute, `Prop '${attributeName}' is not allowed`);
|
||||
} else if (name && !supportedProps?.has(attributeName)) {
|
||||
add(attribute, `Prop '${attributeName}' is not supported by ${name} and will be ignored`, "warning");
|
||||
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 && expression.type !== "JSXEmptyExpression") visit(expression, depth + 1, bindings);
|
||||
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));
|
||||
@@ -304,3 +329,13 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createElement, Fragment } from "react";
|
||||
|
||||
import { asNode, asNodeArray, isInterpreterCallback, SafeJsxError } from "./interpreter-foundation";
|
||||
import { asNode, asNodeArray, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Budget, Environment, InterpreterCallback } from "./interpreter-foundation";
|
||||
import { normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
import { diagnoseCustomJsxProps, normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
import { CUSTOM_JSX_BLOCKED_TAGS } from "./policy";
|
||||
|
||||
export interface JsxEmitterContext {
|
||||
@@ -54,32 +54,20 @@ export function emitJsxElement(
|
||||
if (attribute.type !== "JSXAttribute") throw new SafeJsxError(`Unsupported JSX attribute: ${attribute.type}`);
|
||||
const nameNode = asNode(attribute.name, "attribute name");
|
||||
if (nameNode.type !== "JSXIdentifier") throw new SafeJsxError("Namespaced JSX attributes are not supported");
|
||||
const name = normalizedProperty(nameNode.name);
|
||||
const rawName = String(nameNode.name);
|
||||
// `bind` is a safe declarative JSX prop even though reflective `.bind` access is blocked by the interpreter.
|
||||
const name = rawName === "bind" ? rawName : normalizedProperty(rawName);
|
||||
if (attribute.value == null) rawProps[name] = true;
|
||||
else {
|
||||
const value = asNode(attribute.value, "attribute value");
|
||||
rawProps[name] = value.type === "Literal" ? value.value : context.evaluate(value, environment, depth + 1);
|
||||
}
|
||||
}
|
||||
let children = asNodeArray(node.children, "JSX children").map((child) =>
|
||||
const children = asNodeArray(node.children, "JSX children").map((child) =>
|
||||
context.evaluate(child, environment, depth + 1),
|
||||
);
|
||||
diagnoseCustomJsxProps(rawProps, tag).forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const props = sanitizeCustomJsxProps(rawProps, tag);
|
||||
if (tag === "SubFetch") {
|
||||
const callbackChildren = children.filter(isInterpreterCallback);
|
||||
const callbackProp = rawProps.render;
|
||||
if (callbackProp !== undefined && !isInterpreterCallback(callbackProp)) {
|
||||
throw new SafeJsxError("SubFetch render must be an inline arrow callback");
|
||||
}
|
||||
if (callbackChildren.length > 1 || (callbackChildren.length === 1 && callbackProp !== undefined)) {
|
||||
throw new SafeJsxError("SubFetch accepts only one render callback");
|
||||
}
|
||||
const callback = isInterpreterCallback(callbackProp) ? callbackProp : callbackChildren[0];
|
||||
if (callback) {
|
||||
props.render = (value: unknown, metadata: unknown) => context.renderCallback(callback, [value, metadata]);
|
||||
children = children.filter((child) => child !== callback);
|
||||
}
|
||||
}
|
||||
context.budget.rendered();
|
||||
return createElement(component, props as never, ...(children as ReactNode[]));
|
||||
}
|
||||
|
||||
@@ -20,18 +20,31 @@ export const CUSTOM_JSX_BLOCKED_PROPERTIES: ReadonlySet<string> = new Set([
|
||||
]);
|
||||
|
||||
export const CUSTOM_JSX_BLOCKED_PROPS: ReadonlySet<string> = new Set([
|
||||
"autoFocus",
|
||||
"children",
|
||||
"className",
|
||||
"classNames",
|
||||
"classes",
|
||||
"component",
|
||||
"contentEditable",
|
||||
"dangerouslySetInnerHTML",
|
||||
"form",
|
||||
"formAction",
|
||||
"formEncType",
|
||||
"formMethod",
|
||||
"formNoValidate",
|
||||
"formTarget",
|
||||
"innerRef",
|
||||
"ping",
|
||||
"popover",
|
||||
"popoverTarget",
|
||||
"popoverTargetAction",
|
||||
"portalProps",
|
||||
"ref",
|
||||
"renderRoot",
|
||||
"styles",
|
||||
"unstyled",
|
||||
"srcDoc",
|
||||
"suppressContentEditableWarning",
|
||||
"suppressHydrationWarning",
|
||||
"withinPortal",
|
||||
]);
|
||||
|
||||
@@ -47,7 +60,14 @@ export const CUSTOM_JSX_BLOCKED_TAGS: ReadonlySet<string> = new Set([
|
||||
"style",
|
||||
]);
|
||||
|
||||
export const CUSTOM_JSX_URL_PROPS: ReadonlySet<string> = new Set(["backgroundImage", "href", "src"]);
|
||||
export const CUSTOM_JSX_URL_PROPS: ReadonlySet<string> = new Set([
|
||||
"backgroundImage",
|
||||
"fallbackSrc",
|
||||
"href",
|
||||
"image",
|
||||
"poster",
|
||||
"src",
|
||||
]);
|
||||
|
||||
export const CUSTOM_JSX_BLOCKED_STYLE_KEYS: ReadonlySet<string> = new Set([
|
||||
"backdropFilter",
|
||||
@@ -60,6 +80,7 @@ export const CUSTOM_JSX_BLOCKED_STYLE_KEYS: ReadonlySet<string> = new Set([
|
||||
"left",
|
||||
"mask",
|
||||
"pointerEvents",
|
||||
"pos",
|
||||
"position",
|
||||
"right",
|
||||
"top",
|
||||
@@ -71,3 +92,14 @@ export function normalizeCustomJsxProperty(value: unknown): string {
|
||||
.normalize("NFKC")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export function isBlockedCustomJsxProp(name: string): boolean {
|
||||
return (
|
||||
/^on/iu.test(name) ||
|
||||
name.startsWith("__") ||
|
||||
/(?:Ref|^ref[A-Z])/u.test(name) ||
|
||||
CUSTOM_JSX_BLOCKED_PROPS.has(name) ||
|
||||
CUSTOM_JSX_BLOCKED_STYLE_KEYS.has(name) ||
|
||||
(name !== "bind" && CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(name)))
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createElement, useEffect, useRef, useState } from "react";
|
||||
import { createContext, createElement, useContext, useEffect, useRef, useState } from "react";
|
||||
import * as Core from "@mantine/core";
|
||||
import * as Charts from "@mantine/charts";
|
||||
import * as Dates from "@mantine/dates";
|
||||
|
||||
import { enabledCustomJsxComponents } from "../core/component-registry";
|
||||
import { customJsxBindableComponentNames, enabledCustomJsxComponents } from "../core/component-registry";
|
||||
import { ActionButton, ToggleSwitch } from "../runtime/actions";
|
||||
import { SubData } from "../runtime/data";
|
||||
import { RefreshButton } from "../runtime/refresh-button";
|
||||
@@ -31,19 +31,128 @@ function safeUrl(value: unknown) {
|
||||
return typeof value === "string" && (/^https?:\/\//iu.test(value) || value.startsWith("/") || value.startsWith("#"));
|
||||
}
|
||||
|
||||
function wrap(component: ComponentType<never>, additions: Record<string, unknown> = {}) {
|
||||
return function SafeComponent(props: Record<string, unknown>) {
|
||||
return createElement(component, { ...sanitizeCustomJsxProps(props), ...additions } as never);
|
||||
type WidgetStateValue = string | number | boolean | string[] | number[];
|
||||
interface CustomJsxStateContextValue {
|
||||
state: Record<string, WidgetStateValue>;
|
||||
stateSchema: Record<string, string>;
|
||||
setStateValue(name: string, value: WidgetStateValue): void;
|
||||
}
|
||||
|
||||
const CustomJsxStateContext = createContext<CustomJsxStateContextValue | null>(null);
|
||||
|
||||
export function CustomJsxStateProvider({
|
||||
children,
|
||||
state,
|
||||
stateSchema,
|
||||
setStateValue,
|
||||
}: CustomJsxStateContextValue & { children: ReactNode }) {
|
||||
return (
|
||||
<CustomJsxStateContext.Provider value={{ state, stateSchema, setStateValue }}>
|
||||
{children}
|
||||
</CustomJsxStateContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
const checkedComponents = new Set(["Checkbox", "Switch"]);
|
||||
const openedComponents = new Set(["HoverCard", "Menu", "Popover"]);
|
||||
const activeComponents = new Set(["Stepper"]);
|
||||
const comboboxComponents = new Set(["Autocomplete", "MultiSelect", "Select", "TagsInput", "TreeSelect"]);
|
||||
const popoverInputComponents = new Set([
|
||||
"ColorInput",
|
||||
"DateInput",
|
||||
"DatePickerInput",
|
||||
"DateTimePicker",
|
||||
"MonthPickerInput",
|
||||
"YearPickerInput",
|
||||
]);
|
||||
const buttonRootComponents = new Set(["ActionIcon", "Burger", "Button", "CloseButton", "UnstyledButton"]);
|
||||
|
||||
function extractEventValue(value: unknown, checked: boolean): WidgetStateValue | null {
|
||||
if (value && typeof value === "object" && "currentTarget" in value) {
|
||||
const target = (value as { currentTarget?: { checked?: unknown; value?: unknown } }).currentTarget;
|
||||
const result = checked ? target?.checked : target?.value;
|
||||
return typeof result === "string" || typeof result === "number" || typeof result === "boolean" ? result : null;
|
||||
}
|
||||
if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) return value;
|
||||
if (Array.isArray(value) && value.every((entry) => typeof entry === "string" || entry === null)) {
|
||||
return value.filter((entry): entry is string => typeof entry === "string");
|
||||
}
|
||||
if (Array.isArray(value) && value.every((entry) => typeof entry === "number")) return value;
|
||||
return typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null
|
||||
? value
|
||||
: null;
|
||||
}
|
||||
|
||||
function useBoundProps(componentName: string, props: Record<string, unknown>): Record<string, unknown> {
|
||||
const binding = typeof props.bind === "string" ? props.bind : undefined;
|
||||
const context = useContext(CustomJsxStateContext);
|
||||
const sanitized = sanitizeCustomJsxProps(props);
|
||||
delete sanitized.bind;
|
||||
if (!binding || !context || !customJsxBindableComponentNames.has(componentName)) return sanitized;
|
||||
const stateType = context.stateSchema[binding];
|
||||
if (!stateType) return sanitized;
|
||||
|
||||
const update = (value: unknown, checked = false) => {
|
||||
const extracted = extractEventValue(value, checked);
|
||||
context.setStateValue(binding, extracted ?? emptyStateValue(stateType));
|
||||
};
|
||||
if (componentName === "Calendar") {
|
||||
return { ...sanitized, date: context.state[binding], onDateChange: update };
|
||||
}
|
||||
if (checkedComponents.has(componentName)) {
|
||||
return {
|
||||
...sanitized,
|
||||
checked: Boolean(context.state[binding]),
|
||||
onChange: (event: unknown) => update(event, true),
|
||||
};
|
||||
}
|
||||
if (openedComponents.has(componentName)) {
|
||||
return { ...sanitized, opened: Boolean(context.state[binding]), onChange: update, withinPortal: false };
|
||||
}
|
||||
if (activeComponents.has(componentName)) {
|
||||
return { ...sanitized, active: Number(context.state[binding] ?? 0), onStepClick: update };
|
||||
}
|
||||
return { ...sanitized, value: context.state[binding], onChange: update };
|
||||
}
|
||||
|
||||
function emptyStateValue(type: string): WidgetStateValue {
|
||||
if (type.endsWith("[]")) return [];
|
||||
if (type === "number") return 0;
|
||||
if (type === "boolean") return false;
|
||||
return "";
|
||||
}
|
||||
|
||||
function wrap(componentName: string, component: ComponentType<never>, additions: Record<string, unknown> = {}) {
|
||||
return function SafeComponent(props: Record<string, unknown>) {
|
||||
const bound = useBoundProps(componentName, props);
|
||||
const scoped = { ...bound, ...additions };
|
||||
if (comboboxComponents.has(componentName)) scoped.comboboxProps = scopeOverlayProps(bound.comboboxProps);
|
||||
if (popoverInputComponents.has(componentName)) scoped.popoverProps = scopeOverlayProps(bound.popoverProps);
|
||||
return createElement(component, scoped as never, props.children as ReactNode);
|
||||
};
|
||||
}
|
||||
|
||||
function scopeOverlayProps(value: unknown) {
|
||||
const candidate =
|
||||
value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? sanitizeCustomJsxProps(value as Record<string, unknown>)
|
||||
: {};
|
||||
return { ...candidate, withinPortal: false };
|
||||
}
|
||||
|
||||
function SafeLink({ component, props }: { component: ComponentType<never>; props: Record<string, unknown> }) {
|
||||
const sanitized = sanitizeCustomJsxProps(props);
|
||||
return createElement(component, {
|
||||
...sanitized,
|
||||
href: safeUrl(props.href) ? props.href : undefined,
|
||||
rel: sanitized.target === "_blank" ? "noopener noreferrer" : sanitized.rel,
|
||||
} as never);
|
||||
const target = sanitized.target === "_blank" || sanitized.target === "_self" ? sanitized.target : undefined;
|
||||
return createElement(
|
||||
component,
|
||||
{
|
||||
...sanitized,
|
||||
href: safeUrl(props.href) ? props.href : undefined,
|
||||
target,
|
||||
rel: target === "_blank" ? "noopener noreferrer" : sanitized.rel,
|
||||
} as never,
|
||||
props.children as ReactNode,
|
||||
);
|
||||
}
|
||||
|
||||
function createCopyButton(labels: { copy: string; copied: string }) {
|
||||
@@ -90,7 +199,16 @@ export function createCustomJsxComponents(adapters: CustomJsxComponentAdapters):
|
||||
for (const descriptor of enabledCustomJsxComponents) {
|
||||
const namespace = namespaces[descriptor.package];
|
||||
const component = namespace ? resolveExport(namespace, descriptor.name) : undefined;
|
||||
if (component) components[descriptor.name] = component;
|
||||
if (component) {
|
||||
const additions: Record<string, unknown> = {};
|
||||
if (
|
||||
["HoverCard", "Menu", "Popover", "Tooltip", "Tooltip.Floating", "TooltipFloating"].includes(descriptor.name)
|
||||
) {
|
||||
additions.withinPortal = false;
|
||||
}
|
||||
if (buttonRootComponents.has(descriptor.name)) additions.type = "button";
|
||||
components[descriptor.name] = wrap(descriptor.name, component, additions);
|
||||
}
|
||||
}
|
||||
const core = Core as unknown as Namespace;
|
||||
for (const name of [
|
||||
@@ -107,28 +225,18 @@ export function createCustomJsxComponents(adapters: CustomJsxComponentAdapters):
|
||||
"Chip",
|
||||
] as const) {
|
||||
const component = resolveExport(core, name);
|
||||
if (component) components[name] = wrap(component);
|
||||
if (component) components[name] = wrap(name, component, buttonRootComponents.has(name) ? { type: "button" } : {});
|
||||
}
|
||||
const anchor = resolveExport(core, "Anchor");
|
||||
const navLink = resolveExport(core, "NavLink");
|
||||
if (anchor) components.Anchor = (props) => <SafeLink component={anchor} props={props} />;
|
||||
if (navLink) components.NavLink = (props) => <SafeLink component={navLink} props={props} />;
|
||||
for (const [name, additions] of Object.entries({
|
||||
Rating: { readOnly: true },
|
||||
Slider: { readOnly: true },
|
||||
Switch: { readOnly: true },
|
||||
SegmentedControl: { readOnly: true },
|
||||
Pagination: { disabled: true },
|
||||
})) {
|
||||
const component = resolveExport(core, name);
|
||||
if (component) components[name] = wrap(component, additions);
|
||||
}
|
||||
const dates = Dates as unknown as Namespace;
|
||||
for (const descriptor of enabledCustomJsxComponents.filter(
|
||||
(item) => item.package === "@mantine/dates" && item.safety === "wrapped",
|
||||
)) {
|
||||
const component = resolveExport(dates, descriptor.name);
|
||||
if (component) components[descriptor.name] = wrap(component, { static: true });
|
||||
if (component) components[descriptor.name] = wrap(descriptor.name, component);
|
||||
}
|
||||
Object.assign(components, {
|
||||
CopyButton: createCopyButton(adapters.copyLabels),
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { customJsxSupportedPropsByName } from "../core";
|
||||
import { isInterpreterCallback, SafeJsxError } from "./interpreter-foundation";
|
||||
import {
|
||||
CUSTOM_JSX_BLOCKED_PROPERTIES,
|
||||
CUSTOM_JSX_BLOCKED_PROPS,
|
||||
CUSTOM_JSX_BLOCKED_STYLE_KEYS,
|
||||
CUSTOM_JSX_URL_PROPS,
|
||||
isBlockedCustomJsxProp,
|
||||
normalizeCustomJsxProperty,
|
||||
} from "./policy";
|
||||
|
||||
@@ -61,7 +60,7 @@ function sanitizeStyle(value: unknown): Record<string, string | number> | undefi
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const result: Record<string, string | number> = {};
|
||||
for (const [key, styleValue] of Object.entries(value)) {
|
||||
if (CUSTOM_JSX_BLOCKED_STYLE_KEYS.has(key) || key.startsWith("--")) continue;
|
||||
if (CUSTOM_JSX_BLOCKED_STYLE_KEYS.has(key)) continue;
|
||||
if (typeof styleValue !== "string" && typeof styleValue !== "number") continue;
|
||||
if (typeof styleValue === "string" && /(?:url\s*\(|expression\s*\(|javascript:|position\s*:)/i.test(styleValue)) {
|
||||
continue;
|
||||
@@ -71,26 +70,96 @@ function sanitizeStyle(value: unknown): Record<string, string | number> | undefi
|
||||
return result;
|
||||
}
|
||||
|
||||
function sanitizeStyles(value: unknown): Record<string, Record<string, string | number>> | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const result: Record<string, Record<string, string | number>> = {};
|
||||
for (const [selector, styles] of Object.entries(value)) {
|
||||
if (!/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(selector)) continue;
|
||||
const sanitized = sanitizeStyle(styles);
|
||||
if (sanitized) result[selector] = sanitized;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function sanitizeCustomJsxProps(
|
||||
props: Readonly<Record<string, unknown>>,
|
||||
componentName?: string,
|
||||
_componentName?: string,
|
||||
): Record<string, unknown> {
|
||||
const safe: Record<string, unknown> = {};
|
||||
const supportedProps = componentName ? customJsxSupportedPropsByName.get(componentName) : undefined;
|
||||
for (const [key, value] of Object.entries(props)) {
|
||||
if ((/^on/i.test(key) && !supportedProps?.has(key)) || CUSTOM_JSX_BLOCKED_PROPS.has(key)) continue;
|
||||
if (componentName && !supportedProps?.has(key)) continue;
|
||||
if (typeof value === "function" || isInterpreterCallback(value)) continue;
|
||||
return sanitizeObject(props);
|
||||
}
|
||||
|
||||
function sanitizeObject(value: Readonly<Record<string, unknown>>): Record<string, unknown> {
|
||||
const safe: Record<string, unknown> = Object.create(null);
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (isBlockedCustomJsxProp(key)) continue;
|
||||
if (typeof child === "function" || isInterpreterCallback(child)) continue;
|
||||
if (CUSTOM_JSX_URL_PROPS.has(key)) {
|
||||
if (isSafeUrl(value)) safe[key] = value;
|
||||
if (isSafeUrl(child)) safe[key] = child;
|
||||
continue;
|
||||
}
|
||||
if (key === "style") {
|
||||
const style = sanitizeStyle(value);
|
||||
const style = sanitizeStyle(child);
|
||||
if (style) safe.style = style;
|
||||
continue;
|
||||
}
|
||||
safe[key] = value;
|
||||
if (key === "styles") {
|
||||
const styles = sanitizeStyles(child);
|
||||
if (styles) safe.styles = styles;
|
||||
continue;
|
||||
}
|
||||
safe[key] = key === "data" || key === "series" ? sanitizeSerializableData(child) : sanitizeNestedValue(child);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
function sanitizeSerializableData(value: unknown): unknown {
|
||||
if (typeof value === "function" || isInterpreterCallback(value)) return undefined;
|
||||
if (Array.isArray(value)) return value.map(sanitizeSerializableData);
|
||||
if (value !== null && typeof value === "object") {
|
||||
const safe: Record<string, unknown> = Object.create(null);
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(key))) continue;
|
||||
safe[key] = sanitizeSerializableData(child);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function sanitizeNestedValue(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(sanitizeNestedValue);
|
||||
if (value !== null && typeof value === "object") return sanitizeObject(value as Record<string, unknown>);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function diagnoseCustomJsxProps(props: Readonly<Record<string, unknown>>, componentName: string): string[] {
|
||||
const diagnostics: string[] = [];
|
||||
diagnoseObject(props, componentName, diagnostics);
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
function diagnoseObject(value: Readonly<Record<string, unknown>>, path: string, diagnostics: string[]) {
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
const propertyPath = `${path}.${key}`;
|
||||
if (isBlockedCustomJsxProp(key) || typeof child === "function" || isInterpreterCallback(child)) {
|
||||
diagnostics.push(`BLOCKED_CAPABILITY: Prop '${propertyPath}' is not allowed`);
|
||||
continue;
|
||||
}
|
||||
if (CUSTOM_JSX_URL_PROPS.has(key) && !isSafeUrl(child)) {
|
||||
diagnostics.push(`INVALID_PROP_VALUE: '${propertyPath}' contains an unsafe URL`);
|
||||
continue;
|
||||
}
|
||||
if (key === "data" || key === "series") continue;
|
||||
if (Array.isArray(child)) {
|
||||
child.forEach((entry, index) => {
|
||||
if (isInterpreterCallback(entry) || typeof entry === "function") {
|
||||
diagnostics.push(`BLOCKED_CAPABILITY: Prop '${propertyPath}[${index}]' is not allowed`);
|
||||
} else if (entry !== null && typeof entry === "object") {
|
||||
diagnoseObject(entry as Record<string, unknown>, `${propertyPath}[${index}]`, diagnostics);
|
||||
}
|
||||
});
|
||||
} else if (child !== null && typeof child === "object" && key !== "style" && key !== "styles") {
|
||||
diagnoseObject(child as Record<string, unknown>, propertyPath, diagnostics);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user