@exodus/stasis-core 1.0.0-beta.12 → 1.0.0-beta.14
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 +9 -98
- package/package.json +4 -2
- package/src/add.js +68 -70
- package/src/artifact-util.js +48 -21
- package/src/brotli.js +23 -3
- package/src/bundle-util.js +65 -10
- package/src/bundle.js +14 -2
- package/src/cli.js +153 -0
- package/src/config.js +14 -4
- package/src/extract.js +148 -41
- package/src/fs.js +1 -19
- package/src/hooks.js +4 -3
- package/src/host.js +12 -1
- package/src/lockfile.js +15 -1
- package/src/state-util.js +26 -0
- package/src/state.js +155 -146
- package/src/util.js +48 -70
package/src/extract.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
-
import { dirname,
|
|
3
|
-
import { brotliDecompressSync } from 'node:zlib'
|
|
1
|
+
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, join, relative, resolve, sep } from 'node:path'
|
|
4
3
|
|
|
4
|
+
import { parseBundleBytes } from './brotli.js'
|
|
5
5
|
import { Bundle } from './bundle.js'
|
|
6
6
|
import { Lockfile } from './lockfile.js'
|
|
7
7
|
import { sha512integrity } from './state-util.js'
|
|
8
|
-
import { EXECUTE_BITS, canObserveExecuteBits, moduleFileKey,
|
|
8
|
+
import { EXECUTE_BITS, canObserveExecuteBits, moduleFileKey, moduleFileKeys, relativeEscapes } from './util.js'
|
|
9
9
|
|
|
10
10
|
const FILE_LOCK = 'stasis.lock.json'
|
|
11
|
+
const LOCK_MODES = new Set(['frozen', 'add', 'replace', 'ignore', 'none'])
|
|
11
12
|
|
|
12
13
|
// Buffer.from silently drops invalid chars, so a tampered `resource:base64` could hash-spoof; require a fixed point.
|
|
13
14
|
function assertCanonicalBase64(content, file) {
|
|
@@ -18,37 +19,94 @@ function assertCanonicalBase64(content, file) {
|
|
|
18
19
|
return buf
|
|
19
20
|
}
|
|
20
21
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
22
|
+
// Hashes the raw on-disk bytes, so decodes 'resource:base64' back first.
|
|
23
|
+
export const lockfileFromBundle = (bundle) => Lockfile.fromBundle(bundle, (file, content) =>
|
|
24
|
+
sha512integrity(bundle.formats.get(file) === 'resource:base64' ? assertCanonicalBase64(content, file) : content))
|
|
25
|
+
|
|
26
|
+
// Where two parsed JSON values first differ, as a path into them, or null when they are equal.
|
|
27
|
+
function firstDifference(bundle, lock, path = '') {
|
|
28
|
+
if (bundle === lock) return null
|
|
29
|
+
const nested = (x) => typeof x === 'object' && x !== null
|
|
30
|
+
if (!nested(bundle) || !nested(lock) || Array.isArray(bundle) !== Array.isArray(lock)) {
|
|
31
|
+
return `${path} ${bundle === undefined ? 'is only in the lockfile' : lock === undefined ? 'is only in the bundle' : 'differs'}`
|
|
32
|
+
}
|
|
33
|
+
// Own keys only: JSON.parse makes a `__proto__` file name an own property, never the prototype.
|
|
34
|
+
const own = (x, key) => (Object.hasOwn(x, key) ? x[key] : undefined)
|
|
35
|
+
for (const key of new Set([...Object.keys(bundle), ...Object.keys(lock)])) {
|
|
36
|
+
const diff = firstDifference(own(bundle, key), own(lock, key), `${path}[${Array.isArray(bundle) ? key : JSON.stringify(key)}]`)
|
|
37
|
+
if (diff) return diff
|
|
38
|
+
}
|
|
39
|
+
return null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function readLockfile(lockAbs) {
|
|
43
|
+
try {
|
|
44
|
+
return Lockfile.parse(readFileSync(lockAbs, 'utf-8'))
|
|
45
|
+
} catch (cause) {
|
|
46
|
+
throw new Error(`extract: not a valid stasis lockfile: ${lockAbs}`, { cause })
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// lock=frozen: the lockfile derived from the bundle must be the one in the output dir, every field of it --
|
|
51
|
+
// entries, packages, hashes, imports, formats and execute bits. Compared re-serialized, so formatting is free.
|
|
52
|
+
function assertLockfileMatches(lockAbs, derived) {
|
|
53
|
+
const diff = firstDifference(JSON.parse(derived.serialize()), JSON.parse(readLockfile(lockAbs).serialize()))
|
|
54
|
+
if (diff !== null) throw new Error(`extract: --lock=frozen: the bundle does not match ${lockAbs}: ${diff}`)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// lock=add: the derived lockfile is merged into the one in the output dir, which must agree with it on all
|
|
58
|
+
// both record -- Lockfile.merge refuses any other conflict -- so what is new is recorded and nothing recorded changes,
|
|
59
|
+
// save a payload-free stat:* record, which content of the same kind upgrades as a run's lock=add does.
|
|
60
|
+
function addToLockfile(lockAbs, derived) {
|
|
61
|
+
const lock = readLockfile(lockAbs)
|
|
62
|
+
let merged
|
|
63
|
+
try {
|
|
64
|
+
merged = lock.merge(derived)
|
|
65
|
+
} catch (cause) {
|
|
66
|
+
throw new Error(`extract: --lock=add: the bundle conflicts with ${lockAbs}: ${cause.message}`, { cause })
|
|
67
|
+
}
|
|
68
|
+
// merge lets the incoming side's execute bits win, which here would change a recorded one.
|
|
69
|
+
const recorded = moduleFileKeys(lock.modules, { scope: lock.config.scope })
|
|
70
|
+
for (const file of moduleFileKeys(derived.modules, { scope: derived.config.scope })) {
|
|
71
|
+
if (recorded.has(file) && lock.executable.has(file) !== derived.executable.has(file)) {
|
|
72
|
+
throw new Error(`extract: --lock=add: the bundle conflicts with ${lockAbs}: ${file}'s execute bit differs`)
|
|
29
73
|
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
74
|
+
}
|
|
75
|
+
return merged
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// A file's device and inode (as bigints: a number can round a large Windows file id), undefined when there's none.
|
|
79
|
+
function fileId(path) {
|
|
80
|
+
const stats = statSync(path, { throwIfNoEntry: false, bigint: true })
|
|
81
|
+
return stats && `${stats.dev}:${stats.ino}`
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Whether the bytes for `file` are already at `abs`, so it is left as it is; throws for anything else there. Extract
|
|
85
|
+
// never overwrites a file with other bytes, nor the bundle it reads, under its own name or another (a symlink, a hard link).
|
|
86
|
+
function alreadyInPlace(abs, file, content, bundleId) {
|
|
87
|
+
const stats = statSync(abs, { throwIfNoEntry: false, bigint: true })
|
|
88
|
+
if (stats === undefined) {
|
|
89
|
+
// A dangling symlink: the write would create its target, wherever that is.
|
|
90
|
+
if (lstatSync(abs, { throwIfNoEntry: false }) !== undefined) throw new Error(`extract: ${file} is a dangling symlink`)
|
|
91
|
+
return false
|
|
92
|
+
}
|
|
93
|
+
if (`${stats.dev}:${stats.ino}` === bundleId) throw new Error(`extract: ${file} is the bundle being extracted`)
|
|
94
|
+
if (!stats.isFile()) throw new Error(`extract: ${file} exists and is not a file`)
|
|
95
|
+
if (!readFileSync(abs).equals(Buffer.from(content))) throw new Error(`extract: ${file} exists with other content, which extract never overwrites`)
|
|
96
|
+
return true
|
|
42
97
|
}
|
|
43
98
|
|
|
44
|
-
export function extractCommand({ cwd = process.cwd(), bundleFile, output, logLabel = 'stasis-core' } = {}) {
|
|
99
|
+
export function extractCommand({ cwd = process.cwd(), bundleFile, output, lock: lockMode, logLabel = 'stasis-core' } = {}) {
|
|
45
100
|
if (!bundleFile) throw new Error('extract: a bundle file is required')
|
|
101
|
+
if (lockMode !== undefined && !LOCK_MODES.has(lockMode)) {
|
|
102
|
+
throw new Error(`extract: lock must be one of ${[...LOCK_MODES].join(', ')} (got ${JSON.stringify(lockMode)})`)
|
|
103
|
+
}
|
|
46
104
|
const bundleAbs = resolve(cwd, bundleFile)
|
|
47
105
|
if (!existsSync(bundleAbs)) throw new Error(`extract: bundle file not found: ${bundleAbs}`)
|
|
48
106
|
|
|
49
107
|
let bundle
|
|
50
108
|
try {
|
|
51
|
-
bundle =
|
|
109
|
+
bundle = parseBundleBytes(readFileSync(bundleAbs))
|
|
52
110
|
} catch (cause) {
|
|
53
111
|
// Bundle.parse throws message-less asserts; wrap so the user learns which file failed.
|
|
54
112
|
throw new Error(`extract: not a valid stasis bundle: ${bundleAbs}`, { cause })
|
|
@@ -60,6 +118,25 @@ export function extractCommand({ cwd = process.cwd(), bundleFile, output, logLab
|
|
|
60
118
|
const outDir = resolve(cwd, output ?? '.')
|
|
61
119
|
const outPrefix = outDir === sep ? outDir : `${outDir}${sep}`
|
|
62
120
|
const lockAbs = join(outDir, FILE_LOCK)
|
|
121
|
+
// A file (or a dangling symlink) there holds neither a lockfile nor room for the bundle's paths.
|
|
122
|
+
const outStats = statSync(outDir, { throwIfNoEntry: false })
|
|
123
|
+
if (outStats === undefined ? lstatSync(outDir, { throwIfNoEntry: false }) !== undefined : !outStats.isDirectory()) {
|
|
124
|
+
throw new Error(`extract: output dir ${outDir} is not a directory`)
|
|
125
|
+
}
|
|
126
|
+
// lstat, not existsSync: a dangling symlink there is a lockfile too, so the default fails closed on it.
|
|
127
|
+
const lockPresent = lstatSync(lockAbs, { throwIfNoEntry: false }) !== undefined
|
|
128
|
+
// Unset: assert the lockfile already in the output dir, else write none.
|
|
129
|
+
const lock = lockMode ?? (lockPresent ? 'frozen' : 'none')
|
|
130
|
+
const frozen = lock === 'frozen'
|
|
131
|
+
if (frozen && !lockPresent) throw new Error(`extract: --lock=frozen needs ${lockAbs}`)
|
|
132
|
+
if (lock === 'none' && lockPresent) {
|
|
133
|
+
throw new Error(`extract: unexpected ${lockAbs} with --lock=none (frozen checks the bundle against it, add merges the bundle into it, replace replaces it, ignore leaves it alone)`)
|
|
134
|
+
}
|
|
135
|
+
// ignore neither reads nor writes the lockfile; a v0 bundle derives none, so it has nothing to check against one, add or replace one with.
|
|
136
|
+
if (lockPresent && !withLockfile && lock !== 'ignore') {
|
|
137
|
+
throw new Error(`extract: a legacy v0 bundle can not ${{ frozen: 'be checked against', add: 'be added to', replace: 'replace' }[lock]} ${lockAbs}`)
|
|
138
|
+
}
|
|
139
|
+
const merging = lock === 'add' && lockPresent
|
|
63
140
|
|
|
64
141
|
// Plan-first: every target is validated inside outDir before any write; walk modules, not the last-wins
|
|
65
142
|
// `sources` getter. Containment is lexical -- symlinks are followed, so untrusted bundles need a fresh dir (doc/extract.md).
|
|
@@ -77,21 +154,19 @@ export function extractCommand({ cwd = process.cwd(), bundleFile, output, logLab
|
|
|
77
154
|
if (typeof content !== 'string') throw new Error(`extract: bundle file content is not a string: ${file}`)
|
|
78
155
|
const abs = resolve(outDir, file)
|
|
79
156
|
const relToOut = relative(outDir, abs)
|
|
80
|
-
//
|
|
81
|
-
if (
|
|
157
|
+
// relativeEscapes is `../`-aware, NOT a bare startsWith('..') -- that would reject a legit `..foo` filename.
|
|
158
|
+
if (relativeEscapes(relToOut) || !abs.startsWith(outPrefix)) {
|
|
82
159
|
throw new Error(`extract: bundle path escapes output dir: ${file}`)
|
|
83
160
|
}
|
|
84
161
|
// A non-canonical path changes under the resolve+relative round-trip; writing it desyncs tree from lockfile.
|
|
85
162
|
if (relToOut !== file) throw new Error(`extract: non-canonical bundle path: ${file}`)
|
|
163
|
+
// No bundle Bundle.parse takes carries a stasis.lock.json, so no write lands on the lockfile.
|
|
86
164
|
if (targets.has(abs)) throw new Error(`extract: duplicate bundle path: ${file}`)
|
|
87
|
-
if (withLockfile && abs === lockAbs) {
|
|
88
|
-
throw new Error(`extract: bundle contains ${FILE_LOCK}, which would collide with the derived lockfile`)
|
|
89
|
-
}
|
|
90
165
|
targets.add(abs)
|
|
91
166
|
// Executability rides the plan tuple, so the chmod can only ever reach a file we actually wrote.
|
|
92
167
|
const exec = bundle.executable.has(key)
|
|
93
168
|
if (exec) executables += 1
|
|
94
|
-
writes.push([abs, bundle.formats.get(key) === 'resource:base64' ? assertCanonicalBase64(content, file) : content, exec])
|
|
169
|
+
writes.push([abs, bundle.formats.get(key) === 'resource:base64' ? assertCanonicalBase64(content, file) : content, exec, file])
|
|
95
170
|
}
|
|
96
171
|
}
|
|
97
172
|
// A planned file must not also be a parent directory of another, else the writes throw halfway through.
|
|
@@ -102,10 +177,35 @@ export function extractCommand({ cwd = process.cwd(), bundleFile, output, logLab
|
|
|
102
177
|
}
|
|
103
178
|
}
|
|
104
179
|
}
|
|
105
|
-
|
|
180
|
+
// Only add and replace write a lockfile, and frozen checks one; each before the first write.
|
|
181
|
+
const writesLock = lock === 'add' || lock === 'replace'
|
|
182
|
+
const derived = withLockfile && (frozen || writesLock) ? lockfileFromBundle(bundle) : null
|
|
183
|
+
if (frozen) assertLockfileMatches(lockAbs, derived)
|
|
184
|
+
const lockText = derived === null || frozen ? null : (merging ? addToLockfile(lockAbs, derived) : derived).serialize()
|
|
185
|
+
|
|
186
|
+
// What is already on disk, checked whole before the first write too: each directory a write needs must be one (or
|
|
187
|
+
// missing), and each target missing or already holding its bytes. The lockfile, which --lock governs, is no
|
|
188
|
+
// exception to the bundle being off limits.
|
|
189
|
+
const bundleId = fileId(bundleAbs)
|
|
190
|
+
if (lockText !== null && fileId(lockAbs) === bundleId) throw new Error(`extract: ${FILE_LOCK} is the bundle being extracted`)
|
|
191
|
+
const checkedDirs = new Set()
|
|
192
|
+
const inPlace = new Set()
|
|
193
|
+
for (const [abs, content, , file] of writes) {
|
|
194
|
+
// Top-down, so a stat never runs into a file higher up (ENOTDIR); the first missing one ends the walk.
|
|
195
|
+
const dirs = []
|
|
196
|
+
for (let d = dirname(abs); d.length > outDir.length; d = dirname(d)) dirs.push(d)
|
|
197
|
+
for (const d of dirs.toReversed()) {
|
|
198
|
+
if (checkedDirs.has(d)) continue
|
|
199
|
+
const stats = statSync(d, { throwIfNoEntry: false })
|
|
200
|
+
if (stats === undefined && lstatSync(d, { throwIfNoEntry: false }) === undefined) break
|
|
201
|
+
if (!stats?.isDirectory()) throw new Error(`extract: ${relative(outDir, d) || '.'} is in the way of ${file}: not a directory`)
|
|
202
|
+
checkedDirs.add(d)
|
|
203
|
+
}
|
|
204
|
+
if (alreadyInPlace(abs, file, content, bundleId)) inPlace.add(abs)
|
|
205
|
+
}
|
|
106
206
|
|
|
107
207
|
// Only the execute bit is attested, so only it is touched -- rw bits stay as written (never widen a 0600 target)
|
|
108
|
-
// and setuid/setgid/sticky are cleared. Applied to every
|
|
208
|
+
// and setuid/setgid/sticky are cleared. Applied to every extracted file, one already in place too; skipped for v0, which attests no modes.
|
|
109
209
|
const withModes = withLockfile && canObserveExecuteBits()
|
|
110
210
|
let chmodFailures = 0
|
|
111
211
|
const applyMode = (abs, exec) => {
|
|
@@ -132,20 +232,27 @@ export function extractCommand({ cwd = process.cwd(), bundleFile, output, logLab
|
|
|
132
232
|
}
|
|
133
233
|
|
|
134
234
|
for (const [abs, content, exec] of writes) {
|
|
135
|
-
|
|
136
|
-
|
|
235
|
+
if (!inPlace.has(abs)) {
|
|
236
|
+
mkdirSync(dirname(abs), { recursive: true })
|
|
237
|
+
// Exclusive: a file that appeared since the check, or a second path a case-insensitive disk folds onto an
|
|
238
|
+
// earlier one, fails the write rather than being overwritten.
|
|
239
|
+
writeFileSync(abs, content, { flag: 'wx' })
|
|
240
|
+
}
|
|
137
241
|
if (withModes) applyMode(abs, exec)
|
|
138
242
|
}
|
|
139
243
|
mkdirSync(outDir, { recursive: true }) // for an empty bundle, where no write created it
|
|
140
|
-
if (
|
|
244
|
+
if (lockText !== null) writeFileSync(lockAbs, lockText)
|
|
141
245
|
|
|
142
|
-
const
|
|
143
|
-
|
|
246
|
+
const notes = [executables > 0 && `${executables} executable`, inPlace.size > 0 && `${inPlace.size} already in place`].filter(Boolean)
|
|
247
|
+
const execNote = notes.length > 0 ? ` (${notes.join(', ')})` : ''
|
|
248
|
+
const andLock = lockText !== null && !merging ? ` and ${FILE_LOCK}` : ''
|
|
249
|
+
const lockNote = frozen ? `, verified against ${FILE_LOCK}` : merging ? `, added to ${FILE_LOCK}` : ''
|
|
250
|
+
console.warn(`[${logLabel}] Extracted ${writes.length} file(s)${execNote}${andLock} to ${outDir}${lockNote}`)
|
|
144
251
|
if (chmodFailures > 0) {
|
|
145
252
|
console.warn(`[${logLabel}] Warning: could not set file modes on ${chmodFailures} file(s) (the filesystem may not support them); contents were written`)
|
|
146
253
|
}
|
|
147
|
-
if (!withLockfile) {
|
|
254
|
+
if (!withLockfile && writesLock) {
|
|
148
255
|
console.warn(`[${logLabel}] Warning: legacy v0 bundle records no package name/version, so ${FILE_LOCK} can not be restored and was not written`)
|
|
149
256
|
}
|
|
150
|
-
return { dir: outDir, files: writes.length, executable: executables }
|
|
257
|
+
return { dir: outDir, files: writes.length, executable: executables, inPlace: inPlace.size, lock }
|
|
151
258
|
}
|
package/src/fs.js
CHANGED
|
@@ -8,7 +8,7 @@ import { createRequire, syncBuiltinESMExports } from 'node:module'
|
|
|
8
8
|
import { resolve } from 'node:path'
|
|
9
9
|
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
10
10
|
|
|
11
|
-
import { realReadFileSync } from './state-util.js'
|
|
11
|
+
import { realContained, realReadFileSync } from './state-util.js'
|
|
12
12
|
import { isDotEnvFile, isPathWithin, isStasisArtifactName } from './util.js'
|
|
13
13
|
|
|
14
14
|
const require = createRequire(import.meta.url)
|
|
@@ -40,24 +40,6 @@ function toAbsPath(path) {
|
|
|
40
40
|
return null
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
let realRootCache
|
|
44
|
-
function realRootOf(root) {
|
|
45
|
-
if (realRootCache?.root !== root) {
|
|
46
|
-
let real
|
|
47
|
-
try { real = realRealpathSync(root) } catch { real = root }
|
|
48
|
-
realRootCache = { root, real }
|
|
49
|
-
}
|
|
50
|
-
return realRootCache.real
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// Capture-side containment: the path's REAL location must stay inside root's real path, else an
|
|
54
|
-
// in-tree symlink pointing OUT would pull external content into the signed bundle.
|
|
55
|
-
function realContained(root, abs) {
|
|
56
|
-
let real
|
|
57
|
-
try { real = realRealpathSync(abs) } catch { return false }
|
|
58
|
-
return isPathWithin(realRootOf(root), real)
|
|
59
|
-
}
|
|
60
|
-
|
|
61
43
|
// At the project root, drop stasis's own artifacts from the RECORDED listing so it doesn't depend on
|
|
62
44
|
// whether an earlier run left them behind; the program still receives the true on-disk `names`.
|
|
63
45
|
function dirCaptureNames(root, abs, names) {
|
package/src/hooks.js
CHANGED
|
@@ -8,6 +8,7 @@ import assert from 'node:assert/strict'
|
|
|
8
8
|
|
|
9
9
|
import { State } from './state.js'
|
|
10
10
|
import { installFsHooks } from './fs.js'
|
|
11
|
+
import { inScope } from './state-util.js'
|
|
11
12
|
import { NATIVE_BUILD_FORMATS, NODE_FORMATS, RESOURCE_FORMATS, SOURCE_LANGUAGE_FORMATS, STAT_FORMATS, erasedTypeScriptFormat, nestedMap } from './util.js'
|
|
12
13
|
|
|
13
14
|
// Snapshot off the namespace so `--fs` can't redirect stasis's own capture/shard reads.
|
|
@@ -368,7 +369,7 @@ function load(url, context, nextLoad) {
|
|
|
368
369
|
|
|
369
370
|
if (state?.config.loadBundle) {
|
|
370
371
|
// node_modules scope serves only nm deps; gate on inNodeModules(), not a raw substring (symlinks).
|
|
371
|
-
if (!state
|
|
372
|
+
if (!inScope(state, url)) return nextLoad(url, context)
|
|
372
373
|
const { source, format } = state.getFile(url)
|
|
373
374
|
// Cross-check format only when the resolve chain set it; the formats map is itself attested
|
|
374
375
|
// against the lockfile at construction. A transforming preload (`stasis run --import tsx`)
|
|
@@ -564,7 +565,7 @@ function patchCjsResolution() {
|
|
|
564
565
|
if (loadMode && typeof request === 'string' && !isBuiltin(request)) {
|
|
565
566
|
if (typeof parent?.filename === 'string') {
|
|
566
567
|
const parentURL = pathToFileURL(parent.filename).toString()
|
|
567
|
-
if (state
|
|
568
|
+
if (inScope(state, parentURL)) {
|
|
568
569
|
// Module._resolveFilename resolves for require(), whose target settles a divergent edge.
|
|
569
570
|
const resolved = state.resolveBundled(parentURL, request, { conditions: ['require'] })
|
|
570
571
|
if (resolved !== undefined) {
|
|
@@ -578,7 +579,7 @@ function patchCjsResolution() {
|
|
|
578
579
|
// record) keeps a listing or payload-free stat from hijacking resolution. Node 24.14-24.17
|
|
579
580
|
// re-resolve here every commonjs-sync eval; the no-parent shape survives on >=24.18 too.
|
|
580
581
|
const url = pathToFileURL(request).toString()
|
|
581
|
-
if ((state
|
|
582
|
+
if (inScope(state, url) && state.hasFsFileContent(url)) {
|
|
582
583
|
assertInfraMatchesBundle(url)
|
|
583
584
|
return resolvePath(request)
|
|
584
585
|
}
|
package/src/host.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import * as fs from 'node:fs'
|
|
2
2
|
import { createRequire, findPackageJSON } from 'node:module'
|
|
3
|
+
import { join, matchesGlob, relative } from 'node:path'
|
|
3
4
|
import { pathToFileURL } from 'node:url'
|
|
4
5
|
|
|
5
6
|
// Snapshotted before `stasis run --fs` patches node:fs, whose realpathSync doesn't throw ENOENT and
|
|
6
7
|
// whose statSync answers with synthetic modes.
|
|
7
|
-
const { lstatSync, opendirSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync } = fs
|
|
8
|
+
const { globSync, lstatSync, opendirSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync } = fs
|
|
8
9
|
|
|
9
10
|
export const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
|
|
10
11
|
|
|
@@ -34,6 +35,16 @@ export const diskHost = {
|
|
|
34
35
|
},
|
|
35
36
|
readlink: (p) => (lstatSync(p).isSymbolicLink() ? readlinkSync(p) : null),
|
|
36
37
|
realpath: (p) => realpathSync(p),
|
|
38
|
+
// fs.globSync's matches of `pattern` from `cwd`, as it spells them, never walking into a path
|
|
39
|
+
// `exclude` takes, given its absolute path (Node leaves one out where its `**` meets it alone).
|
|
40
|
+
// With `exclude`, the walk is over Dirents, which know their parent (Node hands its callback a
|
|
41
|
+
// bare name for a file otherwise), each match then spelled from `cwd`.
|
|
42
|
+
glob(pattern, { cwd, exclude } = {}) {
|
|
43
|
+
if (exclude === undefined) return globSync(pattern, { cwd })
|
|
44
|
+
const pathOf = (dirent) => join(dirent.parentPath, dirent.name)
|
|
45
|
+
return globSync(pattern, { cwd, withFileTypes: true, exclude: (dirent) => exclude(pathOf(dirent)) }).map((dirent) => relative(cwd, pathOf(dirent)))
|
|
46
|
+
},
|
|
47
|
+
matchesGlob,
|
|
37
48
|
findPackageJSON: (p) => findPackageJSON(pathToFileURL(p).href),
|
|
38
49
|
resolve(parentFile, specifier, conditions) {
|
|
39
50
|
if (parentFile !== lastParent) {
|
package/src/lockfile.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { assert, assertArtifactPath, duplicateKeyError, serializeExecutable, flatFileKeys, groupModules, hasNodeModulesSegment, mergeExecutableSets, mergeFormatMaps, mergeImportMaps, mergeModuleMaps, normalizeModule, parseEntries, parseExecutable, parseFormats, parseImports, serializeEntries, serializeFormats, serializeImports } from './artifact-util.js'
|
|
1
|
+
import { assert, assertArtifactPath, duplicateKeyError, serializeExecutable, flatFileKeys, groupModules, hasNodeModulesSegment, mergeExecutableSets, mergeFormatMaps, mergeImportMaps, mergeModuleMaps, moduleFileKey, moduleInfo, normalizeModule, parseEntries, parseExecutable, parseFormats, parseImports, serializeEntries, serializeFormats, serializeImports } from './artifact-util.js'
|
|
2
2
|
|
|
3
3
|
const VERSION = 0
|
|
4
4
|
|
|
@@ -33,6 +33,20 @@ export class Lockfile {
|
|
|
33
33
|
this.executable = executable ?? new Set()
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
// The companion lockfile of `bundle`: its shape, each file's content swapped for its integrity,
|
|
37
|
+
// `integrityOf(file, content)` of its project-relative path. Imports and formats carry across, else
|
|
38
|
+
// the lockfile is bytes-only and a frozen run skips those cross-checks; the file set is the bundle's,
|
|
39
|
+
// so its executable list attests it as-is.
|
|
40
|
+
static fromBundle(bundle, integrityOf) {
|
|
41
|
+
const modules = new Map()
|
|
42
|
+
for (const [dir, m] of bundle.modules) {
|
|
43
|
+
const files = Object.create(null)
|
|
44
|
+
for (const [rel, content] of Object.entries(m.files)) files[rel] = integrityOf(moduleFileKey(dir, rel), content)
|
|
45
|
+
modules.set(dir, moduleInfo({ ...m, files }))
|
|
46
|
+
}
|
|
47
|
+
return new Lockfile({ config: bundle.config, entries: bundle.entries, modules, imports: bundle.imports, formats: bundle.formats, executable: bundle.executable })
|
|
48
|
+
}
|
|
49
|
+
|
|
36
50
|
static parse(text) {
|
|
37
51
|
const json = JSON.parse(text)
|
|
38
52
|
assert(json.version === VERSION)
|
package/src/state-util.js
CHANGED
|
@@ -2,8 +2,10 @@ import assert from 'node:assert/strict'
|
|
|
2
2
|
import { hash } from 'node:crypto'
|
|
3
3
|
import * as fs from 'node:fs'
|
|
4
4
|
import { join, resolve, sep } from 'node:path'
|
|
5
|
+
import { pathToFileURL } from 'node:url'
|
|
5
6
|
|
|
6
7
|
import { diskHost } from './host.js'
|
|
8
|
+
import { isPathWithin } from './util.js'
|
|
7
9
|
|
|
8
10
|
// Genuine fs readers snapshotted off the namespace before any --fs patch. A plain `import { readFileSync }`
|
|
9
11
|
// won't do: --fs monkey-patches fs then syncBuiltinESMExports() rebinds named imports, so snapshotting dodges that.
|
|
@@ -11,6 +13,21 @@ export const realReadFileSync = fs.readFileSync
|
|
|
11
13
|
export const realReadFile = fs.promises.readFile
|
|
12
14
|
export const realReaddirSync = fs.readdirSync
|
|
13
15
|
export const realExistsSync = fs.existsSync
|
|
16
|
+
const realRealpathSync = fs.realpathSync
|
|
17
|
+
|
|
18
|
+
let realRootCache
|
|
19
|
+
// Capture-side containment: the REAL location of `abs` must stay inside `root`'s real path (`root`
|
|
20
|
+
// itself where that has none), else an in-tree symlink pointing OUT would pull external content in.
|
|
21
|
+
export function realContained(root, abs) {
|
|
22
|
+
if (realRootCache?.root !== root) {
|
|
23
|
+
let real
|
|
24
|
+
try { real = realRealpathSync(root) } catch { real = root }
|
|
25
|
+
realRootCache = { root, real }
|
|
26
|
+
}
|
|
27
|
+
let real
|
|
28
|
+
try { real = realRealpathSync(abs) } catch { return false }
|
|
29
|
+
return isPathWithin(realRootCache.real, real)
|
|
30
|
+
}
|
|
14
31
|
|
|
15
32
|
assert.equal(sep, '/', 'Not tested on Windows')
|
|
16
33
|
|
|
@@ -44,3 +61,12 @@ export function canonicalizePath(p, host = diskHost) {
|
|
|
44
61
|
return abs
|
|
45
62
|
}
|
|
46
63
|
}
|
|
64
|
+
|
|
65
|
+
// Whether `url` is in `state`'s scope, as it attests one: anywhere under scope=full, else in
|
|
66
|
+
// node_modules. Over State's public members alone, so a plugin may ask it of a State another
|
|
67
|
+
// stasis-core copy made (State.preload).
|
|
68
|
+
export const inScope = (state, url) => state.config.full || state.inNodeModules(url)
|
|
69
|
+
|
|
70
|
+
// Whether the file at `absolute` is one `state`'s bundle serves under load: within its root (outside
|
|
71
|
+
// it: system files, scratch, read from disk) and in its scope. Over State's public members, as inScope.
|
|
72
|
+
export const servedByBundle = (state, absolute) => isPathWithin(state.root, absolute) && inScope(state, pathToFileURL(absolute).toString())
|