@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
package/src/call-log.ts CHANGED
@@ -21,13 +21,21 @@ const SENSITIVE_KEYS = new Set([
21
21
  const BEARER = /Bearer\s+[A-Za-z0-9._~+/-]+=*/gi;
22
22
  const XAI_KEY = /xai-[A-Za-z0-9_-]{16,}/g;
23
23
 
24
+ function redactText(value: string): string {
25
+ return value.replace(BEARER, 'Bearer [redacted]').replace(XAI_KEY, 'xai-[redacted]');
26
+ }
27
+
28
+ function redactLogError(error: CallLogEntry['error']): CallLogEntry['error'] {
29
+ return error && { code: redactText(error.code), message: redactText(error.message), status: error.status };
30
+ }
31
+
24
32
  /**
25
33
  * Remove credential-shaped values before a call log is written.
26
34
  * Post text is preserved; only known secret keys and token formats are replaced.
27
35
  */
28
36
  export function redactForLog(value: unknown, seen = new WeakSet<object>()): unknown {
29
37
  if (typeof value === 'string') {
30
- return value.replace(BEARER, 'Bearer [redacted]').replace(XAI_KEY, 'xai-[redacted]');
38
+ return redactText(value);
31
39
  }
32
40
  if (value === null || typeof value !== 'object') {
33
41
  return value;
@@ -69,17 +77,35 @@ function stamp(): string {
69
77
  return new Date().toISOString().replace(/[-:]/g, '').replace('.', '');
70
78
  }
71
79
 
80
+ async function callLogPaths(dir: string): Promise<string[]> {
81
+ try {
82
+ const names = await fs.promises.readdir(dir);
83
+ return names.filter(name => /^call-.*\.json$/.test(name)).map(name => path.join(dir, name));
84
+ } catch (error) {
85
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ async function recentCallLogFiles(paths: string[]) {
91
+ const files = await Promise.all(paths.map(async file => {
92
+ try {
93
+ const stat = await fs.promises.lstat(file);
94
+ return stat.isFile() ? { file, bytes: stat.size, mtimeMs: stat.mtimeMs } : null;
95
+ } catch (error) {
96
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null;
97
+ throw error;
98
+ }
99
+ }));
100
+ return files.filter(file => file !== null).sort((left, right) => right.mtimeMs - left.mtimeMs);
101
+ }
102
+
72
103
  async function pruneCallLogs(dir: string, keep: number): Promise<void> {
73
104
  if (keep <= 0) return;
74
- const names = (await fs.promises.readdir(dir)).filter((name) => /^call-.*\.json$/.test(name));
75
- if (names.length <= keep) return;
76
- const ranked = await Promise.all(names.map(async (name) => {
77
- const full = path.join(dir, name);
78
- const stat = await fs.promises.stat(full);
79
- return { full, mtime: stat.mtimeMs };
80
- }));
81
- ranked.sort((left, right) => right.mtime - left.mtime);
82
- await Promise.all(ranked.slice(keep).map((item) => fs.promises.rm(item.full, { force: true })));
105
+ const paths = await callLogPaths(dir);
106
+ if (paths.length <= keep) return;
107
+ const ranked = await recentCallLogFiles(paths);
108
+ await Promise.all(ranked.slice(keep).map(({ file }) => fs.promises.rm(file, { force: true })));
83
109
  }
84
110
 
85
111
  /**
@@ -95,6 +121,7 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
95
121
  const bounded = boundForLog(redactForLog(attempt.raw_response), config.logMaxBytes);
96
122
  return {
97
123
  ...attempt,
124
+ error: redactLogError(attempt.error),
98
125
  raw_response: bounded.value,
99
126
  raw_response_truncated: bounded.truncated,
100
127
  raw_response_bytes: bounded.bytes,
@@ -108,14 +135,14 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
108
135
  elapsed_ms: entry.elapsed_ms,
109
136
  endpoint: entry.endpoint,
110
137
  model: entry.model,
111
- query: entry.query,
138
+ query: redactText(entry.query),
112
139
  credential_source: entry.credential_source,
113
140
  billing_mode: entry.billing_mode,
114
141
  request: redactForLog(entry.request),
115
142
  attempts: redactedAttempts,
116
143
  raw_response: redactedAttempts.length > 0 ? redactedAttempts[redactedAttempts.length - 1].raw_response : null,
117
144
  outcome: entry.outcome,
118
- error: entry.error,
145
+ error: redactLogError(entry.error),
119
146
  };
120
147
 
121
148
  const dir = config.logDir;
@@ -124,39 +151,33 @@ export async function writeCallLog(entry: CallLogEntry): Promise<string | null>
124
151
  const temporary = path.join(dir, `.${filename}.${process.pid}.tmp`);
125
152
  try {
126
153
  await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
127
- await fs.promises.chmod(dir, 0o700);
128
154
  await fs.promises.writeFile(temporary, JSON.stringify(record, null, 2), { mode: 0o600 });
129
155
  await fs.promises.chmod(temporary, 0o600);
130
156
  await fs.promises.rename(temporary, destination);
131
- await fs.promises.chmod(destination, 0o600);
132
- await pruneCallLogs(dir, config.logKeep);
133
- return destination;
134
- } catch (err: any) {
135
- console.error(`x-search-mcp call_log_error=${err?.message || 'failed to write call log'}`);
157
+ } catch (error) {
158
+ const message = error instanceof Error ? redactText(error.message) : 'failed to write call log';
159
+ console.error(`x-search-mcp call_log_error=${message}`);
136
160
  await fs.promises.rm(temporary, { force: true }).catch(() => undefined);
137
161
  return null;
138
162
  }
163
+ try {
164
+ await pruneCallLogs(dir, config.logKeep);
165
+ } catch (error) {
166
+ const message = error instanceof Error ? redactText(error.message) : 'failed to prune call logs';
167
+ console.error(`x-search-mcp call_log_prune_error=${message}`);
168
+ }
169
+ return destination;
139
170
  }
140
171
 
141
172
  export async function listCallLogs(limit = 20): Promise<{ enabled: boolean; directory: string; keep: number; files: Array<{ file: string; bytes: number; mtime: string }> }> {
142
173
  const config = loadConfig();
143
174
  const bounded = Math.max(1, Math.min(limit, 100));
144
- let names: string[] = [];
145
- try {
146
- names = (await fs.promises.readdir(config.logDir)).filter((name) => /^call-.*\.json$/.test(name));
147
- } catch (err: any) {
148
- if (err?.code !== 'ENOENT') throw err;
149
- }
150
- const ranked = await Promise.all(names.map(async (name) => {
151
- const full = path.join(config.logDir, name);
152
- const stat = await fs.promises.stat(full);
153
- return { file: full, bytes: stat.size, mtimeMs: stat.mtimeMs, mtime: stat.mtime.toISOString() };
154
- }));
155
- ranked.sort((left, right) => right.mtimeMs - left.mtimeMs);
175
+ const ranked = await recentCallLogFiles(await callLogPaths(config.logDir));
156
176
  return {
157
177
  enabled: config.logEnabled,
158
178
  directory: config.logDir,
159
179
  keep: config.logKeep,
160
- files: ranked.slice(0, bounded).map(({ file, bytes, mtime }) => ({ file, bytes, mtime })),
180
+ files: ranked.slice(0, bounded).map(({ file, bytes, mtimeMs }) =>
181
+ ({ file, bytes, mtime: new Date(mtimeMs).toISOString() })),
161
182
  };
162
183
  }
package/src/cli.ts CHANGED
@@ -21,19 +21,24 @@ HTTP options:
21
21
  --host <address> Bind address (default: 127.0.0.1)
22
22
  --port <number> TCP port (default: 8000; 0 chooses an available port)
23
23
  --path <path> MCP endpoint (default: /mcp)
24
- --token-file <file> Private file containing the HTTP bearer token
25
- --allowed-host <hostname> Allow an additional Host hostname; repeatable, no ports
24
+ --token-file <file> Private file containing the single-account HTTP bearer token
25
+ --allowed-host <hostname> Allow an additional single-account Host hostname; repeatable, no ports
26
26
  --allowed-origin <url> Allow an exact browser origin; repeatable
27
+ --multi-user Require per-user OAuth and encrypted xAI API key bindings
28
+ --dev-local-key Use a local wrapping key for multi-user development
27
29
 
28
30
  HTTP credentials: X_SEARCH_HTTP_TOKEN or X_SEARCH_HTTP_TOKEN_FILE.
29
31
  Other HTTP environment defaults: X_SEARCH_HTTP_HOST, X_SEARCH_HTTP_PORT,
30
32
  X_SEARCH_HTTP_PATH, X_SEARCH_HTTP_ALLOWED_HOSTS, X_SEARCH_HTTP_ALLOWED_ORIGINS.
31
- Grok credentials remain server-side; HTTP access uses its own bearer token.`);
33
+ Multi-user settings use X_SEARCH_MULTI_USER_*; see docs/multi-user.md.`);
32
34
  return;
33
35
  }
34
36
 
35
37
  if (command === 'http' || command === '--http') {
36
- const service = await startHttp(createServer, loadHttpOptions(argv.slice(1)));
38
+ const args = argv.slice(1);
39
+ const service = args.includes('--multi-user')
40
+ ? await (await import('./multi-user/cli.js')).startMultiUserCli(args.filter(argument => argument !== '--multi-user'))
41
+ : await startHttp(createServer, loadHttpOptions(args));
37
42
  const stop = () => {
38
43
  void service.close().catch(() => {
39
44
  console.error('Could not shut down the HTTP MCP service cleanly');
package/src/config.ts CHANGED
@@ -79,7 +79,7 @@ function parseReasoningEffort(val: string | undefined): ReasoningEffort | undefi
79
79
  return effort;
80
80
  }
81
81
 
82
- export function loadConfig(): Config {
82
+ export function loadConfig({ managed = false }: { managed?: boolean } = {}): Config {
83
83
  const defaultAuthDir = path.join(os.homedir(), '.config', 'x-search-mcp');
84
84
  const defaultAuthFile = path.join(defaultAuthDir, 'auth.json');
85
85
  const authFile = process.env.X_SEARCH_AUTH_FILE
@@ -87,7 +87,7 @@ export function loadConfig(): Config {
87
87
  : defaultAuthFile;
88
88
 
89
89
  return {
90
- authMode: parseAuthMode(process.env.X_SEARCH_AUTH_MODE),
90
+ authMode: managed ? 'api_key' : parseAuthMode(process.env.X_SEARCH_AUTH_MODE),
91
91
  authFile,
92
92
  authDir: path.dirname(authFile),
93
93
  oauthClientId: process.env.XAI_OAUTH_CLIENT_ID || 'b1a00492-073a-47ea-816f-4c329264a828',
@@ -96,8 +96,8 @@ export function loadConfig(): Config {
96
96
  retries: parseBoundedInt(process.env.X_SEARCH_RETRIES, 'X_SEARCH_RETRIES', 0, 3, 2),
97
97
  maxTurns: parseBoundedInt(process.env.X_SEARCH_MAX_TURNS, 'X_SEARCH_MAX_TURNS', 1, 20, 4),
98
98
  reasoningEffort: parseReasoningEffort(process.env.X_SEARCH_REASONING_EFFORT),
99
- apiKey: getApiKey(),
100
- logEnabled: parseEnabled(process.env.X_SEARCH_LOG, 'X_SEARCH_LOG', true),
99
+ apiKey: managed ? null : getApiKey(),
100
+ logEnabled: !managed && parseEnabled(process.env.X_SEARCH_LOG, 'X_SEARCH_LOG', true),
101
101
  logDir: process.env.X_SEARCH_LOG_DIR
102
102
  ? path.resolve(process.env.X_SEARCH_LOG_DIR)
103
103
  : path.join(defaultAuthDir, 'logs'),
@@ -0,0 +1,84 @@
1
+ import { getAuthStatus, startDeviceFlow } from './auth.js';
2
+ import { HttpError } from './http.js';
3
+
4
+ type DevicePrompt = Awaited<ReturnType<typeof startDeviceFlow>>['prompt'];
5
+ export const deviceFailureStatuses = ['denied', 'expired', 'superseded', 'failed', 'cancelled'] as const;
6
+ type DeviceFailureStatus = typeof deviceFailureStatuses[number];
7
+ type DeviceFailure = { status: DeviceFailureStatus; error: { code: string; message: string; status: number | null } };
8
+ type DeviceState = { status: 'idle' | 'starting' | 'authorized' }
9
+ | { status: 'pending'; expires_at: string }
10
+ | DeviceFailure;
11
+ type DeviceStart = ({ status: 'pending' } & DevicePrompt) | DeviceFailure;
12
+
13
+ const deviceFailures: Record<string, { status: DeviceFailureStatus; message: string }> = {
14
+ DEVICE_LOGIN_DENIED: { status: 'denied', message: 'Grok authorization was declined.' },
15
+ DEVICE_LOGIN_EXPIRED: { status: 'expired', message: 'The Grok device code expired.' },
16
+ DEVICE_LOGIN_SUPERSEDED: { status: 'superseded', message: 'The local credential changed. Check its status before signing in again.' },
17
+ DEVICE_LOGIN_INVALID_RESPONSE: { status: 'failed', message: 'xAI returned invalid device authorization data.' },
18
+ cancelled: { status: 'cancelled', message: 'The login was cancelled.' },
19
+ };
20
+
21
+ function deviceLoginFailure(error: unknown): DeviceFailure {
22
+ const code = error instanceof HttpError ? error.code
23
+ : error instanceof Error && error.name === 'AbortError' ? 'cancelled' : 'DEVICE_LOGIN_FAILED';
24
+ const failure = Object.hasOwn(deviceFailures, code) ? deviceFailures[code] : undefined;
25
+ return {
26
+ status: failure?.status ?? 'failed',
27
+ error: {
28
+ code,
29
+ message: failure?.message ?? 'Could not complete Grok device authorization.',
30
+ status: error instanceof HttpError ? error.status : null,
31
+ },
32
+ };
33
+ }
34
+
35
+ export function createDeviceLogin() {
36
+ const controller = new AbortController();
37
+ let starting: Promise<DeviceStart> | undefined;
38
+ let polling: Promise<void> | undefined;
39
+ let pending: ({ status: 'pending' } & DevicePrompt) | undefined;
40
+ let state: DeviceState = { status: 'idle' };
41
+
42
+ return {
43
+ async start(): Promise<DeviceStart> {
44
+ if (starting) return starting;
45
+ if (pending) return pending;
46
+ state = { status: 'starting' };
47
+ starting = startDeviceFlow(controller.signal).then((flow): DeviceStart => {
48
+ pending = { status: 'pending', ...flow.prompt };
49
+ state = { status: 'pending', expires_at: pending.expires_at };
50
+ polling = flow.waitForAuthorization().then(
51
+ () => { state = { status: 'authorized' }; },
52
+ error => { state = deviceLoginFailure(error); },
53
+ ).finally(() => {
54
+ pending = undefined;
55
+ polling = undefined;
56
+ });
57
+ return pending;
58
+ }).catch(error => {
59
+ const failure = deviceLoginFailure(error);
60
+ state = failure;
61
+ return failure;
62
+ }).finally(() => { starting = undefined; });
63
+ return starting;
64
+ },
65
+ status() {
66
+ const { hasOAuth, oauthExpiresAt, hasApiKey, defaultAuthMode } = getAuthStatus();
67
+ const oauthState = !hasOAuth ? 'missing'
68
+ : !oauthExpiresAt ? 'unknown'
69
+ : Date.parse(oauthExpiresAt) > Date.now() ? 'unexpired' : 'expired';
70
+ return {
71
+ ...state,
72
+ oauth_state: oauthState,
73
+ oauth_expires_at: oauthExpiresAt,
74
+ has_api_key: hasApiKey,
75
+ auth_mode: defaultAuthMode,
76
+ };
77
+ },
78
+ async close() {
79
+ controller.abort();
80
+ await starting;
81
+ await polling;
82
+ },
83
+ };
84
+ }
@@ -1,11 +1,11 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { normalizeAllowedHost, normalizeAllowedOrigin, normalizeHttpPath, type HttpServerOptions } from './http-server.js';
3
3
 
4
- /** CLI flags override environment defaults; an explicit token file wins over env credentials. */
5
- export function loadHttpOptions(args: string[], env: NodeJS.ProcessEnv = process.env): HttpServerOptions {
4
+ /** Parse listener options without reading a single-account credential. */
5
+ export function parseHttpOptions(args: string[], env: NodeJS.ProcessEnv) {
6
6
  let host = env.X_SEARCH_HTTP_HOST ?? '127.0.0.1';
7
7
  let port = env.X_SEARCH_HTTP_PORT ?? '8000';
8
- let path = env.X_SEARCH_HTTP_PATH ?? '/mcp';
8
+ let path = env.X_SEARCH_HTTP_PATH;
9
9
  let tokenFile: string | undefined;
10
10
  const hosts: string[] = [];
11
11
  const origins: string[] = [];
@@ -32,7 +32,13 @@ export function loadHttpOptions(args: string[], env: NodeJS.ProcessEnv = process
32
32
  const parseList = (value: string | undefined) => value?.split(',').map(item => item.trim()).filter(Boolean) ?? [];
33
33
  const allowedHosts = (hosts.length ? hosts : parseList(env.X_SEARCH_HTTP_ALLOWED_HOSTS)).map(normalizeAllowedHost);
34
34
  const allowedOrigins = (origins.length ? origins : parseList(env.X_SEARCH_HTTP_ALLOWED_ORIGINS)).map(normalizeAllowedOrigin);
35
- const endpoint = normalizeHttpPath(path);
35
+ return { host, port: Number(port), path: path === undefined ? undefined : normalizeHttpPath(path),
36
+ allowedHosts, allowedOrigins, tokenFile };
37
+ }
38
+
39
+ /** CLI flags override environment defaults; an explicit token file wins over env credentials. */
40
+ export function loadHttpOptions(args: string[], env: NodeJS.ProcessEnv = process.env): HttpServerOptions {
41
+ const { tokenFile, path, ...listener } = parseHttpOptions(args, env);
36
42
  let token = env.X_SEARCH_HTTP_TOKEN?.trim();
37
43
  const file = tokenFile ?? (!token ? env.X_SEARCH_HTTP_TOKEN_FILE : undefined);
38
44
  if (file !== undefined) {
@@ -44,5 +50,5 @@ export function loadHttpOptions(args: string[], env: NodeJS.ProcessEnv = process
44
50
  if (!token || /\s/.test(token)) {
45
51
  throw new Error('Set X_SEARCH_HTTP_TOKEN or a non-empty HTTP token file via --token-file / X_SEARCH_HTTP_TOKEN_FILE');
46
52
  }
47
- return { host, port: Number(port), path: endpoint, token, allowedHosts, allowedOrigins };
53
+ return { ...listener, path: path ?? '/mcp', token };
48
54
  }
@@ -1,11 +1,12 @@
1
1
  import { timingSafeEqual } from 'node:crypto';
2
- import { createServer as createNodeServer, type ServerResponse } from 'node:http';
2
+ import { createServer as createNodeServer, type IncomingMessage, type ServerResponse } from 'node:http';
3
3
  import { isIP } from 'node:net';
4
- import { createMcpHandler, McpServer, type McpServerFactory } from '@modelcontextprotocol/server';
4
+ import { createMcpHandler, McpServer, type AuthInfo, type McpServerFactory } from '@modelcontextprotocol/server';
5
5
  import { hostHeaderValidation, originValidation, toNodeHandler } from '@modelcontextprotocol/node';
6
6
 
7
7
  export interface HttpServerOptions {
8
- token: string;
8
+ token?: string;
9
+ authentication?: HttpAuthentication;
9
10
  host?: string;
10
11
  port?: number;
11
12
  path?: string;
@@ -14,6 +15,13 @@ export interface HttpServerOptions {
14
15
  maxRequestBodyBytes?: number;
15
16
  }
16
17
 
18
+ export interface HttpAuthentication {
19
+ resourceMetadataUrl: string;
20
+ scope: string;
21
+ verify(token: string): Promise<AuthInfo | 'insufficient_scope' | 'forbidden' | null>;
22
+ route?(path: string, request: IncomingMessage, response: ServerResponse): Promise<boolean>;
23
+ }
24
+
17
25
  export interface RunningHttpServer {
18
26
  url: string;
19
27
  close(): Promise<void>;
@@ -54,7 +62,11 @@ function json(response: ServerResponse, status: number, message: string): void {
54
62
 
55
63
  /** Owns one listener and the SDK's stateless per-request handler. */
56
64
  export async function startHttp(factory: McpServerFactory, options: HttpServerOptions): Promise<RunningHttpServer> {
57
- if (typeof options.token !== 'string' || !options.token.trim() || /\s/.test(options.token)) {
65
+ const authentication = options.authentication;
66
+ if (authentication && options.token !== undefined) {
67
+ throw new Error('Select one HTTP authentication mode');
68
+ }
69
+ if (!authentication && (typeof options.token !== 'string' || !options.token.trim() || /\s/.test(options.token))) {
58
70
  throw new Error('A non-empty HTTP bearer token without whitespace is required');
59
71
  }
60
72
  const host = options.host ?? '127.0.0.1';
@@ -71,7 +83,7 @@ export async function startHttp(factory: McpServerFactory, options: HttpServerOp
71
83
  const allowedOrigins = (options.allowedOrigins ?? []).map(normalizeAllowedOrigin);
72
84
  const validateHost = hostHeaderValidation(allowedHosts);
73
85
  const validateOrigin = originValidation(allowedOrigins.length ? allowedOrigins.map(value => new URL(value).hostname) : loopback);
74
- const expectedToken = Buffer.from(options.token);
86
+ const expectedToken = Buffer.from(options.token ?? '');
75
87
  type Product = Awaited<ReturnType<McpServerFactory>>;
76
88
  const products = new Set<Product>();
77
89
  const creating = new Set<Promise<Product>>();
@@ -99,8 +111,9 @@ export async function startHttp(factory: McpServerFactory, options: HttpServerOp
99
111
  };
100
112
  const handler = createMcpHandler(ownedFactory, { legacy: 'stateless', maxRequestBodySize: maxBody });
101
113
  const nodeHandler = toNodeHandler(handler, { maxRequestBodySize: maxBody });
114
+ const requests = new Set<Promise<void>>();
102
115
 
103
- const listener = createNodeServer((request, response) => {
116
+ async function handleRequest(request: IncomingMessage & { auth?: AuthInfo }, response: ServerResponse) {
104
117
  if (!validateHost(request, response) || !validateOrigin(request, response)) return;
105
118
  const origin = request.headers.origin;
106
119
  if (origin && allowedOrigins.length && !allowedOrigins.includes(origin)) {
@@ -112,14 +125,14 @@ export async function startHttp(factory: McpServerFactory, options: HttpServerOp
112
125
  json(response, 400, 'Invalid request URL');
113
126
  return;
114
127
  }
115
- if (pathname !== endpointPath) {
116
- json(response, 404, 'Not found');
117
- return;
118
- }
119
128
  if (origin && allowedOrigins.includes(origin)) {
120
129
  response.setHeader('Access-Control-Allow-Origin', origin);
121
130
  response.setHeader('Vary', 'Origin');
122
- response.setHeader('Access-Control-Expose-Headers', 'MCP-Protocol-Version, MCP-Session-Id');
131
+ response.setHeader('Access-Control-Expose-Headers', 'MCP-Protocol-Version, MCP-Session-Id, WWW-Authenticate');
132
+ }
133
+ if (pathname !== endpointPath) {
134
+ if (!await authentication?.route?.(pathname, request, response)) json(response, 404, 'Not found');
135
+ return;
123
136
  }
124
137
  if (request.method === 'OPTIONS' && origin && allowedOrigins.includes(origin)) {
125
138
  if (request.headers['access-control-request-method'] !== 'POST') {
@@ -144,18 +157,41 @@ export async function startHttp(factory: McpServerFactory, options: HttpServerOp
144
157
  return;
145
158
  }
146
159
  const authorization = request.headers.authorization;
147
- const supplied = typeof authorization === 'string' ? /^Bearer\s+(\S+)$/i.exec(authorization)?.[1] : undefined;
148
- const candidate = Buffer.from(supplied ?? '');
149
- if (candidate.length !== expectedToken.length || !timingSafeEqual(candidate, expectedToken)) {
150
- response.setHeader('WWW-Authenticate', 'Bearer realm="x-search-mcp"');
151
- json(response, 401, 'Valid MCP bearer credentials are required');
152
- return;
160
+ const supplied = typeof authorization === 'string' && request.headersDistinct.authorization?.length === 1
161
+ ? /^Bearer\s+(\S+)$/i.exec(authorization)?.[1] : undefined;
162
+ if (authentication) {
163
+ const verdict = supplied ? await authentication.verify(supplied) : null;
164
+ if (response.destroyed || stopping) return;
165
+ if (verdict === 'forbidden') {
166
+ json(response, 403, 'This user is not invited to use this service');
167
+ return;
168
+ }
169
+ if (verdict === null || verdict === 'insufficient_scope') {
170
+ const error = verdict === 'insufficient_scope' ? ', error="insufficient_scope"' : supplied ? ', error="invalid_token"' : '';
171
+ response.setHeader('WWW-Authenticate', `Bearer resource_metadata="${authentication.resourceMetadataUrl}", scope="${authentication.scope}"${error}`);
172
+ json(response, verdict === 'insufficient_scope' ? 403 : 401, 'Valid MCP bearer credentials are required');
173
+ return;
174
+ }
175
+ request.auth = verdict;
176
+ } else {
177
+ const candidate = Buffer.from(supplied ?? '');
178
+ if (candidate.length !== expectedToken.length || !timingSafeEqual(candidate, expectedToken)) {
179
+ response.setHeader('WWW-Authenticate', 'Bearer realm="x-search-mcp"');
180
+ json(response, 401, 'Valid MCP bearer credentials are required');
181
+ return;
182
+ }
153
183
  }
154
- void nodeHandler(request, response).catch(() => {
184
+ await nodeHandler(request, response);
185
+ }
186
+
187
+ const listener = createNodeServer((request, response) => {
188
+ const task = handleRequest(request, response).catch(() => {
155
189
  if (response.destroyed) return;
156
190
  if (response.headersSent) response.destroy();
157
191
  else json(response, 500, 'MCP HTTP request failed');
158
192
  });
193
+ requests.add(task);
194
+ void task.then(() => { requests.delete(task); });
159
195
  });
160
196
 
161
197
  try {
@@ -181,6 +217,7 @@ export async function startHttp(factory: McpServerFactory, options: HttpServerOp
181
217
  // The SDK's legacy leg starts per-request teardown without awaiting it.
182
218
  // Drain every owned product as well as the modern handler's exchanges.
183
219
  await Promise.all([handler.close(), ...[...products].map(product => product.close()), stopped]);
220
+ await Promise.allSettled([...requests]);
184
221
  })();
185
222
  return closing;
186
223
  },
package/src/index.ts CHANGED
@@ -9,3 +9,6 @@ export * from './http-server.js';
9
9
  export * from './http-config.js';
10
10
  export * from './version.js';
11
11
  export * from './cli.js';
12
+ export * from './multi-user/bindings.js';
13
+ export * from './multi-user/keys.js';
14
+ export * from './multi-user/service.js';
@@ -0,0 +1,135 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { closeSync, constants, fstatSync, openSync, statSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { open, seal, type DataKeyProvider, type SealedValue } from './keys.js';
6
+
7
+ export interface Principal {
8
+ issuer: string;
9
+ subject: string;
10
+ }
11
+
12
+ interface BindingRow {
13
+ revision: string;
14
+ envelope: string | null;
15
+ }
16
+
17
+ interface CredentialEnvelope {
18
+ version: 1;
19
+ wrapped: string;
20
+ value: SealedValue;
21
+ }
22
+
23
+ export class BindingChangedError extends Error {
24
+ constructor() { super('The credential binding changed. Reload the settings page and try again.'); }
25
+ }
26
+
27
+ function contextFor(user: Principal, revision: string): string {
28
+ return JSON.stringify(['x-search-mcp', 'xai-api-key', user.issuer, user.subject, revision]);
29
+ }
30
+
31
+ export function validApiKey(value: string): boolean {
32
+ return /^[!-~]{1,512}$/.test(value);
33
+ }
34
+
35
+ export class BindingStore {
36
+ private readonly db: DatabaseSync;
37
+
38
+ constructor(file: string, private readonly keys: DataKeyProvider) {
39
+ const directory = statSync(dirname(file));
40
+ if (!directory.isDirectory() || directory.mode & 0o077 || directory.uid !== process.getuid?.()) {
41
+ throw new Error('The credential database requires a private, user-owned directory');
42
+ }
43
+ const fd = openSync(file, constants.O_RDWR | constants.O_CREAT | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
44
+ try {
45
+ const info = fstatSync(fd);
46
+ if (!info.isFile() || info.mode & 0o077 || info.uid !== process.getuid?.()) {
47
+ throw new Error('The credential database must be a private, user-owned file');
48
+ }
49
+ } finally { closeSync(fd); }
50
+
51
+ this.db = new DatabaseSync(file);
52
+ try {
53
+ this.db.exec(`
54
+ PRAGMA busy_timeout = 5000;
55
+ PRAGMA secure_delete = ON;
56
+ CREATE TABLE IF NOT EXISTS bindings (
57
+ issuer TEXT NOT NULL,
58
+ subject TEXT NOT NULL,
59
+ revision TEXT NOT NULL,
60
+ envelope TEXT,
61
+ PRIMARY KEY (issuer, subject)
62
+ ) STRICT;
63
+ `);
64
+ } catch (error) {
65
+ this.db.close();
66
+ throw error;
67
+ }
68
+ }
69
+
70
+ private row(user: Principal): BindingRow | undefined {
71
+ return this.db.prepare('SELECT revision, envelope FROM bindings WHERE issuer = ? AND subject = ?')
72
+ .get(user.issuer, user.subject) as BindingRow | undefined;
73
+ }
74
+
75
+ has(user: Principal): boolean { return Boolean(this.row(user)?.envelope); }
76
+
77
+ async bind(user: Principal, apiKey: string): Promise<void> {
78
+ if (!validApiKey(apiKey)) throw new Error('Enter a valid xAI API key');
79
+ const previous = this.row(user)?.revision ?? null;
80
+ const revision = randomUUID();
81
+ const context = contextFor(user, revision);
82
+ let envelope: CredentialEnvelope;
83
+ try {
84
+ const { plaintext, wrapped } = await this.keys.generate(context);
85
+ const secret = Buffer.from(apiKey);
86
+ try {
87
+ envelope = { version: 1, wrapped, value: seal(plaintext, secret, context) };
88
+ } finally {
89
+ plaintext.fill(0);
90
+ secret.fill(0);
91
+ }
92
+ } catch {
93
+ throw new Error('Could not encrypt the credential');
94
+ }
95
+ const saved = this.db.prepare(`
96
+ INSERT INTO bindings (issuer, subject, revision, envelope)
97
+ SELECT ?, ?, ?, ?
98
+ WHERE (SELECT revision FROM bindings WHERE issuer = ? AND subject = ?) IS ?
99
+ ON CONFLICT (issuer, subject) DO UPDATE SET revision = excluded.revision, envelope = excluded.envelope
100
+ `).run(user.issuer, user.subject, revision, JSON.stringify(envelope), user.issuer, user.subject, previous);
101
+ if (!saved.changes) throw new BindingChangedError();
102
+ }
103
+
104
+ async get(user: Principal): Promise<string | null> {
105
+ const row = this.row(user);
106
+ if (!row?.envelope) return null;
107
+ const context = contextFor(user, row.revision);
108
+ let apiKey: string;
109
+ try {
110
+ const envelope = JSON.parse(row.envelope) as CredentialEnvelope;
111
+ if (envelope.version !== 1) throw new Error('Unsupported credential format');
112
+ const dataKey = await this.keys.unwrap(envelope.wrapped, context);
113
+ try {
114
+ const secret = open(dataKey, envelope.value, context);
115
+ try { apiKey = secret.toString('utf8'); } finally { secret.fill(0); }
116
+ } finally { dataKey.fill(0); }
117
+ } catch {
118
+ throw new Error('Could not decrypt the credential');
119
+ }
120
+ // An unbind or replacement can complete during the asynchronous KMS read.
121
+ return this.row(user)?.revision === row.revision ? apiKey : null;
122
+ }
123
+
124
+ unbind(user: Principal): boolean {
125
+ const wasBound = this.has(user);
126
+ // Retain only the revision so an older in-flight bind cannot restore it.
127
+ this.db.prepare(`
128
+ INSERT INTO bindings (issuer, subject, revision, envelope) VALUES (?, ?, ?, NULL)
129
+ ON CONFLICT (issuer, subject) DO UPDATE SET revision = excluded.revision, envelope = NULL
130
+ `).run(user.issuer, user.subject, randomUUID());
131
+ return wasBound;
132
+ }
133
+
134
+ close(): void { this.db.close(); }
135
+ }