SOURCE DOWNLOAD

木漏茶室源码下载中心

整站 PHP 源码:可浏览文件、复制路径、下载单文件或打包 ZIP。

发布版本 v6.25.231 升级后自动生成独立源码包,下载中心只发送这份冻结包 已排除 config.php / 用户数据 / 上传文件 / 升级备份
komorebi-forum 183 个节点 · PHP 8.3.37 · 完整源码 ZIP 1.31 MB
下载完整源码 ZIP 源码包大小:1.31 MB 安装教程 作者主页 免费开源 免费下载 ↓
COMMUNITY DEPLOYMENTS

已经跑起来的木漏茶室

从源码下载中心下载、完成安装并回传验证的站外站点。每个站点只计 1 次部署下载量;已记录站点会实时读取名称、版本、Logo 与在线状态,本机、内网和证书异常站点无法完成回传。

实时检测
2 个站点已部署

已展示全部 2 个站点。

inc/package_guard.php 11.2 KB · 发布包 v6.25.231
下载
<?php
/**
 * 上传包安全检测:ZIP 结构、路径穿越、文件白名单、PHP 语法与危险调用。
 * 插件、扩展包、系统升级包共用这里的检查,检测通过后才会落盘启用。
 */

function package_tmp_root()
{
    $dir = APP_ROOT . '/storage/tmp';
    if (!is_dir($dir)) {
        @mkdir($dir, 0775, true);
    }
    return $dir;
}

function package_tmp_make($prefix = 'pkg')
{
    $dir = package_tmp_root() . '/' . $prefix . '_' . date('YmdHis') . '_' . bin2hex(random_bytes(5));
    if (!@mkdir($dir, 0775, true) && !is_dir($dir)) {
        throw new Exception('无法创建临时目录,请检查 storage/tmp 权限');
    }
    return $dir;
}

function package_remove_dir($dir)
{
    $dir = rtrim((string) $dir, '/\\');
    $tmpRoot = rtrim(package_tmp_root(), '/\\');
    if ($dir === '' || !is_dir($dir) || strpos($dir, $tmpRoot . '/') !== 0) {
        return;
    }
    $items = @scandir($dir);
    if (!is_array($items)) {
        return;
    }
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }
        $path = $dir . '/' . $item;
        if (is_link($path) || is_file($path)) {
            @unlink($path);
        } elseif (is_dir($path)) {
            package_remove_dir($path);
        }
    }
    @rmdir($dir);
}

/** 相对路径安全校验:拒绝绝对路径、盘符、..、反斜杠与控制字符 */
function package_relpath_ok($rel)
{
    $rel = str_replace('\\', '/', (string) $rel);
    if ($rel === '' || strpos($rel, "\0") !== false || strpos($rel, '../') !== false || $rel === '..') {
        return false;
    }
    if (preg_match('#^(/|[a-zA-Z]:)#', $rel)) {
        return false;
    }
    foreach (explode('/', $rel) as $part) {
        if ($part === '' || $part === '.' || $part === '..') {
            return false;
        }
        if (preg_match('/[<>:"|?*]/', $part)) {
            return false;
        }
    }
    return true;
}

function package_path_blocked($rel, $forUpgrade = false)
{
    $rel = str_replace('\\', '/', (string) $rel);
    $parts = explode('/', $rel);
    $blockedDirs = ['data', 'uploads', 'storage', '.git', '.idea', 'node_modules', 'system'];
    foreach ($parts as $part) {
        if (in_array(strtolower($part), $blockedDirs, true)) {
            return true;
        }
    }
    $base = strtolower(basename($rel));
    if (in_array($base, ['config.php', '.htaccess', '.user.ini', 'install.php', 'install-login.json'], true)) {
        return true;
    }
    if (preg_match('/^\.', $base)) {
        return true;
    }
    if ($forUpgrade && strpos($rel, 'komorebi-upgrade.json') !== false) {
        return true;
    }
    return false;
}

function package_zip_inspect($zipPath, array $limits = [])
{
    if (!class_exists('ZipArchive')) {
        throw new Exception('当前 PHP 未启用 zip 扩展,无法检测 ZIP 包');
    }
    $maxFiles = (int) ($limits['max_files'] ?? 6000);
    $maxTotal = (int) ($limits['max_total'] ?? 300 * 1024 * 1024);
    $maxSingle = (int) ($limits['max_single'] ?? 60 * 1024 * 1024);
    $maxRatio = (int) ($limits['max_ratio'] ?? 150);
    $zip = new ZipArchive();
    $open = $zip->open($zipPath, ZipArchive::CHECKCONS);
    if ($open !== true) {
        throw new Exception('ZIP 包损坏或格式不正确');
    }
    $num = $zip->numFiles;
    if ($num <= 0) {
        $zip->close();
        throw new Exception('ZIP 包是空的');
    }
    if ($num > $maxFiles) {
        $zip->close();
        throw new Exception('ZIP 包文件数量超过上限(' . $maxFiles . ' 个)');
    }
    $total = 0;
    $entries = [];
    for ($i = 0; $i < $num; $i++) {
        $stat = $zip->statIndex($i);
        if (!is_array($stat)) {
            $zip->close();
            throw new Exception('ZIP 包内第 ' . ($i + 1) . ' 个条目无法读取');
        }
        $name = (string) ($stat['name'] ?? '');
        if (!package_relpath_ok(rtrim($name, '/')) && rtrim($name, '/') !== '') {
            $zip->close();
            throw new Exception('ZIP 包含非法路径:' . $name);
        }
        $size = (int) ($stat['size'] ?? 0);
        $compressed = (int) ($stat['comp_size'] ?? 0);
        if ($size > $maxSingle) {
            $zip->close();
            throw new Exception('ZIP 内单个文件超过上限:' . $name);
        }
        if ($compressed > 0 && $size > 0 && ($size / $compressed) > $maxRatio) {
            $zip->close();
            throw new Exception('ZIP 压缩比异常,疑似压缩炸弹:' . $name);
        }
        $total += $size;
        if ($total > $maxTotal) {
            $zip->close();
            throw new Exception('ZIP 解压后总大小超过上限');
        }
        $opsys = 0;
        $attr = 0;
        if ($zip->getExternalAttributesIndex($i, $opsys, $attr) && $opsys === ZipArchive::OPSYS_UNIX) {
            if ((($attr >> 16) & 0xF000) === 0xA000) {
                $zip->close();
                throw new Exception('ZIP 包包含软链接,已拒绝:' . $name);
            }
        }
        $entries[] = ['name' => $name, 'size' => $size];
    }
    $zip->close();
    return ['entries' => $entries, 'total' => $total];
}

function package_extract_zip($zipPath, array $limits = [])
{
    package_zip_inspect($zipPath, $limits);
    $work = package_tmp_make('unzip');
    $zip = new ZipArchive();
    if ($zip->open($zipPath) !== true) {
        package_remove_dir($work);
        throw new Exception('无法读取 ZIP 包');
    }
    $ok = $zip->extractTo($work);
    $zip->close();
    if (!$ok) {
        package_remove_dir($work);
        throw new Exception('ZIP 解压失败,请检查 storage/tmp 权限');
    }
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($work, FilesystemIterator::SKIP_DOTS));
    foreach ($rii as $f) {
        if ($f->isLink()) {
            package_remove_dir($work);
            throw new Exception('解压后发现软链接,已拒绝');
        }
    }
    return $work;
}

function package_find_manifest($root, $filename, $maxDepth = 2)
{
    $hits = [];
    $rii = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)
    );
    foreach ($rii as $f) {
        if (!$f->isFile() || strtolower($f->getFilename()) !== strtolower($filename)) {
            continue;
        }
        $rel = str_replace('\\', '/', substr($f->getPathname(), strlen($root) + 1));
        if (substr_count($rel, '/') <= $maxDepth) {
            $hits[] = $f->getPathname();
        }
    }
    return $hits;
}

/** 允许包内有一个顶层目录;返回真正的项目根 */
function package_content_root($work, $manifestPath)
{
    $root = dirname($manifestPath);
    return $root;
}

function package_version_matches($version, $min = '', $max = '')
{
    $version = (string) $version;
    if ($min !== '' && version_compare($version, (string) $min, '<')) {
        return false;
    }
    if ($max !== '') {
        $max = trim((string) $max);
        $parts = explode('.', $max);
        if (count($parts) < 3) {
            // 8.3 表示 8.3.x,上界取 8.4.0;单段 8 表示 8.x,上界取 9.0.0
            $ceil = $parts;
            $ceil[count($ceil) - 1] = (string) ((int) $ceil[count($ceil) - 1] + 1);
            $ceil = implode('.', $ceil) . (count($parts) === 1 ? '.0.0' : '.0');
            if (version_compare($version, $ceil, '>=')) {
                return false;
            }
        } elseif (version_compare($version, $max, '>')) {
            return false;
        }
    }
    return true;
}

/** PHP 语法检查:优先 php -l,缺少 exec 时用 token_get_all(TOKEN_PARSE) 兜底 */
function package_php_lint($file)
{
    if (!is_file($file)) {
        return '文件不存在';
    }
    $code = (string) @file_get_contents($file);
    if (strpos($code, '<?php') === false && strpos($code, '<?=') === false) {
        return '';
    }
    try {
        token_get_all($code, TOKEN_PARSE);
    } catch (ParseError $e) {
        return 'PHP 语法错误:' . $e->getMessage() . '(第 ' . $e->getLine() . ' 行)';
    } catch (Throwable $e) {
        return 'PHP 语法错误:' . $e->getMessage();
    }
    return '';
}

/** 去掉注释和字符串内容,避免把说明文字里的函数名误判为调用 */
function package_code_without_literals($code)
{
    $out = '';
    foreach (token_get_all((string) $code) as $token) {
        if (is_array($token)) {
            if (in_array($token[0], [T_COMMENT, T_DOC_COMMENT, T_CONSTANT_ENCAPSED_STRING, T_ENCAPSED_AND_WHITESPACE], true)) {
                continue;
            }
            $out .= $token[1];
        } else {
            $out .= $token;
        }
    }
    return $out;
}

function package_plugin_code_errors($code, $label = 'plugin.php')
{
    $errors = [];
    $bare = package_code_without_literals($code);
    $patterns = [
        '/\b(eval|assert|create_function|shell_exec|system|passthru|popen|proc_open|pcntl_exec|curl_exec|curl_multi_exec|fsockopen|stream_socket_client)\s*\(/i' => '危险命令/远程执行调用',
        '/\b(unlink|rmdir|rename|chmod|chown|copy|file_put_contents|fopen|fwrite|ftruncate|symlink|link|mkdir|touch|tempnam|move_uploaded_file)\s*\(/i' => '文件写入或删除调用',
        '/\bDB::(run|delete|query|exec|pdo)\b|\bDROP\s+TABLE\b|\bTRUNCATE\s+TABLE\b|\bALTER\s+TABLE\b/i' => '直接操作数据库',
        '/\b(include|require)(_once)?\s*\(/i' => '引入包外文件',
    ];
    foreach ($patterns as $re => $reason) {
        if (preg_match($re, $bare)) {
            $errors[] = $label . ' 含' . $reason;
        }
    }
    return $errors;
}

function package_plugin_html_errors($html, $label = 'HTML')
{
    $errors = [];
    $html = (string) $html;
    if (mb_strlen($html, 'UTF-8') > 200000) {
        $errors[] = $label . ' 超过 200KB';
    }
    $re = '/<script\s+[^>]*src\s*=|javascript\s*:|<iframe\b|<object\b|<embed\b|document\.cookie|localStorage|fetch\s*\(|XMLHttpRequest|eval\s*\(/i';
    if (preg_match($re, $html)) {
        $errors[] = $label . ' 含外链脚本或敏感浏览器调用';
    }
    return $errors;
}

function package_scan_files($root, array $limits = [])
{
    $maxFiles = (int) ($limits['max_files'] ?? 6000);
    $maxTotal = (int) ($limits['max_total'] ?? 300 * 1024 * 1024);
    $files = [];
    $total = 0;
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS));
    foreach ($rii as $f) {
        if ($f->isLink()) {
            throw new Exception('包里包含软链接:' . $f->getPathname());
        }
        if (!$f->isFile()) {
            continue;
        }
        $rel = str_replace('\\', '/', substr($f->getPathname(), strlen($root) + 1));
        if (!package_relpath_ok($rel)) {
            throw new Exception('包里包含非法路径:' . $rel);
        }
        $size = (int) $f->getSize();
        $total += $size;
        if ($size > (int) ($limits['max_single'] ?? 60 * 1024 * 1024)) {
            throw new Exception('文件超过上限:' . $rel);
        }
        $files[] = ['rel' => $rel, 'full' => $f->getPathname(), 'size' => $size];
        if (count($files) > $maxFiles) {
            throw new Exception('文件数量超过上限');
        }
        if ($total > $maxTotal) {
            throw new Exception('解压后总大小超过上限');
        }
    }
    return $files;
}
主题