feat(custom-widgets): complete Custom JSX v2 (#6390)
This commit is contained in:
1 parent
3a1245cbc5
commit
acdfcbb18e
416 files changed
+37853
-18066
No files matched your search
@@ -0,0 +1,72 @@
|
||||
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);
|
||||
const arguments_ = nodesOf(node.arguments);
|
||||
if (callee?.type === "ArrowFunctionExpression") {
|
||||
if (arguments_.length > 0) return true;
|
||||
const body = nodeOf(callee.body);
|
||||
return body ? containsEscapingCallbackChildren(body) : false;
|
||||
}
|
||||
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 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;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
export interface CustomJsxTemplateDiagnostic {
|
||||
severity: "error" | "warning";
|
||||
message: string;
|
||||
index: number;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
export function createCustomJsxParseDiagnostic(_template: string, error: unknown): CustomJsxTemplateDiagnostic {
|
||||
const parseError = error as Error & { pos?: number; loc?: { line?: number; column?: number } };
|
||||
const parseIndex = Math.max(0, (parseError.pos ?? 2) - 2);
|
||||
const duplicateArgument = /Argument name clash/iu.test(parseError.message);
|
||||
const message = duplicateArgument
|
||||
? "DUPLICATE_LOCAL_BINDING: Callback parameter names must be unique"
|
||||
: parseError.message;
|
||||
|
||||
return {
|
||||
severity: "error",
|
||||
message,
|
||||
index: parseIndex,
|
||||
line: parseError.loc?.line ?? 1,
|
||||
column: Math.max(
|
||||
1,
|
||||
(parseError.loc?.column ?? 0) + (parseError.loc?.line === 1 || parseError.loc?.line === undefined ? -1 : 1),
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import {
|
||||
customJsxBindableComponentNames,
|
||||
customJsxComponentByName,
|
||||
customJsxSupportedPropsByName,
|
||||
resolveCustomJsxComponentName,
|
||||
} from "../core/component-registry";
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { containsEscapingCallback, nodeOf, nodesOf } from "./analyzer-ast";
|
||||
import { closestCustomJsxComponentName, customJsxTagName, isSafeLiteralCustomJsxUrl } from "./analyzer-language";
|
||||
import { CUSTOM_JSX_URL_PROPS, isBlockedCustomJsxProp } from "./policy";
|
||||
import { getInvalidCustomJsxPropValueReason } from "./runtime-component-policy";
|
||||
|
||||
interface AnalyzerJsxContext {
|
||||
add(node: AstNode, message: string, severity?: "error" | "warning"): void;
|
||||
visit(node: AstNode, depth: number, bindings: ReadonlySet<string>): void;
|
||||
visitArrow(node: AstNode, depth: number, bindings: ReadonlySet<string>): void;
|
||||
}
|
||||
|
||||
export function analyzeCustomJsxElement(
|
||||
node: AstNode,
|
||||
depth: number,
|
||||
bindings: ReadonlySet<string>,
|
||||
context: AnalyzerJsxContext,
|
||||
): void {
|
||||
const opening = nodeOf(node.openingElement);
|
||||
if (!opening) {
|
||||
context.add(node, "Invalid JSX element");
|
||||
return;
|
||||
}
|
||||
const nameNode = nodeOf(opening.name);
|
||||
const name = nameNode ? customJsxTagName(nameNode) : null;
|
||||
const resolvedName = name ? resolveCustomJsxComponentName(name) : null;
|
||||
const descriptor = resolvedName ? customJsxComponentByName.get(resolvedName) : undefined;
|
||||
if (descriptor?.safety === "denied") {
|
||||
context.add(
|
||||
opening,
|
||||
`BLOCKED_CAPABILITY: '${name}' is not available${descriptor.reason ? ` because it ${descriptor.reason.toLowerCase()}` : ""}`,
|
||||
);
|
||||
} else if (!descriptor) {
|
||||
const suggestion = name ? closestCustomJsxComponentName(name) : undefined;
|
||||
context.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) context.visit(argument, depth + 1, bindings);
|
||||
continue;
|
||||
}
|
||||
if (attribute.type !== "JSXAttribute") {
|
||||
context.add(attribute, `Unsupported JSX attribute '${attribute.type}'`);
|
||||
continue;
|
||||
}
|
||||
const attributeNameNode = nodeOf(attribute.name);
|
||||
const attributeName = attributeNameNode?.type === "JSXIdentifier" ? String(attributeNameNode.name) : "";
|
||||
const componentBlockedProp = descriptor?.blockedProps.find(({ name: propName }) => propName === attributeName);
|
||||
if (componentBlockedProp) {
|
||||
context.add(
|
||||
attribute,
|
||||
`BLOCKED_CAPABILITY: Prop '${attributeName}' on '${name}' is not allowed because ${componentBlockedProp.reason.toLowerCase()}`,
|
||||
);
|
||||
} else if (isBlockedCustomJsxProp(attributeName)) {
|
||||
context.add(attribute, `BLOCKED_CAPABILITY: Prop '${attributeName}' is not allowed`);
|
||||
} else if (
|
||||
resolvedName &&
|
||||
attributeName !== "bind" &&
|
||||
!customJsxSupportedPropsByName.get(resolvedName)?.has(attributeName)
|
||||
) {
|
||||
context.add(attribute, `UNKNOWN_MANTINE_PROP: '${attributeName}' on ${name} will be passed through`, "warning");
|
||||
} else if (resolvedName && attributeName === "bind" && !customJsxBindableComponentNames.has(resolvedName)) {
|
||||
context.add(attribute, `BINDING_UNAVAILABLE: '${name}' does not have a declarative binding adapter`, "warning");
|
||||
}
|
||||
analyzeAttributeValue(resolvedName, attributeName, attribute, depth, bindings, context);
|
||||
}
|
||||
|
||||
nodesOf(node.children).forEach((child) => {
|
||||
const expression = child.type === "JSXExpressionContainer" ? nodeOf(child.expression) : null;
|
||||
if (resolvedName === "SubFetch" && expression?.type === "ArrowFunctionExpression") {
|
||||
context.visitArrow(expression, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
context.visit(child, depth + 1, bindings);
|
||||
});
|
||||
}
|
||||
|
||||
function analyzeAttributeValue(
|
||||
componentName: string | null,
|
||||
attributeName: string,
|
||||
attribute: AstNode,
|
||||
depth: number,
|
||||
bindings: ReadonlySet<string>,
|
||||
context: AnalyzerJsxContext,
|
||||
): void {
|
||||
const value = nodeOf(attribute.value);
|
||||
const literalValue =
|
||||
value?.type === "Literal"
|
||||
? value
|
||||
: value?.type === "JSXExpressionContainer" && nodeOf(value.expression)?.type === "Literal"
|
||||
? nodeOf(value.expression)
|
||||
: null;
|
||||
if (componentName && literalValue?.type === "Literal") {
|
||||
const reason = getInvalidCustomJsxPropValueReason(componentName, attributeName, literalValue.value);
|
||||
if (reason) context.add(attribute, `INVALID_PROP_VALUE: ${reason}`);
|
||||
}
|
||||
if (
|
||||
CUSTOM_JSX_URL_PROPS.has(attributeName) &&
|
||||
value?.type === "Literal" &&
|
||||
typeof value.value === "string" &&
|
||||
!isSafeLiteralCustomJsxUrl(value.value)
|
||||
) {
|
||||
context.add(attribute, `INVALID_PROP_VALUE: '${attributeName}' contains an unsafe URL`);
|
||||
}
|
||||
if (value?.type !== "JSXExpressionContainer") return;
|
||||
const expression = nodeOf(value.expression);
|
||||
if (expression && containsEscapingCallback(expression)) {
|
||||
context.add(attribute, `BLOCKED_CAPABILITY: Callback prop '${attributeName}' is not allowed`);
|
||||
} else if (expression && expression.type !== "JSXEmptyExpression") {
|
||||
context.visit(expression, depth + 1, bindings);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { enabledCustomJsxComponents } from "../core/component-registry";
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { nodeOf, staticPropertyName } from "./analyzer-ast";
|
||||
|
||||
export const ROOT_BINDINGS = new Set([
|
||||
"Array",
|
||||
"Boolean",
|
||||
"Date",
|
||||
"Infinity",
|
||||
"JSON",
|
||||
"Math",
|
||||
"NaN",
|
||||
"Number",
|
||||
"Object",
|
||||
"String",
|
||||
"data",
|
||||
"options",
|
||||
"inputs",
|
||||
"status",
|
||||
"decodeURIComponent",
|
||||
"encodeURIComponent",
|
||||
"isFinite",
|
||||
"isNaN",
|
||||
"parseFloat",
|
||||
"parseInt",
|
||||
"undefined",
|
||||
]);
|
||||
|
||||
export const RESERVED_LOCAL_BINDINGS = new Set(["data", "status", "options", "inputs"]);
|
||||
const callableRootBindings = new Set([
|
||||
"Boolean",
|
||||
"Number",
|
||||
"String",
|
||||
"decodeURIComponent",
|
||||
"encodeURIComponent",
|
||||
"isFinite",
|
||||
"isNaN",
|
||||
"parseFloat",
|
||||
"parseInt",
|
||||
]);
|
||||
const callableRootMembers: Readonly<Record<string, ReadonlySet<string>>> = {
|
||||
Array: new Set(["from", "isArray"]),
|
||||
Date: new Set([
|
||||
"create",
|
||||
"getDay",
|
||||
"getMonth",
|
||||
"getTime",
|
||||
"getYear",
|
||||
"now",
|
||||
"toISOString",
|
||||
"toLocaleDateString",
|
||||
"toLocaleTimeString",
|
||||
]),
|
||||
JSON: new Set(["stringify"]),
|
||||
Math: new Set(["abs", "ceil", "floor", "max", "min", "pow", "round", "sqrt"]),
|
||||
Object: new Set(["entries", "keys", "values"]),
|
||||
};
|
||||
const enabledComponentNames = enabledCustomJsxComponents.map((component) => component.name);
|
||||
|
||||
export function closestCustomJsxComponentName(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;
|
||||
}
|
||||
|
||||
export function customJsxTagName(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 ? customJsxTagName(object) : null;
|
||||
const right = property ? customJsxTagName(property) : null;
|
||||
return left && right ? `${left}.${right}` : null;
|
||||
}
|
||||
|
||||
export function isSafeLiteralCustomJsxUrl(value: string): boolean {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
export function isStaticallyCallableBinding(node: AstNode): boolean {
|
||||
if (node.type === "Identifier") return callableRootBindings.has(String(node.name));
|
||||
if (node.type !== "MemberExpression") return false;
|
||||
const object = nodeOf(node.object);
|
||||
const property = nodeOf(node.property);
|
||||
if (object?.type !== "Identifier") return false;
|
||||
const propertyName = node.computed ? staticPropertyName(property) : String(property?.name ?? "");
|
||||
return Boolean(propertyName && callableRootMembers[String(object.name)]?.has(propertyName));
|
||||
}
|
||||
|
||||
export function canStaticallyProduceCallable(node: AstNode): boolean {
|
||||
if (isStaticallyCallableBinding(node) || ["ArrowFunctionExpression", "FunctionExpression"].includes(node.type)) {
|
||||
return true;
|
||||
}
|
||||
if (node.type === "ConditionalExpression") {
|
||||
const consequent = nodeOf(node.consequent);
|
||||
const alternate = nodeOf(node.alternate);
|
||||
return Boolean(
|
||||
(consequent && canStaticallyProduceCallable(consequent)) ||
|
||||
(alternate && canStaticallyProduceCallable(alternate)),
|
||||
);
|
||||
}
|
||||
if (node.type === "LogicalExpression") {
|
||||
const left = nodeOf(node.left);
|
||||
const right = nodeOf(node.right);
|
||||
return Boolean((left && canStaticallyProduceCallable(left)) || (right && canStaticallyProduceCallable(right)));
|
||||
}
|
||||
if (node.type === "ChainExpression") {
|
||||
const expression = nodeOf(node.expression);
|
||||
return Boolean(expression && canStaticallyProduceCallable(expression));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -1,77 +1,62 @@
|
||||
import { Parser } from "acorn";
|
||||
import jsx from "acorn-jsx";
|
||||
|
||||
import { customJsxComponentByName, customJsxSupportedPropsByName } from "../core/component-registry";
|
||||
import {
|
||||
CUSTOM_JSX_BLOCKED_PROPERTIES,
|
||||
CUSTOM_JSX_BLOCKED_PROPS,
|
||||
CUSTOM_JSX_LIMITS,
|
||||
isBlockedCustomJsxLexicalBinding,
|
||||
normalizeCustomJsxProperty,
|
||||
} from "./policy";
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { nodeOf, nodesOf, staticPropertyName } from "./analyzer-ast";
|
||||
import { createCustomJsxParseDiagnostic } from "./analyzer-diagnostics";
|
||||
import type { CustomJsxTemplateDiagnostic } from "./analyzer-diagnostics";
|
||||
import { analyzeCustomJsxElement } from "./analyzer-jsx";
|
||||
import {
|
||||
canStaticallyProduceCallable,
|
||||
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";
|
||||
|
||||
interface AstNode {
|
||||
type: string;
|
||||
start?: number;
|
||||
loc?: { start?: { line?: number; column?: number } };
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface CustomJsxTemplateDiagnostic {
|
||||
severity: "error" | "warning";
|
||||
message: string;
|
||||
index: number;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
export type { CustomJsxTemplateDiagnostic } from "./analyzer-diagnostics";
|
||||
|
||||
const JsxParser = Parser.extend(jsx());
|
||||
const requestStatusLabels = new Set(["loading", "success", "error"]);
|
||||
|
||||
const rootBindings = new Set([
|
||||
"Array",
|
||||
"Boolean",
|
||||
"Date",
|
||||
"Infinity",
|
||||
"JSON",
|
||||
"Math",
|
||||
"NaN",
|
||||
"Number",
|
||||
"Object",
|
||||
"String",
|
||||
"data",
|
||||
"decodeURIComponent",
|
||||
"encodeURIComponent",
|
||||
"isFinite",
|
||||
"isNaN",
|
||||
"parseFloat",
|
||||
"parseInt",
|
||||
"undefined",
|
||||
]);
|
||||
function directRequestStatusId(node: AstNode | null): string | null {
|
||||
if (node?.type !== "MemberExpression") return null;
|
||||
const object = nodeOf(node.object);
|
||||
if (object?.type !== "Identifier" || object.name !== "status") return null;
|
||||
const property = nodeOf(node.property);
|
||||
return node.computed
|
||||
? (staticPropertyName(property) ?? null)
|
||||
: String(property?.name ?? property?.value ?? "") || null;
|
||||
}
|
||||
|
||||
const nodeOf = (value: unknown): AstNode | null =>
|
||||
value !== null && typeof value === "object" && typeof (value as { type?: unknown }).type === "string"
|
||||
? (value as AstNode)
|
||||
function invalidRequestStatusComparison(node: AstNode) {
|
||||
if (!["===", "==", "!==", "!="].includes(String(node.operator))) return null;
|
||||
const left = nodeOf(node.left);
|
||||
const right = nodeOf(node.right);
|
||||
const leftStatus = directRequestStatusId(left);
|
||||
const rightStatus = directRequestStatusId(right);
|
||||
const leftLabel = left?.type === "Literal" && typeof left.value === "string" ? left.value : null;
|
||||
const rightLabel = right?.type === "Literal" && typeof right.value === "string" ? right.value : null;
|
||||
const requestId =
|
||||
leftStatus && rightLabel && requestStatusLabels.has(rightLabel)
|
||||
? leftStatus
|
||||
: rightStatus && leftLabel && requestStatusLabels.has(leftLabel)
|
||||
? rightStatus
|
||||
: null;
|
||||
return requestId
|
||||
? `INVALID_STATUS_COMPARISON: status.${requestId} is an object. Use status.${requestId}?.loading, status.${requestId}?.ok === true, or status.${requestId}?.ok === false`
|
||||
: 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;
|
||||
};
|
||||
}
|
||||
|
||||
export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDiagnostic[] {
|
||||
const diagnostics: CustomJsxTemplateDiagnostic[] = [];
|
||||
@@ -98,17 +83,46 @@ 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;
|
||||
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")
|
||||
add(body, "UNSUPPORTED_BLOCK_STATEMENT: Use one expression in authored callbacks");
|
||||
else if (canStaticallyProduceCallable(body)) {
|
||||
add(body, "CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
|
||||
} else visit(body, depth + 1, callbackBindings);
|
||||
};
|
||||
|
||||
const visit = (node: AstNode, depth: number, bindings: ReadonlySet<string>): void => {
|
||||
visit = (node: AstNode, depth: number, bindings: ReadonlySet<string>): void => {
|
||||
if (!checkBudget(node, depth)) return;
|
||||
|
||||
switch (node.type) {
|
||||
@@ -124,46 +138,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 || descriptor.safety === "denied") {
|
||||
add(opening, name ? `Component '${name}' is not available` : "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) : "";
|
||||
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");
|
||||
}
|
||||
const value = nodeOf(attribute.value);
|
||||
if (value?.type === "JSXExpressionContainer") {
|
||||
const expression = nodeOf(value.expression);
|
||||
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":
|
||||
@@ -176,9 +151,9 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
return;
|
||||
}
|
||||
case "Literal":
|
||||
if (node.regex !== undefined || typeof node.value === "bigint") {
|
||||
add(node, "Regular expressions and bigint literals are not supported");
|
||||
}
|
||||
if (typeof node.value === "bigint") add(node, "BIGINT_NOT_SUPPORTED: Use Number for widget values");
|
||||
if (node.regex !== undefined && !isSafeRegexLiteral(node.regex))
|
||||
add(node, "UNSAFE_REGEX: Use a bounded regex without lookbehind, backreferences, or nested quantifiers");
|
||||
return;
|
||||
case "Identifier": {
|
||||
const name = String(node.name ?? "");
|
||||
@@ -223,6 +198,13 @@ 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`);
|
||||
}
|
||||
if (node.type === "BinaryExpression") {
|
||||
const statusDiagnostic = invalidRequestStatusComparison(node);
|
||||
if (statusDiagnostic) add(node, statusDiagnostic);
|
||||
}
|
||||
const left = nodeOf(node.left);
|
||||
const right = nodeOf(node.right);
|
||||
if (left) visit(left, depth + 1, bindings);
|
||||
@@ -250,27 +232,66 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
|
||||
}
|
||||
case "CallExpression": {
|
||||
const callee = nodeOf(node.callee);
|
||||
const arguments_ = nodesOf(node.arguments);
|
||||
if (node.optional) {
|
||||
add(node, "CALL_TARGET_NOT_ALLOWED: Optional calls are not supported");
|
||||
}
|
||||
if (callee?.type === "ArrowFunctionExpression") {
|
||||
add(callee, "CALL_TARGET_NOT_ALLOWED: Inline IIFEs are not supported");
|
||||
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: Authored callbacks must use one expression");
|
||||
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;
|
||||
@@ -290,17 +311,18 @@ 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 } };
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
message: parseError.message,
|
||||
index: Math.max(0, (parseError.pos ?? 2) - 2),
|
||||
line: parseError.loc?.line ?? 1,
|
||||
column: Math.max(1, (parseError.loc?.column ?? 2) - 1),
|
||||
});
|
||||
diagnostics.push(createCustomJsxParseDiagnostic(template, error));
|
||||
}
|
||||
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
function isSafeRegexLiteral(regex: unknown): boolean {
|
||||
if (!regex || typeof regex !== "object") return false;
|
||||
const { pattern, flags } = regex as { pattern?: unknown; flags?: unknown };
|
||||
if (typeof pattern !== "string" || pattern.length > 128 || typeof flags !== "string" || /[^gimsu]/u.test(flags))
|
||||
return false;
|
||||
return !/\\[1-9]|\(\?<[=!]|(?:\+|\*|\{\d+(?:,\d*)?\})\)?(?:\+|\*|\{)/u.test(pattern);
|
||||
}
|
||||
@@ -1,28 +1,28 @@
|
||||
import { isSafeCallable } from "./safe-bindings";
|
||||
import { isInterpreterCallback, normalizedSliceIndex, numericArgument, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { Budget, InterpreterCallback } from "./interpreter-foundation";
|
||||
|
||||
interface CollectionMethodContext {
|
||||
budget: Budget;
|
||||
runCallback(callback: InterpreterCallback, args: unknown[], depth: number): unknown;
|
||||
}
|
||||
import type { InterpreterCallback } from "./interpreter-foundation";
|
||||
import type { InterpreterMethodContext } from "./interpreter-method-context";
|
||||
import { callStringMethod } from "./string-methods";
|
||||
|
||||
export function callCollectionMethod(
|
||||
receiver: unknown,
|
||||
method: string,
|
||||
args: unknown[],
|
||||
depth: number,
|
||||
context: CollectionMethodContext,
|
||||
context: InterpreterMethodContext,
|
||||
): { handled: boolean; value?: unknown } {
|
||||
if (Array.isArray(receiver)) {
|
||||
if (method === "map" || method === "filter") {
|
||||
if (method === "map" || method === "filter" || method === "flatMap") {
|
||||
const callback = args[0];
|
||||
if (isSafeCallable(callback)) {
|
||||
const result: unknown[] = [];
|
||||
for (let index = 0; index < receiver.length; index += 1) {
|
||||
context.budget.collection();
|
||||
const callbackResult = callback(receiver[index] as never);
|
||||
if (method === "map") result.push(callbackResult);
|
||||
if (method === "flatMap" && Array.isArray(callbackResult)) {
|
||||
context.budget.collection(callbackResult.length);
|
||||
result.push(...callbackResult);
|
||||
} else if (method === "map" || method === "flatMap") result.push(callbackResult);
|
||||
else if (callbackResult) result.push(receiver[index]);
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
@@ -32,7 +32,25 @@ export function callCollectionMethod(
|
||||
for (let index = 0; index < receiver.length; index += 1) {
|
||||
context.budget.collection();
|
||||
const callbackResult = context.runCallback(callback, [receiver[index], index, receiver], depth + 1);
|
||||
if (method === "map" || callbackResult) result.push(method === "map" ? callbackResult : receiver[index]);
|
||||
if (method === "flatMap" && Array.isArray(callbackResult)) {
|
||||
context.budget.collection(callbackResult.length);
|
||||
result.push(...callbackResult);
|
||||
} else if (method === "map" || method === "flatMap" || callbackResult) {
|
||||
result.push(method === "map" || method === "flatMap" ? callbackResult : receiver[index]);
|
||||
}
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
if (method === "concat") {
|
||||
const result = [...receiver];
|
||||
for (const value of args) {
|
||||
if (Array.isArray(value)) {
|
||||
context.budget.collection(value.length);
|
||||
result.push(...value);
|
||||
} else {
|
||||
context.budget.collection();
|
||||
result.push(value);
|
||||
}
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
@@ -155,98 +173,11 @@ export function callCollectionMethod(
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof receiver === "string") {
|
||||
switch (method) {
|
||||
case "toUpperCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toUpperCase()) };
|
||||
case "toLowerCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toLowerCase()) };
|
||||
case "trim":
|
||||
return { handled: true, value: context.budget.string(receiver.trim()) };
|
||||
case "trimStart":
|
||||
return { handled: true, value: context.budget.string(receiver.trimStart()) };
|
||||
case "trimEnd":
|
||||
return { handled: true, value: context.budget.string(receiver.trimEnd()) };
|
||||
case "replace": {
|
||||
const search = String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
const matchIndex = receiver.indexOf(search);
|
||||
if (matchIndex === -1) return { handled: true, value: context.budget.string(receiver) };
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.slice(0, matchIndex) + replacement + receiver.slice(matchIndex + search.length),
|
||||
),
|
||||
};
|
||||
}
|
||||
case "replaceAll": {
|
||||
const search = String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
if (search.length === 0) return { handled: true, value: context.budget.string(receiver) };
|
||||
let result = "";
|
||||
let cursor = 0;
|
||||
while (cursor < receiver.length) {
|
||||
const matchIndex = receiver.indexOf(search, cursor);
|
||||
if (matchIndex === -1) {
|
||||
result += receiver.slice(cursor);
|
||||
break;
|
||||
}
|
||||
result += receiver.slice(cursor, matchIndex) + replacement;
|
||||
cursor = matchIndex + search.length;
|
||||
}
|
||||
return { handled: true, value: context.budget.string(result) };
|
||||
}
|
||||
case "indexOf":
|
||||
return { handled: true, value: receiver.indexOf(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "lastIndexOf": {
|
||||
const fromIndex = args[1] !== undefined ? numericArgument(args[1], receiver.length) : undefined;
|
||||
return { handled: true, value: receiver.lastIndexOf(String(args[0] ?? ""), fromIndex) };
|
||||
}
|
||||
case "repeat": {
|
||||
let maxCount = 0;
|
||||
if (receiver.length > 0) maxCount = Math.floor(200_001 / receiver.length);
|
||||
const count = Math.max(0, Math.min(numericArgument(args[0], 0), maxCount));
|
||||
return { handled: true, value: context.budget.string(receiver.repeat(count).slice(0, 200_001)) };
|
||||
}
|
||||
case "slice":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.slice(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "substring":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.substring(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "includes":
|
||||
return { handled: true, value: receiver.includes(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "startsWith":
|
||||
return { handled: true, value: receiver.startsWith(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "endsWith":
|
||||
return { handled: true, value: receiver.endsWith(String(args[0] ?? ""), args[1] as number | undefined) };
|
||||
case "padStart":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padStart(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "padEnd":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padEnd(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "charAt":
|
||||
return { handled: true, value: receiver.charAt(numericArgument(args[0], 0)) };
|
||||
case "split": {
|
||||
const limit = Math.max(0, Math.min(2_000, numericArgument(args[1], 2_000)));
|
||||
const split = args[0] === undefined ? [receiver] : receiver.split(String(args[0]), limit);
|
||||
context.budget.collection(split.length);
|
||||
return { handled: true, value: split };
|
||||
}
|
||||
}
|
||||
if (typeof receiver === "string") return callStringMethod(receiver, method, args, context);
|
||||
|
||||
if (receiver instanceof RegExp && method === "test") {
|
||||
const value = String(args[0] ?? "");
|
||||
return { handled: true, value: receiver.test(value) };
|
||||
}
|
||||
|
||||
if (typeof receiver === "number") {
|
||||
@@ -258,6 +189,9 @@ export function callCollectionMethod(
|
||||
const precision = Math.max(1, Math.min(21, numericArgument(args[0], 1)));
|
||||
return { handled: true, value: receiver.toPrecision(precision) };
|
||||
}
|
||||
if (method === "toLocaleString") {
|
||||
return { handled: true, value: context.budget.string(receiver.toLocaleString()) };
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
|
||||
import type { AstNode, Budget, Environment, InterpreterCallback } from "./interpreter-foundation";
|
||||
|
||||
export interface JsxEmitterContext {
|
||||
components: Readonly<Record<string, ComponentType<never>>>;
|
||||
budget: Budget;
|
||||
warnings: Set<string>;
|
||||
evaluate(node: AstNode, environment: Environment, depth: number): unknown;
|
||||
createCallback(node: AstNode, environment: Environment): InterpreterCallback;
|
||||
renderCallback(callback: InterpreterCallback, args: unknown[], depth: number): ReactNode;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { asNode, asNodeArray, Environment, INTERPRETER_CALLBACK, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Budget, InterpreterCallback } from "./interpreter-foundation";
|
||||
import { RESERVED_LOCAL_BINDINGS } from "./analyzer-language";
|
||||
import { isBlockedCustomJsxLexicalBinding } from "./policy";
|
||||
|
||||
interface InterpreterCallbackContext {
|
||||
budget: Budget;
|
||||
evaluate(node: AstNode, environment: Environment, depth: number): unknown;
|
||||
}
|
||||
|
||||
export function createInterpreterCallback(node: AstNode, environment: Environment): InterpreterCallback {
|
||||
if (node.async || node.generator)
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Async and generator callbacks are not supported");
|
||||
const parameterNames = new Set<string>();
|
||||
const params = asNodeArray(node.params, "callback parameters").map((param) => {
|
||||
if (param.type !== "Identifier")
|
||||
throw new SafeJsxError("INVALID_LOCAL_DECLARATION: Callback parameters must be identifiers");
|
||||
const name = String(param.name);
|
||||
if (isBlockedCustomJsxLexicalBinding(name) || RESERVED_LOCAL_BINDINGS.has(name))
|
||||
throw new SafeJsxError(`INVALID_LOCAL_DECLARATION: '${name}' is not a safe callback parameter name`);
|
||||
if (parameterNames.has(name)) throw new SafeJsxError(`DUPLICATE_LOCAL_BINDING: '${name}' is already declared`);
|
||||
parameterNames.add(name);
|
||||
return name;
|
||||
});
|
||||
const body = asNode(node.body, "callback body");
|
||||
if (body.type === "BlockStatement")
|
||||
throw new SafeJsxError("UNSUPPORTED_BLOCK_STATEMENT: Use one expression in authored callbacks");
|
||||
return { kind: INTERPRETER_CALLBACK, params, body, environment };
|
||||
}
|
||||
|
||||
export function runInterpreterCallback(
|
||||
callback: InterpreterCallback,
|
||||
args: unknown[],
|
||||
depth: number,
|
||||
context: InterpreterCallbackContext,
|
||||
): unknown {
|
||||
context.budget.operation(depth);
|
||||
const values: Record<string, unknown> = Object.create(null);
|
||||
callback.params.forEach((name, index) => {
|
||||
values[name] = args[index];
|
||||
});
|
||||
const result = context.evaluate(callback.body, new Environment(values, callback.environment), depth + 1);
|
||||
if (
|
||||
typeof result === "function" ||
|
||||
(result !== null && typeof result === "object" && "kind" in result && result.kind === INTERPRETER_CALLBACK)
|
||||
) {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Authored callbacks cannot return callable values");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -39,6 +39,13 @@ export class SafeJsxError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class SafeJsxBudgetError extends SafeJsxError {
|
||||
public constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "SafeJsxBudgetError";
|
||||
}
|
||||
}
|
||||
|
||||
export class Environment {
|
||||
public constructor(
|
||||
private readonly values: Readonly<Record<string, unknown>>,
|
||||
@@ -61,22 +68,22 @@ export class Budget {
|
||||
public constructor(private readonly limits: EvaluationBudgets) {}
|
||||
public operation(depth: number): void {
|
||||
if (depth > this.limits.maxAstDepth)
|
||||
throw new SafeJsxError(`Template exceeded the AST depth limit (${this.limits.maxAstDepth})`);
|
||||
throw new SafeJsxBudgetError(`Template exceeded the AST depth limit (${this.limits.maxAstDepth})`);
|
||||
if (++this.operations > this.limits.maxOperations)
|
||||
throw new SafeJsxError(`Template exceeded the operation limit (${this.limits.maxOperations})`);
|
||||
throw new SafeJsxBudgetError(`Template exceeded the operation limit (${this.limits.maxOperations})`);
|
||||
}
|
||||
public collection(count = 1): void {
|
||||
this.collectionItems += count;
|
||||
if (this.collectionItems > this.limits.maxCollectionItems)
|
||||
throw new SafeJsxError(`Template exceeded the collection limit (${this.limits.maxCollectionItems})`);
|
||||
throw new SafeJsxBudgetError(`Template exceeded the collection limit (${this.limits.maxCollectionItems})`);
|
||||
}
|
||||
public rendered(): void {
|
||||
if (++this.renderedNodes > this.limits.maxRenderedNodes)
|
||||
throw new SafeJsxError(`Template exceeded the rendered node limit (${this.limits.maxRenderedNodes})`);
|
||||
throw new SafeJsxBudgetError(`Template exceeded the rendered node limit (${this.limits.maxRenderedNodes})`);
|
||||
}
|
||||
public string(value: string): string {
|
||||
if (value.length > this.limits.maxStringLength)
|
||||
throw new SafeJsxError(`Template exceeded the string length limit (${this.limits.maxStringLength})`);
|
||||
throw new SafeJsxBudgetError(`Template exceeded the string length limit (${this.limits.maxStringLength})`);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { Budget, InterpreterCallback } from "./interpreter-foundation";
|
||||
|
||||
export interface InterpreterMethodContext {
|
||||
budget: Budget;
|
||||
runCallback(callback: InterpreterCallback, args: unknown[], depth: number): unknown;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Parser } from "acorn";
|
||||
import jsx from "acorn-jsx";
|
||||
|
||||
import type { AstNode } from "./interpreter-foundation";
|
||||
import { asNode, asNodeArray, SafeJsxError } from "./interpreter-foundation";
|
||||
import { CUSTOM_JSX_LIMITS } from "./policy";
|
||||
|
||||
const JsxParser = Parser.extend(jsx());
|
||||
|
||||
export function parseCustomJsxTemplate(template: string): AstNode {
|
||||
if (template.length > CUSTOM_JSX_LIMITS.templateLength) {
|
||||
throw new SafeJsxError(`Template exceeds the ${CUSTOM_JSX_LIMITS.templateLength} character limit`);
|
||||
}
|
||||
let program: AstNode;
|
||||
try {
|
||||
program = JsxParser.parse(`<>${template}</>`, {
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
allowAwaitOutsideFunction: false,
|
||||
allowReturnOutsideFunction: false,
|
||||
}) as unknown as AstNode;
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unable to parse JSX template";
|
||||
throw new SafeJsxError(
|
||||
/Argument name clash/iu.test(message)
|
||||
? "DUPLICATE_LOCAL_BINDING: Callback parameter names must be unique"
|
||||
: message,
|
||||
);
|
||||
}
|
||||
const body = asNodeArray(program.body, "program body");
|
||||
if (body.length !== 1 || body[0]?.type !== "ExpressionStatement") {
|
||||
throw new SafeJsxError("Template must contain JSX only");
|
||||
}
|
||||
return asNode(body[0].expression, "template expression");
|
||||
}
|
||||
|
||||
export function normalizeCustomJsxText(value: string): string {
|
||||
const lines = value.replace(/\r/g, "").split("\n");
|
||||
let result = "";
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
let line = lines[index] ?? "";
|
||||
line = line.replace(/\t/g, " ");
|
||||
if (index !== 0) line = line.replace(/^\s+/, "");
|
||||
if (index !== lines.length - 1) line = line.replace(/\s+$/, "");
|
||||
if (!line) continue;
|
||||
if (result) result += " ";
|
||||
result += line;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -1,25 +1,18 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { Parser } from "acorn";
|
||||
import jsx from "acorn-jsx";
|
||||
|
||||
import { callCollectionMethod } from "./collection-methods";
|
||||
import { staticPropertyName } from "./analyzer-ast";
|
||||
import type { JsxEmitterContext } from "./emitter-context";
|
||||
import { createInterpreterCallback, runInterpreterCallback } from "./interpreter-callbacks";
|
||||
import { emitJsxElement, emitJsxFragment } from "./jsx-emitter";
|
||||
import type { JsxEmitterContext } from "./jsx-emitter";
|
||||
import { isSafeCallable } from "./safe-bindings";
|
||||
import {
|
||||
asNode,
|
||||
asNodeArray,
|
||||
Budget,
|
||||
DEFAULT_BUDGETS,
|
||||
Environment,
|
||||
INTERPRETER_CALLBACK,
|
||||
SafeJsxError,
|
||||
} from "./interpreter-foundation";
|
||||
import { asNode, asNodeArray, Budget, DEFAULT_BUDGETS, Environment, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, EvaluationBudgets, InterpreterCallback, SafeJsxBudgets } from "./interpreter-foundation";
|
||||
import { normalizeCustomJsxText, parseCustomJsxTemplate } from "./interpreter-parser";
|
||||
import { normalizedProperty, ownProperty } from "./safe-properties";
|
||||
import { CUSTOM_JSX_LIMITS } from "./policy";
|
||||
import { CUSTOM_JSX_CALLBACK_METHODS } from "./safe-language-policy";
|
||||
|
||||
export { SafeJsxError } from "./interpreter-foundation";
|
||||
export { SafeJsxBudgetError, SafeJsxError } from "./interpreter-foundation";
|
||||
export type { SafeJsxBudgets } from "./interpreter-foundation";
|
||||
export { sanitizeCustomJsxProps } from "./safe-properties";
|
||||
|
||||
@@ -35,23 +28,6 @@ export interface SafeJsxRenderResult {
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
const JsxParser = Parser.extend(jsx());
|
||||
|
||||
function jsxText(value: string): string {
|
||||
const lines = value.replace(/\r/g, "").split("\n");
|
||||
let result = "";
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
let line = lines[index] ?? "";
|
||||
line = line.replace(/\t/g, " ");
|
||||
if (index !== 0) line = line.replace(/^\s+/, "");
|
||||
if (index !== lines.length - 1) line = line.replace(/\s+$/, "");
|
||||
if (!line) continue;
|
||||
if (result) result += " ";
|
||||
result += line;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
class Interpreter {
|
||||
private readonly budget: Budget;
|
||||
private readonly warnings = new Set<string>();
|
||||
@@ -73,6 +49,21 @@ class Interpreter {
|
||||
|
||||
switch (node.type) {
|
||||
case "Literal":
|
||||
if (node.regex !== undefined) {
|
||||
const regex = node.regex as { pattern?: unknown; flags?: unknown };
|
||||
if (
|
||||
typeof regex.pattern !== "string" ||
|
||||
regex.pattern.length > 128 ||
|
||||
typeof regex.flags !== "string" ||
|
||||
/[^gimsu]/u.test(regex.flags) ||
|
||||
/\\[1-9]|\(\?<[=!]|(?:\+|\*|\{\d+(?:,\d*)?\})\)?(?:\+|\*|\{)/u.test(regex.pattern)
|
||||
) {
|
||||
throw new SafeJsxError("UNSAFE_REGEX: Invalid regular expression literal");
|
||||
}
|
||||
return new RegExp(regex.pattern, regex.flags);
|
||||
}
|
||||
if (typeof node.value === "bigint")
|
||||
throw new SafeJsxError("BIGINT_NOT_SUPPORTED: Use Number for widget values");
|
||||
return node.value;
|
||||
case "Identifier":
|
||||
return environment.get(String(node.name));
|
||||
@@ -81,7 +72,7 @@ class Interpreter {
|
||||
case "JSXFragment":
|
||||
return this.evaluateJsxFragment(node, environment, depth + 1);
|
||||
case "JSXText": {
|
||||
const text = this.budget.string(jsxText(String(node.value ?? "")));
|
||||
const text = this.budget.string(normalizeCustomJsxText(String(node.value ?? "")));
|
||||
if (text) this.budget.rendered();
|
||||
return text || null;
|
||||
}
|
||||
@@ -110,11 +101,19 @@ class Interpreter {
|
||||
case "CallExpression":
|
||||
return this.evaluateCall(node, environment, depth + 1);
|
||||
case "ArrowFunctionExpression":
|
||||
return this.createCallback(node, environment);
|
||||
throw new SafeJsxError(
|
||||
"CALLBACK_VALUE_NOT_ALLOWED: Callbacks are only allowed in safe collection methods and trusted slots",
|
||||
);
|
||||
case "TemplateLiteral":
|
||||
return this.evaluateTemplateLiteral(node, environment, depth + 1);
|
||||
case "ChainExpression":
|
||||
return this.evaluate(asNode(node.expression, "chain expression"), environment, depth + 1);
|
||||
case "AssignmentExpression":
|
||||
case "UpdateExpression":
|
||||
case "NewExpression":
|
||||
case "AwaitExpression":
|
||||
case "YieldExpression":
|
||||
throw new SafeJsxError(`UNSUPPORTED_BLOCK_STATEMENT: '${node.type}' is not allowed in safe expressions`);
|
||||
default:
|
||||
throw new SafeJsxError(`Unsupported expression: ${node.type}`);
|
||||
}
|
||||
@@ -134,8 +133,8 @@ class Interpreter {
|
||||
budget: this.budget,
|
||||
warnings: this.warnings,
|
||||
evaluate: (node, environment, depth) => this.evaluate(node, environment, depth),
|
||||
renderCallback: (callback, args) =>
|
||||
new Interpreter(this.components, callback.environment, this.limits).runCallback(callback, args, 0) as ReactNode,
|
||||
createCallback: (node, environment) => this.createCallback(node, environment),
|
||||
renderCallback: (callback, args, depth) => this.runCallback(callback, args, depth) as ReactNode,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -277,11 +276,26 @@ class Interpreter {
|
||||
|
||||
private evaluateCall(node: AstNode, environment: Environment, depth: number): unknown {
|
||||
if (node.optional) throw new SafeJsxError("Optional calls are not supported");
|
||||
const args = asNodeArray(node.arguments, "call arguments").map((argument) => {
|
||||
const callee = asNode(node.callee, "call target");
|
||||
const argumentNodes = asNodeArray(node.arguments, "call arguments");
|
||||
if (callee.type === "ArrowFunctionExpression")
|
||||
throw new SafeJsxError("CALL_TARGET_NOT_ALLOWED: Inline IIFEs are not supported");
|
||||
const callbackMethod =
|
||||
callee.type === "MemberExpression"
|
||||
? callee.computed
|
||||
? staticPropertyName(asNode(callee.property, "method property"))
|
||||
: normalizedProperty(asNode(callee.property, "method property").name)
|
||||
: null;
|
||||
const args = argumentNodes.map((argument) => {
|
||||
if (argument.type === "SpreadElement") throw new SafeJsxError("Spread call arguments are not supported");
|
||||
if (argument.type === "ArrowFunctionExpression") {
|
||||
if (!callbackMethod || !CUSTOM_JSX_CALLBACK_METHODS.has(callbackMethod)) {
|
||||
throw new SafeJsxError("CALLBACK_VALUE_NOT_ALLOWED: Callback argument is not allowed for this call");
|
||||
}
|
||||
return this.createCallback(argument, environment);
|
||||
}
|
||||
return this.evaluate(argument, environment, depth + 1);
|
||||
});
|
||||
const callee = asNode(node.callee, "call target");
|
||||
|
||||
if (callee.type === "MemberExpression") {
|
||||
const receiver = this.evaluate(asNode(callee.object, "method receiver"), environment, depth + 1);
|
||||
@@ -317,27 +331,14 @@ class Interpreter {
|
||||
}
|
||||
|
||||
private createCallback(node: AstNode, environment: Environment): InterpreterCallback {
|
||||
if (node.async || node.generator || node.expression === false) {
|
||||
throw new SafeJsxError("Only synchronous expression-bodied arrow callbacks are supported");
|
||||
}
|
||||
const params = asNodeArray(node.params, "callback parameters").map((param) => {
|
||||
if (param.type !== "Identifier") throw new SafeJsxError("Callback parameters must be identifiers");
|
||||
return normalizedProperty(param.name);
|
||||
});
|
||||
return {
|
||||
kind: INTERPRETER_CALLBACK,
|
||||
params,
|
||||
body: asNode(node.body, "callback body"),
|
||||
environment,
|
||||
};
|
||||
return createInterpreterCallback(node, environment);
|
||||
}
|
||||
|
||||
private runCallback(callback: InterpreterCallback, args: unknown[], depth: number): unknown {
|
||||
const values: Record<string, unknown> = Object.create(null);
|
||||
callback.params.forEach((name, index) => {
|
||||
values[name] = args[index];
|
||||
return runInterpreterCallback(callback, args, depth, {
|
||||
budget: this.budget,
|
||||
evaluate: (node, environment, callbackDepth) => this.evaluate(node, environment, callbackDepth),
|
||||
});
|
||||
return this.evaluate(callback.body, new Environment(values, callback.environment), depth + 1);
|
||||
}
|
||||
|
||||
private evaluateTemplateLiteral(node: AstNode, environment: Environment, depth: number): string {
|
||||
@@ -355,33 +356,11 @@ class Interpreter {
|
||||
}
|
||||
}
|
||||
|
||||
function parseTemplate(template: string): AstNode {
|
||||
if (template.length > CUSTOM_JSX_LIMITS.templateLength) {
|
||||
throw new SafeJsxError(`Template exceeds the ${CUSTOM_JSX_LIMITS.templateLength} character limit`);
|
||||
}
|
||||
let program: AstNode;
|
||||
try {
|
||||
program = JsxParser.parse(`<>${template}</>`, {
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
allowAwaitOutsideFunction: false,
|
||||
allowReturnOutsideFunction: false,
|
||||
}) as unknown as AstNode;
|
||||
} catch (error) {
|
||||
throw new SafeJsxError(error instanceof Error ? error.message : "Unable to parse JSX template");
|
||||
}
|
||||
const body = asNodeArray(program.body, "program body");
|
||||
if (body.length !== 1 || body[0]?.type !== "ExpressionStatement") {
|
||||
throw new SafeJsxError("Template must contain JSX only");
|
||||
}
|
||||
return asNode(body[0].expression, "template expression");
|
||||
}
|
||||
|
||||
export function renderSafeJsx({ template, components, bindings, budgets }: RenderSafeJsxOptions): SafeJsxRenderResult {
|
||||
const limits: EvaluationBudgets = { ...DEFAULT_BUDGETS, ...budgets };
|
||||
for (const [name, value] of Object.entries(limits)) {
|
||||
if (!Number.isSafeInteger(value) || value <= 0) throw new SafeJsxError(`Invalid interpreter budget: ${name}`);
|
||||
}
|
||||
const root = parseTemplate(template);
|
||||
const root = parseCustomJsxTemplate(template);
|
||||
return new Interpreter(components, new Environment(bindings), limits).render(root);
|
||||
}
|
||||
@@ -1,19 +1,13 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { createElement, Fragment } from "react";
|
||||
|
||||
import { asNode, asNodeArray, isInterpreterCallback, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Budget, Environment, InterpreterCallback } from "./interpreter-foundation";
|
||||
import { normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
import { asNode, asNodeArray, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { AstNode, Environment } from "./interpreter-foundation";
|
||||
import type { JsxEmitterContext } from "./emitter-context";
|
||||
import { resolveCustomJsxComponentName } from "../core/component-registry";
|
||||
import { diagnoseCustomJsxProps, normalizedProperty, sanitizeCustomJsxProps } from "./safe-properties";
|
||||
import { CUSTOM_JSX_BLOCKED_TAGS } from "./policy";
|
||||
|
||||
export interface JsxEmitterContext {
|
||||
components: Readonly<Record<string, ComponentType<never>>>;
|
||||
budget: Budget;
|
||||
warnings: Set<string>;
|
||||
evaluate(node: AstNode, environment: Environment, depth: number): unknown;
|
||||
renderCallback(callback: InterpreterCallback, args: unknown[]): ReactNode;
|
||||
}
|
||||
|
||||
export function emitJsxFragment(
|
||||
node: AstNode,
|
||||
environment: Environment,
|
||||
@@ -35,11 +29,12 @@ export function emitJsxElement(
|
||||
): ReactNode {
|
||||
const opening = asNode(node.openingElement, "JSX opening element");
|
||||
const tag = jsxTagName(asNode(opening.name, "JSX tag"));
|
||||
const resolvedTag = resolveCustomJsxComponentName(tag);
|
||||
if (CUSTOM_JSX_BLOCKED_TAGS.has(tag.toLowerCase())) {
|
||||
context.warnings.add(`Blocked element: ${tag}`);
|
||||
return null;
|
||||
}
|
||||
const component = context.components[tag];
|
||||
const component = context.components[resolvedTag];
|
||||
if (!component) {
|
||||
context.warnings.add(`Unknown or unavailable component: ${tag}`);
|
||||
return null;
|
||||
@@ -54,32 +49,26 @@ 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) =>
|
||||
context.evaluate(child, environment, depth + 1),
|
||||
);
|
||||
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");
|
||||
const children = asNodeArray(node.children, "JSX children").map((child) => {
|
||||
const expression =
|
||||
child.type === "JSXExpressionContainer" ? asNode(child.expression, "JSX child expression") : null;
|
||||
if (resolvedTag === "SubFetch" && expression?.type === "ArrowFunctionExpression") {
|
||||
const callback = context.createCallback(expression, environment);
|
||||
return (value: unknown) => context.renderCallback(callback, [value], depth + 1);
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
return context.evaluate(child, environment, depth + 1);
|
||||
});
|
||||
diagnoseCustomJsxProps(rawProps, resolvedTag).forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const props = sanitizeCustomJsxProps(rawProps, resolvedTag);
|
||||
context.budget.rendered();
|
||||
return createElement(component, props as never, ...(children as ReactNode[]));
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ export const CUSTOM_JSX_LIMITS = Object.freeze({
|
||||
templateLength: 50_000,
|
||||
astDepth: 64,
|
||||
operations: 25_000,
|
||||
collectionItems: 2_000,
|
||||
collectionItems: 4_000,
|
||||
renderedNodes: 10_000,
|
||||
stringLength: 200_000,
|
||||
});
|
||||
@@ -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,14 +80,40 @@ export const CUSTOM_JSX_BLOCKED_STYLE_KEYS: ReadonlySet<string> = new Set([
|
||||
"left",
|
||||
"mask",
|
||||
"pointerEvents",
|
||||
"pos",
|
||||
"position",
|
||||
"right",
|
||||
"top",
|
||||
"zIndex",
|
||||
]);
|
||||
|
||||
const CUSTOM_JSX_BLOCKED_POSITION_PROPS: ReadonlySet<string> = new Set([
|
||||
"bottom",
|
||||
"inset",
|
||||
"left",
|
||||
"pos",
|
||||
"right",
|
||||
"top",
|
||||
"zIndex",
|
||||
]);
|
||||
|
||||
export function normalizeCustomJsxProperty(value: unknown): string {
|
||||
return String(value ?? "")
|
||||
.normalize("NFKC")
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
export function isBlockedCustomJsxLexicalBinding(name: string): boolean {
|
||||
return CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(name));
|
||||
}
|
||||
|
||||
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_POSITION_PROPS.has(name) ||
|
||||
(name !== "bind" && CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(name)))
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
export function isSafeCustomJsxUrl(value: unknown) {
|
||||
if (typeof value !== "string") return false;
|
||||
if (value.startsWith("#")) return true;
|
||||
if (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;
|
||||
}
|
||||
}
|
||||
|
||||
export function getScopedCustomJsxControlName(scopeId: string, name: string) {
|
||||
const safeScope = scopeId.replaceAll(/[^A-Za-z0-9_-]/gu, "_");
|
||||
const safeName = encodeURIComponent(name).replaceAll("%", "_");
|
||||
return `custom-widget-${safeScope}-${safeName}`;
|
||||
}
|
||||
|
||||
export function getInvalidCustomJsxPropValueReason(componentName: string, propName: string, value: unknown) {
|
||||
if (
|
||||
["DateTimePicker", "InlineDateTimePicker"].includes(componentName) &&
|
||||
propName === "type" &&
|
||||
![undefined, "default", "range"].includes(value as undefined | string)
|
||||
) {
|
||||
return `${componentName}.type supports only 'default' or 'range'`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,15 +1,21 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createElement, useEffect, useRef, useState } from "react";
|
||||
import { createContext, createElement, useContext, useEffect, useId, 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,
|
||||
getCustomJsxBindingType,
|
||||
} from "../core/component-registry";
|
||||
import type { CustomJsxBindingType } from "../core/component-registry";
|
||||
import { ActionButton, ToggleSwitch } from "../runtime/actions";
|
||||
import { SubData } from "../runtime/data";
|
||||
import { RefreshButton } from "../runtime/refresh-button";
|
||||
import { SubFetch } from "../runtime/sub-fetch";
|
||||
import { Collapsible, PaginatedList, StatBar, TabPanel, TabsContainer, TypeBadge } from "./interactive-components";
|
||||
import { getScopedCustomJsxControlName, isSafeCustomJsxUrl } from "./runtime-component-policy";
|
||||
import { sanitizeCustomJsxProps } from "./safe-properties";
|
||||
|
||||
type Namespace = Readonly<Record<string, unknown>>;
|
||||
@@ -27,23 +33,157 @@ function resolveExport(namespace: Namespace, name: string): ComponentType<never>
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function safeUrl(value: unknown) {
|
||||
return typeof value === "string" && (/^https?:\/\//iu.test(value) || value.startsWith("/") || value.startsWith("#"));
|
||||
export type WidgetInputValue = string | number | boolean | string[] | number[];
|
||||
export type WidgetInputType = CustomJsxBindingType;
|
||||
interface CustomJsxInputsContextValue {
|
||||
scopeId: string;
|
||||
inputs: Record<string, WidgetInputValue>;
|
||||
inputTypes: Record<string, WidgetInputType>;
|
||||
registerInput(name: string, type: WidgetInputType, initialValue: WidgetInputValue): void;
|
||||
setInputValue(name: string, type: WidgetInputType, value: WidgetInputValue): void;
|
||||
}
|
||||
|
||||
function wrap(component: ComponentType<never>, additions: Record<string, unknown> = {}) {
|
||||
return function SafeComponent(props: Record<string, unknown>) {
|
||||
return createElement(component, { ...sanitizeCustomJsxProps(props), ...additions } as never);
|
||||
const CustomJsxInputsContext = createContext<CustomJsxInputsContextValue | null>(null);
|
||||
|
||||
export function CustomJsxInputsProvider({
|
||||
children,
|
||||
scopeId,
|
||||
inputs,
|
||||
inputTypes,
|
||||
registerInput,
|
||||
setInputValue,
|
||||
}: CustomJsxInputsContextValue & { children: ReactNode }) {
|
||||
return (
|
||||
<CustomJsxInputsContext.Provider value={{ scopeId, inputs, inputTypes, registerInput, setInputValue }}>
|
||||
{children}
|
||||
</CustomJsxInputsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
const checkedComponents = new Set(["Checkbox", "Switch"]);
|
||||
const openedComponents = new Set(["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",
|
||||
"TimePicker",
|
||||
"YearPickerInput",
|
||||
]);
|
||||
const modalPickerComponents = new Set(["DatePickerInput", "DateTimePicker", "MonthPickerInput", "YearPickerInput"]);
|
||||
const namedRadioComponents = new Set(["Radio", "Radio.Card", "Radio.Group", "RadioCard", "RadioGroup"]);
|
||||
const buttonRootComponents = new Set(["ActionIcon", "Burger", "Button", "CloseButton", "UnstyledButton"]);
|
||||
|
||||
function extractEventValue(value: unknown, checked: boolean): WidgetInputValue | 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 detachedScopeId = useId();
|
||||
const binding = typeof props.bind === "string" ? props.bind : undefined;
|
||||
const context = useContext(CustomJsxInputsContext);
|
||||
const sanitized = sanitizeCustomJsxProps(props, componentName);
|
||||
if (namedRadioComponents.has(componentName) && typeof sanitized.name === "string") {
|
||||
sanitized.name = getScopedCustomJsxControlName(context?.scopeId ?? detachedScopeId, sanitized.name);
|
||||
}
|
||||
delete sanitized.bind;
|
||||
const inputType = getCustomJsxBindingType(componentName, sanitized);
|
||||
const initialValue = getInitialInputValue(inputType, sanitized);
|
||||
const isBound = Boolean(binding && context && inputType && customJsxBindableComponentNames.has(componentName));
|
||||
useEffect(() => {
|
||||
if (isBound && binding && context && inputType) context.registerInput(binding, inputType, initialValue);
|
||||
}, [binding, context, initialValue, inputType, isBound]);
|
||||
if (!isBound || !binding || !context || !inputType) return sanitized;
|
||||
delete sanitized.defaultValue;
|
||||
delete sanitized.defaultChecked;
|
||||
const currentValue = context.inputs[binding] ?? initialValue;
|
||||
|
||||
const update = (value: unknown, checked = false) => {
|
||||
const extracted = extractEventValue(value, checked);
|
||||
context.setInputValue(binding, inputType, extracted ?? emptyInputValue(inputType));
|
||||
};
|
||||
if (checkedComponents.has(componentName)) {
|
||||
return {
|
||||
...sanitized,
|
||||
checked: Boolean(currentValue),
|
||||
onChange: (event: unknown) => update(event, true),
|
||||
};
|
||||
}
|
||||
if (openedComponents.has(componentName)) {
|
||||
return { ...sanitized, opened: Boolean(currentValue), onChange: update, withinPortal: false };
|
||||
}
|
||||
if (activeComponents.has(componentName)) {
|
||||
return { ...sanitized, active: Number(currentValue), onStepClick: update };
|
||||
}
|
||||
return { ...sanitized, value: currentValue, onChange: update };
|
||||
}
|
||||
|
||||
function getInitialInputValue(type: WidgetInputType | null, props: Record<string, unknown>): WidgetInputValue {
|
||||
if (!type) return "";
|
||||
const candidate = type === "boolean" ? props.defaultChecked : props.defaultValue;
|
||||
if (type === "boolean" && typeof candidate === "boolean") return candidate;
|
||||
if (type === "number" && typeof candidate === "number") return candidate;
|
||||
if (type === "string" && typeof candidate === "string") return candidate;
|
||||
if (type === "string[]" && Array.isArray(candidate) && candidate.every((item) => typeof item === "string"))
|
||||
return candidate;
|
||||
if (type === "number[]" && Array.isArray(candidate) && candidate.every((item) => typeof item === "number"))
|
||||
return candidate;
|
||||
return emptyInputValue(type);
|
||||
}
|
||||
|
||||
function emptyInputValue(type: WidgetInputType): WidgetInputValue {
|
||||
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: isSafeCustomJsxUrl(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 +230,17 @@ 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 (modalPickerComponents.has(descriptor.name)) additions.dropdownType = "popover";
|
||||
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,29 +257,12 @@ 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 });
|
||||
}
|
||||
Object.assign(components, {
|
||||
CopyButton: createCopyButton(adapters.copyLabels),
|
||||
PaginatedList,
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
export const CUSTOM_JSX_BINARY_OPERATORS: ReadonlySet<string> = new Set([
|
||||
"+",
|
||||
"-",
|
||||
"*",
|
||||
"/",
|
||||
"%",
|
||||
"**",
|
||||
"<",
|
||||
"<=",
|
||||
">",
|
||||
">=",
|
||||
"==",
|
||||
"!=",
|
||||
"===",
|
||||
"!==",
|
||||
]);
|
||||
|
||||
export const CUSTOM_JSX_CALLBACK_METHODS: ReadonlySet<string> = new Set([
|
||||
"every",
|
||||
"filter",
|
||||
"find",
|
||||
"findIndex",
|
||||
"flatMap",
|
||||
"map",
|
||||
"reduce",
|
||||
"some",
|
||||
"sort",
|
||||
]);
|
||||
|
||||
export const CUSTOM_JSX_SAFE_VALUE_METHODS: ReadonlySet<string> = new Set([
|
||||
...CUSTOM_JSX_CALLBACK_METHODS,
|
||||
"at",
|
||||
"charAt",
|
||||
"concat",
|
||||
"endsWith",
|
||||
"flat",
|
||||
"flatMap",
|
||||
"includes",
|
||||
"indexOf",
|
||||
"join",
|
||||
"lastIndexOf",
|
||||
"localeCompare",
|
||||
"match",
|
||||
"padEnd",
|
||||
"padStart",
|
||||
"pop",
|
||||
"repeat",
|
||||
"replace",
|
||||
"replaceAll",
|
||||
"reverse",
|
||||
"slice",
|
||||
"search",
|
||||
"split",
|
||||
"startsWith",
|
||||
"substring",
|
||||
"toFixed",
|
||||
"toLocaleString",
|
||||
"toLowerCase",
|
||||
"toPrecision",
|
||||
"toString",
|
||||
"toUpperCase",
|
||||
"trim",
|
||||
"trimEnd",
|
||||
"trimStart",
|
||||
"test",
|
||||
]);
|
||||
@@ -1,10 +1,13 @@
|
||||
import { customJsxSupportedPropsByName } from "../core";
|
||||
import { isValidElement } from "react";
|
||||
|
||||
import { isInterpreterCallback, SafeJsxError } from "./interpreter-foundation";
|
||||
import { customJsxComponentByName } from "../core/component-registry";
|
||||
import { getInvalidCustomJsxPropValueReason } from "./runtime-component-policy";
|
||||
import {
|
||||
CUSTOM_JSX_BLOCKED_PROPERTIES,
|
||||
CUSTOM_JSX_BLOCKED_PROPS,
|
||||
CUSTOM_JSX_BLOCKED_STYLE_KEYS,
|
||||
CUSTOM_JSX_URL_PROPS,
|
||||
isBlockedCustomJsxProp,
|
||||
normalizeCustomJsxProperty,
|
||||
} from "./policy";
|
||||
|
||||
@@ -61,7 +64,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 +74,129 @@ 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,
|
||||
): 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;
|
||||
const blockedProps = componentName
|
||||
? new Set(customJsxComponentByName.get(componentName)?.blockedProps.map(({ name }) => name) ?? [])
|
||||
: undefined;
|
||||
return sanitizeObject(props, blockedProps, componentName);
|
||||
}
|
||||
|
||||
function sanitizeObject(
|
||||
value: Readonly<Record<string, unknown>>,
|
||||
componentBlockedProps?: ReadonlySet<string>,
|
||||
componentName?: string,
|
||||
): Record<string, unknown> {
|
||||
const safe: Record<string, unknown> = Object.create(null);
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (isBlockedCustomJsxProp(key) || componentBlockedProps?.has(key)) continue;
|
||||
if (componentName && getInvalidCustomJsxPropValueReason(componentName, key, child)) 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 (typeof value === "function" || isInterpreterCallback(value)) return undefined;
|
||||
if (isValidElement(value)) return value;
|
||||
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[] = [];
|
||||
const blockedProps = new Map(
|
||||
customJsxComponentByName.get(componentName)?.blockedProps.map(({ name, reason }) => [name, reason]) ?? [],
|
||||
);
|
||||
diagnoseObject(props, componentName, diagnostics, blockedProps, componentName);
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
function diagnoseObject(
|
||||
value: Readonly<Record<string, unknown>>,
|
||||
path: string,
|
||||
diagnostics: string[],
|
||||
componentBlockedProps?: ReadonlyMap<string, string>,
|
||||
componentName?: string,
|
||||
) {
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
const propertyPath = `${path}.${key}`;
|
||||
const componentBlockedReason = componentBlockedProps?.get(key);
|
||||
if (componentBlockedReason) {
|
||||
diagnostics.push(
|
||||
`BLOCKED_CAPABILITY: Prop '${propertyPath}' is not allowed because ${componentBlockedReason.toLowerCase()}`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const invalidValueReason = componentName ? getInvalidCustomJsxPropValueReason(componentName, key, child) : null;
|
||||
if (invalidValueReason) {
|
||||
diagnostics.push(`INVALID_PROP_VALUE: '${propertyPath}' is not allowed because ${invalidValueReason}`);
|
||||
continue;
|
||||
}
|
||||
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 (isValidElement(child)) continue;
|
||||
if (key === "data" || key === "series") continue;
|
||||
if (Array.isArray(child)) {
|
||||
child.forEach((entry, index) => {
|
||||
if (isValidElement(entry)) return;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { numericArgument, SafeJsxError } from "./interpreter-foundation";
|
||||
import type { InterpreterMethodContext } from "./interpreter-method-context";
|
||||
|
||||
export function callStringMethod(
|
||||
receiver: string,
|
||||
method: string,
|
||||
args: unknown[],
|
||||
context: InterpreterMethodContext,
|
||||
): { handled: boolean; value?: unknown } {
|
||||
switch (method) {
|
||||
case "toUpperCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toUpperCase()) };
|
||||
case "toLowerCase":
|
||||
return { handled: true, value: context.budget.string(receiver.toLowerCase()) };
|
||||
case "trim":
|
||||
return { handled: true, value: context.budget.string(receiver.trim()) };
|
||||
case "trimStart":
|
||||
return { handled: true, value: context.budget.string(receiver.trimStart()) };
|
||||
case "trimEnd":
|
||||
return { handled: true, value: context.budget.string(receiver.trimEnd()) };
|
||||
case "replace": {
|
||||
const search = args[0] instanceof RegExp ? args[0] : String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
if (search instanceof RegExp)
|
||||
return { handled: true, value: context.budget.string(receiver.replace(search, replacement)) };
|
||||
const matchIndex = receiver.indexOf(search);
|
||||
if (matchIndex === -1) return { handled: true, value: context.budget.string(receiver) };
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.slice(0, matchIndex) + replacement + receiver.slice(matchIndex + search.length),
|
||||
),
|
||||
};
|
||||
}
|
||||
case "replaceAll": {
|
||||
const search = args[0] instanceof RegExp ? args[0] : String(args[0] ?? "");
|
||||
const replacement = String(args[1] ?? "");
|
||||
if (search instanceof RegExp) {
|
||||
if (!search.global) throw new SafeJsxError("replaceAll() requires a global regular expression");
|
||||
return { handled: true, value: context.budget.string(receiver.replaceAll(search, replacement)) };
|
||||
}
|
||||
if (search.length === 0) return { handled: true, value: context.budget.string(receiver) };
|
||||
let result = "";
|
||||
let cursor = 0;
|
||||
while (cursor < receiver.length) {
|
||||
const matchIndex = receiver.indexOf(search, cursor);
|
||||
if (matchIndex === -1) {
|
||||
result += receiver.slice(cursor);
|
||||
break;
|
||||
}
|
||||
result += receiver.slice(cursor, matchIndex) + replacement;
|
||||
cursor = matchIndex + search.length;
|
||||
}
|
||||
return { handled: true, value: context.budget.string(result) };
|
||||
}
|
||||
case "indexOf":
|
||||
return { handled: true, value: receiver.indexOf(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "lastIndexOf": {
|
||||
const fromIndex = args[1] !== undefined ? numericArgument(args[1], receiver.length) : undefined;
|
||||
return { handled: true, value: receiver.lastIndexOf(String(args[0] ?? ""), fromIndex) };
|
||||
}
|
||||
case "repeat": {
|
||||
const maxCount = receiver.length > 0 ? Math.floor(200_001 / receiver.length) : 0;
|
||||
const count = Math.max(0, Math.min(numericArgument(args[0], 0), maxCount));
|
||||
return { handled: true, value: context.budget.string(receiver.repeat(count).slice(0, 200_001)) };
|
||||
}
|
||||
case "slice":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.slice(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "substring":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(receiver.substring(numericArgument(args[0], 0), args[1] as number | undefined)),
|
||||
};
|
||||
case "includes":
|
||||
return { handled: true, value: receiver.includes(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "startsWith":
|
||||
return { handled: true, value: receiver.startsWith(String(args[0] ?? ""), numericArgument(args[1], 0)) };
|
||||
case "endsWith":
|
||||
return { handled: true, value: receiver.endsWith(String(args[0] ?? ""), args[1] as number | undefined) };
|
||||
case "padStart":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padStart(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "padEnd":
|
||||
return {
|
||||
handled: true,
|
||||
value: context.budget.string(
|
||||
receiver.padEnd(Math.min(numericArgument(args[0], 0), 200_001), String(args[1] ?? " ")),
|
||||
),
|
||||
};
|
||||
case "charAt":
|
||||
return { handled: true, value: receiver.charAt(numericArgument(args[0], 0)) };
|
||||
case "localeCompare":
|
||||
return { handled: true, value: receiver.localeCompare(String(args[0] ?? "")) };
|
||||
case "split": {
|
||||
const limit = Math.max(0, Math.min(2_000, numericArgument(args[1], 2_000)));
|
||||
const separator = args[0] instanceof RegExp ? args[0] : args[0] === undefined ? undefined : String(args[0]);
|
||||
const split = separator === undefined ? [receiver] : receiver.split(separator, limit);
|
||||
context.budget.collection(split.length);
|
||||
return { handled: true, value: split };
|
||||
}
|
||||
case "match": {
|
||||
const pattern = args[0] instanceof RegExp ? args[0] : String(args[0] ?? "");
|
||||
const matches = receiver.match(pattern);
|
||||
if (matches) context.budget.collection(matches.length);
|
||||
return { handled: true, value: matches ? [...matches] : null };
|
||||
}
|
||||
case "search":
|
||||
return { handled: true, value: receiver.search(args[0] instanceof RegExp ? args[0] : String(args[0] ?? "")) };
|
||||
default:
|
||||
return { handled: false };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user