From 07c29cc736bc0c354aa1e25d74dbc36b444ae3a6 Mon Sep 17 00:00:00 2001 From: x_ror <16686943+x-ror@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:29:41 +0200 Subject: [PATCH] feat(runtime): add a Web global surface that hides the Node names eval takes a trailing `surface: Global_Surface = .Node`. `.Node` is what every context got before and stays the default; `run_file` and the CLI never select anything else. `.Web` exposes the web-platform subset only: no `process`, `require`, `module`, `exports`, `__filename`, `__dirname`, `Buffer`, `global`, `setImmediate`/`clearImmediate`, and no `__lava*` hook. How `.Web` gets there: - the CommonJS entry bindings are never injected; - install_stdio does not run, so internal/stdio and the node-streams stack are never compiled (console writes through its own native writer); - `process`, `Buffer`, `setImmediate`, `clearImmediate` and `global` are installed for the bootstrap and removed as the last step before user code; - an `.mjs` source name is Invalid_Input, and no top-level nextTick drain is appended. The one change on the default path: `__lavaDrainNextTicks` and `__lava_tl_drain` are now defined from install_microtasks instead of microtasks.js, with the same attributes. They are non-configurable, so a `.Web` context could not have deleted them. `.Web` promises that the names are gone, nothing more: web APIs still hand out Buffer-backed bytes and `ERR_*` codes (x-ror/larva#5). Pinned by cmd/lava/global_surface_test.odin; seven mutations recorded in tests/mutation-manifest.json. Co-Authored-By: Claude Fable 5.2 --- cmd/lava/global_surface_test.odin | 350 +++++++++++++++++++++++++ docs/ARCHITECTURE.md | 30 +++ pkg/runtime/environment.odin | 61 ++++- pkg/runtime/globals.odin | 39 ++- pkg/runtime/js/bootstrap/microtasks.js | 30 +-- pkg/runtime/runtime.odin | 94 ++++++- tests/mutation-manifest.json | 63 +++++ 7 files changed, 621 insertions(+), 46 deletions(-) create mode 100644 cmd/lava/global_surface_test.odin diff --git a/cmd/lava/global_surface_test.odin b/cmd/lava/global_surface_test.odin new file mode 100644 index 00000000..2cad5a5c --- /dev/null +++ b/cmd/lava/global_surface_test.odin @@ -0,0 +1,350 @@ +#+build linux, darwin +package main + +import "core:strings" +import "core:testing" +import jsc "lava:pkg/jsc" +import lava "lava:pkg/runtime" +import eventloop "lava:pkg/runtime/eventloop" + +// Pins Global_Surface (runtime.odin), a Lava-only seam with no node counterpart: +// node has one global surface, so nothing here is oracle-able and it lives in an +// Odin test. `.Node` is the default and must stay byte-identical to the pre-seam +// runtime; `.Web` must make every Node-only NAME unreachable from the script while +// the web-platform APIs it keeps still WORK, not merely exist — an API that throws +// because an internal module read a removed global live would pass a `typeof` +// check and fail here. +// +// Every check is recorded and compared at the end rather than thrown at first +// failure, so a mutation's red output names the check it broke (the manifest's +// expect_detail matches on that name). The sync table throws from the top level +// (Execution_Error, message carries the names); the async table throws from a +// timer (an uncaught async exception: exit code 1, the names on stderr). A +// watchdog timer that only a completed async table clears keeps a chain that never +// settles from passing silently. +GLOBAL_SURFACE_WEB_SCRIPT :: ` +const results = []; +function record(name, fn) { + let out; + try { + out = String(fn()); + } catch (e) { + out = 'THREW:' + e.name + ':' + e.message; + } + results[results.length] = name + '=' + out; +} +function compare(table, got, want) { + const bad = []; + for (let i = 0; i < want.length || i < got.length; i++) { + if (got[i] !== want[i]) bad[bad.length] = 'want ' + want[i] + ' got ' + got[i]; + } + if (bad.length !== 0) throw new Error(table + ': ' + bad.join('; ')); +} + +// The names, by typeof — 'in globalThis' would also pass for a name that is +// reachable through a scope binding rather than a global property. +record('process', function () { return typeof process; }); +record('require', function () { return typeof require; }); +record('module', function () { return typeof module; }); +record('exports', function () { return typeof exports; }); +record('__filename', function () { return typeof __filename; }); +record('__dirname', function () { return typeof __dirname; }); +record('Buffer', function () { return typeof Buffer; }); +record('global', function () { return typeof global; }); +record('setImmediate', function () { return typeof setImmediate; }); +record('clearImmediate', function () { return typeof clearImmediate; }); +record('__lava_precache', function () { return typeof __lava_precache; }); +record('__lavaDrainNextTicks', function () { return typeof __lavaDrainNextTicks; }); +record('__lava_tl_drain', function () { return typeof __lava_tl_drain; }); +// Catches a __lava* hook this list does not name yet. Taken again from the async +// table, next to 'tl-drain-after': a statement appended to the entry (the top-level +// drain's 'var __lava_tl_drain = …') has only RUN once the body has finished, and +// JSC keeps that program-level var out of getOwnPropertyNames — the census misses +// it, while typeof and 'in' see it. +function lavaOwn() { + const names = Object.getOwnPropertyNames(globalThis); + const hits = []; + for (let i = 0; i < names.length; i++) if (names[i].slice(0, 6) === '__lava') hits[hits.length] = names[i]; + return hits.length === 0 ? 'none' : hits.join(','); +} +record('lava-own', lavaOwn); +// A fresh function body resolves free names against the global object only. +record('fn-process', function () { return new Function('return typeof process')(); }); + +// The kept APIs, exercised. +record('url', function () { + const u = new URL('https://a.example/p?x=1&y=2'); + u.searchParams.append('z', '3'); + return u.href + '|' + u.searchParams.get('y'); +}); +record('text', function () { + const s = 'héllo € 😀'; + const bytes = new TextEncoder().encode(s); + return bytes.length + ':' + (new TextDecoder().decode(bytes) === s); +}); +record('clone', function () { + const inner = { v: 1 }; + const src = { a: { b: [1, 2] }, m: new Map([['k', inner]]) }; + const c = structuredClone(src); + return [c !== src, c.a !== src.a, c.a.b.join('-'), c.m instanceof Map, c.m.get('k').v, c.m.get('k') !== inner].join(','); +}); +record('headers', function () { + const h = new Headers({ 'Content-Type': 'text/plain' }); + h.append('X-A', '1'); + h.append('x-a', '2'); + return h.get('content-type') + '|' + h.get('x-a'); +}); +record('base64', function () { return btoa('hi?') + '|' + atob('aGk/'); }); +record('crypto', function () { + const a = new Uint8Array(16); + const r = crypto.getRandomValues(a); + const id = crypto.randomUUID(); + return [/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(id), r === a, a.length].join(','); +}); +record('abort', function () { + const ac = new AbortController(); + let fired = 0; + ac.signal.addEventListener('abort', function () { fired++; }); + ac.abort(); + return [fired, ac.signal.aborted, ac.signal.reason.name].join(','); +}); +record('performance', function () { + const a = performance.now(); + return typeof a === 'number' && a >= 0 && performance.now() >= a; +}); +record('stream-family', function () { + return [ReadableStream, WritableStream, TransformStream, ByteLengthQueuingStrategy, CountQueuingStrategy, + fetch, Request, Response, Blob, File].map(function (f) { return typeof f; }).join(','); +}); +record('console', function () { return console.log('global-surface web ok'); }); + +compare('sync', results, [ + 'process=undefined', 'require=undefined', 'module=undefined', 'exports=undefined', + '__filename=undefined', '__dirname=undefined', 'Buffer=undefined', 'global=undefined', + 'setImmediate=undefined', 'clearImmediate=undefined', '__lava_precache=undefined', + '__lavaDrainNextTicks=undefined', '__lava_tl_drain=undefined', 'lava-own=none', 'fn-process=undefined', + 'url=https://a.example/p?x=1&y=2&z=3|2', 'text=15:true', 'clone=true,true,1-2,true,1,true', + 'headers=text/plain|1, 2', 'base64=aGk/|hi?', 'crypto=true,true,16', 'abort=1,true,AbortError', + 'performance=true', + 'stream-family=function,function,function,function,function,function,function,function,function,function', + 'console=undefined', +]); + +// Async: registered in this order at the top level, so the microtask order is +// observable — queueMicrotask shares one FIFO with promise jobs. +const order = []; +queueMicrotask(function () { order[order.length] = 'qm'; }); +Promise.resolve().then(function () { order[order.length] = 'p'; }); + +const watchdog = setTimeout(function () { + throw new Error('async: never completed'); +}, 5000); +const cancelled = setTimeout(function () { + throw new Error('async: a cleared timeout fired'); +}, 1); +clearTimeout(cancelled); + +const asyncResults = []; +async function arecord(name, fn) { + let out; + try { + out = String(await fn()); + } catch (e) { + out = 'THREW:' + e.name + ':' + e.message; + } + asyncResults[asyncResults.length] = name + '=' + out; +} + +async function main() { + // main() runs synchronously up to its first await; yield a timer turn first so the + // top-level microtasks above have run when 'microtask-order' reads them. + await new Promise(function (resolve) { setTimeout(resolve, 0); }); + await arecord('microtask-order', function () { return order.join(','); }); + await arecord('lava-own-after', lavaOwn); + await arecord('tl-drain-after', function () { + return typeof __lava_tl_drain + ',' + ('__lava_tl_drain' in globalThis); + }); + await arecord('stream', async function () { + const rs = new ReadableStream({ + start(c) { c.enqueue('a'); c.enqueue('b'); c.close(); }, + }); + const reader = rs.getReader(); + let s = ''; + for (;;) { + const r = await reader.read(); + if (r.done) break; + s += r.value; + } + return s; + }); + await arecord('blob', function () { return new Blob(['x', 'y']).text(); }); + await arecord('response', function () { return new Response('x').text(); }); + await arecord('timeout', function () { + return new Promise(function (resolve) { setTimeout(resolve, 1, 'fired'); }); + }); + await arecord('interval', function () { + return new Promise(function (resolve) { + let n = 0; + const id = setInterval(function () { + n++; + if (n === 3) { + clearInterval(id); + // One more tick past the clear: a live interval would push n to 4. + setTimeout(function () { resolve(n); }, 5); + } + }, 1); + }); + }); +} +main().then(function () { + clearTimeout(watchdog); + setTimeout(function () { + compare('async', asyncResults, [ + 'microtask-order=qm,p', 'lava-own-after=none', + 'tl-drain-after=undefined,false', 'stream=ab', 'blob=xy', 'response=x', 'timeout=fired', 'interval=3', + ]); + }, 0); +}); +` + +@(test) +global_surface_web_hides_node_names :: proc(t: ^testing.T) { + loop := eventloop.init() + // eval consumes (destroys) the loop on every path; do not destroy it here. + result := lava.eval(GLOBAL_SURFACE_WEB_SCRIPT, "", &loop, false, surface = .Web) + defer lava.result_destroy(&result) + + testing.expectf( + t, + result.status == .Ok, + "eval did not complete cleanly: status=%v message=%q", + result.status, + result.message, + ) + // Non-zero means the async table threw from its timer (its names are on stderr) + // or the watchdog fired. + testing.expectf(t, result.exit_code == 0, "eval exit code=%d (want 0)", result.exit_code) +} + +// The ESM transform emits `require` and `__lava_precache`, which `.Web` never +// injects, so an `.mjs` source name is refused up front rather than failing inside +// the transformed body. The `.Node` control proves the refusal is the surface's. +@(test) +global_surface_web_rejects_mjs :: proc(t: ^testing.T) { + web := lava.eval("export const x = 1;\n", "entry.mjs", nil, surface = .Web) + defer lava.result_destroy(&web) + testing.expectf(t, web.status == .Invalid_Input, "web .mjs status=%v (want Invalid_Input)", web.status) + testing.expect_value(t, web.exit_code, 2) + testing.expectf(t, strings.contains(web.message, ".mjs"), "web .mjs message=%q", web.message) + + node := lava.eval("export const x = 1;\n", "entry.mjs", nil) + defer lava.result_destroy(&node) + testing.expectf(t, node.status == .Ok, "node .mjs status=%v message=%q", node.status, node.message) +} + +// What each surface's script asserts about the names. Thrown from the top level, so +// a miss lands in Result.message by name. +@(private = "file") +NODE_NAMES_PRESENT :: ` +const missing = ['process', 'require', 'module', 'exports', '__filename', '__dirname', 'Buffer', 'global', + 'setImmediate', 'clearImmediate', '__lava_precache', '__lavaDrainNextTicks'].filter(function (n) { + return new Function('return typeof ' + n)() === 'undefined'; +}); +if (missing.length !== 0) throw new Error('node surface missing: ' + missing.join(',')); +` + +@(private = "file") +NODE_NAMES_ABSENT :: ` +const present = ['process', 'require', 'module', 'exports', '__filename', '__dirname', 'Buffer', 'global', + 'setImmediate', 'clearImmediate', '__lava_precache', '__lavaDrainNextTicks', '__lava_tl_drain'].filter(function (n) { + return new Function('return typeof ' + n)() !== 'undefined'; +}); +if (present.length !== 0) throw new Error('web surface still has: ' + present.join(',')); +` + +// Node → Web → Node on one thread: nothing the first context set up (a cached host +// function, a thread-local) may carry the Node names into the Web one, and the Web +// one must not leave the next Node context short. The Node evals use the DEFAULT +// argument, which pins `.Node` as the default surface. +@(test) +global_surface_alternates_on_one_thread :: proc(t: ^testing.T) { + expect_ok :: proc(t: ^testing.T, what: string, result: lava.Result) { + testing.expectf( + t, + result.status == .Ok, + "%s: status=%v message=%q", + what, + result.status, + result.message, + ) + } + + first := lava.eval(NODE_NAMES_PRESENT, "", nil) + defer lava.result_destroy(&first) + expect_ok(t, "node before web", first) + + web := lava.eval(NODE_NAMES_ABSENT, "", nil, surface = .Web) + defer lava.result_destroy(&web) + expect_ok(t, "web after node", web) + + second := lava.eval(NODE_NAMES_PRESENT, "", nil) + defer lava.result_destroy(&second) + expect_ok(t, "node after web", second) +} + +// `.Web` never runs install_stdio, so internal/stdio and the node-streams stack it +// pulls in (node:stream, events, the internal/streams/* files) are never compiled. +// Observed through Runtime_State.builtin_compiles, the counter lazy_builtins_test.odin +// reads: after init, the first `events` resolve compiles it under `.Web` and finds it +// cached under `.Node`. `events` rather than `stream` because only stdio's stack pulls +// it in and its factory reads no removed global; node:stream's internals capture +// `process.nextTick` at module-eval, so instantiating it on `.Web` throws — which is +// fine, nothing there can require it. Built by hand rather than through lava.eval so +// the state outlives init and the counter can be read. +@(test) +global_surface_web_skips_stdio :: proc(t: ^testing.T) { + node_init, node_events := surface_events_compiles(t, .Node) + web_init, web_events := surface_events_compiles(t, .Web) + + testing.expectf(t, node_events == 0, "node: resolving events compiled %d factories (want 0: stdio loaded it)", node_events) + testing.expectf(t, web_events > 0, "web: resolving events compiled nothing — stdio was instantiated at init") + testing.expectf( + t, + web_init < node_init, + "web init compiled %d factories, node init %d — web must compile fewer", + web_init, + node_init, + ) +} + +// surface_events_compiles inits a context on `surface` and returns how many builtin +// factories init compiled, then how many one resolve of `events` compiled on top. +@(private = "file") +surface_events_compiles :: proc(t: ^testing.T, surface: lava.Global_Surface) -> (at_init: int, events: int) { + jsc.lava_jsc_init() + gclass := lava.make_global_class() + gctx := jsc.JSGlobalContextCreate(gclass) + testing.expect(t, gctx != nil, "could not create a JSC global context") + if gctx == nil { + jsc.JSClassRelease(gclass) + return + } + defer jsc.JSClassRelease(gclass) + defer jsc.JSGlobalContextRelease(gctx) + ctx := cast(jsc.JSContextRef)gctx + + state := lava.new_runtime_state(nil) + jsc.JSObjectSetPrivate(jsc.JSContextGetGlobalObject(ctx), cast(rawptr)state) + defer lava.destroy_runtime_state(ctx, state) + lava.capture_error_intrinsics(ctx, state) + jsc.prime_view_probe(ctx) + lava.setup_module_environment(ctx, "", nil, surface) + defer free_all(context.temp_allocator) + + at_init = state.builtin_compiles + spec := lava.js_string_value(ctx, "events") + exports := lava.require_builtin(ctx, spec) + testing.expectf(t, exports != nil, "%v: the builtin resolver did not answer 'events'", surface) + events = state.builtin_compiles - at_init + return +} diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 2c003eac..0330c6fb 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -292,6 +292,36 @@ native codec at every size. Removed rather than left as folklore steering review `index`, and `node_modules` walking. **`package.json` `"exports"` conditional resolution is not yet implemented** — a real gap for modern packages. +### 3.4.1 Global surfaces (`Global_Surface`, `runtime.odin`) + +`eval` takes a trailing `surface` (default `.Node`), threaded through +`setup_module_environment` into `install_globals`. `.Node` is everything `lava run` +exposes; `run_file` and the CLI never select anything else. `.Web` is for an embedder +that runs untrusted web-platform code: the context keeps fetch, URL, the Web Streams +family, TextEncoder/TextDecoder, Blob/File, AbortController, structuredClone, +atob/btoa, crypto, performance, console, queueMicrotask and the four timer functions, +while `process`, `require`, `module`, `exports`, `__filename`, `__dirname`, `Buffer`, +`global`, `setImmediate`/`clearImmediate` and every `__lava*` hook are unreachable by +name. The bootstrap still needs some of those names while it runs, so `.Web` works in +three groups: + +1. **Never injected** — the CommonJS entry bindings (`__filename`, `__dirname`, + `require`, `__lava_precache`, `module`, `exports`) and the top-level drain's + `__lavaDrainNextTicks`/`__lava_tl_drain`. Builtins get `require` as a factory + argument, and native dispatch drains nextTicks through `Runtime_State`, so nothing + internal reads them. `eval` appends no top-level drain and registers no entry module; + an `.mjs` source is `Invalid_Input`, since the ESM transform emits `require`. +2. **Not installed** — `install_stdio`. `internal/stdio` and the node-streams stack it + pulls in are never compiled; `console` writes through its own native writer. +3. **Installed, then removed** as the last step before user code — `process`, + `Buffer`, `setImmediate`, `clearImmediate`, `global`. The loader hands `process` to + `node:process`, `microtasks.js` installs `nextTick` on it, and the eager modules + capture at module-eval. + +`.Web` promises only that the names are gone: web APIs still hand out Node-shaped +values (Buffer-backed bytes, `ERR_*` codes), so `Buffer` stays reachable through a +value's `.constructor`. Pinned by `cmd/lava/global_surface_test.odin`. + ### 3.5 I/O transports (`fetch_*`, `dns.odin`, `tls.odin`) `fetch_transport.odin` is a platform-agnostic connect→[TLS]→write→read state diff --git a/pkg/runtime/environment.odin b/pkg/runtime/environment.odin index 5771ec87..1d0f1cbc 100644 --- a/pkg/runtime/environment.odin +++ b/pkg/runtime/environment.odin @@ -17,20 +17,40 @@ Module_Context :: struct { } // Головна функція, яка налаштовує середовище під Node.js (Тепер приймає loop) -setup_module_environment :: proc(ctx: jsc.JSContextRef, file_path: string, loop: ^eventloop.Loop) { +// +// `surface` (see Global_Surface, runtime.odin) decides what the entry script can +// name. Under `.Web` the CommonJS entry bindings — `__filename`, `__dirname`, +// `require`, `__lava_precache`, `module`, `exports` — are never injected, and the +// Node globals the bootstrap still needed are removed once install_globals is done. +// `.Node` takes exactly the path it took before the parameter existed. +setup_module_environment :: proc( + ctx: jsc.JSContextRef, + file_path: string, + loop: ^eventloop.Loop, + surface: Global_Surface = .Node, +) { global_obj := jsc.JSContextGetGlobalObject(ctx) - // 1. Розраховуємо __filename та __dirname - abs_path, _ := filepath.abs(file_path, context.temp_allocator) - dir_path := filepath.dir(abs_path) + if surface == .Node { + // 1. Розраховуємо __filename та __dirname + abs_path, _ := filepath.abs(file_path, context.temp_allocator) + dir_path := filepath.dir(abs_path) - // 2. Інжектуємо __filename та __dirname як глобальні змінні - inject_global_string(ctx, global_obj, "__filename", abs_path) - inject_global_string(ctx, global_obj, "__dirname", dir_path) + // 2. Інжектуємо __filename та __dirname як глобальні змінні + inject_global_string(ctx, global_obj, "__filename", abs_path) + inject_global_string(ctx, global_obj, "__dirname", dir_path) + } // 2.5. Встановлюємо глобальні об'єкти Node (console, process, таймери). // Вказівник на Event Loop живе у приватних даних global object, а не у JS. - install_globals(ctx, loop) + install_globals(ctx, loop, surface) + + if surface == .Web { + // The LAST step before user code: nothing below this point runs on `.Web`, + // and eval evaluates the entry next. + remove_node_globals(ctx, global_obj) + return + } // 3. Інжектуємо функцію require req_name := jsc.JSStringCreateWithUTF8CString("require") @@ -105,6 +125,31 @@ setup_module_environment :: proc(ctx: jsc.JSContextRef, file_path: string, loop: ) } +// WEB_REMOVED_GLOBALS are the Node globals install_globals puts on every context and +// `.Web` takes back off. Each one is needed while the bootstrap runs, which is why +// they are removed rather than never installed: the loader hands `process` to +// node:process, microtasks.js installs `process.nextTick` on it, and the eager +// modules capture at module-eval (blob.js fixes its EOL from process.platform, +// buffer.js publishes `Buffer`). The scheduler and the native drain never read them +// back off the global (Runtime_State.dispatch_fn / next_tick_drain), so removing +// them leaves timers and microtasks working. +@(private = "file") +WEB_REMOVED_GLOBALS :: [?]cstring{"process", "Buffer", "setImmediate", "clearImmediate", "global"} + +// remove_node_globals deletes WEB_REMOVED_GLOBALS from the global object. All of +// them are plain configurable properties (set_named / inject_native_function pass no +// attributes; buffer.js assigns), so the delete cannot be refused. Deleting from the +// global object can move it to JSC's dictionary mode — a cost `.Web` alone pays, +// once per context; `.Node` never calls this. +@(private = "file") +remove_node_globals :: proc(ctx: jsc.JSContextRef, global_obj: jsc.JSObjectRef) { + for name in WEB_REMOVED_GLOBALS { + js_name := jsc.JSStringCreateWithUTF8CString(name) + jsc.JSObjectDeleteProperty(ctx, global_obj, js_name, nil) + jsc.JSStringRelease(js_name) + } +} + inject_global_string :: proc( ctx: jsc.JSContextRef, global_obj: jsc.JSObjectRef, diff --git a/pkg/runtime/globals.odin b/pkg/runtime/globals.odin index f20a13c8..a40d3e2e 100644 --- a/pkg/runtime/globals.odin +++ b/pkg/runtime/globals.odin @@ -878,7 +878,12 @@ process_memory_usage_cb :: proc "c" ( // install_globals wires the Node-like global surface (console, process, // timers, queueMicrotask, globalThis) onto the context's global object. // Timer functions are no-ops when no event loop is bound. -install_globals :: proc(ctx: jsc.JSContextRef, loop: ^eventloop.Loop) { +// +// `.Web` (Global_Surface, runtime.odin) changes two things here and nothing else: +// install_stdio does not run, and install_microtasks defines no `__lava*` hook. +// Everything else is installed as on `.Node` — the bootstrap needs `process` and the +// rest — and setup_module_environment removes the Node names afterwards. +install_globals :: proc(ctx: jsc.JSContextRef, loop: ^eventloop.Loop, surface: Global_Surface = .Node) { global := jsc.JSContextGetGlobalObject(ctx) set_named(ctx, global, "globalThis", cast(jsc.JSValueRef)global) @@ -908,11 +913,15 @@ install_globals :: proc(ctx: jsc.JSContextRef, loop: ^eventloop.Loop) { install_performance(ctx, global) // process.nextTick + queueMicrotask are a JS shim (needs `process` to exist). - install_microtasks(ctx, global) + install_microtasks(ctx, global, surface) // process.stdout / process.stderr LAST of the process bits: the loader hands out a // closure rather than eager-requiring stdio, because stdio builds on `stream`, which // needs both the `process` global and `process.nextTick` to already be there. - install_stdio(ctx, global) + // Not on `.Web`, where `process` is removed before user code: stdio would compile + // internal/stdio and the whole node-streams stack (node:stream, events, + // internal/streams/*) for an object nothing can reach. console does not need it — + // bootstrap/console.js writes through the native writers install_console hands it. + if surface == .Node do install_stdio(ctx, global) install_rejection_tracker(ctx) } @@ -965,7 +974,13 @@ performance_now_cb :: proc "c" ( // (globalThis, process) so it can install process.nextTick and queueMicrotask // with Node-matching ordering. See js/bootstrap/microtasks.js for why these live // in JS on top of JSC's promise-job queue rather than the native event loop. -install_microtasks :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { +// +// On `.Node` it also defines the two globals eval's top-level drain names (see +// TOP_LEVEL_DRAIN, runtime.odin): `__lavaDrainNextTicks` and the `__lava_tl_drain` +// binding the drain assigns to. They are defined HERE, not in microtasks.js, because +// they are non-configurable — a `.Web` context could not delete them after the +// fact — and `.Web` appends no drain, so it simply never gets them. +install_microtasks :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef, surface: Global_Surface = .Node) { process := get_named(ctx, global, "process") if process == nil || !jsc.JSValueIsObject(ctx, process) do return @@ -1018,6 +1033,22 @@ install_microtasks :: proc(ctx: jsc.JSContextRef, global: jsc.JSObjectRef) { jsc.JSValueProtect(ctx, drain) state.next_tick_drain = drain } + + if surface == .Node && drain != nil && jsc.JSValueIsObject(ctx, drain) { + // The source-level hook for checkpoint 1 before JSEvaluateScript returns: + // non-writable, non-enumerable, non-configurable, as microtasks.js defined it. + drain_name := jsc.JSStringCreateWithUTF8CString("__lavaDrainNextTicks") + defer jsc.JSStringRelease(drain_name) + jsc.JSObjectSetProperty(ctx, global, drain_name, drain, {.ReadOnly, .DontEnum, .DontDelete}, nil) + // Pre-create the binding the drain's `var __lava_tl_drain = ...` assigns to, as + // a non-enumerable property. A VariableStatement (kept for its empty completion + // value) would otherwise create an ENUMERABLE non-configurable global; + // redeclaring an existing own property writes through without changing this + // descriptor, so the internal name stays out of `Object.keys(globalThis)`. + tl_name := jsc.JSStringCreateWithUTF8CString("__lava_tl_drain") + defer jsc.JSStringRelease(tl_name) + jsc.JSObjectSetProperty(ctx, global, tl_name, jsc.JSValueMakeUndefined(ctx), {.DontEnum, .DontDelete}, nil) + } } // invoke_user_callback runs a user JS callback at an event-loop boundary (timer / diff --git a/pkg/runtime/js/bootstrap/microtasks.js b/pkg/runtime/js/bootstrap/microtasks.js index 03a1aa81..ab32a731 100644 --- a/pkg/runtime/js/bootstrap/microtasks.js +++ b/pkg/runtime/js/bootstrap/microtasks.js @@ -63,7 +63,6 @@ var promiseThen = uncurryThis(Promise.prototype.then); var arraySlice = uncurryThis(Array.prototype.slice); var functionApply = Reflect.apply; - var objectDefineProperty = Object.defineProperty; var EMPTY = []; var resolved = promiseResolve(PromiseCtor); @@ -147,29 +146,10 @@ process.nextTick = nextTick; globalObject.queueMicrotask = queueMicrotask; - // Internal, non-enumerable global so the native top-level drain shim (a trailing - // statement appended to the entry source) can reach checkpoint 1 before - // JSEvaluateScript returns. Native also receives drainNextTicks directly via the - // factory return below; this hook exists only for the JS-source-level drain. - objectDefineProperty(globalObject, '__lavaDrainNextTicks', { - value: drainNextTicks, - writable: false, - enumerable: false, - configurable: false, - }); - - // Pre-create the binding the top-level drain assigns to, as a non-enumerable - // property. The appended `var __lava_tl_drain = ...` (a VariableStatement, kept - // for its empty completion value — see runtime.odin) would otherwise create an - // *enumerable*, non-configurable global; redeclaring an existing own property - // instead writes through without changing this descriptor, so the internal name - // stays out of `Object.keys(globalThis)` / `for...in`. - objectDefineProperty(globalObject, '__lava_tl_drain', { - value: undefined, - writable: true, - enumerable: false, - configurable: false, - }); - + // The global hooks the native top-level drain shim (a trailing statement appended + // to the entry source) reaches checkpoint 1 through — `__lavaDrainNextTicks` and + // the `__lava_tl_drain` binding — are defined by install_microtasks from the + // drainNextTicks returned here, and only on the `.Node` surface: they are + // non-configurable, so a `.Web` context could not delete them once defined. return { drainNextTicks: drainNextTicks, dispatch: dispatch }; }); diff --git a/pkg/runtime/runtime.odin b/pkg/runtime/runtime.odin index 710a0970..9f8c30a2 100644 --- a/pkg/runtime/runtime.odin +++ b/pkg/runtime/runtime.odin @@ -38,6 +38,57 @@ Result :: struct { backend_failed: bool, } +// Global_Surface selects which global names a context's script can reach — the +// trailing `surface` parameter of eval, threaded through setup_module_environment +// into install_globals. +// +// .Node Everything `lava run` exposes: the web-platform set below plus +// `process`, `require`, `module`, `exports`, `__filename`, `__dirname`, +// `Buffer`, `global`, `setImmediate`/`clearImmediate`, and the internal +// `__lava_precache`/`__lavaDrainNextTicks`/`__lava_tl_drain` hooks. +// The default; `run_file` and the CLI never select anything else. +// .Web The web-platform subset only: fetch/Request/Response/Headers, +// URL/URLSearchParams, the Web Streams family and its queuing strategies, +// TextEncoder/TextDecoder, Blob/File, AbortController/AbortSignal, +// structuredClone, atob/btoa, crypto, performance, console, +// queueMicrotask, and setTimeout/setInterval/clearTimeout/clearInterval. +// A classic script only: an `.mjs` source name is Invalid_Input (exit 2), +// because the ESM transform emits `require` and `__lava_precache`. +// Node: +// No counterpart — node has one global surface. `.Node` is the one the oracle +// suites check, byte for byte. +// Deviates: +// `.Web` is a Lava-only surface; pinned by cmd/lava/global_surface_test.odin +// (every hidden name by `typeof`, every kept API exercised, `.mjs` refused, stdio +// never compiled, Node/Web/Node alternating on one thread). +// +// How `.Web` gets there, in three groups, because the bootstrap needs some of the +// Node names while it runs: +// 1. Never injected: `__filename`, `__dirname`, `require`, `__lava_precache`, +// `module`, `exports` (setup_module_environment). Nothing internal reads them — +// builtins get `require` as a factory argument. `__lava_tl_drain`/ +// `__lavaDrainNextTicks` are not defined either (install_microtasks): eval +// appends no top-level drain, since nothing a `.Web` script can name queues a +// nextTick, so node's nextTick-before-promise ordering has nothing to order. +// Native dispatch still drains through Runtime_State.next_tick_drain. +// 2. Not installed: install_stdio. internal/stdio and the node-streams stack it +// pulls in are never compiled; console writes through its own native writer. +// 3. Installed, then removed as the last step before user code (remove_node_globals): +// `process`, `Buffer`, `setImmediate`, `clearImmediate`, `global`. The loader +// hands `process` to node:process and microtasks.js installs nextTick on it; +// the eager modules capture at module-eval (blob.js's EOL reads +// process.platform), so these must exist until the bootstrap is done. +// +// What `.Web` does NOT promise: the web APIs still hand out Node-shaped values — +// Buffer-backed bytes, `ERR_*` codes — so `Buffer` stays reachable through a value's +// `.constructor`. The NAMES are gone, nothing more (x-ror/larva#5). And +// internal/url.js reads `process.platform` live inside fileURLToPath/pathToFileURL; +// those are node:url APIs, unreachable without `require`. +Global_Surface :: enum { + Node, // everything `lava run` exposes today. Default. + Web, // the web-platform subset only. +} + result_destroy :: proc(res: ^Result) { if res.is_allocated && len(res.message) > 0 { delete(res.message) @@ -135,6 +186,11 @@ reported :: proc(result: Result, report: Result_Hook, report_data: rawptr) -> Re // REPORT: a non-nil `report` (Result_Hook) fires exactly once on every return — // pre-flight rejections included — with the Result being returned, before eval's // deferred loop teardown and context release run. +// +// SURFACE: `surface` picks the global names the script can reach (Global_Surface). +// `.Web` runs a classic script only — an `.mjs` source name is refused up front — +// and the entry is neither registered in the module cache nor given the top-level +// nextTick drain, both of which exist for CommonJS and process.nextTick. eval :: proc( source: string, source_name := "", @@ -145,8 +201,9 @@ eval :: proc( pre_run_data: rawptr = nil, report: Result_Hook = nil, report_data: rawptr = nil, + surface: Global_Surface = .Node, ) -> Result { - // eval consumes the loop on EVERY path (see the OWNERSHIP note above). These two + // eval consumes the loop on EVERY path (see the OWNERSHIP note above). These three // pre-flight rejections return before the JS context (and the deferred teardown // below) exists, so they destroy the loop explicitly. It holds no handles yet, so // this single destroy needs no live context. @@ -168,6 +225,18 @@ eval :: proc( }, report, report_data) } + // The ESM transform rewrites an `.mjs` entry to CommonJS that calls `require` and + // `__lava_precache`, neither of which a `.Web` context has; refused here, before a + // context exists, rather than failing inside the transformed body. + if surface == .Web && strings.has_suffix(source_name, ".mjs") { + if loop != nil do eventloop.destroy(loop) + return reported(Result { + status = .Invalid_Input, + exit_code = 2, + message = "the web global surface runs classic scripts only; .mjs sources need the node surface", + }, report, report_data) + } + // A JS runtime must survive writes to closed pipes/sockets (Node parity): // see signals_posix.odin. Installed per eval — the call is idempotent. ignore_sigpipe() @@ -258,7 +327,7 @@ eval :: proc( eventloop.destroy(loop) } - setup_module_environment(cast(jsc.JSContextRef)ctx, source_name, loop) + setup_module_environment(cast(jsc.JSContextRef)ctx, source_name, loop, surface) // ESM entrypoints (.mjs) are rewritten to CommonJS via the same transform the // loader applies to imported .mjs modules; script (.js) and `lava eval` @@ -287,7 +356,7 @@ eval :: proc( eval_source = wrapped mjs_wrapped = wrapped mjs_allocated = true - } else { + } else if surface == .Node { // Register the CommonJS/script entry in the module cache before it runs, so // requiring the entry by path returns the same instance (and an entry- // involved require cycle terminates instead of re-executing the entry). The @@ -304,12 +373,19 @@ eval :: proc( // completion value) so it does not clobber the script's completion value used by // `lava eval`'s echo; the leading "\n;" guards a trailing line comment / missing // semicolon; typeof keeps it a no-op if the microtask shim failed to install. + // + // Not on `.Web`: nothing a `.Web` script can name queues a nextTick, so there is no + // ordering to keep, and the drain's two globals are deliberately absent there + // (install_microtasks). The post-evaluation drain_next_ticks_settled below still + // runs on both surfaces; it goes through Runtime_State, not a global. TOP_LEVEL_DRAIN :: "\n;var __lava_tl_drain = (typeof __lavaDrainNextTicks === 'function') && __lavaDrainNextTicks();\n" - if combined, concat_err := strings.concatenate( - {eval_source, TOP_LEVEL_DRAIN}, - context.temp_allocator, - ); concat_err == nil { - eval_source = combined + if surface == .Node { + if combined, concat_err := strings.concatenate( + {eval_source, TOP_LEVEL_DRAIN}, + context.temp_allocator, + ); concat_err == nil { + eval_source = combined + } } script := js_string_from_string(eval_source) @@ -366,7 +442,7 @@ eval :: proc( // Refresh the cached entry exports: a CommonJS entry body may have reassigned // module.exports, so the pre-eval partial registered above is now stale. - if !mjs_allocated { + if !mjs_allocated && surface == .Node { register_entry_module(cast(jsc.JSContextRef)ctx, state, source_name) } diff --git a/tests/mutation-manifest.json b/tests/mutation-manifest.json index 6aa4600c..58123aea 100644 --- a/tests/mutation-manifest.json +++ b/tests/mutation-manifest.json @@ -2932,6 +2932,69 @@ "replace": "", "gate": "compat:tests/node-compat/cases/86-os-internal-modules.js", "expect_detail": "node: constants dlopen object" + }, + { + "name": "global_surface_web_hides_node_names dies when Buffer is dropped from the .Web removal list", + "why": "WEB_REMOVED_GLOBALS is the only thing that takes the bootstrap-only Node globals back off a .Web context; a name missing from it stays reachable by name, which is exactly what .Web promises it is not.", + "source": "pkg/runtime/environment.odin", + "find": "[?]cstring{\"process\", \"Buffer\", \"setImmediate\", \"clearImmediate\", \"global\"}", + "replace": "[?]cstring{\"process\", \"setImmediate\", \"clearImmediate\", \"global\"}", + "gate": "odin:cmd/lava:main.global_surface_web_hides_node_names", + "expect_detail": "want Buffer=undefined got Buffer=function" + }, + { + "name": "global_surface_web_hides_node_names dies when .Web falls through to the CommonJS entry bindings", + "why": "The early return after remove_node_globals is what keeps require, __lava_precache, module and exports off a .Web context; without it a .Web script reaches the filesystem loader.", + "source": "pkg/runtime/environment.odin", + "find": "\t\tremove_node_globals(ctx, global_obj)\n\t\treturn\n", + "replace": "\t\tremove_node_globals(ctx, global_obj)\n", + "gate": "odin:cmd/lava:main.global_surface_web_hides_node_names", + "expect_detail": "want require=undefined got require=function" + }, + { + "name": "global_surface_web_skips_stdio dies when install_stdio runs on .Web", + "why": "stdio compiles internal/stdio and the node-streams stack for a process object .Web removes; the surface gate is what keeps that cost off .Web contexts.", + "source": "pkg/runtime/globals.odin", + "find": "\tif surface == .Node do install_stdio(ctx, global)", + "replace": "\tinstall_stdio(ctx, global)", + "gate": "odin:cmd/lava:main.global_surface_web_skips_stdio", + "expect_detail": "web: resolving events compiled nothing" + }, + { + "name": "global_surface_web_rejects_mjs dies when eval stops refusing .mjs on .Web", + "why": "The ESM transform emits require and __lava_precache, which .Web never injects; the pre-flight refusal is the contract a .Web caller gets instead of a body that depends on names it cannot have.", + "source": "pkg/runtime/runtime.odin", + "find": "if surface == .Web && strings.has_suffix(source_name, \".mjs\") {", + "replace": "if false && surface == .Web && strings.has_suffix(source_name, \".mjs\") {", + "gate": "odin:cmd/lava:main.global_surface_web_rejects_mjs", + "expect_detail": "web .mjs status=Ok (want Invalid_Input)" + }, + { + "name": "global_surface_web_hides_node_names dies when install_microtasks defines the drain hooks on .Web", + "why": "__lavaDrainNextTicks and __lava_tl_drain are non-configurable, so .Web cannot delete them afterwards; the surface check in install_microtasks is the only thing that keeps them off.", + "source": "pkg/runtime/globals.odin", + "find": "if surface == .Node && drain != nil && jsc.JSValueIsObject(ctx, drain) {", + "replace": "if drain != nil && jsc.JSValueIsObject(ctx, drain) {", + "gate": "odin:cmd/lava:main.global_surface_web_hides_node_names", + "expect_detail": "want __lavaDrainNextTicks=undefined got __lavaDrainNextTicks=function" + }, + { + "name": "global_surface_web_hides_node_names dies when eval appends the top-level drain on .Web", + "why": "The appended `var __lava_tl_drain = ...` declares a __lava* global in the script's global scope once the entry body finishes; only the post-body typeof/in check sees it, because JSC keeps the program-level var out of getOwnPropertyNames.", + "source": "pkg/runtime/runtime.odin", + "find": "\tif surface == .Node {\n\t\tif combined, concat_err := strings.concatenate(", + "replace": "\tif true {\n\t\tif combined, concat_err := strings.concatenate(", + "gate": "odin:cmd/lava:main.global_surface_web_hides_node_names", + "expect_detail": "want tl-drain-after=undefined,false got tl-drain-after=boolean,true" + }, + { + "name": "global_surface_alternates_on_one_thread dies when eval's default surface is not .Node", + "why": "run_file, the CLI and every existing embedder call eval without a surface; the default is what keeps them byte-identical to the pre-seam runtime.", + "source": "pkg/runtime/runtime.odin", + "find": "\tsurface: Global_Surface = .Node,\n) -> Result {", + "replace": "\tsurface: Global_Surface = .Web,\n) -> Result {", + "gate": "odin:cmd/lava:main.global_surface_alternates_on_one_thread", + "expect_detail": "node before web: status=Execution_Error" } ] }