from __future__ import annotations import argparse from pathlib import Path _ORIGINAL = """ const rootSkip = new Set(['proc', 'dev', 'sys']); for (const p of readConfig?.denyOnly || []) { if (normalizePathForSandbox(p) === '/') { for (const child of fs.readdirSync('/')) { if (!rootSkip.has(child)) readDenyPaths.push('/' + child); } } """ _REPLACEMENT = """ const rootSkip = new Set(['proc', 'dev', 'sys']); const rootChildIsAllowedSymlink = (childPath) => { try { if (!fs.lstatSync(childPath).isSymbolicLink()) return false; const resolved = fs.realpathSync(childPath); return readAllowPaths.some(allowPath => resolved === allowPath || resolved.startsWith(allowPath + '/')); } catch { return false; } }; for (const p of readConfig?.denyOnly || []) { if (normalizePathForSandbox(p) === '/') { for (const child of fs.readdirSync('/')) { const childPath = '/' + child; if (!rootSkip.has(child) && !rootChildIsAllowedSymlink(childPath)) readDenyPaths.push(childPath); } } """ _TMPFS_ORIGINAL = """ args.push('--ro-bind', allowPath, allowPath); logForDebugging(`[Sandbox Linux] Re-allowed read access within denied region: ${allowPath}`); } } } """ _TMPFS_REPLACEMENT = """ args.push('--ro-bind', allowPath, allowPath); logForDebugging(`[Sandbox Linux] Re-allowed read access within denied region: ${allowPath}`); } } // A denyRead tmpfs must not become an unlisted writable location. Remount // only the parent mount read-only; explicit writable child binds remain rw. if (!allowedWritePaths.includes(normalizedPath)) { args.push('--remount-ro', normalizedPath); } } """ def patch_file(path: Path) -> None: source = path.read_text(encoding="utf-8") if _REPLACEMENT in source or _TMPFS_REPLACEMENT in source: raise RuntimeError("sandbox runtime merged-usr patch is already patched") if source.count(_ORIGINAL) != 1: raise RuntimeError("sandbox runtime merged-usr patch target does not match pinned source") if source.count(_TMPFS_ORIGINAL) != 1: raise RuntimeError("sandbox runtime read-only tmpfs patch target does not match pinned source") patched = source.replace(_ORIGINAL, _REPLACEMENT) patched = patched.replace(_TMPFS_ORIGINAL, _TMPFS_REPLACEMENT) path.write_text(patched, encoding="utf-8") def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("path", type=Path) args = parser.parse_args() patch_file(args.path) if __name__ == "__main__": main()