@rulecad/cad 0.8.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 +45 -16
- package/CHANGELOG.md +724 -0
- package/EXAMPLES.md +61 -54
- package/README.md +376 -98
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2664 -541
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1883 -435
- package/lib/beams.mjs +256 -52
- package/lib/belts.mjs +66 -15
- package/lib/board-work.mjs +12 -0
- package/lib/bought.mjs +309 -53
- package/lib/buildpage.mjs +179 -29
- package/lib/cache-file.mjs +105 -0
- package/lib/carried.mjs +201 -0
- package/lib/clone.mjs +194 -42
- package/lib/code-text.mjs +28 -0
- package/lib/design-imports.mjs +127 -0
- package/lib/design.mjs +871 -147
- package/lib/designshapes.mjs +142 -0
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +922 -192
- package/lib/errors.mjs +16 -3
- package/lib/estimates.mjs +51 -0
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2708 -507
- package/lib/fe-key.mjs +29 -0
- package/lib/fittings.mjs +721 -122
- package/lib/fixings.mjs +38 -13
- package/lib/framebuild.mjs +790 -175
- package/lib/framecheck.mjs +1901 -368
- package/lib/framegen.mjs +108 -22
- package/lib/frameheat.mjs +225 -42
- package/lib/frameprint.mjs +513 -108
- package/lib/frames.mjs +86 -18
- package/lib/framesize.mjs +719 -120
- package/lib/frametip.mjs +235 -0
- package/lib/gait.mjs +135 -23
- package/lib/grip.mjs +62 -13
- package/lib/guides.mjs +1403 -230
- package/lib/host.mjs +129 -23
- package/lib/inplace.mjs +171 -36
- package/lib/jigs.mjs +360 -78
- package/lib/joins.mjs +697 -118
- package/lib/jsonedit.mjs +88 -26
- package/lib/kept.mjs +84 -0
- package/lib/kit.mjs +439 -69
- package/lib/layout.mjs +2 -1
- package/lib/links.mjs +149 -42
- package/lib/list.mjs +334 -64
- package/lib/live-guard.mjs +68 -0
- package/lib/live-shape.mjs +96 -24
- package/lib/live.mjs +189 -59
- package/lib/loads.mjs +597 -136
- package/lib/machine.mjs +372 -74
- package/lib/magnets.mjs +162 -44
- package/lib/measured.mjs +1080 -117
- package/lib/mesh.mjs +526 -119
- package/lib/meshcmd.mjs +215 -60
- package/lib/motors.mjs +1002 -214
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +18 -1
- package/lib/optimise.mjs +991 -287
- package/lib/order.mjs +515 -114
- package/lib/panels.mjs +482 -94
- package/lib/parts.mjs +81 -23
- package/lib/pins.mjs +163 -44
- package/lib/plates.mjs +223 -35
- package/lib/player.mjs +37 -9
- package/lib/power.mjs +64 -13
- package/lib/preview.mjs +83 -16
- package/lib/profilemeasure.mjs +572 -129
- package/lib/rules.mjs +17 -6
- package/lib/sandbox-hooks.mjs +179 -27
- package/lib/sandbox-lock.mjs +225 -0
- package/lib/sandbox-preload.mjs +2 -2
- package/lib/sandbox-run.mjs +122 -25
- package/lib/sandbox.mjs +667 -75
- package/lib/schema.mjs +42 -11
- package/lib/seats.mjs +227 -49
- package/lib/services.mjs +261 -52
- package/lib/sheet.mjs +963 -179
- package/lib/slotnuts.mjs +213 -34
- package/lib/targets/gist.mjs +4 -1
- package/lib/targets.mjs +22 -4
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +285 -39
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +200 -14
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
- 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
package/lib/rules.mjs
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import fs from 'node:fs';
|
|
4
4
|
import path from 'node:path';
|
|
5
5
|
import { host, readJson } from './host.mjs';
|
|
6
|
-
import { RULE_DIRS, WS } from './workspace.mjs';
|
|
6
|
+
import { RULE_DIRS, WS, readOwnText } from './workspace.mjs';
|
|
7
7
|
import { plainName } from './names.mjs';
|
|
8
8
|
import { resolve as resolveWith } from '@rulecad/variables';
|
|
9
9
|
|
|
@@ -21,10 +21,11 @@ export function loadRuleSet(name, dir) {
|
|
|
21
21
|
const own = path.join(WS, 'rules', `${name}.json`);
|
|
22
22
|
if (!dir && file !== own) {
|
|
23
23
|
insideWorkspace(own);
|
|
24
|
-
host.writeText(own,
|
|
24
|
+
host.writeText(own, readOwnText(file));
|
|
25
25
|
console.error(`copied the ${name} rule set into rules/${name}.json: yours to keep and edit`);
|
|
26
26
|
}
|
|
27
|
-
|
|
27
|
+
// (a release's own rules are read from its folder: the workspace's copy may have been measured again since)
|
|
28
|
+
return readJson(dir ? file : own);
|
|
28
29
|
}
|
|
29
30
|
/**
|
|
30
31
|
* `file` (a rule set about to be written into the workspace's rules/) if no folder or file on its way down from the
|
|
@@ -38,12 +39,22 @@ export function insideWorkspace(file) {
|
|
|
38
39
|
if (host.name !== 'node') return file; // (a workspace in memory has no links)
|
|
39
40
|
const top = path.resolve(WS); // (the workspace's own folder may be reached by a link: only what is inside it counts)
|
|
40
41
|
for (let p = path.resolve(file); p.startsWith(top + path.sep); p = path.dirname(p)) {
|
|
41
|
-
let link = false;
|
|
42
|
-
|
|
42
|
+
let link = false;
|
|
43
|
+
try {
|
|
44
|
+
link = fs.lstatSync(p).isSymbolicLink();
|
|
45
|
+
} catch {
|
|
46
|
+
// (not there yet: nothing to follow)
|
|
47
|
+
}
|
|
48
|
+
if (link)
|
|
49
|
+
throw new Error(
|
|
50
|
+
`${path.relative(WS, p)} is a link to somewhere else, so nothing was written to ${path.relative(WS, file)}: it could land outside the workspace. Make ${path.relative(WS, p)} a folder or file of the workspace's own`,
|
|
51
|
+
);
|
|
43
52
|
}
|
|
44
53
|
return file;
|
|
45
54
|
}
|
|
46
|
-
// A rule set read as it is, the workspace's if it has one: for figures a check only reads, leaving the workspace alone
|
|
55
|
+
// A rule set read as it is, the workspace's if it has one: for figures a check only reads, leaving the workspace alone.
|
|
56
|
+
// (Both read through readJson, which reads a file of the workspace only where it really is inside it: a rules/x.json
|
|
57
|
+
// that is a link to a file elsewhere is refused, code workspace.outside. workspace.mjs ownFile.)
|
|
47
58
|
export function peekRuleSet(name) {
|
|
48
59
|
plainName(name, 'rule set name');
|
|
49
60
|
const file = RULE_DIRS.map((d) => path.join(d, `${name}.json`)).find((f) => host.exists(f));
|
package/lib/sandbox-hooks.mjs
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
|
-
// The sandbox's import hook: code in the design's project may import
|
|
2
|
-
//
|
|
1
|
+
// The sandbox's import hook: code in the design's project may import the packages in ALLOWED (below: the one list,
|
|
2
|
+
// which the README, AGENTS.md and sandbox.mjs follow, and test/sandbox-docs.test.mjs holds them to) and files of its
|
|
3
|
+
// own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
|
|
4
|
+
// Where Node has module.registerHooks (22.15 on) the hook runs in the design's own thread and sees require() as well as
|
|
5
|
+
// import; before that it runs in a worker and sees only import. A CommonJS file has the CommonJS loader itself to hand
|
|
6
|
+
// (module.constructor, require.cache), which can load Node's own modules past any hook: so no file of the project is
|
|
7
|
+
// loaded as CommonJS (.cjs, or a .js file Node reads as CommonJS), on every Node. A design and its files are ES modules
|
|
8
|
+
// (import and export), as the README says. The runner (sandbox-run.mjs) shuts the CommonJS loader to Node's own
|
|
9
|
+
// modules as well, before the design loads, for any other way to it (test/sandbox-loader.test.mjs tries them).
|
|
3
10
|
// An allowed package is named plainly and must lead inside that package: '@jscad/modeling/../../graceful-fs' would
|
|
4
11
|
// otherwise climb out of it to any file of the workspace, and a file outside the project isn't held to these rules.
|
|
5
12
|
import fs from 'node:fs';
|
|
@@ -10,7 +17,48 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
10
17
|
// (Not @rulecad/pcb: a board design reaches the board engine as v.pcb, which the runner loads as the tool's own
|
|
11
18
|
// module. The engine imports Node's modules, which a package a design may import may not, and the permission model
|
|
12
19
|
// holds it to reads only.)
|
|
13
|
-
|
|
20
|
+
/**
|
|
21
|
+
* The only modules of Node's own the sandbox loads, for the tool's code (a design gets none): what the tool's packages
|
|
22
|
+
* use as they run (Manifold's loader asks for fs, path and url; a board's engine for crypto) and others like them,
|
|
23
|
+
* none of which reaches the network, another program, a worker or another loader. Every other module of Node's (net,
|
|
24
|
+
* http, dns, tls, tty, child_process, worker_threads, vm, inspector and the rest) is refused to every caller, by this
|
|
25
|
+
* hook and by the runner's lock on the CommonJS loader (sandbox-lock.mjs): before Node 25 that is what keeps the
|
|
26
|
+
* network shut, whatever way round the rest a design finds.
|
|
27
|
+
*/
|
|
28
|
+
export const QUIET = new Set(
|
|
29
|
+
(
|
|
30
|
+
'assert assert/strict buffer console constants crypto events fs fs/promises os path path/posix path/win32 ' +
|
|
31
|
+
'perf_hooks process punycode querystring readline readline/promises stream stream/consumers stream/promises ' +
|
|
32
|
+
'stream/web string_decoder timers timers/promises url util util/types zlib'
|
|
33
|
+
).split(' '),
|
|
34
|
+
);
|
|
35
|
+
// Where these hooks run in the design's own thread (module.registerHooks), the design can change String.prototype,
|
|
36
|
+
// Set.prototype and the like for everyone: what decides which of Node's modules load, and whether code is the
|
|
37
|
+
// design's, uses functions taken here, before any design runs, and lists of its own.
|
|
38
|
+
const call = Reflect.apply,
|
|
39
|
+
startsWith = String.prototype.startsWith,
|
|
40
|
+
slice = String.prototype.slice,
|
|
41
|
+
has = Set.prototype.has,
|
|
42
|
+
QUIET_NOW = new Set(QUIET),
|
|
43
|
+
NODES = new Set(builtinModules);
|
|
44
|
+
const bare = (spec) => (call(startsWith, spec, ['node:']) ? call(slice, spec, [5]) : spec);
|
|
45
|
+
/** Whether spec names a module of Node's own (with or without "node:"). @param {string} spec */
|
|
46
|
+
export const isNodes = (spec) =>
|
|
47
|
+
typeof spec === 'string' && (call(startsWith, spec, ['node:']) || call(has, NODES, [spec]));
|
|
48
|
+
/** Whether spec names one of Node's own modules the sandbox loads for the tool (QUIET). @param {string} spec */
|
|
49
|
+
export const quiet = (spec) => typeof spec === 'string' && call(has, QUIET_NOW, [bare(spec)]);
|
|
50
|
+
const within = (url, folder) => typeof url === 'string' && !!folder && call(startsWith, url, [folder]);
|
|
51
|
+
|
|
52
|
+
/** The packages a design may import, by name (a file inside one too): the hook's one list, as the documents give it. */
|
|
53
|
+
export const ALLOWED = [
|
|
54
|
+
'@jscad/modeling',
|
|
55
|
+
'@rulecad/shapes',
|
|
56
|
+
'@rulecad/flexures',
|
|
57
|
+
'@rulecad/gears',
|
|
58
|
+
'@rulecad/motors',
|
|
59
|
+
'@rulecad/frames',
|
|
60
|
+
'@rulecad/fixings',
|
|
61
|
+
];
|
|
14
62
|
|
|
15
63
|
// Each allowed package's real folder, as the tool itself finds it (from its entry up to the package.json of that
|
|
16
64
|
// name: exports may hide that file), found once; null where the tool can't find the package
|
|
@@ -18,9 +66,12 @@ function home(name) {
|
|
|
18
66
|
try {
|
|
19
67
|
for (let d = path.dirname(fileURLToPath(import.meta.resolve(name))); path.dirname(d) !== d; d = path.dirname(d)) {
|
|
20
68
|
const pj = path.join(d, 'package.json');
|
|
21
|
-
if (fs.existsSync(pj) && JSON.parse(fs.readFileSync(pj, 'utf8')).name === name)
|
|
69
|
+
if (fs.existsSync(pj) && JSON.parse(fs.readFileSync(pj, 'utf8')).name === name)
|
|
70
|
+
return pathToFileURL(fs.realpathSync(d) + path.sep).href;
|
|
22
71
|
}
|
|
23
|
-
} catch {
|
|
72
|
+
} catch {
|
|
73
|
+
/* not where the tool can find it */
|
|
74
|
+
}
|
|
24
75
|
return null;
|
|
25
76
|
}
|
|
26
77
|
|
|
@@ -28,8 +79,13 @@ function home(name) {
|
|
|
28
79
|
function needs(url) {
|
|
29
80
|
try {
|
|
30
81
|
const j = JSON.parse(fs.readFileSync(new URL('package.json', url), 'utf8'));
|
|
31
|
-
return [
|
|
32
|
-
|
|
82
|
+
return [
|
|
83
|
+
...ALLOWED,
|
|
84
|
+
...['dependencies', 'peerDependencies', 'optionalDependencies'].flatMap((k) => Object.keys(j[k] || {})),
|
|
85
|
+
];
|
|
86
|
+
} catch {
|
|
87
|
+
return ALLOWED;
|
|
88
|
+
}
|
|
33
89
|
}
|
|
34
90
|
|
|
35
91
|
/**
|
|
@@ -40,7 +96,15 @@ function needs(url) {
|
|
|
40
96
|
*/
|
|
41
97
|
export const homesOf = () => Object.fromEntries(ALLOWED.map((a) => [a, home(a)]));
|
|
42
98
|
|
|
43
|
-
let project = '',
|
|
99
|
+
let project = '',
|
|
100
|
+
homes = {},
|
|
101
|
+
deps = {};
|
|
102
|
+
// The files of its own project the design imported (file: URLs, without a query), for the build's cache: a kept build
|
|
103
|
+
// holds while each of them reads as it did (design.mjs). The runner asks for them by importing IMPORTED, a module these
|
|
104
|
+
// hooks make up, which works the same whether they run in the runner's thread or in a worker of their own (older Node).
|
|
105
|
+
const imported = new Set();
|
|
106
|
+
/** The name the runner imports to learn which of its project's files the design imported (a list of file: URLs). */
|
|
107
|
+
export const IMPORTED = 'rulecad-imports:list';
|
|
44
108
|
/**
|
|
45
109
|
* Set the hooks up: the design's project (a file: URL ending in a slash) and, from the preload, the packages' folders.
|
|
46
110
|
* @param {{ project?: string, homes?: Record<string, string | null> }} [data]
|
|
@@ -51,33 +115,97 @@ export async function initialize(data) {
|
|
|
51
115
|
deps = Object.fromEntries(ALLOWED.filter((a) => homes[a]).map((a) => [a, needs(homes[a])]));
|
|
52
116
|
}
|
|
53
117
|
|
|
54
|
-
const deny = (spec, why) =>
|
|
118
|
+
const deny = (spec, why) =>
|
|
119
|
+
Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
|
|
55
120
|
|
|
56
|
-
// The same check, for in-thread hooks (synchronous) and worker hooks (async)
|
|
121
|
+
// The same check, for in-thread hooks (synchronous) and worker hooks (async). (IMPORTED only after the check: a design
|
|
122
|
+
// that imports it by name is refused, as any name that isn't an allowed package is.)
|
|
57
123
|
export function resolveHook(spec, context, next) {
|
|
58
|
-
const fromDesign = check(spec, context)
|
|
59
|
-
|
|
124
|
+
const fromDesign = check(spec, context);
|
|
125
|
+
if (spec === IMPORTED) return { url: IMPORTED, shortCircuit: true };
|
|
126
|
+
const r = next(spec, context);
|
|
127
|
+
return fromDesign ? noted(spec, after(spec, r)) : inPackage(spec, context, r);
|
|
60
128
|
}
|
|
61
129
|
export async function resolve(spec, context, next) {
|
|
62
|
-
const fromDesign = check(spec, context)
|
|
63
|
-
|
|
130
|
+
const fromDesign = check(spec, context);
|
|
131
|
+
if (spec === IMPORTED) return { url: IMPORTED, shortCircuit: true };
|
|
132
|
+
const r = await next(spec, context);
|
|
133
|
+
return fromDesign ? noted(spec, after(spec, r)) : inPackage(spec, context, r);
|
|
134
|
+
}
|
|
135
|
+
/** The import hook's load, in this thread: IMPORTED's text, the list as it stands (the runner imports it once, after
|
|
136
|
+
* the design's main has run); any other module as Node loads it, but a file of the project that is CommonJS. */
|
|
137
|
+
export function loadHook(url, context, next) {
|
|
138
|
+
return url === IMPORTED
|
|
139
|
+
? { format: 'module', source: `export default ${JSON.stringify([...imported])};`, shortCircuit: true }
|
|
140
|
+
: notCommonJS(url, next(url, context));
|
|
141
|
+
}
|
|
142
|
+
/** The import hook's load, in a worker (older Node): as loadHook. */
|
|
143
|
+
export async function load(url, context, next) {
|
|
144
|
+
return url === IMPORTED ? loadHook(url, context) : notCommonJS(url, await next(url, context));
|
|
145
|
+
}
|
|
146
|
+
// A file of the project that Node would run as CommonJS (format 'commonjs', or 'commonjs-typescript' for a .cts) is
|
|
147
|
+
// refused before it runs: it would have module.constructor, the CommonJS loader, which hands out Node's own modules
|
|
148
|
+
// whatever this hook says. (A package kept in the project's node_modules is the project's too, and held the same.)
|
|
149
|
+
function notCommonJS(url, r) {
|
|
150
|
+
if (within(url, project) && typeof r?.format === 'string' && call(startsWith, r.format, ['commonjs'])) {
|
|
151
|
+
const file = fileURLToPath(url.replace(/[?#].*$/, ''));
|
|
152
|
+
throw Object.assign(
|
|
153
|
+
new Error(
|
|
154
|
+
`designs can't load ${file}: it is a CommonJS file (require and module.exports), and a design's files are ES modules (import and export). In the sandbox a CommonJS file could reach Node's own modules, so none is loaded. Write it with import and export (a .js file in a workspace whose package.json says "type": "module", or a .mjs file)`,
|
|
155
|
+
),
|
|
156
|
+
{ code: 'design.sandbox' },
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
return r;
|
|
160
|
+
}
|
|
161
|
+
// A file of the project the design reached by a relative path is noted (a package's copy kept in the project's
|
|
162
|
+
// node_modules is not the design's own code: it changes with an install, as the tool's packages do)
|
|
163
|
+
function noted(spec, r) {
|
|
164
|
+
if (isRelative(spec) && r.url.startsWith(project)) {
|
|
165
|
+
const u = new URL(r.url);
|
|
166
|
+
if (!u.pathname.split('/').some((s) => s.toLowerCase() === 'node_modules')) {
|
|
167
|
+
u.search = '';
|
|
168
|
+
u.hash = '';
|
|
169
|
+
imported.add(u.href);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return r;
|
|
64
173
|
}
|
|
65
174
|
// A design may reach any file of an allowed package, and such a file isn't the design's, so it is free of the rules
|
|
66
175
|
// above: one that imports something the package doesn't depend on would hand that to the design. @jscad/modeling's
|
|
67
176
|
// own tests require('ava'), and an "ava" the workspace installs (a file: dependency, say) may do anything. So a file
|
|
68
177
|
// of an allowed package (not of a package kept in its node_modules) may import only the allowed packages, what its
|
|
69
178
|
// package.json depends on, and its own files.
|
|
70
|
-
const packageAt = (url) =>
|
|
179
|
+
const packageAt = (url) =>
|
|
180
|
+
ALLOWED.find(
|
|
181
|
+
(a) =>
|
|
182
|
+
homes[a] &&
|
|
183
|
+
url?.startsWith(homes[a]) &&
|
|
184
|
+
!url
|
|
185
|
+
.slice(homes[a].length)
|
|
186
|
+
.split('/')
|
|
187
|
+
.some((s) => s.toLowerCase() === 'node_modules'),
|
|
188
|
+
);
|
|
71
189
|
// (before Node looks for a name, and after it finds a relative file)
|
|
72
190
|
function packageCheck(spec, context) {
|
|
73
191
|
const name = packageAt(context.parentURL);
|
|
74
|
-
if (
|
|
75
|
-
|
|
192
|
+
if (
|
|
193
|
+
name &&
|
|
194
|
+
!isRelative(spec) &&
|
|
195
|
+
(spec.startsWith('node:') ||
|
|
196
|
+
builtinModules.includes(spec) ||
|
|
197
|
+
!deps[name].some((d) => spec === d || spec.startsWith(`${d}/`)))
|
|
198
|
+
) {
|
|
199
|
+
throw deny(
|
|
200
|
+
spec,
|
|
201
|
+
`${fileURLToPath(context.parentURL)} would import it, and its package ${name} doesn't depend on it (a design may use a package's own files, not the tools its tests use)`,
|
|
202
|
+
);
|
|
76
203
|
}
|
|
77
204
|
}
|
|
78
205
|
function inPackage(spec, context, r) {
|
|
79
206
|
const name = isRelative(spec) && packageAt(context.parentURL);
|
|
80
|
-
if (name && !r.url.startsWith(homes[name]))
|
|
207
|
+
if (name && !r.url.startsWith(homes[name]))
|
|
208
|
+
throw deny(spec, `${fileURLToPath(context.parentURL)} would reach outside its package, ${name}`);
|
|
81
209
|
return r;
|
|
82
210
|
}
|
|
83
211
|
const isRelative = (spec) => spec.startsWith('./') || spec.startsWith('../');
|
|
@@ -87,32 +215,56 @@ const packageOf = (spec) => ALLOWED.find((a) => spec === a || spec.startsWith(`$
|
|
|
87
215
|
// uses, or a copy in the project: not through a link out of the project to some other folder of the same name.
|
|
88
216
|
const after = (spec, r) => {
|
|
89
217
|
if (isRelative(spec)) {
|
|
90
|
-
if (!r.url
|
|
218
|
+
if (!within(r.url, project)) throw deny(spec, 'it is outside the project');
|
|
91
219
|
return r;
|
|
92
220
|
}
|
|
93
|
-
const name = packageOf(spec),
|
|
94
|
-
|
|
221
|
+
const name = packageOf(spec),
|
|
222
|
+
inside = homes[name];
|
|
223
|
+
if (!within(r.url, project) && !within(r.url, inside)) {
|
|
95
224
|
const to = r.url.startsWith('file:') ? fileURLToPath(r.url) : r.url;
|
|
96
225
|
const own = inside ? ` (${fileURLToPath(inside)})` : '';
|
|
97
|
-
throw deny(
|
|
226
|
+
throw deny(
|
|
227
|
+
spec,
|
|
228
|
+
`it leads outside the package ${name}, to ${to}. A design may use only the copy rulecad itself uses${own} or one inside its project: if the workspace installs another copy, give it the version rulecad uses (npm ls ${name} lists the copies)`,
|
|
229
|
+
);
|
|
98
230
|
}
|
|
99
231
|
return r;
|
|
100
232
|
};
|
|
101
233
|
// A file inside a package is named plainly: no '.' or '..' among the folders, no backslash, no %-encoded letters, and
|
|
102
234
|
// never in the package's own node_modules (another package, which may read files: a nested graceful-fs, say). Windows
|
|
103
235
|
// drops a name's trailing dots and spaces and knows NODE_M~1 for node_modules, so those spellings are refused too.
|
|
104
|
-
const odd = (s) => {
|
|
105
|
-
const
|
|
236
|
+
const odd = (s) => {
|
|
237
|
+
const t = s.replace(/[. ]+$/, '').toLowerCase();
|
|
238
|
+
return t === '' || t === 'node_modules' || s.includes('~');
|
|
239
|
+
};
|
|
240
|
+
const climbs = (spec, name) =>
|
|
241
|
+
/[\\%]/.test(spec) ||
|
|
242
|
+
(spec !== name &&
|
|
243
|
+
spec
|
|
244
|
+
.slice(name.length + 1)
|
|
245
|
+
.split('/')
|
|
246
|
+
.some(odd));
|
|
106
247
|
// Everything under the project is the design's code, a node_modules folder there included
|
|
107
248
|
function check(spec, context) {
|
|
108
|
-
const fromDesign =
|
|
249
|
+
const fromDesign = within(context.parentURL, project);
|
|
250
|
+
// (whoever imports it: code of the design's that has worked its way to the CommonJS loader can make a module that
|
|
251
|
+
// says it is a file of the tool's, sandbox-lock.mjs says how, so the tool's own code is held to the same list)
|
|
252
|
+
if (!fromDesign && isNodes(spec) && !quiet(spec) && bare(spec) !== 'module')
|
|
253
|
+
throw deny(
|
|
254
|
+
spec,
|
|
255
|
+
"in the sandbox none of Node's own modules that reach the network, other programs or workers is loaded",
|
|
256
|
+
);
|
|
109
257
|
if (!fromDesign) packageCheck(spec, context);
|
|
110
258
|
if (fromDesign) {
|
|
111
|
-
if (
|
|
259
|
+
if (isNodes(spec)) throw deny(spec, 'a design only makes shapes (no files, network or programs)');
|
|
112
260
|
if (!isRelative(spec)) {
|
|
113
261
|
const name = packageOf(spec);
|
|
114
262
|
if (!name) throw deny(spec, `only ${ALLOWED.join(', ')} and files in its project`);
|
|
115
|
-
if (climbs(spec, name))
|
|
263
|
+
if (climbs(spec, name))
|
|
264
|
+
throw deny(
|
|
265
|
+
spec,
|
|
266
|
+
`a file of ${name} is named by its path inside the package, with no "." or ".." folders, node_modules, backslashes, "%" or "~", and no folder whose name ends in a dot or a space`,
|
|
267
|
+
);
|
|
116
268
|
}
|
|
117
269
|
}
|
|
118
270
|
return fromDesign;
|
|
@@ -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() } });
|