@rulecad/cad 0.9.0 → 0.11.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 +29 -10
- package/CHANGELOG.md +604 -0
- package/EXAMPLES.md +122 -105
- package/README.md +292 -63
- package/bin/cad.mjs +500 -87
- package/lib/assembly.mjs +486 -134
- package/lib/bays.mjs +124 -0
- package/lib/cache-file.mjs +148 -0
- package/lib/clone.mjs +93 -11
- package/lib/code-text.mjs +28 -0
- package/lib/design-imports.mjs +127 -0
- package/lib/design.mjs +291 -59
- package/lib/designshapes.mjs +142 -0
- package/lib/edit.mjs +29 -5
- 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 +73 -92
- package/lib/framecheck.mjs +154 -77
- package/lib/framegen.mjs +9 -1
- package/lib/frames.mjs +6 -2
- package/lib/framesize.mjs +45 -82
- package/lib/gait.mjs +17 -7
- package/lib/guides.mjs +84 -50
- package/lib/host.mjs +7 -3
- package/lib/kit.mjs +5 -5
- package/lib/list.mjs +29 -21
- package/lib/live-guard.mjs +18 -8
- package/lib/loads.mjs +35 -23
- package/lib/measured.mjs +740 -99
- package/lib/mesh.mjs +156 -56
- package/lib/motors.mjs +26 -33
- package/lib/names.mjs +15 -0
- package/lib/node-version.mjs +52 -0
- package/lib/optimise.mjs +34 -25
- package/lib/order.mjs +5 -12
- package/lib/parts.mjs +3 -0
- package/lib/picture-servers.mjs +66 -0
- package/lib/power.mjs +14 -7
- package/lib/preview.mjs +12 -25
- package/lib/programs.mjs +113 -0
- package/lib/rules.mjs +2 -1
- package/lib/sandbox-guard.mjs +43 -0
- 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 +345 -42
- package/lib/sheet.mjs +114 -3
- package/lib/targets/gist.mjs +9 -6
- package/lib/versions.mjs +294 -35
- package/lib/workspace.mjs +6 -3
- package/package.json +14 -14
- package/schemas/assembly.schema.json +6 -5
- package/schemas/object.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,66 @@
|
|
|
1
|
+
// The two small web servers cad takes its pictures from. preview.mjs starts one, and a headless Chrome to open it, for
|
|
2
|
+
// the few seconds a picture takes: partsServer(data) serves the page that draws a part's six views
|
|
3
|
+
// (lib/preview/page.html), the part itself (/data.json) and three's build files; pageServer(html) serves one page (an
|
|
4
|
+
// SVG drawing, a report) whatever is asked for.
|
|
5
|
+
// Both answer only to this computer's own names and addresses, as the live views do (live-guard.mjs, which says why):
|
|
6
|
+
// any web page open in the browser can send requests to a server on this computer, and one whose own name is pointed
|
|
7
|
+
// at 127.0.0.1 (DNS rebinding) could otherwise read the part or the page while its picture is taken. preview.mjs sends
|
|
8
|
+
// Chrome to http://127.0.0.1:<port>/, so Chrome's own requests always name this computer.
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import http from 'node:http';
|
|
12
|
+
import { createRequire } from 'node:module';
|
|
13
|
+
import { TOOL } from './workspace.mjs';
|
|
14
|
+
import { liveGuard } from './live-guard.mjs';
|
|
15
|
+
|
|
16
|
+
const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // wherever npm put it
|
|
17
|
+
|
|
18
|
+
// The check both servers run on each request. What a refused request is told is their own: there is no name to ask
|
|
19
|
+
// for with --allow-host here, and no run to stop
|
|
20
|
+
const allowed = liveGuard({
|
|
21
|
+
host: '127.0.0.1',
|
|
22
|
+
says: {
|
|
23
|
+
host: (given) =>
|
|
24
|
+
'cad serves this page for a few seconds, to make a picture of it, and only to this computer: ' +
|
|
25
|
+
`it does not answer to "${given}".\n`,
|
|
26
|
+
post: 'cad serves this page only to make a picture of it: it takes nothing sent from another page.\n',
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The server a part's six views are drawn from: the page, the part and three's build files, and nothing else. It
|
|
32
|
+
* answers only to this computer's own names and addresses.
|
|
33
|
+
* @param {string} data the part as the page reads it (JSON: title, meta, parts with their triangles)
|
|
34
|
+
* @returns {import('node:http').Server} not yet listening
|
|
35
|
+
*/
|
|
36
|
+
export function partsServer(data) {
|
|
37
|
+
return http.createServer((req, res) => {
|
|
38
|
+
if (!allowed(req, res)) return;
|
|
39
|
+
// An address that can't be read (//) is not found: read with new URL() it threw, and ended the command
|
|
40
|
+
const u = URL.parse(req.url ?? '', 'http://x')?.pathname ?? '';
|
|
41
|
+
const send = (type, body) => {
|
|
42
|
+
res.writeHead(200, { 'Content-Type': type });
|
|
43
|
+
res.end(body);
|
|
44
|
+
};
|
|
45
|
+
if (u === '/') return send('text/html', fs.readFileSync(path.join(TOOL, 'lib/preview/page.html')));
|
|
46
|
+
if (u === '/data.json') return send('application/json', data);
|
|
47
|
+
const f = path.join(THREE, path.basename(u)); // only three's build files
|
|
48
|
+
if (u.startsWith('/three/') && fs.existsSync(f)) return send('text/javascript', fs.readFileSync(f));
|
|
49
|
+
res.writeHead(404);
|
|
50
|
+
res.end();
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The server any page's picture is taken from: it answers every request with the page, and only to this computer's
|
|
56
|
+
* own names and addresses.
|
|
57
|
+
* @param {string} html the page
|
|
58
|
+
* @returns {import('node:http').Server} not yet listening
|
|
59
|
+
*/
|
|
60
|
+
export function pageServer(html) {
|
|
61
|
+
return http.createServer((req, res) => {
|
|
62
|
+
if (!allowed(req, res)) return;
|
|
63
|
+
res.writeHead(200, { 'Content-Type': 'text/html' });
|
|
64
|
+
res.end(html);
|
|
65
|
+
});
|
|
66
|
+
}
|
package/lib/power.mjs
CHANGED
|
@@ -18,6 +18,9 @@ export function powerChecks(s, f) {
|
|
|
18
18
|
const m = d.model,
|
|
19
19
|
refs = { item: d.id, ...(d.joint ? { joint: d.joint } : {}) };
|
|
20
20
|
if (m.type === 'stepper') {
|
|
21
|
+
// A stepper sheet's rated current is per phase, what each coil carries with both on at a full step. It is taken
|
|
22
|
+
// as the peak a driver lets through each coil, as Pololu advises (the cautious reading: a microstepping sine at
|
|
23
|
+
// that peak never puts more through a coil than the sheet allows), and so is a drive's own "current"
|
|
21
24
|
const rated = m.figures.rated_current?.value,
|
|
22
25
|
current = d.spec.current ?? rated,
|
|
23
26
|
R = m.figures.resistance?.value;
|
|
@@ -41,19 +44,23 @@ export function powerChecks(s, f) {
|
|
|
41
44
|
continue;
|
|
42
45
|
}
|
|
43
46
|
const model = driverModel(o.bought.set, { variant: o.bought.variant ?? undefined }),
|
|
44
|
-
{ vref, findings } = setting(
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
{ vref, findings, rms } = setting(
|
|
48
|
+
model,
|
|
49
|
+
{ peak: current },
|
|
50
|
+
{
|
|
51
|
+
cooled: !!d.spec.cooled,
|
|
52
|
+
supply: voltage,
|
|
53
|
+
microsteps: d.spec.microsteps,
|
|
54
|
+
},
|
|
55
|
+
);
|
|
49
56
|
for (const x of findings)
|
|
50
57
|
f(x.level, `${d.id}: ${x.text}`, `${d.id}: driver`, { code: x.code, values: x.values, refs });
|
|
51
58
|
if (!findings.some((x) => x.level === 'fail'))
|
|
52
59
|
f(
|
|
53
60
|
'pass',
|
|
54
|
-
`${d.id} on ${model.name}: set the trimmer to ${n3(vref, 3)} V for ${n3(current, 2)} A per coil (${model.formula}${model.uart ? `, or set it over UART` : ''}), ${model.sense} ohm sense resistors: read yours before trusting this`,
|
|
61
|
+
`${d.id} on ${model.name}: set the trimmer to ${n3(vref, 3)} V for ${n3(current, 2)} A peak per coil${model.measure === 'rms' ? ` (${n3(rms, 2)} A RMS)` : ''} (${model.formula}${model.uart ? `, or set it over UART` : ''}), ${model.sense} ohm sense resistors: read yours before trusting this`,
|
|
55
62
|
null,
|
|
56
|
-
{ code: 'motor.driver', refs, values: { vref, current, sense: model.sense } },
|
|
63
|
+
{ code: 'motor.driver', refs, values: { vref, current, peak: current, rms, sense: model.sense } },
|
|
57
64
|
);
|
|
58
65
|
} else if (m.type === 'servo') {
|
|
59
66
|
draws.push({ name: d.id, current: 0.7, voltage: m.figures.rated_voltage?.value ?? 5, duty: d.spec.duty ?? 0.2 });
|
package/lib/preview.mjs
CHANGED
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
// solid with built (an assembly with show: built); explode drops
|
|
4
4
|
// supports below and, in an assembly, lifts each kind of object above the one before (plate, switches, keycaps); a part
|
|
5
5
|
// with `lift` (a screw, a nut: lib/fasten.mjs) goes with the part it sits in (`with`) and then out along its own axis.
|
|
6
|
-
// rendered by headless Chrome from lib/preview/page.html, served on this
|
|
6
|
+
// rendered by headless Chrome from lib/preview/page.html, served on this computer only for the few seconds it takes,
|
|
7
|
+
// by a server that answers only to this computer's own names (picture-servers.mjs).
|
|
7
8
|
import fs from 'node:fs';
|
|
8
9
|
import os from 'node:os';
|
|
9
10
|
import path from 'node:path';
|
|
10
|
-
import http from 'node:http';
|
|
11
11
|
import { spawn } from 'node:child_process';
|
|
12
|
-
import {
|
|
13
|
-
import { TOOL } from './workspace.mjs';
|
|
12
|
+
import { pageServer, partsServer } from './picture-servers.mjs';
|
|
14
13
|
|
|
15
14
|
// Any Chrome or Chromium: $CAD_CHROME, else the usual places on macOS, Linux and Windows
|
|
16
15
|
const CHROME =
|
|
@@ -25,7 +24,6 @@ const CHROME =
|
|
|
25
24
|
'/opt/pw-browsers/chromium',
|
|
26
25
|
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
|
27
26
|
].find((f) => fs.existsSync(f));
|
|
28
|
-
const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // wherever npm put it
|
|
29
27
|
|
|
30
28
|
export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null, built = false }) {
|
|
31
29
|
const flat = (tris) => {
|
|
@@ -47,31 +45,16 @@ export async function preview(parts, { title = '', meta = '', out, explode = fal
|
|
|
47
45
|
positions: flat(p.triangles),
|
|
48
46
|
})),
|
|
49
47
|
});
|
|
50
|
-
|
|
51
|
-
const u = new URL(req.url, 'http://x').pathname;
|
|
52
|
-
const send = (type, body) => {
|
|
53
|
-
res.writeHead(200, { 'Content-Type': type });
|
|
54
|
-
res.end(body);
|
|
55
|
-
};
|
|
56
|
-
if (u === '/') return send('text/html', fs.readFileSync(path.join(TOOL, 'lib/preview/page.html')));
|
|
57
|
-
if (u === '/data.json') return send('application/json', data);
|
|
58
|
-
const f = path.join(THREE, path.basename(u)); // only three's build files
|
|
59
|
-
if (u.startsWith('/three/') && fs.existsSync(f)) return send('text/javascript', fs.readFileSync(f));
|
|
60
|
-
res.writeHead(404);
|
|
61
|
-
res.end();
|
|
62
|
-
});
|
|
63
|
-
return shoot(server, out);
|
|
48
|
+
return shoot(partsServer(data), out);
|
|
64
49
|
}
|
|
65
50
|
|
|
66
|
-
// Any page as an image: html served on this
|
|
51
|
+
// Any page as an image: html served on this computer for the few seconds Chrome takes (an SVG drawing, a report)
|
|
67
52
|
export async function picture(html, out, { width = 1800, height = 1200 } = {}) {
|
|
68
|
-
|
|
69
|
-
res.writeHead(200, { 'Content-Type': 'text/html' });
|
|
70
|
-
res.end(html);
|
|
71
|
-
});
|
|
72
|
-
return shoot(server, out, { width, height });
|
|
53
|
+
return shoot(pageServer(html), out, { width, height });
|
|
73
54
|
}
|
|
74
55
|
|
|
56
|
+
// Chrome is sent to the server by this computer's address, the one name the server is sure to answer to
|
|
57
|
+
// (picture-servers.mjs refuses a request that names any other computer)
|
|
75
58
|
async function shoot(server, out, { width = 1800, height = 1200 } = {}) {
|
|
76
59
|
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
|
77
60
|
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cad-preview-'));
|
|
@@ -119,7 +102,11 @@ async function shoot(server, out, { width = 1800, height = 1200 } = {}) {
|
|
|
119
102
|
});
|
|
120
103
|
});
|
|
121
104
|
} finally {
|
|
105
|
+
// The picture is made, or Chrome has failed: nobody has anything left to ask, so every connection goes with the
|
|
106
|
+
// server. close() alone waits for each one still open, and nothing ever ends one that has asked nothing or
|
|
107
|
+
// stopped half-way through asking: a web page's early connection to the port kept the cad command from ending
|
|
122
108
|
server.close();
|
|
109
|
+
server.closeAllConnections();
|
|
123
110
|
// Chrome's helpers can still be writing to its profile as it exits (macOS: "Directory not empty"): try a few
|
|
124
111
|
// times, and leave it in the temporary folder rather than fail a picture that was made
|
|
125
112
|
try {
|
package/lib/programs.mjs
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// The programs cad starts that are not its own (git, gh, the file browser), found once each by cad itself.
|
|
2
|
+
//
|
|
3
|
+
// A program named without its folder is looked for by the system, and not only in PATH's folders: on Windows, Node
|
|
4
|
+
// looks first in the folder the program is started in, and on every system a PATH with an empty entry or "." in it
|
|
5
|
+
// looks in the current folder. cad starts git with the workspace as its folder, and the user's current folder is
|
|
6
|
+
// usually inside the workspace, and a workspace can come from anyone: a git.exe in one would run with the user's full
|
|
7
|
+
// rights, outside the design sandbox. So cad finds each program itself, by walking PATH: only entries that are full
|
|
8
|
+
// paths, none inside the workspace (npm puts the workspace's node_modules/.bin on PATH, and a stranger's package can put
|
|
9
|
+
// a "git" there), and on Windows only the kinds of file Windows starts without a shell (.com and .exe; a .bat or .cmd
|
|
10
|
+
// needs one, and cad never starts a program through a shell). The program is then started by the full path found.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { execFileSync } from 'node:child_process';
|
|
14
|
+
import { WS } from './workspace.mjs';
|
|
15
|
+
|
|
16
|
+
// The real path of a folder or file (every link followed), or the path as it is where it is not there
|
|
17
|
+
const real = (p) => {
|
|
18
|
+
try {
|
|
19
|
+
return fs.realpathSync.native(p);
|
|
20
|
+
} catch {
|
|
21
|
+
return path.resolve(p);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// Whether a path lies in a folder, or is it (on Windows and macOS, letters compared without their case)
|
|
26
|
+
const inside = (p, folder, platform) => {
|
|
27
|
+
const fold = platform === 'linux' ? (s) => s : (s) => s.toLowerCase(),
|
|
28
|
+
r = path.relative(fold(folder), fold(p));
|
|
29
|
+
return r === '' || (!r.startsWith('..') && !path.isAbsolute(r));
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// A file that can be run: on Windows, a file (its extension says it runs); elsewhere, a file with leave to run
|
|
33
|
+
function runnable(f, platform) {
|
|
34
|
+
try {
|
|
35
|
+
if (!fs.statSync(f).isFile()) return false;
|
|
36
|
+
if (platform !== 'win32') fs.accessSync(f, fs.constants.X_OK);
|
|
37
|
+
return true;
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Where a program is, looked for in PATH's folders only: a full path, or null when it is in none of them. Entries that
|
|
45
|
+
* are empty, relative ("." among them) or inside one of the folders in `avoid` (the workspace, unless told otherwise)
|
|
46
|
+
* are passed over, and so is a program found by a link that leads back inside one. On Windows the name is tried with
|
|
47
|
+
* each extension in PATHEXT that Windows starts without a shell (.com, .exe).
|
|
48
|
+
* @param {string} name the program's name alone, as "git"
|
|
49
|
+
* @param {{ env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, avoid?: string[] }} [options]
|
|
50
|
+
* @returns {string | null}
|
|
51
|
+
*/
|
|
52
|
+
export function findProgram(name, { env = process.env, platform = process.platform, avoid = [WS] } = {}) {
|
|
53
|
+
if (!/^[\w.-]+$/.test(name) || name.startsWith('.')) throw new Error(`not a program's name: ${name}`);
|
|
54
|
+
const p = platform === 'win32' ? path.win32 : path.posix,
|
|
55
|
+
// (Windows keeps its variables' names in any case: Path, PATH)
|
|
56
|
+
get = (k) => (platform === 'win32' ? Object.entries(env).find(([n]) => n.toUpperCase() === k)?.[1] : env[k]),
|
|
57
|
+
away = avoid.map(real);
|
|
58
|
+
const exts =
|
|
59
|
+
platform !== 'win32'
|
|
60
|
+
? ['']
|
|
61
|
+
: path.win32.extname(name)
|
|
62
|
+
? ['']
|
|
63
|
+
: (get('PATHEXT') || '.COM;.EXE')
|
|
64
|
+
.split(';')
|
|
65
|
+
.map((e) => e.trim().toLowerCase())
|
|
66
|
+
.filter((e) => e === '.com' || e === '.exe');
|
|
67
|
+
for (const entry of (get('PATH') || '').split(platform === 'win32' ? ';' : ':')) {
|
|
68
|
+
const dir = entry.trim().replace(/^"(.*)"$/, '$1'); // (Windows allows a quoted entry)
|
|
69
|
+
if (!dir || !p.isAbsolute(dir) || (platform === 'win32' && !/^([a-z]:[\\/]|\\\\)/i.test(dir))) continue;
|
|
70
|
+
if (away.some((w) => inside(real(dir), w, platform))) continue;
|
|
71
|
+
for (const ext of exts) {
|
|
72
|
+
const f = p.join(dir, name + ext);
|
|
73
|
+
if (runnable(f, platform) && !away.some((w) => inside(real(f), w, platform))) return f;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const found = new Map();
|
|
80
|
+
/**
|
|
81
|
+
* findProgram for the workspace, looked for once a run: a full path, or null.
|
|
82
|
+
* @param {string} name @returns {string | null}
|
|
83
|
+
*/
|
|
84
|
+
export function whereIs(name) {
|
|
85
|
+
if (!found.has(name)) found.set(name, findProgram(name));
|
|
86
|
+
return found.get(name);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The full path of a program cad starts, found once a run (findProgram), or an Error whose code is ENOENT, in plain
|
|
91
|
+
* words, when it is not on PATH outside the workspace.
|
|
92
|
+
* @param {string} name @param {string} what what the program is for, said when it is missing ("git, which keeps releases")
|
|
93
|
+
* @returns {string}
|
|
94
|
+
*/
|
|
95
|
+
export function program(name, what = name) {
|
|
96
|
+
const f = whereIs(name);
|
|
97
|
+
if (f) return f;
|
|
98
|
+
const e = /** @type {Error & { code: string }} */ (
|
|
99
|
+
new Error(
|
|
100
|
+
`${what} is not installed on this computer, or is not in any folder on its PATH. (cad looks for ${name} only in PATH's own folders, never in the workspace, so a program of that name in the workspace is not used.) Install it, or add its folder to PATH, then run the command again`,
|
|
101
|
+
)
|
|
102
|
+
);
|
|
103
|
+
e.code = 'ENOENT';
|
|
104
|
+
throw e;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Run a program cad starts (program()) by its full path, never through a shell: execFileSync's own options.
|
|
109
|
+
* @param {string} name @param {string[]} args @param {import('node:child_process').ExecFileSyncOptions} [options]
|
|
110
|
+
* @param {string} [what] what the program is for, said when it is missing
|
|
111
|
+
*/
|
|
112
|
+
export const runProgram = (name, args, options = {}, what = name) =>
|
|
113
|
+
execFileSync(program(name, what), args, { ...options, shell: false });
|
package/lib/rules.mjs
CHANGED
|
@@ -24,7 +24,8 @@ export function loadRuleSet(name, dir) {
|
|
|
24
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
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// The sandbox's guard: a small process of its own that ends a design's sandboxed process when the cad command that
|
|
2
|
+
// started it ends, however it ends. Started by sandbox.mjs (guardChild), once a command, with a pipe from the command
|
|
3
|
+
// as its input. The command writes `+<pid>` when it starts a sandboxed process and `-<pid>` when that process has
|
|
4
|
+
// ended. When the pipe closes (the command finished, was killed from outside, its terminal was closed, a test or CI
|
|
5
|
+
// job that ran it was stopped), the guard stops every process still listed and exits.
|
|
6
|
+
// The check can't be in the sandboxed process itself: a design that loops for ever holds that process's only thread,
|
|
7
|
+
// so no timer of its own would ever run, and a thread of its own would need the sandbox to allow workers. Nor can the
|
|
8
|
+
// command's own time limit do it, as a timer in the command dies with the command.
|
|
9
|
+
// It runs no design and reads nothing but its input. It ignores the signals a terminal sends to all its processes
|
|
10
|
+
// (Ctrl-C, a closed window), so it is the closing of the pipe that ends it, after the command, never before.
|
|
11
|
+
const listed = new Set();
|
|
12
|
+
for (const s of ['SIGINT', 'SIGHUP', 'SIGTERM', 'SIGBREAK']) {
|
|
13
|
+
try {
|
|
14
|
+
process.on(s, () => {}); // (the command's end closes the pipe, which is what this waits for)
|
|
15
|
+
} catch {
|
|
16
|
+
// (a signal this system doesn't have: nothing to ignore)
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
let rest = '';
|
|
20
|
+
process.stdin.setEncoding('utf8');
|
|
21
|
+
process.stdin.on('data', (text) => {
|
|
22
|
+
const lines = (rest + text).split('\n');
|
|
23
|
+
rest = lines.pop();
|
|
24
|
+
for (const line of lines) {
|
|
25
|
+
const m = /^([+-])(\d+)$/.exec(line.trim());
|
|
26
|
+
if (!m) continue;
|
|
27
|
+
if (m[1] === '+') listed.add(Number(m[2]));
|
|
28
|
+
else listed.delete(Number(m[2]));
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
const end = () => {
|
|
32
|
+
for (const pid of listed) {
|
|
33
|
+
try {
|
|
34
|
+
process.kill(pid, 'SIGKILL');
|
|
35
|
+
} catch {
|
|
36
|
+
// (it has ended already)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
process.exit(0);
|
|
40
|
+
};
|
|
41
|
+
process.stdin.on('end', end);
|
|
42
|
+
process.stdin.on('close', end);
|
|
43
|
+
process.stdin.on('error', end);
|
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,40 @@ 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 = [
|
|
14
54
|
'@jscad/modeling',
|
|
15
55
|
'@rulecad/shapes',
|
|
16
56
|
'@rulecad/flexures',
|
|
@@ -59,6 +99,12 @@ export const homesOf = () => Object.fromEntries(ALLOWED.map((a) => [a, home(a)])
|
|
|
59
99
|
let project = '',
|
|
60
100
|
homes = {},
|
|
61
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';
|
|
62
108
|
/**
|
|
63
109
|
* Set the hooks up: the design's project (a file: URL ending in a slash) and, from the preload, the packages' folders.
|
|
64
110
|
* @param {{ project?: string, homes?: Record<string, string | null> }} [data]
|
|
@@ -72,16 +118,58 @@ export async function initialize(data) {
|
|
|
72
118
|
const deny = (spec, why) =>
|
|
73
119
|
Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
|
|
74
120
|
|
|
75
|
-
// 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.)
|
|
76
123
|
export function resolveHook(spec, context, next) {
|
|
77
|
-
const fromDesign = check(spec, context)
|
|
78
|
-
|
|
79
|
-
|
|
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);
|
|
80
128
|
}
|
|
81
129
|
export async function resolve(spec, context, next) {
|
|
82
|
-
const fromDesign = check(spec, context)
|
|
83
|
-
|
|
84
|
-
|
|
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;
|
|
85
173
|
}
|
|
86
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
|
|
87
175
|
// above: one that imports something the package doesn't depend on would hand that to the design. @jscad/modeling's
|
|
@@ -127,12 +215,12 @@ const packageOf = (spec) => ALLOWED.find((a) => spec === a || spec.startsWith(`$
|
|
|
127
215
|
// uses, or a copy in the project: not through a link out of the project to some other folder of the same name.
|
|
128
216
|
const after = (spec, r) => {
|
|
129
217
|
if (isRelative(spec)) {
|
|
130
|
-
if (!r.url
|
|
218
|
+
if (!within(r.url, project)) throw deny(spec, 'it is outside the project');
|
|
131
219
|
return r;
|
|
132
220
|
}
|
|
133
221
|
const name = packageOf(spec),
|
|
134
222
|
inside = homes[name];
|
|
135
|
-
if (!r.url
|
|
223
|
+
if (!within(r.url, project) && !within(r.url, inside)) {
|
|
136
224
|
const to = r.url.startsWith('file:') ? fileURLToPath(r.url) : r.url;
|
|
137
225
|
const own = inside ? ` (${fileURLToPath(inside)})` : '';
|
|
138
226
|
throw deny(
|
|
@@ -158,11 +246,17 @@ const climbs = (spec, name) =>
|
|
|
158
246
|
.some(odd));
|
|
159
247
|
// Everything under the project is the design's code, a node_modules folder there included
|
|
160
248
|
function check(spec, context) {
|
|
161
|
-
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
|
+
);
|
|
162
257
|
if (!fromDesign) packageCheck(spec, context);
|
|
163
258
|
if (fromDesign) {
|
|
164
|
-
if (spec
|
|
165
|
-
throw deny(spec, 'a design only makes shapes (no files, network or programs)');
|
|
259
|
+
if (isNodes(spec)) throw deny(spec, 'a design only makes shapes (no files, network or programs)');
|
|
166
260
|
if (!isRelative(spec)) {
|
|
167
261
|
const name = packageOf(spec);
|
|
168
262
|
if (!name) throw deny(spec, `only ${ALLOWED.join(', ')} and files in its project`);
|