strutvane 0.1.0-next.0 → 0.2.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +81 -11
- package/dist/bin.mjs +762 -12
- package/dist/bin.mjs.map +1 -1
- package/package.json +47 -14
- package/dist/bin.d.mts +0 -1
- package/dist/launcher-BrUi5a5_.mjs +0 -371
- package/dist/launcher-BrUi5a5_.mjs.map +0 -1
- package/dist/launcher.d.mts +0 -103
- package/dist/launcher.d.mts.map +0 -1
- package/dist/launcher.mjs +0 -1
package/dist/bin.mjs
CHANGED
|
@@ -1,30 +1,780 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
2
|
+
import { lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { constants, homedir, tmpdir } from "node:os";
|
|
4
|
+
import { dirname, isAbsolute, join, posix, relative, resolve, win32 } from "node:path";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
// src/boundary.ts
|
|
8
|
+
/**
|
|
9
|
+
* Which folders may ever be treated as a Strutvane project.
|
|
10
|
+
*
|
|
11
|
+
* Treating a folder as the project means running code from it (`strut.js`, or the framework in
|
|
12
|
+
* its `node_modules`). So, walking up from the working directory, the search stops (with no
|
|
13
|
+
* project) at a folder that:
|
|
14
|
+
* - is a file-system or drive root,
|
|
15
|
+
* - is the OS temp directory itself,
|
|
16
|
+
* - is above the user's home directory,
|
|
17
|
+
* because anyone able to write there (other users, an extracted archive) could otherwise plant a
|
|
18
|
+
* project that applies to every folder below it. On POSIX the project folder must also belong to
|
|
19
|
+
* the current user.
|
|
20
|
+
*
|
|
21
|
+
* These are the same rules as `@strutvane/framework`'s `console/project/boundary.ts`. This
|
|
22
|
+
* package has no dependencies (it must work before anything is installed), so the rules are
|
|
23
|
+
* mirrored here rather than imported. Keep the two in step.
|
|
24
|
+
*
|
|
25
|
+
* @module
|
|
26
|
+
*/
|
|
27
|
+
/**
|
|
28
|
+
* The boundary facts of this process.
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* isForbiddenProjectDir('/tmp', processBoundary()) // true
|
|
32
|
+
*/
|
|
33
|
+
function processBoundary() {
|
|
34
|
+
return {
|
|
35
|
+
home: homedir(),
|
|
36
|
+
temp: tmpdir(),
|
|
37
|
+
uid: typeof process.getuid === "function" ? process.getuid() : void 0
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** Every spelling of a path worth comparing: as given, and with links resolved. */
|
|
41
|
+
function spellings(path) {
|
|
42
|
+
const out = [resolve(path)];
|
|
43
|
+
try {
|
|
44
|
+
out.push(realpathSync.native(path));
|
|
45
|
+
} catch {}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
/** Path equality; case-insensitive on Windows and macOS, whose file systems usually are. */
|
|
49
|
+
function samePath(a, b) {
|
|
50
|
+
const fold = process.platform === "win32" || process.platform === "darwin";
|
|
51
|
+
const norm = (p) => fold ? resolve(p).toLowerCase() : resolve(p);
|
|
52
|
+
return norm(a) === norm(b);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Whether `child` is `parent` itself or lies inside it. Both should already be real paths (links
|
|
56
|
+
* resolved), or a link inside `parent` could point anywhere.
|
|
57
|
+
*
|
|
58
|
+
* Why not `startsWith`: `/srv/app-evil` starts with `/srv/app`. `path.relative` compares whole
|
|
59
|
+
* segments, and on Windows it ignores case and reports another drive as an absolute path.
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* isInside('/srv/app', '/srv/app/strut.js') // true
|
|
63
|
+
* isInside('/srv/app', '/srv/app-evil/strut.js') // false
|
|
64
|
+
*/
|
|
65
|
+
function isInside(parent, child) {
|
|
66
|
+
const rel = relative(parent, child);
|
|
67
|
+
if (rel === "") return true;
|
|
68
|
+
if (isAbsolute(rel)) return false;
|
|
69
|
+
return rel.split(/[\\/]/)[0] !== "..";
|
|
70
|
+
}
|
|
71
|
+
/** Whether `ancestor` is a strict ancestor of `path`. */
|
|
72
|
+
function isStrictAncestor(ancestor, path) {
|
|
73
|
+
return !samePath(ancestor, path) && isInside(ancestor, path);
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* A file-system or drive root, the temp directory itself, or a folder above home: never a
|
|
77
|
+
* project, and the upward search stops there.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* isForbiddenProjectDir('C:\\', facts) // true
|
|
81
|
+
*/
|
|
82
|
+
function isForbiddenProjectDir(dir, facts) {
|
|
83
|
+
for (const d of spellings(dir)) {
|
|
84
|
+
if (dirname(d) === d) return true;
|
|
85
|
+
for (const temp of spellings(facts.temp)) if (samePath(d, temp)) return true;
|
|
86
|
+
for (const home of spellings(facts.home)) if (isStrictAncestor(d, home)) return true;
|
|
87
|
+
}
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* POSIX only: whether `dir` belongs to the current user (always `true` without a uid, i.e. on
|
|
92
|
+
* Windows). A missing folder is not owned by anyone: `false`.
|
|
93
|
+
*/
|
|
94
|
+
function isOwnedByCurrentUser(dir, facts) {
|
|
95
|
+
if (facts.uid === void 0) return true;
|
|
96
|
+
try {
|
|
97
|
+
return statSync(dir).uid === facts.uid;
|
|
98
|
+
} catch {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
// src/child.ts
|
|
103
|
+
/**
|
|
104
|
+
* Running the project's script as a child process, and passing its result back.
|
|
105
|
+
*
|
|
106
|
+
* - **No shell, ever.** The program is the running Node (`process.execPath`) and the arguments go
|
|
107
|
+
* in an array, so `a&b`, `$(x)`, `; rm -rf ~` or `%PATH%` reach `strut.js` as plain text on
|
|
108
|
+
* every platform. Arguments come after the script path, so `--import=x.mjs` or `--require x`
|
|
109
|
+
* are the script's arguments, never Node options.
|
|
110
|
+
* - **Exit codes** come back unchanged. When the child is killed by a signal, the caller re-raises
|
|
111
|
+
* that signal on itself (see `bin.ts`), so a parent shell or CI sees what really happened;
|
|
112
|
+
* where that is not possible (Windows) the exit code is the shell convention 128 + signal.
|
|
113
|
+
* - **Signals** sent to this process are forwarded to the child, so `kill <pid>` or a supervisor
|
|
114
|
+
* stopping the guard stops the command too, and the guard never exits before the child: see
|
|
115
|
+
* {@link shouldForward} for which ones and why.
|
|
116
|
+
*
|
|
117
|
+
* @module
|
|
118
|
+
*/
|
|
119
|
+
/** Signals the guard listens for while a child runs. */
|
|
120
|
+
const HANDLED_SIGNALS = Object.freeze([
|
|
121
|
+
"SIGINT",
|
|
122
|
+
"SIGTERM",
|
|
123
|
+
"SIGHUP",
|
|
124
|
+
"SIGBREAK"
|
|
125
|
+
]);
|
|
126
|
+
/**
|
|
127
|
+
* Whether a signal received by the guard is passed on to the child.
|
|
128
|
+
*
|
|
129
|
+
* - **Windows: never.** A console Ctrl+C or Ctrl+Break already reaches every process attached to
|
|
130
|
+
* the console, the child included, and "sending" a signal to a Windows process terminates it
|
|
131
|
+
* outright, which would deny `strut.js` its own clean-up. The guard only keeps a listener so it
|
|
132
|
+
* is not the one to die first.
|
|
133
|
+
* - **Ctrl+C at a terminal (POSIX, `SIGINT` with stdin a TTY): not forwarded.** The terminal
|
|
134
|
+
* sends it to the whole foreground process group, so the child already has it; a second copy
|
|
135
|
+
* can turn "stop gracefully" into "force quit" in commands that count presses (a dev server).
|
|
136
|
+
* - **Everything else is forwarded** (`SIGTERM`, `SIGHUP`, and `SIGINT` without a terminal, e.g.
|
|
137
|
+
* from a supervisor or `kill -INT`), since only the guard received it.
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* shouldForward('SIGTERM', 'linux', true) // true
|
|
141
|
+
* shouldForward('SIGINT', 'linux', true) // false
|
|
142
|
+
*/
|
|
143
|
+
function shouldForward(signal, platform, stdinIsTTY) {
|
|
144
|
+
if (platform === "win32") return false;
|
|
145
|
+
if (signal === "SIGINT" && stdinIsTTY) return false;
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
/** The exit code that stands for death by `signal` (128 + its number; 1 when unknown). */
|
|
149
|
+
function signalExitCode(signal) {
|
|
150
|
+
const number = constants.signals[signal];
|
|
151
|
+
return typeof number === "number" ? 128 + number : 1;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Run `node <script> <args...>` with no shell, forward signals while it runs, and resolve with
|
|
155
|
+
* how it ended. Never rejects: a child that cannot start resolves as `{ kind: 'error' }`.
|
|
156
|
+
*
|
|
157
|
+
* @example
|
|
158
|
+
* await runChild({ execPath: process.execPath, script: '/srv/blog/strut.js', args: ['migrate'], ... })
|
|
159
|
+
* // { kind: 'exit', code: 0 }
|
|
160
|
+
*/
|
|
161
|
+
const runChild = (request) => new Promise((resolvePromise) => {
|
|
162
|
+
const signals = request.signals ?? process;
|
|
163
|
+
let settled = false;
|
|
164
|
+
const child = spawn(request.execPath, [request.script, ...request.args], {
|
|
165
|
+
cwd: request.cwd,
|
|
166
|
+
env: request.env,
|
|
167
|
+
stdio: request.stdio ?? "inherit",
|
|
168
|
+
shell: false,
|
|
169
|
+
windowsHide: true
|
|
170
|
+
});
|
|
171
|
+
const onSignal = (signal) => {
|
|
172
|
+
if (child.exitCode !== null || child.signalCode !== null) return;
|
|
173
|
+
if (shouldForward(signal, request.platform, request.stdinIsTTY)) child.kill(signal);
|
|
174
|
+
};
|
|
175
|
+
for (const signal of HANDLED_SIGNALS) signals.on(signal, onSignal);
|
|
176
|
+
const finish = (outcome) => {
|
|
177
|
+
if (settled) return;
|
|
178
|
+
settled = true;
|
|
179
|
+
for (const signal of HANDLED_SIGNALS) signals.off(signal, onSignal);
|
|
180
|
+
resolvePromise(outcome);
|
|
181
|
+
};
|
|
182
|
+
child.once("error", (error) => finish({
|
|
183
|
+
kind: "error",
|
|
184
|
+
message: error.message
|
|
185
|
+
}));
|
|
186
|
+
child.once("exit", (code, signal) => {
|
|
187
|
+
if (signal !== null) finish({
|
|
188
|
+
kind: "signal",
|
|
189
|
+
signal
|
|
190
|
+
});
|
|
191
|
+
else finish({
|
|
192
|
+
kind: "exit",
|
|
193
|
+
code: code ?? 1
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
// src/messages.ts
|
|
198
|
+
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g;
|
|
199
|
+
/**
|
|
200
|
+
* Text from outside the guard (a path, an argument, a version from a file it does not control),
|
|
201
|
+
* made safe for a terminal: control characters (ANSI escapes, line breaks) removed and the length
|
|
202
|
+
* capped, so a crafted folder or argument can't rewrite the screen or fake a message.
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* printable('a\u001b[2Jb') // 'a[2Jb'
|
|
206
|
+
*/
|
|
207
|
+
function printable(text, max = 200) {
|
|
208
|
+
const clean = text.replace(CONTROL, "");
|
|
209
|
+
return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* The dist-tag to name in `npm create strutvane@<tag>`: `next` while this package is a
|
|
213
|
+
* pre-release (before 1.0 the core train is published under `next`, decision #128), `latest`
|
|
214
|
+
* otherwise. The same rule as create-strutvane's `releaseTag()`.
|
|
215
|
+
*
|
|
216
|
+
* @example
|
|
217
|
+
* releaseTag('0.2.0-next.0') // 'next'
|
|
218
|
+
* releaseTag('1.0.0') // 'latest'
|
|
219
|
+
*/
|
|
220
|
+
function releaseTag(version) {
|
|
221
|
+
return version.includes("-") ? "next" : "latest";
|
|
222
|
+
}
|
|
223
|
+
/** `npm create strutvane@<tag> <name>`, the one command that makes a project. */
|
|
224
|
+
function createCommand(version, name = "my-app") {
|
|
225
|
+
return `npm create strutvane@${releaseTag(version)} ${name}`;
|
|
226
|
+
}
|
|
227
|
+
/** A project name worth echoing back in a suggestion (otherwise the placeholder is shown). */
|
|
228
|
+
const SIMPLE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
|
|
229
|
+
/** Commands people type to make a new project. */
|
|
230
|
+
const CREATE_WORDS = /* @__PURE__ */ new Set([
|
|
231
|
+
"new",
|
|
232
|
+
"create",
|
|
233
|
+
"init"
|
|
234
|
+
]);
|
|
235
|
+
/** `strutvane <version>`. */
|
|
236
|
+
function versionText(version) {
|
|
237
|
+
return `strutvane ${printable(version, 64)}`;
|
|
238
|
+
}
|
|
239
|
+
/** What `npx strutvane` does, and how to make a project. Printed for `help` outside a project. */
|
|
240
|
+
function helpText(version, start) {
|
|
241
|
+
return [
|
|
242
|
+
`${versionText(version)}: run Strutvane project commands with npx.`,
|
|
243
|
+
"",
|
|
244
|
+
`No Strutvane project was found in ${printable(start)} or the folders above it.`,
|
|
245
|
+
"",
|
|
246
|
+
"Create a new app:",
|
|
247
|
+
` ${createCommand(version)}`,
|
|
248
|
+
"",
|
|
249
|
+
"Inside a project, `npx strutvane <command>` runs exactly what `node strut <command>` runs,",
|
|
250
|
+
"with the project's own @strutvane/framework (try `node strut list` there). A project is a",
|
|
251
|
+
"folder whose package.json lists @strutvane/framework.",
|
|
252
|
+
"",
|
|
253
|
+
"This command never installs or downloads anything."
|
|
254
|
+
].join("\n");
|
|
255
|
+
}
|
|
256
|
+
/** A project command was typed outside a project. */
|
|
257
|
+
function noProjectText(version, command, start) {
|
|
258
|
+
return [
|
|
259
|
+
`strutvane: "${printable(command, 60)}" needs a Strutvane project, and none was found in ${printable(start)}`,
|
|
260
|
+
" or the folders above it (a project is a folder whose package.json lists",
|
|
261
|
+
" @strutvane/framework; the search never goes above your home folder).",
|
|
262
|
+
"",
|
|
263
|
+
` Create one with: ${createCommand(version)}`,
|
|
264
|
+
" Then run commands inside it: node strut list"
|
|
265
|
+
].join("\n");
|
|
266
|
+
}
|
|
267
|
+
/** `new`, `create` or `init` was typed: point to the installer instead of running anything. */
|
|
268
|
+
function createText(version, name) {
|
|
269
|
+
return [
|
|
270
|
+
"strutvane: new projects are made by the installer, which asks how you want the app set up:",
|
|
271
|
+
"",
|
|
272
|
+
` ${createCommand(version, name !== void 0 && SIMPLE_NAME.test(name) ? name : "<name>")}`
|
|
273
|
+
].join("\n");
|
|
274
|
+
}
|
|
275
|
+
/** A candidate project folder was found but is not trusted. */
|
|
276
|
+
function untrustedText(dir, reason) {
|
|
277
|
+
const where = printable(dir);
|
|
278
|
+
if (reason === "not-owned") return [`strutvane: ${where} looks like a Strutvane project, but it belongs to another user.`, " Refusing to run code from it. Run the command as the folder owner, or fix its ownership."].join("\n");
|
|
279
|
+
return [
|
|
280
|
+
`strutvane: ${where} has a strut.js, but its package.json does not list @strutvane/framework,`,
|
|
281
|
+
" so it is not a Strutvane project and its strut.js was not run.",
|
|
282
|
+
" If it is your project, add the framework (npm install @strutvane/framework) and try again;",
|
|
283
|
+
" otherwise run the command from your project folder."
|
|
284
|
+
].join("\n");
|
|
285
|
+
}
|
|
286
|
+
/** Why a trusted project still can't be run, and the fix. */
|
|
287
|
+
function refusalText(reason, path, realPath) {
|
|
288
|
+
const where = printable(path);
|
|
289
|
+
switch (reason) {
|
|
290
|
+
case "root-unreadable": return `strutvane: the project folder ${where} can no longer be read. Check it exists and try again.`;
|
|
291
|
+
case "root-is-link": return [`strutvane: the project folder ${where} is a link${realPath === void 0 ? "" : ` to ${printable(realPath)}`}.`, " Refusing to run code through a link: open the real folder and run the command there."].join("\n");
|
|
292
|
+
case "strut-not-file": return [`strutvane: ${where} is a link or not a regular file, so it was not run.`, " Restore strut.js from git (or from a new project made with npm create strutvane)."].join("\n");
|
|
293
|
+
case "strut-outside-root": return `strutvane: ${where} really lives outside the project folder, so it was not run.`;
|
|
294
|
+
case "framework-missing": return [`strutvane: the project's dependencies are not installed (${where} is missing).`, " Run: npm install (or npm run setup in a project made by create-strutvane)"].join("\n");
|
|
295
|
+
case "framework-outside-root": return [`strutvane: ${where} points outside the project folder (a link or junction), so it was not run.`, " Install the framework into the project instead: npm install"].join("\n");
|
|
296
|
+
case "framework-invalid": return [`strutvane: ${where} is not a usable @strutvane/framework (wrong name, or no safe "strutvane" program).`, " Reinstall it: npm install"].join("\n");
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/** The guard was started again by the project it started (a `strut.js` calling `npx strutvane`). */
|
|
300
|
+
function loopText() {
|
|
301
|
+
return ["strutvane: npx strutvane was started again from inside the command it ran, so it stopped", " instead of looping. Call `node strut` (not `npx strutvane`) from strut.js and project scripts."].join("\n");
|
|
302
|
+
}
|
|
303
|
+
/** Node is older than the minimum. */
|
|
304
|
+
function nodeTooOldText(found, minimum) {
|
|
305
|
+
return [`strutvane: Node.js ${printable(found, 32)} is too old; Strutvane needs Node.js ${minimum} or newer.`, " Install a current LTS from https://nodejs.org and try again."].join("\n");
|
|
306
|
+
}
|
|
307
|
+
/** The child could not be started at all. */
|
|
308
|
+
function startFailedText(script, message) {
|
|
309
|
+
return `strutvane: could not start ${printable(script)}: ${printable(message)}`;
|
|
310
|
+
}
|
|
311
|
+
// src/manifest.ts
|
|
312
|
+
/**
|
|
313
|
+
* Reading `package.json` files the guard does not control.
|
|
314
|
+
*
|
|
315
|
+
* Every manifest read here is untrusted input (it may be in a folder someone else wrote), so the
|
|
316
|
+
* reader is lenient (any problem means "no manifest") and bounded (a huge file is not read).
|
|
317
|
+
* Nothing in a manifest is ever executed; it only decides what is trusted.
|
|
318
|
+
*
|
|
319
|
+
* @module
|
|
320
|
+
*/
|
|
321
|
+
/** The package that marks a Strutvane project, and whose `strutvane` program runs commands. */
|
|
322
|
+
const FRAMEWORK_PACKAGE = "@strutvane/framework";
|
|
323
|
+
/**
|
|
324
|
+
* Read a JSON object file. Returns `undefined` when it is missing, not a regular file, larger than
|
|
325
|
+
* {@link MAX_MANIFEST_BYTES}, not valid JSON, or not an object.
|
|
326
|
+
*
|
|
327
|
+
* @example
|
|
328
|
+
* readJsonObject('/srv/app/package.json')?.['name'] // 'my-app'
|
|
329
|
+
*/
|
|
330
|
+
function readJsonObject(path) {
|
|
331
|
+
try {
|
|
332
|
+
const stats = statSync(path);
|
|
333
|
+
if (!stats.isFile() || stats.size > 1048576) return void 0;
|
|
334
|
+
const text = readFileSync(path, "utf8");
|
|
335
|
+
const parsed = JSON.parse(text.charCodeAt(0) === 65279 ? text.slice(1) : text);
|
|
336
|
+
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : void 0;
|
|
337
|
+
} catch {
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
/** `<dir>/package.json`, read with {@link readJsonObject}. */
|
|
342
|
+
function readManifest(dir) {
|
|
343
|
+
return readJsonObject(join(dir, "package.json"));
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Whether a manifest lists `@strutvane/framework` in `dependencies` or `devDependencies` (as an
|
|
347
|
+
* own property with a string range). That is what makes a folder a Strutvane project.
|
|
348
|
+
*
|
|
349
|
+
* Why only those two fields: an optional or peer dependency is not installed for the app itself,
|
|
350
|
+
* and the framework's own project detection uses the same two.
|
|
351
|
+
*
|
|
352
|
+
* @example
|
|
353
|
+
* declaresFramework({ dependencies: { '@strutvane/framework': '^0.2.0-next.0' } }) // true
|
|
354
|
+
*/
|
|
355
|
+
function declaresFramework(manifest) {
|
|
356
|
+
if (manifest === void 0) return false;
|
|
357
|
+
return ["dependencies", "devDependencies"].some((field) => {
|
|
358
|
+
const deps = manifest[field];
|
|
359
|
+
return typeof deps === "object" && deps !== null && !Array.isArray(deps) && Object.hasOwn(deps, "@strutvane/framework") && typeof deps["@strutvane/framework"] === "string";
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
// src/project.ts
|
|
5
363
|
/**
|
|
6
|
-
*
|
|
364
|
+
* Finding the Strutvane project for a working directory.
|
|
365
|
+
*
|
|
366
|
+
* From the working directory upwards, the **nearest** folder that holds a `strut.js` or whose
|
|
367
|
+
* package.json lists `@strutvane/framework` is the candidate, and the search ends there (an
|
|
368
|
+
* ancestor further up is never considered, so a project can't be hijacked from above). The
|
|
369
|
+
* candidate is trusted only when:
|
|
370
|
+
* - its package.json lists `@strutvane/framework` (a `strut.js` on its own is not enough: anyone
|
|
371
|
+
* can drop a file called `strut.js` into a folder);
|
|
372
|
+
* - it passes the boundary rules of `boundary.ts` (never a root, the temp directory or a folder
|
|
373
|
+
* above home; owned by the current user on POSIX).
|
|
374
|
+
*
|
|
375
|
+
* Only files are read here; nothing is run.
|
|
7
376
|
*
|
|
8
377
|
* @module
|
|
9
378
|
*/
|
|
10
|
-
|
|
379
|
+
/** The file that `node strut` runs, in the project root. */
|
|
380
|
+
const STRUT_FILE = "strut.js";
|
|
381
|
+
/** Whether `path` exists in any form (a file, a folder, a link, even a broken link). */
|
|
382
|
+
function exists(path) {
|
|
11
383
|
try {
|
|
12
|
-
|
|
13
|
-
return
|
|
384
|
+
lstatSync(path);
|
|
385
|
+
return true;
|
|
14
386
|
} catch {
|
|
15
|
-
return
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Find the project for `start` (see the module documentation for the rules).
|
|
392
|
+
*
|
|
393
|
+
* @example
|
|
394
|
+
* findProject('/home/ana/blog/app/models', facts) // { kind: 'project', root: '/home/ana/blog' }
|
|
395
|
+
*/
|
|
396
|
+
function findProject(start, facts) {
|
|
397
|
+
const from = resolve(start);
|
|
398
|
+
let dir = from;
|
|
399
|
+
for (;;) {
|
|
400
|
+
if (isForbiddenProjectDir(dir, facts)) return {
|
|
401
|
+
kind: "none",
|
|
402
|
+
start: from
|
|
403
|
+
};
|
|
404
|
+
const declares = declaresFramework(readManifest(dir));
|
|
405
|
+
if (declares || exists(join(dir, "strut.js"))) {
|
|
406
|
+
if (!declares) return {
|
|
407
|
+
kind: "untrusted",
|
|
408
|
+
dir,
|
|
409
|
+
reason: "strut-without-framework"
|
|
410
|
+
};
|
|
411
|
+
if (!isOwnedByCurrentUser(dir, facts)) return {
|
|
412
|
+
kind: "untrusted",
|
|
413
|
+
dir,
|
|
414
|
+
reason: "not-owned"
|
|
415
|
+
};
|
|
416
|
+
return {
|
|
417
|
+
kind: "project",
|
|
418
|
+
root: dir
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
const parent = dirname(dir);
|
|
422
|
+
if (parent === dir) return {
|
|
423
|
+
kind: "none",
|
|
424
|
+
start: from
|
|
425
|
+
};
|
|
426
|
+
dir = parent;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
// src/target.ts
|
|
430
|
+
/**
|
|
431
|
+
* What to run for a trusted project root, and the checks that keep it inside that root.
|
|
432
|
+
*
|
|
433
|
+
* `node strut <args>` runs the project's `strut.js`. So the guard runs that same file, with the
|
|
434
|
+
* same Node, when it is there. Without a `strut.js` (a project made by hand, or one whose
|
|
435
|
+
* `strut.js` was deleted) it runs what `strut.js` would run for a framework command: the
|
|
436
|
+
* `strutvane` program of the project's own installed `@strutvane/framework`. Never a second copy,
|
|
437
|
+
* and never anything fetched.
|
|
438
|
+
*
|
|
439
|
+
* Every path is checked on its **real** location (links resolved), and must stay inside the
|
|
440
|
+
* project root:
|
|
441
|
+
* - the root itself must not be a link (a link can make an innocent-looking folder run code from
|
|
442
|
+
* anywhere); the user is told the real folder to open instead;
|
|
443
|
+
* - `strut.js` must be a regular file, not a link;
|
|
444
|
+
* - `node_modules/@strutvane/framework` must really be inside the root (an `npm link` or a
|
|
445
|
+
* planted junction pointing elsewhere is refused), must be named `@strutvane/framework`, and its
|
|
446
|
+
* `bin` must be a plain relative `.js`/`.mjs`/`.cjs` path that stays inside the package.
|
|
447
|
+
*
|
|
448
|
+
* The file that runs is handed to Node by its real path, so what was checked is what runs.
|
|
449
|
+
*
|
|
450
|
+
* @module
|
|
451
|
+
*/
|
|
452
|
+
/** The name of the framework's program in its package.json `bin`. */
|
|
453
|
+
const FRAMEWORK_BIN = "strutvane";
|
|
454
|
+
/** Scripts the guard may hand to Node. */
|
|
455
|
+
const SCRIPT_EXTENSION = /\.[cm]?js$/;
|
|
456
|
+
/**
|
|
457
|
+
* Whether a package.json `bin` value is a plain relative path to a script: not empty, no NUL, not
|
|
458
|
+
* absolute on any platform (`/x`, `C:\x`, `\\server\share\x`), not drive-relative (`C:x`), no `..`
|
|
459
|
+
* segment, and ending in `.js`, `.mjs` or `.cjs`.
|
|
460
|
+
*
|
|
461
|
+
* Why so strict: the value comes from a file inside `node_modules`, and becomes a path Node runs.
|
|
462
|
+
*
|
|
463
|
+
* @example
|
|
464
|
+
* isSafeBinPath('dist/console/bin.mjs') // true
|
|
465
|
+
* isSafeBinPath('..\\..\\evil.js') // false
|
|
466
|
+
*/
|
|
467
|
+
function isSafeBinPath(bin) {
|
|
468
|
+
if (bin === "" || bin.length > 512 || bin.includes("\0")) return false;
|
|
469
|
+
if (posix.isAbsolute(bin) || win32.isAbsolute(bin) || /^[A-Za-z]:/.test(bin)) return false;
|
|
470
|
+
if (bin.split(/[\\/]/).includes("..")) return false;
|
|
471
|
+
return SCRIPT_EXTENSION.test(bin);
|
|
472
|
+
}
|
|
473
|
+
/** The `strutvane` entry of a manifest's `bin` (a string `bin` counts as the package's only one). */
|
|
474
|
+
function frameworkBin(manifest) {
|
|
475
|
+
const bin = manifest["bin"];
|
|
476
|
+
if (typeof bin === "string") return bin;
|
|
477
|
+
if (typeof bin !== "object" || bin === null || Array.isArray(bin)) return void 0;
|
|
478
|
+
if (!Object.hasOwn(bin, "strutvane")) return void 0;
|
|
479
|
+
const entry = bin[FRAMEWORK_BIN];
|
|
480
|
+
return typeof entry === "string" ? entry : void 0;
|
|
481
|
+
}
|
|
482
|
+
/** `lstat`, or `undefined` when the path does not exist (or cannot be read). */
|
|
483
|
+
function lstatOrUndefined(path) {
|
|
484
|
+
try {
|
|
485
|
+
return lstatSync(path);
|
|
486
|
+
} catch {
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/** The real path, or `undefined` when it cannot be resolved (missing, broken link, no access). */
|
|
491
|
+
function realOrUndefined(path) {
|
|
492
|
+
try {
|
|
493
|
+
return realpathSync.native(path);
|
|
494
|
+
} catch {
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
/**
|
|
499
|
+
* Decide what to run for the trusted project root `root` (see the module documentation).
|
|
500
|
+
*
|
|
501
|
+
* @example
|
|
502
|
+
* resolveTarget('/srv/blog') // { kind: 'run', root: '/srv/blog', script: '/srv/blog/strut.js', via: 'strut.js' }
|
|
503
|
+
*/
|
|
504
|
+
function resolveTarget(root) {
|
|
505
|
+
const rootStats = lstatOrUndefined(root);
|
|
506
|
+
const realRoot = realOrUndefined(root);
|
|
507
|
+
if (rootStats === void 0 || realRoot === void 0) return {
|
|
508
|
+
kind: "refused",
|
|
509
|
+
reason: "root-unreadable",
|
|
510
|
+
path: root
|
|
511
|
+
};
|
|
512
|
+
if (rootStats.isSymbolicLink()) return {
|
|
513
|
+
kind: "refused",
|
|
514
|
+
reason: "root-is-link",
|
|
515
|
+
path: root,
|
|
516
|
+
realPath: realRoot
|
|
517
|
+
};
|
|
518
|
+
const strut = join(root, STRUT_FILE);
|
|
519
|
+
const strutStats = lstatOrUndefined(strut);
|
|
520
|
+
if (strutStats !== void 0) {
|
|
521
|
+
if (strutStats.isSymbolicLink() || !strutStats.isFile()) return {
|
|
522
|
+
kind: "refused",
|
|
523
|
+
reason: "strut-not-file",
|
|
524
|
+
path: strut
|
|
525
|
+
};
|
|
526
|
+
const real = realOrUndefined(strut);
|
|
527
|
+
if (real === void 0 || !isInside(realRoot, real)) return {
|
|
528
|
+
kind: "refused",
|
|
529
|
+
reason: "strut-outside-root",
|
|
530
|
+
path: strut
|
|
531
|
+
};
|
|
532
|
+
return {
|
|
533
|
+
kind: "run",
|
|
534
|
+
root,
|
|
535
|
+
script: real,
|
|
536
|
+
via: "strut.js"
|
|
537
|
+
};
|
|
538
|
+
}
|
|
539
|
+
return frameworkTarget(root, realRoot);
|
|
540
|
+
}
|
|
541
|
+
/** The framework's own `strutvane` program, for a project without `strut.js`. */
|
|
542
|
+
function frameworkTarget(root, realRoot) {
|
|
543
|
+
const dir = join(root, "node_modules", ...FRAMEWORK_PACKAGE.split("/"));
|
|
544
|
+
if (lstatOrUndefined(dir) === void 0) return {
|
|
545
|
+
kind: "refused",
|
|
546
|
+
reason: "framework-missing",
|
|
547
|
+
path: dir
|
|
548
|
+
};
|
|
549
|
+
const realDir = realOrUndefined(dir);
|
|
550
|
+
if (realDir === void 0 || !isInside(realRoot, realDir)) return {
|
|
551
|
+
kind: "refused",
|
|
552
|
+
reason: "framework-outside-root",
|
|
553
|
+
path: dir
|
|
554
|
+
};
|
|
555
|
+
const manifest = readJsonObject(join(realDir, "package.json"));
|
|
556
|
+
const bin = manifest === void 0 ? void 0 : frameworkBin(manifest);
|
|
557
|
+
if (manifest?.["name"] !== "@strutvane/framework" || bin === void 0 || !isSafeBinPath(bin)) return {
|
|
558
|
+
kind: "refused",
|
|
559
|
+
reason: "framework-invalid",
|
|
560
|
+
path: dir
|
|
561
|
+
};
|
|
562
|
+
const real = realOrUndefined(resolve(realDir, bin));
|
|
563
|
+
if (real === void 0 || !isInside(realDir, real) || !isRegularFile(real)) return {
|
|
564
|
+
kind: "refused",
|
|
565
|
+
reason: "framework-invalid",
|
|
566
|
+
path: dir
|
|
567
|
+
};
|
|
568
|
+
return {
|
|
569
|
+
kind: "run",
|
|
570
|
+
root,
|
|
571
|
+
script: real,
|
|
572
|
+
via: "framework"
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/** Whether `path` is a regular file (following links). */
|
|
576
|
+
function isRegularFile(path) {
|
|
577
|
+
try {
|
|
578
|
+
return statSync(path).isFile();
|
|
579
|
+
} catch {
|
|
580
|
+
return false;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
// src/version.ts
|
|
584
|
+
/**
|
|
585
|
+
* This package's own version, and the Node.js versions it supports.
|
|
586
|
+
*
|
|
587
|
+
* @module
|
|
588
|
+
*/
|
|
589
|
+
/** The oldest Node.js the guard (and the framework it starts) supports: package.json `engines`. */
|
|
590
|
+
const MIN_NODE = "24.3.0";
|
|
591
|
+
/**
|
|
592
|
+
* This package's version, read from its own package.json (one folder up from both `src/` and
|
|
593
|
+
* `dist/`), so it can never drift from what was published. `0.0.0` if it cannot be read.
|
|
594
|
+
*
|
|
595
|
+
* @example
|
|
596
|
+
* ownVersion() // '0.2.0-next.0'
|
|
597
|
+
*/
|
|
598
|
+
function ownVersion(manifestUrl = new URL("../package.json", import.meta.url)) {
|
|
599
|
+
const version = readJsonObject(fileURLToPath(manifestUrl))?.["version"];
|
|
600
|
+
return typeof version === "string" ? version : "0.0.0";
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Whether `version` (`process.versions.node`, e.g. `24.3.0`) is at least `minimum`. Anything that
|
|
604
|
+
* is not `major.minor.patch` counts as too old (fail closed).
|
|
605
|
+
*
|
|
606
|
+
* @example
|
|
607
|
+
* isNodeSupported('24.3.0', '24.3.0') // true
|
|
608
|
+
* isNodeSupported('22.12.0', '24.3.0') // false
|
|
609
|
+
*/
|
|
610
|
+
function isNodeSupported(version, minimum = MIN_NODE) {
|
|
611
|
+
const parse = (v) => {
|
|
612
|
+
const match = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
|
|
613
|
+
return match === null ? void 0 : [
|
|
614
|
+
Number(match[1]),
|
|
615
|
+
Number(match[2]),
|
|
616
|
+
Number(match[3])
|
|
617
|
+
];
|
|
618
|
+
};
|
|
619
|
+
const have = parse(version);
|
|
620
|
+
const need = parse(minimum);
|
|
621
|
+
if (have === void 0 || need === void 0) return false;
|
|
622
|
+
for (let i = 0; i < 3; i++) {
|
|
623
|
+
const a = have[i] ?? 0;
|
|
624
|
+
const b = need[i] ?? 0;
|
|
625
|
+
if (a !== b) return a > b;
|
|
16
626
|
}
|
|
627
|
+
return true;
|
|
628
|
+
}
|
|
629
|
+
// src/main.ts
|
|
630
|
+
/**
|
|
631
|
+
* `npx strutvane <args>`: the whole decision, with every process fact injected so it can be
|
|
632
|
+
* tested without touching the real process.
|
|
633
|
+
*
|
|
634
|
+
* 1. Node older than {@link MIN_NODE}: say so, exit 1.
|
|
635
|
+
* 2. Started again by the command it started (`STRUTVANE_NPX_DEPTH`): stop, exit 1, no loop.
|
|
636
|
+
* 3. Find the project (`project.ts`) and what to run in it (`target.ts`).
|
|
637
|
+
* - Found and trusted: run it with the user's arguments exactly as typed, and hand back its
|
|
638
|
+
* exit code or signal. Every argument goes to the project, `--version` and `help` included,
|
|
639
|
+
* because that is what `node strut` does.
|
|
640
|
+
* - Found but untrusted or refused: say why and how to fix it, exit 1. Nothing runs.
|
|
641
|
+
* - Not found: `help` / `--help` / no command prints help (exit 0), `--version` prints this
|
|
642
|
+
* package's version (exit 0), `new` / `create` / `init` prints the installer command, and
|
|
643
|
+
* anything else explains that it needs a project. Those last two exit 2: nothing was done.
|
|
644
|
+
*
|
|
645
|
+
* Nothing is ever installed or downloaded; outside a project the guard only prints.
|
|
646
|
+
*
|
|
647
|
+
* @module
|
|
648
|
+
*/
|
|
649
|
+
/** Exit codes of the guard itself (the project's own codes pass through unchanged). */
|
|
650
|
+
const EXIT = Object.freeze({
|
|
651
|
+
OK: 0,
|
|
652
|
+
/** Refused to run (untrusted folder, link, missing or invalid framework, loop, old Node). */
|
|
653
|
+
FAILURE: 1,
|
|
654
|
+
/** Outside a project: the command needs one (or is `new`), so nothing was done. */
|
|
655
|
+
USAGE: 2
|
|
656
|
+
});
|
|
657
|
+
/** Counts how deep `npx strutvane` is nested inside itself (guards against loops). */
|
|
658
|
+
const DEPTH_ENV = "STRUTVANE_NPX_DEPTH";
|
|
659
|
+
/** Flags that ask for this package's version outside a project. */
|
|
660
|
+
const VERSION_FLAGS = /* @__PURE__ */ new Set([
|
|
661
|
+
"--version",
|
|
662
|
+
"-v",
|
|
663
|
+
"-V"
|
|
664
|
+
]);
|
|
665
|
+
/** Words and flags that ask for help outside a project. */
|
|
666
|
+
const HELP_WORDS = /* @__PURE__ */ new Set([
|
|
667
|
+
"help",
|
|
668
|
+
"--help",
|
|
669
|
+
"-h"
|
|
670
|
+
]);
|
|
671
|
+
/**
|
|
672
|
+
* The child's environment: the user's, plus the nesting depth and, on Windows,
|
|
673
|
+
* `NoDefaultCurrentDirectoryInExePath`, so a `.cmd` the project starts through cmd.exe can't pick
|
|
674
|
+
* up a program planted in the working directory before PATH.
|
|
675
|
+
*/
|
|
676
|
+
function childEnvironment(env, platform, depth) {
|
|
677
|
+
return {
|
|
678
|
+
...env,
|
|
679
|
+
...platform === "win32" ? { NoDefaultCurrentDirectoryInExePath: "1" } : {},
|
|
680
|
+
[DEPTH_ENV]: String(depth + 1)
|
|
681
|
+
};
|
|
17
682
|
}
|
|
18
|
-
|
|
683
|
+
/** The nesting depth from the environment (anything unexpected counts as 0). */
|
|
684
|
+
function depthOf(env) {
|
|
685
|
+
const value = env[DEPTH_ENV];
|
|
686
|
+
return value !== void 0 && /^\d{1,3}$/.test(value) ? Number(value) : 0;
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Run the guard for `argv` (the arguments after `strutvane`). Never throws for expected
|
|
690
|
+
* situations; returns how to end.
|
|
691
|
+
*
|
|
692
|
+
* @example
|
|
693
|
+
* await main(['migrate'], environment) // { exitCode: 0 } after `node strut migrate` succeeded
|
|
694
|
+
*/
|
|
695
|
+
async function main(argv, env) {
|
|
696
|
+
if (!isNodeSupported(env.nodeVersion)) {
|
|
697
|
+
env.stderr(nodeTooOldText(env.nodeVersion, MIN_NODE));
|
|
698
|
+
return { exitCode: EXIT.FAILURE };
|
|
699
|
+
}
|
|
700
|
+
const depth = depthOf(env.env);
|
|
701
|
+
if (depth >= 1) {
|
|
702
|
+
env.stderr(loopText());
|
|
703
|
+
return { exitCode: EXIT.FAILURE };
|
|
704
|
+
}
|
|
705
|
+
const search = findProject(env.cwd, env.boundary ?? processBoundary());
|
|
706
|
+
if (search.kind === "untrusted") {
|
|
707
|
+
env.stderr(untrustedText(search.dir, search.reason));
|
|
708
|
+
return { exitCode: EXIT.FAILURE };
|
|
709
|
+
}
|
|
710
|
+
if (search.kind === "none") return outside(argv, search.start, env);
|
|
711
|
+
const target = resolveTarget(search.root);
|
|
712
|
+
if (target.kind === "refused") {
|
|
713
|
+
env.stderr(refusalText(target.reason, target.path, target.realPath));
|
|
714
|
+
return { exitCode: EXIT.FAILURE };
|
|
715
|
+
}
|
|
716
|
+
const outcome = await (env.run ?? runChild)({
|
|
717
|
+
execPath: env.execPath,
|
|
718
|
+
script: target.script,
|
|
719
|
+
args: argv,
|
|
720
|
+
cwd: target.root,
|
|
721
|
+
env: childEnvironment(env.env, env.platform, depth),
|
|
722
|
+
platform: env.platform,
|
|
723
|
+
stdinIsTTY: env.stdinIsTTY
|
|
724
|
+
});
|
|
725
|
+
switch (outcome.kind) {
|
|
726
|
+
case "exit": return { exitCode: outcome.code };
|
|
727
|
+
case "signal": return {
|
|
728
|
+
signal: outcome.signal,
|
|
729
|
+
exitCode: signalExitCode(outcome.signal)
|
|
730
|
+
};
|
|
731
|
+
case "error":
|
|
732
|
+
env.stderr(startFailedText(target.script, outcome.message));
|
|
733
|
+
return { exitCode: EXIT.FAILURE };
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
/** Outside a project: only print (help, version, the installer command, or why not). */
|
|
737
|
+
function outside(argv, start, env) {
|
|
738
|
+
const [first, second] = argv;
|
|
739
|
+
if (first === void 0 || HELP_WORDS.has(first)) {
|
|
740
|
+
env.stdout(helpText(env.version, start));
|
|
741
|
+
return { exitCode: EXIT.OK };
|
|
742
|
+
}
|
|
743
|
+
if (VERSION_FLAGS.has(first)) {
|
|
744
|
+
env.stdout(versionText(env.version));
|
|
745
|
+
return { exitCode: EXIT.OK };
|
|
746
|
+
}
|
|
747
|
+
if (CREATE_WORDS.has(first)) {
|
|
748
|
+
env.stderr(createText(env.version, second));
|
|
749
|
+
return { exitCode: EXIT.USAGE };
|
|
750
|
+
}
|
|
751
|
+
env.stderr(noProjectText(env.version, first, start));
|
|
752
|
+
return { exitCode: EXIT.USAGE };
|
|
753
|
+
}
|
|
754
|
+
// src/bin.ts
|
|
755
|
+
/**
|
|
756
|
+
* The `strutvane` executable (`npx strutvane <command>`). All decisions live in `main.ts`
|
|
757
|
+
* (tested); this file only connects them to the real process: arguments, output, the exit code,
|
|
758
|
+
* and re-raising a signal the child died of.
|
|
759
|
+
*
|
|
760
|
+
* It is the one file in this package allowed to print with `console` (package.json
|
|
761
|
+
* `strutvane.allowConsole`).
|
|
762
|
+
*
|
|
763
|
+
* @module
|
|
764
|
+
*/
|
|
765
|
+
const outcome = await main(process.argv.slice(2), {
|
|
19
766
|
cwd: process.cwd(),
|
|
20
767
|
env: process.env,
|
|
21
768
|
execPath: process.execPath,
|
|
22
769
|
platform: process.platform,
|
|
770
|
+
nodeVersion: process.versions.node,
|
|
23
771
|
version: ownVersion(),
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
772
|
+
stdinIsTTY: process.stdin.isTTY === true,
|
|
773
|
+
stdout: (text) => console.log(text),
|
|
774
|
+
stderr: (text) => console.error(text)
|
|
27
775
|
});
|
|
776
|
+
process.exitCode = outcome.exitCode;
|
|
777
|
+
if ("signal" in outcome && process.platform !== "win32") process.kill(process.pid, outcome.signal);
|
|
28
778
|
export {};
|
|
29
779
|
|
|
30
780
|
//# sourceMappingURL=bin.mjs.map
|