@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,329 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import type { IncomingMessage, ServerResponse } from 'node:http';
3
+ import * as oidc from 'openid-client';
4
+ import type { HttpAuthentication } from '../http-server.js';
5
+ import { BindingChangedError, validApiKey, type BindingStore, type Principal } from './bindings.js';
6
+ import { fetchIdentity, httpsUrl, type IdentityOptions } from './identity.js';
7
+ import { open, seal, type SealedValue } from './keys.js';
8
+
9
+ export interface SettingsOptions {
10
+ clientId: string;
11
+ clientSecret: string;
12
+ }
13
+
14
+ interface Expiring {
15
+ expiresAt: number;
16
+ }
17
+
18
+ interface Login extends Expiring {
19
+ state: string;
20
+ nonce: string;
21
+ verifier: string;
22
+ }
23
+
24
+ interface Session extends Expiring {
25
+ user: Principal;
26
+ csrf: string;
27
+ }
28
+
29
+ const loginCookie = '__Host-x-search-login';
30
+ const sessionCookie = '__Host-x-search-settings';
31
+ const loginSeconds = 5 * 60;
32
+ const sessionSeconds = 60 * 60;
33
+ const maxEntries = 1024;
34
+ const maxSessionsPerUser = 5;
35
+ const maxFormBytes = 4096;
36
+ const keyWritesPerMinute = 5;
37
+ const maxActiveCallbacks = 16;
38
+ const pagePath = '/settings';
39
+ const loginPath = '/settings/login';
40
+ const callbackPath = '/settings/callback';
41
+ const keyPath = '/settings/key';
42
+ const unbindPath = '/settings/unbind';
43
+ const logoutPath = '/settings/logout';
44
+ const postPaths = new Set([keyPath, unbindPath, logoutPath]);
45
+
46
+ function token(): string { return randomBytes(32).toString('base64url'); }
47
+
48
+ function cookieValue(request: IncomingMessage, name: string): string {
49
+ const values = request.headers.cookie?.split(';').map(part => part.trim())
50
+ .filter(part => part.startsWith(name + '=')) ?? [];
51
+ return values.length === 1 ? values[0].slice(name.length + 1) : '';
52
+ }
53
+
54
+ function cookie(name: string, value: string, seconds: number): string {
55
+ return `${name}=${value}; Path=/; Max-Age=${seconds}; HttpOnly; Secure; SameSite=Lax`;
56
+ }
57
+
58
+ function lookup<T extends Expiring>(entries: Map<string, T>, key: string): T | undefined {
59
+ const entry = entries.get(key);
60
+ if (entry && entry.expiresAt > Date.now()) return entry;
61
+ entries.delete(key);
62
+ return undefined;
63
+ }
64
+
65
+ function hasRoom<T extends Expiring>(entries: Map<string, T>): boolean {
66
+ const now = Date.now();
67
+ for (const [key, entry] of entries) if (entry.expiresAt <= now) entries.delete(key);
68
+ return entries.size < maxEntries;
69
+ }
70
+
71
+ function readLogin(key: Buffer, value: string): Login | undefined {
72
+ if (!/^[A-Za-z0-9_-]{1,1024}$/.test(value)) return undefined;
73
+ try {
74
+ const envelope = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as SealedValue;
75
+ const plaintext = open(key, envelope, loginCookie);
76
+ try {
77
+ const login = JSON.parse(plaintext.toString('utf8')) as Login;
78
+ return login.expiresAt > Date.now() ? login : undefined;
79
+ } finally { plaintext.fill(0); }
80
+ } catch { return undefined; }
81
+ }
82
+
83
+ function redirect(response: ServerResponse, url: string): void {
84
+ response.writeHead(303, { Location: url });
85
+ response.end();
86
+ }
87
+
88
+ function escapeHtml(value: string): string {
89
+ return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
90
+ .replaceAll('"', '&quot;').replaceAll("'", '&#39;');
91
+ }
92
+
93
+ function page(response: ServerResponse, status: number, body: string): void {
94
+ response.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' });
95
+ response.end(`<!doctype html>
96
+ <html lang="en">
97
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
98
+ <title>X Search Settings</title>
99
+ <style>
100
+ :root { color-scheme: light dark; font: 1rem system-ui, sans-serif; }
101
+ body { margin: 3rem auto; max-width: 33rem; padding: 0 1.25rem; line-height: 1.5; }
102
+ h1 { line-height: 1.2; } form { margin: 1rem 0; } input, button { font: inherit; }
103
+ input[type=password] { display: block; width: 100%; box-sizing: border-box; margin: .4rem 0 1rem; padding: .5rem; }
104
+ button { display: block; margin-top: 1rem; padding: .45rem .8rem; }
105
+ code { overflow-wrap: anywhere; }
106
+ </style>
107
+ </head><body><main><h1>X Search Settings</h1>${body}</main></body>
108
+ </html>`);
109
+ }
110
+
111
+ function settingsPage(response: ServerResponse, session: Session | undefined, store: BindingStore): void {
112
+ if (!session) {
113
+ page(response, 200, `<p>Sign in with the same account you use to connect your MCP client.</p>
114
+ <p><a href="${loginPath}">Sign in</a></p>`);
115
+ return;
116
+ }
117
+ const bound = store.has(session.user);
118
+ const csrf = `<input type="hidden" name="csrf" value="${session.csrf}">`;
119
+ page(response, 200, `<p>Account ID <code>${escapeHtml(session.user.subject)}</code></p>
120
+ <p>${bound ? 'An xAI API key is saved.' : 'No xAI API key is saved.'}</p>
121
+ <form method="post" action="${keyPath}">
122
+ ${csrf}
123
+ <label for="key">xAI API key</label>
124
+ <input type="password" name="key" id="key" maxlength="512" required autocomplete="off" spellcheck="false">
125
+ <label><input type="checkbox" name="consent" value="yes" required>
126
+ I agree to store my API key encrypted on this server and use my xAI account for searches.</label>
127
+ <button type="submit">${bound ? 'Replace key' : 'Save key'}</button>
128
+ </form>
129
+ ${bound ? `<form method="post" action="${unbindPath}">${csrf}<button type="submit">Remove key</button></form>` : ''}
130
+ <form method="post" action="${logoutPath}">${csrf}<button type="submit">Sign out of Settings</button></form>`);
131
+ }
132
+
133
+ async function readForm(request: IncomingMessage): Promise<URLSearchParams | undefined> {
134
+ const mediaType = request.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase();
135
+ if (mediaType !== 'application/x-www-form-urlencoded' || Number(request.headers['content-length']) > maxFormBytes) {
136
+ request.resume();
137
+ return undefined;
138
+ }
139
+ let size = 0;
140
+ const chunks: Buffer[] = [];
141
+ try {
142
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
143
+ size += chunk.length;
144
+ if (size > maxFormBytes) {
145
+ request.resume();
146
+ return undefined;
147
+ }
148
+ chunks.push(chunk);
149
+ }
150
+ const body = Buffer.concat(chunks, size);
151
+ try { return new URLSearchParams(body.toString('utf8')); }
152
+ finally { body.fill(0); }
153
+ } finally {
154
+ for (const chunk of chunks) chunk.fill(0);
155
+ }
156
+ }
157
+
158
+ export async function createSettings(
159
+ options: SettingsOptions & IdentityOptions,
160
+ publicOrigin: string,
161
+ invited: (subject: unknown) => subject is string,
162
+ store: BindingStore,
163
+ ): Promise<NonNullable<HttpAuthentication['route']>> {
164
+ const { issuer, jwksUri, clientId, clientSecret, identityFetch = fetchIdentity } = options;
165
+ if (!clientId || !clientSecret) {
166
+ throw new Error('Configure a separate confidential OIDC client for the settings page');
167
+ }
168
+ let provider: oidc.Configuration;
169
+ try {
170
+ provider = await oidc.discovery(httpsUrl(issuer, 'OAuth issuer'), clientId,
171
+ { token_endpoint_auth_method: 'client_secret_basic' }, oidc.ClientSecretBasic(clientSecret), {
172
+ timeout: 5,
173
+ execute: [oidc.enableNonRepudiationChecks],
174
+ [oidc.customFetch]: (url, init) => {
175
+ const { body, ...rest } = init;
176
+ return identityFetch(url, { ...rest, body: body instanceof Uint8Array ? Uint8Array.from(body) : body });
177
+ },
178
+ });
179
+ const metadata = provider.serverMetadata();
180
+ if (metadata.issuer !== issuer || metadata.jwks_uri !== jwksUri) {
181
+ throw new Error('Unexpected OIDC issuer or signing keys URL');
182
+ }
183
+ httpsUrl(metadata.authorization_endpoint ?? '', 'OIDC authorization endpoint');
184
+ httpsUrl(metadata.token_endpoint ?? '', 'OIDC token endpoint');
185
+ } catch {
186
+ throw new Error('Could not initialize the settings OIDC client. Check the issuer, discovery, and JWKS configuration.');
187
+ }
188
+ const callbackUrl = new URL(callbackPath, publicOrigin);
189
+ // Unauthenticated login starts consume no slots in a shared server-side pool.
190
+ const loginKey = randomBytes(32);
191
+ const callbacks = new Set<string>();
192
+ const consumed = new Map<string, Expiring>();
193
+ const sessions = new Map<string, Session>();
194
+ const keyWrites = new Map<string, { starts: number[]; active: boolean }>();
195
+
196
+ return async (path, request, response) => {
197
+ const writes = postPaths.has(path);
198
+ if (path !== pagePath && path !== loginPath && path !== callbackPath && !writes) return false;
199
+
200
+ response.setHeader('Cache-Control', 'no-store');
201
+ response.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'");
202
+ // A native form POST uses the document referrer policy to decide whether to send Origin.
203
+ response.setHeader('Referrer-Policy', path === pagePath ? 'same-origin' : 'no-referrer');
204
+ response.setHeader('X-Content-Type-Options', 'nosniff');
205
+ const method = writes ? 'POST' : 'GET';
206
+ const sessionId = cookieValue(request, sessionCookie);
207
+ if (request.method !== method) {
208
+ response.setHeader('Allow', method);
209
+ page(response, 405, '<p>Method not allowed.</p>');
210
+ } else if (path === pagePath) {
211
+ settingsPage(response, lookup(sessions, sessionId), store);
212
+ } else if (path === loginPath) {
213
+ const state = oidc.randomState();
214
+ const nonce = oidc.randomNonce();
215
+ const verifier = oidc.randomPKCECodeVerifier();
216
+ const challenge = await oidc.calculatePKCECodeChallenge(verifier);
217
+ const url = oidc.buildAuthorizationUrl(provider, { redirect_uri: callbackUrl.href, scope: 'openid',
218
+ response_type: 'code', state, nonce, code_challenge: challenge, code_challenge_method: 'S256' });
219
+ const login: Login = { state, nonce, verifier, expiresAt: Date.now() + loginSeconds * 1000 };
220
+ const plaintext = Buffer.from(JSON.stringify(login));
221
+ const sealed = seal(loginKey, plaintext, loginCookie);
222
+ plaintext.fill(0);
223
+ const value = Buffer.from(JSON.stringify(sealed)).toString('base64url');
224
+ response.setHeader('Set-Cookie', cookie(loginCookie, value, loginSeconds));
225
+ redirect(response, url.href);
226
+ } else if (path === callbackPath) {
227
+ const pending = readLogin(loginKey, cookieValue(request, loginCookie));
228
+ const url = new URL(callbackUrl);
229
+ url.search = new URL(request.url ?? callbackPath, publicOrigin).search;
230
+ const states = url.searchParams.getAll('state');
231
+ if (!pending || states.length !== 1 || states[0] !== pending.state
232
+ || callbacks.has(pending.state) || lookup(consumed, pending.state)) {
233
+ page(response, 400, `<p>Sign-in could not be verified. <a href="${pagePath}">Try again</a>.</p>`);
234
+ return true;
235
+ }
236
+ if (callbacks.size >= maxActiveCallbacks) {
237
+ page(response, 503, '<p>Sign-in is busy. Try again shortly.</p>');
238
+ return true;
239
+ }
240
+ if (!hasRoom(consumed)) {
241
+ const oldest = consumed.keys().next().value;
242
+ if (oldest) consumed.delete(oldest);
243
+ }
244
+ consumed.set(pending.state, { expiresAt: pending.expiresAt });
245
+ callbacks.add(pending.state);
246
+ const expiredLogin = cookie(loginCookie, '', 0);
247
+ response.setHeader('Set-Cookie', expiredLogin);
248
+ let subject: unknown;
249
+ try {
250
+ const response = await oidc.authorizationCodeGrant(provider, url, {
251
+ expectedState: pending.state, expectedNonce: pending.nonce, pkceCodeVerifier: pending.verifier,
252
+ });
253
+ subject = response.claims()?.sub;
254
+ } catch {
255
+ page(response, 400, `<p>Sign-in could not be verified. <a href="${pagePath}">Try again</a>.</p>`);
256
+ return true;
257
+ } finally { callbacks.delete(pending.state); }
258
+ if (!invited(subject)) {
259
+ page(response, 403, '<p>This account is not invited to use X Search.</p>');
260
+ return true;
261
+ }
262
+ sessions.delete(sessionId);
263
+ const ownSessions = [...sessions].filter(([, session]) => session.user.subject === subject);
264
+ if (ownSessions.length >= maxSessionsPerUser) sessions.delete(ownSessions[0][0]);
265
+ if (!hasRoom(sessions)) {
266
+ page(response, 503, '<p>Sign-in is busy. Try again later.</p>');
267
+ return true;
268
+ }
269
+ const id = token();
270
+ sessions.set(id, { user: { issuer, subject }, csrf: token(), expiresAt: Date.now() + sessionSeconds * 1000 });
271
+ response.setHeader('Set-Cookie', [expiredLogin, cookie(sessionCookie, id, sessionSeconds)]);
272
+ redirect(response, pagePath);
273
+ } else {
274
+ if (request.headers.origin !== publicOrigin || request.headersDistinct.origin?.length !== 1) {
275
+ page(response, 403, '<p>Open Settings directly to make changes.</p>');
276
+ return true;
277
+ }
278
+ const session = lookup(sessions, sessionId);
279
+ if (!session) {
280
+ page(response, 401, `<p><a href="${pagePath}">Sign in</a> to make changes.</p>`);
281
+ return true;
282
+ }
283
+ const form = await readForm(request);
284
+ if (!form) {
285
+ page(response, 400, '<p>Invalid form.</p>');
286
+ return true;
287
+ }
288
+ const csrf = form.getAll('csrf');
289
+ if (lookup(sessions, sessionId) !== session || csrf.length !== 1 || csrf[0] !== session.csrf) {
290
+ page(response, 403, `<p>Could not verify this form. <a href="${pagePath}">Reload Settings</a>.</p>`);
291
+ return true;
292
+ }
293
+ if (path === logoutPath) {
294
+ sessions.delete(sessionId);
295
+ response.setHeader('Set-Cookie', cookie(sessionCookie, '', 0));
296
+ } else if (path === unbindPath) {
297
+ store.unbind(session.user);
298
+ } else {
299
+ const keys = form.getAll('key');
300
+ const consent = form.getAll('consent');
301
+ if (keys.length !== 1 || !validApiKey(keys[0]) || consent.length !== 1 || consent[0] !== 'yes') {
302
+ page(response, 400, `<p>Enter your xAI API key and consent to save it. <a href="${pagePath}">Back to Settings</a>.</p>`);
303
+ return true;
304
+ }
305
+ const now = Date.now();
306
+ const rate = keyWrites.get(session.user.subject) ?? { starts: [], active: false };
307
+ rate.starts = rate.starts.filter(start => start > now - 60_000);
308
+ if (rate.active || rate.starts.length >= keyWritesPerMinute) {
309
+ page(response, 429, `<p>Too many key updates. Wait a minute and <a href="${pagePath}">try again</a>.</p>`);
310
+ return true;
311
+ }
312
+ rate.active = true;
313
+ rate.starts.push(now);
314
+ keyWrites.set(session.user.subject, rate);
315
+ try { await store.bind(session.user, keys[0]); }
316
+ catch (error) {
317
+ if (error instanceof BindingChangedError) {
318
+ page(response, 409, `<p>The saved key changed. <a href="${pagePath}">Reload Settings</a> and try again.</p>`);
319
+ } else {
320
+ page(response, 503, '<p>Could not save the key. Try again later.</p>');
321
+ }
322
+ return true;
323
+ } finally { rate.active = false; }
324
+ }
325
+ redirect(response, pagePath);
326
+ }
327
+ return true;
328
+ };
329
+ }
@@ -0,0 +1,113 @@
1
+ import { z } from 'zod';
2
+ import { HttpError } from './http.js';
3
+ import type { XSearchInput } from './types.js';
4
+
5
+ const queryLimit = 16_000;
6
+ const handleLimit = 10;
7
+ export const authModeSchema = z.enum(['auto', 'api_key', 'oauth']);
8
+
9
+ export const managedSearchInputSchema = z.strictObject({
10
+ query: z.string().describe('Search query, maximum 16000 characters after trimming'),
11
+ allowed_x_handles: z.array(z.string()).max(handleLimit).optional()
12
+ .describe('Only search these X handles, max 10. Mutually exclusive with excluded_x_handles.'),
13
+ excluded_x_handles: z.array(z.string()).max(handleLimit).optional()
14
+ .describe('Exclude these X handles, max 10. Mutually exclusive with allowed_x_handles.'),
15
+ from_date: z.string().optional().describe('Inclusive start date in YYYY-MM-DD, at most today UTC'),
16
+ to_date: z.string().optional().describe('Exclusive end date in YYYY-MM-DD, later than from_date'),
17
+ enable_image_understanding: z.boolean().optional().describe('Analyze images in matching posts'),
18
+ enable_video_understanding: z.boolean().optional().describe('Analyze videos in matching posts'),
19
+ });
20
+
21
+ export const personalSearchInputSchema = managedSearchInputSchema.extend({
22
+ auth_mode: authModeSchema.optional().describe('Override the configured credential selection mode'),
23
+ });
24
+
25
+ function invalidInput(message: string): HttpError {
26
+ return new HttpError('INVALID_ARGUMENT', `Validation error: ${message}`);
27
+ }
28
+
29
+ function isLeapYear(year: number): boolean {
30
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
31
+ }
32
+
33
+ /** Validate a real calendar date before comparing ISO date strings. */
34
+ export function validateCalendarDate(dateStr: string, fieldName: string): { year: number; month: number; day: number } {
35
+ if (typeof dateStr !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
36
+ throw invalidInput(`${fieldName} must be formatted as YYYY-MM-DD`);
37
+ }
38
+ const [year, month, day] = dateStr.split('-').map(Number);
39
+ if (month < 1 || month > 12) {
40
+ throw invalidInput(`${fieldName} has invalid month: ${month}`);
41
+ }
42
+ const daysInMonth = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
43
+ if (day < 1 || day > daysInMonth[month - 1]) {
44
+ throw invalidInput(`${fieldName} has invalid day ${day} for month ${month} of year ${year}`);
45
+ }
46
+ return { year, month, day };
47
+ }
48
+
49
+ /** Strip leading @ and validate the X handle length and character set. */
50
+ export function validateAndNormalizeHandles(handles: unknown[], fieldName: string): string[] {
51
+ if (!Array.isArray(handles)) {
52
+ throw invalidInput(`${fieldName} must be an array of strings`);
53
+ }
54
+ if (handles.length > handleLimit) {
55
+ throw invalidInput(`${fieldName} cannot exceed ${handleLimit} handles`);
56
+ }
57
+ return handles.map((handle, index) => {
58
+ if (typeof handle !== 'string') {
59
+ throw invalidInput(`${fieldName}[${index}] must be a string`);
60
+ }
61
+ const clean = handle.replace(/^@+/, '').trim();
62
+ if (!/^[A-Za-z0-9_]{1,15}$/.test(clean)) {
63
+ throw invalidInput(`${fieldName}[${index}] must be 1-15 characters matching [A-Za-z0-9_]`);
64
+ }
65
+ return clean;
66
+ });
67
+ }
68
+
69
+ /** Apply the same search rules before credentials are looked up or xAI is called. */
70
+ export function validateSearchParams(rawParams: unknown, { managed = false } = {}): XSearchInput {
71
+ const shape = managed ? managedSearchInputSchema : personalSearchInputSchema;
72
+ const parsed = shape.safeParse(rawParams);
73
+ if (!parsed.success) {
74
+ const detail = parsed.error.issues.map(issue =>
75
+ issue.path.length ? `${issue.path.join('.')}: ${issue.message}` : issue.message).join('; ');
76
+ throw invalidInput(detail);
77
+ }
78
+ const params: XSearchInput = parsed.data;
79
+ const query = params.query.trim();
80
+ if (!query) throw invalidInput('"query" cannot be empty');
81
+ if (query.length > queryLimit) {
82
+ throw invalidInput(`"query" exceeds maximum length of ${queryLimit} characters (got ${query.length})`);
83
+ }
84
+
85
+ const allowed = params.allowed_x_handles && validateAndNormalizeHandles(params.allowed_x_handles, 'allowed_x_handles');
86
+ const excluded = params.excluded_x_handles && validateAndNormalizeHandles(params.excluded_x_handles, 'excluded_x_handles');
87
+ if (allowed?.length && excluded?.length) {
88
+ throw invalidInput('allowed_x_handles and excluded_x_handles cannot both be non-empty');
89
+ }
90
+ const { from_date: from, to_date: to } = params;
91
+ if (from !== undefined) validateCalendarDate(from, 'from_date');
92
+ if (to !== undefined) validateCalendarDate(to, 'to_date');
93
+ if (from && to && from >= to) {
94
+ throw invalidInput(`from_date (${from}) must be strictly earlier than to_date (${to})`);
95
+ }
96
+ if (from) {
97
+ const todayUtc = new Date().toISOString().slice(0, 10);
98
+ if (from > todayUtc) {
99
+ throw invalidInput(`from_date (${from}) cannot be later than today UTC (${todayUtc})`);
100
+ }
101
+ }
102
+
103
+ return {
104
+ query,
105
+ allowed_x_handles: allowed,
106
+ excluded_x_handles: excluded,
107
+ from_date: from,
108
+ to_date: to,
109
+ enable_image_understanding: params.enable_image_understanding,
110
+ enable_video_understanding: params.enable_video_understanding,
111
+ auth_mode: params.auth_mode,
112
+ };
113
+ }
@@ -0,0 +1,127 @@
1
+ import type { InlineCitation, ServerSideCall, XSearchResult } from './types.js';
2
+
3
+ const xSearchToolNames = new Set([
4
+ 'x_search',
5
+ 'x_keyword_search',
6
+ 'x_semantic_search',
7
+ 'x_user_search',
8
+ 'x_thread_fetch',
9
+ ]);
10
+
11
+ type SearchResponse = Pick<XSearchResult, 'answer' | 'citations' | 'inline_citations' | 'search_execution'
12
+ | 'server_side_calls' | 'response_status' | 'incomplete_details' | 'usage'>;
13
+
14
+ function record(value: unknown): Record<string, unknown> | undefined {
15
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
16
+ ? value as Record<string, unknown> : undefined;
17
+ }
18
+
19
+ function text(value: unknown): string {
20
+ return typeof value === 'string' ? value.trim() : '';
21
+ }
22
+
23
+ function citationUrl(value: unknown): string | undefined {
24
+ const candidate = text(value);
25
+ if (!/^https?:\/\//i.test(candidate) || /[\x00-\x1f\x7f]/.test(candidate)) return undefined;
26
+ try {
27
+ const url = new URL(candidate);
28
+ return url.username || url.password ? undefined : candidate;
29
+ } catch {
30
+ return undefined;
31
+ }
32
+ }
33
+
34
+ function citationOffset(value: unknown): number | null {
35
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : null;
36
+ }
37
+
38
+ function inlineCitation(value: unknown): InlineCitation | undefined {
39
+ const annotation = record(value);
40
+ if (!annotation || (annotation.type !== 'url_citation' && !annotation.url)) return undefined;
41
+ const nested = record(annotation.citation);
42
+ const url = citationUrl(annotation.url) ?? citationUrl(nested?.url);
43
+ if (!url) return undefined;
44
+ return {
45
+ url,
46
+ title: text(annotation.title) || text(nested?.title) || null,
47
+ start_index: citationOffset(annotation.start_index),
48
+ end_index: citationOffset(annotation.end_index),
49
+ };
50
+ }
51
+
52
+ function hasXSearchUsage(usage: unknown): boolean {
53
+ const details = record(record(usage)?.server_side_tool_usage_details);
54
+ return [details?.x_posts_fetched, details?.x_users_fetched].some(
55
+ count => typeof count === 'number' && Number.isSafeInteger(count) && count > 0,
56
+ );
57
+ }
58
+
59
+ /** Normalize xAI's visible answer, citations and evidence independently of transport and credentials. */
60
+ export function normalizeSearchResponse(raw: Record<string, unknown>): SearchResponse {
61
+ const canonicalAnswer = text(raw.output_text);
62
+ const answerPieces: string[] = [];
63
+ const citations = new Set<string>();
64
+ const inlineCitations: InlineCitation[] = [];
65
+ const serverSideCalls: ServerSideCall[] = [];
66
+ let xSearchObserved = hasXSearchUsage(raw.usage);
67
+
68
+ for (const sources of [raw.citations, raw.sources]) {
69
+ if (!Array.isArray(sources)) continue;
70
+ for (const source of sources) {
71
+ const url = citationUrl(source);
72
+ if (url) citations.add(url);
73
+ }
74
+ }
75
+
76
+ for (const value of Array.isArray(raw.output) ? raw.output : []) {
77
+ const item = record(value);
78
+ if (!item) continue;
79
+ const name = text(item.name) || text(item.tool_name);
80
+ const callId = text(item.call_id) || text(item.id);
81
+ const isXSearch = xSearchToolNames.has(name) || callId.startsWith('xs_');
82
+ if (isXSearch) xSearchObserved = true;
83
+ if ((isXSearch || item.type === 'custom_tool_call') && (name || callId)) {
84
+ serverSideCalls.push({
85
+ call_id: callId || null,
86
+ name: name || null,
87
+ arguments: item.arguments ?? item.input ?? null,
88
+ });
89
+ }
90
+
91
+ if (item.type !== 'message' && item.type !== undefined) continue;
92
+ const message = record(item.message) ?? item;
93
+ const role = message.role ?? item.role;
94
+ if (role !== undefined && role !== 'assistant') continue;
95
+ if (typeof message.content === 'string') {
96
+ const piece = text(message.content);
97
+ if (piece && !canonicalAnswer) answerPieces.push(piece);
98
+ continue;
99
+ }
100
+ if (!Array.isArray(message.content)) continue;
101
+ for (const blockValue of message.content) {
102
+ const block = record(blockValue);
103
+ if (!block || (block.type !== undefined && block.type !== 'output_text' && block.type !== 'text')) continue;
104
+ const piece = text(block.output_text) || text(block.text);
105
+ if (piece && !canonicalAnswer) answerPieces.push(piece);
106
+ if (!Array.isArray(block.annotations)) continue;
107
+ for (const annotation of block.annotations) {
108
+ const citation = inlineCitation(annotation);
109
+ if (citation) {
110
+ inlineCitations.push(citation);
111
+ citations.add(citation.url);
112
+ }
113
+ }
114
+ }
115
+ }
116
+
117
+ return {
118
+ answer: canonicalAnswer || answerPieces.join('\n\n'),
119
+ citations: [...citations],
120
+ inline_citations: inlineCitations,
121
+ search_execution: xSearchObserved ? 'observed' : 'unreported',
122
+ server_side_calls: serverSideCalls,
123
+ response_status: text(raw.status) || 'completed',
124
+ incomplete_details: raw.incomplete_details ?? null,
125
+ usage: raw.usage ?? null,
126
+ };
127
+ }