feat: запись, правка и поиск файлов, json_query

- write_file: атомарная запись (temp + rename), лимит 1 МБ,
  create_dirs по требованию, только внутри песочницы
- replace_in_file: требует ровно одного совпадения search,
  all:true для осознанной массовой замены
- search_files: regex по содержимому, 'путь:строка: текст',
  пропускает .git/vendor/node_modules/var, бинарные и большие файлы
- find_files: маска по относительному пути или имени
- json_query: путь вида data.items[0].id
- FileSandbox: resolveForWrite и writeAtomic, запрет '..' на запись,
  подсказка в сообщении «путь не найден»
- 88 тестов
This commit is contained in:
rsgrinko committed 2026-11-12 19:12:08 +03:00
1 parent cf627b8ce5
commit 72883fbc53
8 files changed
+1117 -38

No files matched your search

+128 -26
View File
@@ -7,9 +7,8 @@ namespace AiSdk\Tools;
/**
* Ограничитель файловых инструментов: любой путь обязан лежать внутри корня.
*
* Никакой «магии»: относительный путь склеивается с корнем, приводится к
* реальному виду (realpath) и проверяется по префиксу. Всё, что выходит
* наружу — «..», абсолютные пути, симлинки за пределы каталога — отвергается.
* Чтение проверяется через realpath, запись — через realpath каталога:
* иначе «..» и симлинки уводили бы за пределы корня.
*/
final class FileSandbox
{
@@ -32,44 +31,112 @@ final class FileSandbox
}
/**
* Привести относительный путь к абсолютному внутри корня.
* Абсолютный путь к существующему файлу или каталогу.
*
* @throws \RuntimeException если путь вне корня или (для чтения) не найден
* @throws \RuntimeException если путь вне корня или не найден
*/
public function resolve(string $path, bool $mustExist = true): string
public function resolve(string $path): string
{
$path = trim($path);
$relative = $this->normalize($path);
if ($path === '' || $path === '.') {
if ($relative === '') {
return $this->root;
}
if (str_contains($path, "\0")) {
throw new \RuntimeException('Некорректный путь.');
}
if (str_starts_with($path, '/') || preg_match('/^[A-Za-z]:[\\\\\/]/', $path) === 1) {
throw new \RuntimeException('Абсолютные пути запрещены: указывайте путь относительно корня.');
}
$candidate = $this->root . DIRECTORY_SEPARATOR . $path;
$real = realpath($candidate);
$real = realpath($this->root . DIRECTORY_SEPARATOR . $relative);
if ($real === false) {
if ($mustExist) {
throw new \RuntimeException('Путь не найден: ' . $path);
}
return $candidate;
throw new \RuntimeException(
'Путь не найден: ' . $path . '. Нужен путь к файлу относительно корня, например src/app.php.'
);
}
if ($real !== $this->root && !$this->startsWithRoot($real)) {
throw new \RuntimeException('Путь выходит за пределы разрешённого каталога.');
}
$this->assertInside($real);
return $real;
}
/**
* Абсолютный путь для записи. Каталог должен существовать (если не передан
* createDirs), сам файл — нет.
*
* @throws \RuntimeException
*/
public function resolveForWrite(string $path, bool $createDirs = false): string
{
$relative = $this->normalize($path);
if ($relative === '') {
throw new \RuntimeException('Не указан путь к файлу.');
}
$directory = dirname($relative);
$name = basename($relative);
if ($name === '' || $name === '.' || $name === '..') {
throw new \RuntimeException('Некорректное имя файла.');
}
$directoryPath = $directory === '.' || $directory === ''
? $this->root
: $this->root . DIRECTORY_SEPARATOR . $directory;
if (!is_dir($directoryPath)) {
if (!$createDirs) {
throw new \RuntimeException('Каталог не существует: ' . $directory);
}
if (!@mkdir($directoryPath, 0777, true) && !is_dir($directoryPath)) {
throw new \RuntimeException('Не удалось создать каталог: ' . $directory);
}
}
$realDirectory = realpath($directoryPath);
if ($realDirectory === false) {
throw new \RuntimeException('Каталог недоступен: ' . $directory);
}
$this->assertInside($realDirectory);
return $realDirectory . DIRECTORY_SEPARATOR . $name;
}
/**
* Атомарная запись: сначала во временный файл рядом, потом rename.
* Так при сбое не остаётся полузаписанный файл.
*/
public function writeAtomic(string $absolute, string $content): void
{
$directory = dirname($absolute);
$temporary = @tempnam($directory, '.aisdk_');
if ($temporary === false) {
throw new \RuntimeException('Не удалось создать временный файл в ' . $directory);
}
$written = @file_put_contents($temporary, $content);
if ($written === false) {
@unlink($temporary);
throw new \RuntimeException('Не удалось записать файл.');
}
@chmod($temporary, 0644);
// На Windows rename не перезаписывает существующий файл.
if (is_file($absolute) && DIRECTORY_SEPARATOR === '\\') {
@unlink($absolute);
}
if (!@rename($temporary, $absolute)) {
@unlink($temporary);
throw new \RuntimeException('Не удалось переименовать временный файл.');
}
}
/**
* Путь для показа пользователю (относительно корня).
*/
@@ -88,6 +155,41 @@ final class FileSandbox
return $absolute;
}
/**
* Относительный путь без «..», абсолютных путей и нулевых байтов.
*/
private function normalize(string $path): string
{
$path = trim(str_replace('\\', '/', $path));
if ($path === '' || $path === '.') {
return '';
}
if (str_contains($path, "\0")) {
throw new \RuntimeException('Некорректный путь.');
}
if (str_starts_with($path, '/') || preg_match('/^[A-Za-z]:[\\\\\/]/', $path) === 1) {
throw new \RuntimeException('Абсолютные пути запрещены: указывайте путь относительно корня.');
}
$path = preg_replace('#/+#', '/', $path) ?? $path;
if (preg_match('#(^|/)\.\.(/|$)#', $path) === 1) {
throw new \RuntimeException('Путь не должен содержать "..".');
}
return trim($path, '/');
}
private function assertInside(string $real): void
{
if ($real !== $this->root && !$this->startsWithRoot($real)) {
throw new \RuntimeException('Путь выходит за пределы разрешённого каталога.');
}
}
private function startsWithRoot(string $path): bool
{
$prefix = $this->root . DIRECTORY_SEPARATOR;