让分类、会员和示例工具共用同一账号,本地即可跑通登录与授权。 Co-authored-by: Cursor <cursoragent@cursor.com>
148 lines
5.9 KiB
PHP
148 lines
5.9 KiB
PHP
<?php
|
||
|
||
declare(strict_types=1);
|
||
|
||
$config = require __DIR__.'/config.php';
|
||
session_start();
|
||
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
|
||
|
||
if ($path === '/backchannel' && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
|
||
$body = json_decode(file_get_contents('php://input') ?: '', true) ?: [];
|
||
$file = __DIR__.'/revoked.json';
|
||
$list = is_file($file) ? json_decode((string) file_get_contents($file), true) : [];
|
||
$list[] = ['sub' => $body['sub'] ?? '', 'at' => time()];
|
||
file_put_contents($file, json_encode($list));
|
||
http_response_code(204);
|
||
exit;
|
||
}
|
||
|
||
$app = match (true) {
|
||
str_starts_with($path, '/notes'), str_starts_with($path, '/callback/notes') => 'notes',
|
||
str_starts_with($path, '/convert'), str_starts_with($path, '/callback/convert') => 'convert',
|
||
default => null,
|
||
};
|
||
|
||
if ($app === null) {
|
||
header('Location: /notes');
|
||
exit;
|
||
}
|
||
|
||
$client = $config['apps'][$app];
|
||
if (! isset($_SESSION['apps'][$app]) || ! is_array($_SESSION['apps'][$app])) {
|
||
$_SESSION['apps'][$app] = [];
|
||
}
|
||
$bucket = &$_SESSION['apps'][$app];
|
||
|
||
if (str_starts_with($path, '/callback/')) {
|
||
$expected = $bucket['state'] ?? '';
|
||
if (! hash_equals((string) $expected, (string) ($_GET['state'] ?? ''))) {
|
||
render($client['title'], '<p>登录状态校验失败,请回到工具重试。</p>', $config['portal']);
|
||
exit;
|
||
}
|
||
if (isset($_GET['error'])) {
|
||
render($client['title'], '<p>授权被拒绝。</p>', $config['portal']);
|
||
exit;
|
||
}
|
||
$token = httpPost($config['issuer'].'/oauth/token', [
|
||
'grant_type' => 'authorization_code',
|
||
'code' => $_GET['code'] ?? '',
|
||
'redirect_uri' => $client['redirect'],
|
||
'client_id' => $client['client_id'],
|
||
'client_secret' => $client['secret'],
|
||
'code_verifier' => $bucket['verifier'] ?? '',
|
||
]);
|
||
if (! isset($token['access_token'])) {
|
||
render($client['title'], '<p>换取登录凭证失败。</p><pre>'.htmlspecialchars(json_encode($token, JSON_UNESCAPED_UNICODE)).'</pre>', $config['portal']);
|
||
exit;
|
||
}
|
||
$bucket['access_token'] = $token['access_token'];
|
||
$bucket['refresh_token'] = $token['refresh_token'] ?? '';
|
||
header('Location: /'.$app);
|
||
exit;
|
||
}
|
||
|
||
$info = null;
|
||
if (! empty($bucket['access_token'])) {
|
||
$info = httpGet($config['issuer'].'/oauth/userinfo', $bucket['access_token']);
|
||
if (isset($info['error'])) {
|
||
$bucket = [];
|
||
$info = null;
|
||
}
|
||
}
|
||
|
||
if ($info === null) {
|
||
$verifier = rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '=');
|
||
$challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
|
||
$state = bin2hex(random_bytes(16));
|
||
$bucket = ['verifier' => $verifier, 'state' => $state];
|
||
$query = http_build_query([
|
||
'response_type' => 'code',
|
||
'client_id' => $client['client_id'],
|
||
'redirect_uri' => $client['redirect'],
|
||
'scope' => 'openid profile membership',
|
||
'state' => $state,
|
||
'nonce' => bin2hex(random_bytes(8)),
|
||
'code_challenge' => $challenge,
|
||
'code_challenge_method' => 'S256',
|
||
]);
|
||
header('Location: '.$config['issuer'].'/oauth/authorize?'.$query);
|
||
exit;
|
||
}
|
||
|
||
$membership = $info['membership'] ?? [];
|
||
$statusLabels = ['none' => '未开通', 'active' => '有效', 'grace' => '宽限期', 'expired' => '已过期', 'stopped' => '已停用'];
|
||
$statusText = $statusLabels[$membership['status'] ?? 'none'] ?? (string) ($membership['status'] ?? '');
|
||
$allowed = ($membership['entitlements']['tool:'.$app.':access'] ?? false) === true || $app === 'notes';
|
||
$body = '<p>当前用户编号:'.htmlspecialchars((string) ($info['sub'] ?? '')).'</p>'
|
||
.'<p>昵称:'.htmlspecialchars((string) ($info['name'] ?? '')).'</p>'
|
||
.'<p>会员:'.htmlspecialchars((string) ($membership['plan_name'] ?? '免费')).'('.htmlspecialchars($statusText).')</p>'
|
||
.'<p>权益版本:'.htmlspecialchars((string) ($membership['entitlement_version'] ?? '')).'</p>';
|
||
if ($app === 'convert' && ! $allowed) {
|
||
$body .= '<p>这个功能需要会员。你已经登录,开通后重新进入即可使用。</p><p><a href="'.$config['portal'].'/pricing">去开通会员</a></p>';
|
||
} else {
|
||
$body .= '<p>功能已解锁。这是一个最小示例,用来证明两个工具识别的是同一个轻舟账号。</p>';
|
||
}
|
||
$other = $app === 'notes' ? '/convert' : '/notes';
|
||
$body .= '<p><a href="'.$other.'">打开另一个示例工具</a> · <a href="'.$config['portal'].'">返回轻舟</a></p>';
|
||
render($client['title'], $body, $config['portal']);
|
||
|
||
function httpPost(string $url, array $fields): array
|
||
{
|
||
$ch = curl_init($url);
|
||
curl_setopt_array($ch, [
|
||
CURLOPT_POST => true,
|
||
CURLOPT_POSTFIELDS => http_build_query($fields),
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_TIMEOUT => 10,
|
||
]);
|
||
$raw = curl_exec($ch);
|
||
curl_close($ch);
|
||
|
||
return json_decode(is_string($raw) ? $raw : '', true) ?: [];
|
||
}
|
||
|
||
function httpGet(string $url, string $token): array
|
||
{
|
||
$ch = curl_init($url);
|
||
curl_setopt_array($ch, [
|
||
CURLOPT_HTTPHEADER => ['Authorization: Bearer '.$token, 'Accept: application/json'],
|
||
CURLOPT_RETURNTRANSFER => true,
|
||
CURLOPT_TIMEOUT => 10,
|
||
]);
|
||
$raw = curl_exec($ch);
|
||
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
|
||
curl_close($ch);
|
||
if ($status === 401) {
|
||
return ['error' => 'invalid_token'];
|
||
}
|
||
|
||
return json_decode(is_string($raw) ? $raw : '', true) ?: [];
|
||
}
|
||
|
||
function render(string $title, string $body, string $portal): void
|
||
{
|
||
echo '<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>'
|
||
.htmlspecialchars($title).'</title><style>body{font-family:"Microsoft YaHei",sans-serif;background:#f3f7f6;color:#1c1917}main{max-width:640px;margin:48px auto;background:#fff;padding:28px;border-radius:16px}a{color:#0f4c5c}</style></head><body><main><h1>'
|
||
.htmlspecialchars($title).'</h1>'.$body.'</main></body></html>';
|
||
}
|