Skip to content

Commit 7cccd55

Browse files
RafaelGSSbmeck
authored andcommitted
policy: makeRequireFunction on mainModule.require
PR-URL: nodejs-private/node-private#358 Backport-PR-URL: nodejs-private/node-private#371 Signed-off-by: RafaelGSS <rafael.nunu@hotmail.com> Co-authored-by: Bradley Farias <bradley.meck@gmail.com> Reviewed-by: Bradley Farias <bradley.meck@gmail.com> Reviewed-by: Michael Dawson <midawson@redhat.com>
1 parent 5e0142a commit 7cccd55

9 files changed

+145
-40
lines changed

lib/internal/modules/cjs/helpers.js

+9-3
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ const { getOptionValue } = require('internal/options');
2727
const { setOwnProperty } = require('internal/util');
2828
const userConditions = getOptionValue('--conditions');
2929

30+
const {
31+
privateSymbols: {
32+
require_private_symbol,
33+
},
34+
} = internalBinding('util');
35+
3036
let debug = require('internal/util/debuglog').debuglog('module', (fn) => {
3137
debug = fn;
3238
});
@@ -86,7 +92,7 @@ function makeRequireFunction(mod, redirects) {
8692
filepath = fileURLToPath(destination);
8793
urlToFileCache.set(href, filepath);
8894
}
89-
return mod.require(filepath);
95+
return mod[require_private_symbol](mod, filepath);
9096
}
9197
}
9298
if (missing) {
@@ -96,11 +102,11 @@ function makeRequireFunction(mod, redirects) {
96102
ArrayPrototypeJoin([...conditions], ', ')
97103
));
98104
}
99-
return mod.require(specifier);
105+
return mod[require_private_symbol](mod, specifier);
100106
};
101107
} else {
102108
require = function require(path) {
103-
return mod.require(path);
109+
return mod[require_private_symbol](mod, path);
104110
};
105111
}
106112

lib/internal/modules/cjs/loader.js

+33-24
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,11 @@ const { sep } = path;
9797
const { internalModuleStat } = internalBinding('fs');
9898
const packageJsonReader = require('internal/modules/package_json_reader');
9999
const { safeGetenv } = internalBinding('credentials');
100+
const {
101+
privateSymbols: {
102+
require_private_symbol,
103+
},
104+
} = internalBinding('util');
100105
const {
101106
cjsConditions,
102107
hasEsmSyntax,
@@ -158,6 +163,20 @@ let requireDepth = 0;
158163
let statCache = null;
159164
let isPreloading = false;
160165

166+
function internalRequire(module, id) {
167+
validateString(id, 'id');
168+
if (id === '') {
169+
throw new ERR_INVALID_ARG_VALUE('id', id,
170+
'must be a non-empty string');
171+
}
172+
requireDepth++;
173+
try {
174+
return Module._load(id, module, /* isMain */ false);
175+
} finally {
176+
requireDepth--;
177+
}
178+
}
179+
161180
function stat(filename) {
162181
filename = path.toNamespacedPath(filename);
163182
if (statCache !== null) {
@@ -212,6 +231,15 @@ function Module(id = '', parent) {
212231
this.filename = null;
213232
this.loaded = false;
214233
this.children = [];
234+
let redirects;
235+
if (policy?.manifest) {
236+
const moduleURL = pathToFileURL(id);
237+
redirects = policy.manifest.getDependencyMapper(moduleURL);
238+
}
239+
setOwnProperty(this, 'require', makeRequireFunction(this, redirects));
240+
// Loads a module at the given file path. Returns that module's
241+
// `exports` property.
242+
this[require_private_symbol] = internalRequire;
215243
}
216244

217245
const builtinModules = [];
@@ -915,6 +943,7 @@ Module._load = function(request, parent, isMain) {
915943

916944
if (isMain) {
917945
process.mainModule = module;
946+
setOwnProperty(module.require, 'main', process.mainModule);
918947
module.id = '.';
919948
}
920949

@@ -1099,24 +1128,6 @@ Module.prototype.load = function(filename) {
10991128
esmLoader.cjsCache.set(this, exports);
11001129
};
11011130

1102-
1103-
// Loads a module at the given file path. Returns that module's
1104-
// `exports` property.
1105-
Module.prototype.require = function(id) {
1106-
validateString(id, 'id');
1107-
if (id === '') {
1108-
throw new ERR_INVALID_ARG_VALUE('id', id,
1109-
'must be a non-empty string');
1110-
}
1111-
requireDepth++;
1112-
try {
1113-
return Module._load(id, this, /* isMain */ false);
1114-
} finally {
1115-
requireDepth--;
1116-
}
1117-
};
1118-
1119-
11201131
// Resolved path to process.argv[1] will be lazily placed here
11211132
// (needed for setting breakpoint when called with --inspect-brk)
11221133
let resolvedArgv;
@@ -1180,10 +1191,9 @@ function wrapSafe(filename, content, cjsModuleInstance) {
11801191
// Returns exception, if any.
11811192
Module.prototype._compile = function(content, filename) {
11821193
let moduleURL;
1183-
let redirects;
11841194
if (policy?.manifest) {
11851195
moduleURL = pathToFileURL(filename);
1186-
redirects = policy.manifest.getDependencyMapper(moduleURL);
1196+
policy.manifest.getDependencyMapper(moduleURL);
11871197
policy.manifest.assertIntegrity(moduleURL, content);
11881198
}
11891199

@@ -1213,18 +1223,17 @@ Module.prototype._compile = function(content, filename) {
12131223
}
12141224
}
12151225
const dirname = path.dirname(filename);
1216-
const require = makeRequireFunction(this, redirects);
12171226
let result;
12181227
const exports = this.exports;
12191228
const thisValue = exports;
12201229
const module = this;
12211230
if (requireDepth === 0) statCache = new SafeMap();
12221231
if (inspectorWrapper) {
12231232
result = inspectorWrapper(compiledWrapper, thisValue, exports,
1224-
require, module, filename, dirname);
1233+
module.require, module, filename, dirname);
12251234
} else {
12261235
result = ReflectApply(compiledWrapper, thisValue,
1227-
[exports, require, module, filename, dirname]);
1236+
[exports, module.require, module, filename, dirname]);
12281237
}
12291238
hasLoadedAnyUserCJSModule = true;
12301239
if (requireDepth === 0) statCache = null;
@@ -1400,7 +1409,7 @@ Module._preloadModules = function(requests) {
14001409
}
14011410
}
14021411
for (let n = 0; n < requests.length; n++)
1403-
parent.require(requests[n]);
1412+
internalRequire(parent, requests[n]);
14041413
isPreloading = false;
14051414
};
14061415

src/env_properties.h

+2-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@
2424
V(napi_type_tag, "node:napi:type_tag") \
2525
V(napi_wrapper, "node:napi:wrapper") \
2626
V(untransferable_object_private_symbol, "node:untransferableObject") \
27-
V(exiting_aliased_Uint32Array, "node:exiting_aliased_Uint32Array")
27+
V(exiting_aliased_Uint32Array, "node:exiting_aliased_Uint32Array") \
28+
V(require_private_symbol, "node:require_private_symbol")
2829

2930
// Symbols are per-isolate primitives but Environment proxies them
3031
// for the sake of convenience.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
process.mainModule.require('os').cpus();
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
let requires = new WeakMap()
2+
Object.defineProperty(Object.getPrototypeOf(module), 'require', {
3+
get() {
4+
return requires.get(this);
5+
},
6+
set(v) {
7+
requires.set(this, v);
8+
process.nextTick(() => {
9+
let fs = Reflect.apply(v, this, ['fs'])
10+
if (typeof fs.readFileSync === 'function') {
11+
process.exit(1);
12+
}
13+
})
14+
return requires.get(this);
15+
},
16+
configurable: true
17+
})
18+
19+
require('./valid-module')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"onerror": "exit",
3+
"scopes": {
4+
"file:": {
5+
"integrity": true,
6+
"dependencies": {}
7+
}
8+
}
9+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{
2+
"onerror": "exit",
3+
"resources": {
4+
"./object-define-property-bypass.js": {
5+
"integrity": true,
6+
"dependencies": {
7+
"./valid-module": true
8+
}
9+
},
10+
"./valid-module.js": {
11+
"integrity": true,
12+
"dependencies": {
13+
"fs": true
14+
}
15+
}
16+
}
17+
}

test/fixtures/policy-manifest/valid-module.js

Whitespace-only changes.

test/parallel/test-policy-manifest.js

+55-12
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,58 @@ const assert = require('assert');
1111
const { spawnSync } = require('child_process');
1212
const fixtures = require('../common/fixtures.js');
1313

14-
const policyFilepath = fixtures.path('policy-manifest', 'invalid.json');
15-
16-
const result = spawnSync(process.execPath, [
17-
'--experimental-policy',
18-
policyFilepath,
19-
'./fhqwhgads.js',
20-
]);
21-
22-
assert.notStrictEqual(result.status, 0);
23-
const stderr = result.stderr.toString();
24-
assert.match(stderr, /ERR_MANIFEST_INVALID_SPECIFIER/);
25-
assert.match(stderr, /pattern needs to have a single trailing "\*"/);
14+
{
15+
const policyFilepath = fixtures.path('policy-manifest', 'invalid.json');
16+
const result = spawnSync(process.execPath, [
17+
'--experimental-policy',
18+
policyFilepath,
19+
'./fhqwhgads.js',
20+
]);
21+
22+
assert.notStrictEqual(result.status, 0);
23+
const stderr = result.stderr.toString();
24+
assert.match(stderr, /ERR_MANIFEST_INVALID_SPECIFIER/);
25+
assert.match(stderr, /pattern needs to have a single trailing "\*"/);
26+
}
27+
28+
{
29+
const policyFilepath = fixtures.path('policy-manifest', 'onerror-exit.json');
30+
const result = spawnSync(process.execPath, [
31+
'--experimental-policy',
32+
policyFilepath,
33+
'-e',
34+
'require("os").cpus()',
35+
]);
36+
37+
assert.notStrictEqual(result.status, 0);
38+
const stderr = result.stderr.toString();
39+
assert.match(stderr, /ERR_MANIFEST_DEPENDENCY_MISSING/);
40+
assert.match(stderr, /does not list module as a dependency specifier for conditions: require, node, node-addons/);
41+
}
42+
43+
{
44+
const policyFilepath = fixtures.path('policy-manifest', 'onerror-exit.json');
45+
const mainModuleBypass = fixtures.path('policy-manifest', 'main-module-bypass.js');
46+
const result = spawnSync(process.execPath, [
47+
'--experimental-policy',
48+
policyFilepath,
49+
mainModuleBypass,
50+
]);
51+
52+
assert.notStrictEqual(result.status, 0);
53+
const stderr = result.stderr.toString();
54+
assert.match(stderr, /ERR_MANIFEST_DEPENDENCY_MISSING/);
55+
assert.match(stderr, /does not list os as a dependency specifier for conditions: require, node, node-addons/);
56+
}
57+
58+
{
59+
const policyFilepath = fixtures.path('policy-manifest', 'onerror-resource-exit.json');
60+
const objectDefinePropertyBypass = fixtures.path('policy-manifest', 'object-define-property-bypass.js');
61+
const result = spawnSync(process.execPath, [
62+
'--experimental-policy',
63+
policyFilepath,
64+
objectDefinePropertyBypass,
65+
]);
66+
67+
assert.strictEqual(result.status, 0);
68+
}

0 commit comments

Comments
 (0)