@rulecad/cad 0.9.0 → 0.10.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/AGENTS.md +21 -6
- package/CHANGELOG.md +320 -0
- package/EXAMPLES.md +22 -17
- package/README.md +192 -40
- package/bin/cad.mjs +465 -80
- package/lib/assembly.mjs +68 -33
- package/lib/cache-file.mjs +105 -0
- package/lib/code-text.mjs +28 -0
- package/lib/design-imports.mjs +127 -0
- package/lib/design.mjs +251 -55
- package/lib/designshapes.mjs +142 -0
- package/lib/edit.mjs +24 -2
- package/lib/estimates.mjs +51 -0
- package/lib/fasten.mjs +11 -5
- package/lib/fe-key.mjs +29 -0
- package/lib/fittings.mjs +20 -15
- package/lib/fixings.mjs +17 -4
- package/lib/framebuild.mjs +1 -1
- package/lib/framegen.mjs +9 -1
- package/lib/frames.mjs +6 -2
- package/lib/framesize.mjs +8 -81
- package/lib/host.mjs +7 -3
- package/lib/kit.mjs +5 -5
- package/lib/list.mjs +29 -21
- package/lib/loads.mjs +35 -23
- package/lib/measured.mjs +738 -98
- package/lib/motors.mjs +9 -29
- package/lib/names.mjs +15 -0
- package/lib/optimise.mjs +34 -25
- package/lib/order.mjs +4 -10
- package/lib/parts.mjs +3 -0
- package/lib/rules.mjs +2 -1
- package/lib/sandbox-hooks.mjs +109 -15
- package/lib/sandbox-lock.mjs +225 -0
- package/lib/sandbox-preload.mjs +2 -2
- package/lib/sandbox-run.mjs +22 -24
- package/lib/sandbox.mjs +173 -30
- package/lib/sheet.mjs +114 -3
- package/lib/versions.mjs +195 -32
- package/lib/workspace.mjs +3 -2
- package/package.json +11 -11
- package/schemas/assembly.schema.json +1 -1
- package/schemas/project.schema.json +6 -0
- package/templates/coupons/MEASURE.md +109 -0
- package/templates/coupons/assemblies/fixings-test.json +20 -0
- package/templates/coupons/assemblies/slot-test.json +11 -0
- package/templates/coupons/objects/fixings-coupon.js +88 -0
- package/templates/coupons/objects/fixings-coupon.json +26 -0
- package/templates/coupons/objects/holds-coupon.js +130 -0
- package/templates/coupons/objects/holds-coupon.json +42 -0
- package/templates/coupons/objects/slot-coupon.js +89 -0
- package/templates/coupons/objects/slot-coupon.json +29 -0
- package/templates/coupons/project.json +10 -0
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// What the sandbox's runner (sandbox-run.mjs) shuts before the design loads, on top of the import hook
|
|
2
|
+
// (sandbox-hooks.mjs): the ways to Node's own modules, to the network and to files that don't go through an import.
|
|
3
|
+
// The hook keeps every import and require() to the design's own files and the allowed packages, and refuses a
|
|
4
|
+
// CommonJS file of the project outright; what is here holds whatever way the design finds round it.
|
|
5
|
+
// - The CommonJS loader (Module._load, which require(), module.require, createRequire and the loader's own functions
|
|
6
|
+
// all go through) gives no module of Node's that reaches the network, another program or a worker to anyone (the
|
|
7
|
+
// hook's QUIET list holds the rest), and refuses the rest to the design's code: to any call that comes from a file
|
|
8
|
+
// of its project, or from no file at all, by the call's own stack (no parent module it names is believed). No hook
|
|
9
|
+
// can be added past the sandbox's (module.register, module.registerHooks).
|
|
10
|
+
// - process loses its own ways to Node's modules and internals (getBuiltinModule, binding, dlopen), to other
|
|
11
|
+
// processes (kill, execve), and to files (loadEnvFile); and process.exit, the runner's, ends the process.
|
|
12
|
+
// - A pipe's stream (process.stdout, stderr, stdin) is a socket, and a socket's class connects anywhere (before Node
|
|
13
|
+
// 25, whose permission model shuts the network: no --allow-net). So the runner reads and writes its file
|
|
14
|
+
// descriptors itself, and process.stdout, stderr and stdin and the console are plain streams that pass on what is
|
|
15
|
+
// written. (Node 22.13 to 22.14 makes process.stdout itself for its hooks' worker, before the runner starts: the
|
|
16
|
+
// design is given the plain one all the same.)
|
|
17
|
+
// test/sandbox-loader.test.mjs tries each of these, and the other ways round, on the Node it runs on.
|
|
18
|
+
import Module, { isBuiltin } from 'node:module';
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
import { fileURLToPath } from 'node:url';
|
|
22
|
+
import { quiet } from './sandbox-hooks.mjs';
|
|
23
|
+
import { Writable } from 'node:stream';
|
|
24
|
+
import { Console } from 'node:console';
|
|
25
|
+
|
|
26
|
+
const deny = (what, why) => Object.assign(new Error(`designs can't ${what}: ${why}`), { code: 'design.sandbox' });
|
|
27
|
+
|
|
28
|
+
const shut = (o, k, value) => Object.defineProperty(o, k, { value, writable: false, configurable: false });
|
|
29
|
+
|
|
30
|
+
// The code that asks the CommonJS loader for a module: the first frame of the call's stack that is none of Node's own
|
|
31
|
+
// (node:…), by its file (a path, or a file: URL for an ES module), or null where it has none (code made by eval or
|
|
32
|
+
// new Function, or a call from no code at all: a callback queued straight onto the loader). Read with this module's
|
|
33
|
+
// own way of reading a stack, which Error.prepareStackTrace and Error itself are fixed to (lockStacks), and with the
|
|
34
|
+
// functions it calls taken before the design runs (a design may change String.prototype.startsWith for everyone;
|
|
35
|
+
// a stack frame's own functions can't be changed), so the code asking can't dress it up.
|
|
36
|
+
const call = Reflect.apply,
|
|
37
|
+
startsWith = String.prototype.startsWith,
|
|
38
|
+
isArray = Array.isArray,
|
|
39
|
+
isAbsolute = path.isAbsolute;
|
|
40
|
+
let reading = false;
|
|
41
|
+
const asker = () => {
|
|
42
|
+
const limit = Error.stackTraceLimit;
|
|
43
|
+
reading = true;
|
|
44
|
+
try {
|
|
45
|
+
Error.stackTraceLimit = 64;
|
|
46
|
+
const frames = /** @type {any} */ (new Error().stack);
|
|
47
|
+
if (!isArray(frames)) return null;
|
|
48
|
+
for (let i = 2; i < frames.length; i++) {
|
|
49
|
+
// (past asker itself and the loader's lock that called it)
|
|
50
|
+
const f = frames[i],
|
|
51
|
+
file = f.getFileName();
|
|
52
|
+
if (typeof file === 'string' && call(startsWith, file, ['node:'])) continue;
|
|
53
|
+
if (f.isEval() || typeof file !== 'string') return null;
|
|
54
|
+
return call(startsWith, file, ['file:']) || isAbsolute(file) ? file : null;
|
|
55
|
+
}
|
|
56
|
+
return null;
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
} finally {
|
|
60
|
+
reading = false;
|
|
61
|
+
try {
|
|
62
|
+
Error.stackTraceLimit = limit;
|
|
63
|
+
} catch {
|
|
64
|
+
/* as it was */
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
// Error.prepareStackTrace as anyone may set it, but while asker reads a stack, when it is asker's; and Error itself,
|
|
69
|
+
// which Node reads prepareStackTrace from, kept as it is
|
|
70
|
+
function lockStacks() {
|
|
71
|
+
let theirs = Error.prepareStackTrace;
|
|
72
|
+
const ours = (e, frames) => frames;
|
|
73
|
+
Object.defineProperty(Error, 'prepareStackTrace', {
|
|
74
|
+
get: () => (reading ? ours : theirs),
|
|
75
|
+
set: (f) => {
|
|
76
|
+
theirs = f;
|
|
77
|
+
},
|
|
78
|
+
configurable: false,
|
|
79
|
+
});
|
|
80
|
+
shut(globalThis, 'Error', Error);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Shut the CommonJS loader to Node's own modules for the design's code, and take away the ways to add an import hook.
|
|
85
|
+
* Of Node's modules only the quiet ones (QUIET in sandbox-hooks.mjs: no network, programs or workers) are given at
|
|
86
|
+
* all, to anyone: the tool's packages still load those as they run (Manifold's loader asks for fs and path each time
|
|
87
|
+
* a lamina makes one), where the code asking is a file outside the design's project, and never to code with no file
|
|
88
|
+
* (eval, new Function, a callback queued onto the loader itself). That a call comes from the tool's code is read from
|
|
89
|
+
* its stack, which a design that has the loader to hand can still arrange (a tool's function it gives the loader to as
|
|
90
|
+
* a callback, a module it compiles under a tool's file name): so the quiet modules' reads rest on Node's permission
|
|
91
|
+
* model, which keeps them to the folders the sandbox may read, and the network on the list alone.
|
|
92
|
+
* @param {string} project the design's project, a file: URL ending in a slash
|
|
93
|
+
*/
|
|
94
|
+
export function shutLoader(project) {
|
|
95
|
+
lockStacks();
|
|
96
|
+
const load = Module._load,
|
|
97
|
+
// (the project as a file: URL and as a path, as a stack names an ES module's file and a CommonJS one's)
|
|
98
|
+
projectPath = project ? fileURLToPath(project) : '';
|
|
99
|
+
shut(Module, '_load', function _load(request, ...rest) {
|
|
100
|
+
if (typeof request !== 'string') throw deny('load that', 'a module is named by its name');
|
|
101
|
+
if (isBuiltin(request)) {
|
|
102
|
+
if (!quiet(request))
|
|
103
|
+
throw deny(
|
|
104
|
+
`load "${request}"`,
|
|
105
|
+
"in the sandbox none of Node's own modules that reach the network, other programs or workers is loaded",
|
|
106
|
+
);
|
|
107
|
+
const from = asker();
|
|
108
|
+
if (!from || !project || call(startsWith, from, [project]) || call(startsWith, from, [projectPath]))
|
|
109
|
+
throw deny(
|
|
110
|
+
`load "${request}"`,
|
|
111
|
+
"a design only makes shapes, and Node's own modules (files, network, programs) are not for it",
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
return call(load, this, [request, ...rest]);
|
|
115
|
+
});
|
|
116
|
+
for (const k of ['register', 'registerHooks', 'runMain', '_preloadModules', 'enableCompileCache'])
|
|
117
|
+
if (k in Module) shut(Module, k, undefined);
|
|
118
|
+
// and what import gives of node:module and node:process follows (it was taken when the runner first imported them)
|
|
119
|
+
Module.syncBuiltinESMExports();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Take the place of Node's own web client's connection keeper before anything can make one. Node's fetch is undici,
|
|
124
|
+
* which Node loads the first time Headers, FormData, Request, Response, WebSocket, MessageEvent or CloseEvent is
|
|
125
|
+
* touched: it then keeps an agent on globalThis, under this name, that connects anywhere, through no module a design
|
|
126
|
+
* asks for. So the name is held first, for good, by one that refuses: undici keeps one it finds there.
|
|
127
|
+
*/
|
|
128
|
+
export function shutWebClient() {
|
|
129
|
+
const refuse = () => {
|
|
130
|
+
throw deny('reach the network', 'a design only makes shapes');
|
|
131
|
+
};
|
|
132
|
+
const none = Object.freeze({
|
|
133
|
+
dispatch: refuse,
|
|
134
|
+
close: refuse,
|
|
135
|
+
destroy: refuse,
|
|
136
|
+
on: refuse,
|
|
137
|
+
once: refuse,
|
|
138
|
+
emit: refuse,
|
|
139
|
+
removeListener: refuse,
|
|
140
|
+
});
|
|
141
|
+
Object.defineProperty(globalThis, Symbol.for('undici.globalDispatcher.1'), {
|
|
142
|
+
value: none,
|
|
143
|
+
writable: false,
|
|
144
|
+
configurable: false,
|
|
145
|
+
enumerable: false,
|
|
146
|
+
});
|
|
147
|
+
for (const k of ['FormData', 'Headers', 'MessageEvent', 'CloseEvent']) delete globalThis[k];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Take away what process itself offers past the import hook: Node's modules and internals, programs, files. */
|
|
151
|
+
export function shutProcess() {
|
|
152
|
+
for (const k of [
|
|
153
|
+
'getBuiltinModule',
|
|
154
|
+
'binding',
|
|
155
|
+
'_linkedBinding',
|
|
156
|
+
'dlopen',
|
|
157
|
+
'kill',
|
|
158
|
+
'_kill',
|
|
159
|
+
'execve',
|
|
160
|
+
'loadEnvFile',
|
|
161
|
+
'openStdin',
|
|
162
|
+
'_getActiveHandles',
|
|
163
|
+
'_getActiveRequests',
|
|
164
|
+
'_debugProcess',
|
|
165
|
+
'_startProfilerIdleNotifier',
|
|
166
|
+
]) {
|
|
167
|
+
if (k in process) shut(process, k, undefined);
|
|
168
|
+
}
|
|
169
|
+
// and process.exit ends the process however the design changes process: it calls reallyExit, kept as it is
|
|
170
|
+
shut(process, 'reallyExit', process.reallyExit);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// A wait of a millisecond, where a write would block for long (a pipe Node has made non-blocking: older Node makes
|
|
174
|
+
// process.stdout and stderr sockets for its hooks' worker before the runner starts)
|
|
175
|
+
const pause = new Int32Array(new SharedArrayBuffer(4));
|
|
176
|
+
/**
|
|
177
|
+
* Write all of data to a file descriptor (1, stdout; 2, stderr) directly, through no stream: what the runner sends.
|
|
178
|
+
* @param {number} fd @param {string | Uint8Array} data
|
|
179
|
+
*/
|
|
180
|
+
export function writeAll(fd, data) {
|
|
181
|
+
const b = typeof data === 'string' ? Buffer.from(data) : data;
|
|
182
|
+
for (let n = 0, tries = 0; n < b.length;) {
|
|
183
|
+
try {
|
|
184
|
+
n += fs.writeSync(fd, b, n);
|
|
185
|
+
tries = 0;
|
|
186
|
+
} catch (e) {
|
|
187
|
+
if (e.code !== 'EAGAIN') throw e;
|
|
188
|
+
if (++tries > 1000) Atomics.wait(pause, 0, 0, 1); // (the pipe is full: try again at once, then wait a little)
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Put plain streams in the place of process.stdout, stderr and stdin and the console, before anything has asked for
|
|
195
|
+
* the real ones: a pipe's stream is a socket, whose class connects anywhere, so the runner never makes them, and
|
|
196
|
+
* writes to its file descriptors itself (writeAll). What a design writes to stdout or stderr goes on to the same.
|
|
197
|
+
*/
|
|
198
|
+
export function shutStreams() {
|
|
199
|
+
const passOn = (fd) =>
|
|
200
|
+
new Writable({
|
|
201
|
+
write(chunk, encoding, done) {
|
|
202
|
+
try {
|
|
203
|
+
writeAll(fd, typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk);
|
|
204
|
+
done();
|
|
205
|
+
} catch (e) {
|
|
206
|
+
done(e);
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
const out = passOn(1),
|
|
211
|
+
err = passOn(2),
|
|
212
|
+
none = new Writable({ write: (c, e, done) => done() }); // (stdin: read already, nothing more comes)
|
|
213
|
+
for (const [k, s] of [
|
|
214
|
+
['stdout', out],
|
|
215
|
+
['stderr', err],
|
|
216
|
+
['stdin', none],
|
|
217
|
+
])
|
|
218
|
+
Object.defineProperty(process, k, { get: () => s, enumerable: true, configurable: false });
|
|
219
|
+
// what a design prints goes to stderr: stdout carries the reply
|
|
220
|
+
Object.defineProperty(globalThis, 'console', {
|
|
221
|
+
value: new Console({ stdout: err, stderr: err }),
|
|
222
|
+
writable: true,
|
|
223
|
+
configurable: true,
|
|
224
|
+
});
|
|
225
|
+
}
|
package/lib/sandbox-preload.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Loaded first in the sandbox (node --import): the import hook that keeps designs to their own imports. In-thread
|
|
2
2
|
// (module.registerHooks) where Node has it; older Node runs hooks in a worker, which the sandbox then allows.
|
|
3
3
|
import * as mod from 'node:module';
|
|
4
|
-
import { resolveHook, initialize, homesOf } from './sandbox-hooks.mjs';
|
|
4
|
+
import { resolveHook, loadHook, initialize, homesOf } from './sandbox-hooks.mjs';
|
|
5
5
|
|
|
6
6
|
const project = process.env.CAD_SANDBOX_PROJECT;
|
|
7
7
|
if (mod.registerHooks) {
|
|
8
8
|
initialize({ project });
|
|
9
|
-
mod.registerHooks({ resolve: resolveHook });
|
|
9
|
+
mod.registerHooks({ resolve: resolveHook, load: loadHook });
|
|
10
10
|
} else mod.register('./sandbox-hooks.mjs', import.meta.url, { data: { project, homes: homesOf() } });
|
package/lib/sandbox-run.mjs
CHANGED
|
@@ -11,31 +11,21 @@ import * as gears from '@rulecad/gears';
|
|
|
11
11
|
import * as motors from '@rulecad/motors';
|
|
12
12
|
import { designFrames } from './frames.mjs';
|
|
13
13
|
import { designFixings } from './fixings.mjs';
|
|
14
|
+
import { designShapes } from './designshapes.mjs';
|
|
14
15
|
import { named, faces, unpack, watch } from './parts.mjs';
|
|
15
16
|
import { lineOf } from './errors.mjs';
|
|
16
17
|
import { keeper, STAGES_MOST, ROUTES_MOST } from './kept.mjs';
|
|
18
|
+
import { IMPORTED } from './sandbox-hooks.mjs';
|
|
19
|
+
import { shutLoader, shutProcess, shutStreams, shutWebClient, writeAll } from './sandbox-lock.mjs';
|
|
17
20
|
|
|
21
|
+
shutWebClient(); // (first: touching Headers and the like makes an agent that connects anywhere: sandbox-lock.mjs)
|
|
18
22
|
for (const k of ['fetch', 'WebSocket', 'EventSource', 'XMLHttpRequest', 'Request', 'Response']) delete globalThis[k];
|
|
19
23
|
// and the ways round the import hook that process itself offers: Node's own modules by name, its internals, other
|
|
20
|
-
// processes
|
|
24
|
+
// processes, files (sandbox-lock.mjs; sandbox.mjs's header says what this does and doesn't promise)
|
|
21
25
|
const exit = process.exit.bind(process);
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
'_linkedBinding',
|
|
26
|
-
'dlopen',
|
|
27
|
-
'kill',
|
|
28
|
-
'_kill',
|
|
29
|
-
'_getActiveHandles',
|
|
30
|
-
'_getActiveRequests',
|
|
31
|
-
'_debugProcess',
|
|
32
|
-
'_startProfilerIdleNotifier',
|
|
33
|
-
]) {
|
|
34
|
-
if (k in process) Object.defineProperty(process, k, { value: undefined, configurable: false, writable: false });
|
|
35
|
-
}
|
|
36
|
-
const chunks = [];
|
|
37
|
-
for await (const c of process.stdin) chunks.push(c);
|
|
38
|
-
const { js, values, meta, engine, optional, stages, bound, board } = JSON.parse(Buffer.concat(chunks).toString('utf8')),
|
|
26
|
+
shutProcess();
|
|
27
|
+
shutStreams(); // (the request is read, and the reply written, by file descriptor: sandbox-lock.mjs says why)
|
|
28
|
+
const { js, values, meta, engine, optional, stages, bound, board } = JSON.parse(fs.readFileSync(0, 'utf8')),
|
|
39
29
|
context = bound?.fixings;
|
|
40
30
|
// A lamina's slow stages: read from the tool's cache (the workspace is readable), and what this run makes handed back
|
|
41
31
|
// with the parts for the tool to write (this process can't), up to the cap the tool takes (kept.mjs: past it, a stage
|
|
@@ -95,20 +85,24 @@ const engineFor = () => ({
|
|
|
95
85
|
return pcb.mount(thread, x, y, { sets: context?.sets, ...o });
|
|
96
86
|
},
|
|
97
87
|
});
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
88
|
+
// stdout carries the result, so what a design prints (console.log, to see a value) goes to stderr (shutStreams), which
|
|
89
|
+
// the tool passes on
|
|
90
|
+
const done = (o) => {
|
|
91
|
+
writeAll(1, JSON.stringify(o));
|
|
92
|
+
exit(0);
|
|
93
|
+
};
|
|
102
94
|
try {
|
|
95
|
+
shutLoader(process.env.CAD_SANDBOX_PROJECT); // (the CommonJS loader: no design reaches Node's own modules by it)
|
|
103
96
|
const mod = await import(js);
|
|
104
97
|
if (typeof mod.main !== 'function')
|
|
105
98
|
throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
|
|
106
99
|
const ops = await shapes.ops(engine || 'jscad'),
|
|
107
|
-
df = designFixings({ ...(context || {}), ops })
|
|
100
|
+
df = designFixings({ ...(context || {}), ops }), // (v.fixings: bound to the project, as the build's own is)
|
|
101
|
+
ds = designShapes(shapes, { printer: context?.printer }); // (v.shapes: its seats said, as the build's own are)
|
|
108
102
|
const { v, read } = watch(
|
|
109
103
|
values,
|
|
110
104
|
{
|
|
111
|
-
shapes,
|
|
105
|
+
shapes: ds.shapes,
|
|
112
106
|
flexures,
|
|
113
107
|
gears,
|
|
114
108
|
motors,
|
|
@@ -120,10 +114,14 @@ try {
|
|
|
120
114
|
optional,
|
|
121
115
|
);
|
|
122
116
|
const { shapes: made, mechanism } = unpack(await mod.main(v));
|
|
117
|
+
// the files of its project the design imported, as the import hook saw them (after main: it may import as it runs)
|
|
118
|
+
const imports = (await import(IMPORTED)).default;
|
|
123
119
|
const found = {
|
|
124
120
|
read: [...read],
|
|
121
|
+
imports,
|
|
125
122
|
...(mechanism ? { mechanism } : {}),
|
|
126
123
|
...(df.used() ? { fixings: df.found() } : {}),
|
|
124
|
+
...(ds.used() ? { seats: ds.found() } : {}),
|
|
127
125
|
...(Object.keys(kept).length ? { stages: kept } : {}),
|
|
128
126
|
};
|
|
129
127
|
if (pcb) {
|
package/lib/sandbox.mjs
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
|
-
// Designs are code. A JSCAD design runs in a sandbox: another Node process with
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
1
|
+
// Designs are code. A JSCAD design runs in a sandbox: another Node process with Node's permission model on, started
|
|
2
|
+
// with no --allow-fs-write, --allow-child-process, --allow-addons, --allow-wasi or --allow-net, reads allowed only in
|
|
3
|
+
// the folders readable() lists (of the workspace, only the design's own project), and none of this process's environment (no tokens). On top of Node's boundary, to keep
|
|
4
|
+
// a design to making shapes: the import hook (sandbox-hooks.mjs) lets it import only the packages in ALLOWED there and
|
|
5
|
+
// files of its own project, and loads no CommonJS file of the project (which would have the CommonJS loader to hand);
|
|
6
|
+
// the runner (sandbox-run.mjs, with sandbox-lock.mjs) takes away fetch and its kin and process's own ways to Node's
|
|
7
|
+
// modules, shuts the CommonJS loader to Node's modules, and gives the design plain streams in place of the standard
|
|
8
|
+
// streams' sockets. What that leaves a design, Node version by Node version, is the table in the README's Sandbox
|
|
9
|
+
// paragraph (its rows tried by test/sandbox-docs.test.mjs, sandbox-loader.test.mjs and sandbox.test.mjs): it can never
|
|
10
|
+
// write files or start programs, reads only what its imports name (its project's files, the allowed packages), and
|
|
11
|
+
// reaches no socket by any way the tests know of. Before Node 25 that last rests on the runner alone, in the design's
|
|
12
|
+
// own process, as the permission model doesn't cover the network: cad says so once a run (networkWarning). From Node
|
|
13
|
+
// 25 the permission model shuts the network too.
|
|
14
|
+
// So: run only designs you trust, as with any code.
|
|
11
15
|
// It gets its values as data and sends back its parts' faces. A workspace that trusts its designs sets
|
|
12
|
-
// "sandbox": false in cad.config.json (or CAD_TRUST=1
|
|
16
|
+
// "sandbox": false in cad.config.json (counted once the user has run cad trust there) or CAD_TRUST=1.
|
|
13
17
|
// Board designs (engine pcb) run here too, with the board engine: the sandbox may then also read @rulecad/pcb and what
|
|
14
18
|
// it loads (tscircuit's packages), the design gets v.pcb as it would in the tool's process (v.pcb.mount reads the
|
|
15
19
|
// workspace's thread sets, handed in as data), the runner builds the board's Circuit JSON, and the reply carries it
|
|
@@ -25,6 +29,7 @@ import { WS, TOOL, config, trusted, DESIGN_TIMEOUT, DESIGN_MEMORY, ownFile } fro
|
|
|
25
29
|
import { fromFaces } from './parts.mjs';
|
|
26
30
|
import { located } from './errors.mjs';
|
|
27
31
|
import { STAGES_MOST, ROUTES_MOST } from './kept.mjs';
|
|
32
|
+
import { ALLOWED } from './sandbox-hooks.mjs';
|
|
28
33
|
|
|
29
34
|
const flag = (() => {
|
|
30
35
|
const f = process.allowedNodeEnvironmentFlags;
|
|
@@ -41,11 +46,12 @@ const inThread = typeof nodeModule.registerHooks === 'function'; // import hooks
|
|
|
41
46
|
// (a workspace's "sandbox": false counts only once the user has trusted it: cad trust)
|
|
42
47
|
export const sandboxed = () => !!flag && process.env.CAD_TRUST !== '1' && !(config.sandbox === false && trusted());
|
|
43
48
|
|
|
44
|
-
// What the sandbox may read: the workspace,
|
|
49
|
+
// What the sandbox may read: of the workspace, what `own` names (the design's project, the workspace's package.json and
|
|
50
|
+
// the design's own cache folders: runSandboxed), and the packages designs and the runner load (wherever npm put them), and
|
|
45
51
|
// what those load in turn (@rulecad/frames sizes a beam's operations through @rulecad/fixings). Node's permission
|
|
46
52
|
// model follows a link inside these folders wherever it leads, so a link in the design's project or rules/ that leads
|
|
47
53
|
// out of the workspace is refused before the sandbox starts (workspace.mjs noLinksOut, from design.mjs).
|
|
48
|
-
function readable({ board = false, extra = [] } = {}) {
|
|
54
|
+
function readable({ board = false, extra = [], own = [WS] } = {}) {
|
|
49
55
|
const real = (p) => {
|
|
50
56
|
try {
|
|
51
57
|
return fs.realpathSync(p);
|
|
@@ -74,17 +80,11 @@ function readable({ board = false, extra = [] } = {}) {
|
|
|
74
80
|
}
|
|
75
81
|
};
|
|
76
82
|
const dirs = [
|
|
77
|
-
|
|
83
|
+
...own,
|
|
78
84
|
TOOL,
|
|
79
85
|
...[...up(WS), ...up(TOOL)].filter((d) => fs.existsSync(d)),
|
|
80
86
|
...[
|
|
81
|
-
|
|
82
|
-
'@rulecad/shapes',
|
|
83
|
-
'@rulecad/flexures',
|
|
84
|
-
'@rulecad/gears',
|
|
85
|
-
'@rulecad/motors',
|
|
86
|
-
'@rulecad/frames',
|
|
87
|
-
'@rulecad/fixings',
|
|
87
|
+
...ALLOWED, // (what a design may import, and what the runner loads besides)
|
|
88
88
|
'@rulecad/rules/x1c.json',
|
|
89
89
|
'@rulecad/fea',
|
|
90
90
|
'@rulecad/variables',
|
|
@@ -96,7 +96,7 @@ function readable({ board = false, extra = [] } = {}) {
|
|
|
96
96
|
...new Set(
|
|
97
97
|
dirs
|
|
98
98
|
.filter(Boolean)
|
|
99
|
-
.flatMap((d) => [d, real(d)])
|
|
99
|
+
.flatMap((d) => [d, real(d), path.join(real(path.dirname(d)) || path.dirname(d), path.basename(d))]) // (and by its folder's real path: a link spelled from there)
|
|
100
100
|
.filter(Boolean),
|
|
101
101
|
),
|
|
102
102
|
];
|
|
@@ -206,6 +206,90 @@ const ownFolder = (dir) => {
|
|
|
206
206
|
}
|
|
207
207
|
};
|
|
208
208
|
|
|
209
|
+
const isLink = (f) => {
|
|
210
|
+
try {
|
|
211
|
+
return fs.lstatSync(f).isSymbolicLink();
|
|
212
|
+
} catch {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
// Whether a folder, or one inside it, holds a link
|
|
217
|
+
const holdsLink = (dir) => {
|
|
218
|
+
try {
|
|
219
|
+
return fs
|
|
220
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
221
|
+
.some((e) => e.isSymbolicLink() || (e.isDirectory() && holdsLink(path.join(dir, e.name))));
|
|
222
|
+
} catch {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
};
|
|
226
|
+
// The first link in a folder (its node_modules included) that leads anywhere but inside the folder itself or a folder
|
|
227
|
+
// the sandbox reads anyway (reads): { link, to }, or null. Each folder is looked through once, by its real path.
|
|
228
|
+
function linkOut(dir, reads) {
|
|
229
|
+
const inside = (f, d) => {
|
|
230
|
+
const rel = path.relative(d, f);
|
|
231
|
+
return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
|
|
232
|
+
};
|
|
233
|
+
const top = fs.realpathSync(dir),
|
|
234
|
+
allowed = [top, ...reads.filter((r) => r !== dir)],
|
|
235
|
+
seen = new Set();
|
|
236
|
+
const look = (d) => {
|
|
237
|
+
let real;
|
|
238
|
+
try {
|
|
239
|
+
real = fs.realpathSync(d);
|
|
240
|
+
} catch {
|
|
241
|
+
return null;
|
|
242
|
+
}
|
|
243
|
+
if (seen.has(real)) return null;
|
|
244
|
+
seen.add(real);
|
|
245
|
+
let entries;
|
|
246
|
+
try {
|
|
247
|
+
entries = fs.readdirSync(d, { withFileTypes: true });
|
|
248
|
+
} catch {
|
|
249
|
+
return null;
|
|
250
|
+
}
|
|
251
|
+
for (const e of entries) {
|
|
252
|
+
const p = path.join(d, e.name);
|
|
253
|
+
if (e.isSymbolicLink()) {
|
|
254
|
+
let to;
|
|
255
|
+
try {
|
|
256
|
+
to = fs.realpathSync(p);
|
|
257
|
+
} catch {
|
|
258
|
+
continue; // (a link to nothing: reading it finds nothing)
|
|
259
|
+
}
|
|
260
|
+
if (!allowed.some((a) => inside(to, a))) return { link: p, to };
|
|
261
|
+
if (inside(to, top) && fs.statSync(p).isDirectory()) {
|
|
262
|
+
const found = look(p);
|
|
263
|
+
if (found) return found;
|
|
264
|
+
}
|
|
265
|
+
} else if (e.isDirectory()) {
|
|
266
|
+
const found = look(p);
|
|
267
|
+
if (found) return found;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return null;
|
|
271
|
+
};
|
|
272
|
+
return look(dir);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// The files a reply says the design imported, each by its path inside the project ('objects/box.js', with forward
|
|
276
|
+
// slashes): only files of the project are kept (the reply is untrusted, and the tool reads and hashes what is listed)
|
|
277
|
+
function inProject(urls, project) {
|
|
278
|
+
const top = fileURLToPath(project),
|
|
279
|
+
out = new Set();
|
|
280
|
+
for (const u of urls) {
|
|
281
|
+
let f;
|
|
282
|
+
try {
|
|
283
|
+
f = fileURLToPath(u);
|
|
284
|
+
} catch {
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
const rel = path.relative(top, f);
|
|
288
|
+
if (rel && !path.isAbsolute(rel) && !rel.split(path.sep).includes('..')) out.add(rel.split(path.sep).join('/'));
|
|
289
|
+
}
|
|
290
|
+
return [...out].sort();
|
|
291
|
+
}
|
|
292
|
+
|
|
209
293
|
/** The form of a stage's key, as the stage cache makes it: a stage's name, a dash and the 64 hex digits of a SHA-256. */
|
|
210
294
|
export const STAGE_KEY = /^[a-z][a-z0-9 _-]{0,39}-[0-9a-f]{64}$/;
|
|
211
295
|
|
|
@@ -239,7 +323,7 @@ const point = (p) => Array.isArray(p) && p.length === 3 && p.every((n) => typeof
|
|
|
239
323
|
const faceList = (x) => Array.isArray(x) && x.every((f) => Array.isArray(f) && f.every(point));
|
|
240
324
|
const PART = { name: 'string', role: 'string', label: 'string', filament: 'string', mirror: 'boolean' },
|
|
241
325
|
PART_FACES = ['solid', 'polygons', 'triangles'];
|
|
242
|
-
const REPLY = ['parts', 'read', 'mechanism', 'fixings', 'stages', 'board', 'mounted', 'routes'],
|
|
326
|
+
const REPLY = ['parts', 'read', 'imports', 'mechanism', 'fixings', 'seats', 'stages', 'board', 'mounted', 'routes'],
|
|
243
327
|
ERROR = { message: 'string', code: 'string', line: 'number', syntax: 'boolean', resource: 'string' };
|
|
244
328
|
const fields = (o, kinds) => Object.entries(o).find(([k, x]) => !(k in kinds) || typeof x !== kinds[k]);
|
|
245
329
|
|
|
@@ -270,8 +354,8 @@ function checkBoard(b) {
|
|
|
270
354
|
|
|
271
355
|
/**
|
|
272
356
|
* What is wrong with a reply from the sandbox's runner, in a few words, or null when it is one the runner makes:
|
|
273
|
-
* `{ parts, read, mechanism?, fixings?, stages? }`, a board design's `{ parts: [], read, board: {
|
|
274
|
-
* source? }, mounted?, fixings?, routes? }`, or `{ error }`. Its stages no more than `stagesMost` (STAGES_MOST), its
|
|
357
|
+
* `{ parts, read, imports?, mechanism?, fixings?, stages? }`, a board design's `{ parts: [], read, imports?, board: {
|
|
358
|
+
* circuit, matrix?, source? }, mounted?, fixings?, routes? }`, or `{ error }`. Its stages no more than `stagesMost` (STAGES_MOST), its
|
|
275
359
|
* routes no more than ROUTES_MOST.
|
|
276
360
|
* @param {unknown} r the child's stdout, parsed
|
|
277
361
|
* @param {{ count: number, bytes: number }} [stagesMost] @returns {string | null}
|
|
@@ -300,9 +384,20 @@ export function checkReply(r, stagesMost = STAGES_MOST) {
|
|
|
300
384
|
}
|
|
301
385
|
if (!Array.isArray(r.read) || !r.read.every((n) => typeof n === 'string'))
|
|
302
386
|
return 'what it read is not a list of names';
|
|
387
|
+
if (r.imports != null && !(Array.isArray(r.imports) && r.imports.every((u) => typeof u === 'string')))
|
|
388
|
+
return 'what it imported is not a list of files';
|
|
303
389
|
if (r.mechanism != null && !plain(r.mechanism)) return 'its mechanism is not an object';
|
|
304
390
|
if (r.fixings != null && !(Array.isArray(r.fixings) && r.fixings.every(plain)))
|
|
305
391
|
return 'its fixings are not a list of findings';
|
|
392
|
+
// (what v.shapes' seat helpers drew, lib/designshapes.mjs: never more than an info finding of its one code)
|
|
393
|
+
if (
|
|
394
|
+
r.seats != null &&
|
|
395
|
+
!(
|
|
396
|
+
Array.isArray(r.seats) &&
|
|
397
|
+
r.seats.every((x) => plain(x) && x.level === 'info' && x.code === 'seat.drawn' && typeof x.text === 'string')
|
|
398
|
+
)
|
|
399
|
+
)
|
|
400
|
+
return 'its seats are not a list of seat.drawn findings';
|
|
306
401
|
if (r.stages != null) {
|
|
307
402
|
if (!plain(r.stages)) return 'its stages are not an object';
|
|
308
403
|
const bad = Object.entries(r.stages).find(([k, text]) => !STAGE_KEY.test(k) || typeof text !== 'string');
|
|
@@ -331,6 +426,20 @@ export function checkReply(r, stagesMost = STAGES_MOST) {
|
|
|
331
426
|
/** Whether designs can be sandboxed here at all: Node has the permission model. */
|
|
332
427
|
export const canSandbox = () => !!flag;
|
|
333
428
|
|
|
429
|
+
/**
|
|
430
|
+
* What cad says before the first design it runs in the sandbox, where Node's permission model doesn't cover the
|
|
431
|
+
* network (before Node 25: no --allow-net to withhold) and only the runner's own locks keep a design off it
|
|
432
|
+
* (sandbox-lock.mjs), or null where Node's model does.
|
|
433
|
+
* @param {string} [version] Node's version, as process.version gives it @returns {string | null}
|
|
434
|
+
*/
|
|
435
|
+
export function networkWarning(version = process.version) {
|
|
436
|
+
const major = Number(/^v?(\d+)/.exec(version)?.[1]);
|
|
437
|
+
return major < 25
|
|
438
|
+
? `designs are kept off the network on Node ${major} by rulecad alone, not by Node itself: use Node 25 or above for designs you did not write`
|
|
439
|
+
: null;
|
|
440
|
+
}
|
|
441
|
+
let warned = false; // (said once a run)
|
|
442
|
+
|
|
334
443
|
// How long a design may run and how much memory it may use, in the sandbox. A design with an endless loop would
|
|
335
444
|
// otherwise hang every command that builds it, with no word said, and one that fills memory without end would grow
|
|
336
445
|
// until the system stopped it, taking other work with it. Past either limit the design's process is stopped, and the
|
|
@@ -486,7 +595,8 @@ const HEAP_DEATH = /JavaScript heap out of memory|Reached heap limit|Ineffective
|
|
|
486
595
|
* @param {{ frames?: object, fixings?: { sets?: object, printer?: object, material?: string | null } | null }} [request.bound] what the design's helpers are bound to: frames, the workspace's profile sets (lib/frames.mjs framesContext); fixings, what v.fixings is bound to (design.mjs fixingsContext), whose calls come back as fixings. A board's v.pcb.mount reads fixings.sets too
|
|
487
596
|
* @param {{ routes?: { dir: string, shared?: string | null, put: (k: string, text: string) => void } | null } | null} [request.board] set for a board design (engine pcb): routes, where the autorouter's results are kept (the child reads this design's own folder, dir, then the route cache the tool's own process writes, shared; what it routes is handed back and put in dir only)
|
|
488
597
|
* @param {string[]} [request.read] more folders the sandbox may read (a copy of a workspace held in memory)
|
|
489
|
-
* @returns {Promise<{ parts: object[], read: Set<string>, mechanism: object | null, fixings: object[] | null, board?: { circuit: object[], matrix?: object, source?: object }, mounted?: boolean }>}
|
|
598
|
+
* @returns {Promise<{ parts: object[], read: Set<string>, imports: string[], mechanism: object | null, fixings: object[] | null, board?: { circuit: object[], matrix?: object, source?: object }, mounted?: boolean }>}
|
|
599
|
+
* imports: the files of its project the design imported, each by its path inside the project ('objects/box.js')
|
|
490
600
|
*/
|
|
491
601
|
export function runSandboxed({
|
|
492
602
|
d,
|
|
@@ -507,18 +617,49 @@ export function runSandboxed({
|
|
|
507
617
|
} catch (e) {
|
|
508
618
|
return Promise.reject(located(e, d.js, 'design.limit'));
|
|
509
619
|
}
|
|
620
|
+
if (!warned) {
|
|
621
|
+
warned = true;
|
|
622
|
+
const w = networkWarning();
|
|
623
|
+
if (w) process.stderr.write(`Note: ${w}\n`);
|
|
624
|
+
}
|
|
625
|
+
// (real paths: Node names an imported file by where it really is, so a workspace reached through a link still matches)
|
|
626
|
+
const js = fs.realpathSync(d.js),
|
|
627
|
+
project = pathToFileURL(path.dirname(path.dirname(js)) + path.sep).href;
|
|
628
|
+
// Of the workspace, the sandbox reads only the design's project, the package.json that says its files are ES
|
|
629
|
+
// modules, and the design's own folders of the caches: not the workspace's other projects
|
|
630
|
+
// Node's permission model follows a link wherever it leads, and a design can get Node's fs by way of a package's
|
|
631
|
+
// code (sandbox-lock.mjs): so a cache folder holding a link is not read at all (every stage a miss), the workspace's
|
|
632
|
+
// package.json only where it is no link, and a link anywhere in the project (its node_modules too) must lead to a
|
|
633
|
+
// folder the sandbox reads anyway, never to another project or out of the workspace (linksIn)
|
|
634
|
+
const projectDir = path.dirname(path.dirname(js));
|
|
635
|
+
const own = [
|
|
636
|
+
projectDir,
|
|
637
|
+
...[path.join(WS, 'package.json')].filter((f) => !isLink(f)),
|
|
638
|
+
...[stages?.dir, board?.routes?.dir]
|
|
639
|
+
.filter(Boolean)
|
|
640
|
+
.map((dir) => ownFolder(path.resolve(dir)))
|
|
641
|
+
.filter((dir) => dir && !holdsLink(dir)),
|
|
642
|
+
].filter(Boolean);
|
|
643
|
+
const reads = readable({ board: !!board, extra: [...more, ...routes], own });
|
|
644
|
+
const leads = linkOut(projectDir, reads);
|
|
645
|
+
if (leads)
|
|
646
|
+
return Promise.reject(
|
|
647
|
+
Object.assign(
|
|
648
|
+
new Error(
|
|
649
|
+
`${leads.link} is a link to ${leads.to}, which a design of this project may not read, so the design isn't run: in the sandbox a design reads only its own project and the kit's packages, and a link would hand it a file of another project or of yours elsewhere. Copy the file into the project, or take the link out`,
|
|
650
|
+
),
|
|
651
|
+
{ code: 'workspace.outside', file: leads.link },
|
|
652
|
+
),
|
|
653
|
+
);
|
|
510
654
|
const args = [
|
|
511
655
|
flag,
|
|
512
656
|
`--max-old-space-size=${limits.memory}`,
|
|
513
|
-
...
|
|
657
|
+
...reads.map((p) => `--allow-fs-read=${p}`),
|
|
514
658
|
...(inThread ? [] : ['--allow-worker']),
|
|
515
659
|
'--import',
|
|
516
660
|
pathToFileURL(path.join(here, 'sandbox-preload.mjs')).href,
|
|
517
661
|
path.join(here, 'sandbox-run.mjs'),
|
|
518
662
|
];
|
|
519
|
-
// (real paths: Node names an imported file by where it really is, so a workspace reached through a link still matches)
|
|
520
|
-
const js = fs.realpathSync(d.js),
|
|
521
|
-
project = pathToFileURL(path.dirname(path.dirname(js)) + path.sep).href;
|
|
522
663
|
// The child gets none of this process's environment but what Node needs to start: tokens and keys stay out of it
|
|
523
664
|
const env = Object.fromEntries(
|
|
524
665
|
['PATH', 'SystemRoot', 'windir', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'LC_ALL', 'PHYS_DEBUG', 'LAMINA_TIMES']
|
|
@@ -656,8 +797,10 @@ export function runSandboxed({
|
|
|
656
797
|
resolve({
|
|
657
798
|
parts: r.parts.map(({ solid, ...p }) => ({ ...p, geometry: fromFaces(solid) })),
|
|
658
799
|
read: new Set(r.read),
|
|
800
|
+
imports: inProject(r.imports || [], project),
|
|
659
801
|
mechanism: r.mechanism || null,
|
|
660
802
|
fixings: r.fixings || null,
|
|
803
|
+
seats: r.seats || null,
|
|
661
804
|
...(board ? { board: r.board, mounted: r.mounted === true } : {}),
|
|
662
805
|
});
|
|
663
806
|
});
|