-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathvm_context_helper.ts
More file actions
125 lines (103 loc) · 3.37 KB
/
vm_context_helper.ts
File metadata and controls
125 lines (103 loc) · 3.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/* eslint-disable @typescript-eslint/no-require-imports */
import * as fs from 'node:fs';
import { isBuiltin } from 'node:module';
import * as path from 'node:path';
import * as vm from 'node:vm';
import { ALLOWED_DRIVER_REQUIRE_PROPERTY_NAME } from '../../mongodb_all';
const allowedModules = new Set([
'@aws-sdk/credential-providers',
'@mongodb-js/saslprep',
'@mongodb-js/zstd',
'bson',
'gcp-metadata',
'kerberos',
'mongodb-client-encryption',
'mongodb-connection-string-url',
'path',
'snappy',
'socks'
]);
const blockedModules = new Set(['os']);
// TODO: NODE-7460 - Remove Error, Map, Math, Promise, and other unnecessary exports
const exposedGlobals = new Set([
'AbortController',
'AbortSignal',
'BigInt',
'Buffer',
'Date',
'Error',
'Headers',
'Map',
'Math',
'Promise',
'TextDecoder',
'TextEncoder',
'URL',
'URLSearchParams',
'console',
'crypto',
'performance',
'process',
'clearImmediate',
'clearInterval',
'clearTimeout',
'setImmediate',
'setInterval',
'setTimeout',
'queueMicrotask'
]);
/**
* Creates a require function that blocks access to specified core modules
*/
function createRestrictedRequire() {
return function restrictedRequire(moduleName: string) {
const isAllowedBySymbol = !!sandbox[ALLOWED_DRIVER_REQUIRE_PROPERTY_NAME];
const isModuleBuiltin = isBuiltin(moduleName);
const isModuleAllowed = allowedModules.has(moduleName);
const isModuleBlocked = blockedModules.has(moduleName);
const shouldAllow = isModuleAllowed || isModuleBuiltin;
const shouldBlock = (isModuleBlocked || !shouldAllow) && !isAllowedBySymbol;
if (shouldBlock) {
throw new Error(`Access to core module '${moduleName}' is restricted in this context`);
}
return require(moduleName);
} as NodeJS.Require;
}
const context = {
__proto__: null,
// Custom require that blocks core modules
require: createRestrictedRequire(),
// Needed for some modules
global: undefined as any,
globalThis: undefined as any
};
// Expose allowed globals in the context
for (const globalName of exposedGlobals) {
if (globalName in global) {
context[globalName] = (global as any)[globalName];
}
}
// Create a sandbox context with necessary globals
const sandbox = vm.createContext(context);
// Make globalThis point to the sandbox
sandbox.globalThis = sandbox;
/**
* Load the bundled MongoDB driver module in a VM context
* This allows us to control the globals that the driver has access to
*/
export function loadContextifiedMongoDBModule(): typeof import('../../mongodb_all') {
const bundlePath = path.join(__dirname, 'bundle/driver-bundle.js');
if (!fs.existsSync(bundlePath)) {
throw new Error(`Driver bundle not found at ${bundlePath}. Run 'npm run bundle:driver' first.`);
}
const bundleCode = fs.readFileSync(bundlePath, 'utf8');
const exportsContainer = { __proto__: null };
const moduleContainer = { __proto__: null, exports: exportsContainer };
// Wrap the bundle in a CommonJS-style wrapper
const wrapper = `(function(exports, module, require) {${bundleCode}})`;
const script = new vm.Script(wrapper, { filename: bundlePath });
const fn = script.runInContext(sandbox);
// Execute the bundle with the restricted require from the sandbox
fn(moduleContainer.exports, moduleContainer, sandbox.require);
return moduleContainer.exports as unknown as typeof import('../../mongodb_all');
}