Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ const createError = ({ name, message, ...props }) => {
return error
}

const [major] = process.version.slice(1).split('.').map(Number)
const [nodeMajor] = process.version.slice(1).split('.').map(Number)

const PERMISSION_FLAG = major >= 24 ? '--permission' : '--experimental-permission'
const PERMISSION_FLAG = nodeMajor >= 24 ? '--permission' : '--experimental-permission'

const flags = ({ memory }) => {
const flags = ['--disable-warning=ExperimentalWarning', PERMISSION_FLAG]
Expand Down Expand Up @@ -77,9 +77,15 @@ module.exports = (snippet, { tmpdir, timeout, memory, throwError = true } = {})
}

if (error.code === 'ERR_ACCESS_DENIED') {
const permission = error.permission
? error.permission
: error.message.includes('getaddrinfo')
? 'network'
: undefined

throw createError({
name: 'PermissionError',
message: `Access to '${error.permission}' has been restricted`,
message: `Access to '${permission}' has been restricted`,
profiling: { duration: duration() }
})
}
Expand Down
37 changes: 37 additions & 0 deletions test/error.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const test = require('ava')

const isolatedFunction = require('..')

const [nodeMajor] = process.version.slice(1).split('.').map(Number)

test('throw an error if snippet is not a function or string', t => {
t.throws(
() => {
Expand Down Expand Up @@ -139,3 +141,38 @@ test('handle child process', async t => {
t.is(error.message, "Access to 'ChildProcess' has been restricted")
}
})
;(nodeMajor >= 25 ? test : test.skip)('handle network access', async t => {
{
const [fn, cleanup] = isolatedFunction(async () => {
function doFetch (url) {
return new Promise((resolve, reject) => {
const req = require('node:http').get(url, res => {
let data = ''

res.on('data', chunk => {
data += chunk
})

res.on('end', () => {
resolve({
statusCode: res.statusCode,
headers: res.headers,
body: data
})
})
})

req.on('error', reject)
})
}

const { statusCode } = await doFetch('http://example.com')
return statusCode
})

t.teardown(cleanup)

const error = await t.throwsAsync(fn())
t.is(error.message, "Access to 'network' has been restricted")
}
})