fix: clarify narrowed OAuth consent and verify Codex scope grants

This commit is contained in:
陈煜 committed 2026-10-04 02:57:07 +08:00
1 parent 087daef981
commit 5ad64460f7
7 files changed
+256 -5

No files matched your search

+2 -1
View File
@@ -13,7 +13,8 @@
"test:performance": "tsx scripts/performance.ts after",
"test:mcp": "tsx --test --test-concurrency=1 test/mcp.test.ts",
"mcp:probe": "tsx scripts/mcp-probe.ts",
"icons:seed": "node scripts/seed-icons.cjs"
"icons:seed": "node scripts/seed-icons.cjs",
"test:mcp:codex": "tsx --test --test-concurrency=1 test/codex-oauth.test.ts"
},
"dependencies": {
"@modelcontextprotocol/sdk": "1.31.0",
+210
View File
@@ -0,0 +1,210 @@
import 'dotenv/config';
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { randomUUID, randomBytes } from 'node:crypto';
import { mkdtemp, writeFile, readdir, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, resolve, basename, sep } from 'node:path';
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import { PrismaClient } from '@prisma/client';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { today } from '../src/validation';
// Optional real installed-client check; never uses the user's Codex credentials.
for (const useDefaultScopes of [false, true])
test(
'Codex OAuth ' +
(useDefaultScopes ? 'default metadata scopes' : 'explicit scopes') +
' are narrowed to draft without hidden access or direct posting',
async () => {
const resource = process.env.MCP_PUBLIC_URL || 'http://localhost:3100/mcp';
const root = process.env.TEST_API_URL?.replace(/\/api$/, '') || 'http://127.0.0.1:3100';
const origin =
process.env.WEB_ORIGIN && process.env.WEB_ORIGIN !== '*'
? process.env.WEB_ORIGIN
: 'http://localhost:5173';
const db = new PrismaClient();
const home = await mkdtemp(join(tmpdir(), 'worthpath-codex-scope-'));
const username = 'codex_scope_' + randomUUID().slice(0, 12),
password = randomBytes(20).toString('hex');
let userId = '',
clientId = '',
cli: ChildProcessWithoutNullStreams | undefined;
const client = new Client({ name: 'Codex OAuth grant verification', version: '1.31.0' });
async function web(path: string, body: unknown, cookie = '') {
const r = await fetch(root + '/api' + path, {
method: 'POST',
headers: {
Origin: origin,
'Content-Type': 'application/json',
...(cookie ? { Cookie: cookie } : {}),
},
body: JSON.stringify(body),
});
assert.equal(r.status, 201, 'Web request failed: ' + path);
return {
data: await r.json(),
cookie: r.headers.get('set-cookie')?.split(';')[0] || cookie,
};
}
async function deadline<T>(promise: Promise<T>, label: string) {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
new Promise<T>((_, reject) => {
timer = setTimeout(() => reject(Error(label + ' timed out')), 30000);
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
}
try {
const fixture = await web('/auth/register', { username, password });
userId = (await db.user.findUniqueOrThrow({ where: { username } })).id;
await writeFile(
join(home, 'config.toml'),
'mcp_oauth_credentials_store = "file"\n[mcp_servers.worthpath]\nurl = ' +
JSON.stringify(resource) +
'\n',
);
cli = spawn(
process.env.CODEX_CLI || 'codex',
[
'mcp',
'login',
'worthpath',
'--no-browser',
...(useDefaultScopes ? [] : ['--scopes', 'read,draft']),
'--oauth-client-registration',
'dcr',
],
{
env: { ...process.env, CODEX_HOME: home },
windowsHide: true,
stdio: ['pipe', 'pipe', 'pipe'],
},
);
const processExit = new Promise<number | null>((resolve, reject) => {
cli!.on('exit', resolve);
cli!.on('error', reject);
});
// Observe the exit from the start so spawn errors never become unhandled promises.
void processExit.catch(() => {});
const authorization = await deadline(
new Promise<string>((resolve, reject) => {
let output = '';
const receive = (chunk: Buffer) => {
output += chunk.toString();
const found = output.match(/https?:\/\/[^\s]+\/authorize\?[^\s]+/);
if (found) resolve(found[0]);
};
cli!.stdout.on('data', receive);
cli!.stderr.on('data', receive);
cli!.on('error', reject);
cli!.on('exit', () => reject(Error('CLI exited before authorization URL')));
}),
'CLI authorization URL',
);
const request = new URL(authorization);
assert.equal(request.origin, new URL(resource).origin);
const requested = (request.searchParams.get('scope') || '').split(' ').filter(Boolean);
assert.deepEqual(
requested,
useDefaultScopes
? ['read', 'draft', 'write', 'hidden_read', 'hidden_write']
: ['read', 'draft'],
);
clientId = request.searchParams.get('client_id')!;
const redirect = await fetch(request, { redirect: 'manual' });
assert.equal(redirect.status, 302);
const id = new URL(redirect.headers.get('location')!).searchParams.get(
'agent_authorization',
);
assert.ok(id);
// Isolated disposable fixture only. Real users complete consent in the website.
const consent = await web(
'/agent/authorizations/' + id,
{ approve: true, scopes: ['read', 'draft'] },
fixture.cookie,
);
cli.stdin.write(consent.data.redirect + '\n');
cli.stdin.end();
assert.equal(await deadline(processExit, 'CLI callback'), 0);
let access = '';
const find = (value: unknown) => {
if (value && typeof value === 'object') {
const row = value as Record<string, unknown>;
if (typeof row.access_token === 'string') access = row.access_token;
Object.values(row).forEach(find);
}
};
for (const file of (await readdir(home)).filter((n) => n.endsWith('.json')))
find(JSON.parse(await readFile(join(home, file), 'utf8')));
assert.ok(access, 'CLI did not save an OAuth token in its isolated credentials store');
const grant = await db.agentGrant.findFirstOrThrow({ where: { userId, clientId } });
assert.deepEqual(grant.scopes, ['read', 'draft']);
await client.connect(
new StreamableHTTPClientTransport(new URL(resource), {
requestInit: { headers: { Authorization: 'Bearer ' + access } },
}),
);
assert.equal((await client.listTools()).tools.length, 39);
async function call(name: string, args: Record<string, unknown> = {}) {
const result = await client.callTool({ name, arguments: args });
assert.ok(!result.isError, 'Tool failed: ' + name);
return (result.structuredContent as { data: any }).data;
}
const info = await call('connection_info');
assert.deepEqual(info.scopes, ['read', 'draft']);
assert.equal(info.permission, 'draft');
assert.equal(info.readHidden, false);
assert.equal(info.writeHidden, false);
const state = (await call('state_get')).state;
const operation = await call('position_create', {
kind: 'account',
side: 'asset',
name: 'Must remain draft',
category: 'cash',
currency: 'CNY',
amount: '25.50',
date: today(),
notes: '',
expectedState: state,
idempotencyKey: randomUUID(),
});
assert.equal(operation.status, 'pending');
assert.equal(
await db.position.count({ where: { userId } }),
0,
'Draft unexpectedly posted financial data',
);
console.log(
JSON.stringify({
requestedScopes: requested,
grantedScopes: info.scopes,
readHidden: info.readHidden,
writeHidden: info.writeHidden,
ordinaryWrite: operation.status,
tools: 39,
}),
);
} finally {
cli?.kill();
await client.close().catch(() => {});
if (userId) await db.user.deleteMany({ where: { id: userId } });
if (clientId) {
await db.agentAuthorization.deleteMany({ where: { clientId } });
await db.agentClient.deleteMany({ where: { id: clientId } });
}
await db.$disconnect();
assert.ok(
resolve(home).startsWith(resolve(tmpdir()) + sep) &&
basename(home).startsWith('worthpath-codex-scope-'),
);
await rm(home, { recursive: true, force: true });
}
},
);
+22 -4
View File
@@ -119,7 +119,10 @@ function codexSetupPrompt(url: string, level: string) {
'执行 codex mcp login worthpath --scopes ' +
selected +
' --oauth-client-registration dcr 发起网页登录。我会自行登录并确认权限。等待回调时保留登录进程;需要等待我完成网页步骤时,明确告诉我当前状态。',
'授权后检查连接配置与真实工具可用性。能调用时先 tools/list,再 connection_info 核对权限;若当前会话不会重新加载工具,请告诉我重启客户端或新建本机会话后继续验证。只有配置、OAuth 成功和工具调用成功都验证后才能说已可用,不把 codex mcp list 或网页登录成功当作工具调用成功。',
'实测 Codex CLI 0.160.0 显式执行 --scopes read,draft 时只请求这两项;默认登录会使用 scopes_supported,授权链接列出 read,draft,write,hidden_read,hidden_write。如果实际请求范围较宽,这是客户端请求的候选范围,不是最终授权。WorthPath 网页支持收窄:选择本次指定的权限等级,两个隐藏账户选项保持关闭,页面会明确显示最终授予权限;服务端仅按网页选择发行令牌。不要仅因请求包含全部候选权限就终止登录或让我自行检查页面。你可以打开正确 WorthPath 资源的授权页面供我审阅,最终选择和确认仍由我完成。',
'授权后检查连接配置与真实工具可用性。能调用时先 tools/list,再 connection_info;最终 scopes 必须仅为本次指定的 ' +
selected +
',且 readHidden/writeHidden 均为 false。若结果不符,停止使用该连接并报告差异,不修改账目。若当前会话不会重新加载工具,请告诉我重启客户端或新建本机会话后继续验证。只有配置、OAuth 成功和工具调用成功都验证后才能说已可用,不把 codex mcp list 或网页登录成功当作工具调用成功。',
'配置期间不要创建、修改或删除我的账目。后续资产查询、转账和还款优先使用 WorthPath MCP;工具或权限不可用时如实说明。',
...instructions(url).split('\n\n').slice(3),
].join('\n\n');
@@ -657,7 +660,10 @@ export function AgentConnections() {
<div className="agent-confirm">
<h3>审核 OAuth 连接</h3>
<p>{consent.name}</p>
<p>权限:{consent.scopes.join(', ')}</p>
<p>客户端请求的候选权限:{consent.scopes.join(', ')}</p>
<p className="muted">
候选范围不代表已授权。最终仅授予下方选择的权限,隐藏账户权限默认关闭。
</p>
<p>资源:{consent.resource}</p>
<p>回调地址:{consent.redirectUri}</p>
<p className="muted">只批准你正在连接的客户端;请核对回调地址。</p>
@@ -678,7 +684,7 @@ export function AgentConnections() {
</select>
</label>
{consent.scopes.includes('hidden_read') && (
<label>
<label className="check-line">
<input
type="checkbox"
checked={consentHiddenRead}
@@ -691,7 +697,7 @@ export function AgentConnections() {
</label>
)}
{consent.scopes.includes('hidden_write') && (
<label>
<label className="check-line">
<input
type="checkbox"
disabled={!consentHiddenRead || consentLevel === 'read'}
@@ -701,6 +707,18 @@ export function AgentConnections() {
允许修改隐藏账户
</label>
)}
<p role="status">
最终将授予:
{consent.scopes
.filter(
(scope) =>
scope === 'read' ||
scope === consentLevel ||
(scope === 'hidden_read' && consentHiddenRead) ||
(scope === 'hidden_write' && consentHiddenWrite),
)
.join(', ')}
</p>
{[true, false].map((approve) => (
<button
className="secondary"
+7
View File
@@ -1859,6 +1859,13 @@ textarea,
padding: 1rem;
margin: 1rem 0;
}
.agent-confirm .check-line input[type='checkbox'] {
width: 18px;
height: 18px;
min-height: 18px;
padding: 0;
flex: 0 0 18px;
}
.agent-confirm pre {
white-space: pre-wrap;
overflow-wrap: anywhere;
+6
View File
@@ -31,3 +31,9 @@
## 页面配置提示词(2026-10-04 02:32 UTC+8)
新增复制 Codex 配置提示词入口与只读、草稿、普通写入三档申请权限,默认 read,draft。提示词授权本机 Codex 执行连接配置和 OAuth 登录,仅修改 worthpath 连接并保留其他配置;网页确认由用户完成,配置阶段不修改账目。浏览器实际验证三种选项的剪贴板内容、正确资源地址与 scopes;前端类型检查和构建通过,临时账号已清理。没有启动新的真实用户 OAuth 授权,也没有验证外部 Codex 自动执行整段提示词;底层 CLI OAuth 路径沿用本页已有实际验证。
## OAuth 请求范围收窄(2026-10-04 02:56 UTC+8)
授权页新增候选/最终权限的明确区分与动态预览,并优化隐藏权限复选框。配置提示词说明默认 CLI 请求全部权限不等于全部授权,显式 read,draft 路径实测只请求两项,最终始终由用户网页选择与服务端限制。
新增可选 test:mcp:codex,两项真实 Codex CLI 0.160.0 OAuth/DCR 测试通过:显式 read,draft 和默认全部五项请求,网页同等的 consent 选择均发行仅 read,draft 的令牌;39 工具发现、连接权限验证、草稿 pending 且没有直接入账通过。浏览器确认只读默认、草稿选择后最终显示 read,draft、隐藏权限关闭,没有在浏览器点击授权。测试账号与注册已清理。前后端类型检查和前端构建通过,未重复全业务回归,无新增迁移。
+8
View File
@@ -120,3 +120,11 @@ cd E:\WorthPath
### Windows 执行环境挂起
配置提示词已包含短命令排查:优先无 profile 模式,超过 15 秒仅结束自己启动的检查,受限环境仍挂起时使用执行工具的正常权限申请流程继续。OAuth 等待网页回调不适用短命令超时。2026-10-04 本机通过提升权限、login:false 和官方 CLI 完整路径执行 --version 成功,版本 0.160.0。不能据此保证所有客户端沙箱均允许本机执行;权限申请被拒时必须报告具体原因。本次未修改真实 MCP 配置或发起新的用户授权。
### 客户端请求范围与最终授权
本机 Codex CLI 0.160.0 实测:显式 login --scopes read,draft 只请求两项;不指定 scopes 的默认登录请求全部五项。请求范围是候选权限,不是已经授予的权限。授权页可选择只读、草稿或直接写入;隐藏读写默认关闭。页面分别展示候选和最终范围,服务端验证选择是请求子集,再用所选 scopes 覆盖待处理参数并发行令牌。
申请草稿模式时选择“草稿修改(网页确认)”,不勾选隐藏账户;最终将授予应显示 read,draft。授权后用 connection_info 核对实际 scopes 仅有两项、readHidden/writeHidden 均 false。不要仅因默认请求包含全部候选权限就停止登录,最终批准仍由用户完成。
新增可选真实客户端回归:apps/api/test/codex-oauth.test.ts。设置 CODEX_CLI 为本机官方 Codex 可执行文件路径,然后运行 pnpm --filter @worthpath/api test:mcp:codex。前置为可访问的开发 API/MySQL,支持 TEST_API_URL/MCP_PUBLIC_URL/WEB_ORIGIN。测试使用独立临时 CODEX_HOME 与账号,不使用真实客户端凭据;两个测试分别覆盖显式和默认请求,最终 grant 仅 read,draft、39 工具发现、隐藏权限关闭和普通修改返回 pending 且没有 position 入账。自动清理临时凭据、账号与注册。两项实际通过;没有验证用户真实桌面聊天内工具调用。
+1
View File
@@ -92,3 +92,4 @@
- ~~修正 MCP 接入教程误导,补充已验证的 Codex OAuth 配置和 localhost 限制~~ — 已完成:2026-10-04 02:23(UTC+8);CLI 0.160.0 OAuth/DCR 登录及官方 SDK 39 工具发现通过,桌面会话内调用尚未验证。
- ~~在连接 Agent 页面提供可直接发送给 Codex 执行配置的提示词,无需用户输入命令~~ — 已完成并通过三档权限复制、前端类型检查与构建:2026-10-04 02:32(UTC+8);网页登录授权由用户完成。
- ~~Codex 配置提示词补充 Windows PowerShell 挂起排查与正常权限申请流程~~ — 已完成:2026-10-04 02:42(UTC+8);本机提升权限及无 profile 的 CLI 版本检查通过,前端构建通过。
- ~~明确 OAuth 候选与最终授权范围,验证 Codex 请求全部权限时可收窄为 read,draft~~ — 已完成:2026-10-04 02:56(UTC+8);两项真实 CLI OAuth/草稿隔离测试及浏览器权限选择验证通过。