jsfe 1.68.0 → 1.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,542 @@
1
+ /** Flow expressions and named functions run in QuickJS (WebAssembly), never in the host's realm.
2
+ *
3
+ * Flow text is untrusted. The sandbox holds stand-ins (Proxies) for the host objects an expression is given; every
4
+ * property read, write, delete and key listing is a call to host code that returns only a primitive or another
5
+ * stand-in's id. No host object or host function ever enters the sandbox, so neither the host's globals nor its Function
6
+ * constructor are reachable. Only OWN properties cross; inherited members come from the sandbox's own prototypes.
7
+ *
8
+ * One sandbox per process (`sharedSandbox()`), shared by every engine: its globals and built-ins are frozen once set up,
9
+ * so no evaluation can leave state for a later one, and per evaluation the host's object table and the guest's stand-in
10
+ * cache are cleared: a stand-in never outlives its evaluation. Named functions are compiled once per process and call
11
+ * approved functions by name, from the table of the engine evaluating.
12
+ *
13
+ * Host functions (approved functions, and any function the host itself placed in data: JSON flow text cannot hold one)
14
+ * are called on the host; only their arguments and result cross, through the same bridge.
15
+ * Design and measurements: docs/expression-sandbox-design.md.
16
+ */
17
+ import { QuickJS } from '../vendor/quickjs.js';
18
+ const MARK = '';
19
+ const OBJ = MARK + 'o:', FUN = MARK + 'f:', EFUN = MARK + 'h:', GFUN = MARK + 'g:', STR = MARK + 's:', NUM = MARK + 'n:', DATE = MARK + 'd:';
20
+ const UNDEF = MARK + 'u', ABSENT = MARK + 'a';
21
+ const BUILTINS = new Set(['Object', 'Date', 'Math', 'String', 'Number', 'Boolean', 'Array', 'JSON']);
22
+ const identifier = /^[A-Za-z_$][\w$]*$/;
23
+ const COMPILED_CACHE = 1000;
24
+ export const EXPRESSION_LIMITS = Object.freeze({ memoryBytes: 256 * 1024 * 1024, stackBytes: 1024 * 1024, timeoutMs: 500 });
25
+ // Guest runtime. The host functions it is given are captured and removed from the global object before anything else
26
+ // runs; its API is the script's completion value, never a global.
27
+ const GUEST = String.raw `(function () {
28
+ 'use strict';
29
+ var G = globalThis, hostGet = G.__get, hostSet = G.__set, hostHas = G.__has, hostDel = G.__del, hostKeys = G.__keys,
30
+ hostCall = G.__call, hostFormat = G.__format;
31
+ ['__get', '__set', '__has', '__del', '__keys', '__call', '__format'].forEach(function (k) { delete G[k]; });
32
+ var M = '\uE000', byId, ids, gfuns, assigned, evalFns, hostFns = Object.create(null), hostIds = new WeakMap();
33
+ function reset() { byId = Object.create(null); ids = new WeakMap(); gfuns = []; assigned = []; evalFns = Object.create(null); }
34
+ reset();
35
+ function dec(v) {
36
+ if (typeof v !== 'string' || v.charCodeAt(0) !== 0xE000) return v;
37
+ var tag = v.slice(0, 3);
38
+ if (tag === M + 'o:') { var p = v.slice(3).split(':'); return standIn(+p[0], p[1] === 'a'); }
39
+ if (tag === M + 'f:' || tag === M + 'h:') return hostFunction(v);
40
+ if (tag === M + 's:') return v.slice(3);
41
+ if (tag === M + 'n:') return Number(v.slice(3));
42
+ if (tag === M + 'd:') return new Date(Number(v.slice(3)));
43
+ if (v === M + 'u') return undefined;
44
+ return v;
45
+ }
46
+ function enc(v) {
47
+ if (v === undefined) return M + 'u';
48
+ if (v === null || typeof v === 'boolean') return v;
49
+ if (typeof v === 'number') return isFinite(v) && !(v === 0 && 1 / v < 0) ? v : M + 'n:' + (v === 0 ? '-0' : String(v));
50
+ if (typeof v === 'string') return v.charCodeAt(0) === 0xE000 ? M + 's:' + v : v;
51
+ if (typeof v !== 'object' && typeof v !== 'function') throw new TypeError('a ' + typeof v + ' cannot leave an expression');
52
+ if (ids.has(v)) return M + 'o:' + ids.get(v);
53
+ if (typeof v === 'function') { var hid = hostIds.get(v); if (hid !== undefined) return hid; gfuns.push(v); return M + 'g:' + (gfuns.length - 1); }
54
+ if (v instanceof Date) return M + 'd:' + v.getTime();
55
+ if (Array.isArray(v)) { var a = []; for (var i = 0; i < v.length; i++) a.push(enc(v[i])); return a; }
56
+ var o = {};
57
+ Object.keys(v).forEach(function (k) { Object.defineProperty(o, k, {value: enc(v[k]), enumerable: true, writable: true, configurable: true}); });
58
+ return o;
59
+ }
60
+ // f:<name> an approved function by name (named functions hold it), h:<id> a host function for this evaluation only
61
+ function hostFunction(tag) {
62
+ var cache = tag.charAt(1) === 'f' ? hostFns : evalFns;
63
+ if (cache[tag]) return cache[tag];
64
+ var f = function () { resync(); return dec(hostCall(tag, JSON.stringify(enc(Array.prototype.slice.call(arguments))))); };
65
+ hostIds.set(f, tag); cache[tag] = Object.freeze(f); return f;
66
+ }
67
+ function standIn(id, isArr) {
68
+ if (byId[id]) return byId[id];
69
+ var proto = isArr ? Array.prototype : Object.prototype;
70
+ var p = new Proxy(isArr ? [] : {}, {
71
+ get: function (t, k) { if (typeof k === 'symbol') return proto[k]; var v = hostGet(id, k); return v === M + 'a' ? proto[k] : dec(v); },
72
+ set: function (t, k, v) {
73
+ if (typeof k === 'symbol') return false;
74
+ var j = JSON.stringify(enc(v));
75
+ if (!hostSet(id, k, j)) return false;
76
+ if (v && typeof v === 'object' && !ids.has(v) && !(v instanceof Date)) assigned.push([id, k, v, j]);
77
+ return true;
78
+ },
79
+ has: function (t, k) { return typeof k !== 'symbol' && hostHas(id, k); },
80
+ deleteProperty: function (t, k) { return typeof k !== 'symbol' && hostDel(id, k); },
81
+ ownKeys: function () { var ks = JSON.parse(hostKeys(id)); if (isArr && ks.indexOf('length') < 0) ks.push('length'); return ks; },
82
+ getOwnPropertyDescriptor: function (t, k) {
83
+ if (isArr && k === 'length') return {value: dec(hostGet(id, 'length')), writable: true, enumerable: false, configurable: false};
84
+ if (typeof k === 'symbol' || !hostHas(id, k)) return undefined;
85
+ return {value: dec(hostGet(id, k)), writable: true, enumerable: true, configurable: true};
86
+ },
87
+ defineProperty: function (t, k, d) { if (typeof k === 'symbol' || !('value' in d)) return false; return hostSet(id, k, JSON.stringify(enc(d.value))); },
88
+ getPrototypeOf: function () { return proto; },
89
+ setPrototypeOf: function () { return false; },
90
+ preventExtensions: function () { return false; }
91
+ });
92
+ ids.set(p, id); byId[id] = p; return p;
93
+ }
94
+ // A plain object stored into a host object is re-sent before any host call and at the end, only if it changed since.
95
+ function resync() {
96
+ for (var i = 0; i < assigned.length; i++) {
97
+ var a = assigned[i], j = JSON.stringify(enc(a[2]));
98
+ if (j !== a[3]) { hostSet(a[0], a[1], j); a[3] = j; }
99
+ }
100
+ }
101
+ // QuickJS has no Intl: locale formatting (and the zone name in Date#toString) is the host's; only primitives cross.
102
+ function fmt(kind) { return function (locales, options) { return hostFormat(kind, kind === 'number' ? Number(this) : this.getTime(), JSON.stringify(locales === undefined ? null : locales), JSON.stringify(options === undefined ? null : options)); }; }
103
+ ['toLocaleDateString', 'toLocaleString', 'toLocaleTimeString', 'toString', 'toTimeString'].forEach(function (m) { Date.prototype[m] = fmt('date:' + m); });
104
+ Number.prototype.toLocaleString = fmt('number');
105
+ // Intl.DateTimeFormat and Intl.NumberFormat, formatted by the host: the formatter keeps its locales and options, and
106
+ // each call sends them with the value.
107
+ function formatter(kind, valueOf) {
108
+ function F(locales, options) {
109
+ if (!(this instanceof F)) return new F(locales, options);
110
+ this.l = JSON.stringify(locales === undefined ? null : locales);
111
+ this.o = JSON.stringify(options === undefined ? null : options);
112
+ }
113
+ function call(op, self, v) { return hostFormat(kind + ':' + op, valueOf(v), self.l, self.o); }
114
+ F.prototype.format = function (v) { return call('format', this, v); };
115
+ F.prototype.formatToParts = function (v) { return JSON.parse(call('formatToParts', this, v)); };
116
+ F.prototype.resolvedOptions = function () { return JSON.parse(call('resolvedOptions', this, 0)); };
117
+ return F;
118
+ }
119
+ G.Intl = {
120
+ DateTimeFormat: formatter('dtf', function (v) { return v === undefined ? Date.now() : (v instanceof Date ? v.getTime() : Number(v)); }),
121
+ NumberFormat: formatter('nf', function (v) { return Number(v); })
122
+ };
123
+ // structuredClone for data (QuickJS has none): plain objects, arrays, Date, Map, Set and RegExp, cycles kept; a
124
+ // function cannot be cloned, as in the platform's own.
125
+ G.structuredClone = function structuredClone(value) {
126
+ var seen = new Map();
127
+ function clone(v) {
128
+ if (v === null || typeof v !== 'object') {
129
+ if (typeof v === 'function' || typeof v === 'symbol') throw new TypeError('structuredClone: a ' + typeof v + ' could not be cloned');
130
+ return v;
131
+ }
132
+ if (seen.has(v)) return seen.get(v);
133
+ var c;
134
+ if (v instanceof Date) { c = new Date(v.getTime()); seen.set(v, c); return c; }
135
+ if (v instanceof RegExp) { c = new RegExp(v.source, v.flags); seen.set(v, c); return c; }
136
+ if (v instanceof Map) { c = new Map(); seen.set(v, c); v.forEach(function (x, k) { c.set(clone(k), clone(x)); }); return c; }
137
+ if (v instanceof Set) { c = new Set(); seen.set(v, c); v.forEach(function (x) { c.add(clone(x)); }); return c; }
138
+ c = Array.isArray(v) ? [] : {}; seen.set(v, c);
139
+ Object.keys(v).forEach(function (k) { Object.defineProperty(c, k, {value: clone(v[k]), enumerable: true, writable: true, configurable: true}); });
140
+ if (Array.isArray(v)) c.length = v.length;
141
+ return c;
142
+ }
143
+ return clone(value);
144
+ };
145
+ function harden(root) {
146
+ var seen = new WeakSet(), stack = [root];
147
+ while (stack.length) {
148
+ var o = stack.pop();
149
+ if (o === null || (typeof o !== 'object' && typeof o !== 'function') || seen.has(o)) continue;
150
+ seen.add(o); Object.freeze(o); stack.push(Object.getPrototypeOf(o));
151
+ Reflect.ownKeys(o).forEach(function (k) {
152
+ var d = Reflect.getOwnPropertyDescriptor(o, k);
153
+ if (!d) return;
154
+ if ('value' in d) stack.push(d.value); else { stack.push(d.get); stack.push(d.set); }
155
+ });
156
+ }
157
+ }
158
+ return Object.freeze({
159
+ dec: dec, enc: function (v) { return JSON.stringify(enc(v)); }, gfun: function (i) { return gfuns[i]; }, resync: resync,
160
+ reset: reset, harden: function () { harden(G); }, namespace: function () { return Object.create(null); },
161
+ freeze: function (o) { Object.freeze(o); return o; },
162
+ // A host error as a sandbox error. Built by the constructor (and defineProperty), never by assignment: an inherited
163
+ // frozen property cannot be assigned, so the library's own copy would lose the message.
164
+ error: function (name, message) {
165
+ var C = {TypeError: TypeError, RangeError: RangeError, SyntaxError: SyntaxError, ReferenceError: ReferenceError}[name] || Error;
166
+ var e = new C(message);
167
+ if (e.name !== name) Object.defineProperty(e, 'name', {value: name, writable: true, configurable: true});
168
+ return e;
169
+ },
170
+ fill: function (ns, names, values) { for (var i = 0; i < names.length; i++) ns[names[i]] = Object.freeze(values[i]); return Object.freeze(ns); }
171
+ });
172
+ })()`;
173
+ // Releases a sandbox's QuickJS resources once its engine is unreachable. The held value never references the sandbox
174
+ // (the host functions reach it through a WeakRef), so the engine can be collected.
175
+ const registry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(release) : null;
176
+ function release(res) {
177
+ if (res.released)
178
+ return;
179
+ res.released = true;
180
+ for (const h of res.handles)
181
+ if (h.alive)
182
+ h.dispose();
183
+ for (const h of res.compiled.values())
184
+ if (h.alive)
185
+ h.dispose();
186
+ res.compiled.clear();
187
+ res.ctx.dispose();
188
+ res.rt.dispose();
189
+ }
190
+ const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
191
+ const guestError = (ctx, handle) => {
192
+ const e = ctx.dump(handle);
193
+ handle.dispose();
194
+ const message = e && typeof e === 'object' ? (e.message || e.name || JSON.stringify(e)) : String(e);
195
+ return new Error(message);
196
+ };
197
+ export class ExpressionSandbox {
198
+ constructor(limits = {}) {
199
+ const { memoryBytes, stackBytes, timeoutMs } = { ...EXPRESSION_LIMITS, ...limits };
200
+ const rt = QuickJS.newRuntime();
201
+ rt.setMemoryLimit(memoryBytes);
202
+ rt.setMaxStackSize(stackBytes);
203
+ const res = { rt, ctx: null, handles: [], compiled: new Map(), released: false };
204
+ this.res = res;
205
+ this.timeoutMs = timeoutMs;
206
+ this.deadline = 0;
207
+ this.depth = 0;
208
+ this.generation = 0;
209
+ this.owned = [];
210
+ this.approved = null; // the evaluating engine's approved functions (named functions call by name)
211
+ this.evalFuns = [];
212
+ this.evalFunId = new Map(); // any other host function: per evaluation
213
+ this.objs = [];
214
+ this.objId = new Map(); // host objects: per evaluation
215
+ this.namespaces = new WeakMap(); // a named-function namespace -> its guest object
216
+ this.namespaceCache = new Map(); // compiled once per source (see defineNamespace)
217
+ const self = new WeakRef(this);
218
+ rt.setInterruptHandler(() => { const s = self.deref(); return !s || (s.deadline !== 0 && Date.now() > s.deadline); });
219
+ const ctx = rt.newContext();
220
+ res.ctx = ctx;
221
+ this.ctx = ctx;
222
+ const install = (name, method) => {
223
+ const h = ctx.newFunction(name, (...args) => {
224
+ const s = self.deref();
225
+ if (!s)
226
+ throw new Error('expression sandbox released');
227
+ try {
228
+ return s[method](...args);
229
+ }
230
+ catch (error) {
231
+ throw s.errorHandle(error);
232
+ }
233
+ });
234
+ ctx.setProp(ctx.global, name, h);
235
+ h.dispose();
236
+ };
237
+ install('__get', 'hostGet');
238
+ install('__set', 'hostSet');
239
+ install('__has', 'hostHas');
240
+ install('__del', 'hostDel');
241
+ install('__keys', 'hostKeys');
242
+ install('__call', 'hostCall');
243
+ install('__format', 'hostFormat');
244
+ const api = ctx.evalCode(GUEST);
245
+ if (api.error)
246
+ throw guestError(ctx, api.error);
247
+ this.api = api.value;
248
+ res.handles.push(api.value);
249
+ this.guest('harden').dispose();
250
+ registry?.register(this, res);
251
+ }
252
+ /** Releases the QuickJS runtime now (otherwise when the sandbox is collected). */
253
+ dispose() { registry?.unregister(this); release(this.res); }
254
+ guest(name, ...args) {
255
+ const f = this.ctx.getProp(this.api, name);
256
+ try {
257
+ const r = this.ctx.callFunction(f, this.api, ...args);
258
+ if (r.error)
259
+ throw guestError(this.ctx, r.error);
260
+ return r.value;
261
+ }
262
+ finally {
263
+ f.dispose();
264
+ }
265
+ }
266
+ own(h) { this.owned.push(h); return h; }
267
+ /** A host error as a sandbox error handle (the library throws a handle as is). */
268
+ errorHandle(error) {
269
+ const name = this.ctx.newString(String(error?.name || 'Error')), message = this.ctx.newString(String(error?.message ?? error));
270
+ try {
271
+ return this.guest('error', name, message);
272
+ }
273
+ finally {
274
+ name.dispose();
275
+ message.dispose();
276
+ }
277
+ }
278
+ // ── what crosses into the sandbox ────────────────────────────────────────────────────────────────────────────────
279
+ out(v) {
280
+ const ctx = this.ctx;
281
+ if (v === undefined)
282
+ return ctx.undefined;
283
+ if (v === null)
284
+ return ctx.null;
285
+ if (typeof v === 'boolean')
286
+ return v ? ctx.true : ctx.false;
287
+ if (typeof v === 'number')
288
+ return ctx.newNumber(v);
289
+ if (typeof v === 'string')
290
+ return ctx.newString(v.charCodeAt(0) === 0xE000 ? STR + v : v);
291
+ if (typeof v === 'bigint')
292
+ return ctx.newNumber(Number(v));
293
+ if (typeof v === 'function') {
294
+ let id = this.evalFunId.get(v);
295
+ if (id === undefined) {
296
+ id = this.evalFuns.length;
297
+ this.evalFuns.push(v);
298
+ this.evalFunId.set(v, id);
299
+ }
300
+ return ctx.newString(EFUN + id);
301
+ }
302
+ if (typeof v === 'object') {
303
+ const ns = this.namespaces.get(v);
304
+ if (ns)
305
+ return ns.dup();
306
+ if (v instanceof Date)
307
+ return ctx.newString(DATE + v.getTime());
308
+ let id = this.objId.get(v);
309
+ if (id === undefined) {
310
+ id = this.objs.length;
311
+ this.objs.push(v);
312
+ this.objId.set(v, id);
313
+ }
314
+ return ctx.newString(OBJ + id + (Array.isArray(v) ? ':a' : ''));
315
+ }
316
+ return ctx.undefined;
317
+ }
318
+ /** A host value as a sandbox value (a stand-in for an object). */
319
+ toGuest(v) {
320
+ const h = this.own(this.out(v));
321
+ const tagged = (typeof v === 'object' && v !== null && !this.namespaces.has(v)) || typeof v === 'function' || (typeof v === 'string' && v.charCodeAt(0) === 0xE000);
322
+ return tagged ? this.own(this.guest('dec', h)) : h;
323
+ }
324
+ // ── what crosses back ────────────────────────────────────────────────────────────────────────────────────────────
325
+ inn(v) {
326
+ if (v === UNDEF)
327
+ return undefined;
328
+ if (typeof v === 'string') {
329
+ if (v.charCodeAt(0) !== 0xE000)
330
+ return v;
331
+ if (v.startsWith(OBJ))
332
+ return this.object(+v.slice(3).split(':')[0]);
333
+ if (v.startsWith(FUN) || v.startsWith(EFUN))
334
+ return this.hostFunctionOf(v);
335
+ if (v.startsWith(GFUN))
336
+ return this.callback(+v.slice(3));
337
+ if (v.startsWith(STR))
338
+ return v.slice(3);
339
+ if (v.startsWith(NUM))
340
+ return Number(v.slice(3));
341
+ if (v.startsWith(DATE))
342
+ return new Date(Number(v.slice(3)));
343
+ return v;
344
+ }
345
+ if (Array.isArray(v))
346
+ return v.map((x) => this.inn(x));
347
+ if (v && typeof v === 'object') {
348
+ const o = {};
349
+ for (const k of Object.keys(v))
350
+ Object.defineProperty(o, k, { value: this.inn(v[k]), enumerable: true, writable: true, configurable: true });
351
+ return o;
352
+ }
353
+ return v;
354
+ }
355
+ hostFunctionOf(tag) {
356
+ if (tag.startsWith(FUN)) {
357
+ const name = tag.slice(3), f = this.approved && hasOwn(this.approved, name) ? this.approved[name] : undefined;
358
+ if (typeof f !== 'function')
359
+ throw new TypeError(`${name} is not a function`);
360
+ return f;
361
+ }
362
+ const f = this.evalFuns[+tag.slice(3)];
363
+ if (typeof f !== 'function')
364
+ throw new Error('stale function reference');
365
+ return f;
366
+ }
367
+ object(id) {
368
+ if (id >= this.objs.length)
369
+ throw new Error('stale object reference');
370
+ return this.objs[id];
371
+ }
372
+ /** A sandbox function handed to the host: callable while its evaluation runs. */
373
+ callback(index) {
374
+ const generation = this.generation;
375
+ return (...args) => {
376
+ if (this.depth === 0 || generation !== this.generation)
377
+ throw new Error('a function created by an expression cannot be called after the expression ends');
378
+ const f = this.own(this.guest('gfun', this.own(this.ctx.newNumber(index))));
379
+ return this.call(f, args);
380
+ };
381
+ }
382
+ /** Calls a sandbox function with host arguments, inside the current evaluation. */
383
+ call(f, args) {
384
+ const handles = args.map((a) => this.toGuest(a));
385
+ const r = this.ctx.callFunction(f, this.ctx.undefined, ...handles);
386
+ if (r.error)
387
+ throw guestError(this.ctx, r.error);
388
+ this.own(r.value);
389
+ this.guest('resync').dispose();
390
+ const encoded = this.own(this.guest('enc', r.value));
391
+ return this.inn(JSON.parse(this.ctx.getString(encoded)));
392
+ }
393
+ /** One evaluation: a deadline, a fresh object table, every handle released at the end. */
394
+ scope(run, approved) {
395
+ const outer = this.depth === 0;
396
+ const previousApproved = this.approved;
397
+ if (approved)
398
+ this.approved = approved;
399
+ if (outer) {
400
+ if (this.res.released)
401
+ throw new Error('expression sandbox released');
402
+ this.generation++;
403
+ this.deadline = Date.now() + this.timeoutMs;
404
+ }
405
+ this.depth++;
406
+ try {
407
+ return run();
408
+ }
409
+ finally {
410
+ this.depth--;
411
+ this.approved = previousApproved;
412
+ if (outer) {
413
+ this.deadline = 0;
414
+ for (const h of this.owned)
415
+ if (h.alive)
416
+ h.dispose();
417
+ this.owned = [];
418
+ this.objs = [];
419
+ this.objId.clear();
420
+ this.evalFuns = [];
421
+ this.evalFunId.clear();
422
+ this.guest('reset').dispose();
423
+ }
424
+ }
425
+ }
426
+ compile(source) {
427
+ const cached = this.res.compiled.get(source);
428
+ if (cached) {
429
+ this.res.compiled.delete(source);
430
+ this.res.compiled.set(source, cached);
431
+ return cached;
432
+ }
433
+ const r = this.ctx.evalCode(source);
434
+ if (r.error)
435
+ throw guestError(this.ctx, r.error);
436
+ this.res.compiled.set(source, r.value);
437
+ if (this.res.compiled.size > COMPILED_CACHE) {
438
+ const [oldest, h] = this.res.compiled.entries().next().value;
439
+ this.res.compiled.delete(oldest);
440
+ h.dispose();
441
+ }
442
+ return r.value;
443
+ }
444
+ // ── host functions the guest runtime calls ───────────────────────────────────────────────────────────────────────
445
+ hostGet(idH, kH) {
446
+ const o = this.object(this.ctx.getNumber(idH)), k = this.ctx.getString(kH);
447
+ return hasOwn(o, k) ? this.out(o[k]) : this.ctx.newString(ABSENT);
448
+ }
449
+ hostSet(idH, kH, vH) {
450
+ const k = this.ctx.getString(kH);
451
+ if (k === '__proto__')
452
+ return this.ctx.false;
453
+ this.object(this.ctx.getNumber(idH))[k] = this.inn(JSON.parse(this.ctx.getString(vH)));
454
+ return this.ctx.true;
455
+ }
456
+ hostHas(idH, kH) { return hasOwn(this.object(this.ctx.getNumber(idH)), this.ctx.getString(kH)) ? this.ctx.true : this.ctx.false; }
457
+ hostDel(idH, kH) { return delete this.object(this.ctx.getNumber(idH))[this.ctx.getString(kH)] ? this.ctx.true : this.ctx.false; }
458
+ hostKeys(idH) { return this.ctx.newString(JSON.stringify(Object.keys(this.object(this.ctx.getNumber(idH))))); }
459
+ hostCall(fH, aH) {
460
+ const f = this.hostFunctionOf(this.ctx.getString(fH));
461
+ const result = f(...this.inn(JSON.parse(this.ctx.getString(aH))));
462
+ if (result && typeof result.then === 'function')
463
+ throw new Error('an approved function returned a Promise; expressions are synchronous');
464
+ return this.out(result);
465
+ }
466
+ hostFormat(kH, vH, lH, oH) {
467
+ const kind = this.ctx.getString(kH), v = this.ctx.getNumber(vH);
468
+ const locales = JSON.parse(this.ctx.getString(lH)) ?? undefined, options = JSON.parse(this.ctx.getString(oH)) ?? undefined;
469
+ const [family, op] = kind.split(':');
470
+ let s;
471
+ if (family === 'number')
472
+ s = v.toLocaleString(locales, options);
473
+ else if (family === 'date')
474
+ s = new Date(v)[op](locales, options);
475
+ else {
476
+ const f = family === 'dtf' ? new Intl.DateTimeFormat(locales, options) : new Intl.NumberFormat(locales, options);
477
+ s = op === 'format' ? f.format(v) : JSON.stringify(op === 'formatToParts' ? f.formatToParts(v) : f.resolvedOptions());
478
+ }
479
+ return this.ctx.newString(String(s));
480
+ }
481
+ // ── the engine's entry points ────────────────────────────────────────────────────────────────────────────────────
482
+ /** Evaluates one expression. Only the names it mentions are passed in; the standard built-ins are the sandbox's own. */
483
+ evaluate(expression, names, values, approvedFunctions) {
484
+ const keep = [], keepValues = [];
485
+ for (let i = 0; i < names.length; i++) {
486
+ const n = names[i];
487
+ if (BUILTINS.has(n) || !identifier.test(n))
488
+ continue;
489
+ if (!new RegExp(`(^|[^\\w$])${n.replace(/\$/g, '\\$')}([^\\w$]|$)`).test(expression))
490
+ continue;
491
+ keep.push(n);
492
+ keepValues.push(values[i]);
493
+ }
494
+ return this.scope(() => {
495
+ const f = this.compile(`(function(${keep.join(',')}){"use strict"; return (${expression});})`);
496
+ return this.call(f, keepValues);
497
+ }, approvedFunctions || {});
498
+ }
499
+ /** Compiles named functions once per source; returns a namespace bound to `approvedFunctions` (callable from the
500
+ * host; an expression's `fn`). Approved functions are called by name, so one compiled copy serves every engine. */
501
+ defineNamespace({ names, source, approvedFunctions, label }) {
502
+ const approvedNames = Object.keys(approvedFunctions);
503
+ const key = approvedNames.join(',') + '\n' + names.join(',') + '\n' + source;
504
+ let entry = this.namespaceCache.get(key);
505
+ if (!entry) {
506
+ const factorySource = `(function(fn${approvedNames.map((n) => ',' + n).join('')}){"use strict";\n${source}\nreturn [${names.join(',')}];})`;
507
+ const factory = this.ctx.evalCode(factorySource);
508
+ if (factory.error)
509
+ throw new Error(`Named functions ${label}: invalid JavaScript: ${guestError(this.ctx, factory.error).message}`);
510
+ this.res.handles.push(factory.value);
511
+ const ns = this.guest('namespace');
512
+ this.res.handles.push(ns);
513
+ const members = [];
514
+ this.scope(() => {
515
+ const args = [ns, ...approvedNames.map((n) => this.own(this.guest('dec', this.own(this.ctx.newString(FUN + n)))))];
516
+ const r = this.ctx.callFunction(factory.value, this.ctx.undefined, ...args);
517
+ if (r.error)
518
+ throw new Error(`Named functions ${label}: ${guestError(this.ctx, r.error).message}`);
519
+ this.own(r.value);
520
+ for (let i = 0; i < names.length; i++) {
521
+ const m = this.ctx.getProp(r.value, i);
522
+ this.res.handles.push(m);
523
+ members.push(m);
524
+ }
525
+ const namesH = this.own(this.ctx.newArray());
526
+ const valuesH = this.own(this.ctx.newArray());
527
+ names.forEach((n, i) => { this.ctx.setProp(namesH, i, this.own(this.ctx.newString(n))); this.ctx.setProp(valuesH, i, members[i]); });
528
+ this.guest('fill', ns, namesH, valuesH).dispose();
529
+ }, approvedFunctions);
530
+ entry = { ns, members };
531
+ this.namespaceCache.set(key, entry);
532
+ }
533
+ const namespace = Object.create(null);
534
+ names.forEach((n, i) => { namespace[n] = (...args) => this.scope(() => this.call(entry.members[i], args), approvedFunctions); });
535
+ Object.freeze(namespace);
536
+ this.namespaces.set(namespace, entry.ns);
537
+ return namespace;
538
+ }
539
+ }
540
+ let shared;
541
+ /** The process's sandbox, shared by every engine (created on first use, never released). */
542
+ export function sharedSandbox() { return shared ??= new ExpressionSandbox(); }
@@ -1,5 +1,8 @@
1
- export function compileNamedFunctions(definitions: any, { approvedFunctions, label }?: {
2
- approvedFunctions?: {} | undefined;
3
- label?: string | undefined;
4
- }): any;
1
+ /** @param {any} definitions @param {{approvedFunctions?: Record<string, any>, label?: string, sandbox?: ExpressionSandbox}} [options] @returns {Record<string, (...args: any[]) => any> | undefined} */
2
+ export function compileNamedFunctions(definitions: any, { approvedFunctions, label, sandbox }?: {
3
+ approvedFunctions?: Record<string, any>;
4
+ label?: string;
5
+ sandbox?: ExpressionSandbox;
6
+ }): Record<string, (...args: any[]) => any> | undefined;
7
+ export type ExpressionSandbox = import("./expression-sandbox.js").ExpressionSandbox;
5
8
  //# sourceMappingURL=named-functions.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"named-functions.d.ts","sourceRoot":"","sources":["../../src/helpers/named-functions.js"],"names":[],"mappings":"AAOA;;;QAkCC"}
1
+ {"version":3,"file":"named-functions.d.ts","sourceRoot":"","sources":["../../src/helpers/named-functions.js"],"names":[],"mappings":"AASA,wMAAwM;AACxM,mDADY,GAAG,0CAAsB;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,iBAAiB,CAAA;CAAC,GAAsB,MAAM,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,CAAC,GAAG,SAAS,CA8BnM;gCAlCa,OAAO,yBAAyB,EAAE,iBAAiB"}
@@ -1,11 +1,14 @@
1
- /** Compile trusted, JSON-saved JavaScript helpers once for a loaded flow definition.
2
- * Only explicit arguments and approved platform helpers enter their lexical scope.
3
- * Runtime/session values are passed by callers; a registry never captures a session.
1
+ /** Compile JSON-saved JavaScript helpers once for a loaded flow definition, in the expression sandbox (flow text is
2
+ * untrusted: it never runs in the host's realm). Only explicit arguments and approved platform helpers enter their
3
+ * lexical scope. Runtime/session values are passed by callers; a registry never captures a session.
4
4
  */
5
+ import { sharedSandbox } from './expression-sandbox.js';
6
+ /** @typedef {import('./expression-sandbox.js').ExpressionSandbox} ExpressionSandbox */
5
7
  const identifier = /^[A-Za-z_$][\w$]*$/;
6
8
  const forbidden = new Set(['fn', '__proto__', 'prototype', 'constructor']);
7
9
  const own = (value, key) => Object.prototype.hasOwnProperty.call(value, key);
8
- export function compileNamedFunctions(definitions, { approvedFunctions = {}, label = 'flow' } = {}) {
10
+ /** @param {any} definitions @param {{approvedFunctions?: Record<string, any>, label?: string, sandbox?: ExpressionSandbox}} [options] @returns {Record<string, (...args: any[]) => any> | undefined} */
11
+ export function compileNamedFunctions(definitions, { approvedFunctions = {}, label = 'flow', sandbox } = {}) {
9
12
  if (definitions === undefined)
10
13
  return undefined;
11
14
  if (!definitions || typeof definitions !== 'object' || Array.isArray(definitions))
@@ -40,15 +43,8 @@ export function compileNamedFunctions(definitions, { approvedFunctions = {}, lab
40
43
  });
41
44
  // Local declaration names shadow same-named approved helpers exactly as ordinary JS lexical bindings do.
42
45
  const approvedNames = Object.keys(approvedFunctions).filter(name => identifier.test(name) && name !== 'fn' && !own(definitions, name));
43
- let factory;
44
- try {
45
- factory = new Function('fn', ...approvedNames, `"use strict";\n${statements.join('\n')}\nreturn [${names.join(',')}];`);
46
- }
47
- catch (error) {
48
- fail(`invalid JavaScript: ${error.message}`);
49
- }
50
- const namespace = Object.create(null);
51
- const functions = factory(namespace, ...approvedNames.map(name => approvedFunctions[name]));
52
- names.forEach((name, index) => { namespace[name] = functions[index]; });
53
- return Object.freeze(namespace);
46
+ const approved = {};
47
+ for (const name of approvedNames)
48
+ approved[name] = approvedFunctions[name];
49
+ return (sandbox || sharedSandbox()).defineNamespace({ names, source: statements.join('\n'), approvedFunctions: approved, label });
54
50
  }
@@ -87,7 +87,7 @@ export interface ReplyRankRequest {
87
87
  };
88
88
  }
89
89
  /**
90
- * The reply ranker's instructions for both executors. `reasonFor` (what the caller does not want, e.g. "your Curacao
90
+ * The reply ranker's instructions for both executors. `reasonFor` (what the caller does not want, e.g. "your Acme
91
91
  * Club membership") ranks the reply as an answer to "why don't you want it?": only `answers` or `new_request`, no
92
92
  * choices.
93
93
  */
@@ -79,7 +79,7 @@ const TASK = 'A workflow asked the caller a question. Decide what the caller\'s
79
79
  const reasonTask = (x) => `A workflow is filing the caller's request about something the caller does not want (${x}), and asked for the reason. Decide what the caller's latest message does with that question.`;
80
80
  // A reason question offers no `abort` (owner 2026-10-31): a reason is never a withdrawal, so the ranker never has to tell
81
81
  // "I don't need it" from "I'll keep it". A caller who changes their mind declines the request's confirmation, which the
82
- // flow asking for the reason must have (the Curacao cancellation reads the request back before filing it).
82
+ // flow asking for the reason must have (a tenant's cancellation flow reads the request back before filing it).
83
83
  const REASON_OPTIONS = ['answers', 'new_request'];
84
84
  const reasonCriteria = (x) => ({
85
85
  answers: {
@@ -125,7 +125,7 @@ const criteriaOf = (option, choices, reasonFor = '', concern = '') => {
125
125
  };
126
126
  const conversationText = (conversation, input) => `${conversation.length ? `<conversation>\n${conversation.map(t => `${t.role}: ${t.content}`).join('\n')}\n</conversation>\n` : ''}<latest-message>\n${input}\n</latest-message>`;
127
127
  /**
128
- * The reply ranker's instructions for both executors. `reasonFor` (what the caller does not want, e.g. "your Curacao
128
+ * The reply ranker's instructions for both executors. `reasonFor` (what the caller does not want, e.g. "your Acme
129
129
  * Club membership") ranks the reply as an answer to "why don't you want it?": only `answers` or `new_request`, no
130
130
  * choices.
131
131
  */
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ExpressionSandbox } from './helpers/expression-sandbox.js';
1
2
  import type { FlowRecovery } from './host/flow-recovery.js';
2
3
  export type { FlowRecovery } from './host/flow-recovery.js';
3
4
  import type { IntentStageRequest } from './host/intent-stages.js';
@@ -708,6 +709,7 @@ export declare class WorkflowEngine implements Engine {
708
709
  flowsMenu: FlowDefinition[];
709
710
  private readonly sourceFlowDeclarations;
710
711
  private readonly namedFunctionNamespaces;
712
+ readonly expressionSandbox: ExpressionSandbox;
711
713
  /** The flow set's shared data, read in expressions as $data.<name>: deep-frozen, never persisted in session variables. */
712
714
  sharedData?: Record<string, unknown>;
713
715
  primaryCallers?: Record<string, {