fix(custom-widgets): address v2 merge review (#6446)

This commit is contained in:
Thomas authored and GitHub committed 2026-07-23 01:55:15 +02:00
1 parent 6aceb2fd1f
commit df967751f6
123 files changed
+8632 -1477

No files matched your search

@@ -7,7 +7,7 @@ import {
import type { AstNode } from "./analyzer-ast";
import { containsEscapingCallback, nodeOf, nodesOf } from "./analyzer-ast";
import { closestCustomJsxComponentName, customJsxTagName, isSafeLiteralCustomJsxUrl } from "./analyzer-language";
import { CUSTOM_JSX_URL_PROPS, isBlockedCustomJsxProp } from "./policy";
import { CUSTOM_JSX_BINDING_IDENTIFIER_PATTERN, CUSTOM_JSX_URL_PROPS, isBlockedCustomJsxProp } from "./policy";
import { getInvalidCustomJsxPropValueReason } from "./runtime-component-policy";
interface AnalyzerJsxContext {
@@ -75,6 +75,7 @@ export function analyzeCustomJsxElement(
} 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);
}
@@ -88,6 +89,15 @@ export function analyzeCustomJsxElement(
});
}
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,
+5 -12
View File
@@ -23,6 +23,7 @@ import {
CUSTOM_JSX_CALLBACK_METHODS,
CUSTOM_JSX_SAFE_VALUE_METHODS,
} from "./safe-language-policy";
import { isSafeRegexLiteral } from "./regex-policy";
export type { CustomJsxTemplateDiagnostic } from "./analyzer-diagnostics";
@@ -153,7 +154,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
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 bounded regex without lookbehind, backreferences, or nested quantifiers");
add(node, "UNSAFE_REGEX: Use a conservative regex without repeated alternatives or variable quantifiers");
return;
case "Identifier": {
const name = String(node.name ?? "");
@@ -232,7 +233,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
}
case "CallExpression": {
const callee = nodeOf(node.callee);
const arguments_ = nodesOf(node.arguments);
const callArguments = nodesOf(node.arguments);
if (node.optional) {
add(node, "CALL_TARGET_NOT_ALLOWED: Optional calls are not supported");
}
@@ -251,7 +252,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
add(callee, "CALL_TARGET_NOT_ALLOWED: Only documented safe helpers and value methods can be called");
}
if (method && CUSTOM_JSX_CALLBACK_METHODS.has(method)) {
const callback = arguments_[0];
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") {
@@ -260,7 +261,7 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
add(callback, `CALLBACK_VALUE_NOT_ALLOWED: '${method}' requires an inline arrow or safe helper callback`);
}
}
arguments_.forEach((argument, argumentIndex) => {
callArguments.forEach((argument, argumentIndex) => {
if (argument.type === "SpreadElement") add(argument, "Spread call arguments are not supported");
else if (
argument.type === "ArrowFunctionExpression" &&
@@ -318,11 +319,3 @@ export function validateCustomJsxTemplate(template: string): CustomJsxTemplateDi
return diagnostics;
}
function isSafeRegexLiteral(regex: unknown): boolean {
if (!regex || typeof regex !== "object") return false;
const { pattern, flags } = regex as { pattern?: unknown; flags?: unknown };
if (typeof pattern !== "string" || pattern.length > 128 || typeof flags !== "string" || /[^gimsu]/u.test(flags))
return false;
return !/\\[1-9]|\(\?<[=!]|(?:\+|\*|\{\d+(?:,\d*)?\})\)?(?:\+|\*|\{)/u.test(pattern);
}
+78 -7
View File
@@ -1,14 +1,85 @@
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 {
if (value === null || typeof value !== "object") return value;
if (Array.isArray(value)) return value.map(sanitizeData);
const safe: Record<string, unknown> = Object.create(null);
for (const [key, child] of Object.entries(value)) {
if (["constructor", "__proto__", "prototype"].includes(key)) continue;
safe[key] = sanitizeData(child);
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 safe;
return result;
}
const safeMath = Object.freeze(
@@ -11,6 +11,7 @@ import type { AstNode, EvaluationBudgets, InterpreterCallback, SafeJsxBudgets }
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";
@@ -51,16 +52,10 @@ class Interpreter {
case "Literal":
if (node.regex !== undefined) {
const regex = node.regex as { pattern?: unknown; flags?: unknown };
if (
typeof regex.pattern !== "string" ||
regex.pattern.length > 128 ||
typeof regex.flags !== "string" ||
/[^gimsu]/u.test(regex.flags) ||
/\\[1-9]|\(\?<[=!]|(?:\+|\*|\{\d+(?:,\d*)?\})\)?(?:\+|\*|\{)/u.test(regex.pattern)
) {
if (!isSafeRegexLiteral(regex)) {
throw new SafeJsxError("UNSAFE_REGEX: Invalid regular expression literal");
}
return new RegExp(regex.pattern, regex.flags);
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");
@@ -43,7 +43,12 @@ export function emitJsxElement(
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)) Object.assign(rawProps, spread);
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}`);
@@ -7,6 +7,8 @@ export const CUSTOM_JSX_LIMITS = Object.freeze({
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",
@@ -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 };
}