depkill 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +179 -3
- package/data/module-replacements.LICENSE +21 -0
- package/data/module-replacements.json +947 -0
- package/dist/src/anticheat/constants.js +105 -0
- package/dist/src/anticheat/imports.js +419 -0
- package/dist/src/anticheat/tokens.js +177 -0
- package/dist/src/anticheat.js +189 -0
- package/dist/src/card/format.js +113 -0
- package/dist/src/card/svg.js +137 -0
- package/dist/src/card.js +364 -0
- package/dist/src/check.js +139 -0
- package/dist/src/cli.js +333 -0
- package/dist/src/gate/holdout.js +78 -0
- package/dist/src/gate/process.js +78 -0
- package/dist/src/gate.js +532 -0
- package/dist/src/graph.js +148 -0
- package/dist/src/holdout/perturb.js +108 -0
- package/dist/src/holdout/snapshot.js +113 -0
- package/dist/src/init.js +76 -0
- package/dist/src/inputs/generate.js +282 -0
- package/dist/src/inputs.js +273 -0
- package/dist/src/measure.js +149 -0
- package/dist/src/project.js +72 -0
- package/dist/src/record.js +180 -0
- package/dist/src/registry.js +78 -0
- package/dist/src/replacement.js +146 -0
- package/dist/src/runner.js +227 -0
- package/dist/src/runtime/agent-inputs.js +36 -0
- package/dist/src/runtime/child.js +260 -0
- package/dist/src/runtime/esm-hooks.js +44 -0
- package/dist/src/runtime/fsguard.js +264 -0
- package/dist/src/runtime/inspect.js +115 -0
- package/dist/src/runtime/lockdown.js +157 -0
- package/dist/src/runtime/protocol.js +16 -0
- package/dist/src/scan.js +210 -0
- package/dist/src/serialize.js +399 -0
- package/dist/src/tooling.js +88 -0
- package/dist/src/types.js +9 -0
- package/dist/src/usage/common.js +36 -0
- package/dist/src/usage/fallback.js +227 -0
- package/dist/src/usage/ts.js +142 -0
- package/dist/src/usage.js +97 -0
- package/dist/src/util/exports.js +86 -0
- package/dist/src/util/fs.js +64 -0
- package/dist/src/util/term.js +61 -0
- package/package.json +54 -6
- package/skills/AGENTS.section.md +52 -0
- package/skills/depkill/SKILL.md +148 -0
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { availableParallelism, tmpdir } from 'node:os';
|
|
4
|
+
import { basename, dirname, join } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { moduleKey, PROTOCOL_PREFIX } from './runtime/protocol.js';
|
|
7
|
+
const CHILD_PATH = fileURLToPath(new URL('./runtime/child.js', import.meta.url));
|
|
8
|
+
const DEFAULT_CASE_TIMEOUT_MS = 2000;
|
|
9
|
+
const DEFAULT_LOAD_TIMEOUT_MS = 15_000;
|
|
10
|
+
/** Slack per execution on top of caseTimeoutMs, for encoding the result and protocol I/O. */
|
|
11
|
+
const EXECUTION_SLACK_MS = 750;
|
|
12
|
+
const STDERR_TAIL_CHARS = 4000;
|
|
13
|
+
/** Children run side by side on large batches, so many hanging inputs do not add up to minutes. */
|
|
14
|
+
const MAX_LANES = Math.max(1, Math.min(4, availableParallelism()));
|
|
15
|
+
const MIN_CASES_PER_LANE = 16;
|
|
16
|
+
/** Heap cap per child: pathological inputs (e.g. padding to length Infinity) otherwise grow to several GB. */
|
|
17
|
+
const CHILD_HEAP_MB = 1024;
|
|
18
|
+
/** Compiled depkill sources (`dist/src`): child.js and the modules it imports (`../serialize.js`, …). */
|
|
19
|
+
const RUNTIME_ROOT = dirname(dirname(CHILD_PATH));
|
|
20
|
+
/**
|
|
21
|
+
* R31/R32: whether replacement replays run inside Node's permission model. Only the stable `--permission` flag
|
|
22
|
+
* (Node >= 22.13) counts: the older `--experimental-permission` takes a different --allow-fs-read syntax that is
|
|
23
|
+
* not verified, so on those versions the sandbox is reported unavailable (code generation stays disabled).
|
|
24
|
+
*/
|
|
25
|
+
export function replacementSandboxAvailable(flags = process.allowedNodeEnvironmentFlags) {
|
|
26
|
+
return flags.has('--permission');
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Flags for replaying a replacement file (never an original package): no eval / new Function, and — when the
|
|
30
|
+
* sandbox is available — `--permission` with file reads limited to depkill's runtime, the request directory and
|
|
31
|
+
* the replacement (plus its `.depkill/.build` directory for transpiled TypeScript), one `--allow-fs-read` per
|
|
32
|
+
* path. No child processes, workers or writes.
|
|
33
|
+
*/
|
|
34
|
+
export function replacementExecArgv(file, requestDir, flags = process.allowedNodeEnvironmentFlags) {
|
|
35
|
+
const argv = ['--disallow-code-generation-from-strings'];
|
|
36
|
+
if (!replacementSandboxAvailable(flags))
|
|
37
|
+
return argv;
|
|
38
|
+
const dir = dirname(file);
|
|
39
|
+
const inBuild = basename(dir) === '.build' && basename(dirname(dir)) === '.depkill';
|
|
40
|
+
const target = inBuild ? dir : file;
|
|
41
|
+
// Both spellings of the replacement: the loader may open it by its real path (symlinked or 8.3 directories).
|
|
42
|
+
let real = target;
|
|
43
|
+
try {
|
|
44
|
+
real = realpathSync.native(target);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// a missing file fails to load in the child and is reported there
|
|
48
|
+
}
|
|
49
|
+
const reads = [...new Set([RUNTIME_ROOT, requestDir, target, real])];
|
|
50
|
+
return [...argv, '--permission', ...reads.map((path) => `--allow-fs-read=${path}`)];
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* One child process over the request at `requestPath`. A watchdog kills it when a module load exceeds
|
|
54
|
+
* `loadTimeoutMs` or one execution exceeds `caseTimeoutMs` plus slack (a synchronous hang never yields).
|
|
55
|
+
*/
|
|
56
|
+
function spawnChild(requestPath, settings) {
|
|
57
|
+
const env = { ...process.env };
|
|
58
|
+
delete env.NODE_OPTIONS;
|
|
59
|
+
delete env.NODE_TEST_CONTEXT;
|
|
60
|
+
const child = spawn(process.execPath, [`--max-old-space-size=${CHILD_HEAP_MB}`, ...settings.execArgv, CHILD_PATH, requestPath], {
|
|
61
|
+
cwd: settings.cwd, env, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
|
|
62
|
+
});
|
|
63
|
+
const attempt = { messages: [], inProgress: null, timedOut: false, code: null, signal: null, stderr: '' };
|
|
64
|
+
const executionBudget = settings.caseTimeoutMs + EXECUTION_SLACK_MS;
|
|
65
|
+
let timer;
|
|
66
|
+
const arm = (ms) => {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
timer = setTimeout(() => {
|
|
69
|
+
attempt.timedOut = true;
|
|
70
|
+
child.kill('SIGKILL'); // SIGTERM can be trapped by package code; a sync loop never yields to it anyway
|
|
71
|
+
}, ms);
|
|
72
|
+
};
|
|
73
|
+
arm(settings.loadTimeoutMs);
|
|
74
|
+
let buffered = '';
|
|
75
|
+
const onLine = (line) => {
|
|
76
|
+
const at = line.indexOf(PROTOCOL_PREFIX);
|
|
77
|
+
if (at === -1)
|
|
78
|
+
return; // package output
|
|
79
|
+
let message;
|
|
80
|
+
try {
|
|
81
|
+
message = JSON.parse(line.slice(at + PROTOCOL_PREFIX.length));
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
attempt.messages.push(message);
|
|
87
|
+
if (message.t === 'load' || message.t === 'run')
|
|
88
|
+
attempt.inProgress = message;
|
|
89
|
+
arm(message.t === 'load' ? settings.loadTimeoutMs : executionBudget);
|
|
90
|
+
};
|
|
91
|
+
child.stdout.setEncoding('utf8');
|
|
92
|
+
child.stdout.on('data', (chunk) => {
|
|
93
|
+
buffered += chunk;
|
|
94
|
+
const lines = buffered.split('\n');
|
|
95
|
+
buffered = lines.pop() ?? '';
|
|
96
|
+
lines.forEach(onLine);
|
|
97
|
+
});
|
|
98
|
+
child.stderr.setEncoding('utf8');
|
|
99
|
+
child.stderr.on('data', (chunk) => {
|
|
100
|
+
attempt.stderr = (attempt.stderr + chunk).slice(-STDERR_TAIL_CHARS);
|
|
101
|
+
});
|
|
102
|
+
return new Promise((resolve, reject) => {
|
|
103
|
+
child.on('error', (error) => {
|
|
104
|
+
clearTimeout(timer);
|
|
105
|
+
reject(new Error(`Cannot start depkill child process: ${error.message}`, { cause: error }));
|
|
106
|
+
});
|
|
107
|
+
child.on('close', (code, signal) => {
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
onLine(buffered);
|
|
110
|
+
Object.assign(attempt, { code, signal });
|
|
111
|
+
resolve(attempt);
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
function exitText(attempt) {
|
|
116
|
+
return attempt.signal !== null ? `signal ${attempt.signal}` : `code ${attempt.code}`;
|
|
117
|
+
}
|
|
118
|
+
/** Reason recorded for the case (or module) that was in progress when the child stopped early. */
|
|
119
|
+
function blameReason(attempt, phase) {
|
|
120
|
+
if (attempt.timedOut) {
|
|
121
|
+
return phase === 'load' ? 'timeout (module load did not finish)' : 'timeout (synchronous code did not finish)';
|
|
122
|
+
}
|
|
123
|
+
return phase === 'load'
|
|
124
|
+
? `process exited while loading the module (${exitText(attempt)})`
|
|
125
|
+
: `process exited during the call (${exitText(attempt)})`;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Runs `items` in child processes until each has a result. When a child hangs (watchdog) or dies, the case it
|
|
129
|
+
* was running — or every case of the module it was loading — gets `blamed`, and the rest run in a fresh child.
|
|
130
|
+
*/
|
|
131
|
+
async function driveLane(spec, settings, requestPath) {
|
|
132
|
+
const results = new Map();
|
|
133
|
+
let pending = spec.items;
|
|
134
|
+
while (pending.length > 0) {
|
|
135
|
+
const request = { target: spec.target, mode: spec.mode, cases: pending, caseTimeoutMs: settings.caseTimeoutMs, root: settings.cwd };
|
|
136
|
+
writeFileSync(requestPath, JSON.stringify(request));
|
|
137
|
+
const attempt = await spawnChild(requestPath, settings);
|
|
138
|
+
const before = results.size;
|
|
139
|
+
for (const message of attempt.messages) {
|
|
140
|
+
const value = 'id' in message ? spec.result(message) : undefined;
|
|
141
|
+
if (value !== undefined && 'id' in message)
|
|
142
|
+
results.set(message.id, value);
|
|
143
|
+
}
|
|
144
|
+
const progress = attempt.inProgress;
|
|
145
|
+
if (progress?.t === 'run' && !results.has(progress.id)) {
|
|
146
|
+
results.set(progress.id, spec.blamed(blameReason(attempt, 'run')));
|
|
147
|
+
}
|
|
148
|
+
else if (progress?.t === 'load') {
|
|
149
|
+
const reason = blameReason(attempt, 'load');
|
|
150
|
+
for (const item of pending) {
|
|
151
|
+
if (!results.has(item.id) && moduleKey(spec.target, item.exportId) === progress.subpath)
|
|
152
|
+
results.set(item.id, spec.blamed(reason));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
pending = pending.filter((item) => !results.has(item.id));
|
|
156
|
+
if (pending.length > 0 && results.size === before) {
|
|
157
|
+
const tail = attempt.stderr.trim();
|
|
158
|
+
throw new Error(`depkill child process stopped without running any case (${exitText(attempt)})${tail ? `:\n${tail}` : ''}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return results;
|
|
162
|
+
}
|
|
163
|
+
/** Contiguous slices of `items`, one per lane; order inside a lane is preserved. */
|
|
164
|
+
function lanes(items) {
|
|
165
|
+
const count = Math.max(1, Math.min(MAX_LANES, Math.floor(items.length / MIN_CASES_PER_LANE)));
|
|
166
|
+
const size = Math.ceil(items.length / count);
|
|
167
|
+
return Array.from({ length: count }, (_, i) => items.slice(i * size, (i + 1) * size)).filter((lane) => lane.length > 0);
|
|
168
|
+
}
|
|
169
|
+
async function drive(spec, settings) {
|
|
170
|
+
const dir = realpathSync.native(mkdtempSync(join(tmpdir(), 'depkill-run-')));
|
|
171
|
+
try {
|
|
172
|
+
// The request directory is only known here, so the replacement sandbox (R31) is completed here too.
|
|
173
|
+
const run = spec.target.kind === 'file' ? { ...settings, execArgv: replacementExecArgv(spec.target.path, dir, settings.nodeFlags) } : settings;
|
|
174
|
+
const maps = await Promise.all(lanes(spec.items).map((items, i) => driveLane({ ...spec, items }, run, join(dir, `request-${i}.json`))));
|
|
175
|
+
return new Map(maps.flatMap((map) => [...map]));
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
rmSync(dir, { recursive: true, force: true });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function settingsFor(target, opts) {
|
|
182
|
+
return {
|
|
183
|
+
caseTimeoutMs: opts.caseTimeoutMs ?? DEFAULT_CASE_TIMEOUT_MS,
|
|
184
|
+
loadTimeoutMs: opts.loadTimeoutMs ?? DEFAULT_LOAD_TIMEOUT_MS,
|
|
185
|
+
cwd: opts.cwd ?? (target.kind === 'package' ? target.resolveFrom : dirname(target.path)),
|
|
186
|
+
execArgv: [],
|
|
187
|
+
nodeFlags: opts.nodeFlags,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
function assertUniqueIds(items) {
|
|
191
|
+
const seen = new Set();
|
|
192
|
+
for (const { id } of items) {
|
|
193
|
+
if (seen.has(id))
|
|
194
|
+
throw new Error(`Duplicate case id: ${id}`);
|
|
195
|
+
seen.add(id);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Executes each case against `target` in isolated child Node processes (env without NODE_OPTIONS) and
|
|
200
|
+
* returns the cases, in order, with their recorded outcome. Each case runs twice in the same child (differing
|
|
201
|
+
* results are `nondeterministic`); hangs, crashes and `process.exit` calls become `unsupported` for the case
|
|
202
|
+
* responsible. Large batches are split into a few contiguous lanes that run in parallel.
|
|
203
|
+
*/
|
|
204
|
+
export async function runCases(target, cases, opts = {}) {
|
|
205
|
+
if (cases.length === 0)
|
|
206
|
+
return [];
|
|
207
|
+
assertUniqueIds(cases);
|
|
208
|
+
const outcomes = await drive({
|
|
209
|
+
target, mode: 'cases', items: cases,
|
|
210
|
+
result: (message) => (message.t === 'done' ? message.outcome : undefined),
|
|
211
|
+
blamed: (reason) => ({ kind: 'unsupported', reason }),
|
|
212
|
+
}, settingsFor(target, opts));
|
|
213
|
+
return cases.map((c) => ({ ...c, outcome: outcomes.get(c.id) }));
|
|
214
|
+
}
|
|
215
|
+
/** Runtime kind of each export id (function / value / unloadable), loaded the same way runCases loads it. */
|
|
216
|
+
export async function probeExports(target, exportIds, opts = {}) {
|
|
217
|
+
const unique = [...new Set(exportIds)];
|
|
218
|
+
if (unique.length === 0)
|
|
219
|
+
return {};
|
|
220
|
+
const items = unique.map((exportId) => ({ id: exportId, exportId, source: 'generated', args: [] }));
|
|
221
|
+
const kinds = await drive({
|
|
222
|
+
target, mode: 'probe', items,
|
|
223
|
+
result: (message) => (message.t === 'kind' ? message.kind : undefined),
|
|
224
|
+
blamed: () => 'unloadable',
|
|
225
|
+
}, settingsFor(target, opts));
|
|
226
|
+
return Object.fromEntries(unique.map((id) => [id, kinds.get(id)]));
|
|
227
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// `node agent-inputs.js <inputs.mjs> <out.json>`: loads an agent-written inputs module in its own process
|
|
2
|
+
// (fresh module cache, project code isolated from depkill) and writes `{ inputs }` or `{ error }` as JSON.
|
|
3
|
+
// Arguments are encoded here so non-JSON values (undefined, NaN, -0, Map, ...) survive.
|
|
4
|
+
import { writeFileSync } from 'node:fs';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { encode } from '../serialize.js';
|
|
7
|
+
function isRecord(value) {
|
|
8
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
async function load(file) {
|
|
11
|
+
let mod;
|
|
12
|
+
try {
|
|
13
|
+
mod = (await import(pathToFileURL(file).href));
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
return { error: `cannot load: ${error instanceof Error ? error.message : String(error)}` };
|
|
17
|
+
}
|
|
18
|
+
const table = mod.default;
|
|
19
|
+
if (!isRecord(table))
|
|
20
|
+
return { error: 'the default export must be an object mapping export ids to argument lists' };
|
|
21
|
+
const inputs = {};
|
|
22
|
+
for (const [exportId, lists] of Object.entries(table)) {
|
|
23
|
+
if (!Array.isArray(lists) || !lists.every((args) => Array.isArray(args))) {
|
|
24
|
+
return { error: `"${exportId}" must be an array of argument arrays, e.g. [['a', 1], ['b', 2]]` };
|
|
25
|
+
}
|
|
26
|
+
inputs[exportId] = lists.map((args) => encode(args));
|
|
27
|
+
}
|
|
28
|
+
return { inputs };
|
|
29
|
+
}
|
|
30
|
+
const [file, out] = process.argv.slice(2);
|
|
31
|
+
if (file === undefined || out === undefined) {
|
|
32
|
+
process.stderr.write('usage: agent-inputs.js <inputs.mjs> <out.json>\n');
|
|
33
|
+
process.exit(2);
|
|
34
|
+
}
|
|
35
|
+
writeFileSync(out, JSON.stringify(await load(file)));
|
|
36
|
+
process.exit(0);
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// Entry point of the isolated child process spawned by runner.ts: `node child.js <request.json>`.
|
|
2
|
+
// Loads the package (or a replacement file), executes each case twice, and reports one protocol line per
|
|
3
|
+
// step on stdout. Everything the package itself prints is diverted to stderr.
|
|
4
|
+
import { readFileSync } from 'node:fs';
|
|
5
|
+
import { createRequire, isBuiltin } from 'node:module';
|
|
6
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { decode, encode, outcomesEqual } from '../serialize.js';
|
|
9
|
+
import { findPackageDir, IMPORT_CONDITIONS, resolveExports } from '../util/exports.js';
|
|
10
|
+
import { findTag, liveValueReason, opaqueCtor } from './inspect.js';
|
|
11
|
+
import { lockDownForReplacement } from './lockdown.js';
|
|
12
|
+
import { exportName, moduleKey, PROTOCOL_PREFIX } from './protocol.js';
|
|
13
|
+
/** Keeps the real stdout for protocol lines and points `process.stdout.write` (and so console.log) at stderr. */
|
|
14
|
+
function takeOverStdout() {
|
|
15
|
+
const protocolWrite = process.stdout.write.bind(process.stdout);
|
|
16
|
+
process.stdout.write = process.stderr.write.bind(process.stderr);
|
|
17
|
+
// The leading newline ends any partial line the package wrote straight to fd 1.
|
|
18
|
+
// Waiting for the write callback means the line has left this process before the next step can hang.
|
|
19
|
+
return (message) => new Promise((done) => {
|
|
20
|
+
protocolWrite(`\n${PROTOCOL_PREFIX}${JSON.stringify(message)}\n`, () => done());
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function errorMessage(error) {
|
|
24
|
+
try {
|
|
25
|
+
return error instanceof Error ? error.message : String(error);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return '<unreadable error>';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** Entry file of `name + subpath`: CommonJS resolution first, then the `exports` map's import conditions. */
|
|
32
|
+
function resolvePackageEntry(name, subpath, resolveFrom) {
|
|
33
|
+
const specifier = name + subpath;
|
|
34
|
+
let firstError = null;
|
|
35
|
+
try {
|
|
36
|
+
const resolved = createRequire(join(resolveFrom, 'package.json')).resolve(specifier);
|
|
37
|
+
if (isAbsolute(resolved) && !isBuiltin(resolved))
|
|
38
|
+
return resolved;
|
|
39
|
+
// A bare result is a Node builtin shadowing the npm package of the same name: find the package itself.
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
firstError = error; // e.g. ERR_PACKAGE_PATH_NOT_EXPORTED for import-only exports
|
|
43
|
+
}
|
|
44
|
+
const dir = findPackageDir(name, resolveFrom);
|
|
45
|
+
if (dir === null)
|
|
46
|
+
throw firstError ?? new Error(`Cannot find package "${name}" from ${resolveFrom}`);
|
|
47
|
+
const manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
|
|
48
|
+
if (manifest.exports !== undefined) {
|
|
49
|
+
const target = resolveExports(manifest.exports, `.${subpath}`, IMPORT_CONDITIONS);
|
|
50
|
+
if (target === null)
|
|
51
|
+
throw firstError ?? new Error(`"${specifier}" is not exported by ${join(dir, 'package.json')}`);
|
|
52
|
+
return resolve(dir, target);
|
|
53
|
+
}
|
|
54
|
+
// No exports map: main / index resolution against the package directory itself.
|
|
55
|
+
return createRequire(join(dir, 'package.json')).resolve(join(dir, ...subpath.split('/').filter((part) => part !== '')));
|
|
56
|
+
}
|
|
57
|
+
function createLoader(target, send) {
|
|
58
|
+
const cache = new Map();
|
|
59
|
+
return async (exportId) => {
|
|
60
|
+
const key = moduleKey(target, exportId);
|
|
61
|
+
const cached = cache.get(key);
|
|
62
|
+
if (cached !== undefined)
|
|
63
|
+
return cached;
|
|
64
|
+
await send({ t: 'load', subpath: key });
|
|
65
|
+
let loaded;
|
|
66
|
+
try {
|
|
67
|
+
const file = target.kind === 'file' ? target.path : resolvePackageEntry(target.name, key, target.resolveFrom);
|
|
68
|
+
loaded = { ok: true, mod: (await import(pathToFileURL(file).href)) };
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
loaded = { ok: false, error: errorMessage(error) };
|
|
72
|
+
}
|
|
73
|
+
cache.set(key, loaded);
|
|
74
|
+
return loaded;
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function isObjectLike(value) {
|
|
78
|
+
return (typeof value === 'object' && value !== null) || typeof value === 'function';
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Transpiled ES modules in CommonJS (`exports.__esModule = true; exports.default = fn`): `import()` yields
|
|
82
|
+
* `module.exports` as the default, but every consumer (TS/Babel `__importDefault`, bundlers) uses
|
|
83
|
+
* `exports.default`, so that is the default export.
|
|
84
|
+
*/
|
|
85
|
+
function interopDefault(value) {
|
|
86
|
+
if (value === null || typeof value !== 'object')
|
|
87
|
+
return value;
|
|
88
|
+
const exportsObject = value;
|
|
89
|
+
return exportsObject.__esModule === true && Object.hasOwn(exportsObject, 'default') ? exportsObject.default : value;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The export and the `this` a project call would use: `#default` is the default export (or the namespace when
|
|
93
|
+
* there is none; `exports.default` for transpiled CJS), `#*` the namespace, other names the named export or a
|
|
94
|
+
* property of the default export (CommonJS `module.exports`, which then is also `this`), or of a transpiled
|
|
95
|
+
* CJS module's `exports.default` object. `value` undefined means the export does not exist (R26).
|
|
96
|
+
*
|
|
97
|
+
* `strict` (replacement files, R28): those interop fallbacks model how the project consumed the ORIGINAL, but
|
|
98
|
+
* the project will `import` the replacement directly, so only what that import yields counts: `#default` is
|
|
99
|
+
* `mod.default` exactly, `#name` is `mod[name]` exactly.
|
|
100
|
+
*/
|
|
101
|
+
function lookup(mod, name, strict) {
|
|
102
|
+
if (name === '*')
|
|
103
|
+
return { value: mod, thisArg: undefined };
|
|
104
|
+
if (strict) {
|
|
105
|
+
if (name === 'default')
|
|
106
|
+
return { value: mod.default, thisArg: undefined };
|
|
107
|
+
const own = mod[name];
|
|
108
|
+
const holder = mod.default;
|
|
109
|
+
// CommonJS `exports.f` is also `module.exports.f`; a `pkg.f()` call has `module.exports` as `this`.
|
|
110
|
+
return { value: own, thisArg: own !== undefined && isObjectLike(holder) && holder[name] === own ? holder : undefined };
|
|
111
|
+
}
|
|
112
|
+
if (name === 'default')
|
|
113
|
+
return { value: 'default' in mod ? interopDefault(mod.default) : mod, thisArg: undefined };
|
|
114
|
+
const holder = mod.default;
|
|
115
|
+
const own = mod[name];
|
|
116
|
+
if (own !== undefined) {
|
|
117
|
+
return { value: own, thisArg: isObjectLike(holder) && holder[name] === own ? holder : undefined };
|
|
118
|
+
}
|
|
119
|
+
const member = isObjectLike(holder) ? holder[name] : undefined;
|
|
120
|
+
if (member !== undefined)
|
|
121
|
+
return { value: member, thisArg: holder };
|
|
122
|
+
const inner = interopDefault(holder);
|
|
123
|
+
if (inner !== holder && isObjectLike(inner))
|
|
124
|
+
return { value: inner[name], thisArg: inner };
|
|
125
|
+
return { value: undefined, thisArg: holder };
|
|
126
|
+
}
|
|
127
|
+
function thenOf(value) {
|
|
128
|
+
if (!isObjectLike(value))
|
|
129
|
+
return null;
|
|
130
|
+
try {
|
|
131
|
+
const then = value.then;
|
|
132
|
+
return typeof then === 'function' ? then : null;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function thrownOutcome(thrown) {
|
|
139
|
+
const e = encode(thrown);
|
|
140
|
+
if (e !== null && typeof e === 'object' && !Array.isArray(e) && typeof e.$err === 'string' && typeof e.message === 'string') {
|
|
141
|
+
return { kind: 'throw', name: e.$err, message: e.message };
|
|
142
|
+
}
|
|
143
|
+
return { kind: 'throw', name: 'NonError', message: JSON.stringify(e) };
|
|
144
|
+
}
|
|
145
|
+
function settle(thenable, timeoutMs) {
|
|
146
|
+
return new Promise((done) => {
|
|
147
|
+
const timer = setTimeout(() => done({ status: 'timeout' }), timeoutMs);
|
|
148
|
+
Promise.resolve(thenable).then((value) => { clearTimeout(timer); done({ status: 'fulfilled', value }); }, (reason) => { clearTimeout(timer); done({ status: 'rejected', reason }); });
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* `return` outcome, unless the raw result is live (stream/emitter/timer), encodes to an opaque value, or (for
|
|
153
|
+
* calls) contains a function: `{ $fn: name }` only records a name, so any same-named function would match (R25).
|
|
154
|
+
* `snapshot` results (non-callable exports read with no arguments, including `#*`) may contain functions.
|
|
155
|
+
*/
|
|
156
|
+
function returnOutcome(raw, value, args, snapshot) {
|
|
157
|
+
const live = liveValueReason(raw, 'returns') ?? liveValueReason(args, 'leaves in its arguments');
|
|
158
|
+
if (live !== null)
|
|
159
|
+
return { kind: 'unsupported', reason: live };
|
|
160
|
+
const argsAfter = encode(args);
|
|
161
|
+
const opaque = opaqueCtor(value) ?? opaqueCtor(argsAfter);
|
|
162
|
+
if (opaque !== null)
|
|
163
|
+
return { kind: 'unsupported', reason: `opaque value ${opaque}` };
|
|
164
|
+
if (!snapshot && (findTag(value, '$fn') !== null || findTag(argsAfter, '$fn') !== null)) {
|
|
165
|
+
return { kind: 'unsupported', reason: 'returns a function' };
|
|
166
|
+
}
|
|
167
|
+
return { kind: 'return', value, argsAfter };
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* One execution. Async results are tagged (`{ $async: 'fulfilled', value }` / `{ $async: 'rejected', reason }`)
|
|
171
|
+
* so a promise never compares equal to the plain value or a synchronous throw.
|
|
172
|
+
*/
|
|
173
|
+
async function execute(mod, c, timeoutMs, strict) {
|
|
174
|
+
const args = decode(c.args);
|
|
175
|
+
let raw;
|
|
176
|
+
let snapshot = false;
|
|
177
|
+
try {
|
|
178
|
+
const { value, thisArg } = lookup(mod, exportName(c.exportId), strict);
|
|
179
|
+
// A missing export must never "return undefined": a replacement lacking it would match an undefined original.
|
|
180
|
+
if (value === undefined)
|
|
181
|
+
return { kind: 'unsupported', reason: 'export not found' };
|
|
182
|
+
if (typeof value === 'function') {
|
|
183
|
+
// Arguments decode functions to no-op stubs whose calls are never observed: no evidence either way.
|
|
184
|
+
if (findTag(c.args, '$fn') !== null)
|
|
185
|
+
return { kind: 'unsupported', reason: 'takes a function argument' };
|
|
186
|
+
raw = Reflect.apply(value, thisArg, args);
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
if (args.length > 0)
|
|
190
|
+
return { kind: 'unsupported', reason: 'export is not callable' };
|
|
191
|
+
raw = value;
|
|
192
|
+
snapshot = true;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
return thrownOutcome(error);
|
|
197
|
+
}
|
|
198
|
+
if (thenOf(raw) === null)
|
|
199
|
+
return returnOutcome(raw, encode(raw), args, snapshot);
|
|
200
|
+
const settled = await settle(raw, timeoutMs);
|
|
201
|
+
if (settled.status === 'timeout')
|
|
202
|
+
return { kind: 'unsupported', reason: 'timeout (promise never settled)' };
|
|
203
|
+
if (settled.status === 'fulfilled') {
|
|
204
|
+
return returnOutcome(settled.value, { $async: 'fulfilled', value: encode(settled.value) }, args, snapshot);
|
|
205
|
+
}
|
|
206
|
+
return returnOutcome(settled.reason, { $async: 'rejected', reason: encode(settled.reason) }, args, snapshot);
|
|
207
|
+
}
|
|
208
|
+
/** Runs a case twice (announcing each pass); differing outcomes are nondeterministic. */
|
|
209
|
+
async function runCase(mod, c, timeoutMs, strict, send) {
|
|
210
|
+
await send({ t: 'run', id: c.id, pass: 1 });
|
|
211
|
+
const first = await execute(mod, c, timeoutMs, strict);
|
|
212
|
+
if (first.kind === 'unsupported')
|
|
213
|
+
return first;
|
|
214
|
+
await send({ t: 'run', id: c.id, pass: 2 });
|
|
215
|
+
const second = await execute(mod, c, timeoutMs, strict);
|
|
216
|
+
if (second.kind === 'unsupported')
|
|
217
|
+
return second;
|
|
218
|
+
return outcomesEqual(first, second) ? first : { kind: 'nondeterministic' };
|
|
219
|
+
}
|
|
220
|
+
function kindOf(mod, exportId, strict) {
|
|
221
|
+
try {
|
|
222
|
+
return typeof lookup(mod, exportName(exportId), strict).value === 'function' ? 'function' : 'value';
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return 'value';
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
async function main() {
|
|
229
|
+
const requestPath = process.argv[2];
|
|
230
|
+
if (requestPath === undefined)
|
|
231
|
+
throw new Error('usage: child.js <request.json>');
|
|
232
|
+
const request = JSON.parse(readFileSync(requestPath, 'utf8'));
|
|
233
|
+
const send = takeOverStdout();
|
|
234
|
+
// Stray async errors from package code must not kill the remaining cases.
|
|
235
|
+
process.on('uncaughtException', (error) => process.stderr.write(`depkill child: uncaught ${errorMessage(error)}\n`));
|
|
236
|
+
process.on('unhandledRejection', (reason) => process.stderr.write(`depkill child: unhandled rejection ${errorMessage(reason)}\n`));
|
|
237
|
+
// R33: a replacement may not reach the original package, other code or the network (never applied to originals).
|
|
238
|
+
if (request.target.kind === 'file')
|
|
239
|
+
lockDownForReplacement(request.target.path, request.root);
|
|
240
|
+
const load = createLoader(request.target, send);
|
|
241
|
+
const strict = request.target.kind === 'file';
|
|
242
|
+
for (const c of request.cases) {
|
|
243
|
+
const loaded = await load(c.exportId);
|
|
244
|
+
if (request.mode === 'probe') {
|
|
245
|
+
await send({ t: 'run', id: c.id, pass: 1 });
|
|
246
|
+
await send({ t: 'kind', id: c.id, kind: loaded.ok ? kindOf(loaded.mod, c.exportId, strict) : 'unloadable' });
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
const outcome = loaded.ok
|
|
250
|
+
? await runCase(loaded.mod, c, request.caseTimeoutMs, strict, send)
|
|
251
|
+
: { kind: 'unsupported', reason: `cannot load module: ${loaded.error}` };
|
|
252
|
+
await send({ t: 'done', id: c.id, outcome });
|
|
253
|
+
}
|
|
254
|
+
// Package handles (servers, intervals) must not keep the child alive.
|
|
255
|
+
process.exit(0);
|
|
256
|
+
}
|
|
257
|
+
main().catch((error) => {
|
|
258
|
+
process.stderr.write(`depkill child failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
|
|
259
|
+
process.exit(70);
|
|
260
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Worker-thread ESM resolve hook for Node 20.6–22.14 where Module.registerHooks is unavailable.
|
|
2
|
+
import { isBuiltin } from 'node:module';
|
|
3
|
+
let allowedUrls = new Set();
|
|
4
|
+
let allowedBuiltins = new Set();
|
|
5
|
+
let foldCase = false;
|
|
6
|
+
const fold = (value) => (foldCase ? value.toLowerCase() : value);
|
|
7
|
+
const isDenied = (specifier) => {
|
|
8
|
+
if (!isBuiltin(specifier))
|
|
9
|
+
return false;
|
|
10
|
+
const bare = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier;
|
|
11
|
+
return !allowedBuiltins.has(bare);
|
|
12
|
+
};
|
|
13
|
+
function denied(specifier) {
|
|
14
|
+
return Object.assign(new Error(`depkill sandbox: "${specifier}" is not available to a replacement`), {
|
|
15
|
+
code: 'ERR_DEPKILL_DENIED',
|
|
16
|
+
});
|
|
17
|
+
}
|
|
18
|
+
export function initialize(data) {
|
|
19
|
+
foldCase = data.foldCase;
|
|
20
|
+
allowedUrls = new Set(data.urls);
|
|
21
|
+
allowedBuiltins = new Set(data.allowedBuiltins);
|
|
22
|
+
}
|
|
23
|
+
export async function resolve(specifier, context, nextResolve) {
|
|
24
|
+
if (isBuiltin(specifier)) {
|
|
25
|
+
if (isDenied(specifier))
|
|
26
|
+
throw denied(specifier);
|
|
27
|
+
return nextResolve(specifier, context);
|
|
28
|
+
}
|
|
29
|
+
let result;
|
|
30
|
+
try {
|
|
31
|
+
result = await nextResolve(specifier, context);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
throw denied(specifier);
|
|
35
|
+
}
|
|
36
|
+
if (result.url.startsWith('node:')) {
|
|
37
|
+
if (isDenied(result.url))
|
|
38
|
+
throw denied(specifier);
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
if (!allowedUrls.has(fold(result.url)))
|
|
42
|
+
throw denied(specifier);
|
|
43
|
+
return result;
|
|
44
|
+
}
|