@scoheart/x-search-mcp 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +59 -75
  2. package/TOOL.md +28 -17
  3. package/dist/package.json +8 -1
  4. package/dist/src/auth.d.ts +14 -5
  5. package/dist/src/auth.d.ts.map +1 -1
  6. package/dist/src/auth.js +180 -118
  7. package/dist/src/auth.js.map +1 -1
  8. package/dist/src/call-log.d.ts.map +1 -1
  9. package/dist/src/call-log.js +52 -33
  10. package/dist/src/call-log.js.map +1 -1
  11. package/dist/src/cli.d.ts.map +1 -1
  12. package/dist/src/cli.js +9 -4
  13. package/dist/src/cli.js.map +1 -1
  14. package/dist/src/config.d.ts +3 -1
  15. package/dist/src/config.d.ts.map +1 -1
  16. package/dist/src/config.js +4 -4
  17. package/dist/src/config.js.map +1 -1
  18. package/dist/src/device-login.d.ts +46 -0
  19. package/dist/src/device-login.d.ts.map +1 -0
  20. package/dist/src/device-login.js +72 -0
  21. package/dist/src/device-login.js.map +1 -0
  22. package/dist/src/http-config.d.ts +9 -0
  23. package/dist/src/http-config.d.ts.map +1 -1
  24. package/dist/src/http-config.js +10 -5
  25. package/dist/src/http-config.js.map +1 -1
  26. package/dist/src/http-server.d.ts +10 -2
  27. package/dist/src/http-server.d.ts.map +1 -1
  28. package/dist/src/http-server.js +46 -15
  29. package/dist/src/http-server.js.map +1 -1
  30. package/dist/src/index.d.ts +3 -0
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +3 -0
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/multi-user/bindings.d.ts +21 -0
  35. package/dist/src/multi-user/bindings.d.ts.map +1 -0
  36. package/dist/src/multi-user/bindings.js +129 -0
  37. package/dist/src/multi-user/bindings.js.map +1 -0
  38. package/dist/src/multi-user/cli.d.ts +23 -0
  39. package/dist/src/multi-user/cli.d.ts.map +1 -0
  40. package/dist/src/multi-user/cli.js +82 -0
  41. package/dist/src/multi-user/cli.js.map +1 -0
  42. package/dist/src/multi-user/identity.d.ts +17 -0
  43. package/dist/src/multi-user/identity.d.ts.map +1 -0
  44. package/dist/src/multi-user/identity.js +78 -0
  45. package/dist/src/multi-user/identity.js.map +1 -0
  46. package/dist/src/multi-user/keys.d.ts +17 -0
  47. package/dist/src/multi-user/keys.d.ts.map +1 -0
  48. package/dist/src/multi-user/keys.js +54 -0
  49. package/dist/src/multi-user/keys.js.map +1 -0
  50. package/dist/src/multi-user/kms.d.ts +10 -0
  51. package/dist/src/multi-user/kms.d.ts.map +1 -0
  52. package/dist/src/multi-user/kms.js +83 -0
  53. package/dist/src/multi-user/kms.js.map +1 -0
  54. package/dist/src/multi-user/service.d.ts +13 -0
  55. package/dist/src/multi-user/service.d.ts.map +1 -0
  56. package/dist/src/multi-user/service.js +92 -0
  57. package/dist/src/multi-user/service.js.map +1 -0
  58. package/dist/src/multi-user/settings.d.ts +9 -0
  59. package/dist/src/multi-user/settings.d.ts.map +1 -0
  60. package/dist/src/multi-user/settings.js +323 -0
  61. package/dist/src/multi-user/settings.js.map +1 -0
  62. package/dist/src/search-input.d.ts +43 -0
  63. package/dist/src/search-input.d.ts.map +1 -0
  64. package/dist/src/search-input.js +105 -0
  65. package/dist/src/search-input.js.map +1 -0
  66. package/dist/src/search-response.d.ts +6 -0
  67. package/dist/src/search-response.d.ts.map +1 -0
  68. package/dist/src/search-response.js +125 -0
  69. package/dist/src/search-response.js.map +1 -0
  70. package/dist/src/search.d.ts +5 -20
  71. package/dist/src/search.d.ts.map +1 -1
  72. package/dist/src/search.js +67 -332
  73. package/dist/src/search.js.map +1 -1
  74. package/dist/src/server.d.ts +9 -1
  75. package/dist/src/server.d.ts.map +1 -1
  76. package/dist/src/server.js +88 -81
  77. package/dist/src/server.js.map +1 -1
  78. package/dist/src/tool-contract.d.ts +150 -0
  79. package/dist/src/tool-contract.d.ts.map +1 -0
  80. package/dist/src/tool-contract.js +83 -0
  81. package/dist/src/tool-contract.js.map +1 -0
  82. package/docs/multi-user.md +108 -0
  83. package/examples/codex.toml +1 -1
  84. package/examples/mcp.json +1 -1
  85. package/package.json +8 -1
  86. package/src/auth.ts +178 -125
  87. package/src/call-log.ts +52 -31
  88. package/src/cli.ts +9 -4
  89. package/src/config.ts +4 -4
  90. package/src/device-login.ts +84 -0
  91. package/src/http-config.ts +11 -5
  92. package/src/http-server.ts +55 -18
  93. package/src/index.ts +3 -0
  94. package/src/multi-user/bindings.ts +135 -0
  95. package/src/multi-user/cli.ts +78 -0
  96. package/src/multi-user/identity.ts +83 -0
  97. package/src/multi-user/keys.ts +66 -0
  98. package/src/multi-user/kms.ts +87 -0
  99. package/src/multi-user/service.ts +92 -0
  100. package/src/multi-user/settings.ts +329 -0
  101. package/src/search-input.ts +113 -0
  102. package/src/search-response.ts +127 -0
  103. package/src/search.ts +130 -426
  104. package/src/server.ts +97 -82
  105. package/src/tool-contract.ts +90 -0
@@ -0,0 +1,108 @@
1
+ # 多用户 X Search MCP
2
+
3
+ 一套 HTTPS MCP 地址供受邀用户连接。用户在客户端授权访问 MCP,再用同一个身份到设置页绑定自己的 xAI API Key。服务根据 OAuth 签发方和用户 ID 查找绑定,每次搜索使用该用户的 xAI API 额度。
4
+
5
+ ```mermaid
6
+ flowchart LR
7
+ C["Codex / Pi"] -->|"MCP access token"| M["HTTPS /mcp"]
8
+ C <-->|"OAuth"| I["身份服务"]
9
+ B["用户浏览器"] <-->|"OIDC 登录"| I
10
+ B -->|"同意保存 API Key"| S["HTTPS /settings"]
11
+ S -->|"写入密文"| D["SQLite"]
12
+ M -->|"按登录用户取密文"| D
13
+ M <-->|"封装和解封数据密钥"| K["阿里云 KMS"]
14
+ S <-->|"生成数据密钥"| K
15
+ M -->|"该用户的 API Key"| X["xAI Responses API"]
16
+ ```
17
+
18
+ 当前多人模式的上游认证使用 xAI API Key。Grok 订阅需要验证官方 OAuth 客户端和 X Search 权限,现有个人模式的 `auth login` 用于独立的单用户进程。 [xAI X Search](https://docs.x.ai/developers/tools/x-search) · [Grok OpenCode 集成](https://x.ai/news/grok-opencode)
19
+
20
+ ## 服务端配置
21
+
22
+ 1. 准备有效的 HTTPS 证书和一个专用主机名。以下用 `https://mcp.example.com/mcp`。MCP 客户端 URL、OAuth resource indicator 和 access token 的 `aud` 必须与此完全一致,包括路径和末尾斜杠。
23
+ 2. 选择支持 MCP OAuth 的授权服务器。例如在同一个 WorkOS AuthKit 环境里配置该 resource indicator,按目标客户端启用 CIMD 或 DCR。给设置页另建一个 confidential Connect OAuth 应用,启用 `openid`,回调地址填 `https://mcp.example.com/settings/callback`。后端使用 authorization code、S256、`client_secret_basic` 和签名 ID token。该 ID token 与 MCP access token 必须使用相同的 `iss` 及用户 `sub`。邀请名单填签发方的用户 ID。MCP access token 需要 `client_id`、配置的 scope、有效期,以及唯一且指向此 MCP 的 audience。默认 scope 是 WorkOS 动态客户端支持的 `openid`,可以改成签发方能授予的专用 scope。 [WorkOS MCP 配置](https://workos.com/docs/authkit/mcp) · [WorkOS Connect token claims](https://workos.com/docs/authkit/connect/token-claims)
24
+ 3. 为应用准备一个阿里云对称 KMS 主密钥。ECS RAM 角色仅授予指定密钥的 `kms:GenerateDataKey` 和 `kms:Decrypt`,使用 IMDSv2。KMS 默认使用区域 VPC 端点。按所选 KMS 实例配置该网关及访问权限。专属网关使用 `X_SEARCH_MULTI_USER_KMS_ENDPOINT` 指定实例域名,并用 `X_SEARCH_MULTI_USER_KMS_CA_FILE` 指定实例的 CA PEM 文件。检查同机服务能否访问实例元数据。对外托管建议使用专用工作负载和隔离权限。 [KMS 网关和 CA](https://www.alibabacloud.com/help/en/kms/key-management-service/developer-reference/initialize-the-client-1) · [ECS 接入 KMS](https://www.alibabacloud.com/help/en/kms/key-management-service/ecs)
25
+ 4. 以独立服务用户运行 Node.js,给数据库创建该用户所有的 `0700` 目录。将设置页 OIDC client secret 放入该用户所有的 `0600` 文件。用进程管理器传入以下变量。若使用 systemd,可使用 `StateDirectoryMode=0700`、`UMask=0077` 和 `LimitCORE=0`,并给服务传入 `EnvironmentFile=`。
26
+
27
+ ```dotenv
28
+ X_SEARCH_MULTI_USER_PUBLIC_URL=https://mcp.example.com/mcp
29
+ X_SEARCH_MULTI_USER_ISSUER=https://your-environment.authkit.app
30
+ X_SEARCH_MULTI_USER_JWKS_URL=https://your-environment.authkit.app/oauth2/jwks
31
+ X_SEARCH_MULTI_USER_SCOPE=openid
32
+ X_SEARCH_MULTI_USER_ALLOWED_SUBJECTS=user_REPLACE_ALICE,user_REPLACE_BOB
33
+ X_SEARCH_MULTI_USER_OIDC_CLIENT_ID=client_REPLACE
34
+ X_SEARCH_MULTI_USER_OIDC_CLIENT_SECRET_FILE=/var/lib/x-search-mcp/settings-client-secret
35
+ X_SEARCH_MULTI_USER_DATABASE=/var/lib/x-search-mcp/credentials.sqlite
36
+ X_SEARCH_MULTI_USER_KMS_REGION=cn-hangzhou
37
+ X_SEARCH_MULTI_USER_KMS_KEY_ID=key-REPLACE
38
+ X_SEARCH_MULTI_USER_KMS_ROLE_NAME=x-search-mcp-kms
39
+ ```
40
+
41
+ ```sh
42
+ x-search-mcp http --multi-user --port 8000
43
+ ```
44
+
45
+ 生产环境启动命令需要该主机上的 KMS 访问。开发联调可以用 `--dev-local-key` 与 `X_SEARCH_MULTI_USER_DEV_KEY_FILE`,将一个随机生成、由服务用户所有且权限为 `0600` 的 32 字节文件用作本地包装密钥。测试库和生产库分别建立。授权服务器的 discovery、JWKS 和 token 交换走独立直连。xAI API 请求可经现有的 Oracle 出站代理。KMS 通过配置的阿里云端点访问。
46
+
47
+ ## HTTPS 入口
48
+
49
+ Node 监听回环地址。下面是放入 Nginx HTTPS `server` 块的例子。另将 HTTP 请求重定向至 HTTPS,并在安全组保留必要的公网端口。如果现有单账号服务还在运行,给多人服务分配独立的回环端口,代理指向多人服务。
50
+
51
+ ```nginx
52
+ # In the http context
53
+ map $uri $x_search_auth_client {
54
+ default "";
55
+ /settings/login $binary_remote_addr;
56
+ /settings/callback $binary_remote_addr;
57
+ }
58
+ limit_req_zone $x_search_auth_client zone=x_search_login:10m rate=12r/m;
59
+
60
+ server {
61
+ listen 443 ssl;
62
+ server_name mcp.example.com;
63
+ ssl_certificate /path/to/fullchain.pem;
64
+ ssl_certificate_key /path/to/privkey.pem;
65
+ access_log off;
66
+ error_log /var/log/nginx/x-search-mcp-error.log crit;
67
+
68
+ location ~ ^/(mcp|\.well-known/oauth-protected-resource(?:/mcp)?|settings(?:/(?:login|callback|key|unbind|logout))?)$ {
69
+ limit_req zone=x_search_login burst=10 nodelay;
70
+ limit_req_status 429;
71
+ client_max_body_size 1m;
72
+ proxy_pass http://127.0.0.1:8000;
73
+ proxy_set_header Host mcp.example.com;
74
+ proxy_set_header Authorization $http_authorization;
75
+ proxy_http_version 1.1;
76
+ proxy_buffering off;
77
+ proxy_request_buffering off;
78
+ proxy_read_timeout 620s;
79
+ }
80
+ location / { return 404; }
81
+ }
82
+ ```
83
+
84
+ 入口的登录限流按客户端地址计算。经过额外网关时,仅信任该网关提供的来源地址。公网入口关闭请求正文、Cookie 和 Authorization 采集。搜索默认每个用户每分钟最多 30 次、同时 2 次。保存或替换每个用户每分钟最多 5 次、同时 1 次。设置页会话保存在单进程内,重启后需要重新登录设置页,已加密绑定会保留。
85
+
86
+ ## 用户使用
87
+
88
+ 1. 用支持 OAuth 的 MCP 客户端添加服务器 URL 并授权。
89
+ 2. 在浏览器打开 `https://mcp.example.com/settings`,使用第一步的同一个账号登录,输入 xAI 控制台生成的 API Key 并同意加密保存。
90
+ 3. 在客户端调用 `x_search`。遇到缺少绑定或 xAI 返回 401,工具会附上设置页地址。用户可以在设置页替换或删除自己的 Key。
91
+
92
+ ```sh
93
+ codex mcp add x-search --url https://mcp.example.com/mcp
94
+ # 需要单独启动授权时
95
+ codex mcp login x-search
96
+
97
+ pi mcp add x-search --url https://mcp.example.com/mcp
98
+ pi mcp login x-search
99
+ pi mcp list
100
+ ```
101
+
102
+ ## 凭证和运行数据
103
+
104
+ - SQLite 存储用户标识、绑定版本、AES-256-GCM 密文和 KMS 封装后的数据密钥。封装与密文都绑定当前用户和记录版本。
105
+ - 用户的 Key 会在保存和实际发起 xAI 请求时进入应用进程内存。拥有运行中进程控制权或可同时读取数据库并使用解密权限的人,仍可能使用这些 Key。
106
+ - MCP 客户端从身份服务获取 MCP token。浏览器设置页只保留短期会话和用户标识。多人模式停止写入本地搜索查询和原始响应日志。
107
+ - 解绑对后续搜索生效,已发送的请求可能继续执行。旧备份仍可能包含历史密文。需要立即让旧 Key 失效时,在 xAI 控制台吊销它。恢复备份时检查哪些绑定在备份日期之后被移除。
108
+ - 正式开放前,用两名受邀用户验证真实登录、KMS 加解密、真实 X Search、费用归属和备份恢复。验证公开入口只连接多人实例。 [MCP 授权规范](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization)
@@ -1,6 +1,6 @@
1
1
  [mcp_servers.x-search]
2
2
  command = "npx"
3
- args = ["--yes", "@scoheart/x-search-mcp@0.2.0"]
3
+ args = ["--yes", "@scoheart/x-search-mcp@0.4.0"]
4
4
  tool_timeout_sec = 600
5
5
 
6
6
  [mcp_servers.x-search.env]
package/examples/mcp.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "command": "npx",
5
5
  "args": [
6
6
  "--yes",
7
- "@scoheart/x-search-mcp@0.2.0"
7
+ "@scoheart/x-search-mcp@0.4.0"
8
8
  ],
9
9
  "env": {
10
10
  "X_SEARCH_AUTH_MODE": "auto",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scoheart/x-search-mcp",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Independent MCP service for x_search, inspired by Hermes Agent",
5
5
  "repository": {
6
6
  "type": "git",
@@ -31,6 +31,7 @@
31
31
  "LICENSE",
32
32
  "THIRD_PARTY_NOTICES.md",
33
33
  "examples",
34
+ "docs/multi-user.md",
34
35
  ".env.example",
35
36
  "README.md",
36
37
  "tsconfig.json"
@@ -41,6 +42,7 @@
41
42
  "scripts": {
42
43
  "build": "tsc",
43
44
  "test": "npm run build && node --test test/*.test.mjs",
45
+ "verify:package": "node test/packaged-cli.check.mjs",
44
46
  "prepack": "npm run build",
45
47
  "start": "node dist/bin/x-search-mcp.js"
46
48
  },
@@ -48,8 +50,13 @@
48
50
  "access": "public"
49
51
  },
50
52
  "dependencies": {
53
+ "@alicloud/credentials": "2.4.7",
54
+ "@alicloud/kms20160120": "3.3.2",
55
+ "@alicloud/openapi-core": "1.0.9",
51
56
  "@modelcontextprotocol/node": "2.1.2",
52
57
  "@modelcontextprotocol/server": "2.4.0",
58
+ "jose": "6.2.17",
59
+ "openid-client": "6.8.9",
53
60
  "proper-lockfile": "4.1.2",
54
61
  "undici": "8.12.4",
55
62
  "zod": "4.6.7"
package/src/auth.ts CHANGED
@@ -3,12 +3,13 @@ import path from 'node:path';
3
3
  import crypto from 'node:crypto';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
5
  import lockfile from 'proper-lockfile';
6
- import { sendHttpRequest, HttpError } from './http.js';
6
+ import { sendHttpRequest, HttpError, type SendHttpResponse } from './http.js';
7
7
  import { loadConfig } from './config.js';
8
8
  import type { AuthRecord, AuthStatus, DiscoveryMetadata } from './types.js';
9
9
 
10
10
  const DISCOVERY_URL = 'https://auth.x.ai/.well-known/openid-configuration';
11
11
  const DEFAULT_SCOPE = 'openid profile email offline_access grok-cli:access api:access';
12
+ const maxDateMilliseconds = 8.64e15;
12
13
  const LOCK_OPTIONS = {
13
14
  realpath: false,
14
15
  stale: 60000,
@@ -86,11 +87,12 @@ export function validateOAuthUrl(rawUrl: string): URL {
86
87
  /**
87
88
  * Fetch and validate OIDC discovery metadata from x.ai.
88
89
  */
89
- export async function getDiscoveryMetadata(): Promise<DiscoveryMetadata> {
90
+ export async function getDiscoveryMetadata(signal?: AbortSignal): Promise<DiscoveryMetadata> {
90
91
  validateOAuthUrl(DISCOVERY_URL);
91
92
  const res = await sendHttpRequest({
92
93
  url: DISCOVERY_URL,
93
94
  method: 'GET',
95
+ signal,
94
96
  timeoutSeconds: 30,
95
97
  retries: 2,
96
98
  });
@@ -122,7 +124,8 @@ export function extractJwtExpiry(jwtToken: string | undefined): number | null {
122
124
  const payloadJson = Buffer.from(parts[1], 'base64url').toString('utf8');
123
125
  const payload = JSON.parse(payloadJson);
124
126
  if (typeof payload.exp === 'number') {
125
- return payload.exp * 1000;
127
+ const expiry = payload.exp * 1000;
128
+ if (expiry > 0 && expiry <= maxDateMilliseconds) return expiry;
126
129
  }
127
130
  } catch {
128
131
  // Return null if unparseable
@@ -132,18 +135,10 @@ export function extractJwtExpiry(jwtToken: string | undefined): number | null {
132
135
 
133
136
  function ensureAuthFileExists(authFilePath: string): void {
134
137
  const dir = path.dirname(authFilePath);
135
- if (!fs.existsSync(dir)) {
136
- fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
137
- } else {
138
- try {
139
- fs.chmodSync(dir, 0o700);
140
- } catch {
141
- // Best effort chmod
142
- }
143
- }
138
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
144
139
 
145
140
  if (!fs.existsSync(authFilePath)) {
146
- fs.writeFileSync(authFilePath, '', { mode: 0o600 });
141
+ fs.writeFileSync(authFilePath, '', { flag: 'a', mode: 0o600 });
147
142
  } else {
148
143
  try {
149
144
  fs.chmodSync(authFilePath, 0o600);
@@ -163,8 +158,17 @@ export function saveAuthDataAtomic(authFilePath: string, data: AuthRecord): void
163
158
  const tempFilePath = path.join(dir, `.auth.${Date.now()}.${randomSuffix}.tmp`);
164
159
 
165
160
  const content = JSON.stringify(data, null, 2);
166
- fs.writeFileSync(tempFilePath, content, { mode: 0o600, encoding: 'utf8' });
167
- fs.renameSync(tempFilePath, authFilePath);
161
+ try {
162
+ fs.writeFileSync(tempFilePath, content, { mode: 0o600, encoding: 'utf8' });
163
+ fs.renameSync(tempFilePath, authFilePath);
164
+ } catch (error) {
165
+ try {
166
+ fs.rmSync(tempFilePath, { force: true });
167
+ } catch {
168
+ // Preserve the original write error.
169
+ }
170
+ throw error;
171
+ }
168
172
 
169
173
  try {
170
174
  fs.chmodSync(authFilePath, 0o600);
@@ -186,13 +190,68 @@ export function readAuthData(authFilePath: string): AuthRecord | null {
186
190
  }
187
191
  }
188
192
 
189
- /**
190
- * Execute OAuth Device Code login flow.
191
- * Outputs user_code and verification URL, polls until user authorization is completed.
192
- */
193
- export async function loginWithDeviceCode(): Promise<void> {
193
+ export function oauthRequired(reason: string, status: number | null = null): HttpError {
194
+ return new HttpError('AUTH_REQUIRED', reason + ' Run "x-search-mcp auth login" to authorize a Grok subscription.', status);
195
+ }
196
+
197
+ function oauthErrorCode(error: unknown): string | undefined {
198
+ if (error instanceof HttpError && typeof error.data?.error === 'string') return error.data.error;
199
+ }
200
+
201
+ function invalidDeviceResponse(): HttpError {
202
+ return new HttpError('DEVICE_LOGIN_INVALID_RESPONSE', 'xAI returned invalid device authorization data.');
203
+ }
204
+
205
+ function isOAuthToken(value: unknown): value is string {
206
+ return typeof value === 'string' && value.length > 0 && !/[\s\x00-\x1f\x7f]/.test(value);
207
+ }
208
+
209
+ function parseTokenGrant(payload: unknown, invalidResponse: () => HttpError): Pick<AuthRecord, 'tokens' | 'expires_at'> {
210
+ if (!payload || typeof payload !== 'object') throw invalidResponse();
211
+ const data = payload as Record<string, unknown>;
212
+ const accessToken = data.access_token;
213
+ const refreshToken = data.refresh_token ?? '';
214
+ if (!isOAuthToken(accessToken) || (refreshToken !== '' && !isOAuthToken(refreshToken))) {
215
+ throw invalidResponse();
216
+ }
217
+
218
+ const now = Date.now();
219
+ const rawSeconds = data.expires_in;
220
+ let expiresAt: number;
221
+ if (rawSeconds === undefined || rawSeconds === null) {
222
+ expiresAt = extractJwtExpiry(accessToken) ?? now + 3_600_000;
223
+ } else {
224
+ const seconds = typeof rawSeconds === 'string' && /^\d+(?:\.\d+)?$/.test(rawSeconds.trim())
225
+ ? Number(rawSeconds) : rawSeconds;
226
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0) throw invalidResponse();
227
+ expiresAt = now + seconds * 1000;
228
+ }
229
+ if (expiresAt <= now || expiresAt > maxDateMilliseconds) throw invalidResponse();
230
+
231
+ return {
232
+ tokens: { access_token: accessToken, ...(refreshToken ? { refresh_token: refreshToken } : {}) },
233
+ expires_at: expiresAt,
234
+ };
235
+ }
236
+
237
+ function verifyBrowserUrl(value: unknown, deviceCode: string): string {
238
+ if (typeof value === 'string') {
239
+ try {
240
+ const url = validateOAuthUrl(value);
241
+ if (!url.href.includes(deviceCode) && !url.href.includes(encodeURIComponent(deviceCode))
242
+ && !url.searchParams.has('device_code')) return url.href;
243
+ } catch {
244
+ // The issuer's invalid URL may contain data that should stay out of the tool response.
245
+ }
246
+ }
247
+ throw invalidDeviceResponse();
248
+ }
249
+
250
+ /** Share the same device grant between CLI and stdio. The polling code stays in this closure. */
251
+ export async function startDeviceFlow(signal?: AbortSignal) {
194
252
  const config = loadConfig();
195
- const discovery = await getDiscoveryMetadata();
253
+ const previousAuth = JSON.stringify(readAuthData(config.authFile));
254
+ const discovery = await getDiscoveryMetadata(signal);
196
255
 
197
256
  const deviceParams = new URLSearchParams({
198
257
  client_id: config.oauthClientId,
@@ -206,15 +265,12 @@ export async function loginWithDeviceCode(): Promise<void> {
206
265
  'Content-Type': 'application/x-www-form-urlencoded',
207
266
  },
208
267
  body: deviceParams.toString(),
268
+ signal,
209
269
  timeoutSeconds: 30,
210
- retries: 2,
270
+ retries: 0,
211
271
  });
212
272
 
213
273
  const deviceData = deviceRes.data;
214
- if (!deviceData || !deviceData.device_code || !deviceData.user_code) {
215
- throw new Error('Failed to obtain device authorization code from upstream xAI');
216
- }
217
-
218
274
  const {
219
275
  device_code: deviceCode,
220
276
  user_code: userCode,
@@ -222,106 +278,111 @@ export async function loginWithDeviceCode(): Promise<void> {
222
278
  verification_uri_complete: verificationUriComplete,
223
279
  expires_in: expiresIn = 600,
224
280
  interval: pollInterval = 5,
225
- } = deviceData;
226
-
227
- const authUrl = verificationUriComplete || verificationUri;
228
- const expiresAtDate = new Date(Date.now() + expiresIn * 1000).toLocaleTimeString();
229
-
230
- console.error('\n========================================================');
231
- console.error(' xAI Subscription OAuth Device Login');
232
- console.error('========================================================');
233
- console.error(`1. Visit the authorization page: ${authUrl}`);
234
- console.error(`2. Confirm code: ${userCode}`);
235
- console.error(`3. Code expires at: ${expiresAtDate} (in ${expiresIn}s)`);
236
- console.error('\nWaiting for browser authorization (Ctrl+C to cancel)...');
237
-
238
- let currentInterval = Math.max(pollInterval, 3);
239
- const deadline = Date.now() + expiresIn * 1000;
281
+ } = deviceData ?? {};
282
+ if (typeof deviceCode !== 'string' || !deviceCode
283
+ || typeof userCode !== 'string' || !userCode.trim() || userCode === deviceCode || /[\x00-\x1f\x7f]/.test(userCode)
284
+ || !Number.isSafeInteger(expiresIn) || expiresIn <= 0 || expiresIn * 1000 > 2_147_483_647
285
+ || !Number.isSafeInteger(pollInterval) || pollInterval <= 0) {
286
+ throw invalidDeviceResponse();
287
+ }
240
288
 
241
- while (Date.now() < deadline) {
242
- await new Promise((resolve) => setTimeout(resolve, currentInterval * 1000));
289
+ const expiresAt = Date.now() + expiresIn * 1000;
290
+ const prompt = {
291
+ verification_uri: verifyBrowserUrl(verificationUri, deviceCode),
292
+ ...(verificationUriComplete
293
+ ? { verification_uri_complete: verifyBrowserUrl(verificationUriComplete, deviceCode) } : {}),
294
+ user_code: userCode as string,
295
+ expires_at: new Date(expiresAt).toISOString(),
296
+ };
297
+ const tokenParams = new URLSearchParams({
298
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
299
+ client_id: config.oauthClientId,
300
+ device_code: deviceCode,
301
+ });
243
302
 
244
- const tokenParams = new URLSearchParams({
245
- grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
246
- client_id: config.oauthClientId,
247
- device_code: deviceCode,
248
- });
303
+ async function waitForAuthorization(): Promise<void> {
304
+ let intervalMs = pollInterval * 1000;
305
+ while (Date.now() < expiresAt) {
306
+ await delay(Math.min(intervalMs, expiresAt - Date.now()), undefined, { signal });
307
+ throwIfCancelled(signal);
308
+ if (Date.now() >= expiresAt) break;
249
309
 
250
- let tokenRes: any;
251
- try {
252
- tokenRes = await sendHttpRequest({
253
- url: discovery.token_endpoint,
254
- method: 'POST',
255
- headers: {
256
- 'Content-Type': 'application/x-www-form-urlencoded',
257
- },
258
- body: tokenParams.toString(),
259
- timeoutSeconds: 30,
260
- retries: 0,
261
- });
262
- } catch (err: any) {
263
- if (err instanceof HttpError && err.data && typeof err.data === 'object') {
264
- const oauthError = err.data.error;
265
- if (oauthError === 'authorization_pending') {
266
- continue;
267
- }
268
- if (oauthError === 'slow_down') {
269
- currentInterval += 5;
310
+ let response: SendHttpResponse;
311
+ try {
312
+ response = await sendHttpRequest({
313
+ url: discovery.token_endpoint,
314
+ method: 'POST',
315
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
316
+ body: tokenParams.toString(),
317
+ signal,
318
+ timeoutSeconds: Math.min(30, Math.ceil((expiresAt - Date.now()) / 1000)),
319
+ retries: 0,
320
+ });
321
+ } catch (error) {
322
+ const code = oauthErrorCode(error);
323
+ if (code === 'authorization_pending') continue;
324
+ if (code === 'slow_down') {
325
+ intervalMs += 5000;
270
326
  continue;
271
327
  }
272
- if (oauthError === 'expired_token') {
273
- throw new Error('Device code has expired. Please run login again.');
328
+ if (code === 'expired_token') break;
329
+ if (code === 'access_denied') {
330
+ throw new HttpError('DEVICE_LOGIN_DENIED', 'Grok authorization was declined.');
274
331
  }
275
- if (oauthError === 'access_denied') {
276
- throw new Error('Authorization was denied by the user.');
332
+ if (error instanceof HttpError && (error.code === 'TIMEOUT' || error.code === 'NETWORK_ERROR')) {
333
+ intervalMs *= 2;
334
+ continue;
277
335
  }
278
- }
279
- throw err;
280
- }
281
-
282
- const tokenData = tokenRes.data;
283
- if (tokenData && tokenData.access_token) {
284
- const tokenExpiresIn = tokenData.expires_in;
285
- let expiresAt = tokenExpiresIn ? Date.now() + tokenExpiresIn * 1000 : null;
286
- if (!expiresAt) {
287
- expiresAt = extractJwtExpiry(tokenData.access_token);
288
- }
289
- if (!expiresAt) {
290
- expiresAt = Date.now() + 3600 * 1000;
336
+ throw error;
291
337
  }
292
338
 
293
339
  const record: AuthRecord = {
294
340
  version: 1,
295
341
  client_id: config.oauthClientId,
296
342
  token_endpoint: discovery.token_endpoint,
297
- tokens: {
298
- access_token: tokenData.access_token,
299
- refresh_token: tokenData.refresh_token,
300
- },
301
- expires_at: expiresAt,
343
+ ...parseTokenGrant(response.data, invalidDeviceResponse),
302
344
  };
303
345
 
304
- ensureAuthFileExists(config.authFile);
305
- const release = await lockfile.lock(config.authFile, LOCK_OPTIONS);
346
+ throwIfCancelled(signal);
347
+ fs.mkdirSync(config.authDir, { recursive: true, mode: 0o700 });
348
+ const release = await acquireAuthLock(config.authFile, signal);
306
349
  try {
350
+ throwIfCancelled(signal);
351
+ if (JSON.stringify(readAuthData(config.authFile)) !== previousAuth) {
352
+ throw new HttpError('DEVICE_LOGIN_SUPERSEDED', 'The local credential changed while this sign-in was pending. Check its status before starting a new sign-in.');
353
+ }
307
354
  saveAuthDataAtomic(config.authFile, record);
308
355
  } finally {
309
356
  await release();
310
357
  }
311
-
312
- console.error('\n✓ Successfully authenticated with xAI Subscription OAuth.');
313
- console.error(`Tokens saved to: ${config.authFile}\n`);
314
358
  return;
315
359
  }
360
+ throw new HttpError('DEVICE_LOGIN_EXPIRED', 'The Grok device code expired.');
316
361
  }
317
362
 
318
- throw new Error('Device code expired without receiving authorization. Please run login again.');
363
+ return { prompt, waitForAuthorization, authFile: config.authFile };
364
+ }
365
+
366
+ export async function loginWithDeviceCode(): Promise<void> {
367
+ const { prompt, waitForAuthorization, authFile } = await startDeviceFlow();
368
+ const expiresAt = new Date(prompt.expires_at);
369
+ const expiresIn = Math.ceil((expiresAt.getTime() - Date.now()) / 1000);
370
+ console.error('\n========================================================');
371
+ console.error(' xAI Subscription OAuth Device Login');
372
+ console.error('========================================================');
373
+ console.error(`1. Visit the authorization page: ${prompt.verification_uri_complete ?? prompt.verification_uri}`);
374
+ console.error(`2. Confirm code: ${prompt.user_code}`);
375
+ console.error(`3. Code expires at: ${expiresAt.toLocaleTimeString()} (in ${expiresIn}s)`);
376
+ console.error('\nWaiting for browser authorization (Ctrl+C to cancel)...');
377
+ await waitForAuthorization();
378
+ console.error('\n✓ Successfully authenticated with xAI Subscription OAuth.');
379
+ console.error(`Tokens saved to: ${authFile}\n`);
319
380
  }
320
381
 
321
382
  async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath: string): Promise<string> {
322
383
  const refreshToken = authData?.tokens?.refresh_token;
323
- if (!refreshToken) {
324
- throw new Error('No refresh token available. Run "x-search-mcp auth login" to authenticate.');
384
+ if (!isOAuthToken(refreshToken)) {
385
+ throw oauthRequired('No Grok OAuth refresh token is available.');
325
386
  }
326
387
 
327
388
  const tokenEndpoint = authData.token_endpoint || 'https://auth.x.ai/oauth2/token';
@@ -345,28 +406,22 @@ async function performTokenRefreshUnderLock(authData: AuthRecord, authFilePath:
345
406
  timeoutSeconds: 30,
346
407
  retries: 0,
347
408
  isRefresh: true, // Auto-retry strictly disabled for refresh requests
409
+ }).catch((error: unknown) => {
410
+ if (error instanceof HttpError && oauthErrorCode(error) === 'invalid_grant') {
411
+ throw oauthRequired('xAI rejected the Grok OAuth refresh grant.', error.status);
412
+ }
413
+ throw error;
348
414
  });
349
415
 
350
- const data = res.data;
351
- if (!data || !data.access_token) {
352
- throw new Error('Token refresh response did not contain an access_token');
353
- }
354
-
355
- let expiresAt = data.expires_in ? Date.now() + data.expires_in * 1000 : null;
356
- if (!expiresAt) {
357
- expiresAt = extractJwtExpiry(data.access_token);
358
- }
359
- if (!expiresAt) {
360
- expiresAt = Date.now() + 3600 * 1000;
361
- }
362
-
416
+ const grant = parseTokenGrant(res.data, () =>
417
+ new HttpError('OAUTH_INVALID_TOKEN_RESPONSE', 'xAI returned an invalid OAuth token response.', res.status));
363
418
  const updatedRecord: AuthRecord = {
364
419
  ...authData,
420
+ ...grant,
365
421
  tokens: {
366
- access_token: data.access_token,
367
- refresh_token: data.refresh_token || refreshToken,
422
+ access_token: grant.tokens.access_token,
423
+ refresh_token: grant.tokens.refresh_token ?? refreshToken,
368
424
  },
369
- expires_at: expiresAt,
370
425
  };
371
426
 
372
427
  saveAuthDataAtomic(authFilePath, updatedRecord);
@@ -383,8 +438,8 @@ export async function getValidOAuthAccessToken(signal?: AbortSignal): Promise<st
383
438
  const authFilePath = config.authFile;
384
439
 
385
440
  let authData = readAuthData(authFilePath);
386
- if (!authData || !authData.tokens || !authData.tokens.access_token) {
387
- throw new Error(`No OAuth tokens found in ${authFilePath}. Run "x-search-mcp auth login" first.`);
441
+ if (!authData || !isOAuthToken(authData.tokens?.access_token)) {
442
+ throw oauthRequired('No Grok OAuth credential is available.');
388
443
  }
389
444
 
390
445
  const now = Date.now();
@@ -400,12 +455,12 @@ export async function getValidOAuthAccessToken(signal?: AbortSignal): Promise<st
400
455
  throwIfCancelled(signal);
401
456
  authData = readAuthData(authFilePath);
402
457
  const updatedRemaining = (authData?.expires_at || 0) - Date.now();
403
- if (updatedRemaining > 120_000 && authData?.tokens?.access_token) {
458
+ if (updatedRemaining > 120_000 && isOAuthToken(authData?.tokens?.access_token)) {
404
459
  return authData.tokens.access_token;
405
460
  }
406
461
 
407
462
  if (!authData) {
408
- throw new Error('Authentication data was deleted during token refresh.');
463
+ throw oauthRequired('The Grok OAuth credential was removed.');
409
464
  }
410
465
 
411
466
  const token = await performTokenRefreshUnderLock(authData, authFilePath);
@@ -431,10 +486,10 @@ export async function forceRefreshToken(rejectedAccessToken: string, signal?: Ab
431
486
  throwIfCancelled(signal);
432
487
  const authData = readAuthData(authFilePath);
433
488
  if (!authData || !authData.tokens) {
434
- throw new Error('OAuth authentication file is missing or corrupted.');
489
+ throw oauthRequired('The Grok OAuth credential is missing or corrupted.');
435
490
  }
436
491
 
437
- if (authData.tokens.access_token && authData.tokens.access_token !== rejectedAccessToken) {
492
+ if (isOAuthToken(authData.tokens.access_token) && authData.tokens.access_token !== rejectedAccessToken) {
438
493
  return authData.tokens.access_token;
439
494
  }
440
495
 
@@ -454,12 +509,10 @@ export function getAuthStatus(): AuthStatus {
454
509
  const authData = readAuthData(config.authFile);
455
510
 
456
511
  const hasApiKey = Boolean(config.apiKey);
457
- const hasOAuth = Boolean(authData?.tokens?.access_token);
512
+ const hasOAuth = isOAuthToken(authData?.tokens?.access_token);
458
513
 
459
- let oauthExpiresAt: string | null = null;
460
- if (hasOAuth && authData?.expires_at) {
461
- oauthExpiresAt = new Date(authData.expires_at).toISOString();
462
- }
514
+ const expiry = new Date(authData?.expires_at ?? NaN);
515
+ const oauthExpiresAt = hasOAuth && Number.isFinite(expiry.getTime()) ? expiry.toISOString() : null;
463
516
 
464
517
  return {
465
518
  hasApiKey,