Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

js-runtime: allowlist the template validator and run templates in a vm

Carl-Gerhard Lindesvärd9bd5fb4bea93
diff --git a/packages/core/src/shared/js-runtime/execute.ts b/packages/core/src/shared/js-runtime/execute.ts
index aa6ef4116..609ad6b13 100644
--- a/packages/core/src/shared/js-runtime/execute.ts
+++ b/packages/core/src/shared/js-runtime/execute.ts
@@ -1,5 +1,17 @@
+import { runInNewContext } from 'node:vm';
import { validate } from './validate';
+/**
+ * Wall-clock budget for one template run. The validator refuses loops,
+ * recursion and calls to template-defined functions, so an honest template
+ * finishes in a few milliseconds; this is the backstop for a pathological
+ * regex or a huge .repeat().
+ */
+const EXECUTION_TIMEOUT_MS = 250;
+
+/** Cap on the serialized output so a template cannot balloon a webhook body. */
+const MAX_OUTPUT_BYTES = 1_000_000;
+
/**
* Executes a JavaScript function template
* @param code - JavaScript function code (arrow function or function expression)
@@ -11,26 +23,42 @@ export function execute(
payload: Record<string, unknown>
): unknown {
// Templates are checked when they are saved, but the stored string is what
- // ends up in new Function() here. Check it again at run time rather than
- // trusting whatever passed validation at save time.
+ // ends up being run here. Check it again at run time rather than trusting
+ // whatever passed validation at save time.
const validation = validate(code);
if (!validation.valid) {
throw new Error(`Invalid JavaScript template: ${validation.error}`);
}
try {
- // Create the function code that will be executed
- // 'use strict' ensures 'this' is undefined (not global object)
- const funcCode = `
- 'use strict';
- return (${code})(payload);
- `;
-
- // Create function with safe globals in scope
- const func = new Function('payload', funcCode);
+ // The template runs in a fresh V8 context with its own globals, with
+ // eval/new Function disabled there. The payload crosses in as JSON and
+ // the result crosses out as JSON, so the template never holds a
+ // reference to a host-realm object and nothing it returns carries a host
+ // prototype or function back into the worker. This is not a security
+ // boundary on its own (the validator is), but it means a validator miss
+ // lands in an empty realm instead of the worker process.
+ const script = `'use strict'; JSON.stringify((${code})(JSON.parse(payloadJson)));`;
+ const resultJson: unknown = runInNewContext(
+ script,
+ { payloadJson: JSON.stringify(payload) },
+ {
+ timeout: EXECUTION_TIMEOUT_MS,
+ contextCodeGeneration: { strings: false, wasm: false },
+ microtaskMode: 'afterEvaluate',
+ }
+ );
- // Execute the function
- return func(payload);
+ if (resultJson === undefined) {
+ return undefined;
+ }
+ if (typeof resultJson !== 'string') {
+ throw new Error('Template did not return a JSON-serializable value');
+ }
+ if (Buffer.byteLength(resultJson, 'utf8') > MAX_OUTPUT_BYTES) {
+ throw new Error('Template output is too large');
+ }
+ return JSON.parse(resultJson);
} catch (error) {
throw new Error(
`Error executing JavaScript template: ${
diff --git a/packages/core/src/shared/js-runtime/validate.test.ts b/packages/core/src/shared/js-runtime/validate.test.ts
index 53649592a..c08aa2e76 100644
--- a/packages/core/src/shared/js-runtime/validate.test.ts
+++ b/packages/core/src/shared/js-runtime/validate.test.ts
@@ -1,3 +1,4 @@
+// Ported from packages/js-runtime/src/validate.test.ts (main #510, #511).
import { describe, expect, it } from 'bun:test';
import { execute, validate } from './index';
@@ -145,7 +146,7 @@ describe('validate', () => {
`(payload) => payload['constructor']['constructor']('return 1')()`
);
expect(result.valid).toBe(false);
- expect(result.error).toContain('Computed property access');
+ expect(result.error).toContain('not allowed');
});
it('should block a computed call target reached by optional chaining', () => {
@@ -153,7 +154,7 @@ describe('validate', () => {
`(payload) => payload?.['constructor']['constructor']('return 1')()`
);
expect(result.valid).toBe(false);
- expect(result.error).toContain('Computed property access');
+ expect(result.error).toContain('not allowed');
});
it('should block a computed key written with escape sequences', () => {
@@ -161,7 +162,7 @@ describe('validate', () => {
`(payload) => payload['\\u0063onstructor']['constructor']('return 1')()`
);
expect(result.valid).toBe(false);
- expect(result.error).toContain('Computed property access');
+ expect(result.error).toContain('not allowed');
});
it('should block a computed call target on a nested value', () => {
@@ -191,6 +192,186 @@ describe('validate', () => {
});
});
+ describe('Reads that reach the Function constructor', () => {
+ // Every form here stores or forwards a reference instead of calling it
+ // as a member, which the call checks alone never see. See
+ // GHSA-mc99-9jf5-22cq / GHSA-fmf9-23m7-xg84.
+ it('should block reading .constructor into a local', () => {
+ const result = validate(
+ '(payload) => { const F = payload.constructor.constructor; return F; }'
+ );
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain("'constructor'");
+ });
+
+ it('should block reading .constructor through optional chaining', () => {
+ const result = validate('(payload) => payload?.constructor');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain("'constructor'");
+ });
+
+ it('should block reading .constructor off a literal', () => {
+ const result = validate('(payload) => [].constructor');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain("'constructor'");
+ });
+
+ it('should block reading __proto__ and prototype', () => {
+ expect(validate('(payload) => payload.__proto__').valid).toBe(false);
+ expect(validate('(payload) => payload.name.prototype').valid).toBe(false);
+ });
+
+ it('should block destructuring a forbidden key', () => {
+ const result = validate(
+ '(payload) => { const { constructor: C } = payload; return C; }'
+ );
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain("Destructuring 'constructor'");
+ });
+
+ it('should block destructuring with a computed key', () => {
+ const result = validate(
+ '(payload) => { const { [payload.k]: v } = payload; return v; }'
+ );
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('Computed keys in destructuring');
+ });
+
+ it('should block dynamic computed reads', () => {
+ const result = validate('(payload) => payload[payload.key]');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('Dynamic computed property access');
+ });
+
+ it('should block a template literal key with substitutions', () => {
+ // Built by concatenation so the source file itself has no placeholder.
+ const code = ['(payload) => payload[`$', '{payload.key}`]'].join('');
+ const result = validate(code);
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('Dynamic computed property access');
+ });
+
+ it('should block a sequence-expression callee', () => {
+ const result = validate('(payload) => (0, payload.name.toUpperCase)()');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('Calling the result of an expression');
+ });
+
+ it('should block calling the result of a call', () => {
+ const result = validate('(payload) => JSON.parse(payload.raw)()');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('Calling the result of an expression');
+ });
+
+ it('should block tagged template literals', () => {
+ const result = validate('(payload) => payload.name.trim`x`');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('Tagged template literals');
+ });
+
+ it('should still allow literal keys and numeric indexes', () => {
+ const result = validate(
+ `(payload) => ({ a: payload['name'], b: payload.items[0], c: payload.items.at(-1) })`
+ );
+ expect(result.valid).toBe(true);
+ });
+
+ it('should block calling a local variable', () => {
+ const result = validate(
+ '(payload) => { const fmt = payload.name; return fmt(payload.name); }'
+ );
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain("Calling 'fmt'");
+ });
+
+ it('should block an immediately invoked arrow function', () => {
+ const result = validate('(payload) => (() => payload.name)()');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('Calling the result of an expression');
+ });
+
+ it('should block calling a global that is not a function', () => {
+ const result = validate('(payload) => Math(payload.name)');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain("Calling 'Math'");
+ });
+
+ it('should block a static method on a shadowed global', () => {
+ const result = validate(
+ '(payload) => { const JSON = payload; return JSON.parse(payload.raw); }'
+ );
+ expect(result.valid).toBe(false);
+ });
+
+ it('should block new Date when Date is shadowed', () => {
+ const result = validate(
+ '(payload) => { const Date = payload; return new Date(); }'
+ );
+ expect(result.valid).toBe(false);
+ });
+
+ it('should block assigning to a method on a global', () => {
+ const result = validate(
+ '(payload) => { Math.round = (x) => Math.round(x); return Math.round(1); }'
+ );
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('only target local variables');
+ });
+
+ it('should block assigning to a global itself', () => {
+ const result = validate('(payload) => { JSON = payload; return 1; }');
+ expect(result.valid).toBe(false);
+ });
+
+ it('should block an arrow stored in a variable', () => {
+ const result = validate('(payload) => { const f = (x) => x; return 1; }');
+ expect(result.valid).toBe(false);
+ expect(result.error).toContain('callbacks passed directly');
+ });
+
+ it('should block an arrow in an object literal', () => {
+ const result = validate('(payload) => ({ f: (x) => x })');
+ expect(result.valid).toBe(false);
+ });
+
+ it('should still allow callbacks passed to allowed methods', () => {
+ const result = validate(
+ '(payload) => payload.tags.map((t) => t.toUpperCase()).filter((t) => t.length > 1)'
+ );
+ expect(result.valid).toBe(true);
+ });
+ });
+
+ describe('Allowlist fallbacks', () => {
+ it('should reject syntax outside the allowlist by default', () => {
+ // A class field, a label, a switch: none of these need a dedicated
+ // rule, they are refused because they are not on the list.
+ expect(
+ validate(
+ '(payload) => { switch (payload.name) { default: return 1; } }'
+ ).valid
+ ).toBe(false);
+ expect(validate('(payload) => { x: return 1; }').valid).toBe(false);
+ expect(validate('(payload) => { var x = 1; return x; }').valid).toBe(
+ false
+ );
+ expect(validate('(payload) => { let i = 0; i++; return i; }').valid).toBe(
+ false
+ );
+ expect(validate('(payload) => delete payload.name').valid).toBe(false);
+ expect(validate('(payload) => ({ [payload.k]: 1 })').valid).toBe(false);
+ expect(validate('(payload) => ({ f() { return 1; } })').valid).toBe(
+ false
+ );
+ expect(validate('async (payload) => payload').valid).toBe(false);
+ });
+
+ it('should reject TypeScript syntax', () => {
+ const result = validate('(payload: any) => payload');
+ expect(result.valid).toBe(false);
+ });
+ });
+
describe('Prototype writes', () => {
it('should block writing through __proto__', () => {
const result = validate(
@@ -431,4 +612,64 @@ describe('execute', () => {
}).toThrow('Invalid JavaScript template');
});
});
+
+ describe('Templates in use in production', () => {
+ // Real templates customers have saved. Every one must keep validating
+ // and executing whenever the allowlist is tightened.
+ const productionTemplates = [
+ `(payload) => ({ name: payload.name || 'identify', profileId: payload.profileId, timestamp: new Date(payload.createdAt).toISOString(), properties: { ...(payload.properties || {}), country: payload.country, city: payload.city, device: payload.device, os: payload.os, browser: payload.browser, path: payload.path, firstName: payload.profile ? payload.profile.firstName : undefined, lastName: payload.profile ? payload.profile.lastName : undefined, email: payload.profile ? payload.profile.email : undefined } })`,
+ `(payload) => { if (!payload.profileId || !payload.profileId.includes('@')) return null; return { email_address: payload.profileId, fields: { "city": payload.city || "", "country": payload.country || "" } }; }`,
+ '(payload) => ({ event: payload.name, email: payload.properties?.email ?? null, occurredAt: payload.createdAt })',
+ `(payload) => { return { event_name: payload.name, first_name: payload.properties?.first_name || '', last_name: payload.properties?.last_name || '', email: payload.properties?.email || '', phone: payload.properties?.phone || '', sms_consent: payload.properties?.sms_consent || '', form_name: payload.properties?.form_name || '', form_id: payload.properties?.form_id || '', page_url: payload.properties?.page_url || '' }; }`,
+ ];
+
+ it.each(productionTemplates)('validates and runs: %s', (code) => {
+ expect(validate(code)).toEqual({ valid: true });
+ expect(() => execute(code, basePayload)).not.toThrow();
+ });
+
+ it('produces the expected shape for the identify template', () => {
+ const result = execute(productionTemplates[0]!, basePayload) as Record<
+ string,
+ unknown
+ >;
+ expect(result.name).toBe('page_view');
+ expect(result.timestamp).toBe('2024-01-15T10:30:00.000Z');
+ expect(result.properties).toMatchObject({
+ plan: 'premium',
+ city: 'New York',
+ firstName: 'John',
+ });
+ });
+
+ it('returns null when the template returns null', () => {
+ expect(execute(productionTemplates[1]!, basePayload)).toBeNull();
+ });
+ });
+
+ describe('Isolation', () => {
+ it('does not hand the template a host object', () => {
+ // The payload crosses into the context as JSON, so mutations never
+ // reach the caller's object.
+ const payload = { name: 'x', nested: { a: 1 } };
+ execute(
+ '(payload) => { payload.nested.a = 2; return payload; }',
+ payload
+ );
+ expect(payload.nested.a).toBe(1);
+ });
+
+ it('measures the output cap in UTF-8 bytes', () => {
+ // 600k three-byte characters is 600k UTF-16 units but 1.8MB on the wire.
+ expect(() => execute("(payload) => 'ࠀ'.repeat(600000)", {})).toThrow(
+ 'too large'
+ );
+ });
+
+ it('stops a template that runs too long', () => {
+ expect(() =>
+ execute("(payload) => 'a'.repeat(100000000).replace(/(a+)+b/, '')", {})
+ ).toThrow('Error executing JavaScript template');
+ });
+ });
});
diff --git a/packages/core/src/shared/js-runtime/validate.ts b/packages/core/src/shared/js-runtime/validate.ts
index 817e65503..ce7f16d20 100644
--- a/packages/core/src/shared/js-runtime/validate.ts
+++ b/packages/core/src/shared/js-runtime/validate.ts
@@ -11,23 +11,159 @@ import {
} from './constants';
/**
- * Property names that must never be written through. Assigning to any of
- * these reaches objects shared with the rest of the worker process.
+ * The template language is an allowlist, not a denylist.
+ *
+ * Every AST node type the walker meets must be in ALLOWED_NODE_TYPES or the
+ * template is refused, so a syntax form nobody thought about (a tagged
+ * template, a sequence expression, a class field, ...) is rejected by
+ * default instead of walking past the checks. What is left is deliberately
+ * small: build an object from the payload with property access, literals,
+ * template strings, ternaries, and the allowlisted built-in methods.
+ *
+ * There is no way to call a function the template defined itself. Callbacks
+ * to .map() and friends are the only place an inline arrow may appear, and
+ * only allowlisted methods can invoke them. That removes recursion, IIFEs and
+ * every "store a reference now, call it later" escape in one rule.
*/
-const FORBIDDEN_WRITE_PROPERTIES = new Set([
+const ALLOWED_NODE_TYPES = new Set([
+ // Structure
+ 'File',
+ 'Program',
+ 'ExpressionStatement',
+ 'EmptyStatement',
+ 'ArrowFunctionExpression',
+ 'BlockStatement',
+ 'ReturnStatement',
+ 'IfStatement',
+ 'VariableDeclaration',
+ 'VariableDeclarator',
+
+ // Values
+ 'Identifier',
+ 'NumericLiteral',
+ 'StringLiteral',
+ 'BooleanLiteral',
+ 'NullLiteral',
+ 'RegExpLiteral',
+ 'TemplateLiteral',
+ 'TemplateElement',
+ 'ObjectExpression',
+ 'ObjectProperty',
+ 'ArrayExpression',
+ 'SpreadElement',
+
+ // Access and calls
+ 'MemberExpression',
+ 'OptionalMemberExpression',
+ 'CallExpression',
+ 'OptionalCallExpression',
+ 'NewExpression',
+
+ // Operators
+ 'BinaryExpression',
+ 'LogicalExpression',
+ 'UnaryExpression',
+ 'ConditionalExpression',
+ 'AssignmentExpression',
+
+ // Destructuring in const declarations and callback parameters
+ 'ObjectPattern',
+ 'ArrayPattern',
+ 'RestElement',
+ 'AssignmentPattern',
+]);
+
+/**
+ * Friendlier messages for the things people are most likely to try. Anything
+ * not listed here or in ALLOWED_NODE_TYPES gets a generic refusal.
+ */
+const REJECTION_MESSAGES: Record<string, string> = {
+ ImportDeclaration: 'import/export statements are not allowed',
+ ExportNamedDeclaration: 'import/export statements are not allowed',
+ ExportDefaultDeclaration: 'import/export statements are not allowed',
+ ExportAllDeclaration: 'import/export statements are not allowed',
+ Import: 'Dynamic import() is not allowed',
+ ImportExpression: 'Dynamic import() is not allowed',
+ FunctionDeclaration:
+ 'Named function declarations are not allowed inside the function body.',
+ FunctionExpression:
+ 'Function expressions are not allowed. Use arrow functions instead: (payload) => { ... }',
+ ObjectMethod:
+ 'Methods in object literals are not allowed. Use a plain property instead.',
+ WhileStatement:
+ 'Loops are not allowed. Use array methods like .map(), .filter(), .reduce() instead.',
+ DoWhileStatement:
+ 'Loops are not allowed. Use array methods like .map(), .filter(), .reduce() instead.',
+ ForStatement:
+ 'Loops are not allowed. Use array methods like .map(), .filter(), .reduce() instead.',
+ ForInStatement:
+ 'Loops are not allowed. Use array methods like .map(), .filter(), .reduce() instead.',
+ ForOfStatement:
+ 'Loops are not allowed. Use array methods like .map(), .filter(), .reduce() instead.',
+ SwitchStatement:
+ 'switch statements are not allowed. Use if or a ternary expression instead.',
+ TryStatement: 'try/catch statements are not allowed',
+ ThrowStatement: 'throw statements are not allowed',
+ WithStatement: 'with statements are not allowed',
+ ClassDeclaration: 'Class definitions are not allowed',
+ ClassExpression: 'Class definitions are not allowed',
+ AwaitExpression: 'async/await is not allowed',
+ YieldExpression: 'Generators are not allowed',
+ ThisExpression:
+ "'this' keyword is not allowed. Use the payload parameter instead.",
+ Super: "'super' is not allowed.",
+ MetaProperty: 'new.target and import.meta are not allowed.',
+ TaggedTemplateExpression: 'Tagged template literals are not allowed.',
+ SequenceExpression: 'Comma (sequence) expressions are not allowed.',
+ UpdateExpression:
+ 'Increment and decrement operators (++, --) are not allowed.',
+ LabeledStatement: 'Labels are not allowed.',
+ DebuggerStatement: 'debugger statements are not allowed.',
+};
+
+/**
+ * Property names that must never be read or written through. Reading
+ * 'constructor' off any value walks up to the Function constructor, and
+ * assigning through '__proto__' or 'prototype' reaches objects shared with
+ * the rest of the process. A template never needs any of them.
+ */
+const FORBIDDEN_PROPERTIES = new Set([
'__proto__',
'constructor',
'prototype',
+ 'caller',
+ 'callee',
]);
+/** Globals that may be called directly, as in parseInt(payload.count). */
+const ALLOWED_GLOBAL_FUNCTIONS = new Set([
+ 'parseInt',
+ 'parseFloat',
+ 'isNaN',
+ 'isFinite',
+]);
+
+const ALLOWED_UNARY_OPERATORS = new Set(['!', '-', '+', 'typeof']);
+
+const ALLOWED_ASSIGNMENT_OPERATORS = new Set([
+ '=',
+ '+=',
+ '-=',
+ '*=',
+ '/=',
+ '??=',
+ '||=',
+ '&&=',
+]);
+
+type Node = Record<string, unknown>;
+
/**
* The static name of a member expression's property, or undefined when the key
* is only known at run time (obj[someVariable]).
*/
-function staticPropertyName(
- member: Record<string, unknown>
-): string | undefined {
- const prop = member.property as Record<string, unknown> | undefined;
+function staticPropertyName(member: Node): string | undefined {
+ const prop = member.property as Node | undefined;
if (!prop) {
return undefined;
}
@@ -35,16 +171,18 @@ function staticPropertyName(
// A literal key can be resolved. Babel has already decoded any \u / \x
// escapes into StringLiteral.value by this point. A template literal
// with no substitutions (`__proto__`) is just as static as a string
- // literal and must resolve the same way, or it walks past this check
- // unseen.
+ // literal and must resolve the same way.
if (prop.type === 'StringLiteral') {
return prop.value as string;
}
+ if (prop.type === 'NumericLiteral') {
+ return String(prop.value);
+ }
if (prop.type === 'TemplateLiteral') {
const expressions = prop.expressions as unknown[];
- const quasis = prop.quasis as Record<string, unknown>[];
+ const quasis = prop.quasis as Node[];
if (expressions.length === 0 && quasis.length === 1) {
- const value = quasis[0]!.value as Record<string, unknown>;
+ const value = quasis[0]!.value as Node;
return value.cooked as string;
}
}
@@ -53,15 +191,31 @@ function staticPropertyName(
return prop.type === 'Identifier' ? (prop.name as string) : undefined;
}
+/**
+ * The static key of a property inside an object literal or destructuring
+ * pattern, or undefined when it is computed from an expression.
+ */
+function staticObjectPropertyKey(prop: Node): string | undefined {
+ const key = prop.key as Node | undefined;
+ if (!key) {
+ return undefined;
+ }
+ if (key.type === 'StringLiteral' || key.type === 'NumericLiteral') {
+ return String(key.value);
+ }
+ if (!prop.computed && key.type === 'Identifier') {
+ return key.name as string;
+ }
+ return undefined;
+}
+
/**
* Walk an assignment target back down its member chain and return the first
* forbidden property name it passes through, if any. payload.__proto__.x is a
* write to 'x' but goes through '__proto__', so the whole chain matters.
*/
-function forbiddenPropertyInChain(
- target: Record<string, unknown>
-): string | undefined {
- let current: Record<string, unknown> | undefined = target;
+function forbiddenPropertyInChain(target: Node): string | undefined {
+ let current: Node | undefined = target;
while (
current &&
@@ -69,10 +223,123 @@ function forbiddenPropertyInChain(
current.type === 'OptionalMemberExpression')
) {
const name = staticPropertyName(current);
- if (name && FORBIDDEN_WRITE_PROPERTIES.has(name)) {
+ if (name && FORBIDDEN_PROPERTIES.has(name)) {
return name;
}
- current = current.object as Record<string, unknown> | undefined;
+ current = current.object as Node | undefined;
+ }
+
+ return undefined;
+}
+
+/** The identifier at the root of a member chain: payload in payload.a.b. */
+function chainRoot(target: Node): Node | undefined {
+ let current: Node | undefined = target;
+ while (
+ current &&
+ (current.type === 'MemberExpression' ||
+ current.type === 'OptionalMemberExpression')
+ ) {
+ current = current.object as Node | undefined;
+ }
+ return current;
+}
+
+/** Validate the one statement at the root: a single arrow function. */
+function validateRoot(program: Node): string | undefined {
+ const body = program.body as Node[];
+
+ if (body.length === 0) {
+ return 'Code cannot be empty';
+ }
+
+ if (body.length > 1) {
+ return 'Code must contain only a single function. Multiple statements are not allowed.';
+ }
+
+ const rootStatement = body[0]!;
+
+ if (rootStatement.type !== 'ExpressionStatement') {
+ if (rootStatement.type === 'VariableDeclaration') {
+ return 'Variable declarations (const, let, var) are not allowed. Use a direct function expression instead.';
+ }
+ if (rootStatement.type === 'FunctionDeclaration') {
+ return 'Function declarations are not allowed. Use an arrow function or function expression instead: (payload) => { ... } or function(payload) { ... }';
+ }
+ return 'Code must be a function expression or arrow function';
+ }
+
+ const rootExpression = rootStatement.expression as Node;
+ if (rootExpression.type !== 'ArrowFunctionExpression') {
+ if (rootExpression.type === 'FunctionExpression') {
+ return 'Function expressions are not allowed. Use arrow functions instead: (payload) => { ... }';
+ }
+ return 'Code must be an arrow function, e.g.: (payload) => { ... }';
+ }
+
+ return undefined;
+}
+
+/** Check a call's callee names something on the allowlist. */
+function validateCall(
+ callee: Node,
+ declaredIdentifiers: Set<string>
+): string | undefined {
+ if (callee.type === 'Import') {
+ return 'Dynamic import() is not allowed';
+ }
+
+ // parseInt(x) and friends. A local variable is never callable: the only
+ // functions a template can hold are inline arrows, and those are only ever
+ // invoked by the allowlisted array methods they are passed to.
+ if (callee.type === 'Identifier') {
+ const name = callee.name as string;
+ if (declaredIdentifiers.has(name)) {
+ return `Calling '${name}' is not allowed. Only the built-in methods can be called.`;
+ }
+ if (!ALLOWED_GLOBAL_FUNCTIONS.has(name)) {
+ return `Calling '${name}' is not allowed. Only safe built-in functions are permitted.`;
+ }
+ return undefined;
+ }
+
+ if (
+ callee.type !== 'MemberExpression' &&
+ callee.type !== 'OptionalMemberExpression'
+ ) {
+ return 'Calling the result of an expression is not allowed. Call a named function or method directly.';
+ }
+
+ // A computed key (obj[expr]()) cannot be matched against the allowlist.
+ if (callee.computed) {
+ return 'Computed property access on a call target is not allowed. Use a literal method name, e.g. value.toUpperCase().';
+ }
+
+ const obj = callee.object as Node;
+ const prop = callee.property as Node;
+ if (prop.type !== 'Identifier') {
+ return 'Calling the result of an expression is not allowed. Call a named function or method directly.';
+ }
+ const methodName = prop.name as string;
+
+ // Static method on an allowed global: Math.round(), JSON.parse(). A local
+ // that shadows the global name is an ordinary value and takes the instance
+ // branch below.
+ if (
+ obj.type === 'Identifier' &&
+ ALLOWED_GLOBALS.has(obj.name as string) &&
+ !declaredIdentifiers.has(obj.name as string)
+ ) {
+ const objName = obj.name as string;
+ if (!ALLOWED_METHODS[objName]?.has(methodName)) {
+ return `Method '${objName}.${methodName}' is not allowed. Only safe methods are permitted.`;
+ }
+ return undefined;
+ }
+
+ // Instance method on a value: arr.map(), str.toLowerCase(), arr?.map()
+ if (!ALLOWED_INSTANCE_METHODS.has(methodName)) {
+ return `Method '.${methodName}()' is not allowed. Only safe methods are permitted.`;
}
return undefined;
@@ -91,162 +358,70 @@ export function validate(code: string): {
}
try {
- // Parse the code to AST
const ast = parse(code, {
sourceType: 'module',
allowReturnOutsideFunction: true,
- plugins: ['typescript'],
});
- // Validate root structure: must be exactly one function expression
- const program = ast.program;
- const body = program.body;
-
- if (body.length === 0) {
- return { valid: false, error: 'Code cannot be empty' };
- }
-
- if (body.length > 1) {
- return {
- valid: false,
- error:
- 'Code must contain only a single function. Multiple statements are not allowed.',
- };
- }
-
- const rootStatement = body[0]!;
-
- // Must be an expression statement containing a function
- if (rootStatement.type !== 'ExpressionStatement') {
- if (rootStatement.type === 'VariableDeclaration') {
- return {
- valid: false,
- error:
- 'Variable declarations (const, let, var) are not allowed. Use a direct function expression instead.',
- };
- }
- if (rootStatement.type === 'FunctionDeclaration') {
- return {
- valid: false,
- error:
- 'Function declarations are not allowed. Use an arrow function or function expression instead: (payload) => { ... } or function(payload) { ... }',
- };
- }
- return {
- valid: false,
- error: 'Code must be a function expression or arrow function',
- };
- }
-
- const rootExpression = rootStatement.expression;
- if (rootExpression.type !== 'ArrowFunctionExpression') {
- if (rootExpression.type === 'FunctionExpression') {
- return {
- valid: false,
- error:
- 'Function expressions are not allowed. Use arrow functions instead: (payload) => { ... }',
- };
- }
- return {
- valid: false,
- error: 'Code must be an arrow function, e.g.: (payload) => { ... }',
- };
+ const rootError = validateRoot(ast.program as unknown as Node);
+ if (rootError) {
+ return { valid: false, error: rootError };
}
// Collect all declared identifiers (variables, parameters)
const declaredIdentifiers = collectDeclaredIdentifiers(ast);
+ const rootArrow = (
+ ((ast.program as unknown as Node).body as Node[])[0]! as Node
+ ).expression as Node;
let validationError: string | undefined;
- // Walk the AST to check for allowed patterns only
walkNode(ast, (node, parent) => {
// Skip if we already found an error
if (validationError) {
return;
}
- // Block import/export declarations
- if (
- node.type === 'ImportDeclaration' ||
- node.type === 'ExportDeclaration'
- ) {
- validationError = 'import/export statements are not allowed';
- return;
- }
+ const type = node.type as string;
- // Block dynamic import(). @babel/parser emits 'Import' as the callee of
- // the surrounding CallExpression; 'ImportExpression' is the ESTree shape.
- if (node.type === 'Import' || node.type === 'ImportExpression') {
- validationError = 'Dynamic import() is not allowed';
- return;
- }
-
- // Block function declarations inside the function body
- // (FunctionDeclaration creates a named function, not allowed)
- if (node.type === 'FunctionDeclaration') {
- validationError =
- 'Named function declarations are not allowed inside the function body.';
- return;
- }
-
- // Block loops - use array methods like .map(), .filter() instead
- if (
- node.type === 'WhileStatement' ||
- node.type === 'DoWhileStatement' ||
- node.type === 'ForStatement' ||
- node.type === 'ForInStatement' ||
- node.type === 'ForOfStatement'
- ) {
+ // Anything outside the allowlist is refused, with a friendlier message
+ // where we have one.
+ if (!ALLOWED_NODE_TYPES.has(type)) {
validationError =
- 'Loops are not allowed. Use array methods like .map(), .filter(), .reduce() instead.';
- return;
- }
-
- // Block advanced/dangerous features
- if (node.type === 'TryStatement') {
- validationError = 'try/catch statements are not allowed';
- return;
- }
-
- if (node.type === 'ThrowStatement') {
- validationError = 'throw statements are not allowed';
- return;
- }
-
- if (node.type === 'WithStatement') {
- validationError = 'with statements are not allowed';
+ REJECTION_MESSAGES[type] ??
+ `'${type}' syntax is not allowed. Templates support property access, literals, template strings, ternaries and the built-in methods.`;
return;
}
- if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') {
- validationError = 'Class definitions are not allowed';
- return;
- }
-
- if (node.type === 'AwaitExpression') {
- validationError = 'async/await is not allowed';
- return;
- }
-
- if (node.type === 'YieldExpression') {
- validationError = 'Generators are not allowed';
- return;
+ if (type === 'ArrowFunctionExpression') {
+ if (node.async) {
+ validationError = 'async/await is not allowed';
+ return;
+ }
+ // Besides the root, an arrow may only be a callback handed straight
+ // to a call, e.g. arr.map((x) => ...). One stored in a variable or
+ // assigned onto a global is never callable and is only useful for
+ // wrapping a built-in in itself.
+ const isDirectCallback =
+ (parent?.type === 'CallExpression' ||
+ parent?.type === 'OptionalCallExpression') &&
+ (parent.arguments as Node[]).includes(node);
+ if (node !== rootArrow && !isDirectCallback) {
+ validationError =
+ 'Arrow functions are only allowed as callbacks passed directly to a method, e.g. arr.map((x) => x.name).';
+ return;
+ }
}
- // Block 'this' keyword - arrow functions don't have their own 'this'
- // but we block it entirely to prevent any scope leakage
- if (node.type === 'ThisExpression') {
- validationError =
- "'this' keyword is not allowed. Use the payload parameter instead.";
+ if (type === 'VariableDeclaration' && node.kind === 'var') {
+ validationError = "'var' is not allowed. Use const or let instead.";
return;
}
// Check identifiers that reference globals
- if (node.type === 'Identifier') {
+ if (type === 'Identifier') {
const name = node.name as string;
- // Block 'arguments' - not available in arrow functions anyway
- // but explicitly block to prevent any confusion
if (name === 'arguments') {
validationError =
"'arguments' is not allowed. Use explicit parameters instead.";
@@ -263,80 +438,72 @@ export function validate(code: string): {
return;
}
- // Check if it's an allowed global
if (!ALLOWED_GLOBALS.has(name)) {
validationError = `Use of '${name}' is not allowed. Only safe built-in functions are permitted.`;
return;
}
}
- // Check method calls on global objects (like Math.random, JSON.parse)
- // Handles both regular calls and optional chaining (?.)
+ // Every property read is checked, not only the ones that are called or
+ // assigned: a read of 'constructor' can be stored and used later. A key
+ // that is only known at run time (obj[expr]) could be any of these
+ // names, so it is refused too; literal keys and numeric indexes work.
+ if (type === 'MemberExpression' || type === 'OptionalMemberExpression') {
+ const name = staticPropertyName(node);
+ if (name === undefined) {
+ validationError =
+ 'Dynamic computed property access (obj[expr]) is not allowed. Use a literal key such as obj.key, obj["key"] or arr[0].';
+ return;
+ }
+ if (FORBIDDEN_PROPERTIES.has(name)) {
+ validationError = `Accessing '${name}' is not allowed.`;
+ return;
+ }
+ }
+
+ // Object literal keys must be static too; { [expr]: v } is refused.
if (
- node.type === 'CallExpression' ||
- node.type === 'OptionalCallExpression'
+ type === 'ObjectProperty' &&
+ parent?.type === 'ObjectExpression' &&
+ staticObjectPropertyKey(node) === undefined
) {
- const callee = node.callee as Record<string, unknown>;
- const isMemberExpr =
- callee.type === 'MemberExpression' ||
- callee.type === 'OptionalMemberExpression';
-
- if (isMemberExpr) {
- const obj = callee.object as Record<string, unknown>;
- const prop = callee.property as Record<string, unknown>;
- const computed = callee.computed as boolean;
-
- // A computed key (obj[expr]()) cannot be matched against the
- // allowlist, because the property name is only known at run time.
- // Refuse it rather than letting it past the checks below unseen.
- if (computed) {
+ validationError =
+ 'Computed keys in object literals are not allowed. Use a literal key.';
+ return;
+ }
+
+ // Destructuring is a read too: const { constructor: C } = payload.
+ if (type === 'ObjectPattern') {
+ const properties = node.properties as Node[];
+ for (const prop of properties) {
+ if (prop.type !== 'ObjectProperty') {
+ continue;
+ }
+ const name = staticObjectPropertyKey(prop);
+ if (name === undefined) {
validationError =
- 'Computed property access on a call target is not allowed. Use a literal method name, e.g. value.toUpperCase().';
+ 'Computed keys in destructuring patterns are not allowed.';
return;
}
-
- // Static method call on global object: Math.random(), JSON.parse()
- if (obj.type === 'Identifier' && prop.type === 'Identifier') {
- const objName = obj.name as string;
- const methodName = prop.name as string;
-
- // Check if it's a call on an allowed global object
- if (
- ALLOWED_GLOBALS.has(objName) &&
- ALLOWED_METHODS[objName] &&
- !ALLOWED_METHODS[objName].has(methodName)
- ) {
- validationError = `Method '${objName}.${methodName}' is not allowed. Only safe methods are permitted.`;
- return;
- }
- }
-
- // Instance method call: arr.map(), str.toLowerCase(), arr?.map()
- // We allow these if the method name is in ALLOWED_INSTANCE_METHODS
- if (prop.type === 'Identifier') {
- const methodName = prop.name as string;
-
- // If calling on something other than an allowed global,
- // check if the method is in the allowed instance methods
- if (
- (obj.type !== 'Identifier' ||
- !ALLOWED_GLOBALS.has(obj.name as string)) &&
- !ALLOWED_INSTANCE_METHODS.has(methodName)
- ) {
- validationError = `Method '.${methodName}()' is not allowed. Only safe methods are permitted.`;
- return;
- }
+ if (FORBIDDEN_PROPERTIES.has(name)) {
+ validationError = `Destructuring '${name}' is not allowed.`;
+ return;
}
}
}
+ if (type === 'CallExpression' || type === 'OptionalCallExpression') {
+ validationError = validateCall(
+ node.callee as Node,
+ declaredIdentifiers
+ );
+ return;
+ }
+
// Check 'new' expressions - only allow new Date()
- if (node.type === 'NewExpression') {
- const callee = node.callee as Record<string, unknown>;
+ if (type === 'NewExpression') {
+ const callee = node.callee as Node;
- // Anything other than a bare identifier (a member expression, a
- // parenthesised expression, another call) names a constructor we
- // cannot resolve, so it can never be the Date we allow.
if (callee.type !== 'Identifier') {
validationError =
"The target of 'new' must be a plain identifier. Only 'new Date()' is permitted.";
@@ -344,25 +511,53 @@ export function validate(code: string): {
}
const name = callee.name as string;
- if (name !== 'Date') {
+ if (name !== 'Date' || declaredIdentifiers.has(name)) {
validationError = `'new ${name}()' is not allowed. Only 'new Date()' is permitted.`;
return;
}
}
- // Block writes that reach the prototype chain: payload.__proto__.x = 1,
- // payload['constructor'].prototype.y = 2. Reading these is already
- // handled by the call and 'new' checks above.
- if (
- node.type === 'AssignmentExpression' ||
- node.type === 'UpdateExpression'
- ) {
- const target = (node.left ?? node.argument) as Record<string, unknown>;
+ if (type === 'UnaryExpression') {
+ const operator = node.operator as string;
+ if (!ALLOWED_UNARY_OPERATORS.has(operator)) {
+ validationError = `The '${operator}' operator is not allowed.`;
+ return;
+ }
+ }
+
+ // Plain assignments to locals and to static properties of locals are
+ // fine; anything that reaches the prototype chain is not.
+ if (type === 'AssignmentExpression') {
+ const operator = node.operator as string;
+ if (!ALLOWED_ASSIGNMENT_OPERATORS.has(operator)) {
+ validationError = `The '${operator}' assignment operator is not allowed.`;
+ return;
+ }
+ const target = node.left as Node;
+ if (
+ target.type !== 'Identifier' &&
+ target.type !== 'MemberExpression'
+ ) {
+ validationError =
+ 'Assignments must target a variable or a property, e.g. out.event = payload.name.';
+ return;
+ }
const reached = forbiddenPropertyInChain(target);
if (reached) {
validationError = `Assigning through '${reached}' is not allowed.`;
return;
}
+ // Math.round = ..., JSON.parse = ...: writing to a global replaces a
+ // built-in for the rest of the run. Only locals may be written.
+ const root = chainRoot(target);
+ if (
+ root?.type !== 'Identifier' ||
+ !declaredIdentifiers.has(root.name as string)
+ ) {
+ validationError =
+ 'Assignments may only target local variables and their properties.';
+ return;
+ }
}
});