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,264 @@
|
|
|
1
|
+
// R38: the `fs` a replacement sees is a guarded view — every path it passes must resolve (through symlinks) to a
|
|
2
|
+
// file inside the project root, outside `<root>/.depkill` and outside any `node_modules`. This blocks reading the
|
|
3
|
+
// recorded cases or the original package even on Node without the stable permission model.
|
|
4
|
+
//
|
|
5
|
+
// The builtin's exports are patched in place (`fs`, `fs.promises` = `fs/promises`, with and without `node:`), then
|
|
6
|
+
// `syncBuiltinESMExports()` pushes the patched functions to ESM named imports, so `require('fs')`,
|
|
7
|
+
// `import fs from 'node:fs'`, `import { readFileSync } from 'fs'` and `process.getBuiltinModule('fs')` all agree.
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import { syncBuiltinESMExports } from 'node:module';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { fileURLToPath } from 'node:url';
|
|
12
|
+
import { types } from 'node:util';
|
|
13
|
+
const read = [[0, 'read']];
|
|
14
|
+
const write = [[0, 'write']];
|
|
15
|
+
/** Source read, destination written (copy, link, symlink target → link path). */
|
|
16
|
+
const copy = [[0, 'read'], [1, 'write']];
|
|
17
|
+
const move = [[0, 'write'], [1, 'write']];
|
|
18
|
+
/**
|
|
19
|
+
* R40: every path-taking function of `fs` (callback and Sync forms) and `fs.promises`, with its path positions.
|
|
20
|
+
* Sources and destinations are both checked for copy/link/rename/symlink, so a replacement cannot plant a copy,
|
|
21
|
+
* link or symlink to `.depkill` / `node_modules` content inside the project.
|
|
22
|
+
*/
|
|
23
|
+
export const FS_PATH_RULES = Object.fromEntries(Object.entries({
|
|
24
|
+
access: read, exists: read, lstat: read, open: read, opendir: read, readdir: read, readFile: read,
|
|
25
|
+
readlink: read, realpath: read, stat: read, statfs: read, watch: read, watchFile: read, unwatchFile: read,
|
|
26
|
+
createReadStream: read, openAsBlob: read,
|
|
27
|
+
appendFile: write, chmod: write, chown: write, lchmod: write, lchown: write, lutimes: write, mkdir: write,
|
|
28
|
+
mkdtemp: write, mkdtempDisposable: write, rm: write, rmdir: write, truncate: write, unlink: write, utimes: write, writeFile: write,
|
|
29
|
+
createWriteStream: write,
|
|
30
|
+
copyFile: copy, cp: copy, link: copy, symlink: copy, rename: move,
|
|
31
|
+
}).flatMap(([name, rule]) => [[name, rule], [`${name}Sync`, rule]]));
|
|
32
|
+
/** Functions that take only file descriptors (or no path at all): passed through unchanged. */
|
|
33
|
+
export const FS_NO_PATH = new Set([
|
|
34
|
+
'close', 'fchown', 'fchmod', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'read', 'readv', 'write', 'writev',
|
|
35
|
+
].flatMap((name) => [name, `${name}Sync`]).concat(['_toUnixTimestamp']));
|
|
36
|
+
/** Pattern-based APIs a path check cannot judge: denied outright. Any function not listed anywhere is denied too. */
|
|
37
|
+
export const FS_DENIED = new Set(['glob', 'globSync']);
|
|
38
|
+
const FOLD_CASE = process.platform === 'win32' || process.platform === 'darwin';
|
|
39
|
+
/**
|
|
40
|
+
* R45: the guard runs in the same realm as the replacement, so it uses only intrinsics captured when it is installed
|
|
41
|
+
* (before any replacement code runs) and never a method looked up on a prototype at call time: a replacement may
|
|
42
|
+
* patch `Buffer.prototype`, `String.prototype`, `Function.prototype.apply`, array iterators, `process.cwd` …
|
|
43
|
+
*/
|
|
44
|
+
function captureIntrinsics() {
|
|
45
|
+
return {
|
|
46
|
+
apply: Reflect.apply,
|
|
47
|
+
getPrototypeOf: Reflect.getPrototypeOf,
|
|
48
|
+
hasOwn: Object.hasOwn,
|
|
49
|
+
assign: Object.assign,
|
|
50
|
+
objectToString: Object.prototype.toString,
|
|
51
|
+
stringPrototype: String.prototype,
|
|
52
|
+
toLowerCase: String.prototype.toLowerCase,
|
|
53
|
+
isProxy: types.isProxy,
|
|
54
|
+
isUint8Array: types.isUint8Array,
|
|
55
|
+
Uint8Array,
|
|
56
|
+
URL,
|
|
57
|
+
urlToString: URL.prototype.toString,
|
|
58
|
+
decoder: new TextDecoder('utf-8', { ignoreBOM: true }),
|
|
59
|
+
decode: TextDecoder.prototype.decode,
|
|
60
|
+
fileURLToPath,
|
|
61
|
+
resolve: path.resolve,
|
|
62
|
+
relative: path.relative,
|
|
63
|
+
isAbsolute: path.isAbsolute,
|
|
64
|
+
dirname: path.dirname,
|
|
65
|
+
basename: path.basename,
|
|
66
|
+
join: path.join,
|
|
67
|
+
cwd: process.cwd,
|
|
68
|
+
realpath: fs.realpathSync.native,
|
|
69
|
+
fsConstants: fs.constants,
|
|
70
|
+
Error,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/** First path segment, and whether any segment is `node_modules`: scanned by index, no prototype methods. */
|
|
74
|
+
function segments(value) {
|
|
75
|
+
let first = null;
|
|
76
|
+
let current = '';
|
|
77
|
+
let nodeModules = false;
|
|
78
|
+
for (let i = 0; i <= value.length; i++) {
|
|
79
|
+
const ch = i < value.length ? value[i] : '/';
|
|
80
|
+
if (ch === '/' || ch === '\\') {
|
|
81
|
+
if (first === null)
|
|
82
|
+
first = current;
|
|
83
|
+
if (current === 'node_modules')
|
|
84
|
+
nodeModules = true;
|
|
85
|
+
current = '';
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
current += ch;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return { first: first ?? '', nodeModules };
|
|
92
|
+
}
|
|
93
|
+
export function guardFs(root, allowed) {
|
|
94
|
+
const $ = captureIntrinsics();
|
|
95
|
+
const fold = (value) => (FOLD_CASE ? $.apply($.toLowerCase, value, []) : value);
|
|
96
|
+
const real = (value) => {
|
|
97
|
+
let cur = value;
|
|
98
|
+
let suffix = '';
|
|
99
|
+
for (;;) {
|
|
100
|
+
try {
|
|
101
|
+
const base = $.realpath(cur);
|
|
102
|
+
return suffix === '' ? base : $.join(base, suffix);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
const parent = $.dirname(cur);
|
|
106
|
+
if (parent === cur)
|
|
107
|
+
return value;
|
|
108
|
+
const part = $.basename(cur);
|
|
109
|
+
suffix = suffix === '' ? part : $.join(part, suffix);
|
|
110
|
+
cur = parent;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const fail = (message) => {
|
|
115
|
+
throw $.assign(new $.Error(`depkill sandbox: ${message}`), { code: 'ERR_DEPKILL_DENIED' });
|
|
116
|
+
};
|
|
117
|
+
const verb = (mode) => (mode === 'read' ? 'reading' : 'writing');
|
|
118
|
+
const rootReal = fold(real($.resolve(root)));
|
|
119
|
+
/** Null-prototype lookup table: a patched `Set.prototype.has` cannot widen it. */
|
|
120
|
+
const exempt = Object.create(null);
|
|
121
|
+
for (const file of allowed) {
|
|
122
|
+
exempt[fold($.resolve(file))] = true;
|
|
123
|
+
exempt[fold(real(file))] = true;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* R45: the one string a path argument names, computed once from intrinsics: a string as is; a Buffer/Uint8Array
|
|
127
|
+
* from an intrinsic copy of its bytes; a URL from its intrinsic serialisation, re-parsed into a fresh URL (own
|
|
128
|
+
* getters on the argument are never read). null for a file descriptor (a number, which only a guarded open can
|
|
129
|
+
* produce). Anything else is refused.
|
|
130
|
+
*/
|
|
131
|
+
const pathString = (value, mode) => {
|
|
132
|
+
if (typeof value === 'number')
|
|
133
|
+
return null;
|
|
134
|
+
if (typeof value === 'string')
|
|
135
|
+
return value;
|
|
136
|
+
if ($.isUint8Array(value))
|
|
137
|
+
return $.apply($.decode, $.decoder, [new $.Uint8Array(value)]);
|
|
138
|
+
if (typeof value === 'object' && value !== null && !$.isProxy(value)) {
|
|
139
|
+
let href;
|
|
140
|
+
try {
|
|
141
|
+
href = $.apply($.urlToString, value, []);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// not a URL instance (the brand check failed)
|
|
145
|
+
}
|
|
146
|
+
if (href !== undefined) {
|
|
147
|
+
try {
|
|
148
|
+
return $.fileURLToPath(new $.URL(href));
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return fail(`${verb(mode)} ${href} is not allowed (not a file: URL)`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return fail(`${verb(mode)} a path given as ${$.apply($.objectToString, value, [])} is not allowed (pass a string, Buffer or URL)`);
|
|
156
|
+
};
|
|
157
|
+
/**
|
|
158
|
+
* Node's fs treats any path value whose prototype chain has an `href` as a URL (its internal `isURL`), so a polluted
|
|
159
|
+
* `String.prototype` would turn the checked string into a different file. Checked without running any getter.
|
|
160
|
+
*/
|
|
161
|
+
const assertNotUrlLike = () => {
|
|
162
|
+
for (let proto = $.stringPrototype; proto !== null; proto = $.getPrototypeOf(proto)) {
|
|
163
|
+
if ($.isProxy(proto) || $.hasOwn(proto, 'href'))
|
|
164
|
+
fail('String.prototype was patched to look like a URL');
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
/** `value` made absolute against `base` or the real working directory (never through a patched process.cwd). */
|
|
168
|
+
const absolute = (value, mode, base) => {
|
|
169
|
+
if (value.length >= 2 && value[1] === ':' && !$.isAbsolute(value))
|
|
170
|
+
fail(`${verb(mode)} a drive-relative path (${value}) is not allowed`);
|
|
171
|
+
return $.resolve(base ?? $.apply($.cwd, process, []), value);
|
|
172
|
+
};
|
|
173
|
+
const assertAllowed = (shown, abs, mode) => {
|
|
174
|
+
const target = fold(real(abs));
|
|
175
|
+
if (exempt[target] === true || exempt[fold(abs)] === true)
|
|
176
|
+
return;
|
|
177
|
+
const rel = $.relative(rootReal, target);
|
|
178
|
+
const { first, nodeModules } = segments(rel);
|
|
179
|
+
const outside = rel === '' ? false : $.isAbsolute(rel) || first === '..';
|
|
180
|
+
if (outside || first === '.depkill' || nodeModules || segments(fold(abs)).nodeModules)
|
|
181
|
+
fail(`${verb(mode)} ${shown} is not allowed`);
|
|
182
|
+
};
|
|
183
|
+
const WRITE_OPEN_FLAGS = $.fsConstants.O_WRONLY | $.fsConstants.O_RDWR | $.fsConstants.O_CREAT | $.fsConstants.O_TRUNC | $.fsConstants.O_APPEND;
|
|
184
|
+
const assertReadOnlyOpen = (flags) => {
|
|
185
|
+
if (flags === undefined)
|
|
186
|
+
return;
|
|
187
|
+
if (typeof flags === 'string') {
|
|
188
|
+
if (flags === 'r' || flags === 'rs' || flags === 'sr')
|
|
189
|
+
return;
|
|
190
|
+
fail('writing is not allowed');
|
|
191
|
+
}
|
|
192
|
+
if (typeof flags === 'number' && (flags & WRITE_OPEN_FLAGS) === 0)
|
|
193
|
+
return;
|
|
194
|
+
fail('writing is not allowed');
|
|
195
|
+
};
|
|
196
|
+
/**
|
|
197
|
+
* Normalises and checks every path argument of `rule` in place (R45: fs receives exactly the absolute string that
|
|
198
|
+
* was checked). m1: all write operations (and non-read open flags) are denied even inside the project root.
|
|
199
|
+
*/
|
|
200
|
+
const checkArgs = (name, rule, args) => {
|
|
201
|
+
if (name === 'open' || name === 'openSync')
|
|
202
|
+
assertReadOnlyOpen(args[1]);
|
|
203
|
+
const isSymlink = name === 'symlink' || name === 'symlinkSync';
|
|
204
|
+
let linkDir;
|
|
205
|
+
let writes = false;
|
|
206
|
+
for (let i = rule.length - 1; i >= 0; i--) {
|
|
207
|
+
const position = rule[i][0];
|
|
208
|
+
const mode = rule[i][1];
|
|
209
|
+
if (mode === 'write')
|
|
210
|
+
writes = true;
|
|
211
|
+
const value = pathString(args[position], mode);
|
|
212
|
+
if (value === null)
|
|
213
|
+
continue;
|
|
214
|
+
assertNotUrlLike();
|
|
215
|
+
if (isSymlink && position === 0) {
|
|
216
|
+
// Where the link will point (relative to its directory) and, conservatively, the target read from the cwd.
|
|
217
|
+
assertAllowed(value, absolute(value, mode, linkDir), mode);
|
|
218
|
+
assertAllowed(value, absolute(value, mode), mode);
|
|
219
|
+
args[position] = value;
|
|
220
|
+
}
|
|
221
|
+
else {
|
|
222
|
+
const abs = absolute(value, mode);
|
|
223
|
+
assertAllowed(value, abs, mode);
|
|
224
|
+
args[position] = abs;
|
|
225
|
+
if (isSymlink)
|
|
226
|
+
linkDir = $.dirname(abs);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (writes)
|
|
230
|
+
fail('writing is not allowed');
|
|
231
|
+
};
|
|
232
|
+
const denied = (name) => function deniedFs() {
|
|
233
|
+
return fail(`fs.${name} is not available to a replacement`);
|
|
234
|
+
};
|
|
235
|
+
const wrap = (name, rule, original) => {
|
|
236
|
+
const guarded = function guardedFs(...args) {
|
|
237
|
+
checkArgs(name, rule, args);
|
|
238
|
+
return $.apply(original, this, args);
|
|
239
|
+
};
|
|
240
|
+
// realpath(Sync).native and friends.
|
|
241
|
+
for (const key of Object.keys(original)) {
|
|
242
|
+
const sub = original[key];
|
|
243
|
+
if (typeof sub === 'function')
|
|
244
|
+
guarded[key] = wrap(name, rule, sub);
|
|
245
|
+
}
|
|
246
|
+
return guarded;
|
|
247
|
+
};
|
|
248
|
+
const patch = (target) => {
|
|
249
|
+
for (const name of Object.keys(target)) {
|
|
250
|
+
const value = target[name];
|
|
251
|
+
// Classes (Stats, ReadStream, Dir…) open paths through the patched functions; FS_NO_PATH functions take fds.
|
|
252
|
+
if (typeof value !== 'function' || !/^[a-z_]/.test(name) || FS_NO_PATH.has(name))
|
|
253
|
+
continue;
|
|
254
|
+
const rule = FS_PATH_RULES[name];
|
|
255
|
+
target[name] = rule !== undefined && !FS_DENIED.has(name) ? wrap(name, rule, value) : denied(name);
|
|
256
|
+
if (target[name] === value)
|
|
257
|
+
throw new Error(`depkill sandbox: cannot guard fs.${name}`);
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
const fsExports = fs;
|
|
261
|
+
patch(fs.promises);
|
|
262
|
+
patch(fsExports);
|
|
263
|
+
syncBuiltinESMExports();
|
|
264
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { Stream } from 'node:stream';
|
|
3
|
+
/**
|
|
4
|
+
* Checks run inside the child on raw results before they become evidence: values whose behaviour lives in
|
|
5
|
+
* events, streams, timers or hidden state cannot be compared by their encoding.
|
|
6
|
+
*/
|
|
7
|
+
const MAX_VISITS = 10_000;
|
|
8
|
+
const TIMER_CTORS = (() => {
|
|
9
|
+
const timeout = setTimeout(() => { }, 0);
|
|
10
|
+
const immediate = setImmediate(() => { });
|
|
11
|
+
clearTimeout(timeout);
|
|
12
|
+
clearImmediate(immediate);
|
|
13
|
+
return [timeout.constructor, immediate.constructor];
|
|
14
|
+
})();
|
|
15
|
+
function isPlain(obj) {
|
|
16
|
+
const proto = Object.getPrototypeOf(obj);
|
|
17
|
+
return proto === null || proto === Object.prototype || Object.getPrototypeOf(proto) === null;
|
|
18
|
+
}
|
|
19
|
+
function hasMethods(obj, names) {
|
|
20
|
+
return names.every((name) => typeof obj[name] === 'function');
|
|
21
|
+
}
|
|
22
|
+
/** Why `obj` itself is a live object (stream, emitter, timer), or null. Duck typing only for class instances. */
|
|
23
|
+
function liveKind(obj) {
|
|
24
|
+
if (TIMER_CTORS.includes(obj.constructor) || (!isPlain(obj) && hasMethods(obj, ['ref', 'unref', 'hasRef', 'refresh']))) {
|
|
25
|
+
return 'a timer';
|
|
26
|
+
}
|
|
27
|
+
if (obj instanceof Stream || (!isPlain(obj) && hasMethods(obj, ['pipe'])))
|
|
28
|
+
return 'a stream';
|
|
29
|
+
if (obj instanceof EventEmitter || (!isPlain(obj) && hasMethods(obj, ['on', 'emit'])))
|
|
30
|
+
return 'an EventEmitter';
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
function children(obj) {
|
|
34
|
+
if (obj instanceof Map)
|
|
35
|
+
return [...obj.keys(), ...obj.values()];
|
|
36
|
+
if (obj instanceof Set)
|
|
37
|
+
return [...obj];
|
|
38
|
+
if (ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer)
|
|
39
|
+
return [];
|
|
40
|
+
const keys = Array.isArray(obj)
|
|
41
|
+
? Object.getOwnPropertyNames(obj).filter((key) => key !== 'length')
|
|
42
|
+
: Object.getOwnPropertyNames(obj);
|
|
43
|
+
return keys.map((key) => {
|
|
44
|
+
try {
|
|
45
|
+
return obj[key];
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Unsupported reason when `value` is, or contains, a stream / EventEmitter / timer (e.g. `returns a stream`),
|
|
54
|
+
* else null. Walks arrays, plain objects, Map/Set and class instance own properties; functions are skipped.
|
|
55
|
+
* Throwing getters or proxies end the walk for that object only.
|
|
56
|
+
*/
|
|
57
|
+
export function liveValueReason(value, what) {
|
|
58
|
+
const seen = new Set();
|
|
59
|
+
const stack = [value];
|
|
60
|
+
while (stack.length > 0 && seen.size < MAX_VISITS) {
|
|
61
|
+
const current = stack.pop();
|
|
62
|
+
if (current === null || typeof current !== 'object' || seen.has(current))
|
|
63
|
+
continue;
|
|
64
|
+
seen.add(current);
|
|
65
|
+
try {
|
|
66
|
+
const kind = liveKind(current);
|
|
67
|
+
if (kind !== null)
|
|
68
|
+
return `${what} ${kind}`;
|
|
69
|
+
for (const child of children(current))
|
|
70
|
+
stack.push(child);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// unreadable object: the encoder records it as an error value
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
/** Values of a props map (`$obj` / `$class.props`), whose keys are user data rather than tags. */
|
|
79
|
+
function findInProps(props, tag) {
|
|
80
|
+
if (props === null || typeof props !== 'object' || Array.isArray(props))
|
|
81
|
+
return null;
|
|
82
|
+
for (const value of Object.values(props)) {
|
|
83
|
+
const found = findTag(value, tag);
|
|
84
|
+
if (found !== null)
|
|
85
|
+
return found;
|
|
86
|
+
}
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Value (as a string) of the first `tag` (`$opaque`, `$fn`, ...) anywhere in an encoding, or null.
|
|
91
|
+
* Keys inside `$obj` and `$class.props` maps are user data, so only their values are searched.
|
|
92
|
+
*/
|
|
93
|
+
export function findTag(e, tag) {
|
|
94
|
+
if (e === null || typeof e !== 'object')
|
|
95
|
+
return null;
|
|
96
|
+
if (Array.isArray(e)) {
|
|
97
|
+
for (const item of e) {
|
|
98
|
+
const found = findTag(item, tag);
|
|
99
|
+
if (found !== null)
|
|
100
|
+
return found;
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
if (Object.hasOwn(e, '$obj'))
|
|
105
|
+
return findInProps(e.$obj, tag);
|
|
106
|
+
if (Object.hasOwn(e, '$class'))
|
|
107
|
+
return findInProps(e.props, tag);
|
|
108
|
+
if (Object.hasOwn(e, tag))
|
|
109
|
+
return String(e[tag]);
|
|
110
|
+
return findInProps(e, tag);
|
|
111
|
+
}
|
|
112
|
+
/** Constructor name of the first `$opaque` tag anywhere in an encoding (ruling R8), or null. */
|
|
113
|
+
export function opaqueCtor(e) {
|
|
114
|
+
return findTag(e, '$opaque');
|
|
115
|
+
}
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// R33/R39: runtime builtin allowlist for replacement replays (`kind: 'file'` targets only — never for original packages).
|
|
2
|
+
// Installed in the child after its own imports and before the replacement loads. Every way a replacement could
|
|
3
|
+
// reach the original package, other code or the network goes through one of the hooks below and throws, which
|
|
4
|
+
// makes the case's outcome differ from the recorded one (a check failure). The originals live in this closure
|
|
5
|
+
// only; the replaced properties are non-writable and non-configurable.
|
|
6
|
+
import { realpathSync } from 'node:fs';
|
|
7
|
+
import Module, { isBuiltin } from 'node:module';
|
|
8
|
+
import { resolve } from 'node:path';
|
|
9
|
+
import { pathToFileURL } from 'node:url';
|
|
10
|
+
import { guardFs } from './fsguard.js';
|
|
11
|
+
/**
|
|
12
|
+
* R39: the only builtins a replacement may load (with or without `node:`). Everything else — code loading,
|
|
13
|
+
* processes, network, inspection, and any builtin added in a future Node — is denied.
|
|
14
|
+
*/
|
|
15
|
+
export const ALLOWED_BUILTINS = new Set([
|
|
16
|
+
'assert', 'assert/strict', 'buffer', 'crypto', 'events', 'fs', 'fs/promises', 'os', 'path', 'path/posix', 'path/win32',
|
|
17
|
+
'punycode', 'querystring', 'stream', 'stream/promises', 'stream/web', 'string_decoder', 'timers', 'timers/promises',
|
|
18
|
+
'url', 'util', 'util/types', 'zlib',
|
|
19
|
+
]);
|
|
20
|
+
/** Is `specifier` a builtin on the replacement allowlist? */
|
|
21
|
+
export function isAllowedBuiltin(specifier) {
|
|
22
|
+
if (!isBuiltin(specifier))
|
|
23
|
+
return false;
|
|
24
|
+
return ALLOWED_BUILTINS.has(specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier);
|
|
25
|
+
}
|
|
26
|
+
/** Is `specifier` a builtin a replacement may not load (any builtin off the allowlist)? */
|
|
27
|
+
export function isDeniedBuiltin(specifier) {
|
|
28
|
+
return isBuiltin(specifier) && !isAllowedBuiltin(specifier);
|
|
29
|
+
}
|
|
30
|
+
class DeniedError extends Error {
|
|
31
|
+
code = 'ERR_DEPKILL_DENIED';
|
|
32
|
+
constructor(what) {
|
|
33
|
+
super(`depkill sandbox: ${what} is not available to a replacement`);
|
|
34
|
+
this.name = 'Error';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function deny(what) {
|
|
38
|
+
throw new DeniedError(what);
|
|
39
|
+
}
|
|
40
|
+
/** Replaces `target[name]` for good; fails closed (the child stops) when the property cannot be replaced. */
|
|
41
|
+
function lock(target, name, value) {
|
|
42
|
+
try {
|
|
43
|
+
Object.defineProperty(target, name, { value, writable: false, configurable: false, enumerable: false });
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
target[name] = value;
|
|
47
|
+
}
|
|
48
|
+
if (target[name] !== value)
|
|
49
|
+
throw new Error(`depkill sandbox: cannot replace ${name}`);
|
|
50
|
+
}
|
|
51
|
+
const fold = (path) => (process.platform === 'win32' || process.platform === 'darwin' ? path.toLowerCase() : path);
|
|
52
|
+
/** Locks down this process for replaying the replacement at `targetPath`. */
|
|
53
|
+
export function lockDownForReplacement(targetPath, root = process.cwd()) {
|
|
54
|
+
const files = new Set([fold(resolve(targetPath))]);
|
|
55
|
+
try {
|
|
56
|
+
files.add(fold(realpathSync.native(targetPath)));
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// a missing target fails to load anyway
|
|
60
|
+
}
|
|
61
|
+
const urls = new Set([...files].map((file) => fold(pathToFileURL(file).href)));
|
|
62
|
+
const isTarget = (file) => files.has(fold(file));
|
|
63
|
+
const cjs = Module;
|
|
64
|
+
if (typeof cjs.registerHooks === 'function') {
|
|
65
|
+
cjs.registerHooks({
|
|
66
|
+
resolve(specifier, context, next) {
|
|
67
|
+
if (isBuiltin(specifier)) {
|
|
68
|
+
if (isDeniedBuiltin(specifier))
|
|
69
|
+
deny(`"${specifier}"`);
|
|
70
|
+
return next(specifier, context);
|
|
71
|
+
}
|
|
72
|
+
let result;
|
|
73
|
+
try {
|
|
74
|
+
result = next(specifier, context);
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return deny(`"${specifier}"`);
|
|
78
|
+
}
|
|
79
|
+
if (result.url.startsWith('node:')) {
|
|
80
|
+
if (isDeniedBuiltin(result.url))
|
|
81
|
+
deny(`"${specifier}"`);
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
if (!urls.has(fold(result.url)))
|
|
85
|
+
deny(`"${specifier}"`);
|
|
86
|
+
return result;
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
else if (typeof cjs.register === 'function') {
|
|
91
|
+
cjs.register('./esm-hooks.js', import.meta.url, {
|
|
92
|
+
data: {
|
|
93
|
+
urls: [...urls],
|
|
94
|
+
allowedBuiltins: [...ALLOWED_BUILTINS],
|
|
95
|
+
foldCase: process.platform === 'win32' || process.platform === 'darwin',
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
const originalLoad = cjs._load;
|
|
100
|
+
const originalResolve = cjs._resolveFilename;
|
|
101
|
+
const originalRequire = cjs.prototype.require;
|
|
102
|
+
const originalCompile = cjs.prototype._compile;
|
|
103
|
+
/** Builtins pass unless denied; anything else only when it resolves to the replacement file itself. */
|
|
104
|
+
const check = (request, parent, isMain) => {
|
|
105
|
+
if (typeof request !== 'string')
|
|
106
|
+
deny('a non-string module request');
|
|
107
|
+
if (isBuiltin(request)) {
|
|
108
|
+
if (isDeniedBuiltin(request))
|
|
109
|
+
deny(`"${request}"`);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
let file;
|
|
113
|
+
try {
|
|
114
|
+
file = originalResolve.call(cjs, request, parent, isMain);
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
return deny(`"${request}"`);
|
|
118
|
+
}
|
|
119
|
+
if (!isTarget(file))
|
|
120
|
+
deny(`"${request}"`);
|
|
121
|
+
};
|
|
122
|
+
lock(cjs, '_load', function load(request, parent, isMain) {
|
|
123
|
+
check(request, parent, isMain);
|
|
124
|
+
return originalLoad.call(this, request, parent, isMain);
|
|
125
|
+
});
|
|
126
|
+
lock(cjs.prototype, 'require', function require(id) {
|
|
127
|
+
check(id, this, false);
|
|
128
|
+
return originalRequire.call(this, id);
|
|
129
|
+
});
|
|
130
|
+
// Compiling source text as a CommonJS module is code generation: only the replacement itself, once.
|
|
131
|
+
// CommonJS only: an ES module target is never compiled through Module (and cannot reach a Module instance).
|
|
132
|
+
let compiled = /\.mjs$/i.test(targetPath);
|
|
133
|
+
lock(cjs.prototype, '_compile', function compile(content, filename, ...rest) {
|
|
134
|
+
if (compiled || typeof filename !== 'string' || !isTarget(filename))
|
|
135
|
+
deny('compiling module source');
|
|
136
|
+
compiled = true;
|
|
137
|
+
return originalCompile.call(this, content, filename, ...rest);
|
|
138
|
+
});
|
|
139
|
+
const originalGetBuiltin = process.getBuiltinModule;
|
|
140
|
+
if (typeof originalGetBuiltin === 'function') {
|
|
141
|
+
lock(process, 'getBuiltinModule', (id) => {
|
|
142
|
+
if (typeof id !== 'string' || isDeniedBuiltin(id))
|
|
143
|
+
deny(`process.getBuiltinModule(${JSON.stringify(String(id))})`);
|
|
144
|
+
return originalGetBuiltin.call(process, id);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
for (const name of ['binding', '_linkedBinding', 'dlopen']) {
|
|
148
|
+
lock(process, name, () => deny(`process.${name}`));
|
|
149
|
+
}
|
|
150
|
+
// R38: fs confined to the project, outside .depkill and node_modules (the replacement file itself excepted).
|
|
151
|
+
guardFs(root, [targetPath]);
|
|
152
|
+
for (const name of ['fetch', 'WebSocket', 'EventSource']) {
|
|
153
|
+
lock(globalThis, name, function denied() {
|
|
154
|
+
return deny(`${name} (network access)`);
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Prefix of every protocol line on the child's stdout; anything else on stdout is package noise. */
|
|
2
|
+
export const PROTOCOL_PREFIX = '\u0000DEPKILL\u0000';
|
|
3
|
+
/** `"/sub#name"` -> `"/sub"`; `"#name"` -> `""`. */
|
|
4
|
+
export function exportSubpath(exportId) {
|
|
5
|
+
const hash = exportId.indexOf('#');
|
|
6
|
+
return hash === -1 ? '' : exportId.slice(0, hash);
|
|
7
|
+
}
|
|
8
|
+
/** `"/sub#name"` -> `"name"`; an id without `#` is treated as a root export name. */
|
|
9
|
+
export function exportName(exportId) {
|
|
10
|
+
const hash = exportId.indexOf('#');
|
|
11
|
+
return hash === -1 ? exportId : exportId.slice(hash + 1);
|
|
12
|
+
}
|
|
13
|
+
/** Which module an export id lives in, for a target: file targets have a single module. */
|
|
14
|
+
export function moduleKey(target, exportId) {
|
|
15
|
+
return target.kind === 'file' ? '' : exportSubpath(exportId);
|
|
16
|
+
}
|