Files
Sdf1_login/api/gh_oauth.php
T
ypsdf1 083f760207 15m44v: 修附件占位符替换+token验真+ghLog路径
- gh_api.php ghSyncCreate: 占位符替换串 '\U📎 附件\1\E' 改 '\u📎 附件\1'
  根因: PCRE 的 \U..\E 是大小写转换开关, 夹在 emoji 后把 CJK 误转/乱码,
  导致 issue body 里 [图片N] 未正确替换为附件提示; \u 对 CJK 恒等无副作用
  加 create 诊断日志(has_attach/desc_head/imgs)写 /plugin/gh_sync.log
- gh_api.php ghLog: 路径 dirname(__DIR__)→__DIR__
  根因: gh_api.php 在 /plugin/, __DIR__=/plugin, 旧 dirname 得到网站根 /,
  日志被写到网站根而非 /plugin → 用户在 /plugin 找永远 NOT FOUND
- gh_api.php ghApiRequest: 加 Cache-Control: no-store 头, 防 CF 边缘缓存验活响应
- gh_oauth.php: /user 验活加唯一 query 尾巴(x=nocache_<ts>rand), 破 CF 缓存,
  验活响应不可信是'没授权却显示已授权'根因; 加 probe 日志
- img.json: 修第21行混入的非法字符(反引号+中文逗号, heredoc 事故残留), 保持纯占位符
2026-11-25 15:59:07 +08:00

192 lines
9.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 15m44l 工单第二批 / 15m44m:GitHub issue 双向同步 —— OAuth 授权端点(玩家逐次授权)
*
* 两个用途:
* 1) 发起授权(GET, 无 code):302 到 GitHub OAuth App 的 authorize 页,state=玩家名(CSRF)。
* 玩家名解析优先级:?token=(validateTokenSilent 反解)→ ?player=(兜底)→ 'anon'。
* 前端只需带自己的 TOKEN 即可,不用知道玩家名。
* 2) 回调(GET, 带 code+state):code+client_secret 换 access_token,state=玩家名,
* 写 web_tickets.gh_access_token(按玩家名),回跳 player.php?gh_ok=1&gh_user=xxx。
*
* 凭据全在 img.json(repo.Client ID / Client secrets + repo.webhook_secret),本文件不含敏感值。
* gh_enabled=false(模式.type≠GitHub)时直接报错,避免误跳。
*
* 给用户配的 2 条 URL 之一:
* OAuth 回调(Redirect URI): https://caoyuan.ypshidifu.cn/plugin/api/gh_oauth.php
*/
while (ob_get_level() > 0) { @ob_end_clean(); }
ob_start();
header('X-Content-Type-Options: nosniff');
error_reporting(E_ALL);
ini_set('display_errors', '0');
if (function_exists('opcache_invalidate')) { @opcache_invalidate(__FILE__); }
require_once __DIR__ . '/../core.php';
require_once __DIR__ . '/../lsky.php';
require_once __DIR__ . '/../gh_api.php'; // 15m44s: ghApiRequest(验活 token)
$cfg = loadImgJson();
if (!$cfg['gh_enabled']) {
header('Content-Type: text/html; charset=utf-8');
echo '<meta charset="utf-8"><title>GitHub 工单同步未启用</title>'
. '<p>GitHub issue 工单同步未启用(img.json 的 模式.type 需填 GitHub)。</p>'
. '<p><a href="javascript:history.back()">返回</a></p>';
exit;
}
$clientId = $cfg['gh_client_id'];
$clientSec = $cfg['gh_client_secret'];
$baseSite = rtrim('https://caoyuan.ypshidifu.cn/plugin', '/');
$oauthUrl = $baseSite . '/api/gh_oauth.php';
$ghAuthorize = 'https://github.com/login/oauth/authorize';
$ghToken = 'https://github.com/login/oauth/access_token';
$code = isset($_GET['code']) ? trim((string)$_GET['code']) : '';
// ★ 15m44s 变动:token 继承 —— 玩家已授权过且 access_token 仍有效,直接继承,不重弹授权。
// 只有真无效(401/过期)才重新走 OAuth。避免"一股脑说无效要重新授权"。
// 发起授权前(无 code)先查 gh_auth_tokens 里该玩家的 token,调 GitHub /user 验活:
// - 有效 → 302 回 player.php?gh_ok=1&gh_inherit=1(前端据此显示「已授权」,不弹 GitHub)
// - 无效/无记录 → 继续走下方 authorize 302 重新授权
if ($code === '') {
$probePlayer = '';
$probeTk = isset($_GET['token']) ? trim((string)$_GET['token']) : '';
if ($probeTk !== '') {
$pi = validateTokenSilent($probeTk);
if ($pi && !empty($pi['player'])) $probePlayer = $pi['player'];
}
if ($probePlayer === '' && isset($_GET['player'])) $probePlayer = trim((string)$_GET['player']);
if ($probePlayer !== '') {
$db = getDB();
try {
$db->exec("CREATE TABLE IF NOT EXISTS gh_auth_tokens (
player_name TEXT PRIMARY KEY,
gh_login TEXT DEFAULT '',
access_token TEXT NOT NULL,
updated_at INTEGER NOT NULL
)");
$st = $db->prepare("SELECT access_token, gh_login FROM gh_auth_tokens WHERE player_name = :p AND access_token != '' LIMIT 1");
$st->bindValue(':p', $probePlayer, SQLITE3_TEXT);
$trow = $st->execute()->fetchArray(SQLITE3_ASSOC);
} catch (\Throwable $e) { $trow = null; }
if ($trow && !empty($trow['access_token'])) {
// 验活:GitHub /user 用该 token,200=有效 401=失效。
// ★ 15m44v 修:验活加"破缓存"query —— 给 URL 拼一个每毫秒唯一的随机尾巴
// (如 /user?x=nocache_<ts><rand>),让 Cloudflare 无法把【同一 token 的验活响应】
// 缓存复用。根因:gh_oauth.php 发起授权时调 /user,CF 边缘可能缓存了该 token
// 上一次的 200 响应;token 真失效后(被 GitHub 撤销/过期),CF 仍吐缓存 200 →
// 前端误判"已授权"(用户实测:没授权却显示已授权、提单后 GitHub 又真同步了
// 说明 token 实际有效,但验活逻辑被 CF 缓存干扰导致显示态不可信)。
// 随机尾巴让每个验活都是全新 GET,CF 命中不了缓存,真实 200/401 才可信。
$v = ghApiRequest('GET', '/user?x=nocache_' . (int)microtime(true) . mt_rand(100000, 999999), null, $trow['access_token']);
ghLog('oauth probe player=' . $probePlayer . ' token=' . substr((string)$trow['access_token'], 0, 8)
. ' status=' . (int)$v['status'] . ' ok=' . ($v['ok'] ? 'y' : 'n'));
if (!empty($v['ok'])) {
header('Location: ' . $baseSite . '/player.php?gh_ok=1&gh_inherit=1&gh_user=' . urlencode((string)($trow['gh_login'] ?: '')));
exit;
}
// token 失效 → 继续走下方 authorize 重新授权
}
}
}
if ($code !== '') {
// ===== 回调:换 token =====
$player = isset($_GET['state']) ? trim((string)$_GET['state']) : '';
$scope = 'repo'; // issue 读+写需要 repo 权限
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ghToken);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'client_id' => $clientId,
'client_secret' => $clientSec,
'code' => $code,
'scope' => $scope,
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$body = curl_exec($ch);
$errno = curl_errno($ch);
curl_close($ch);
if ($errno) {
header('Content-Type: text/html; charset=utf-8');
echo '<meta charset="utf-8"><p>获取 GitHub token 失败(cURL ' . htmlspecialchars((string)$errno) . ')。</p>';
exit;
}
parse_str((string)$body, $tok);
$accessToken = isset($tok['access_token']) ? (string)$tok['access_token'] : '';
$ghUser = isset($tok['user_login']) ? (string)$tok['user_login'] : '';
if ($accessToken === '') {
$err = isset($tok['error']) ? (string)$tok['error'] : 'unknown';
header('Content-Type: text/html; charset=utf-8');
echo '<meta charset="utf-8"><p>GitHub 授权失败: ' . htmlspecialchars($err) . '。</p>'
. '<p><a href="javascript:history.back()">返回</a></p>';
exit;
}
// 写库:独立表 gh_auth_tokens(玩家名→GitHub access_token),不污染 web_tickets。
// 工单表只留 gh_issue_number 一列(记录已同步的 issue 号),授权 token 单独存。
$db = getDB();
try { $db->exec("ALTER TABLE web_tickets ADD COLUMN gh_issue_number TEXT DEFAULT ''"); } catch (\Throwable $e) {}
try {
$db->exec("CREATE TABLE IF NOT EXISTS gh_auth_tokens (
player_name TEXT PRIMARY KEY,
gh_login TEXT DEFAULT '',
access_token TEXT NOT NULL,
updated_at INTEGER NOT NULL
)");
$up = $db->prepare("INSERT INTO gh_auth_tokens (player_name, gh_login, access_token, updated_at)
VALUES (:p, :l, :t, :now)
ON CONFLICT(player_name) DO UPDATE SET
gh_login = :l2, access_token = :t2, updated_at = :now2");
$up->bindValue(':p', $player, SQLITE3_TEXT);
$up->bindValue(':l', $ghUser, SQLITE3_TEXT);
$up->bindValue(':t', $accessToken, SQLITE3_TEXT);
$up->bindValue(':now', time(), SQLITE3_INTEGER);
$up->bindValue(':l2', $ghUser, SQLITE3_TEXT);
$up->bindValue(':t2', $accessToken, SQLITE3_TEXT);
$up->bindValue(':now2', time(), SQLITE3_INTEGER);
$up->execute();
} catch (\Throwable $e) {
// 老库若不支持 ON CONFLICT,退化:先删后插
try {
$db->exec("DELETE FROM gh_auth_tokens WHERE player_name = '" . str_replace("'", "''", $player) . "'");
$db->exec("INSERT INTO gh_auth_tokens (player_name, gh_login, access_token, updated_at)
VALUES ('" . str_replace("'", "''", $player) . "', '" . str_replace("'", "''", $ghUser) . "',
'" . str_replace("'", "''", $accessToken) . "', " . time() . ")");
} catch (\Throwable $e2) { /* 忽略,回跳仍成功 */ }
}
// 回跳前端工单页,带成功标记
header('Location: ' . $baseSite . '/player.php?gh_ok=1&gh_user=' . urlencode($ghUser));
exit;
}
// ===== 发起授权:解析玩家名(token 优先,player 兜底)=====
$playerName = '';
$tk = isset($_GET['token']) ? trim((string)$_GET['token']) : '';
if ($tk !== '') {
$info = validateTokenSilent($tk);
if ($info && !empty($info['player'])) $playerName = $info['player'];
}
if ($playerName === '' && isset($_GET['player'])) $playerName = trim((string)$_GET['player']);
if ($playerName === '') $playerName = 'anon';
$state = $playerName;
$authUrl = $ghAuthorize . '?' . http_build_query([
'client_id' => $clientId,
'redirect_uri' => $oauthUrl,
'scope' => 'repo',
'state' => $state,
]);
header('Location: ' . $authUrl);
exit;