Files
stack/packages/plugins/src/imports.mjs
T

36 lines
1.7 KiB
JavaScript

// PL1: executable dependencies must be bundled inside the pinned package.
// This constrains module resolution, not the host authority granted by R10.
// Kept standalone so a sandbox tool can use this same guard in its fresh process.
import { isBuiltin, registerHooks } from 'node:module';
import { isAbsolute, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const roots = new Set();
let registered = false;
const inside = (root, path) => {
const rel = relative(root, path);
return rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel);
};
const refused = () => { throw new Error('plugin import refused'); };
export function guardPluginImports(directory) {
roots.add(resolve(directory));
if (registered) return;
registerHooks({resolve(specifier, context, nextResolve) {
let parent;
try { if (context.parentURL?.startsWith('file:')) parent = fileURLToPath(context.parentURL); }
catch { return refused(); }
const root = parent && [...roots].find(dir => inside(dir, parent));
if (!root || isBuiltin(specifier)) return nextResolve(specifier, context);
// Refuse bare lookups before Node searches unpinned ancestor node_modules.
if (!specifier.startsWith('./') && !specifier.startsWith('../') && !specifier.startsWith('/') && !specifier.startsWith('file:')) return refused();
try {
const candidate = new URL(specifier, context.parentURL);
if (candidate.protocol !== 'file:' || !inside(root, fileURLToPath(candidate))) return refused();
const result = nextResolve(specifier, context);
if (!result.url.startsWith('file:') || !inside(root, fileURLToPath(result.url))) return refused();
return result;
} catch { return refused(); }
}});
registered = true;
}