@exodus/stasis-core 1.0.0-beta.4 → 1.0.0-beta.6
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.
- package/bin/stasis-core.js +17 -3
- package/package.json +6 -4
- package/src/add.js +36 -46
- package/src/artifact-util.js +263 -34
- package/src/bundle-util.js +244 -33
- package/src/bundle.js +154 -110
- package/src/config.js +163 -223
- package/src/extract.js +8 -16
- package/src/fs.js +180 -296
- package/src/hooks.js +228 -108
- package/src/host.js +45 -0
- package/src/lockfile.js +22 -75
- package/src/prune.js +63 -130
- package/src/shard.js +13 -5
- package/src/state-util.js +10 -6
- package/src/state.js +452 -479
- package/src/util.js +35 -48
package/src/hooks.js
CHANGED
|
@@ -8,63 +8,34 @@ import assert from 'node:assert/strict'
|
|
|
8
8
|
|
|
9
9
|
import { State } from './state.js'
|
|
10
10
|
import { installFsHooks } from './fs.js'
|
|
11
|
-
import {
|
|
12
|
-
NATIVE_BUILD_FORMATS as NATIVE_SOURCE_FORMATS,
|
|
13
|
-
NODE_FORMATS as NODEJS_FORMATS,
|
|
14
|
-
RESOURCE_FORMATS,
|
|
15
|
-
SOURCE_LANGUAGE_FORMATS as NON_NODE_SOURCE_LANGUAGES,
|
|
16
|
-
STAT_FORMATS,
|
|
17
|
-
} from './util.js'
|
|
11
|
+
import { NATIVE_BUILD_FORMATS, NODE_FORMATS, RESOURCE_FORMATS, SOURCE_LANGUAGE_FORMATS, STAT_FORMATS, erasedTypeScriptFormat, nestedMap } from './util.js'
|
|
18
12
|
|
|
19
13
|
// Snapshot off the namespace so `--fs` can't redirect stasis's own capture/shard reads.
|
|
20
14
|
const { mkdtempSync, opendirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } = fs
|
|
21
15
|
|
|
22
16
|
const CJS_FORMATS = new Set(['commonjs', 'commonjs-typescript'])
|
|
23
17
|
|
|
18
|
+
// The trust gate's refusal for a bundle-served file whose attested format Node can't execute, by kind.
|
|
24
19
|
function refuseNonNodeFormat(format, url) {
|
|
25
|
-
if (
|
|
26
|
-
throw new Error(
|
|
27
|
-
`[stasis] cannot execute a '${format}' bundle: ${format} bundles are ` +
|
|
28
|
-
`produced for external analysis, not for 'stasis run --bundle=load' (${url})`
|
|
29
|
-
)
|
|
20
|
+
if (SOURCE_LANGUAGE_FORMATS.has(format)) {
|
|
21
|
+
throw new Error(`[stasis] cannot execute a '${format}' bundle: ${format} bundles are produced for external analysis, not for 'stasis run --bundle=load' (${url})`)
|
|
30
22
|
}
|
|
31
|
-
if (
|
|
32
|
-
throw new Error(
|
|
33
|
-
`[stasis] cannot execute a '${format}' file: native build inputs ` +
|
|
34
|
-
`(podspec/gradle/Java/Kotlin/ObjC++/...) are attested for the CocoaPods/Gradle ` +
|
|
35
|
-
`toolchain, not executable by Node (${url})`
|
|
36
|
-
)
|
|
23
|
+
if (NATIVE_BUILD_FORMATS.has(format)) {
|
|
24
|
+
throw new Error(`[stasis] cannot execute a '${format}' file: native build inputs (podspec/gradle/Java/Kotlin/ObjC++/...) are attested for the CocoaPods/Gradle toolchain, not executable by Node (${url})`)
|
|
37
25
|
}
|
|
38
26
|
if (RESOURCE_FORMATS.has(format)) {
|
|
39
|
-
throw new Error(
|
|
40
|
-
`[stasis] cannot import a resource file ('${format}'): asset content is not ` +
|
|
41
|
-
`executable JavaScript. Read it with fs (or your bundler's asset loader) instead (${url})`
|
|
42
|
-
)
|
|
27
|
+
throw new Error(`[stasis] cannot import a resource file ('${format}'): asset content is not executable JavaScript. Read it with fs (or your bundler's asset loader) instead (${url})`)
|
|
43
28
|
}
|
|
44
29
|
if (format === 'patch') {
|
|
45
|
-
throw new Error(
|
|
46
|
-
`[stasis] cannot execute a 'patch' file: a unified diff is applied by a patch step ` +
|
|
47
|
-
`(pnpm patchedDependencies, patch-package, a build script), not run by Node (${url})`
|
|
48
|
-
)
|
|
30
|
+
throw new Error(`[stasis] cannot execute a 'patch' file: a unified diff is applied by a patch step (pnpm patchedDependencies, patch-package, a build script), not run by Node (${url})`)
|
|
49
31
|
}
|
|
50
32
|
if (format === 'directory') {
|
|
51
|
-
throw new Error(
|
|
52
|
-
`[stasis] cannot import a directory listing ('directory'): a captured ` +
|
|
53
|
-
`fs.readdirSync result is not executable JavaScript. Read it with fs.readdirSync instead (${url})`
|
|
54
|
-
)
|
|
33
|
+
throw new Error(`[stasis] cannot import a directory listing ('directory'): a captured fs.readdirSync result is not executable JavaScript. Read it with fs.readdirSync instead (${url})`)
|
|
55
34
|
}
|
|
56
35
|
if (STAT_FORMATS.has(format)) {
|
|
57
|
-
throw new Error(
|
|
58
|
-
`[stasis] cannot import '${url}': the bundle carries only a payload-free stat record ` +
|
|
59
|
-
`('${format}', an fs.lstatSync/statSync capture attesting existence and kind) -- ` +
|
|
60
|
-
`not the file's content. Capture a run that reads or imports it to bundle its bytes.`
|
|
61
|
-
)
|
|
36
|
+
throw new Error(`[stasis] cannot import '${url}': the bundle carries only a payload-free stat record ('${format}', an fs.lstatSync/statSync capture attesting existence and kind) -- not the file's content. Capture a run that reads or imports it to bundle its bytes.`)
|
|
62
37
|
}
|
|
63
|
-
throw new Error(
|
|
64
|
-
`[stasis] cannot execute '${url}': attested format '${format}' is not a Node loader ` +
|
|
65
|
-
`format. The bundle may be tampered, produced by a newer stasis, or built for a ` +
|
|
66
|
-
`non-Node consumer.`
|
|
67
|
-
)
|
|
38
|
+
throw new Error(`[stasis] cannot execute '${url}': attested format '${format}' is not a Node loader format. The bundle may be tampered, produced by a newer stasis, or built for a non-Node consumer.`)
|
|
68
39
|
}
|
|
69
40
|
|
|
70
41
|
// node:59666: restores require.cache/require.extensions the ESM->CJS translator's require omits.
|
|
@@ -139,6 +110,32 @@ let aborted = false
|
|
|
139
110
|
let loadingModule = 0
|
|
140
111
|
// True until the first non-builtin load hook fires (entry detection).
|
|
141
112
|
let entryUnseen = true
|
|
113
|
+
// True until the first parent-less resolution -- the CLI entry. Extra preloads (`stasis run
|
|
114
|
+
// --import tsx`) resolve against a DIRECTORY parent (the cwd URL, '/'-terminated -- never a
|
|
115
|
+
// loadable module) and load BEFORE it: they are runner infrastructure like stasis's own loader.
|
|
116
|
+
// Capturing them would misfile the first preload as the entry (initState from ITS package root)
|
|
117
|
+
// and pollute the artifact with toolchain files; gating them would break --bundle=load (the
|
|
118
|
+
// preload itself must keep loading from disk). Any OTHER pre-entry parent (an [eval] wrapper's
|
|
119
|
+
// import) falls through to the normal path and fails closed on assert.ok(state), like a run
|
|
120
|
+
// without preloads.
|
|
121
|
+
let entryUnresolved = true
|
|
122
|
+
// The runner-infrastructure module graph: every URL the preload phase resolved or loaded, plus
|
|
123
|
+
// its post-entry descendants (a transformer lazy-loading a plugin). Members pass both hooks
|
|
124
|
+
// through unobserved -- but NOT unforgotten:
|
|
125
|
+
// - infraSources stashes each infra load's raw {source, format} and infraEdges its outgoing
|
|
126
|
+
// resolutions, so that when the APP graph reaches an infra module (its load hook can never
|
|
127
|
+
// re-fire -- the module instance is cached) it is PROMOTED into the capture with the exact
|
|
128
|
+
// bytes that executed, its own edges replayed transitively. Without promotion the artifact
|
|
129
|
+
// would ship a dangling edge and a frozen replay would never verify the file.
|
|
130
|
+
// - under --bundle=load, an app edge landing on an infra URL means the cached disk-loaded
|
|
131
|
+
// instance shadows the attested bundle bytes: allowed only when they are identical.
|
|
132
|
+
const infraUrls = new Set()
|
|
133
|
+
const infraSources = new Map()
|
|
134
|
+
const infraEdges = new Map()
|
|
135
|
+
// URLs the bundle=load load hook actually served, so the CJS shim can detect a require() that
|
|
136
|
+
// executed an attested file from DISK instead (a transplanted require.extensions handler, e.g.
|
|
137
|
+
// tsx's '.ts' pipeline, reads and compiles the file itself -- the load hook never fires).
|
|
138
|
+
const servedFromBundle = new Set()
|
|
142
139
|
|
|
143
140
|
// EXODUS_STASIS_PID = the root stasis's pid; on mismatch we're a child and must not write the
|
|
144
141
|
// bundle/lockfile (root owns the artifact; a 2nd writer races). A forked child also relaxes assertEntry.
|
|
@@ -156,6 +153,28 @@ const PRELOAD_ROOT = (() => {
|
|
|
156
153
|
}
|
|
157
154
|
})()
|
|
158
155
|
|
|
156
|
+
// A capture step whose rejection must never be written, even if user code swallows the throw.
|
|
157
|
+
function recording(fn) {
|
|
158
|
+
try {
|
|
159
|
+
return fn()
|
|
160
|
+
} catch (err) {
|
|
161
|
+
aborted = true
|
|
162
|
+
throw err
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// nextLoad with `loadingModule` held, so the --fs hook skips the loader's own read of the source.
|
|
167
|
+
function loadCounted(nextLoad, url, context) {
|
|
168
|
+
loadingModule++
|
|
169
|
+
try {
|
|
170
|
+
return nextLoad(url, context)
|
|
171
|
+
} finally {
|
|
172
|
+
loadingModule--
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const toBuffer = (source) => (Buffer.isBuffer(source) ? source : Buffer.from(source))
|
|
177
|
+
|
|
159
178
|
// Child-process capture forwarding (shards), opt-in via --child-process: a capturing child writes a
|
|
160
179
|
// signed per-pid shard the root verifies against its own public key before merging. Trust rests on
|
|
161
180
|
// that signature, not the dir being secret; shards carry NO bytes (the root re-reads from disk).
|
|
@@ -164,6 +183,16 @@ function shardForwardingEnabled() {
|
|
|
164
183
|
return Boolean(state) && state.config.childProcess && (state.config.writeLockfile || state.config.writeBundle)
|
|
165
184
|
}
|
|
166
185
|
|
|
186
|
+
function clearShardEnv() {
|
|
187
|
+
delete process.env.EXODUS_STASIS_SHARD_DIR
|
|
188
|
+
delete process.env.EXODUS_STASIS_SHARD_KEY
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function removeShardDir() {
|
|
192
|
+
if (!createdShardDir) return
|
|
193
|
+
try { rmSync(createdShardDir, { recursive: true, force: true }) } catch { /* best-effort */ }
|
|
194
|
+
}
|
|
195
|
+
|
|
167
196
|
function writeChildShard() {
|
|
168
197
|
if (!shardForwardingEnabled()) return
|
|
169
198
|
const dir = process.env.EXODUS_STASIS_SHARD_DIR
|
|
@@ -256,17 +285,13 @@ function initState(root) {
|
|
|
256
285
|
} catch {
|
|
257
286
|
// Best-effort: clear any inherited (possibly attacker-set) dir/key so descendants don't fall
|
|
258
287
|
// back to a channel we never minted.
|
|
259
|
-
|
|
260
|
-
createdShardDir = undefined
|
|
261
|
-
|
|
262
|
-
createdShardPubId = undefined
|
|
263
|
-
delete process.env.EXODUS_STASIS_SHARD_DIR
|
|
264
|
-
delete process.env.EXODUS_STASIS_SHARD_KEY
|
|
288
|
+
removeShardDir()
|
|
289
|
+
createdShardDir = createdShardPub = createdShardPubId = undefined
|
|
290
|
+
clearShardEnv()
|
|
265
291
|
}
|
|
266
292
|
} else if (!isChildProcess) {
|
|
267
293
|
// Non-capturing root: shed any inherited (possibly attacker-set) shard env.
|
|
268
|
-
|
|
269
|
-
delete process.env.EXODUS_STASIS_SHARD_KEY
|
|
294
|
+
clearShardEnv()
|
|
270
295
|
}
|
|
271
296
|
|
|
272
297
|
// Persist on exit unless `aborted` -- deliberately NOT gated on exit code, so a clean capture
|
|
@@ -288,9 +313,7 @@ function initState(root) {
|
|
|
288
313
|
// require() from another exit handler) is still attested and must not trip the load hook.
|
|
289
314
|
if (writing) saved = true
|
|
290
315
|
} finally {
|
|
291
|
-
|
|
292
|
-
try { rmSync(createdShardDir, { recursive: true, force: true }) } catch { /* best-effort */ }
|
|
293
|
-
}
|
|
316
|
+
removeShardDir()
|
|
294
317
|
}
|
|
295
318
|
}
|
|
296
319
|
|
|
@@ -308,48 +331,59 @@ function initState(root) {
|
|
|
308
331
|
try {
|
|
309
332
|
save()
|
|
310
333
|
} finally {
|
|
311
|
-
if (!userOwnedSigterm && process.listenerCount('SIGTERM') === 0)
|
|
312
|
-
process.kill(process.pid, 'SIGTERM')
|
|
313
|
-
}
|
|
334
|
+
if (!userOwnedSigterm && process.listenerCount('SIGTERM') === 0) process.kill(process.pid, 'SIGTERM')
|
|
314
335
|
}
|
|
315
336
|
})
|
|
316
337
|
}
|
|
317
338
|
}
|
|
318
339
|
|
|
340
|
+
// Init from the package root of `url` (the entry), exactly as its live load would.
|
|
341
|
+
function initStateFromPackage(url) {
|
|
342
|
+
const pkg = findPackageJSON(url)
|
|
343
|
+
assert.equal(basename(pkg), 'package.json')
|
|
344
|
+
initState(dirname(pkg))
|
|
345
|
+
}
|
|
346
|
+
|
|
319
347
|
function load(url, context, nextLoad) {
|
|
320
348
|
assert.equal(typeof url, 'string')
|
|
321
349
|
|
|
350
|
+
// Runner-infrastructure passthrough (see entryUnresolved): a preload's module graph loads
|
|
351
|
+
// before the entry (or lazily after, from an infra parent). Stash the raw result so a later
|
|
352
|
+
// app-graph edge can promote the module with the exact bytes that executed.
|
|
353
|
+
if ((entryUnresolved || infraUrls.has(url)) && !url.startsWith('node:')) {
|
|
354
|
+
infraUrls.add(url)
|
|
355
|
+
const result = loadCounted(nextLoad, url, context)
|
|
356
|
+
if (!infraSources.has(url)) infraSources.set(url, { source: result.source, format: result.format })
|
|
357
|
+
return result
|
|
358
|
+
}
|
|
359
|
+
|
|
322
360
|
if (url.startsWith('node:')) {
|
|
323
361
|
const result = nextLoad(url, context)
|
|
324
362
|
assert.equal(result.format, 'builtin')
|
|
325
363
|
return result
|
|
326
364
|
}
|
|
327
365
|
|
|
328
|
-
if (state
|
|
366
|
+
if (state?.config.loadBundle) {
|
|
329
367
|
// node_modules scope serves only nm deps; gate on inNodeModules(), not a raw substring (symlinks).
|
|
330
|
-
if (!state.config.full && !state.inNodeModules(url))
|
|
331
|
-
return nextLoad(url, context)
|
|
332
|
-
}
|
|
368
|
+
if (!state.config.full && !state.inNodeModules(url)) return nextLoad(url, context)
|
|
333
369
|
const { source, format } = state.getFile(url)
|
|
334
370
|
// Cross-check format only when the resolve chain set it; the formats map is itself attested
|
|
335
|
-
// against the lockfile at construction.
|
|
336
|
-
|
|
371
|
+
// against the lockfile at construction. A transforming preload (`stasis run --import tsx`)
|
|
372
|
+
// legitimately asks for an attested '-typescript' file as its post-erasure family -- serve
|
|
373
|
+
// the chain's view then (the transformer above us turns the raw source into it).
|
|
374
|
+
let serveFormat = format
|
|
375
|
+
if (context.format != null) {
|
|
376
|
+
if (context.format === erasedTypeScriptFormat(format)) serveFormat = context.format
|
|
377
|
+
else assert.equal(format, context.format)
|
|
378
|
+
}
|
|
337
379
|
// Trust gate: only serve a file whose attested format Node can execute; everything else fails closed.
|
|
338
|
-
if (!
|
|
380
|
+
if (!NODE_FORMATS.has(format)) refuseNonNodeFormat(format, url)
|
|
381
|
+
servedFromBundle.add(url)
|
|
339
382
|
// node:59666: a load-hook-supplied CJS source gets a re-invented require() missing .cache/.extensions.
|
|
340
|
-
|
|
341
|
-
return { source: repairCjsRequire(source), format, shortCircuit: true }
|
|
342
|
-
}
|
|
343
|
-
return { source, format, shortCircuit: true }
|
|
383
|
+
return { source: CJS_FORMATS.has(format) ? repairCjsRequire(source) : source, format: serveFormat, shortCircuit: true }
|
|
344
384
|
}
|
|
345
385
|
|
|
346
|
-
|
|
347
|
-
let result
|
|
348
|
-
try {
|
|
349
|
-
result = nextLoad(url, context)
|
|
350
|
-
} finally {
|
|
351
|
-
loadingModule--
|
|
352
|
-
}
|
|
386
|
+
const result = loadCounted(nextLoad, url, context)
|
|
353
387
|
let { source } = result
|
|
354
388
|
const { format } = result
|
|
355
389
|
assert.notEqual(format, 'builtin')
|
|
@@ -359,25 +393,76 @@ function load(url, context, nextLoad) {
|
|
|
359
393
|
|
|
360
394
|
const isEntry = entryUnseen
|
|
361
395
|
entryUnseen = false
|
|
362
|
-
if (!state)
|
|
363
|
-
const pkg = findPackageJSON(url)
|
|
364
|
-
assert.equal(basename(pkg), 'package.json')
|
|
365
|
-
initState(dirname(pkg))
|
|
366
|
-
}
|
|
396
|
+
if (!state) initStateFromPackage(url)
|
|
367
397
|
|
|
368
398
|
assert.equal(saved, false)
|
|
369
|
-
|
|
370
|
-
try {
|
|
371
|
-
state.addFile(url, { source, format, isEntry })
|
|
372
|
-
} catch (err) {
|
|
373
|
-
aborted = true
|
|
374
|
-
throw err
|
|
375
|
-
}
|
|
399
|
+
recording(() => state.addFile(url, { source, format, isEntry }))
|
|
376
400
|
|
|
377
401
|
return result
|
|
378
402
|
}
|
|
379
403
|
|
|
404
|
+
// Fold a runner-infrastructure module into the capture: an app-graph edge reached a module the
|
|
405
|
+
// preload phase already executed, so its load hook can never re-fire (the instance is cached) and
|
|
406
|
+
// skipping it would ship a dangling edge a frozen replay never verifies. addFile re-verifies the
|
|
407
|
+
// stashed bytes against disk (and against the lockfile/bundle in frozen modes), and the module's
|
|
408
|
+
// own remembered resolutions replay transitively so its dependencies aren't dangling either.
|
|
409
|
+
function promoteInfraUrl(url, { isEntry = false } = {}) {
|
|
410
|
+
if (!infraUrls.delete(url)) return
|
|
411
|
+
const stashed = infraSources.get(url)
|
|
412
|
+
infraSources.delete(url)
|
|
413
|
+
// Same disk fallback as the live load path: Node's CJS loader may return source=null.
|
|
414
|
+
const source = stashed?.source ?? readFileSync(fileURLToPath(url))
|
|
415
|
+
recording(() => state.addFile(url, { source, format: stashed?.format ?? undefined, isEntry }))
|
|
416
|
+
const edges = infraEdges.get(url)
|
|
417
|
+
infraEdges.delete(url)
|
|
418
|
+
for (const [specifier, edge] of edges ?? []) {
|
|
419
|
+
recording(() => state.addImport(url, specifier, edge.url, edge.context))
|
|
420
|
+
if (infraSources.has(edge.url)) promoteInfraUrl(edge.url)
|
|
421
|
+
else infraUrls.delete(edge.url) // resolved but never loaded: a live load would capture it
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Under --bundle=load, an app edge landing on a module the preload phase already loaded means the
|
|
426
|
+
// CACHED disk-loaded instance shadows whatever the hooks would serve from the bundle: allowed
|
|
427
|
+
// only when the executed bytes and the attested bytes are identical, else fail closed.
|
|
428
|
+
function assertInfraMatchesBundle(url) {
|
|
429
|
+
if (!infraUrls.has(url)) return
|
|
430
|
+
const stashed = infraSources.get(url)
|
|
431
|
+
if (stashed === undefined) { infraUrls.delete(url); return } // resolved but never loaded: the hooks will serve it
|
|
432
|
+
const executed = toBuffer(stashed.source ?? readFileSync(fileURLToPath(url)))
|
|
433
|
+
if (!executed.equals(toBuffer(state.getFile(url).source))) {
|
|
434
|
+
throw new Error(
|
|
435
|
+
`[stasis] cannot serve '${url}' from the bundle: a preload already executed it from disk ` +
|
|
436
|
+
`before the entry, and those bytes differ from the attested ones -- refusing the divergent ` +
|
|
437
|
+
`cached instance`
|
|
438
|
+
)
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
380
442
|
function resolve(specifier, context, nextResolve) {
|
|
443
|
+
// Runner-infrastructure passthrough (see entryUnresolved): a preload's graph resolves from a
|
|
444
|
+
// DIRECTORY parent (the cwd URL Node uses for each `--import` specifier -- a directory is never
|
|
445
|
+
// a loadable module, so this cannot shadow an app parent) or from a module already tracked as
|
|
446
|
+
// infrastructure. The first parent-less resolution is still the entry, and any other pre-entry
|
|
447
|
+
// parent (an [eval] wrapper's import) falls through to fail closed below. Each passed-through
|
|
448
|
+
// edge is remembered -- not recorded -- so promoteInfraUrl can replay it if the app graph
|
|
449
|
+
// reaches this module later.
|
|
450
|
+
const infraParent = context.parentURL !== undefined
|
|
451
|
+
&& (infraUrls.has(context.parentURL) || (entryUnresolved && context.parentURL.endsWith('/')))
|
|
452
|
+
if (infraParent) {
|
|
453
|
+
const res = nextResolve(specifier)
|
|
454
|
+
if (!res.url.startsWith('node:')) {
|
|
455
|
+
infraUrls.add(res.url)
|
|
456
|
+
if (infraUrls.has(context.parentURL)) {
|
|
457
|
+
// Last-write-wins per specifier, like observeResolution: only the final target can be the
|
|
458
|
+
// one a cached instance pins.
|
|
459
|
+
nestedMap(infraEdges, context.parentURL).set(specifier, { url: res.url, context: { conditions: context.conditions, format: res.format, importAttributes: context.importAttributes } })
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
return res
|
|
463
|
+
}
|
|
464
|
+
if (entryUnresolved && !context.parentURL) entryUnresolved = false
|
|
465
|
+
|
|
381
466
|
if (isBuiltin(specifier)) {
|
|
382
467
|
const res = nextResolve(specifier)
|
|
383
468
|
assert.equal(res.url, specifier.startsWith('node:') ? specifier : `node:${specifier}`)
|
|
@@ -398,27 +483,25 @@ function resolve(specifier, context, nextResolve) {
|
|
|
398
483
|
initState(process.cwd())
|
|
399
484
|
}
|
|
400
485
|
|
|
401
|
-
if (state
|
|
486
|
+
if (state?.config.loadBundle) {
|
|
402
487
|
// nm scope defers non-nm parents to Node's resolver; gate on inNodeModules() to cover symlinks.
|
|
403
|
-
if (!state.config.full && !(parentURL && state.inNodeModules(parentURL)))
|
|
404
|
-
return nextResolve(specifier)
|
|
405
|
-
}
|
|
488
|
+
if (!state.config.full && !(parentURL && state.inNodeModules(parentURL))) return nextResolve(specifier)
|
|
406
489
|
// A bare specifier with a parent resolves from the recorded import map; otherwise skip
|
|
407
490
|
// nextResolve so the entry needn't be on disk.
|
|
408
491
|
if (parentURL && !specifier.startsWith('file:')) {
|
|
409
492
|
const { url, format } = state.getImport(parentURL, specifier, { conditions, importAttributes })
|
|
410
493
|
// Friendlier error at resolve time; the load gate is the load-bearing one.
|
|
411
|
-
if (format != null && !
|
|
494
|
+
if (format != null && !NODE_FORMATS.has(format)) refuseNonNodeFormat(format, url)
|
|
495
|
+
assertInfraMatchesBundle(url)
|
|
412
496
|
return { url, format, importAttributes: undefined, shortCircuit: true }
|
|
413
497
|
}
|
|
414
|
-
const url = specifier.startsWith('file:')
|
|
415
|
-
? specifier
|
|
416
|
-
: pathToFileURL(resolvePath(process.cwd(), specifier)).toString()
|
|
498
|
+
const url = specifier.startsWith('file:') ? specifier : pathToFileURL(resolvePath(process.cwd(), specifier)).toString()
|
|
417
499
|
// A forked child's main module isn't a declared CLI entry, so skip assertEntry (getFile still
|
|
418
500
|
// fails closed on anything unattested).
|
|
419
501
|
if (!parentURL && state.config.full && !forkedChild) state.assertEntry(url)
|
|
420
502
|
const format = state.getFormat(url)
|
|
421
|
-
if (format != null && !
|
|
503
|
+
if (format != null && !NODE_FORMATS.has(format)) refuseNonNodeFormat(format, url)
|
|
504
|
+
assertInfraMatchesBundle(url)
|
|
422
505
|
return { url, format, importAttributes: undefined, shortCircuit: true }
|
|
423
506
|
}
|
|
424
507
|
|
|
@@ -427,14 +510,23 @@ function resolve(specifier, context, nextResolve) {
|
|
|
427
510
|
|
|
428
511
|
assert.equal(res.importAttributes, undefined) // unsupported yet
|
|
429
512
|
if (parentURL) assert.ok(state)
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
513
|
+
// The app graph reached a module the preload phase already loaded: fold it (and transitively
|
|
514
|
+
// its own graph) into the capture, since its load hook can never re-fire.
|
|
515
|
+
if (infraUrls.has(url)) {
|
|
516
|
+
if (infraSources.has(url)) {
|
|
517
|
+
// The ENTRY itself was preloaded (a wrapper importing the app): init from its package root.
|
|
518
|
+
if (!state) initStateFromPackage(url)
|
|
519
|
+
const isEntry = !parentURL && entryUnseen
|
|
520
|
+
if (isEntry) entryUnseen = false
|
|
521
|
+
promoteInfraUrl(url, { isEntry })
|
|
522
|
+
} else {
|
|
523
|
+
// Resolved during the preload phase but never loaded: the app's own load will capture it.
|
|
524
|
+
infraUrls.delete(url)
|
|
436
525
|
}
|
|
437
526
|
}
|
|
527
|
+
// Parent-less = the entry: recorded via addFile/promotion above, never as an edge (addImport
|
|
528
|
+
// requires a parent, and state can exist here after an entry promotion).
|
|
529
|
+
if (state && parentURL) recording(() => state.addImport(parentURL, specifier, url, { conditions, format, importAttributes }))
|
|
438
530
|
return res
|
|
439
531
|
}
|
|
440
532
|
|
|
@@ -471,7 +563,10 @@ function patchCjsResolution() {
|
|
|
471
563
|
const parentURL = pathToFileURL(parent.filename).toString()
|
|
472
564
|
if (state.config.full || state.inNodeModules(parentURL)) {
|
|
473
565
|
const resolved = state.resolveBundled(parentURL, request)
|
|
474
|
-
if (resolved !== undefined)
|
|
566
|
+
if (resolved !== undefined) {
|
|
567
|
+
assertInfraMatchesBundle(pathToFileURL(resolved).toString())
|
|
568
|
+
return resolved
|
|
569
|
+
}
|
|
475
570
|
}
|
|
476
571
|
} else if (isAbsolute(request)) {
|
|
477
572
|
// NO parent, absolute request: Node's ESM<->CJS interop re-enters the CJS loader with hooks
|
|
@@ -480,27 +575,52 @@ function patchCjsResolution() {
|
|
|
480
575
|
// re-resolve here every commonjs-sync eval; the no-parent shape survives on >=24.18 too.
|
|
481
576
|
const url = pathToFileURL(request).toString()
|
|
482
577
|
if ((state.config.full || state.inNodeModules(url)) && state.hasFsFileContent(url)) {
|
|
578
|
+
assertInfraMatchesBundle(url)
|
|
483
579
|
return resolvePath(request)
|
|
484
580
|
}
|
|
485
581
|
}
|
|
486
582
|
}
|
|
487
583
|
const resolved = original.call(this, request, parent, ...rest)
|
|
488
584
|
// Capture: require.resolve() and some CJS require()s never fire the resolve hook.
|
|
489
|
-
if (state && !loadMode && typeof request === 'string'
|
|
490
|
-
&& !isBuiltin(request) && typeof parent?.filename === 'string') {
|
|
585
|
+
if (state && !loadMode && typeof request === 'string' && !isBuiltin(request) && typeof parent?.filename === 'string') {
|
|
491
586
|
state.observeResolution(pathToFileURL(parent.filename).toString(), request, pathToFileURL(resolved).toString())
|
|
492
587
|
}
|
|
493
588
|
return resolved
|
|
494
589
|
}
|
|
495
590
|
|
|
496
|
-
//
|
|
497
|
-
//
|
|
591
|
+
// Module._load's cache fast path can skip _resolveFilename, so a second require() of the same
|
|
592
|
+
// target goes unrecorded: force it through the PROPERTY (our shim) to observe the edge. This is
|
|
593
|
+
// also the one spot that sees every ACTUAL CJS execution, hook-served or not, so it anchors the
|
|
594
|
+
// executed-file reconciliation for transplanted require.extensions handlers (a transforming
|
|
595
|
+
// preload's CJS pipeline, e.g. `--import tsx` compiling .ts, reads and compiles files itself --
|
|
596
|
+
// the load hook chain never fires for them).
|
|
498
597
|
const originalLoad = Module._load
|
|
499
598
|
Module._load = function (request, parent, ...rest) {
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
599
|
+
let resolvedUrl
|
|
600
|
+
if (state && typeof request === 'string' && !isBuiltin(request) && typeof parent?.filename === 'string') {
|
|
601
|
+
let resolved
|
|
602
|
+
try { resolved = Module._resolveFilename(request, parent, ...rest) } catch { /* original _load raises the real error */ }
|
|
603
|
+
if (typeof resolved === 'string' && isAbsolute(resolved)) resolvedUrl = pathToFileURL(resolved).toString()
|
|
604
|
+
}
|
|
605
|
+
if (resolvedUrl !== undefined && !state.config.loadBundle) {
|
|
606
|
+
// A require() executes its target: remember it so write() can attest/verify anything the
|
|
607
|
+
// load hook never saw, and fold in a module the preload phase already executed.
|
|
608
|
+
state.observeExecution(resolvedUrl)
|
|
609
|
+
if (infraSources.has(resolvedUrl)) promoteInfraUrl(resolvedUrl)
|
|
610
|
+
else infraUrls.delete(resolvedUrl)
|
|
503
611
|
}
|
|
504
|
-
|
|
612
|
+
const result = originalLoad.call(this, request, parent, ...rest)
|
|
613
|
+
// Under --bundle=load, an attested source the load hook never served just executed from DISK
|
|
614
|
+
// (a transplanted require.extensions handler bypasses the hook chain): fail closed -- after
|
|
615
|
+
// the fact, but before anything can trust the run.
|
|
616
|
+
if (resolvedUrl !== undefined && state.config.loadBundle
|
|
617
|
+
&& !servedFromBundle.has(resolvedUrl) && state.isBundledSource(resolvedUrl)) {
|
|
618
|
+
throw new Error(
|
|
619
|
+
`[stasis] '${resolvedUrl}' executed from disk, bypassing the attested bundle -- a ` +
|
|
620
|
+
`require() pipeline transplanted by a preload (e.g. tsx compiling CJS TypeScript) ` +
|
|
621
|
+
`cannot serve bundle bytes and is refused under --bundle=load`
|
|
622
|
+
)
|
|
623
|
+
}
|
|
624
|
+
return result
|
|
505
625
|
}
|
|
506
626
|
}
|
package/src/host.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import * as fs from 'node:fs'
|
|
2
|
+
import { createRequire, findPackageJSON } from 'node:module'
|
|
3
|
+
import { pathToFileURL } from 'node:url'
|
|
4
|
+
|
|
5
|
+
// Snapshotted before `stasis run --fs` patches node:fs, whose realpathSync doesn't throw ENOENT and
|
|
6
|
+
// whose statSync answers with synthetic modes.
|
|
7
|
+
const { lstatSync, opendirSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync } = fs
|
|
8
|
+
|
|
9
|
+
export const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
|
|
10
|
+
|
|
11
|
+
let lastParent
|
|
12
|
+
let lastRequire
|
|
13
|
+
|
|
14
|
+
export const diskHost = {
|
|
15
|
+
stat(p) {
|
|
16
|
+
try {
|
|
17
|
+
return statSync(p, { throwIfNoEntry: false }) ?? null
|
|
18
|
+
} catch {
|
|
19
|
+
return null
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
readFile: (p) => readFileSync(p),
|
|
23
|
+
readdir: (p) => readdirSync(p, { withFileTypes: true }).toSorted(byName),
|
|
24
|
+
// In the filesystem's own order (readdirSync sorts; opendir doesn't).
|
|
25
|
+
readdirUnsorted(p) {
|
|
26
|
+
const entries = []
|
|
27
|
+
const handle = opendirSync(p)
|
|
28
|
+
try {
|
|
29
|
+
for (let e = handle.readSync(); e !== null; e = handle.readSync()) entries.push(e)
|
|
30
|
+
} finally {
|
|
31
|
+
handle.closeSync()
|
|
32
|
+
}
|
|
33
|
+
return entries
|
|
34
|
+
},
|
|
35
|
+
readlink: (p) => (lstatSync(p).isSymbolicLink() ? readlinkSync(p) : null),
|
|
36
|
+
realpath: (p) => realpathSync(p),
|
|
37
|
+
findPackageJSON: (p) => findPackageJSON(pathToFileURL(p).href),
|
|
38
|
+
resolve(parentFile, specifier, conditions) {
|
|
39
|
+
if (parentFile !== lastParent) {
|
|
40
|
+
lastRequire = createRequire(parentFile)
|
|
41
|
+
lastParent = parentFile
|
|
42
|
+
}
|
|
43
|
+
return lastRequire.resolve(specifier, { conditions })
|
|
44
|
+
},
|
|
45
|
+
}
|