feat!: release v2 (#6545)
Co-authored-by: Artur <145776561+arturict@users.noreply.github.com> Co-authored-by: arturict <arturict@users.noreply.github.com> Co-authored-by: Thomas <thomas@ajnart.fr> Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com> Co-authored-by: Danura30082 <danura30082+github@gmail.com> Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com> Co-authored-by: ajnart <thomas@ajnart.fr> Co-authored-by: ajnart <thomas@ajnart.dev> Co-authored-by: chenjun <chenjun@foxmail.com> Co-authored-by: Wikibear <wikibear@users.noreply.github.com> Co-authored-by: Bergasha <bergasha@gmail.com> Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com> Co-authored-by: Lucas Araujo <lucas.lra@gmail.com> Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com> Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social> Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com> Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com> Co-authored-by: thrawnx <tight.bulb9384@fastmail.com> Co-authored-by: Chris <58918656+nordada@users.noreply.github.com> Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com> Co-authored-by: Yanis <naamaneyanis@gmail.com> Co-authored-by: Wikibear <me@sej.de> Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386
-139176
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,328 @@
|
||||
import { customJsxCatalogComponentByName } from "../core/component-catalog";
|
||||
import {
|
||||
customJsxBindableComponentNames,
|
||||
customJsxComponentByName,
|
||||
customJsxSupportedPropsByName,
|
||||
resolveCustomJsxComponentName,
|
||||
} from "../core/component-registry";
|
||||
import type { AstNode } from "./analyzer-ast";
|
||||
import { containsEscapingCallback, nodeOf, nodesOf, staticPropertyName } from "./analyzer-ast";
|
||||
import { closestCustomJsxComponentName, customJsxTagName, isSafeLiteralCustomJsxUrl } from "./analyzer-language";
|
||||
import {
|
||||
CUSTOM_JSX_BINDING_IDENTIFIER_PATTERN,
|
||||
CUSTOM_JSX_LIMITS,
|
||||
CUSTOM_JSX_URL_PROPS,
|
||||
isBlockedCustomJsxProp,
|
||||
} from "./policy";
|
||||
import { getInvalidCustomJsxPropValueReason } from "./runtime-component-policy";
|
||||
|
||||
interface AnalyzerJsxContext {
|
||||
requestParameters?: ReadonlyMap<string, ReadonlySet<string>>;
|
||||
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;
|
||||
}
|
||||
|
||||
const componentsRequiringRequestId = new Set(["SubFetch", "ActionButton", "ToggleSwitch"]);
|
||||
const componentsWithLiteralRequestId = new Set([...componentsRequiringRequestId, "RefreshButton"]);
|
||||
|
||||
function staticParameterKeys(expression: AstNode | null, depth = 0): { keys: Set<string>; complete: boolean } {
|
||||
const keys = new Set<string>();
|
||||
if (!expression) return { keys, complete: true };
|
||||
if (expression.type !== "ObjectExpression" || depth > CUSTOM_JSX_LIMITS.astDepth) return { keys, complete: false };
|
||||
let complete = true;
|
||||
for (const property of nodesOf(expression.properties)) {
|
||||
if (property.type === "SpreadElement") {
|
||||
const spread = staticParameterKeys(nodeOf(property.argument), depth + 1);
|
||||
spread.keys.forEach((key) => keys.add(key));
|
||||
complete &&= spread.complete;
|
||||
continue;
|
||||
}
|
||||
const key = nodeOf(property.key);
|
||||
let name = staticPropertyName(key);
|
||||
if (!property.computed && key?.type === "Identifier") name = String(key.name);
|
||||
if (name === undefined) complete = false;
|
||||
else keys.add(name);
|
||||
}
|
||||
return { keys, complete };
|
||||
}
|
||||
const interactiveTriggerContentComponentNames = new Set([
|
||||
"ActionButton",
|
||||
"ActionIcon",
|
||||
"Anchor",
|
||||
"Autocomplete",
|
||||
"Checkbox",
|
||||
"Checkbox.Card",
|
||||
"Chip",
|
||||
"CloseButton",
|
||||
"ColorInput",
|
||||
"ColorPicker",
|
||||
"DateInput",
|
||||
"DatePicker",
|
||||
"DatePickerInput",
|
||||
"DateTimePicker",
|
||||
"InlineDateTimePicker",
|
||||
"Input",
|
||||
"JsonInput",
|
||||
"MaskInput",
|
||||
"MonthPicker",
|
||||
"MonthPickerInput",
|
||||
"MultiSelect",
|
||||
"NativeSelect",
|
||||
"NumberInput",
|
||||
"PasswordInput",
|
||||
"PinInput",
|
||||
"Radio",
|
||||
"Radio.Card",
|
||||
"RangeSlider",
|
||||
"Rating",
|
||||
"SegmentedControl",
|
||||
"Select",
|
||||
"Slider",
|
||||
"Switch",
|
||||
"TagsInput",
|
||||
"TextInput",
|
||||
"Textarea",
|
||||
"TimeInput",
|
||||
"TimePicker",
|
||||
"TreeSelect",
|
||||
"UnstyledButton",
|
||||
"YearPickerInput",
|
||||
"Button",
|
||||
"RefreshButton",
|
||||
"ToggleSwitch",
|
||||
]);
|
||||
|
||||
const isManualSubFetchTrigger = (attributes: readonly AstNode[]) => {
|
||||
const triggerAttribute = attributes.find((attribute) => {
|
||||
if (attribute.type !== "JSXAttribute") return false;
|
||||
const attributeName = nodeOf(attribute.name);
|
||||
return attributeName?.type === "JSXIdentifier" && attributeName.name === "trigger";
|
||||
});
|
||||
const triggerValue = nodeOf(triggerAttribute?.value);
|
||||
const triggerExpression =
|
||||
triggerValue?.type === "JSXExpressionContainer" ? nodeOf(triggerValue.expression) : triggerValue;
|
||||
if (triggerExpression?.type === "Literal") return triggerExpression.value === "manual";
|
||||
return triggerExpression !== null;
|
||||
};
|
||||
|
||||
const findInteractiveTriggerContentNode = (root: AstNode) => {
|
||||
const pending = [root];
|
||||
while (pending.length > 0) {
|
||||
const current = pending.pop();
|
||||
if (!current) continue;
|
||||
|
||||
if (current.type === "JSXElement") {
|
||||
const opening = nodeOf(current.openingElement);
|
||||
const nameNode = opening ? nodeOf(opening.name) : null;
|
||||
const name = nameNode ? customJsxTagName(nameNode) : null;
|
||||
const resolvedName = name ? resolveCustomJsxComponentName(name) : null;
|
||||
if (resolvedName && interactiveTriggerContentComponentNames.has(resolvedName)) return opening ?? current;
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(current)) {
|
||||
if (["end", "loc", "start", "type"].includes(key)) continue;
|
||||
if (Array.isArray(value)) {
|
||||
pending.push(...nodesOf(value));
|
||||
continue;
|
||||
}
|
||||
const child = nodeOf(value);
|
||||
if (child) pending.push(child);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
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;
|
||||
const attributes = nodesOf(opening.attributes);
|
||||
if (resolvedName && componentsWithLiteralRequestId.has(resolvedName)) {
|
||||
const requestIdAttribute = attributes.find((attribute) => {
|
||||
if (attribute.type !== "JSXAttribute") return false;
|
||||
const attributeName = nodeOf(attribute.name);
|
||||
return attributeName?.type === "JSXIdentifier" && attributeName.name === "requestId";
|
||||
});
|
||||
const requestIdValue = requestIdAttribute ? nodeOf(requestIdAttribute.value) : null;
|
||||
const requestIdExpression =
|
||||
requestIdValue?.type === "JSXExpressionContainer" ? nodeOf(requestIdValue.expression) : null;
|
||||
const requestIdLiteral = requestIdValue?.type === "Literal" ? requestIdValue : requestIdExpression;
|
||||
const requiresRequestId = componentsRequiringRequestId.has(resolvedName);
|
||||
const hasInvalidRequestId =
|
||||
requestIdAttribute !== undefined &&
|
||||
(requestIdLiteral?.type !== "Literal" ||
|
||||
typeof requestIdLiteral.value !== "string" ||
|
||||
requestIdLiteral.value.trim().length === 0);
|
||||
if ((!requestIdAttribute && requiresRequestId) || hasInvalidRequestId) {
|
||||
context.add(requestIdAttribute ?? opening, `${resolvedName} must use a literal requestId`);
|
||||
}
|
||||
if (componentsRequiringRequestId.has(resolvedName) && typeof requestIdLiteral?.value === "string") {
|
||||
const expected = context.requestParameters?.get(requestIdLiteral.value);
|
||||
let parameterProps = ["params"];
|
||||
if (resolvedName === "ToggleSwitch") parameterProps = ["enabledParams", "disabledParams"];
|
||||
for (const parameterProp of parameterProps) {
|
||||
const paramsAttribute = attributes.find((attribute) => nodeOf(attribute.name)?.name === parameterProp);
|
||||
const params = nodeOf(nodeOf(paramsAttribute?.value)?.expression);
|
||||
// Unknown keys stay runtime-checked, but must not conceal known extra keys.
|
||||
if (expected && (!paramsAttribute || params?.type === "ObjectExpression")) {
|
||||
const actual = staticParameterKeys(params);
|
||||
const missing = [...expected].filter((name) => actual.complete && !actual.keys.has(name));
|
||||
const extra = [...actual.keys].filter((name) => !expected.has(name));
|
||||
if (missing.length > 0 || extra.length > 0) {
|
||||
context.add(
|
||||
paramsAttribute ?? opening,
|
||||
`REQUEST_PARAMS_MISMATCH: ${resolvedName}.${parameterProp} '${requestIdLiteral.value}' expects only [${[...expected].join(", ")}]; missing [${missing.join(", ")}], extra [${extra.join(", ")}]. Match params to the request's $param references; fixed query values belong in the request, not params.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (resolvedName === "TablerIcon") {
|
||||
const attributeNames = new Set<string>();
|
||||
for (const attribute of attributes) {
|
||||
if (attribute.type !== "JSXAttribute") continue;
|
||||
const attributeName = nodeOf(attribute.name);
|
||||
if (attributeName?.type === "JSXIdentifier") attributeNames.add(String(attributeName.name));
|
||||
}
|
||||
for (const prop of customJsxCatalogComponentByName.get(resolvedName)?.props ?? []) {
|
||||
if (prop.required && !attributeNames.has(prop.name)) {
|
||||
context.add(opening, `MISSING_REQUIRED_PROP: '${prop.name}' on ${name} is required`);
|
||||
}
|
||||
}
|
||||
}
|
||||
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 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) : "";
|
||||
if (resolvedName === "SubFetch" && attributeName === "triggerContent" && isManualSubFetchTrigger(attributes)) {
|
||||
const triggerContent = nodeOf(attribute.value);
|
||||
const triggerContentExpression =
|
||||
triggerContent?.type === "JSXExpressionContainer" ? nodeOf(triggerContent.expression) : null;
|
||||
const interactiveNode = triggerContentExpression
|
||||
? findInteractiveTriggerContentNode(triggerContentExpression)
|
||||
: null;
|
||||
if (interactiveNode) {
|
||||
context.add(
|
||||
interactiveNode,
|
||||
"SubFetch triggerContent cannot contain interactive descendants because the manual trigger wraps it in a button",
|
||||
);
|
||||
}
|
||||
}
|
||||
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)
|
||||
) {
|
||||
if (resolvedName === "TablerIcon") {
|
||||
context.add(attribute, `UNKNOWN_COMPONENT_PROP: '${attributeName}' on ${name} is not supported`);
|
||||
} else {
|
||||
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");
|
||||
}
|
||||
if (attributeName === "bind") analyzeBindAttribute(attribute, context);
|
||||
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 analyzeBindAttribute(attribute: AstNode, context: AnalyzerJsxContext): void {
|
||||
const value = nodeOf(attribute.value);
|
||||
if (value?.type !== "Literal" || typeof value.value !== "string") {
|
||||
context.add(attribute, "bind must use a literal input name");
|
||||
} else if (!CUSTOM_JSX_BINDING_IDENTIFIER_PATTERN.test(value.value)) {
|
||||
context.add(attribute, `Invalid bind input name '${value.value}'`);
|
||||
}
|
||||
}
|
||||
|
||||
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}`);
|
||||
}
|
||||
const expression = value?.type === "JSXExpressionContainer" ? nodeOf(value.expression) : null;
|
||||
if (attributeName === "resetKey" && ["ArrayExpression", "ObjectExpression"].includes(expression?.type ?? "")) {
|
||||
context.add(attribute, "INVALID_PROP_VALUE: resetKey must resolve to a finite number, string, boolean, or null");
|
||||
}
|
||||
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;
|
||||
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,138 @@
|
||||
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",
|
||||
"toLocaleString",
|
||||
"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);
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import { Parser } from "acorn";
|
||||
import jsx from "acorn-jsx";
|
||||
|
||||
import {
|
||||
CUSTOM_JSX_BLOCKED_PROPERTIES,
|
||||
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";
|
||||
import { isSafeRegexLiteral } from "./regex-policy";
|
||||
|
||||
export type { CustomJsxTemplateDiagnostic } from "./analyzer-diagnostics";
|
||||
|
||||
const JsxParser = Parser.extend(jsx());
|
||||
const requestStatusLabels = new Set(["loading", "success", "error"]);
|
||||
const unsupportedRequestStatusFields = new Set(["isLoading", "isError", "isFetching", "fetching"]);
|
||||
|
||||
export function addCustomJsxDiagnosticSourceExcerpts(
|
||||
template: string,
|
||||
diagnostics: readonly CustomJsxTemplateDiagnostic[],
|
||||
) {
|
||||
return diagnostics.map((diagnostic) => ({
|
||||
...diagnostic,
|
||||
sourceExcerpt: template.slice(Math.max(0, diagnostic.index - 100), diagnostic.index + 100),
|
||||
}));
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function invalidRequestStatusField(node: AstNode) {
|
||||
if (node.type !== "MemberExpression") return null;
|
||||
const object = nodeOf(node.object);
|
||||
const property = nodeOf(node.property);
|
||||
const requestId = directRequestStatusId(object);
|
||||
const field = node.computed ? staticPropertyName(property) : String(property?.name ?? "");
|
||||
if (!requestId || !field || !unsupportedRequestStatusFields.has(field)) return null;
|
||||
return `INVALID_STATUS_FIELD: status.${requestId}.${field} is not available. Use status.${requestId}?.loading or status.${requestId}?.ok === false`;
|
||||
}
|
||||
|
||||
export function validateCustomJsxTemplate(
|
||||
template: string,
|
||||
requestParameters?: ReadonlyMap<string, ReadonlySet<string>>,
|
||||
): CustomJsxTemplateDiagnostic[] {
|
||||
const diagnostics: CustomJsxTemplateDiagnostic[] = [];
|
||||
let operations = 0;
|
||||
|
||||
const add = (node: AstNode, message: string, severity: "error" | "warning" = "error") => {
|
||||
const line = node.loc?.start?.line ?? 1;
|
||||
diagnostics.push({
|
||||
severity,
|
||||
message,
|
||||
index: Math.max(0, (node.start ?? 2) - 2),
|
||||
line,
|
||||
column: Math.max(1, (node.loc?.start?.column ?? 0) + 1 - (line === 1 ? 2 : 0)),
|
||||
});
|
||||
};
|
||||
|
||||
const checkBudget = (node: AstNode, depth: number) => {
|
||||
operations += 1;
|
||||
if (depth > CUSTOM_JSX_LIMITS.astDepth)
|
||||
add(node, `Template exceeds the AST depth limit (${CUSTOM_JSX_LIMITS.astDepth})`);
|
||||
if (operations === CUSTOM_JSX_LIMITS.operations + 1) {
|
||||
add(node, `Template exceeds the operation limit (${CUSTOM_JSX_LIMITS.operations})`);
|
||||
}
|
||||
return depth <= CUSTOM_JSX_LIMITS.astDepth && operations <= CUSTOM_JSX_LIMITS.operations;
|
||||
};
|
||||
|
||||
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);
|
||||
};
|
||||
|
||||
visit = (node: AstNode, depth: number, bindings: ReadonlySet<string>): void => {
|
||||
if (!checkBudget(node, depth)) return;
|
||||
|
||||
switch (node.type) {
|
||||
case "Program":
|
||||
nodesOf(node.body).forEach((child) => visit(child, depth + 1, bindings));
|
||||
return;
|
||||
case "ExpressionStatement": {
|
||||
const expression = nodeOf(node.expression);
|
||||
if (expression) visit(expression, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
case "JSXFragment":
|
||||
nodesOf(node.children).forEach((child) => visit(child, depth + 1, bindings));
|
||||
return;
|
||||
case "JSXElement": {
|
||||
analyzeCustomJsxElement(node, depth, bindings, { add, visit, visitArrow, requestParameters });
|
||||
return;
|
||||
}
|
||||
case "JSXText":
|
||||
case "JSXEmptyExpression":
|
||||
case "TemplateElement":
|
||||
return;
|
||||
case "JSXExpressionContainer": {
|
||||
const expression = nodeOf(node.expression);
|
||||
if (expression && expression.type !== "JSXEmptyExpression") visit(expression, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
case "Literal":
|
||||
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 conservative regex without repeated alternatives or variable quantifiers");
|
||||
return;
|
||||
case "Identifier": {
|
||||
const name = String(node.name ?? "");
|
||||
if (!bindings.has(name)) add(node, `Unknown binding '${name}'`);
|
||||
return;
|
||||
}
|
||||
case "ArrayExpression":
|
||||
nodesOf(node.elements).forEach((child) => {
|
||||
const argument = child.type === "SpreadElement" ? nodeOf(child.argument) : child;
|
||||
if (argument) visit(argument, depth + 1, bindings);
|
||||
});
|
||||
return;
|
||||
case "ObjectExpression":
|
||||
nodesOf(node.properties).forEach((property) => {
|
||||
if (property.type === "SpreadElement") {
|
||||
const argument = nodeOf(property.argument);
|
||||
if (argument) visit(argument, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
if (property.type !== "Property" || property.kind !== "init" || property.method || property.shorthand) {
|
||||
add(property, "Only explicit object properties are supported");
|
||||
return;
|
||||
}
|
||||
const key = nodeOf(property.key);
|
||||
if (property.computed && key) visit(key, depth + 1, bindings);
|
||||
if (
|
||||
!property.computed &&
|
||||
key &&
|
||||
CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(key.name ?? key.value))
|
||||
) {
|
||||
add(key, "Reflective object properties are not allowed");
|
||||
}
|
||||
const value = nodeOf(property.value);
|
||||
if (value) visit(value, depth + 1, bindings);
|
||||
});
|
||||
return;
|
||||
case "UnaryExpression":
|
||||
if (!["!", "+", "-", "typeof"].includes(String(node.operator))) {
|
||||
add(node, `Unary operator '${String(node.operator)}' is not supported`);
|
||||
}
|
||||
if (nodeOf(node.argument)) visit(node.argument as AstNode, depth + 1, bindings);
|
||||
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);
|
||||
if (right) visit(right, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
case "ConditionalExpression": {
|
||||
[node.test, node.consequent, node.alternate].map(nodeOf).forEach((child) => {
|
||||
if (child) visit(child, depth + 1, bindings);
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "MemberExpression": {
|
||||
const object = nodeOf(node.object);
|
||||
const property = nodeOf(node.property);
|
||||
const statusDiagnostic = invalidRequestStatusField(node);
|
||||
if (statusDiagnostic) add(node, statusDiagnostic);
|
||||
if (object) visit(object, depth + 1, bindings);
|
||||
if (node.computed && property) visit(property, depth + 1, bindings);
|
||||
const propertyName = node.computed
|
||||
? staticPropertyName(property)
|
||||
: String(property?.name ?? property?.value ?? "");
|
||||
if (propertyName && CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(propertyName))) {
|
||||
add(property ?? node, "Reflective property access is not allowed");
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "CallExpression": {
|
||||
const callee = nodeOf(node.callee);
|
||||
const callArguments = 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);
|
||||
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 = callArguments[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`);
|
||||
}
|
||||
}
|
||||
callArguments.forEach((argument, argumentIndex) => {
|
||||
if (argument.type === "SpreadElement") add(argument, "Spread call arguments are not supported");
|
||||
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": {
|
||||
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;
|
||||
case "ChainExpression": {
|
||||
const expression = nodeOf(node.expression);
|
||||
if (expression) visit(expression, depth + 1, bindings);
|
||||
return;
|
||||
}
|
||||
default:
|
||||
add(node, `Unsupported expression '${node.type}'`);
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const program = JsxParser.parse(`<>${template}</>`, {
|
||||
ecmaVersion: "latest",
|
||||
sourceType: "module",
|
||||
locations: true,
|
||||
}) as unknown as AstNode;
|
||||
visit(program, 0, ROOT_BINDINGS);
|
||||
} catch (error) {
|
||||
diagnostics.push(createCustomJsxParseDiagnostic(template, error));
|
||||
}
|
||||
|
||||
return diagnostics;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import { createSafeCallable } from "./safe-bindings";
|
||||
import { SafeJsxBudgetError, SafeJsxError } from "./interpreter-foundation";
|
||||
|
||||
export const CUSTOM_JSX_DATA_LIMITS = Object.freeze({
|
||||
depth: 32,
|
||||
nodes: 50_000,
|
||||
stringLength: 200_000,
|
||||
});
|
||||
|
||||
interface SanitizeTask {
|
||||
value: unknown;
|
||||
depth: number;
|
||||
assign(value: unknown): void;
|
||||
}
|
||||
|
||||
function sanitizeData(value: unknown): unknown {
|
||||
let result: unknown;
|
||||
let nodes = 0;
|
||||
const seen = new WeakSet<object>();
|
||||
const tasks: SanitizeTask[] = [{ value, depth: 0, assign: (sanitized) => (result = sanitized) }];
|
||||
|
||||
while (tasks.length > 0) {
|
||||
const task = tasks.pop();
|
||||
if (!task) break;
|
||||
if (++nodes > CUSTOM_JSX_DATA_LIMITS.nodes) {
|
||||
throw new SafeJsxBudgetError(`Response data exceeded the node limit (${CUSTOM_JSX_DATA_LIMITS.nodes})`);
|
||||
}
|
||||
if (task.depth > CUSTOM_JSX_DATA_LIMITS.depth) {
|
||||
throw new SafeJsxBudgetError(`Response data exceeded the depth limit (${CUSTOM_JSX_DATA_LIMITS.depth})`);
|
||||
}
|
||||
if (typeof task.value === "string" && task.value.length > CUSTOM_JSX_DATA_LIMITS.stringLength) {
|
||||
throw new SafeJsxBudgetError(
|
||||
`Response data exceeded the string length limit (${CUSTOM_JSX_DATA_LIMITS.stringLength})`,
|
||||
);
|
||||
}
|
||||
if (task.value === null || typeof task.value !== "object") {
|
||||
task.assign(task.value);
|
||||
continue;
|
||||
}
|
||||
if (seen.has(task.value)) throw new SafeJsxError("Response data must not contain circular or repeated objects");
|
||||
seen.add(task.value);
|
||||
|
||||
if (Array.isArray(task.value)) {
|
||||
if (task.value.length > CUSTOM_JSX_DATA_LIMITS.nodes - nodes) {
|
||||
throw new SafeJsxBudgetError(`Response data exceeded the node limit (${CUSTOM_JSX_DATA_LIMITS.nodes})`);
|
||||
}
|
||||
const safe = Array.from<unknown>({ length: task.value.length });
|
||||
task.assign(safe);
|
||||
for (let index = task.value.length - 1; index >= 0; index -= 1) {
|
||||
if (!Object.hasOwn(task.value, index)) continue;
|
||||
tasks.push({
|
||||
value: task.value[index],
|
||||
depth: task.depth + 1,
|
||||
assign: (sanitized) => (safe[index] = sanitized),
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const entries = Object.entries(task.value);
|
||||
if (entries.length > CUSTOM_JSX_DATA_LIMITS.nodes - nodes) {
|
||||
throw new SafeJsxBudgetError(`Response data exceeded the node limit (${CUSTOM_JSX_DATA_LIMITS.nodes})`);
|
||||
}
|
||||
const safe: Record<string, unknown> = Object.create(null);
|
||||
task.assign(safe);
|
||||
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
||||
const [key, child] = entries[index] as [string, unknown];
|
||||
if (["constructor", "__proto__", "prototype"].includes(key)) continue;
|
||||
if (key.length > CUSTOM_JSX_DATA_LIMITS.stringLength) {
|
||||
throw new SafeJsxBudgetError(
|
||||
`Response data exceeded the string length limit (${CUSTOM_JSX_DATA_LIMITS.stringLength})`,
|
||||
);
|
||||
}
|
||||
tasks.push({
|
||||
value: child,
|
||||
depth: task.depth + 1,
|
||||
assign: (sanitized) => (safe[key] = sanitized),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
const safeMath = Object.freeze(
|
||||
Object.assign(Object.create(null) as Record<string, unknown>, {
|
||||
round: createSafeCallable((value: number) => Math.round(value)),
|
||||
floor: createSafeCallable((value: number) => Math.floor(value)),
|
||||
ceil: createSafeCallable((value: number) => Math.ceil(value)),
|
||||
abs: createSafeCallable((value: number) => Math.abs(value)),
|
||||
min: createSafeCallable((...values: number[]) => Math.min(...values)),
|
||||
max: createSafeCallable((...values: number[]) => Math.max(...values)),
|
||||
pow: createSafeCallable((base: number, exponent: number) => Math.pow(base, exponent)),
|
||||
sqrt: createSafeCallable((value: number) => Math.sqrt(value)),
|
||||
PI: Math.PI,
|
||||
}),
|
||||
);
|
||||
|
||||
const formatLocaleDateTime = (value: string | number, locale = "en-US", timeZone?: string) => {
|
||||
const options: Intl.DateTimeFormatOptions = { dateStyle: "medium", timeStyle: "short" };
|
||||
if (timeZone) options.timeZone = timeZone;
|
||||
return new Intl.DateTimeFormat(locale, options).format(new Date(value));
|
||||
};
|
||||
|
||||
const safeDate = Object.freeze(
|
||||
Object.assign(Object.create(null) as Record<string, unknown>, {
|
||||
now: createSafeCallable(() => Date.now()),
|
||||
create: createSafeCallable((value?: string | number) =>
|
||||
value === undefined ? Date.now() : new Date(value).getTime(),
|
||||
),
|
||||
toISOString: createSafeCallable((value: string | number) => new Date(value).toISOString()),
|
||||
toLocaleDateString: createSafeCallable((value: string | number, locale?: string) =>
|
||||
new Date(value).toLocaleDateString(locale ?? "en-US"),
|
||||
),
|
||||
toLocaleTimeString: createSafeCallable((value: string | number, locale?: string) =>
|
||||
new Date(value).toLocaleTimeString(locale ?? "en-US"),
|
||||
),
|
||||
toLocaleString: createSafeCallable(formatLocaleDateTime),
|
||||
getTime: createSafeCallable((value: string | number) => new Date(value).getTime()),
|
||||
getYear: createSafeCallable((value: string | number) => new Date(value).getFullYear()),
|
||||
getMonth: createSafeCallable((value: string | number) => new Date(value).getMonth()),
|
||||
getDay: createSafeCallable((value: string | number) => new Date(value).getUTCDay()),
|
||||
}),
|
||||
);
|
||||
|
||||
export function createCustomJsxBindings(apiData: unknown) {
|
||||
const safeJson = Object.freeze(
|
||||
Object.assign(Object.create(null) as Record<string, unknown>, {
|
||||
stringify: createSafeCallable((value: unknown, _replacer?: null, space?: string | number) =>
|
||||
JSON.stringify(value, null, space),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const safeArray = Object.freeze(
|
||||
Object.assign(Object.create(null) as Record<string, unknown>, {
|
||||
isArray: createSafeCallable(Array.isArray),
|
||||
from: createSafeCallable((value: ArrayLike<unknown> | Iterable<unknown>) => Array.from(value).slice(0, 2_000)),
|
||||
}),
|
||||
);
|
||||
const safeObject = Object.freeze(
|
||||
Object.assign(Object.create(null) as Record<string, unknown>, {
|
||||
keys: createSafeCallable(Object.keys),
|
||||
values: createSafeCallable(Object.values),
|
||||
entries: createSafeCallable(Object.entries),
|
||||
}),
|
||||
);
|
||||
return {
|
||||
data: sanitizeData(apiData),
|
||||
String: createSafeCallable((value: unknown) => String(value)),
|
||||
Number: createSafeCallable((value: unknown) => Number(value)),
|
||||
Boolean: createSafeCallable((value: unknown) => Boolean(value)),
|
||||
Math: safeMath,
|
||||
JSON: safeJson,
|
||||
Array: safeArray,
|
||||
Object: safeObject,
|
||||
Date: safeDate,
|
||||
parseInt: createSafeCallable((value: string, radix?: number) => parseInt(value, radix)),
|
||||
parseFloat: createSafeCallable((value: string) => parseFloat(value)),
|
||||
encodeURIComponent: createSafeCallable((value: string) => encodeURIComponent(value)),
|
||||
decodeURIComponent: createSafeCallable((value: string) => decodeURIComponent(value)),
|
||||
isNaN: createSafeCallable((value: unknown) => Number.isNaN(Number(value))),
|
||||
isFinite: createSafeCallable((value: unknown) => Number.isFinite(Number(value))),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { isSafeCallable } from "./safe-bindings";
|
||||
import { isInterpreterCallback, normalizedSliceIndex, numericArgument, SafeJsxError } from "./interpreter-foundation";
|
||||
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: InterpreterMethodContext,
|
||||
): { handled: boolean; value?: unknown } {
|
||||
if (Array.isArray(receiver)) {
|
||||
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 === "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 };
|
||||
}
|
||||
if (!isInterpreterCallback(callback)) throw new SafeJsxError(`${method} requires an inline arrow callback`);
|
||||
const result: unknown[] = [];
|
||||
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 === "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 };
|
||||
}
|
||||
if (method === "pop") {
|
||||
context.budget.collection();
|
||||
return { handled: true, value: receiver.length > 0 ? receiver[receiver.length - 1] : undefined };
|
||||
}
|
||||
if (method === "slice") {
|
||||
const start = normalizedSliceIndex(args[0], receiver.length, 0);
|
||||
const end = normalizedSliceIndex(args[1], receiver.length, receiver.length);
|
||||
const result: unknown[] = [];
|
||||
for (let index = start; index < Math.max(start, end); index += 1) {
|
||||
context.budget.collection();
|
||||
result.push(receiver[index]);
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
if (method === "join") {
|
||||
context.budget.collection(receiver.length);
|
||||
const separator = String(args[0] ?? ",");
|
||||
let result = "";
|
||||
receiver.forEach((item, index) => {
|
||||
result += `${index === 0 ? "" : separator}${String(item ?? "")}`;
|
||||
context.budget.string(result);
|
||||
});
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
if (method === "includes") {
|
||||
context.budget.collection(receiver.length);
|
||||
return { handled: true, value: receiver.some((item) => Object.is(item, args[0])) };
|
||||
}
|
||||
if (method === "indexOf") {
|
||||
context.budget.collection(receiver.length);
|
||||
return { handled: true, value: receiver.findIndex((item) => Object.is(item, args[0])) };
|
||||
}
|
||||
if (method === "find" || method === "findIndex" || method === "some" || method === "every") {
|
||||
const callback = args[0];
|
||||
const useSafe = isSafeCallable(callback);
|
||||
if (!useSafe && !isInterpreterCallback(callback))
|
||||
throw new SafeJsxError(`${method} requires an inline arrow callback`);
|
||||
for (let index = 0; index < receiver.length; index += 1) {
|
||||
context.budget.collection();
|
||||
const result = useSafe
|
||||
? (callback as (...a: never[]) => unknown)(receiver[index] as never)
|
||||
: context.runCallback(callback as InterpreterCallback, [receiver[index], index, receiver], depth + 1);
|
||||
if (method === "find" && result) return { handled: true, value: receiver[index] };
|
||||
if (method === "findIndex" && result) return { handled: true, value: index };
|
||||
if (method === "some" && result) return { handled: true, value: true };
|
||||
if (method === "every" && !result) return { handled: true, value: false };
|
||||
}
|
||||
const defaults: Record<string, unknown> = { find: undefined, findIndex: -1, some: false, every: true };
|
||||
return { handled: true, value: defaults[method] };
|
||||
}
|
||||
if (method === "sort") {
|
||||
const callback = args[0];
|
||||
if (!isInterpreterCallback(callback)) throw new SafeJsxError("sort requires an inline arrow callback");
|
||||
const copy = [...receiver];
|
||||
copy.sort((left, right) => {
|
||||
context.budget.collection();
|
||||
const delta = Number(context.runCallback(callback, [left, right], depth + 1));
|
||||
if (!Number.isFinite(delta)) return 0;
|
||||
return delta;
|
||||
});
|
||||
return { handled: true, value: copy };
|
||||
}
|
||||
if (method === "reduce") {
|
||||
const callback = args[0];
|
||||
if (!isInterpreterCallback(callback)) throw new SafeJsxError("reduce requires an inline arrow callback");
|
||||
if (receiver.length === 0 && args.length < 2) {
|
||||
throw new SafeJsxError("Reduce of empty array with no initial value");
|
||||
}
|
||||
let startIndex = 0;
|
||||
let accumulator: unknown;
|
||||
if (args.length < 2) {
|
||||
accumulator = receiver[0];
|
||||
startIndex = 1;
|
||||
} else {
|
||||
accumulator = args[1];
|
||||
}
|
||||
for (let index = startIndex; index < receiver.length; index += 1) {
|
||||
context.budget.collection();
|
||||
accumulator = context.runCallback(callback, [accumulator, receiver[index], index, receiver], depth + 1);
|
||||
}
|
||||
return { handled: true, value: accumulator };
|
||||
}
|
||||
if (method === "at") {
|
||||
const index = numericArgument(args[0], 0);
|
||||
let normalizedIndex = index;
|
||||
if (index < 0) normalizedIndex = receiver.length + index;
|
||||
context.budget.collection();
|
||||
const outOfBounds = normalizedIndex < 0 || normalizedIndex >= receiver.length;
|
||||
return { handled: true, value: outOfBounds ? undefined : receiver[normalizedIndex] };
|
||||
}
|
||||
if (method === "flat") {
|
||||
// ponytail: only depth=1 supported; deeper nesting requires recursive budget tracking
|
||||
const flatDepth = numericArgument(args[0], 1);
|
||||
if (flatDepth !== 1) throw new SafeJsxError("flat() only supports depth 1");
|
||||
const result: unknown[] = [];
|
||||
for (const item of receiver) {
|
||||
context.budget.collection();
|
||||
if (Array.isArray(item)) {
|
||||
for (const nested of item) {
|
||||
context.budget.collection();
|
||||
result.push(nested);
|
||||
}
|
||||
} else {
|
||||
result.push(item);
|
||||
}
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
if (method === "reverse") {
|
||||
const copy = [...receiver];
|
||||
const result: unknown[] = [];
|
||||
for (let index = copy.length - 1; index >= 0; index -= 1) {
|
||||
context.budget.collection();
|
||||
result.push(copy[index]);
|
||||
}
|
||||
return { handled: true, value: result };
|
||||
}
|
||||
}
|
||||
|
||||
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") {
|
||||
if (method === "toFixed") {
|
||||
const digits = Math.max(0, Math.min(20, numericArgument(args[0], 0)));
|
||||
return { handled: true, value: receiver.toFixed(digits) };
|
||||
}
|
||||
if (method === "toPrecision") {
|
||||
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 (
|
||||
(typeof receiver === "number" || typeof receiver === "boolean" || typeof receiver === "string") &&
|
||||
method === "toString"
|
||||
) {
|
||||
return { handled: true, value: context.budget.string(String(receiver)) };
|
||||
}
|
||||
|
||||
return { handled: false };
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@mantine/core";
|
||||
|
||||
export function createCopyButton(labels: { copy: string; copied: string }) {
|
||||
return function SafeCopyButton({ value }: { value?: string; children?: ReactNode }) {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const timer = useRef<ReturnType<typeof setTimeout>>(undefined);
|
||||
useEffect(() => () => clearTimeout(timer.current), []);
|
||||
const copy = async () => {
|
||||
if (!value) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(value);
|
||||
setCopied(true);
|
||||
clearTimeout(timer.current);
|
||||
timer.current = setTimeout(() => setCopied(false), 2_000);
|
||||
} catch {
|
||||
setCopied(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Button
|
||||
size="xs"
|
||||
variant={copied ? "filled" : "light"}
|
||||
color={copied ? "teal" : "blue"}
|
||||
onClick={() => void copy()}
|
||||
>
|
||||
{copied ? labels.copied : labels.copy}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -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,8 @@
|
||||
export * from "./analyzer";
|
||||
export * from "./interpreter";
|
||||
export * from "./policy";
|
||||
export * from "./safe-bindings";
|
||||
export * from "./bindings";
|
||||
export * from "./runtime-components";
|
||||
export * from "./interactive-components";
|
||||
export { sanitizeCustomJsxProps } from "./safe-properties";
|
||||
@@ -0,0 +1,228 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { Children, isValidElement, useEffect, useRef, useState } from "react";
|
||||
import { ActionIcon, Badge, Collapse, Group, Stack, Tabs, Text, UnstyledButton } from "@mantine/core";
|
||||
import { IconChevronDown, IconChevronLeft, IconChevronRight, IconChevronUp } from "@tabler/icons-react";
|
||||
|
||||
interface PaginatedListProps {
|
||||
children: ReactNode;
|
||||
pageSize?: number;
|
||||
}
|
||||
|
||||
export function PaginatedList({ children, pageSize = 6 }: PaginatedListProps) {
|
||||
const items = Children.toArray(children);
|
||||
const totalPages = Math.max(1, Math.ceil(items.length / pageSize));
|
||||
const [page, setPage] = useState(0);
|
||||
const prevCountRef = useRef(items.length);
|
||||
|
||||
useEffect(() => {
|
||||
if (items.length !== prevCountRef.current) {
|
||||
setPage(0);
|
||||
prevCountRef.current = items.length;
|
||||
}
|
||||
}, [items.length]);
|
||||
|
||||
const clampedPage = Math.min(page, totalPages - 1);
|
||||
const start = clampedPage * pageSize;
|
||||
const visible = items.slice(start, start + pageSize);
|
||||
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
<div>{visible}</div>
|
||||
{totalPages > 1 && (
|
||||
<Group justify="center" gap="xs">
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
disabled={clampedPage === 0}
|
||||
onClick={() => setPage((p) => Math.max(0, p - 1))}
|
||||
>
|
||||
<IconChevronLeft size={14} />
|
||||
</ActionIcon>
|
||||
<Text size="xs" c="dimmed">
|
||||
{clampedPage + 1} / {totalPages}
|
||||
</Text>
|
||||
<ActionIcon
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
disabled={clampedPage >= totalPages - 1}
|
||||
onClick={() => setPage((p) => Math.min(totalPages - 1, p + 1))}
|
||||
>
|
||||
<IconChevronRight size={14} />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
interface TabsContainerProps {
|
||||
children: ReactNode;
|
||||
defaultTab?: string;
|
||||
}
|
||||
|
||||
function isTabPanel(child: ReactNode): child is React.ReactElement<TabPanelProps> {
|
||||
return isValidElement<TabPanelProps>(child) && child.type === TabPanel && typeof child.props.value === "string";
|
||||
}
|
||||
|
||||
export function TabsContainer({ children, defaultTab }: TabsContainerProps) {
|
||||
const panels = Children.toArray(children).filter(isTabPanel);
|
||||
const firstPanel = panels[0];
|
||||
const panelValues = new Set(panels.map((p) => p.props.value));
|
||||
const resolvedDefault = defaultTab && panelValues.has(defaultTab) && defaultTab;
|
||||
const initialTab = resolvedDefault || firstPanel?.props.value || null;
|
||||
const [activeTab, setActiveTab] = useState<string | null>(initialTab);
|
||||
|
||||
return (
|
||||
<Tabs value={activeTab} onChange={setActiveTab}>
|
||||
<Tabs.List>
|
||||
{panels.map((panel) => (
|
||||
<Tabs.Tab key={panel.props.value} value={panel.props.value}>
|
||||
{panel.props.label ?? panel.props.value}
|
||||
</Tabs.Tab>
|
||||
))}
|
||||
</Tabs.List>
|
||||
{panels.map((panel) => (
|
||||
<Tabs.Panel key={panel.props.value} value={panel.props.value} pt="sm">
|
||||
{panel.props.children}
|
||||
</Tabs.Panel>
|
||||
))}
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
||||
interface TabPanelProps {
|
||||
children: ReactNode;
|
||||
value: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
export function TabPanel({ children }: TabPanelProps) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
interface CollapsibleProps {
|
||||
children: ReactNode;
|
||||
title: string;
|
||||
defaultOpen?: boolean;
|
||||
}
|
||||
|
||||
const COLLAPSE_CHEVRONS = {
|
||||
closed: IconChevronDown,
|
||||
open: IconChevronUp,
|
||||
} as const;
|
||||
|
||||
const COLLAPSE_STATE: Record<0 | 1, keyof typeof COLLAPSE_CHEVRONS> = {
|
||||
0: "closed",
|
||||
1: "open",
|
||||
};
|
||||
|
||||
export function Collapsible({ children, title, defaultOpen = false }: CollapsibleProps) {
|
||||
const [opened, setOpened] = useState(defaultOpen);
|
||||
const Chevron = COLLAPSE_CHEVRONS[COLLAPSE_STATE[Number(opened) as 0 | 1]];
|
||||
|
||||
return (
|
||||
<Stack gap={0}>
|
||||
<UnstyledButton onClick={() => setOpened((o) => !o)} py={4}>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<Chevron size={14} />
|
||||
<Text size="sm" fw={600}>
|
||||
{title}
|
||||
</Text>
|
||||
</Group>
|
||||
</UnstyledButton>
|
||||
<Collapse expanded={opened}>{children}</Collapse>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
interface StatBarProps {
|
||||
value: number;
|
||||
max?: number;
|
||||
label?: string;
|
||||
color?: string;
|
||||
}
|
||||
|
||||
function calcPct(value: number, max: number): number {
|
||||
if (max <= 0) return 0;
|
||||
return Math.min((value / max) * 100, 100);
|
||||
}
|
||||
|
||||
export function StatBar({ value, max = 100, label, color = "blue" }: StatBarProps) {
|
||||
const pct = calcPct(value, max);
|
||||
|
||||
return (
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
{label && (
|
||||
<Text size="xs" w={80} ta="right" c="dimmed">
|
||||
{label}
|
||||
</Text>
|
||||
)}
|
||||
<div
|
||||
style={{
|
||||
flex: 1,
|
||||
height: 8,
|
||||
borderRadius: 4,
|
||||
background: "var(--mantine-color-default-border)",
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: `${pct}%`,
|
||||
height: "100%",
|
||||
borderRadius: 4,
|
||||
background: `var(--mantine-color-${color}-6)`,
|
||||
transition: "width 0.3s ease",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<Text size="xs" w={30} c="dimmed">
|
||||
{value}
|
||||
</Text>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
interface TypeBadgeProps {
|
||||
type: string;
|
||||
size?: "xs" | "sm" | "md" | "lg" | "xl";
|
||||
}
|
||||
|
||||
const TYPE_COLORS: Record<string, string> = {
|
||||
normal: "gray",
|
||||
fire: "red",
|
||||
water: "blue",
|
||||
electric: "yellow",
|
||||
grass: "green",
|
||||
ice: "cyan",
|
||||
fighting: "orange",
|
||||
poison: "grape",
|
||||
ground: "yellow",
|
||||
flying: "indigo",
|
||||
psychic: "pink",
|
||||
bug: "lime",
|
||||
rock: "orange",
|
||||
ghost: "violet",
|
||||
dragon: "indigo",
|
||||
dark: "dark",
|
||||
steel: "gray",
|
||||
fairy: "pink",
|
||||
};
|
||||
|
||||
function normalizeType(type: unknown): string {
|
||||
if (typeof type === "string") return type;
|
||||
if (type == null) return "";
|
||||
return String(type);
|
||||
}
|
||||
|
||||
export function TypeBadge({ type, size = "sm" }: TypeBadgeProps) {
|
||||
const typeStr = normalizeType(type);
|
||||
const color = TYPE_COLORS[typeStr.toLowerCase()] ?? "gray";
|
||||
return (
|
||||
<Badge color={color} size={size} variant="filled" tt="capitalize">
|
||||
{typeStr}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { CUSTOM_JSX_LIMITS } from "./policy";
|
||||
|
||||
export interface AstNode {
|
||||
type: string;
|
||||
start?: number;
|
||||
end?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface EvaluationBudgets {
|
||||
maxAstDepth: number;
|
||||
maxOperations: number;
|
||||
maxCollectionItems: number;
|
||||
maxRenderedNodes: number;
|
||||
maxStringLength: number;
|
||||
}
|
||||
|
||||
export interface SafeJsxBudgets extends Partial<EvaluationBudgets> {}
|
||||
export const INTERPRETER_CALLBACK = Symbol("custom-jsx-interpreter-callback");
|
||||
export const DEFAULT_BUDGETS: EvaluationBudgets = {
|
||||
maxAstDepth: CUSTOM_JSX_LIMITS.astDepth,
|
||||
maxOperations: CUSTOM_JSX_LIMITS.operations,
|
||||
maxCollectionItems: CUSTOM_JSX_LIMITS.collectionItems,
|
||||
maxRenderedNodes: CUSTOM_JSX_LIMITS.renderedNodes,
|
||||
maxStringLength: CUSTOM_JSX_LIMITS.stringLength,
|
||||
};
|
||||
|
||||
export interface InterpreterCallback {
|
||||
readonly kind: typeof INTERPRETER_CALLBACK;
|
||||
readonly params: readonly string[];
|
||||
readonly body: AstNode;
|
||||
readonly environment: Environment;
|
||||
}
|
||||
|
||||
export class SafeJsxError extends Error {
|
||||
public constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "SafeJsxError";
|
||||
}
|
||||
}
|
||||
|
||||
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>>,
|
||||
private readonly parent?: Environment,
|
||||
) {}
|
||||
public get(name: string): unknown {
|
||||
if (Object.hasOwn(this.values, name)) return this.values[name];
|
||||
if (this.parent) return this.parent.get(name);
|
||||
if (name === "undefined") return undefined;
|
||||
if (name === "NaN") return Number.NaN;
|
||||
if (name === "Infinity") return Number.POSITIVE_INFINITY;
|
||||
throw new SafeJsxError(`Unknown binding: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
export class Budget {
|
||||
private operations = 0;
|
||||
private collectionItems = 0;
|
||||
private renderedNodes = 0;
|
||||
public constructor(private readonly limits: EvaluationBudgets) {}
|
||||
public operation(depth: number): void {
|
||||
if (depth > this.limits.maxAstDepth)
|
||||
throw new SafeJsxBudgetError(`Template exceeded the AST depth limit (${this.limits.maxAstDepth})`);
|
||||
if (++this.operations > 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 SafeJsxBudgetError(`Template exceeded the collection limit (${this.limits.maxCollectionItems})`);
|
||||
}
|
||||
public rendered(): void {
|
||||
if (++this.renderedNodes > 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 SafeJsxBudgetError(`Template exceeded the string length limit (${this.limits.maxStringLength})`);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
export function asNode(value: unknown, context: string): AstNode {
|
||||
if (!value || typeof value !== "object" || typeof (value as { type?: unknown }).type !== "string")
|
||||
throw new SafeJsxError(`Invalid ${context} node`);
|
||||
return value as AstNode;
|
||||
}
|
||||
|
||||
export function asNodeArray(value: unknown, context: string): AstNode[] {
|
||||
if (!Array.isArray(value)) throw new SafeJsxError(`Invalid ${context}`);
|
||||
return value.map((item) => asNode(item, context));
|
||||
}
|
||||
|
||||
export const isInterpreterCallback = (value: unknown): value is InterpreterCallback =>
|
||||
typeof value === "object" && value !== null && (value as { kind?: unknown }).kind === INTERPRETER_CALLBACK;
|
||||
|
||||
export function numericArgument(value: unknown, fallback: number): number {
|
||||
const number = value === undefined ? fallback : Number(value);
|
||||
if (!Number.isFinite(number)) return fallback;
|
||||
return Math.trunc(number);
|
||||
}
|
||||
|
||||
export function normalizedSliceIndex(value: unknown, length: number, fallback: number): number {
|
||||
const index = numericArgument(value, fallback);
|
||||
if (index < 0) return Math.max(length + index, 0);
|
||||
return Math.min(index, length);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,363 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
|
||||
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 { isSafeCallable } from "./safe-bindings";
|
||||
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_CALLBACK_METHODS } from "./safe-language-policy";
|
||||
import { isSafeRegexLiteral } from "./regex-policy";
|
||||
|
||||
export { SafeJsxBudgetError, SafeJsxError } from "./interpreter-foundation";
|
||||
export type { SafeJsxBudgets } from "./interpreter-foundation";
|
||||
export { sanitizeCustomJsxProps } from "./safe-properties";
|
||||
|
||||
export interface RenderSafeJsxOptions {
|
||||
template: string;
|
||||
components: Readonly<Record<string, ComponentType<never>>>;
|
||||
bindings: Readonly<Record<string, unknown>>;
|
||||
budgets?: SafeJsxBudgets;
|
||||
}
|
||||
|
||||
export interface SafeJsxRenderResult {
|
||||
node: ReactNode;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
class Interpreter {
|
||||
private readonly budget: Budget;
|
||||
private readonly warnings = new Set<string>();
|
||||
|
||||
public constructor(
|
||||
private readonly components: Readonly<Record<string, ComponentType<never>>>,
|
||||
private readonly environment: Environment,
|
||||
private readonly limits: EvaluationBudgets,
|
||||
) {
|
||||
this.budget = new Budget(limits);
|
||||
}
|
||||
|
||||
public render(root: AstNode): SafeJsxRenderResult {
|
||||
return { node: this.evaluate(root, this.environment, 0) as ReactNode, warnings: [...this.warnings] };
|
||||
}
|
||||
|
||||
private evaluate(node: AstNode, environment: Environment, depth: number): unknown {
|
||||
this.budget.operation(depth);
|
||||
|
||||
switch (node.type) {
|
||||
case "Literal":
|
||||
if (node.regex !== undefined) {
|
||||
const regex = node.regex as { pattern?: unknown; flags?: unknown };
|
||||
if (!isSafeRegexLiteral(regex)) {
|
||||
throw new SafeJsxError("UNSAFE_REGEX: Invalid regular expression literal");
|
||||
}
|
||||
return new RegExp(regex.pattern as string, regex.flags as string);
|
||||
}
|
||||
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));
|
||||
case "JSXElement":
|
||||
return this.evaluateJsxElement(node, environment, depth + 1);
|
||||
case "JSXFragment":
|
||||
return this.evaluateJsxFragment(node, environment, depth + 1);
|
||||
case "JSXText": {
|
||||
const text = this.budget.string(normalizeCustomJsxText(String(node.value ?? "")));
|
||||
if (text) this.budget.rendered();
|
||||
return text || null;
|
||||
}
|
||||
case "JSXExpressionContainer": {
|
||||
const expression = asNode(node.expression, "JSX expression");
|
||||
if (expression.type === "JSXEmptyExpression") return null;
|
||||
const value = this.evaluate(expression, environment, depth + 1);
|
||||
return typeof value === "string" ? this.budget.string(value) : value;
|
||||
}
|
||||
case "ArrayExpression":
|
||||
return this.evaluateArray(node, environment, depth + 1);
|
||||
case "ObjectExpression":
|
||||
return this.evaluateObject(node, environment, depth + 1);
|
||||
case "UnaryExpression":
|
||||
return this.evaluateUnary(node, environment, depth + 1);
|
||||
case "BinaryExpression":
|
||||
return this.evaluateBinary(node, environment, depth + 1);
|
||||
case "LogicalExpression":
|
||||
return this.evaluateLogical(node, environment, depth + 1);
|
||||
case "ConditionalExpression":
|
||||
return this.evaluate(node.test as AstNode, environment, depth + 1)
|
||||
? this.evaluate(asNode(node.consequent, "conditional consequent"), environment, depth + 1)
|
||||
: this.evaluate(asNode(node.alternate, "conditional alternate"), environment, depth + 1);
|
||||
case "MemberExpression":
|
||||
return this.evaluateMember(node, environment, depth + 1);
|
||||
case "CallExpression":
|
||||
return this.evaluateCall(node, environment, depth + 1);
|
||||
case "ArrowFunctionExpression":
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateJsxFragment(node: AstNode, environment: Environment, depth: number): ReactNode {
|
||||
return emitJsxFragment(node, environment, depth, this.emitterContext());
|
||||
}
|
||||
|
||||
private evaluateJsxElement(node: AstNode, environment: Environment, depth: number): ReactNode {
|
||||
return emitJsxElement(node, environment, depth, this.emitterContext());
|
||||
}
|
||||
|
||||
private emitterContext(): JsxEmitterContext {
|
||||
return {
|
||||
components: this.components,
|
||||
budget: this.budget,
|
||||
warnings: this.warnings,
|
||||
evaluate: (node, environment, depth) => this.evaluate(node, environment, depth),
|
||||
createCallback: (node, environment) => this.createCallback(node, environment),
|
||||
renderCallback: (callback, args, depth) => this.runCallback(callback, args, depth) as ReactNode,
|
||||
};
|
||||
}
|
||||
|
||||
private evaluateArray(node: AstNode, environment: Environment, depth: number): unknown[] {
|
||||
const result: unknown[] = [];
|
||||
const elements = node.elements;
|
||||
if (!Array.isArray(elements)) throw new SafeJsxError("Invalid array expression");
|
||||
for (const elementValue of elements) {
|
||||
if (elementValue == null) {
|
||||
result.push(undefined);
|
||||
continue;
|
||||
}
|
||||
const element = asNode(elementValue, "array element");
|
||||
if (element.type === "SpreadElement") {
|
||||
const spread = this.evaluate(asNode(element.argument, "array spread"), environment, depth + 1);
|
||||
if (!Array.isArray(spread)) throw new SafeJsxError("Only arrays can be spread into arrays");
|
||||
this.budget.collection(spread.length);
|
||||
result.push(...spread);
|
||||
} else {
|
||||
this.budget.collection();
|
||||
result.push(this.evaluate(element, environment, depth + 1));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private evaluateObject(node: AstNode, environment: Environment, depth: number): Record<string, unknown> {
|
||||
const result: Record<string, unknown> = Object.create(null);
|
||||
for (const property of asNodeArray(node.properties, "object properties")) {
|
||||
if (property.type === "SpreadElement") {
|
||||
const spread = this.evaluate(asNode(property.argument, "object spread"), environment, depth + 1);
|
||||
if (!spread || typeof spread !== "object" || Array.isArray(spread)) {
|
||||
throw new SafeJsxError("Only objects can be spread into objects");
|
||||
}
|
||||
for (const [key, value] of Object.entries(spread)) result[normalizedProperty(key)] = value;
|
||||
continue;
|
||||
}
|
||||
if (property.type !== "Property" || property.kind !== "init" || property.method || property.shorthand) {
|
||||
throw new SafeJsxError("Only explicit object properties are supported");
|
||||
}
|
||||
const keyNode = asNode(property.key, "object key");
|
||||
const key = normalizedProperty(
|
||||
property.computed
|
||||
? this.evaluate(keyNode, environment, depth + 1)
|
||||
: keyNode.type === "Identifier"
|
||||
? keyNode.name
|
||||
: keyNode.value,
|
||||
);
|
||||
result[key] = this.evaluate(asNode(property.value, "object value"), environment, depth + 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private evaluateUnary(node: AstNode, environment: Environment, depth: number): unknown {
|
||||
const value = this.evaluate(asNode(node.argument, "unary argument"), environment, depth + 1);
|
||||
switch (node.operator) {
|
||||
case "!":
|
||||
return !value;
|
||||
case "+":
|
||||
return Number(value);
|
||||
case "-":
|
||||
return -Number(value);
|
||||
case "typeof":
|
||||
return typeof value;
|
||||
default:
|
||||
throw new SafeJsxError(`Unsupported unary operator: ${String(node.operator)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateBinary(node: AstNode, environment: Environment, depth: number): unknown {
|
||||
const left = this.evaluate(asNode(node.left, "binary left operand"), environment, depth + 1);
|
||||
const right = this.evaluate(asNode(node.right, "binary right operand"), environment, depth + 1);
|
||||
switch (node.operator) {
|
||||
case "+":
|
||||
return typeof left === "string" || typeof right === "string"
|
||||
? this.budget.string(String(left) + String(right))
|
||||
: Number(left) + Number(right);
|
||||
case "-":
|
||||
return Number(left) - Number(right);
|
||||
case "*":
|
||||
return Number(left) * Number(right);
|
||||
case "/":
|
||||
return Number(left) / Number(right);
|
||||
case "%":
|
||||
return Number(left) % Number(right);
|
||||
case "**":
|
||||
return Number(left) ** Number(right);
|
||||
case "<":
|
||||
return (left as number) < (right as number);
|
||||
case "<=":
|
||||
return (left as number) <= (right as number);
|
||||
case ">":
|
||||
return (left as number) > (right as number);
|
||||
case ">=":
|
||||
return (left as number) >= (right as number);
|
||||
case "==":
|
||||
if (left == null || right == null) return left == null && right == null;
|
||||
return String(left) === String(right);
|
||||
case "!=":
|
||||
if (left == null || right == null) return left != null || right != null;
|
||||
return String(left) !== String(right);
|
||||
case "===":
|
||||
return left === right;
|
||||
case "!==":
|
||||
return left !== right;
|
||||
default:
|
||||
throw new SafeJsxError(`Unsupported binary operator: ${String(node.operator)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private evaluateLogical(node: AstNode, environment: Environment, depth: number): unknown {
|
||||
const left = this.evaluate(asNode(node.left, "logical left operand"), environment, depth + 1);
|
||||
if (node.operator === "&&") {
|
||||
return left ? this.evaluate(asNode(node.right, "logical right operand"), environment, depth + 1) : left;
|
||||
}
|
||||
if (node.operator === "||") {
|
||||
return left ? left : this.evaluate(asNode(node.right, "logical right operand"), environment, depth + 1);
|
||||
}
|
||||
if (node.operator === "??") {
|
||||
return left == null ? this.evaluate(asNode(node.right, "logical right operand"), environment, depth + 1) : left;
|
||||
}
|
||||
throw new SafeJsxError(`Unsupported logical operator: ${String(node.operator)}`);
|
||||
}
|
||||
|
||||
private memberProperty(node: AstNode, environment: Environment, depth: number): string {
|
||||
const propertyNode = asNode(node.property, "member property");
|
||||
return normalizedProperty(
|
||||
node.computed
|
||||
? this.evaluate(propertyNode, environment, depth + 1)
|
||||
: propertyNode.type === "Identifier"
|
||||
? propertyNode.name
|
||||
: propertyNode.value,
|
||||
);
|
||||
}
|
||||
|
||||
private evaluateMember(node: AstNode, environment: Environment, depth: number): unknown {
|
||||
const object = this.evaluate(asNode(node.object, "member object"), environment, depth + 1);
|
||||
const property = this.memberProperty(node, environment, depth + 1);
|
||||
return ownProperty(object, property);
|
||||
}
|
||||
|
||||
private evaluateCall(node: AstNode, environment: Environment, depth: number): unknown {
|
||||
if (node.optional) throw new SafeJsxError("Optional calls are not supported");
|
||||
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);
|
||||
});
|
||||
|
||||
if (callee.type === "MemberExpression") {
|
||||
const receiver = this.evaluate(asNode(callee.object, "method receiver"), environment, depth + 1);
|
||||
const method = this.memberProperty(callee, environment, depth + 1);
|
||||
const collectionResult = this.callCollectionMethod(receiver, method, args, depth + 1);
|
||||
if (collectionResult.handled) return collectionResult.value;
|
||||
const callable = ownProperty(receiver, method);
|
||||
if (!isSafeCallable(callable)) throw new SafeJsxError(`Calling method '${method}' is not allowed`);
|
||||
return this.accountHostResult(callable(...(args as never[])));
|
||||
}
|
||||
|
||||
const callable = this.evaluate(callee, environment, depth + 1);
|
||||
if (!isSafeCallable(callable)) throw new SafeJsxError("Calling this value is not allowed");
|
||||
return this.accountHostResult(callable(...(args as never[])));
|
||||
}
|
||||
|
||||
private callCollectionMethod(
|
||||
receiver: unknown,
|
||||
method: string,
|
||||
args: unknown[],
|
||||
depth: number,
|
||||
): { handled: boolean; value?: unknown } {
|
||||
return callCollectionMethod(receiver, method, args, depth, {
|
||||
budget: this.budget,
|
||||
runCallback: (callback, callbackArgs, callbackDepth) => this.runCallback(callback, callbackArgs, callbackDepth),
|
||||
});
|
||||
}
|
||||
|
||||
private accountHostResult(value: unknown): unknown {
|
||||
if (typeof value === "string") return this.budget.string(value);
|
||||
if (Array.isArray(value)) this.budget.collection(value.length);
|
||||
return value;
|
||||
}
|
||||
|
||||
private createCallback(node: AstNode, environment: Environment): InterpreterCallback {
|
||||
return createInterpreterCallback(node, environment);
|
||||
}
|
||||
|
||||
private runCallback(callback: InterpreterCallback, args: unknown[], depth: number): unknown {
|
||||
return runInterpreterCallback(callback, args, depth, {
|
||||
budget: this.budget,
|
||||
evaluate: (node, environment, callbackDepth) => this.evaluate(node, environment, callbackDepth),
|
||||
});
|
||||
}
|
||||
|
||||
private evaluateTemplateLiteral(node: AstNode, environment: Environment, depth: number): string {
|
||||
const quasis = asNodeArray(node.quasis, "template literal parts");
|
||||
const expressions = asNodeArray(node.expressions, "template literal expressions");
|
||||
let result = "";
|
||||
quasis.forEach((quasi, index) => {
|
||||
const value = quasi.value;
|
||||
if (!value || typeof value !== "object") throw new SafeJsxError("Invalid template literal part");
|
||||
result += String((value as { cooked?: unknown }).cooked ?? "");
|
||||
const expression = expressions[index];
|
||||
if (expression) result += String(this.evaluate(expression, environment, depth + 1));
|
||||
});
|
||||
return this.budget.string(result);
|
||||
}
|
||||
}
|
||||
|
||||
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 = parseCustomJsxTemplate(template);
|
||||
return new Interpreter(components, new Environment(bindings), limits).render(root);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { createElement, Fragment } from "react";
|
||||
|
||||
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 function emitJsxFragment(
|
||||
node: AstNode,
|
||||
environment: Environment,
|
||||
depth: number,
|
||||
context: JsxEmitterContext,
|
||||
): ReactNode {
|
||||
const children = asNodeArray(node.children, "fragment children").map((child) =>
|
||||
context.evaluate(child, environment, depth + 1),
|
||||
);
|
||||
context.budget.rendered();
|
||||
return createElement(Fragment, null, ...(children as ReactNode[]));
|
||||
}
|
||||
|
||||
export function emitJsxElement(
|
||||
node: AstNode,
|
||||
environment: Environment,
|
||||
depth: number,
|
||||
context: JsxEmitterContext,
|
||||
): 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[resolvedTag];
|
||||
if (!component) {
|
||||
context.warnings.add(`Unknown or unavailable component: ${tag}`);
|
||||
return null;
|
||||
}
|
||||
const rawProps: Record<string, unknown> = {};
|
||||
for (const attribute of asNodeArray(opening.attributes, "JSX attributes")) {
|
||||
if (attribute.type === "JSXSpreadAttribute") {
|
||||
const spread = context.evaluate(asNode(attribute.argument, "spread attribute"), environment, depth + 1);
|
||||
if (spread && typeof spread === "object" && !Array.isArray(spread)) {
|
||||
if (Object.hasOwn(spread, "bind")) {
|
||||
throw new SafeJsxError("BIND_SPREAD_NOT_ALLOWED: The bind prop must be an explicit literal JSX attribute");
|
||||
}
|
||||
Object.assign(rawProps, spread);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
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, metadata: unknown) => context.renderCallback(callback, [value, metadata], depth + 1);
|
||||
}
|
||||
return context.evaluate(child, environment, depth + 1);
|
||||
});
|
||||
const normalizedChildren = resolvedTag === "SubFetch" ? normalizeSubFetchChildren(children) : children;
|
||||
diagnoseCustomJsxProps(rawProps, resolvedTag).forEach((diagnostic) => context.warnings.add(diagnostic));
|
||||
const props = sanitizeCustomJsxProps(rawProps, resolvedTag);
|
||||
context.budget.rendered();
|
||||
return createElement(component, props as never, ...(normalizedChildren as ReactNode[]));
|
||||
}
|
||||
|
||||
function normalizeSubFetchChildren(children: unknown[]): unknown[] {
|
||||
const callbacks = children.filter((child) => typeof child === "function");
|
||||
if (callbacks.length !== 1) return children;
|
||||
const callback = callbacks[0];
|
||||
if (children.some((child) => !isEmptySubFetchChild(child) && child !== callback)) return children;
|
||||
return [callback];
|
||||
}
|
||||
|
||||
function isEmptySubFetchChild(child: unknown): boolean {
|
||||
return child === null || child === undefined || child === false || child === true || child === "";
|
||||
}
|
||||
|
||||
function jsxTagName(node: AstNode): string {
|
||||
if (node.type === "JSXIdentifier") return String(node.name);
|
||||
if (node.type === "JSXMemberExpression") {
|
||||
return `${jsxTagName(asNode(node.object, "JSX member object"))}.${jsxTagName(asNode(node.property, "JSX member property"))}`;
|
||||
}
|
||||
throw new SafeJsxError(`Unsupported JSX tag: ${node.type}`);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
export const CUSTOM_JSX_LIMITS = Object.freeze({
|
||||
templateLength: 50_000,
|
||||
astDepth: 64,
|
||||
operations: 25_000,
|
||||
collectionItems: 4_000,
|
||||
renderedNodes: 10_000,
|
||||
stringLength: 200_000,
|
||||
});
|
||||
|
||||
export const CUSTOM_JSX_BINDING_IDENTIFIER_PATTERN = /^[A-Za-z][A-Za-z0-9_-]*$/u;
|
||||
|
||||
export const CUSTOM_JSX_BLOCKED_PROPERTIES: ReadonlySet<string> = new Set([
|
||||
"__proto__",
|
||||
"apply",
|
||||
"arguments",
|
||||
"bind",
|
||||
"call",
|
||||
"callee",
|
||||
"caller",
|
||||
"constructor",
|
||||
"prototype",
|
||||
]);
|
||||
|
||||
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",
|
||||
"srcDoc",
|
||||
"suppressContentEditableWarning",
|
||||
"suppressHydrationWarning",
|
||||
"withinPortal",
|
||||
]);
|
||||
|
||||
export const CUSTOM_JSX_BLOCKED_TAGS: ReadonlySet<string> = new Set([
|
||||
"base",
|
||||
"embed",
|
||||
"form",
|
||||
"iframe",
|
||||
"link",
|
||||
"meta",
|
||||
"object",
|
||||
"script",
|
||||
"style",
|
||||
]);
|
||||
|
||||
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",
|
||||
"behavior",
|
||||
"bottom",
|
||||
"clipPath",
|
||||
"content",
|
||||
"filter",
|
||||
"inset",
|
||||
"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,144 @@
|
||||
interface RegexGroupState {
|
||||
atomCount: number;
|
||||
containsAlternation: boolean;
|
||||
containsQuantifier: boolean;
|
||||
}
|
||||
|
||||
interface RegexQuantifier {
|
||||
nextIndex: number;
|
||||
variable: boolean;
|
||||
}
|
||||
|
||||
const MAX_REGEX_PATTERN_LENGTH = 128;
|
||||
const MAX_EXACT_REPETITION = 1_000;
|
||||
|
||||
/**
|
||||
* JavaScript's regular-expression engine can backtrack exponentially. Keep authored
|
||||
* expressions in a deliberately small, linear-time subset: no lookarounds or
|
||||
* backreferences, no repeated alternatives/groups, and at most one quantifier that
|
||||
* can consume a variable number of characters in the whole expression.
|
||||
*/
|
||||
export 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 > MAX_REGEX_PATTERN_LENGTH ||
|
||||
typeof flags !== "string" ||
|
||||
/[^gimsu]/u.test(flags)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return isSafeRegexPattern(pattern);
|
||||
}
|
||||
|
||||
function isSafeRegexPattern(pattern: string): boolean {
|
||||
const groups: RegexGroupState[] = [createGroupState()];
|
||||
let variableQuantifiers = 0;
|
||||
let index = 0;
|
||||
|
||||
const consumeAtom = (nested?: RegexGroupState): boolean => {
|
||||
const parent = groups.at(-1);
|
||||
if (!parent) return false;
|
||||
parent.atomCount += 1;
|
||||
if (nested) {
|
||||
parent.containsAlternation ||= nested.containsAlternation;
|
||||
parent.containsQuantifier ||= nested.containsQuantifier;
|
||||
}
|
||||
const quantifier = readQuantifier(pattern, index);
|
||||
if (!quantifier) return true;
|
||||
if (quantifier.nextIndex > pattern.length) return false;
|
||||
if (nested && (nested.atomCount === 0 || nested.containsAlternation || nested.containsQuantifier)) return false;
|
||||
parent.containsQuantifier = true;
|
||||
if (quantifier.variable && ++variableQuantifiers > 1) return false;
|
||||
index = quantifier.nextIndex;
|
||||
return true;
|
||||
};
|
||||
|
||||
while (index < pattern.length) {
|
||||
const character = pattern[index];
|
||||
if (character === "\\") {
|
||||
const escaped = pattern[index + 1];
|
||||
if (escaped === undefined || /[1-9k]/u.test(escaped)) return false;
|
||||
index += 2;
|
||||
if (!consumeAtom()) return false;
|
||||
continue;
|
||||
}
|
||||
if (character === "[") {
|
||||
index += 1;
|
||||
let closed = false;
|
||||
while (index < pattern.length) {
|
||||
if (pattern[index] === "\\") index += 2;
|
||||
else {
|
||||
const classCharacter = pattern[index++];
|
||||
if (classCharacter === "]") {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!closed || !consumeAtom()) return false;
|
||||
continue;
|
||||
}
|
||||
if (character === "(") {
|
||||
if (pattern[index + 1] === "?") return false;
|
||||
groups.push(createGroupState());
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (character === ")") {
|
||||
if (groups.length === 1) return false;
|
||||
const nested = groups.pop();
|
||||
index += 1;
|
||||
if (!nested || !consumeAtom(nested)) return false;
|
||||
continue;
|
||||
}
|
||||
if (character === "|") {
|
||||
const current = groups.at(-1);
|
||||
if (!current) return false;
|
||||
current.containsAlternation = true;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (character === "^" || character === "$") {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if (character === "*" || character === "+" || character === "?" || character === "{") {
|
||||
// A valid quantifier is consumed with its atom. Reaching one here means it is
|
||||
// malformed or is an unsupported literal brace construct.
|
||||
return false;
|
||||
}
|
||||
index += 1;
|
||||
if (!consumeAtom()) return false;
|
||||
}
|
||||
|
||||
return groups.length === 1;
|
||||
}
|
||||
|
||||
function createGroupState(): RegexGroupState {
|
||||
return { atomCount: 0, containsAlternation: false, containsQuantifier: false };
|
||||
}
|
||||
|
||||
function readQuantifier(pattern: string, index: number): RegexQuantifier | null {
|
||||
const character = pattern[index];
|
||||
if (character === "*" || character === "+" || character === "?") {
|
||||
const nextIndex = pattern[index + 1] === "?" ? index + 2 : index + 1;
|
||||
return { nextIndex, variable: true };
|
||||
}
|
||||
if (character !== "{") return null;
|
||||
const match = /^\{(\d+)(?:,(\d*))?\}/u.exec(pattern.slice(index));
|
||||
if (!match) return null;
|
||||
const minimum = Number(match[1]);
|
||||
const maximum = match[2] === undefined || match[2] === "" ? undefined : Number(match[2]);
|
||||
if (
|
||||
!Number.isSafeInteger(minimum) ||
|
||||
minimum > MAX_EXACT_REPETITION ||
|
||||
(maximum !== undefined && (!Number.isSafeInteger(maximum) || maximum > MAX_EXACT_REPETITION))
|
||||
) {
|
||||
return { nextIndex: pattern.length + 1, variable: true };
|
||||
}
|
||||
let nextIndex = index + match[0].length;
|
||||
if (pattern[nextIndex] === "?") nextIndex += 1;
|
||||
return { nextIndex, variable: match[2] !== undefined && maximum !== minimum };
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { customJsxTablerIconNames } from "../core/tabler-icons";
|
||||
|
||||
const supportedIconNames: ReadonlySet<string> = new Set(customJsxTablerIconNames);
|
||||
|
||||
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 (componentName === "TablerIcon" && propName === "name") {
|
||||
if (typeof value !== "string" || !supportedIconNames.has(value)) {
|
||||
return "TablerIcon.name must be a registered kebab-case icon name, such as server, database, bell, cloud, or circle-check; React component names such as IconServer are not supported";
|
||||
}
|
||||
}
|
||||
if (propName === "resetKey" && value !== null) {
|
||||
const scalar =
|
||||
typeof value === "string" || typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value));
|
||||
if (!scalar) return "resetKey supports only a finite number, string, boolean, or null";
|
||||
}
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
import type { ComponentType, ReactNode } from "react";
|
||||
import { createContext, createElement, useContext, useEffect, useId, useRef } from "react";
|
||||
import * as Core from "@mantine/core";
|
||||
import * as Charts from "@mantine/charts";
|
||||
import * as Dates from "@mantine/dates";
|
||||
|
||||
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 { createCopyButton } from "./copy-button";
|
||||
import { Collapsible, PaginatedList, StatBar, TabPanel, TabsContainer, TypeBadge } from "./interactive-components";
|
||||
import { getScopedCustomJsxControlName, isSafeCustomJsxUrl } from "./runtime-component-policy";
|
||||
import { sanitizeCustomJsxProps } from "./safe-properties";
|
||||
|
||||
type Namespace = object;
|
||||
|
||||
function resolveExport(namespace: Namespace, name: string): ComponentType<never> | undefined {
|
||||
let value: unknown = namespace;
|
||||
for (const segment of name.split(".")) {
|
||||
if (!value || (typeof value !== "object" && typeof value !== "function") || !Object.hasOwn(value, segment)) {
|
||||
return undefined;
|
||||
}
|
||||
value = Reflect.get(value, segment);
|
||||
}
|
||||
return typeof value === "function" || (typeof value === "object" && value !== null)
|
||||
? (value as ComponentType<never>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
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;
|
||||
resetInput(name: string, type: WidgetInputType): void;
|
||||
}
|
||||
|
||||
const CustomJsxInputsContext = createContext<CustomJsxInputsContextValue | null>(null);
|
||||
|
||||
export function CustomJsxInputsProvider({
|
||||
children,
|
||||
scopeId,
|
||||
inputs,
|
||||
inputTypes,
|
||||
registerInput,
|
||||
setInputValue,
|
||||
resetInput,
|
||||
}: CustomJsxInputsContextValue & { children: ReactNode }) {
|
||||
return (
|
||||
<CustomJsxInputsContext.Provider value={{ scopeId, inputs, inputTypes, registerInput, setInputValue, resetInput }}>
|
||||
{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 serializedResetKey = serializeResetKey(props.resetKey);
|
||||
const sanitized = sanitizeCustomJsxProps(props, componentName);
|
||||
if (namedRadioComponents.has(componentName) && typeof sanitized.name === "string") {
|
||||
sanitized.name = getScopedCustomJsxControlName(context?.scopeId ?? detachedScopeId, sanitized.name);
|
||||
}
|
||||
delete sanitized.bind;
|
||||
delete sanitized.resetKey;
|
||||
const inputType = getCustomJsxBindingType(componentName, sanitized);
|
||||
const initialValue = getInitialInputValue(inputType, sanitized);
|
||||
const serializedInitialValue = JSON.stringify(initialValue);
|
||||
const isBound = Boolean(binding && context && inputType && customJsxBindableComponentNames.has(componentName));
|
||||
const registerInput = context?.registerInput;
|
||||
useEffect(() => {
|
||||
if (!isBound || !binding || !registerInput || !inputType || serializedInitialValue === undefined) return;
|
||||
return registerInput(binding, inputType, JSON.parse(serializedInitialValue) as WidgetInputValue);
|
||||
}, [binding, inputType, isBound, registerInput, serializedInitialValue]);
|
||||
const previousResetKey = useRef<{ initialized: boolean; value?: string }>({ initialized: false });
|
||||
const resetInput = context?.resetInput;
|
||||
useEffect(() => {
|
||||
const previous = previousResetKey.current;
|
||||
previousResetKey.current = { initialized: true, value: serializedResetKey };
|
||||
if (!previous.initialized || previous.value === serializedResetKey || serializedResetKey === undefined) return;
|
||||
if (!isBound || !binding || !inputType || !resetInput) return;
|
||||
resetInput(binding, inputType);
|
||||
}, [binding, inputType, isBound, resetInput, serializedResetKey]);
|
||||
if (!isBound || !binding || !context || !inputType) return sanitized;
|
||||
delete sanitized.defaultValue;
|
||||
delete sanitized.defaultChecked;
|
||||
let currentValue = initialValue;
|
||||
if (context.inputTypes[binding] === inputType && Object.hasOwn(context.inputs, binding)) {
|
||||
const storedValue = context.inputs[binding];
|
||||
if (storedValue !== undefined) currentValue = storedValue;
|
||||
}
|
||||
|
||||
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 serializeResetKey(value: unknown) {
|
||||
if (value === null) return "null";
|
||||
if (typeof value === "number") return Number.isFinite(value) ? `number:${value}` : undefined;
|
||||
if (typeof value === "string") return `string:${value}`;
|
||||
if (typeof value === "boolean") return `boolean:${value}`;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
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" && Number.isFinite(candidate)) 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" && Number.isFinite(item))
|
||||
)
|
||||
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);
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
export interface CustomJsxComponentAdapters {
|
||||
TablerIcon: ComponentType<never>;
|
||||
copyLabels: { copy: string; copied: string };
|
||||
}
|
||||
|
||||
export function createCustomJsxComponents(adapters: CustomJsxComponentAdapters): Record<string, ComponentType<never>> {
|
||||
const namespaces: Record<string, Namespace> = {
|
||||
"@mantine/core": Core,
|
||||
"@mantine/charts": Charts,
|
||||
"@mantine/dates": Dates,
|
||||
};
|
||||
const components: Record<string, ComponentType<never>> = {};
|
||||
for (const descriptor of enabledCustomJsxComponents) {
|
||||
const namespace = namespaces[descriptor.package];
|
||||
const component = namespace ? resolveExport(namespace, descriptor.name) : undefined;
|
||||
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: Namespace = Core;
|
||||
for (const name of [
|
||||
"Notification",
|
||||
"LoadingOverlay",
|
||||
"Overlay",
|
||||
"Breadcrumbs",
|
||||
"Stepper",
|
||||
"Tree",
|
||||
"Button",
|
||||
"ActionIcon",
|
||||
"Burger",
|
||||
"CloseButton",
|
||||
"Chip",
|
||||
] as const) {
|
||||
const component = resolveExport(core, name);
|
||||
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} />;
|
||||
Object.assign(components, {
|
||||
CopyButton: createCopyButton(adapters.copyLabels),
|
||||
PaginatedList,
|
||||
TabsContainer,
|
||||
TabPanel,
|
||||
Collapsible,
|
||||
StatBar,
|
||||
TypeBadge,
|
||||
TablerIcon: adapters.TablerIcon,
|
||||
SubFetch,
|
||||
SubData,
|
||||
ActionButton,
|
||||
ToggleSwitch,
|
||||
RefreshButton,
|
||||
});
|
||||
return components;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
const safeCallables = new WeakSet<(...args: never[]) => unknown>();
|
||||
|
||||
/**
|
||||
* Marks a host function as callable by the Custom JSX interpreter.
|
||||
*
|
||||
* The interpreter never calls an arbitrary function obtained from data or a
|
||||
* prototype. Host helpers must opt in through this module instead.
|
||||
*/
|
||||
export function createSafeCallable<T extends (...args: never[]) => unknown>(callable: T): T {
|
||||
safeCallables.add(callable);
|
||||
return callable;
|
||||
}
|
||||
|
||||
export function isSafeCallable(value: unknown): value is (...args: never[]) => unknown {
|
||||
return typeof value === "function" && safeCallables.has(value as (...args: never[]) => unknown);
|
||||
}
|
||||
@@ -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",
|
||||
]);
|
||||
@@ -0,0 +1,202 @@
|
||||
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_STYLE_KEYS,
|
||||
CUSTOM_JSX_URL_PROPS,
|
||||
isBlockedCustomJsxProp,
|
||||
normalizeCustomJsxProperty,
|
||||
} from "./policy";
|
||||
|
||||
export function normalizedProperty(value: unknown): string {
|
||||
if (typeof value !== "string" && typeof value !== "number") {
|
||||
throw new SafeJsxError("Property names must be strings or numbers");
|
||||
}
|
||||
const property = String(value);
|
||||
if (CUSTOM_JSX_BLOCKED_PROPERTIES.has(normalizeCustomJsxProperty(property))) {
|
||||
throw new SafeJsxError(`Access to reflective property '${property}' is not allowed`);
|
||||
}
|
||||
return property;
|
||||
}
|
||||
|
||||
function isArrayIndex(property: string): boolean {
|
||||
if (!/^(?:0|[1-9]\d*)$/.test(property)) return false;
|
||||
const index = Number(property);
|
||||
return Number.isSafeInteger(index) && index >= 0;
|
||||
}
|
||||
|
||||
export function ownProperty(object: unknown, propertyValue: unknown): unknown {
|
||||
const property = normalizedProperty(propertyValue);
|
||||
if (object == null) return undefined;
|
||||
|
||||
if (Array.isArray(object)) {
|
||||
if (property === "length") return object.length;
|
||||
if (!isArrayIndex(property)) return undefined;
|
||||
return Object.hasOwn(object, property) ? object[Number(property)] : undefined;
|
||||
}
|
||||
|
||||
if (typeof object === "string") {
|
||||
if (property === "length") return object.length;
|
||||
if (!isArrayIndex(property)) return undefined;
|
||||
return object[Number(property)];
|
||||
}
|
||||
|
||||
if (typeof object !== "object") return undefined;
|
||||
return Object.hasOwn(object, property) ? (object as Record<string, unknown>)[property] : undefined;
|
||||
}
|
||||
|
||||
function isSafeUrl(value: unknown): boolean {
|
||||
if (typeof value !== "string") return false;
|
||||
if (value.startsWith("#")) return true;
|
||||
if (value.startsWith("/") && !value.startsWith("//")) return true;
|
||||
try {
|
||||
const parsed = new URL(value);
|
||||
return (parsed.protocol === "http:" || parsed.protocol === "https:") && !parsed.username && !parsed.password;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizeStyle(value: unknown): Record<string, string | number> | undefined {
|
||||
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)) continue;
|
||||
if (typeof styleValue !== "string" && typeof styleValue !== "number") continue;
|
||||
if (typeof styleValue === "string" && /(?:url\s*\(|expression\s*\(|javascript:|position\s*:)/i.test(styleValue)) {
|
||||
continue;
|
||||
}
|
||||
result[key] = styleValue;
|
||||
}
|
||||
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 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(child)) safe[key] = child;
|
||||
continue;
|
||||
}
|
||||
if (key === "style") {
|
||||
const style = sanitizeStyle(child);
|
||||
if (style) safe.style = style;
|
||||
continue;
|
||||
}
|
||||
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