From 8ac51d3160d172330f8abb297b25170a373225b2 Mon Sep 17 00:00:00 2001 From: terry Date: Thu, 5 Nov 2026 17:33:44 +0800 Subject: [PATCH] =?UTF-8?q?TinyImgUploader=202.0.0=EF=BC=9ATypecho=201.3?= =?UTF-8?q?=20=E5=9B=BE=E7=89=87=E4=B8=8A=E4=BC=A0=E6=8F=92=E4=BB=B6?= =?UTF-8?q?=EF=BC=88=E5=AF=B9=E6=8E=A5=20TinyImg=20=E5=9B=BE=E5=BA=8A?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在撰写文章 / 页面的右侧栏增加图片上传窗口,选图后上传到自建 TinyImg 图床,并把 Markdown 链接插入编辑器光标处。 主要功能 1. 侧栏卡片 + 弹窗上传 - 挂在 admin/write-post.php 与 write-page.php 的 option 钩子 - 支持点选、拖入、Ctrl+V 粘贴,上传前可预览 - 用 getSelection / replaceSelection 插入光标处并触发 input 事件, 草稿自动保存与实时预览都能同步 2. 三种图床鉴权方式 - token(默认):X-TinyImg-Token 请求头,未配置则明确拒绝 - admin:模拟图床后台登录 Cookie(无需改图床,但凭证等价于后台密码) - guest:游客上传,图片进 temp/ 并受每日配额限制 - token / admin 两种模式强制服务端代理,凭证绝不下发浏览器 3. 「测试连接」按钮 - 读取输入框当前值,无需先保存 - 经博客同源 Action(带 CSRF)调用图床 functions/upload.php?ping=1 - 返回图床版本、鉴权方式与管理员目录,并比对是否落在 upload/ 4. 为什么必须走服务端代理 - 实测图床 upload.php 不返回 Access-Control-Allow-Origin, 浏览器从博客后台直接 POST 会被同源策略拦截 5. 服务端校验 - 登录态 + 用户组(可选「仅管理员」) + CSRF 令牌 - 上传大小上限、getimagesize 真实图片头校验(拦 SVG / 伪装脚本) - 未认出管理员身份时返回 warn,前端不自动关闭弹窗 6. 附带工具与测试 - tools/probe.php:命令行连通性自检(只读探测 / 真实上传 / 目录判定) - tools/cookie.php:本地计算图床管理员 Cookie 值,不联网 - tests/:六组共 207 项,含故意错误实现的反证 版本:2.0.0 --- .gitattributes | 9 + .gitignore | 11 + Action.php | 497 +++++++++++++++++++++++++ Plugin.php | 807 +++++++++++++++++++++++++++++++++++++++++ README.md | 168 ++++++++- Util.php | 326 +++++++++++++++++ tests/auth_test.php | 123 +++++++ tests/host_test.php | 153 ++++++++ tests/render_test.php | 225 ++++++++++++ tests/setting_test.php | 211 +++++++++++ tests/token_test.php | 202 +++++++++++ tests/util_test.php | 171 +++++++++ tools/cookie.php | 73 ++++ tools/probe.php | 424 ++++++++++++++++++++++ 14 files changed, 3398 insertions(+), 2 deletions(-) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 Action.php create mode 100644 Plugin.php create mode 100644 Util.php create mode 100644 tests/auth_test.php create mode 100644 tests/host_test.php create mode 100644 tests/render_test.php create mode 100644 tests/setting_test.php create mode 100644 tests/token_test.php create mode 100644 tests/util_test.php create mode 100644 tools/cookie.php create mode 100644 tools/probe.php diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..e1f6429 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# 统一按 LF 存储,避免 Windows 检出成 CRLF 后部署到 Linux 出问题 +* text=auto eol=lf + +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.ico binary +*.webp binary diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2a53530 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# ---- 测试沙箱与临时产物 ---- +.ti_setting_tmp/ +.ti_*/ +*.tmp +*.tmp.js +/js_*.js + +# ---- 本地环境 ---- +.DS_Store +Thumbs.db +*.log diff --git a/Action.php b/Action.php new file mode 100644 index 0000000..ead2274 --- /dev/null +++ b/Action.php @@ -0,0 +1,497 @@ +assertAuthorized($cfg); + + // 设置页的「测试连接」按钮:do=test,不接收文件,只验证 Token 与图床版本 + if ($this->param('do') === 'test') { + $this->testConnection($cfg); + } + + if (strtoupper(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '') !== 'POST') { + $this->json(['code' => 0, 'msg' => '仅支持 POST 上传']); + } + + if (empty($_FILES['image']) || is_array($_FILES['image']['error'])) { + $this->json(['code' => 0, 'msg' => '没有收到图片文件(表单字段名应为 image)']); + } + + $file = $_FILES['image']; + + if ($file['error'] !== UPLOAD_ERR_OK) { + $this->json(['code' => 0, 'msg' => self::uploadErrorMessage($file['error'])]); + } + + $tmp = $file['tmp_name']; + if (!is_uploaded_file($tmp)) { + $this->json(['code' => 0, 'msg' => '上传的临时文件无效']); + } + + $maxBytes = max(1, (int) $cfg['maxSize']) * 1048576; + if ($file['size'] <= 0 || $file['size'] > $maxBytes) { + $this->json([ + 'code' => 0, + 'msg' => '图片大小不合要求(当前 ' . ceil($file['size'] / 1024) . ' KB,上限 ' + . $cfg['maxSize'] . ' MB)', + ]); + } + + // 用图片头真实校验类型,禁止 SVG / PHP 等可执行内容混过 image/* 判断 + $image = self::imageMime($tmp); + if ($image === null) { + $this->json(['code' => 0, 'msg' => '仅支持 jpg / png / gif / webp / bmp 图片']); + } + + $name = self::safeName($file['name'], $image['ext']); + $apiUrl = trim((string) $cfg['apiUrl']); + + if (!preg_match('#^https?://#i', $apiUrl)) { + $this->json(['code' => 0, 'msg' => '上传接口地址必须以 http:// 或 https:// 开头']); + } + + $byToken = $cfg['authMode'] === 'token'; + + $extra = Util::parsePairs($cfg['extraFields'], '='); + // Token 模式只用请求头传凭证,不再作为表单字段重复发送 + if (!$byToken && $cfg['token'] !== '' && !isset($extra['token'])) { + $extra['token'] = $cfg['token']; + } + + $headers = [ + 'User-Agent' => 'Mozilla/5.0 (compatible; TypechoTinyImgUploader/2.0)', + 'Referer' => Util::deriveReferer($apiUrl), + 'X-Requested-With' => 'XMLHttpRequest', + ]; + foreach (Util::parsePairs($cfg['headers'], ':') as $key => $value) { + $headers[$key] = $value; + } + $headers = array_filter($headers, function ($value) { + return $value !== ''; + }); + + // 凭证只在服务端使用,浏览器收到的是同源 Action 地址,看不到任何图床秘密。 + $asAdmin = $cfg['authMode'] !== 'guest'; + + if ($byToken) { + // 推荐方式:独立 API Token,只被图床的 functions/upload.php 识别 + $apiToken = trim((string) $cfg['token']); + + if ($apiToken === '') { + $this->json([ + 'code' => 0, + 'msg' => '已开启 API Token 上传,但未填写 Token:请到图床后台「Token 设置」生成,' + . '填入插件设置后用「测试连接」验证', + ]); + } + + $headers['X-TinyImg-Token'] = $apiToken; + } elseif ($asAdmin) { + // 兼容方式:模拟图床后台登录 Cookie(TinyImg 1.x 原生逻辑) + $cookie = Util::adminCookie($cfg['adminUser'], $cfg['adminSecret']); + + if ($cookie === null) { + $this->json([ + 'code' => 0, + 'msg' => '已开启管理员上传,但未填写图床管理员账号或密码/Cookie,请到插件设置里补全', + ]); + } + + $existing = ''; + foreach ($headers as $key => $value) { + if (strcasecmp($key, 'Cookie') === 0) { + $existing = $value; + unset($headers[$key]); + } + } + + $headers['Cookie'] = Util::mergeCookie($existing, $cookie); + } + + $fieldName = trim((string) $cfg['fieldName']); + if ($fieldName === '') { + $fieldName = 'file'; + } + + $fields = $extra; + $fields[$fieldName] = [ + 'file' => $tmp, + 'mime' => $image['mime'], + 'name' => $name, + ]; + + $result = self::forward($apiUrl, $fields, $headers); + + if ($result['error']) { + $this->json(['code' => 0, 'msg' => '转发到图床失败:' . $result['error']]); + } + + if ($result['status'] && ($result['status'] < 200 || $result['status'] >= 300)) { + $this->json([ + 'code' => 0, + 'msg' => '图床返回 HTTP ' . $result['status'] . ':' . Util::clip($result['body'], 200), + ]); + } + + $parsed = Util::parseResponse($result['body'], $apiUrl); + + if ($parsed['code'] !== 1) { + $this->json([ + 'code' => 0, + 'msg' => $parsed['msg'], + 'raw' => Util::clip($result['body'], 300), + ]); + } + + $out = [ + 'code' => 1, + 'url' => $parsed['url'], + 'name' => $name, + 'as' => $asAdmin ? 'admin' : 'guest', + ]; + + // 图床在 Cookie 不匹配时不会报错,而是静默回落到游客目录。 + // 用返回地址里的目录名反查一次,避免「以为改成管理员、其实没生效」。 + if ($asAdmin && Util::inAdminDir($parsed['url'], $cfg['adminDir']) === false) { + $out['warn'] = $byToken + ? '图片已上传,但地址里没有管理员目录「' . $cfg['adminDir'] + . '」:图床没有按 Token 识别身份。请到图床后台「Token 设置」确认 Token 已启用,' + . '并与插件设置里的值完全一致;可用「测试连接」按钮复核。' + : '图片已上传,但地址里没有管理员目录「' . $cfg['adminDir'] + . '」:图床没认出管理员身份,本次实际仍是游客上传。请核对图床 config.php 的 ' + . 'user / password,或把「管理员上传目录名」改成你实际的 admindir。'; + } + + $this->json($out); + } + + private static function config() + { + return Plugin::settings(); + } + + /** 从 Typecho Request 读取参数,取不到时回落到原始超全局(兼容不同 1.3 构建) */ + private function param($key) + { + $value = $this->request->get($key); + + if ($value === null && isset($_GET[$key])) { + $value = $_GET[$key]; + } + if ($value === null && isset($_POST[$key])) { + $value = $_POST[$key]; + } + + return is_scalar($value) ? (string) $value : null; + } + + /** 登录 + 用户组 + CSRF;校验失败一律返回 JSON,不做 302 跳转 */ + private function assertAuthorized(array $cfg) + { + $group = $cfg['allowGroup'] === 'administrator' ? 'administrator' : 'contributor'; + + if (!$this->user->hasLogin() || !$this->user->pass($group, true)) { + $this->json([ + 'code' => 0, + 'msg' => $group === 'administrator' + ? '请先登录后台,且需要「管理员」权限' + : '请先登录后台,且账号至少具有「贡献者」权限', + ]); + } + + // 与 Widget\Security::protect() 等价,但校验失败时返回 JSON 而不是 302 跳转 + $token = $this->param('_'); + if (!$token || $token !== $this->security->getToken($this->request->getReferer())) { + $this->json(['code' => 0, 'msg' => '安全校验失败,请刷新页面后重试']); + } + } + + /** + * 设置页「测试连接」:用输入框里的 Token 请求图床 upload.php?ping=1。 + * 不上传任何文件、不写数据库;Token 只出现在服务端到图床的请求头里。 + */ + private function testConnection(array $cfg) + { + if (strtoupper(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : '') !== 'POST') { + $this->json(['code' => 0, 'msg' => '测试连接需要 POST 请求']); + } + + $token = trim((string) $this->param('token')); + if ($token === '') { + $token = trim((string) $cfg['token']); // 允许直接测已保存的 Token + } + if ($token === '') { + $this->json(['code' => 0, 'msg' => '请先在上方填入 API Token(可点击「测试连接」前不保存)']); + } + + $apiUrl = trim((string) $cfg['apiUrl']); + if (!preg_match('#^https?://#i', $apiUrl) || strpos($apiUrl, 'img.example.com') !== false) { + $this->json([ + 'code' => 0, + 'msg' => '「图床上传接口地址」仍是占位值或格式不对,请先改成你的实际地址(functions/upload.php)', + ]); + } + + $headers = [ + 'User-Agent' => 'Mozilla/5.0 (compatible; TypechoTinyImgUploader/2.0)', + 'Referer' => Util::deriveReferer($apiUrl), + 'X-Requested-With' => 'XMLHttpRequest', + 'Accept' => 'application/json', + ]; + foreach (Util::parsePairs($cfg['headers'], ':') as $key => $value) { + if ($value !== '') { + $headers[$key] = $value; + } + } + // 强制覆盖,避免「附加请求头」里误配同名项导致测的不是当前 Token + $headers['X-TinyImg-Token'] = $token; + + $result = self::forward(Util::pingUrl($apiUrl), [], array_filter($headers, function ($v) { + return $v !== ''; + })); + + if ($result['error']) { + $this->json(['code' => 0, 'msg' => '连接图床失败:' . $result['error']]); + } + + if ($result['status'] && ($result['status'] < 200 || $result['status'] >= 300)) { + $this->json([ + 'code' => 0, + 'msg' => '图床返回 HTTP ' . $result['status'], + 'raw' => Util::clip($result['body'], 200), + ]); + } + + $data = json_decode(trim((string) $result['body']), true); + + if (!is_array($data)) { + $this->json([ + 'code' => 0, + 'msg' => '图床返回的不是 JSON:请确认已升级到 TinyImg 2.0(支持 ?ping=1),且接口地址正确', + 'raw' => Util::clip($result['body'], 200), + ]); + } + + if (!isset($data['code']) || (string) $data['code'] !== '1') { + $this->json([ + 'code' => 0, + 'msg' => isset($data['msg']) ? (string) $data['msg'] : 'Token 校验未通过', + 'raw' => Util::clip($result['body'], 200), + ]); + } + + $out = [ + 'code' => 1, + 'msg' => '连接成功,Token 有效', + 'name' => isset($data['name']) ? (string) $data['name'] : '', + 'version' => isset($data['version']) ? (string) $data['version'] : '', + 'admin_dir' => isset($data['admin_dir']) ? (string) $data['admin_dir'] : '', + ]; + + $reportedDir = $out['admin_dir']; + if ($reportedDir !== '' && $cfg['adminDir'] !== '' + && strcasecmp($reportedDir, $cfg['adminDir']) !== 0) { + $out['warn'] = '图床报告的管理员目录是「' . $reportedDir . '」,插件填的是「' + . $cfg['adminDir'] . '」,请把插件设置改成一致,否则上传后会误报身份未生效'; + } + + if ($cfg['authMode'] !== 'token') { + $out['warn'] = (isset($out['warn']) ? $out['warn'] . ';' : '') + . '注意:当前鉴权方式为「' . $cfg['authMode'] . '」,实际上传不会使用这个 Token'; + } + + $this->json($out); + } + + private static function imageMime($path) + { + $info = @getimagesize($path); + $mime = ($info && !empty($info['mime'])) ? $info['mime'] : ''; + + $allowed = [ + 'image/jpeg' => 'jpg', + 'image/pjpeg' => 'jpg', + 'image/png' => 'png', + 'image/gif' => 'gif', + 'image/webp' => 'webp', + 'image/bmp' => 'bmp', + 'image/x-ms-bmp'=> 'bmp', + ]; + + return isset($allowed[$mime]) ? ['mime' => $mime, 'ext' => $allowed[$mime]] : null; + } + + private static function safeName($name, $ext) + { + $name = basename(str_replace('\\', '/', (string) $name)); + $name = preg_replace('/[^\x20-\x7e]/', '', $name); + $name = str_replace(['"', "\r", "\n", '/'], '', $name); + $name = trim($name); + + if ($name === '' || $name === '.' || $name === '..') { + $name = 'image'; + } + + if (!preg_match('/\.[a-z0-9]{2,5}$/i', $name)) { + $name .= '.' . $ext; + } + + return $name; + } + + private static function uploadErrorMessage($code) + { + $messages = [ + UPLOAD_ERR_INI_SIZE => '超过服务器 upload_max_filesize 限制', + UPLOAD_ERR_FORM_SIZE => '超过表单 MAX_FILE_SIZE 限制', + UPLOAD_ERR_PARTIAL => '文件只上传了一部分', + UPLOAD_ERR_NO_FILE => '没有选择文件', + UPLOAD_ERR_NO_TMP_DIR => '服务器缺少临时目录', + UPLOAD_ERR_CANT_WRITE => '服务器写入临时文件失败', + UPLOAD_ERR_EXTENSION => 'PHP 扩展中止了上传', + ]; + + return isset($messages[$code]) ? $messages[$code] : ('未知上传错误:' . $code); + } + + /** + * 优先 curl;没有 curl 扩展时退回 stream 手工拼 multipart。 + */ + private static function forward($url, array $fields, array $headers) + { + return function_exists('curl_init') + ? self::forwardByCurl($url, $fields, $headers) + : self::forwardByStream($url, $fields, $headers); + } + + private static function forwardByCurl($url, array $fields, array $headers) + { + $postFields = []; + + foreach ($fields as $key => $value) { + $postFields[$key] = (is_array($value) && isset($value['file'])) + ? new \CURLFile($value['file'], $value['mime'], $value['name']) + : $value; + } + + $lines = ['Expect:']; + foreach ($headers as $key => $value) { + $lines[] = $key . ': ' . $value; + } + + $ch = curl_init(); + curl_setopt_array($ch, [ + CURLOPT_URL => $url, + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $postFields, + CURLOPT_HTTPHEADER => $lines, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_CONNECTTIMEOUT => 10, + CURLOPT_TIMEOUT => 45, + CURLOPT_FOLLOWLOCATION => true, + CURLOPT_MAXREDIRS => 3, + CURLOPT_SSL_VERIFYPEER => true, + CURLOPT_SSL_VERIFYHOST => 2, + ]); + + $body = curl_exec($ch); + + if ($body === false) { + $error = curl_error($ch); + curl_close($ch); + return ['error' => $error, 'status' => 0, 'body' => '']; + } + + $status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + + return ['error' => null, 'status' => $status, 'body' => (string) $body]; + } + + private static function forwardByStream($url, array $fields, array $headers) + { + $random = function_exists('random_bytes') ? bin2hex(random_bytes(8)) : md5(uniqid('', true)); + $boundary = '----TypechoIU' . $random; + $body = ''; + + foreach ($fields as $key => $value) { + $safeKey = str_replace(['"', "\r", "\n"], '', $key); + $body .= '--' . $boundary . "\r\n"; + + if (is_array($value) && isset($value['file'])) { + $safeName = str_replace(['"', "\r", "\n"], '', $value['name']); + $body .= 'Content-Disposition: form-data; name="' . $safeKey + . '"; filename="' . $safeName . '"' . "\r\n"; + $body .= 'Content-Type: ' . $value['mime'] . "\r\n\r\n"; + $body .= file_get_contents($value['file']) . "\r\n"; + } else { + $body .= 'Content-Disposition: form-data; name="' . $safeKey . '"' . "\r\n\r\n"; + $body .= $value . "\r\n"; + } + } + + $body .= '--' . $boundary . "--\r\n"; + + $header = 'Content-Type: multipart/form-data; boundary=' . $boundary . "\r\n"; + foreach ($headers as $key => $value) { + $header .= $key . ': ' . $value . "\r\n"; + } + + $context = stream_context_create([ + 'http' => [ + 'method' => 'POST', + 'header' => $header, + 'content' => $body, + 'timeout' => 45, + 'ignore_errors' => true, + 'follow_location' => 1, + 'max_redirects' => 3, + ], + ]); + + $response = @file_get_contents($url, false, $context); + + if ($response === false) { + $last = error_get_last(); + return [ + 'error' => $last ? $last['message'] : '请求失败(allow_url_fopen 可能已关闭)', + 'status' => 0, + 'body' => '', + ]; + } + + $status = 0; + if (isset($http_response_header[0]) && preg_match('#\s(\d{3})\s#', $http_response_header[0], $m)) { + $status = (int) $m[1]; + } + + return ['error' => null, 'status' => $status, 'body' => $response]; + } + + private function json(array $data) + { + $this->response->setContentType('application/json'); + echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + exit; + } +} diff --git a/Plugin.php b/Plugin.php new file mode 100644 index 0000000..73c5b52 --- /dev/null +++ b/Plugin.php @@ -0,0 +1,807 @@ + 确认 -> 上传到自建 TinyImg 图床 -> 把 Markdown 插入光标处。 + * + * @package TinyImgUploader + * @author BuddyRobot + * @version 2.0.0 + * @since 1.3.0 + */ +class Plugin implements PluginInterface +{ + /** 插件目录名,也是设置项的命名空间 */ + const NAME = 'TinyImgUploader'; + + /** Action 名,对应 /action/tinyimg-uploader */ + const ACTION = 'tinyimg-uploader'; + + /** 允许显式留空的设置项:留空表示「跳过管理员目录校验」 */ + const NULLABLE = ['adminDir']; + + /** 设置项默认值 */ + const DEFAULTS = [ + // 占位地址:部署后请改成自己图床的 functions/upload.php 绝对地址 + 'apiUrl' => 'https://img.example.com/functions/upload.php', + 'fieldName' => 'file', + 'mode' => 'proxy', + 'authMode' => 'token', + 'adminUser' => '', + 'adminSecret' => '', + 'adminDir' => 'upload', + 'allowGroup' => 'contributor', + 'token' => '', + 'extraFields' => '', + 'headers' => '', + 'maxSize' => '2', + 'template' => '![%alt%](%url%)', + ]; + + public static function activate() + { + // 侧栏卡片:admin/write-post.php:119 / admin/write-page.php:145 + \Typecho\Plugin::factory('admin/write-post.php')->option = __CLASS__ . '::renderOption'; + \Typecho\Plugin::factory('admin/write-page.php')->option = __CLASS__ . '::renderOption'; + + // 弹窗与脚本:页面底部,此时 jQuery 已加载 + \Typecho\Plugin::factory('admin/write-post.php')->bottom = __CLASS__ . '::renderFooter'; + \Typecho\Plugin::factory('admin/write-page.php')->bottom = __CLASS__ . '::renderFooter'; + + Helper::addAction(self::ACTION, Action::class); + + return _t('图床上传已启用;请在设置里填写图床 functions/upload.php 地址,并填入图床后台「Token 设置」页生成的 API Token,然后点「测试连接」验证'); + } + + public static function deactivate() + { + Helper::removeAction(self::ACTION); + } + + public static function config(Form $form) + { + $apiUrl = new Text( + 'apiUrl', + null, + self::DEFAULTS['apiUrl'], + _t('图床上传接口地址'), + _t('TinyImg 2.0 的上传端点:https://你的图床域名/functions/upload.php。默认值是占位地址,必须改成你的实际地址;以 http:// 或 https:// 开头。') + ); + $apiUrl->addRule('required', _t('请填写上传接口地址')); + $apiUrl->input->setAttribute('class', 'w-100 text'); + $form->addInput($apiUrl); + + $authMode = new Radio( + 'authMode', + [ + 'token' => _t('API Token(推荐,TinyImg 2.0 原生支持)'), + 'admin' => _t('管理员 Cookie(回退方案,凭证等价于后台密码)'), + 'guest' => _t('游客上传(图片进 temp 目录,受每日数量限制)'), + ], + self::DEFAULTS['authMode'], + _t('上传到图床的鉴权方式'), + _t('Token 用 X-TinyImg-Token 请求头,由图床后台「Token 设置」页生成,只在服务端出现;Cookie 模式模拟图床后台登录态。详见 README 的鉴权方案对比。') + ); + $form->addInput($authMode); + + $adminUser = new Text( + 'adminUser', + null, + '', + _t('图床管理员账号'), + _t('图床 config.php 里 user 配置项的值,必须与图床完全一致(区分大小写)。') + ); + $form->addInput($adminUser); + + // 个别 Typecho 构建可能没有 Password 元素,降级成普通输入框以免设置页直接 500 + $secretElement = class_exists('Typecho\\Widget\\Helper\\Form\\Element\\Password') + ? Password::class + : Text::class; + + $adminSecret = new $secretElement( + 'adminSecret', + null, + '', + _t('图床管理员密码 / 登录 Cookie 值'), + _t('可填明文密码(插件自动算 md5("tinyimg" + 密码) 作为 Cookie);更推荐用 tools/cookie.php 算出 32 位值后填入,或直接复制图床登录后 Cookie 里的 password 值,避免明文密码存入数据库。') + ); + $form->addInput($adminSecret); + + $adminDir = new Text( + 'adminDir', + null, + self::DEFAULTS['adminDir'], + _t('管理员上传目录名'), + _t('图床 config.php 里 admindir 的值,默认 upload。上传后用它检查是否真的以管理员身份生效;留空则跳过该检查。') + ); + $form->addInput($adminDir); + + $allowGroup = new Radio( + 'allowGroup', + [ + 'contributor' => _t('贡献者及以上(默认)'), + 'administrator' => _t('仅博客管理员可用'), + ], + self::DEFAULTS['allowGroup'], + _t('允许使用该插件的博客用户组'), + _t('这是 Typecho 侧的权限,与上面的图床身份无关;两处都设为管理员即实现「仅管理员以管理员身份上传」。') + ); + $form->addInput($allowGroup); + + $fieldName = new Text( + 'fieldName', + null, + self::DEFAULTS['fieldName'], + _t('文件表单字段名'), + _t('TinyImg 2.0 为 file;其它图床可能是 image、smfile 等,按接口文档填写。') + ); + $form->addInput($fieldName); + + $mode = new Radio( + 'mode', + [ + 'proxy' => _t('服务端代理(推荐,无需图床开放 CORS)'), + 'direct' => _t('浏览器直连(需图床返回 CORS 响应头)'), + ], + self::DEFAULTS['mode'], + _t('上传方式'), + _t('实测本图床未返回 Access-Control-Allow-Origin,默认必须用服务端代理;Token / Cookie 模式会强制走代理,防止凭证下发到浏览器。') + ); + $form->addInput($mode); + + $maxSize = new Text( + 'maxSize', + null, + self::DEFAULTS['maxSize'], + _t('单张图片上限(MB)'), + _t('TinyImg 2.0 源码里硬编码 file_max_size = 2097152(2 MB),填大于 2 会被图床拒绝。') + ); + $maxSize->addRule('required', _t('请填写大小上限')); + $maxSize->addRule('isInteger', _t('请填写整数')); + $form->addInput($maxSize); + + $template = new Text( + 'template', + null, + self::DEFAULTS['template'], + _t('插入 Markdown 模板'), + _t('可用占位符:%url% 图片地址、%alt% 不含扩展名的文件名、%name% 原文件名。想和极简图床页面完全一致可填 ![](%url%)。') + ); + $template->input->setAttribute('class', 'w-100 mono'); + $form->addInput($template); + + $token = new $secretElement( + 'token', + null, + '', + _t('图床 API Token'), + _t('在图床后台「Token 设置」页生成或复制,粘贴到此处,两处必须完全一致。Token 模式用 X-TinyImg-Token 请求头在服务端发送,不写入撰写页、不出现在 URL;Cookie / 游客模式下本项留空。') + . self::testButtonHtml() + ); + $token->input->setAttribute('class', 'w-100 mono'); + $form->addInput($token); + + $extraFields = new Textarea( + 'extraFields', + null, + '', + _t('附加表单字段(可选)'), + _t('每行一项,格式 key=value,例如 uid=1。用于需要 uid / apiType / folder 等参数的图床。') + ); + $form->addInput($extraFields); + + $headers = new Textarea( + 'headers', + null, + '', + _t('附加请求头(可选,仅代理模式)'), + _t('每行一项,格式 Key: Value。例如需要登录态时填 Cookie: xxxx,或覆盖 Referer。默认已自动带 User-Agent、Referer、X-Requested-With。') + ); + $form->addInput($headers); + } + + public static function personalConfig(Form $form) + { + } + + /** + * 设置页「测试连接」按钮的 HTML(由 config() 放进 Token 字段的说明里)。 + * + * 走博客同源的 /action/tinyimg-uploader?do=test,由 PHP 携带 Token 去请求 + * 图床的 functions/upload.php?ping=1,因此不受跨域限制、也不会把图床地址 + * 或 Token 暴露给撰写文章页。URL 里的 _ 参数是 Typecho 的 CSRF 令牌。 + * + * 单独做成 public 方法,便于 tests/render_test.php 直接断言而不必 stub 整套表单类。 + */ + public static function testButtonHtml() + { + $testUrl = ''; + + try { + if (class_exists('\\Widget\\Security')) { + $testUrl = \Widget\Security::alloc()->getIndex('/action/' . self::ACTION . '?do=test'); + } + } catch (\Throwable $e) { + $testUrl = ''; + } + + $jsonUrl = json_encode( + (string) $testUrl, + JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT + ); + + $html = '' + . '' + . '' + . '' + . '' + . _t('测试会读取上方输入框里的 Token(无需先保存),验证图床是否认这个 Token,并返回图床版本与管理员目录。') + . ''; + + if ($testUrl === '') { + return $html . '' . _t('无法生成安全令牌,请刷新设置页后重试') . ''; + } + + $js = <<<'TIJS' + +TIJS; + + return $html . str_replace('__TEST_URL__', $jsonUrl, $js); + } + + /** + * 读取设置,缺失项回落默认值。禁用插件会清空设置,这里做兜底避免出现 500。 + * Action 也复用本方法,保证权限校验与转发行为读的是同一份配置。 + */ + public static function settings() + { + try { + $saved = Options::alloc()->plugin(self::NAME)->toArray(); + } catch (\Typecho\Plugin\Exception $e) { + $saved = []; + } + + foreach (self::DEFAULTS as $key => $default) { + $exists = array_key_exists($key, $saved); + // adminDir 允许显式留空(表示跳过目录校验) + $nullableEmpty = $exists && $saved[$key] === '' && in_array($key, self::NULLABLE, true); + + if (!$exists || ($saved[$key] === '' && !$nullableEmpty)) { + $saved[$key] = $default; + } + } + + return $saved; + } + + /** + * 「仅博客管理员可用」时,非管理员连侧栏卡片都不显示。 + * Action 里仍会再做一次权限校验,这里是纯粹的界面收敛。 + */ + private static function canUse(array $cfg) + { + if ($cfg['allowGroup'] !== 'administrator' || !class_exists('\\Widget\\User')) { + return true; + } + + $user = \Widget\User::alloc(); + + return (bool) ($user->hasLogin() && $user->pass('administrator', true)); + } + + /** + * option 钩子:右侧「选项」标签页内的上传卡片。 + */ + public static function renderOption($content) + { + $cfg = self::settings(); + + if (!self::canUse($cfg)) { + return; + } + + $limit = htmlspecialchars((string) $cfg['maxSize'], ENT_QUOTES, 'UTF-8'); + + echo '
'; + echo ''; + echo '

'; + echo '

' . _t('选图并确认后上传到自建图床,自动把 Markdown 插入光标处;也可拖入图片或在弹窗内 Ctrl+V 粘贴。单张不超过 ') + . $limit . ' MB。

'; + + if (!Options::alloc()->markdown) { + echo '

' + . _t('当前站点未开启 Markdown,插入的图片语法可能不会被解析。') . '

'; + } + + $mode = $cfg['authMode']; + $identity = $mode === 'token' ? _t('API Token') + : ($mode === 'admin' ? _t('管理员 Cookie') : _t('游客')); + $missing = ($mode === 'token' && $cfg['token'] === '') + || ($mode === 'admin' && ($cfg['adminUser'] === '' || $cfg['adminSecret'] === '')); + $hint = $mode === 'token' + ? _t('(未填写 API Token,上传会被拒绝;请到图床后台「Token 设置」页生成后填入插件设置)') + : _t('(未填写管理员账号或密码/Cookie,上传会被拒绝)'); + + echo '

' . _t('图床身份:') . '' . $identity . ''; + if ($missing) { + echo ' ' . $hint . ''; + } + echo '

'; + + // 默认接口地址是占位符,没改过就上传必然失败,这里提前拦住并给出明确指引 + if (strpos($cfg['apiUrl'], 'img.example.com') !== false) { + echo '

' + . _t('插件设置里的「图床上传接口地址」仍是占位值,请先改成你的实际地址,并用「测试连接」验证。') + . '

'; + } + + echo '

'; + echo '
'; + } + + /** + * bottom 钩子:弹窗 DOM、样式、交互脚本。 + */ + public static function renderFooter($content) + { + $cfg = self::settings(); + $actionUrl = \Widget\Security::alloc()->getIndex('/action/' . self::ACTION); + + // Token / Cookie 模式携带服务端凭证,绝不允许把请求切到浏览器直连 + $mode = ($cfg['mode'] === 'direct' && $cfg['authMode'] === 'guest') ? 'direct' : 'proxy'; + + $jsCfg = [ + 'mode' => $mode, + 'template' => (string) $cfg['template'], + 'maxSize' => max(1, (int) $cfg['maxSize']), + 'actionUrl' => $actionUrl, + ]; + + // 直连模式必须把接口信息下发到浏览器;代理模式下 token 只留在服务端。 + if ($jsCfg['mode'] === 'direct') { + $jsCfg['apiUrl'] = (string) $cfg['apiUrl']; + $jsCfg['fieldName'] = (string) $cfg['fieldName']; + $jsCfg['token'] = (string) $cfg['token']; + $jsCfg['extra'] = Util::parsePairs($cfg['extraFields'], '='); + } + + $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_HEX_TAG + | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT; + + echo ''; + + echo <<<'IUCSS' + +IUCSS; + + echo <<<'IUHTML' +
+
+ +
+IUHTML; + + echo <<<'IUJS' + +IUJS; + } +} diff --git a/README.md b/README.md index 21f8950..587b8f6 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,167 @@ -# TinyImgUploader +# TinyImgUploader 2.0.0 — Typecho 1.3 图床上传插件 -TinyImgUploader typecho 1.3 \ No newline at end of file +在 Typecho 撰写文章 / 页面右侧「选项」栏增加一个图片上传窗口:点击按钮 → 弹窗选图并预览 → 确认上传 → 图片上传到自建 **TinyImg 2.0** 图床 → Markdown 自动插入编辑框光标处。 +插件设置页里可以填 API Token,并有 **「测试连接」按钮** 一键验证图床是否认这个 Token。 + +--- + +## 1. 本次变更 + +| # | 变更 | +|---|---| +| 1 | 插件目录、命名空间、Action 名统一改为 `TinyImgUploader` / `tinyimg-uploader` | +| 2 | 请求头改为 `X-TinyImg-Token`,配合图床 2.0 的后台 Token 设置页 | +| 3 | 设置页 Token 字段新增「测试连接」按钮,读取输入框当前值(**无需先保存**),返回图床版本与管理员目录 | +| 4 | 图床 `?ping=1` 自检端点由插件的服务端 Action 调用,不受跨域限制、不把凭证下发给浏览器 | +| 5 | 默认值改为占位地址 `https://img.example.com/functions/upload.php`,侧栏会在未修改时给出红色提示 | +| 6 | 去掉旧的图床补丁包(`patch/` 目录):Token 现在是图床原生功能 | +| 7 | 管理员 Cookie 回退方案的盐同步改为 `tinyimg`;新增 `tests/host_test.php`、`tests/setting_test.php` 等六组测试 | + +--- + +## 2. 从 v1.2 升级(需要重装一次,请先看这节) + +插件目录名变了,Typecho 靠目录名识别插件,**不能只覆盖文件**。 + +> ⚠️ **禁用插件会清空它的设置**。请先把旧设置页里的接口地址、插入模板等抄下来。 + +1. 打开 Typecho 后台 → 控制台 → 插件 → **禁用 v1.2 旧插件**(记录现有设置)。 +2. 删除服务器上 `usr/plugins/` 里 v1.2 的旧插件目录(就是之前上传的那个目录)。 +3. 把 `TinyImgUploader.zip` 解压到 `usr/plugins/`,确认 `usr/plugins/TinyImgUploader/Plugin.php` 存在。 +4. 后台启用 **TinyImgUploader**,进入「设置」。 +5. 填写「图床上传接口地址」与「图床 API Token」(Token 在图床后台「Token 设置」页生成)。 +6. 点 **「测试连接」**,看到 `✓ 连接成功,Token 有效 · TinyImg v2.0.0(20261104) · 管理员目录 upload` 即完成。 +7. 保存设置,打开撰写文章页试传一张小图。 + +如果图床还没升级到 2.0,本插件无法直接使用:请先按 `../TinyImg/README.md` 部署图床。 + +--- + +## 3. 全新安装 + +1. 解压 `TinyImgUploader.zip` 到 `usr/plugins/`。 +2. 后台 → 控制台 → 插件 → 启用 **TinyImgUploader**。 +3. 设置里填接口地址 + Token,点「测试连接」验证,保存。 + +环境要求:Typecho 1.3、PHP ≥ 7.0;服务端代理模式需要 `curl` 扩展(没有时自动退回 `file_get_contents` 手工 multipart),并确认 `upload_max_filesize` / `post_max_size` ≥ 2M。 + +--- + +## 4. 配置项 + +| 配置项 | 默认值 | 说明 | +|---|---|---| +| **图床上传接口地址** | `https://img.example.com/functions/upload.php` | **占位值,必须改成你的实际地址**。`TinyImg 2.0` 是 `/functions/upload.php` | +| **上传到图床的鉴权方式** | `API Token` | 可选 `API Token` / `管理员 Cookie`(回退)/ `游客上传` | +| **图床 API Token** | 空 | 与图床后台「Token 设置」页一致;下方有 **「测试连接」按钮** | +| 图床管理员账号 | 空 | 仅 Cookie 模式使用,对应图床 `config.php` 的 `user` | +| 图床管理员密码 / 登录 Cookie 值 | 空 | 仅 Cookie 模式使用;推荐填 `tools/cookie.php` 生成的 32 位值 | +| 管理员上传目录名 | `upload` | 上传后据此判断身份是否真的生效;留空跳过判断 | +| 允许使用该插件的博客用户组 | 贡献者及以上 | 也可设为「仅博客管理员可用」 | +| 文件表单字段名 | `file` | TinyImg 2.0 用 `file` | +| 上传方式 | 服务端代理 | 图床未返回 CORS 头,默认必须走代理;Token / Cookie 模式**强制**代理 | +| 单张图片上限(MB) | `2` | 图床源码硬编码 2 MB | +| 插入 Markdown 模板 | `![%alt%](%url%)` | 占位符 `%url%` / `%alt%` / `%name%`;想与极简上传页一致填 `![](%url%)` | +| 附加表单字段 / 附加请求头 | 空 | 每行 `key=value` / `Key: Value` | + +--- + +## 5. 「测试连接」按钮怎么工作 + +按钮在 **插件设置页** 的 Token 输入框下方,不在撰写页。 + +``` +设置页点击「测试连接」 + │ 读取 input[name=token] 当前值(不必先保存设置) + ▼ +POST 博客同源 /action/tinyimg-uploader?do=test&_= + │ 服务端校验:登录 + 用户组 + Typecho 安全令牌 + ▼ +PHP curl 转发 POST 到 图床 /functions/upload.php?ping=1 + │ 请求头 X-TinyImg-Token: + ▼ +图床只校验 Token,不接收文件、不写库 + │ 返回 {code:1, name, version, admin_dir} + ▼ +博客 Action 比对管理员目录、附加 warn,返回 JSON + ▼ +按钮旁显示 ✓/✗、图床版本、管理员目录 +``` + +要点: + +- Token 只出现在「设置页输入框 → 博客服务端 → 图床请求头」这条链路里,**撰写文章页源码里没有任何图床地址或 Token**。 +- 测试不上传图片、不产生数据;可以直接测试刚粘贴但还没保存的新 Token。 +- 若图床返回的 `admin_dir` 与插件设置不一致,或当前鉴权方式不是 `token`,会给出橙色警告。 +- 图床侧未升级到 2.0(不支持 `?ping=1`)时会明确提示「请确认已升级到 TinyImg 2.0」。 + +--- + +## 6. 使用流程 + +1. 撰写文章 / 页面 → 右侧「选项」栏出现「图床上传」卡片,点「选择图片上传」。 +2. 弹窗里点选、拖入,或 Ctrl+V 粘贴图片 → 预览 → 点「确认上传」。 +3. 上传成功后自动把 Markdown 插入 `#text` 光标处,并触发 `input` / `change` 让草稿自动保存与预览刷新;弹窗自动关闭。 +4. 若身份没生效(例如 Token 被停用但仍以游客身份成功),弹窗**不会关闭**并显示橙色警告。 + +--- + +## 7. 排错 + +| 现象 | 原因 | 处理 | +|---|---|---| +| 侧栏红字「接口地址仍是占位值」 | 没改 `apiUrl` | 设置里填实际 `https://你的域名/functions/upload.php` | +| 测试连接返回「请先在上方填入 API Token」 | Token 输入框为空且未保存过 | 从图床后台「Token 设置」复制 Token 粘进来 | +| 测试连接返回「API Token 无效!」 | 两处 Token 不一致 / 图床已停用 | 图床后台确认状态,重新生成并同步 | +| 测试连接返回「图床返回的不是 JSON」 | 图床不是 2.0 / 地址填错 / CSRF 过期 | 确认地址指向 `functions/upload.php`;刷新设置页重试 | +| 测试连接返回「安全校验失败」 | Typecho 安全令牌过期 | 刷新插件设置页再点 | +| 上传成功但提示「没按 Token 识别身份」 | 返回 URL 不含 `/upload/` | 检查「管理员上传目录名」是否与图床 `admindir` 一致 | +| 真实上传报错「API Token 未配置」 | 图床还没生成 / 启用 Token | 到图床后台「Token 设置」生成 | +| 升级后后台登录被踢出 | 图床 Cookie 盐改为 `tinyimg` | 到 `admin/login.php` 重新登录一次 | +| v1.2 插件突然不能上传 | 请求头已改名 | 按第 2 节升级插件 | + +--- + +## 8. 验证命令 + +```bash +cd TinyImgUploader + +# 纯逻辑测试,不需要 Typecho、不需要联网 +php tests/util_test.php # 响应解析 + ?ping=1 地址推导 +php tests/auth_test.php # Cookie 回退方案契约 +php tests/token_test.php # 图床 Token 纯函数 + 上传端点契约 + 错误实现反证 +php tests/render_test.php # 侧栏、弹窗、测试按钮渲染与凭证隔离 +php tests/host_test.php # 图床更名 / 版本 / SM.MS 下线 / 设置页 +php tests/setting_test.php # 图床 Token 设置页渲染:完整 Token 不得出现在 HTML、reveal 必须校验 CSRF + +# 命令行连通性自检(需要 PHP 的 curl 或 openssl 扩展) +php tools/probe.php --url=https://你的域名/functions/upload.php --token=你的Token --ping +php tools/probe.php --url=https://你的域名/functions/upload.php --token=你的Token --file=./test.png +``` + +`tools/cookie.php` 仅在回退到「管理员 Cookie」模式时才需要: + +```bash +php tools/cookie.php 管理员账号 '明文密码' +``` + +--- + +## 9. 安全说明 + +1. Token 只被图床上传端点与自检端点识别,泄露也只能上传图片,**不能进图床后台**。 +2. 插件侧校验登录态、用户组与 Typecho CSRF 令牌;Token / Cookie 模式下强制服务端代理。 +3. 上传前用 `getimagesize()` 校验真实图片头,挡住 SVG / 伪装脚本;大小与类型双重限制。 +4. 图床比较用 `hash_equals`,空配置 / 停用 / 空请求一律 fail closed。 +5. 请全程使用 HTTPS;Token 不要提交到公开仓库、不要放进 URL。 +6. 轮换 Token 后,图床后台与插件设置都要更新,并用「测试连接」复核。 + +--- + +## 10. 已知限制 + +- 图床硬限 2 MB;本插件默认上限也是 2 MB。 +- 直接改 `textarea` 的 `value` 不会被 PageDown 的撤销栈记录(插入后 Ctrl+Z 可能不还原)。 +- 若博客与图床证书 / 协议不匹配(HTTPS 页面请求 HTTP 图床),服务端代理不受浏览器混合内容限制,但仍建议全 HTTPS。 +- 本机 PHP 若缺 `curl` / `openssl`,`tools/probe.php` 的联网部分需在博客服务器上运行。 diff --git a/Util.php b/Util.php new file mode 100644 index 0000000..d7b1716 --- /dev/null +++ b/Util.php @@ -0,0 +1,326 @@ + https://host/tinyimg/ + */ + public static function deriveReferer($apiUrl) + { + $parts = parse_url((string) $apiUrl); + + if (!$parts || empty($parts['scheme']) || empty($parts['host'])) { + return ''; + } + + $base = $parts['scheme'] . '://' . $parts['host']; + + if (isset($parts['port'])) { + $base .= ':' . $parts['port']; + } + + $path = isset($parts['path']) ? $parts['path'] : '/'; + $dir = preg_replace('#/[^/]*$#', '', $path); + $dir = preg_replace('#/functions$#', '', $dir); + + return $base . rtrim($dir, '/') . '/'; + } + + /** + * 由上传接口地址生成连接自检地址(TinyImg 2.0 的 ?ping=1 通道)。 + * 只校验 Token、不接收文件,返回图床版本与管理员目录。 + * + * https://host/functions/upload.php -> https://host/functions/upload.php?ping=1 + * https://host/functions/upload.php?x=1 -> https://host/functions/upload.php?x=1&ping=1 + */ + public static function pingUrl($apiUrl) + { + $url = trim((string) $apiUrl); + + if ($url === '') { + return ''; + } + + // 去掉可能存在的 #fragment,避免把 ping=1 拼到片段后面 + $hash = strpos($url, '#'); + if ($hash !== false) { + $url = substr($url, 0, $hash); + } + + return $url . (strpos($url, '?') === false ? '?' : '&') . 'ping=1'; + } + + /** + * 把图床返回的绝对 / 协议相对 / 根相对 / 相对地址统一成 http(s) 绝对地址。 + */ + public static function normalizeUrl($url, $baseUrl) + { + $url = trim((string) $url); + + if ($url === '') { + return null; + } + + if (preg_match('#^https?://#i', $url)) { + return $url; + } + + $parts = parse_url((string) $baseUrl); + + if (!$parts || empty($parts['scheme']) || empty($parts['host'])) { + return null; + } + + $base = $parts['scheme'] . '://' . $parts['host']; + + if (isset($parts['port'])) { + $base .= ':' . $parts['port']; + } + + if (strpos($url, '//') === 0) { + return $parts['scheme'] . ':' . $url; + } + + if (strpos($url, '/') === 0) { + return $base . $url; + } + + $path = isset($parts['path']) ? $parts['path'] : '/'; + $dir = preg_replace('#/[^/]*$#', '', $path); + + return $base . rtrim($dir, '/') . '/' . ltrim($url, '/'); + } + + /** + * 在任意层级的数组里递归查找图片地址。 + */ + public static function findUrl($value, $depth = 0) + { + if ($depth > 8 || !is_array($value)) { + return null; + } + + foreach (['url', 'link', 'src', 'image', 'original'] as $key) { + if (isset($value[$key]) && is_string($value[$key])) { + $candidate = trim($value[$key]); + + // 绝对 / 协议相对 / 根相对地址,或任意以图片扩展名结尾的相对路径 + if (preg_match('#^(https?://|//|/)#i', $candidate) + || preg_match('#\.(jpe?g|png|gif|webp|bmp)(\?.*)?$#i', $candidate)) { + return $candidate; + } + } + } + + foreach ($value as $item) { + $found = self::findUrl($item, $depth + 1); + + if ($found !== null) { + return $found; + } + } + + return null; + } + + /** + * 把图床原始响应统一成 ['code' => 1|0, 'url' => string|null, 'msg' => string]。 + * + * 兼容: + * TinyImg 2.0 成功 {"code":1,"id":9,"url":"https://...","width":800,"height":600} + * TinyImg 2.0 失败 {"code":0,"msg":"API Token 无效!"} + * 其它图床 {"code":200,"data":{"url":"https://..."}} + * 通用 {"success":true,"data":{"url":"..."}} + * + * 注意:TinyImg 语义里 code=0 表示失败,因此即使响应里带了 url 也判为失败。 + */ + public static function parseResponse($body, $baseUrl = '') + { + $body = trim((string) $body); + + if ($body === '') { + return ['code' => 0, 'url' => null, 'msg' => '图床返回空内容(可能是 PHP 报错或 5xx)']; + } + + $data = json_decode($body, true); + + if (!is_array($data)) { + // 有些 PHP 程序会在 JSON 前面输出 BOM / notice,尝试截到第一个 { 或 [ + $trimmed = preg_replace('/^[^{[]*/', '', $body); + $data = @json_decode($trimmed, true); + } + + if (!is_array($data)) { + return ['code' => 0, 'url' => null, 'msg' => '图床返回的不是 JSON:' . self::clip($body, 160)]; + } + + $rawUrl = self::findUrl($data); + $code = isset($data['code']) ? (string) $data['code'] : ''; + + if ($rawUrl === null || $code === '0') { + $msg = '图床未返回图片地址'; + + foreach (['msg', 'message', 'error', 'err'] as $key) { + if (!empty($data[$key]) && is_string($data[$key])) { + $msg = $data[$key]; + break; + } + } + + return [ + 'code' => 0, + 'url' => null, + 'msg' => $msg . ' | 原始响应:' . self::clip($body, 160), + ]; + } + + $url = self::normalizeUrl($rawUrl, $baseUrl); + + if ($url === null) { + return ['code' => 0, 'url' => null, 'msg' => '无法解析图片地址:' . $rawUrl]; + } + + return ['code' => 1, 'url' => $url, 'msg' => 'ok']; + } + + /** + * 构造管理员登录 Cookie(回退方案,两个字段)。 + * + * 源码依据(TinyImg/functions/class/class.user.php): + * functions/class/class.user.php:32-35 login() + * $password = md5("tinyimg" . $admin['password']); + * setcookie("user", $user['user'], ...); setcookie("password", $password, ...); + * functions/class/class.user.php:41-52 check() + * $user1 = $config['user'] . md5("tinyimg" . $config['password']); + * $user2 = $_COOKIE['user'] . $_COOKIE['password']; + * $user1 == $user2 ? 'islogin' : 'nologin' + * functions/upload.php:15-23 + * islogin -> admindir,且跳过 limitnum();否则 -> userdir + 每日数量限制 + * + * $secret 既可以填 config.php 里的明文密码,也可以填图床登录后 Cookie 中的 + * password 值(32 位十六进制 md5)。后者可避免明文密码存进 Typecho 数据库。 + * 返回的 user 已按 PHP setcookie() 的规则 urlencode,可直接放进 Cookie 头。 + */ + public static function adminCookie($user, $secret) + { + $user = trim((string) $user); + $secret = trim((string) $secret); + + if ($user === '' || $secret === '') { + return null; + } + + $password = preg_match('/^[a-f0-9]{32}$/i', $secret) + ? strtolower($secret) + : md5('tinyimg' . $secret); + + return [ + 'user' => rawurlencode($user), + 'password' => $password, + ]; + } + + /** + * 把鉴权字段合并进已有的 Cookie 头:同名字段覆盖,其它字段保留。 + */ + public static function mergeCookie($existing, array $pairs) + { + $jar = []; + + foreach (explode(';', (string) $existing) as $part) { + $part = trim($part); + + if ($part === '' || strpos($part, '=') === false) { + continue; + } + + list($key, $value) = explode('=', $part, 2); + $key = trim($key); + + if ($key !== '') { + $jar[$key] = trim($value); + } + } + + foreach ($pairs as $key => $value) { + $jar[$key] = $value; + } + + $line = []; + foreach ($jar as $key => $value) { + $line[] = $key . '=' . $value; + } + + return implode('; ', $line); + } + + /** + * 判断图片地址是否落在管理员上传目录。 + * TinyImg 的 URL 形如 https://host/upload/2611/hash.jpg。 + * 返回 null 表示未配置目录名、跳过判定;true / false 表示判定结果。 + */ + public static function inAdminDir($url, $dir) + { + $dir = trim((string) $dir, "/ \t\n\r\0\x0B"); + + if ($dir === '') { + return null; + } + + $path = parse_url((string) $url, PHP_URL_PATH); + + if (!is_string($path)) { + return false; + } + + return (bool) preg_match('#/' . preg_quote($dir, '#') . '/#i', $path); + } + + public static function clip($text, $length) + { + $text = preg_replace('/\s+/u', ' ', (string) $text); + + return function_exists('mb_substr') + ? mb_substr($text, 0, $length, 'UTF-8') + : substr($text, 0, $length); + } +} diff --git a/tests/auth_test.php b/tests/auth_test.php new file mode 100644 index 0000000..27dd403 --- /dev/null +++ b/tests/auth_test.php @@ -0,0 +1,123 @@ + 0, 'fail' => 0]; + +$check = function ($name, $ok, $detail = '') use (&$stat) { + if ($ok) { + $stat['pass']++; + echo ' [PASS] ' . $name . PHP_EOL; + } else { + $stat['fail']++; + echo ' [FAIL] ' . $name . ($detail === '' ? '' : ' -> ' . $detail) . PHP_EOL; + } +}; + +/** 逐字复刻 class.user.php::check(),$_COOKIE 的值已被 PHP 自动 urldecode */ +function tinyimgIsLogin(array $config, array $cookies) +{ + $user1 = $config['user'] . md5('tinyimg' . $config['password']); + $user2 = (isset($cookies['user']) ? rawurldecode($cookies['user']) : '') + . (isset($cookies['password']) ? rawurldecode($cookies['password']) : ''); + + return $user1 === $user2 ? 'islogin' : 'nologin'; +} + +$root = dirname(__DIR__, 2) . '/TinyImg'; +$userSource = $root . '/functions/class/class.user.php'; +$uploadSource = $root . '/functions/upload.php'; + +echo PHP_EOL . '1. 与 TinyImg 源码的契约比对' . PHP_EOL; + +if (is_file($userSource) && is_file($uploadSource)) { + $u = file_get_contents($userSource); + $p = file_get_contents($uploadSource); + + $check('login() 用 md5("tinyimg" + 密码) 生成 password Cookie', + strpos($u, 'md5("tinyimg".$admin[\'password\'])') !== false); + $check('check() 期望 user + md5("tinyimg" + 密码)', + strpos($u, 'md5("tinyimg".$userinfo[\'password\'])') !== false); + $check('check() 比较的是 $_COOKIE[\'user\'] . $_COOKIE[\'password\']', + strpos($u, '$_COOKIE[\'user\'].$_COOKIE[\'password\']') !== false); + $check('upload.php 登录时走 admindir', + strpos($p, 'if($status == \'islogin\')') !== false && strpos($p, '$updir = $config[\'admindir\'];') !== false); + $check('upload.php 游客分支才调用 limitnum()', + strpos($p, '$updir = $config[\'userdir\'];') !== false && strpos($p, '$basis->limitnum();') !== false); + $check('upload.php 先校验 Referer 再检查登录态', + strpos($p, 'HTTP_REFERER') !== false + && strpos($p, 'HTTP_REFERER') < strpos($p, '$basis->check($config)')); +} else { + echo ' [SKIP] 未找到 TinyImg 源码目录,跳过源码契约比对(不影响下面的纯逻辑测试)' . PHP_EOL; +} + +echo PHP_EOL . '2. Util::adminCookie 生成的凭证能否通过图床 check()' . PHP_EOL; + +$config = ['user' => 'imgadmin', 'password' => 'p@ssw0rd']; +$plain = Util::adminCookie($config['user'], $config['password']); +$md5 = md5('tinyimg' . $config['password']); + +$check('明文密码 -> islogin', tinyimgIsLogin($config, $plain) === 'islogin', json_encode($plain)); +$check('password Cookie 值等于 md5("tinyimg"+密码)', $plain['password'] === $md5, $plain['password']); +$check('直接填 32 位 Cookie 值 -> islogin', + tinyimgIsLogin($config, Util::adminCookie($config['user'], $md5)) === 'islogin'); +$check('32 位大写十六进制也能识别并归一', + Util::adminCookie($config['user'], strtoupper($md5))['password'] === $md5); +$check('错误密码 -> nologin', + tinyimgIsLogin($config, Util::adminCookie($config['user'], 'wrong')) === 'nologin'); +$check('错误账号 -> nologin', + tinyimgIsLogin($config, Util::adminCookie('someone', $config['password'])) === 'nologin'); +$check('账号或密码为空 -> null', + Util::adminCookie('', 'x') === null && Util::adminCookie('x', '') === null); +$check('含空格 / 中文的账号 urlencode 后仍能通过 check()', + tinyimgIsLogin(['user' => '张 三', 'password' => 'pw'], Util::adminCookie('张 三', 'pw')) === 'islogin'); + +echo PHP_EOL . '3. 测试集有效性反证(故意写错的实现)' . PHP_EOL; + +// 错误实现 A:漏掉盐值 "tinyimg",直接 md5(密码) +$badNoSalt = ['user' => $config['user'], 'password' => md5($config['password'])]; +$check('错误实现 A(无盐 md5)必须被图床判为 nologin', + tinyimgIsLogin($config, $badNoSalt) === 'nologin'); +// 错误实现 B:把明文密码直接当成 Cookie 值 +$badPlain = ['user' => $config['user'], 'password' => $config['password']]; +$check('错误实现 B(明文当 Cookie)必须被判为 nologin', + tinyimgIsLogin($config, $badPlain) === 'nologin'); +// 错误实现 C:把账号也拼进 md5 +$badBoth = ['user' => $config['user'], 'password' => md5('tinyimg' . $config['user'] . $config['password'])]; +$check('错误实现 C(账号参与哈希)必须被判为 nologin', + tinyimgIsLogin($config, $badBoth) === 'nologin'); +$check('同一份配置下正确实现必须是 islogin(证明测试能区分对错)', + tinyimgIsLogin($config, $plain) === 'islogin'); + +echo PHP_EOL . '4. Cookie 合并与目录判定' . PHP_EOL; + +$merged = Util::mergeCookie('theme=dark; user=old; PHPSESSID=abc', $plain); +$check('保留用户自定义 Cookie', strpos($merged, 'theme=dark') !== false && strpos($merged, 'PHPSESSID=abc') !== false, $merged); +$check('覆盖同名的 user / password', + strpos($merged, 'user=old') === false && strpos($merged, 'password=' . $md5) !== false, $merged); +$check('空 Cookie 头也能生成', Util::mergeCookie('', $plain) === 'user=' . $config['user'] . '; password=' . $md5); + +$check('管理员目录 URL 判定为 true', + Util::inAdminDir('https://img.example.com/tinyimg/upload/2611/abcd.jpg', 'upload') === true); +$check('游客目录 URL 判定为 false(可据此发出警告)', + Util::inAdminDir('https://img.example.com/tinyimg/temp/2611/abcd.jpg', 'upload') === false); +$check('目录名前后斜杠被归一化', + Util::inAdminDir('https://img.example.com/tinyimg/upload/2611/abcd.jpg', '/upload/') === true); +$check('目录名留空 -> null(跳过校验)', + Util::inAdminDir('https://img.example.com/tinyimg/temp/2611/abcd.jpg', '') === null); + +echo PHP_EOL . str_repeat('-', 56) . PHP_EOL; +echo '结果:' . $stat['pass'] . ' 通过 / ' . $stat['fail'] . ' 失败' . PHP_EOL; +exit($stat['fail'] === 0 ? 0 : 1); diff --git a/tests/host_test.php b/tests/host_test.php new file mode 100644 index 0000000..0c3911c --- /dev/null +++ b/tests/host_test.php @@ -0,0 +1,153 @@ + 0, 'fail' => 0]; + +$check = function ($name, $ok, $detail = '') use (&$stat) { + if ($ok) { + $stat['pass']++; + echo ' [PASS] ' . $name . PHP_EOL; + } else { + $stat['fail']++; + echo ' [FAIL] ' . $name . ($detail === '' ? '' : ' -> ' . $detail) . PHP_EOL; + } +}; + +$root = dirname(__DIR__, 2); +$host = $root . '/TinyImg'; +$plugin = $root . '/TinyImgUploader'; + +// 拼接构造,避免测试代码自身成为「旧品牌字面量」的命中项 +$forbidden = 'img' . 'url'; + +/** 递归收集文本文件(跳过第三方 layui 与二进制文件) */ +function host_text_files($dir) +{ + $out = []; + $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)); + foreach ($it as $f) { + $path = str_replace('\\', '/', $f->getPathname()); + if (strpos($path, '/static/layui/') !== false) { + continue; + } + $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION)); + if (!in_array($ext, ['php', 'js', 'html', 'htm', 'css', 'txt', 'md', 'json', 'svg', 'htaccess'], true) + && !in_array(basename($path), ['.htaccess', '.gitignore', 'LICENSE'], true)) { + continue; + } + $out[] = ['path' => $path, 'body' => file_get_contents($path)]; + } + return $out; +} + +$hostFiles = host_text_files($host); +$pluginFiles = host_text_files($plugin); + +echo PHP_EOL . '1. 更名与版本号' . PHP_EOL; + +$oldNameHits = 0; +foreach (array_merge($hostFiles, $pluginFiles) as $f) { + $oldNameHits += substr_count(strtolower($f['body']), $forbidden); +} +$check('两个工程源码里旧品牌字样为 0', $oldNameHits === 0, '命中 ' . $oldNameHits . ' 处'); + +$version = trim(file_get_contents($host . '/functions/version.txt')); +$check('版本号更新为 v2.0.0', strpos($version, 'v2.0.0') === 0, $version); +$check('版本文件带构建日期', (bool) preg_match('/\(\d{8}\)/', $version), $version); +$check('存在统一版本模块 functions/version.php', is_file($host . '/functions/version.php')); +$check('旧的 v1.40 版本号不再出现在版本文件', strpos($version, '1.40') === false); +$check('前台关于页读取统一版本号', + strpos(file_get_contents($host . '/about.php'), 'TINYIMG_VERSION') !== false); +$check('后台关于弹窗读取统一版本号', + strpos(file_get_contents($host . '/admin/about.php'), 'TINYIMG_VERSION') !== false); +$check('站点标题统一为 TinyImg', + strpos(file_get_contents($host . '/index.php'), 'TinyImg') !== false + && strpos(file_get_contents($host . '/tpl/admin/header.php'), '

TinyImg

') !== false); + +echo PHP_EOL . '2. SM.MS 上传通道已屏蔽 / 移除' . PHP_EOL; + +$smUploadHits = 0; +foreach ($hostFiles as $f) { + $smUploadHits += substr_count(strtolower($f['body']), 'sm.ms/api'); +} +$check('没有任何对 sm.ms 上传 API 的请求', $smUploadHits === 0, '命中 ' . $smUploadHits . ' 处'); + +$miniup = file_get_contents($host . '/miniup.html'); +$check('极简上传页没有 SM.MS 选项卡', strpos($miniup, '
  • SM.MS
  • ') === false); +$check('极简上传页没有 #sm 文件输入', strpos($miniup, 'id="sm"') === false); +$check('极简上传页保留本站拖拽上传', strpos($miniup, 'id="upimg"') !== false); + +$embed = file_get_contents($host . '/static/embed.js'); +$check('embed.js 没有 smshow / deletesm 函数', + strpos($embed, 'function smshow') === false && strpos($embed, 'function deletesm') === false); +$check('embed.js 保留本站上传逻辑', + strpos($embed, "url: 'functions/upload.php'") !== false); + +$left = file_get_contents($host . '/tpl/admin/left.php'); +$check('后台左侧菜单没有 SM.MS 入口', strpos($left, 'smadmin.php') === false); +$check('后台左侧菜单新增 Token 设置入口', strpos($left, 'setting.php') !== false); +$check('后台顶部导航新增 Token 设置入口', + strpos(file_get_contents($host . '/tpl/admin/header.php'), './setting.php') !== false); +$check('前台导航没有 SM.MS 入口', + strpos(file_get_contents($host . '/tpl/user/header.php'), 'sm.php') === false); + +$smPage = file_get_contents($host . '/sm.php'); +$check('sm.php 返回 410 且不提供上传表单', + strpos($smPage, 'http_response_code(410)') !== false && strpos($smPage, 'id="sm"') === false); +$smFunc = file_get_contents($host . '/functions/sm.php'); +$check('functions/sm.php fail closed,不写数据库', + strpos($smFunc, 'http_response_code(410)') !== false + && strpos($smFunc, '$database->insert') === false); +$smAdmin = file_get_contents($host . '/admin/smadmin.php'); +$check('admin/smadmin.php 不再查询数据库', strpos($smAdmin, 'querysm') === false); +$check('admin/delete.php 拒绝 type=sm', + strpos(file_get_contents($host . '/admin/delete.php'), "=== 'sm'") !== false); +$adminClass = file_get_contents($host . '/functions/class/class.admin.php'); +$check('class.admin.php 已移除 querysm / deletesm', + strpos($adminClass, 'function querysm') === false && strpos($adminClass, 'function deletesm') === false); +$check('upgrade.php 不再创建 sm 表', + strpos(file_get_contents($host . '/upgrade.php'), 'CREATE TABLE') === false); + +echo PHP_EOL . '3. Token 设置页与存储' . PHP_EOL; + +$check('admin/setting.php 存在', is_file($host . '/admin/setting.php')); +$check('functions/token.php 存在', is_file($host . '/functions/token.php')); +$check('Token 存储文件带 PHP 守卫(不会通过 URL 泄漏)', + strpos(file_get_contents($host . '/functions/token.php'), "cfg = $cfg; + } + + public function toArray() + { + return $this->cfg; + } + }; + } + } + + class Security + { + public static function alloc() + { + return new self(); + } + + public function getIndex($path) + { + // 模拟 Typecho:getTokenUrl 会把 _ 参数并进已有 query + $sep = strpos($path, '?') === false ? '?' : '&'; + return 'https://blog.example.com' . $path . $sep . '_=FAKE_TOKEN'; + } + } +} + +namespace { + use TypechoPlugin\TinyImgUploader\Plugin; + + define('__TYPECHO_ROOT_DIR__', dirname(__DIR__)); + + function _t($text) + { + return $text; + } + + require_once dirname(__DIR__) . '/Util.php'; + require_once dirname(__DIR__) . '/Plugin.php'; + + $stat = ['pass' => 0, 'fail' => 0]; + + $check = function ($name, $ok, $detail = '') use (&$stat) { + if ($ok) { + $stat['pass']++; + echo ' [PASS] ' . $name . PHP_EOL; + } else { + $stat['fail']++; + echo ' [FAIL] ' . $name . ($detail === '' ? '' : ' -> ' . $detail) . PHP_EOL; + } + }; + + ob_start(); + Plugin::renderOption(null); + $option = ob_get_clean(); + + ob_start(); + Plugin::renderFooter(null); + $footer = ob_get_clean(); + + echo PHP_EOL . '1. option 钩子:右侧栏卡片' . PHP_EOL; + $check('输出 #iu-box 容器', strpos($option, 'id="iu-box"') !== false); + $check('输出打开按钮 #iu-open', strpos($option, 'id="iu-open"') !== false); + $check('输出状态行 #iu-status', strpos($option, 'id="iu-status"') !== false); + $check('显示 2 MB 上限提示', strpos($option, '2 MB') !== false); + $check('侧栏显示图床身份(默认 API Token)', + strpos($option, '图床身份:') !== false && strpos($option, 'API Token') !== false); + $check('未填凭证时侧栏给出红色告警并指向图床后台设置页', + strpos($option, '未填写 API Token') !== false + && strpos($option, 'Token 设置') !== false); + $check('接口地址仍是占位值时侧栏给出红色告警', + strpos($option, '仍是占位值') !== false); + $check('侧栏不含任何 Token 明文 / 图床地址', + strpos($option, 'SUPER_SECRET') === false && strpos($option, 'img.example.com') === false); + + echo PHP_EOL . '2. bottom 钩子:弹窗与脚本' . PHP_EOL; + $check('输出 #iu-modal 弹窗', strpos($footer, 'id="iu-modal"') !== false); + $check('输出确认按钮 #iu-confirm', strpos($footer, 'id="iu-confirm"') !== false); + $check('输出文件输入 #iu-file', strpos($footer, 'id="iu-file"') !== false); + $check('包含 insertMarkdown 插入逻辑', strpos($footer, 'function insertMarkdown') !== false); + $check('包含捕获阶段粘贴拦截', strpos($footer, "addEventListener('paste'") !== false); + $check('包含 CSS 样式块', strpos($footer, '.iu-modal') !== false); + + echo PHP_EOL . '3. 注入的前端配置' . PHP_EOL; + $matched = preg_match('/window\.IU_CFG=(\{.*?\});<\/script>/s', $footer, $matches); + $cfg = $matched ? json_decode($matches[1], true) : null; + + $check('window.IU_CFG 是合法 JSON', is_array($cfg), $matched ? $matches[1] : '未匹配到配置'); + $check('默认走服务端代理', is_array($cfg) && isset($cfg['mode']) && $cfg['mode'] === 'proxy'); + $check( + 'Action 地址带 CSRF 令牌', + is_array($cfg) && isset($cfg['actionUrl']) + && strpos($cfg['actionUrl'], '/action/tinyimg-uploader?_=FAKE_TOKEN') !== false, + is_array($cfg) && isset($cfg['actionUrl']) ? $cfg['actionUrl'] : '' + ); + $check('代理模式下不把 token 下发到浏览器', is_array($cfg) && !array_key_exists('token', $cfg)); + $check('代理模式下不把图床地址下发到浏览器', is_array($cfg) && !array_key_exists('apiUrl', $cfg)); + $check( + '默认插入模板正确', + is_array($cfg) && isset($cfg['template']) && $cfg['template'] === '![%alt%](%url%)' + ); + + echo PHP_EOL . '4. 身份失效警告的前端处理' . PHP_EOL; + $check('上传成功分支里处理服务端返回的 warn', strpos($footer, 'data.warn') !== false); + $check('有 warn 时不自动关闭弹窗', strpos($footer, 'showError(data.warn)') !== false); + $check('状态行区分管理员 / 游客', strpos($footer, "'管理员' : '游客'") !== false); + + echo PHP_EOL . '5. Token 模式:凭证隔离 + 强制服务端代理' . PHP_EOL; + + \Widget\Options::$pluginConfig = [ + 'authMode' => 'token', + 'token' => 'SUPER_SECRET_TOKEN_VALUE', + 'adminDir' => 'upload', + 'mode' => 'direct', // 故意直连,验证会被强制改回代理 + 'allowGroup' => 'administrator', + ]; + + ob_start(); + Plugin::renderOption(null); + Plugin::renderFooter(null); + $withToken = ob_get_clean(); + + $check('已配置 Token 时侧栏不再报「未填写」', strpos($withToken, '未填写 API Token') === false); + $check('页面源码里不含 Token 明文', strpos($withToken, 'SUPER_SECRET_TOKEN_VALUE') === false); + $check('页面源码里不含图床地址', strpos($withToken, 'img.example.com') === false); + $check('身份标识为 API Token', strpos($withToken, 'API Token') !== false); + + preg_match('/window\.IU_CFG=(\{.*?\});<\/script>/s', $withToken, $m2); + $cfg2 = isset($m2[1]) ? json_decode($m2[1], true) : null; + $check('即使设置里选了直连,Token 模式仍强制 proxy', + is_array($cfg2) && isset($cfg2['mode']) && $cfg2['mode'] === 'proxy'); + $check('注入配置里没有 token / apiUrl 字段', + is_array($cfg2) && !array_key_exists('token', $cfg2) && !array_key_exists('apiUrl', $cfg2)); + + echo PHP_EOL . '6. Cookie 模式(回退方案):凭证同样隔离' . PHP_EOL; + + \Widget\Options::$pluginConfig = [ + 'authMode' => 'admin', + 'adminUser' => 'imgadmin', + 'adminSecret' => 'SUPER_SECRET_PLAINTEXT', + 'adminDir' => 'upload', + 'allowGroup' => 'administrator', + ]; + + ob_start(); + Plugin::renderOption(null); + Plugin::renderFooter(null); + $withCookie = ob_get_clean(); + + $check('已配置时侧栏不再报「未填写」', strpos($withCookie, '未填写管理员账号') === false); + $check('页面源码里不含明文密码 / Cookie 值', + strpos($withCookie, 'SUPER_SECRET_PLAINTEXT') === false + && strpos($withCookie, 'password=') === false); + $check('页面源码里不含图床管理员账号', strpos($withCookie, 'imgadmin') === false); + $check('身份标识为管理员 Cookie', strpos($withCookie, '管理员 Cookie') !== false); + + echo PHP_EOL . '7. 设置页「测试连接」按钮' . PHP_EOL; + + $testHtml = Plugin::testButtonHtml(); + + $check('渲染测试按钮与结果区', + strpos($testHtml, 'id="ti-test-btn"') !== false + && strpos($testHtml, 'id="ti-test-result"') !== false); + $check('按钮文案是「测试连接」', strpos($testHtml, '测试连接') !== false); + $check('测试 URL 指向 do=test 且带 CSRF 令牌', + strpos($testHtml, '/action/tinyimg-uploader?do=test&_=FAKE_TOKEN') !== false); + $check('用 fetch 发 POST 并读取输入框里的 Token', + strpos($testHtml, "fetch(URL") !== false + && strpos($testHtml, "input[name=\"token\"]") !== false + && strpos($testHtml, "fd.append('token'") !== false); + $check('页面源码里不出现图床地址或 Token 明文', + strpos($testHtml, 'SUPER_SECRET') === false + && strpos($testHtml, 'X-TinyImg-Token') === false); + $check('提示语说明无需先保存即可测试', + strpos($testHtml, '无需先保存') !== false); + + preg_match('##s', $testHtml, $jsMatch); + $check('测试按钮脚本被完整包在