desearch-mcp-server 0.2.0 → 0.2.1

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 (45) hide show
  1. package/CHANGELOG.md +13 -1
  2. package/README.md +58 -4
  3. package/build/http.d.ts +2 -8
  4. package/build/http.d.ts.map +1 -1
  5. package/build/http.js +126 -37
  6. package/build/oauth/client-ip.d.ts +10 -0
  7. package/build/oauth/client-ip.d.ts.map +1 -0
  8. package/build/oauth/client-ip.js +28 -0
  9. package/build/oauth/crypto.d.ts +20 -0
  10. package/build/oauth/crypto.d.ts.map +1 -0
  11. package/build/oauth/crypto.js +89 -0
  12. package/build/oauth/errors.d.ts +9 -0
  13. package/build/oauth/errors.d.ts.map +1 -0
  14. package/build/oauth/errors.js +13 -0
  15. package/build/oauth/flow.d.ts +8 -0
  16. package/build/oauth/flow.d.ts.map +1 -0
  17. package/build/oauth/flow.js +424 -0
  18. package/build/oauth/http.d.ts +24 -0
  19. package/build/oauth/http.d.ts.map +1 -0
  20. package/build/oauth/http.js +137 -0
  21. package/build/oauth/metadata.d.ts +19 -0
  22. package/build/oauth/metadata.d.ts.map +1 -0
  23. package/build/oauth/metadata.js +86 -0
  24. package/build/oauth/page.d.ts +14 -0
  25. package/build/oauth/page.d.ts.map +1 -0
  26. package/build/oauth/page.js +92 -0
  27. package/build/oauth/rate-limit.d.ts +14 -0
  28. package/build/oauth/rate-limit.d.ts.map +1 -0
  29. package/build/oauth/rate-limit.js +19 -0
  30. package/build/oauth/redirects.d.ts +14 -0
  31. package/build/oauth/redirects.d.ts.map +1 -0
  32. package/build/oauth/redirects.js +78 -0
  33. package/build/oauth/store.d.ts +139 -0
  34. package/build/oauth/store.d.ts.map +1 -0
  35. package/build/oauth/store.js +606 -0
  36. package/build/oauth/validate-key.d.ts +21 -0
  37. package/build/oauth/validate-key.d.ts.map +1 -0
  38. package/build/oauth/validate-key.js +61 -0
  39. package/build/request-key.d.ts +9 -0
  40. package/build/request-key.d.ts.map +1 -0
  41. package/build/request-key.js +24 -0
  42. package/build/server.d.ts +1 -1
  43. package/build/server.d.ts.map +1 -1
  44. package/build/server.js +151 -5
  45. package/package.json +2 -1
@@ -0,0 +1,606 @@
1
+ import { createClient } from "redis";
2
+ import { ACCESS_TOKEN_PREFIX, REFRESH_TOKEN_PREFIX, decryptSecret, encryptSecret, encryptionKey, positiveInt, randomToken, sha256, } from "./crypto.js";
3
+ import { isProductionHost, OAuthConfigError } from "./errors.js";
4
+ import { resourcesMatch } from "./metadata.js";
5
+ export { OAuthConfigError, isProductionHost };
6
+ const PREFIX = "desearch:oauth:";
7
+ const FAMILY_PREFIX = PREFIX + "family:";
8
+ const REVOKED_PREFIX = PREFIX + "family-revoked:";
9
+ export function clientTtlSec() {
10
+ return positiveInt(process.env.OAUTH_CLIENT_TTL_SEC, 60 * 60 * 24 * 90, 3600, 60 * 60 * 24 * 365 * 5);
11
+ }
12
+ export function accessTtlSec() {
13
+ return positiveInt(process.env.OAUTH_ACCESS_TTL_SEC, 3600, 60, 60 * 60 * 24);
14
+ }
15
+ export function refreshTtlSec() {
16
+ return positiveInt(process.env.OAUTH_REFRESH_TTL_SEC, 60 * 60 * 24 * 30, 300, 60 * 60 * 24 * 90);
17
+ }
18
+ export function codeTtlSec() {
19
+ return positiveInt(process.env.OAUTH_CODE_TTL_SEC, 300, 30, 600);
20
+ }
21
+ export class KvOAuthStore {
22
+ kv;
23
+ constructor(kv) {
24
+ this.kv = kv;
25
+ }
26
+ async saveClient(record) {
27
+ await this.kv.set(PREFIX + "client:" + record.clientId, JSON.stringify(record), clientTtlSec());
28
+ }
29
+ async getClient(clientId) {
30
+ return readJson(await this.kv.get(PREFIX + "client:" + clientId));
31
+ }
32
+ /**
33
+ * Per-subject fixed window. `bucket` separates registration from key checks.
34
+ * The subject is hashed so the stored key is not the raw address.
35
+ */
36
+ async consumeRateLimit(bucket, subject, limit, windowSec) {
37
+ const now = Date.now();
38
+ const windowMs = windowSec * 1000;
39
+ const windowId = Math.floor(now / windowMs);
40
+ const retryAfterSec = Math.max(1, Math.ceil(((windowId + 1) * windowMs - now) / 1000));
41
+ const key = `${PREFIX}rl:${bucket}:${sha256(subject)}:${windowId}`;
42
+ const count = await this.kv.increment(key, windowSec);
43
+ return { allowed: count <= limit, retryAfterSec };
44
+ }
45
+ async saveCode(code, record) {
46
+ await this.kv.set(PREFIX + "code:" + sha256(code), JSON.stringify(record), codeTtlSec());
47
+ }
48
+ async consumeCode(code) {
49
+ const hash = sha256(code);
50
+ const result = await this.kv.consumeAuthCode(PREFIX + "code:" + hash, PREFIX + "code-used:" + hash, Date.now(), refreshTtlSec());
51
+ if (result.status === "ok") {
52
+ const record = readJson(result.recordJson ?? null);
53
+ if (!record) {
54
+ return { ok: false };
55
+ }
56
+ return { ok: true, record };
57
+ }
58
+ if (result.status === "replay" && result.familyId) {
59
+ await this.revokeFamily(result.familyId);
60
+ }
61
+ return { ok: false };
62
+ }
63
+ async commitIssuedCode(code, familyId) {
64
+ const result = await this.kv.commitAuthCode(PREFIX + "code-used:" + sha256(code), familyId, refreshTtlSec());
65
+ return result === "committed";
66
+ }
67
+ async saveAccess(token, record) {
68
+ const key = PREFIX + "access:" + sha256(token);
69
+ await this.kv.set(key, JSON.stringify(record), accessTtlSec());
70
+ await this.remember(record.familyId, "accessKeys", key);
71
+ }
72
+ async getAccess(token) {
73
+ const key = PREFIX + "access:" + sha256(token);
74
+ const record = readJson(await this.kv.get(key));
75
+ if (!record) {
76
+ return null;
77
+ }
78
+ if (record.expiresAt <= Date.now()) {
79
+ await this.kv.del(key);
80
+ return null;
81
+ }
82
+ return record;
83
+ }
84
+ async saveRefresh(token, record) {
85
+ const key = PREFIX + "refresh:" + sha256(token);
86
+ await this.kv.set(key, JSON.stringify(record), refreshTtlSec());
87
+ await this.remember(record.familyId, "refreshKeys", key);
88
+ }
89
+ /**
90
+ * Rotate a refresh token. The claim, reuse detection, and family revoke
91
+ * flag are one atomic step (in-process for memory, one Lua script for Redis)
92
+ * so two overlapping presentations cannot both mint a new grant.
93
+ */
94
+ async rotateRefresh(token, options) {
95
+ const hash = sha256(token);
96
+ const claimed = await this.kv.claimRefresh({
97
+ refreshKey: PREFIX + "refresh:" + hash,
98
+ tombstoneKey: PREFIX + "refresh-used:" + hash,
99
+ now: Date.now(),
100
+ expectedClientId: options.clientId,
101
+ canonicalResource: options.canonicalResource,
102
+ presentedResource: options.presentedResource ?? "",
103
+ tombTtlSec: refreshTtlSec(),
104
+ familyKeyPrefix: FAMILY_PREFIX,
105
+ revokedKeyPrefix: REVOKED_PREFIX,
106
+ });
107
+ if (claimed.status === "resource_mismatch") {
108
+ return {
109
+ ok: false,
110
+ error: "invalid_target",
111
+ description: claimed.resourceReason === "presented"
112
+ ? "The resource does not match the refresh token."
113
+ : "The refresh token was issued for a different resource.",
114
+ };
115
+ }
116
+ if (claimed.status === "reused" && claimed.familyId) {
117
+ await this.revokeFamily(claimed.familyId);
118
+ }
119
+ if (claimed.status !== "ok" || !claimed.recordJson) {
120
+ return {
121
+ ok: false,
122
+ error: "invalid_grant",
123
+ description: "The refresh token is invalid or was already used.",
124
+ };
125
+ }
126
+ const record = readJson(claimed.recordJson);
127
+ if (!record) {
128
+ return {
129
+ ok: false,
130
+ error: "invalid_grant",
131
+ description: "The refresh token is invalid or was already used.",
132
+ };
133
+ }
134
+ const accessToken = randomToken(ACCESS_TOKEN_PREFIX, 32);
135
+ const refreshToken = randomToken(REFRESH_TOKEN_PREFIX, 32);
136
+ const accessExpires = Date.now() + accessTtlSec() * 1000;
137
+ const refreshExpires = Date.now() + refreshTtlSec() * 1000;
138
+ await this.saveAccess(accessToken, {
139
+ clientId: record.clientId,
140
+ resource: record.resource,
141
+ scope: record.scope,
142
+ apiKeyCiphertext: record.apiKeyCiphertext,
143
+ expiresAt: accessExpires,
144
+ familyId: record.familyId,
145
+ });
146
+ await this.saveRefresh(refreshToken, {
147
+ clientId: record.clientId,
148
+ resource: record.resource,
149
+ scope: record.scope,
150
+ apiKeyCiphertext: record.apiKeyCiphertext,
151
+ expiresAt: refreshExpires,
152
+ familyId: record.familyId,
153
+ });
154
+ if (await this.isFamilyRevoked(record.familyId)) {
155
+ await this.revokeFamily(record.familyId);
156
+ return {
157
+ ok: false,
158
+ error: "invalid_grant",
159
+ description: "The refresh token is invalid or was already used.",
160
+ };
161
+ }
162
+ return {
163
+ ok: true,
164
+ accessToken,
165
+ refreshToken,
166
+ scope: record.scope,
167
+ expiresIn: accessTtlSec(),
168
+ };
169
+ }
170
+ async isFamilyRevoked(familyId) {
171
+ return (await this.kv.get(REVOKED_PREFIX + familyId)) === "1";
172
+ }
173
+ readApiKey(ciphertext) {
174
+ try {
175
+ return decryptSecret(ciphertext);
176
+ }
177
+ catch (error) {
178
+ console.error(`OAuth token decrypt failed: ${error instanceof Error ? error.message : "unknown error"}`);
179
+ return null;
180
+ }
181
+ }
182
+ sealApiKey(apiKey) {
183
+ return encryptSecret(apiKey);
184
+ }
185
+ async remember(familyId, field, key) {
186
+ const familyKey = FAMILY_PREFIX + familyId;
187
+ const family = readJson(await this.kv.get(familyKey)) ?? {
188
+ accessKeys: [],
189
+ refreshKeys: [],
190
+ };
191
+ family[field].push(key);
192
+ await this.kv.set(familyKey, JSON.stringify(family), refreshTtlSec());
193
+ }
194
+ async revokeFamily(familyId) {
195
+ await this.kv.set(REVOKED_PREFIX + familyId, "1", refreshTtlSec());
196
+ const familyKey = FAMILY_PREFIX + familyId;
197
+ const family = readJson(await this.kv.get(familyKey));
198
+ if (!family) {
199
+ return;
200
+ }
201
+ await Promise.all([
202
+ ...family.accessKeys.map((key) => this.kv.del(key)),
203
+ ...family.refreshKeys.map((key) => this.kv.del(key)),
204
+ this.kv.del(familyKey),
205
+ ]);
206
+ }
207
+ }
208
+ function readJson(raw) {
209
+ if (!raw) {
210
+ return null;
211
+ }
212
+ try {
213
+ return JSON.parse(raw);
214
+ }
215
+ catch {
216
+ return null;
217
+ }
218
+ }
219
+ class MemoryKv {
220
+ rows = new Map();
221
+ async get(key) {
222
+ return this.getSync(key);
223
+ }
224
+ async getDel(key) {
225
+ const value = this.getSync(key);
226
+ this.rows.delete(key);
227
+ return value;
228
+ }
229
+ async set(key, value, ttlSec) {
230
+ this.setSync(key, value, ttlSec);
231
+ }
232
+ async del(key) {
233
+ this.rows.delete(key);
234
+ }
235
+ async increment(key, ttlSec) {
236
+ const now = Date.now();
237
+ const row = this.rows.get(key);
238
+ if (!row || row.expiresAt <= now) {
239
+ this.rows.set(key, { value: "1", expiresAt: now + ttlSec * 1000 });
240
+ return 1;
241
+ }
242
+ const next = (Number(row.value) || 0) + 1;
243
+ row.value = String(next);
244
+ return next;
245
+ }
246
+ async consumeAuthCode(codeKey, tombstoneKey, now, tombTtlSec) {
247
+ const raw = this.getSync(codeKey);
248
+ if (!raw) {
249
+ const tomb = this.getSync(tombstoneKey);
250
+ if (!tomb) {
251
+ return { status: "missing" };
252
+ }
253
+ if (tomb === "pending" || tomb === "replayed") {
254
+ this.setSync(tombstoneKey, "replayed", tombTtlSec);
255
+ return { status: "replay" };
256
+ }
257
+ this.revokeFamilySync(tomb);
258
+ return { status: "replay", familyId: tomb };
259
+ }
260
+ const record = readJson(raw);
261
+ if (!record || record.expiresAt <= now) {
262
+ this.rows.delete(codeKey);
263
+ return { status: "missing" };
264
+ }
265
+ this.rows.delete(codeKey);
266
+ this.setSync(tombstoneKey, "pending", tombTtlSec);
267
+ return { status: "ok", recordJson: raw };
268
+ }
269
+ async commitAuthCode(tombstoneKey, familyId, tombTtlSec) {
270
+ if (this.getSync(tombstoneKey) === "replayed") {
271
+ return "replayed";
272
+ }
273
+ this.setSync(tombstoneKey, familyId, tombTtlSec);
274
+ return "committed";
275
+ }
276
+ async claimRefresh(input) {
277
+ const raw = this.getSync(input.refreshKey);
278
+ if (!raw) {
279
+ const familyId = this.getSync(input.tombstoneKey);
280
+ if (familyId) {
281
+ this.revokeFamilySync(familyId);
282
+ return { status: "reused", familyId };
283
+ }
284
+ return { status: "invalid" };
285
+ }
286
+ const record = readJson(raw);
287
+ if (!record || record.expiresAt <= input.now) {
288
+ this.rows.delete(input.refreshKey);
289
+ return { status: "invalid" };
290
+ }
291
+ if (record.clientId !== input.expectedClientId) {
292
+ return { status: "client_mismatch" };
293
+ }
294
+ if (input.presentedResource && !resourcesMatch(record.resource, input.presentedResource)) {
295
+ return { status: "resource_mismatch", resourceReason: "presented" };
296
+ }
297
+ if (!resourcesMatch(record.resource, input.canonicalResource)) {
298
+ return { status: "resource_mismatch", resourceReason: "canonical" };
299
+ }
300
+ if (record.replacedBy) {
301
+ this.setSync(input.tombstoneKey, record.familyId, input.tombTtlSec);
302
+ this.revokeFamilySync(record.familyId);
303
+ return { status: "reused", familyId: record.familyId };
304
+ }
305
+ const remainingMs = (this.rows.get(input.refreshKey)?.expiresAt ?? input.now) - input.now;
306
+ record.replacedBy = "claimed";
307
+ this.rows.set(input.refreshKey, {
308
+ value: JSON.stringify(record),
309
+ expiresAt: input.now + Math.max(1000, remainingMs),
310
+ });
311
+ this.setSync(input.tombstoneKey, record.familyId, input.tombTtlSec);
312
+ return { status: "ok", recordJson: raw };
313
+ }
314
+ getSync(key) {
315
+ const row = this.rows.get(key);
316
+ if (!row) {
317
+ return null;
318
+ }
319
+ if (row.expiresAt <= Date.now()) {
320
+ this.rows.delete(key);
321
+ return null;
322
+ }
323
+ return row.value;
324
+ }
325
+ setSync(key, value, ttlSec) {
326
+ this.rows.set(key, { value, expiresAt: Date.now() + ttlSec * 1000 });
327
+ }
328
+ revokeFamilySync(familyId) {
329
+ this.setSync(REVOKED_PREFIX + familyId, "1", refreshTtlSec());
330
+ const familyKey = FAMILY_PREFIX + familyId;
331
+ const family = readJson(this.getSync(familyKey));
332
+ if (!family) {
333
+ return;
334
+ }
335
+ for (const key of family.accessKeys) {
336
+ this.rows.delete(key);
337
+ }
338
+ for (const key of family.refreshKeys) {
339
+ this.rows.delete(key);
340
+ }
341
+ this.rows.delete(familyKey);
342
+ }
343
+ }
344
+ const CONSUME_CODE_SCRIPT = `
345
+ local raw = redis.call('GET', KEYS[1])
346
+ local now = tonumber(ARGV[1])
347
+ local ttl = tonumber(ARGV[2])
348
+ if not raw then
349
+ local tomb = redis.call('GET', KEYS[2])
350
+ if not tomb or tomb == '' then
351
+ return cjson.encode({ status = 'missing' })
352
+ end
353
+ if tomb == 'pending' or tomb == 'replayed' then
354
+ redis.call('SET', KEYS[2], 'replayed', 'EX', ttl)
355
+ return cjson.encode({ status = 'replay' })
356
+ end
357
+ local revokedKey = ARGV[3] .. tomb
358
+ local familyKey = ARGV[4] .. tomb
359
+ redis.call('SET', revokedKey, '1', 'EX', ttl)
360
+ local familyRaw = redis.call('GET', familyKey)
361
+ if familyRaw then
362
+ local family = cjson.decode(familyRaw)
363
+ for _, key in ipairs(family.accessKeys or {}) do redis.call('DEL', key) end
364
+ for _, key in ipairs(family.refreshKeys or {}) do redis.call('DEL', key) end
365
+ redis.call('DEL', familyKey)
366
+ end
367
+ return cjson.encode({ status = 'replay', familyId = tomb })
368
+ end
369
+ local ok, record = pcall(cjson.decode, raw)
370
+ if not ok or type(record) ~= 'table' or tonumber(record.expiresAt or 0) <= now then
371
+ redis.call('DEL', KEYS[1])
372
+ return cjson.encode({ status = 'missing' })
373
+ end
374
+ redis.call('DEL', KEYS[1])
375
+ redis.call('SET', KEYS[2], 'pending', 'EX', ttl)
376
+ return cjson.encode({ status = 'ok', record = raw })
377
+ `;
378
+ const INCREMENT_SCRIPT = `
379
+ local n = redis.call('INCR', KEYS[1])
380
+ if n == 1 then
381
+ redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
382
+ else
383
+ local ttl = redis.call('TTL', KEYS[1])
384
+ if ttl < 0 then
385
+ redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
386
+ end
387
+ end
388
+ return n
389
+ `;
390
+ const COMMIT_CODE_SCRIPT = `
391
+ local tomb = redis.call('GET', KEYS[1])
392
+ if tomb == 'replayed' then
393
+ return 'replayed'
394
+ end
395
+ redis.call('SET', KEYS[1], ARGV[1], 'EX', tonumber(ARGV[2]))
396
+ return 'committed'
397
+ `;
398
+ const CLAIM_REFRESH_SCRIPT = `
399
+ local function norm(value)
400
+ if type(value) ~= 'string' then return '' end
401
+ local scheme, rest = string.match(value, '^([%a][%w+.-]*)://(.*)$')
402
+ if not scheme then
403
+ return (string.gsub(value, '/+$', ''))
404
+ end
405
+ local host, path = string.match(rest, '^([^/]+)(.*)$')
406
+ path = path or ''
407
+ path = string.gsub(path, '[?#].*$', '')
408
+ path = string.gsub(path, '/+$', '')
409
+ return string.lower(scheme) .. '://' .. string.lower(host or '') .. path
410
+ end
411
+
412
+ local function revoke(familyId, ttl, revokedPrefix, familyPrefix)
413
+ if not familyId or familyId == '' then return end
414
+ redis.call('SET', revokedPrefix .. familyId, '1', 'EX', ttl)
415
+ local familyRaw = redis.call('GET', familyPrefix .. familyId)
416
+ if not familyRaw then return end
417
+ local family = cjson.decode(familyRaw)
418
+ for _, key in ipairs(family.accessKeys or {}) do redis.call('DEL', key) end
419
+ for _, key in ipairs(family.refreshKeys or {}) do redis.call('DEL', key) end
420
+ redis.call('DEL', familyPrefix .. familyId)
421
+ end
422
+
423
+ local raw = redis.call('GET', KEYS[1])
424
+ local now = tonumber(ARGV[1])
425
+ local ttl = tonumber(ARGV[6])
426
+ if not raw then
427
+ local familyId = redis.call('GET', KEYS[2])
428
+ if familyId and familyId ~= '' then
429
+ revoke(familyId, ttl, ARGV[7], ARGV[8])
430
+ return cjson.encode({ status = 'reused', familyId = familyId })
431
+ end
432
+ return cjson.encode({ status = 'invalid' })
433
+ end
434
+ local ok, record = pcall(cjson.decode, raw)
435
+ if not ok or type(record) ~= 'table' or tonumber(record.expiresAt or 0) <= now then
436
+ redis.call('DEL', KEYS[1])
437
+ return cjson.encode({ status = 'invalid' })
438
+ end
439
+ if record.clientId ~= ARGV[2] then
440
+ return cjson.encode({ status = 'client_mismatch' })
441
+ end
442
+ if ARGV[4] ~= '' and norm(record.resource) ~= norm(ARGV[4]) then
443
+ return cjson.encode({ status = 'resource_mismatch', resourceReason = 'presented' })
444
+ end
445
+ if norm(record.resource) ~= norm(ARGV[3]) then
446
+ return cjson.encode({ status = 'resource_mismatch', resourceReason = 'canonical' })
447
+ end
448
+ if record.replacedBy and record.replacedBy ~= '' and record.replacedBy ~= cjson.null then
449
+ redis.call('SET', KEYS[2], record.familyId, 'EX', ttl)
450
+ revoke(record.familyId, ttl, ARGV[7], ARGV[8])
451
+ return cjson.encode({ status = 'reused', familyId = record.familyId })
452
+ end
453
+ local pttl = redis.call('PTTL', KEYS[1])
454
+ if pttl < 1 then pttl = 1000 end
455
+ record.replacedBy = 'claimed'
456
+ redis.call('SET', KEYS[1], cjson.encode(record), 'PX', pttl)
457
+ redis.call('SET', KEYS[2], record.familyId, 'EX', ttl)
458
+ return cjson.encode({ status = 'ok', record = raw })
459
+ `;
460
+ class RedisKv {
461
+ client;
462
+ constructor(client) {
463
+ this.client = client;
464
+ }
465
+ async get(key) {
466
+ return this.client.get(key);
467
+ }
468
+ async getDel(key) {
469
+ return this.client.getDel(key);
470
+ }
471
+ async set(key, value, ttlSec) {
472
+ await this.client.set(key, value, { EX: ttlSec });
473
+ }
474
+ async del(key) {
475
+ await this.client.del(key);
476
+ }
477
+ async increment(key, ttlSec) {
478
+ const reply = await this.client.eval(INCREMENT_SCRIPT, {
479
+ keys: [key],
480
+ arguments: [String(ttlSec)],
481
+ });
482
+ const count = typeof reply === "number" ? reply : Number(redisText(reply));
483
+ if (!Number.isSafeInteger(count) || count < 1) {
484
+ throw new Error("Unexpected Redis rate limit reply");
485
+ }
486
+ return count;
487
+ }
488
+ async consumeAuthCode(codeKey, tombstoneKey, now, tombTtlSec) {
489
+ const reply = await this.client.eval(CONSUME_CODE_SCRIPT, {
490
+ keys: [codeKey, tombstoneKey],
491
+ arguments: [String(now), String(tombTtlSec), REVOKED_PREFIX, FAMILY_PREFIX],
492
+ });
493
+ const parsed = parseScript(reply, { status: "missing" });
494
+ return { status: parsed.status, recordJson: parsed.record, familyId: parsed.familyId };
495
+ }
496
+ async commitAuthCode(tombstoneKey, familyId, tombTtlSec) {
497
+ const reply = await this.client.eval(COMMIT_CODE_SCRIPT, {
498
+ keys: [tombstoneKey],
499
+ arguments: [familyId, String(tombTtlSec)],
500
+ });
501
+ const text = redisText(reply);
502
+ return text === "replayed" ? "replayed" : "committed";
503
+ }
504
+ async claimRefresh(input) {
505
+ const reply = await this.client.eval(CLAIM_REFRESH_SCRIPT, {
506
+ keys: [input.refreshKey, input.tombstoneKey],
507
+ arguments: [
508
+ String(input.now),
509
+ input.expectedClientId,
510
+ input.canonicalResource,
511
+ input.presentedResource,
512
+ input.familyKeyPrefix,
513
+ String(input.tombTtlSec),
514
+ input.revokedKeyPrefix,
515
+ input.familyKeyPrefix,
516
+ ],
517
+ });
518
+ const parsed = parseScript(reply, { status: "invalid" });
519
+ return {
520
+ status: parsed.status,
521
+ recordJson: parsed.record,
522
+ familyId: parsed.familyId,
523
+ resourceReason: parsed.resourceReason,
524
+ };
525
+ }
526
+ }
527
+ function redisText(value) {
528
+ if (typeof value === "string") {
529
+ return value;
530
+ }
531
+ if (value instanceof Uint8Array) {
532
+ return new TextDecoder().decode(value);
533
+ }
534
+ throw new Error("Unexpected Redis script reply");
535
+ }
536
+ function parseScript(value, fallback) {
537
+ try {
538
+ return JSON.parse(redisText(value));
539
+ }
540
+ catch {
541
+ return fallback;
542
+ }
543
+ }
544
+ const globalStore = globalThis;
545
+ let redisClientPromise;
546
+ async function redisClient() {
547
+ if (redisClientPromise) {
548
+ return redisClientPromise;
549
+ }
550
+ const url = process.env.REDIS_URL?.trim();
551
+ if (!url) {
552
+ throw new OAuthConfigError("REDIS_URL is required when OAUTH_STORE=redis");
553
+ }
554
+ const client = createClient({ url });
555
+ client.on("error", (error) => {
556
+ console.error(`OAuth Redis error: ${error.message}`);
557
+ });
558
+ redisClientPromise = client.connect().then(() => client);
559
+ return redisClientPromise;
560
+ }
561
+ export async function getOAuthStore() {
562
+ const backend = (process.env.OAUTH_STORE ?? "memory").trim().toLowerCase();
563
+ if (isProductionHost() && backend !== "redis") {
564
+ throw new OAuthConfigError("OAUTH_STORE must be redis in production");
565
+ }
566
+ if (globalStore.__desearchOAuthStore) {
567
+ return globalStore.__desearchOAuthStore;
568
+ }
569
+ if (backend === "memory" || backend === "") {
570
+ globalStore.__desearchOAuthStore = new KvOAuthStore(new MemoryKv());
571
+ return globalStore.__desearchOAuthStore;
572
+ }
573
+ if (backend === "redis") {
574
+ if (!process.env.REDIS_URL?.trim()) {
575
+ throw new OAuthConfigError("REDIS_URL is required when OAUTH_STORE=redis");
576
+ }
577
+ try {
578
+ encryptionKey({ requireConfigured: true });
579
+ }
580
+ catch (error) {
581
+ throw new OAuthConfigError(error instanceof Error ? error.message : "OAUTH_ENCRYPTION_KEY is required when OAUTH_STORE=redis");
582
+ }
583
+ const client = await redisClient();
584
+ globalStore.__desearchOAuthStore = new KvOAuthStore(new RedisKv(client));
585
+ return globalStore.__desearchOAuthStore;
586
+ }
587
+ throw new OAuthConfigError("OAUTH_STORE must be memory or redis");
588
+ }
589
+ export function resetOAuthForTests() {
590
+ if (process.env.NODE_ENV === "production") {
591
+ throw new Error("OAuth store reset is disabled");
592
+ }
593
+ delete globalStore.__desearchOAuthStore;
594
+ }
595
+ export function memoryStoreForTests() {
596
+ if (process.env.NODE_ENV === "production") {
597
+ throw new Error("OAuth store reset is disabled");
598
+ }
599
+ return new KvOAuthStore(new MemoryKv());
600
+ }
601
+ export function redisKvForTests(client) {
602
+ if (process.env.NODE_ENV === "production") {
603
+ throw new Error("OAuth store reset is disabled");
604
+ }
605
+ return new RedisKv(client);
606
+ }
@@ -0,0 +1,21 @@
1
+ export interface KeyCheckOk {
2
+ ok: true;
3
+ }
4
+ export interface KeyCheckFail {
5
+ ok: false;
6
+ message: string;
7
+ }
8
+ export type KeyCheck = KeyCheckOk | KeyCheckFail;
9
+ export declare function setApiKeyCheckerForTests(checker: ((apiKey: string) => Promise<KeyCheck>) | null): void;
10
+ /**
11
+ * Confirm the key with Desearch before an authorization code is issued.
12
+ * `GET /twitter/trends?woeid=1&count=1` asks for fewer trends than the route
13
+ * allows, so a real key is authenticated and then rejected as invalid input
14
+ * (HTTP 422) instead of running a full trends query. Only 422 counts as valid.
15
+ * Invalid keys return 401 or 403. Any other status, including 2xx, is an error:
16
+ * the trends route may have changed, and treating success as "valid" would
17
+ * accept a key the check never authenticated.
18
+ */
19
+ export declare function validateDesearchApiKey(apiKey: string, fetchImpl?: typeof fetch): Promise<KeyCheck>;
20
+ export declare function checkDesearchApiKey(apiKey: string): Promise<KeyCheck>;
21
+ //# sourceMappingURL=validate-key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate-key.d.ts","sourceRoot":"","sources":["../../oauth/validate-key.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACvB,EAAE,EAAE,IAAI,CAAC;CACZ;AAED,MAAM,WAAW,YAAY;IACzB,EAAE,EAAE,KAAK,CAAC;IACV,OAAO,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,MAAM,QAAQ,GAAG,UAAU,GAAG,YAAY,CAAC;AAQjD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC,GAAG,IAAI,GAAG,IAAI,CAKtG;AAED;;;;;;;;GAQG;AACH,wBAAsB,sBAAsB,CACxC,MAAM,EAAE,MAAM,EACd,SAAS,GAAE,OAAO,KAAa,GAChC,OAAO,CAAC,QAAQ,CAAC,CAoCnB;AAED,wBAAsB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAK3E"}
@@ -0,0 +1,61 @@
1
+ const INVALID_MESSAGE = "That API key was rejected. Copy the full key from the Desearch console and try again.";
2
+ const UNAVAILABLE_MESSAGE = "Could not verify the API key. Try again in a moment.";
3
+ let checkerOverride = null;
4
+ export function setApiKeyCheckerForTests(checker) {
5
+ if (process.env.NODE_ENV === "production") {
6
+ throw new Error("API key check overrides are disabled");
7
+ }
8
+ checkerOverride = checker;
9
+ }
10
+ /**
11
+ * Confirm the key with Desearch before an authorization code is issued.
12
+ * `GET /twitter/trends?woeid=1&count=1` asks for fewer trends than the route
13
+ * allows, so a real key is authenticated and then rejected as invalid input
14
+ * (HTTP 422) instead of running a full trends query. Only 422 counts as valid.
15
+ * Invalid keys return 401 or 403. Any other status, including 2xx, is an error:
16
+ * the trends route may have changed, and treating success as "valid" would
17
+ * accept a key the check never authenticated.
18
+ */
19
+ export async function validateDesearchApiKey(apiKey, fetchImpl = fetch) {
20
+ const trimmed = apiKey.trim();
21
+ if (!trimmed || /\s/.test(trimmed) || trimmed.length > 200) {
22
+ return { ok: false, message: INVALID_MESSAGE };
23
+ }
24
+ const base = (process.env.DESEARCH_API_BASE ?? "https://api.desearch.ai").replace(/\/+$/, "");
25
+ const url = new URL("/twitter/trends", base);
26
+ url.searchParams.set("woeid", "1");
27
+ url.searchParams.set("count", "1");
28
+ const controller = new AbortController();
29
+ const timer = setTimeout(() => controller.abort(), 8000);
30
+ try {
31
+ const response = await fetchImpl(url, {
32
+ method: "GET",
33
+ headers: {
34
+ Authorization: trimmed,
35
+ Accept: "application/json",
36
+ },
37
+ signal: controller.signal,
38
+ });
39
+ await response.arrayBuffer().catch(() => undefined);
40
+ if (response.status === 401 || response.status === 403) {
41
+ return { ok: false, message: INVALID_MESSAGE };
42
+ }
43
+ if (response.status === 422) {
44
+ return { ok: true };
45
+ }
46
+ console.warn(`Desearch API key check returned unexpected HTTP ${response.status}`);
47
+ return { ok: false, message: UNAVAILABLE_MESSAGE };
48
+ }
49
+ catch {
50
+ return { ok: false, message: UNAVAILABLE_MESSAGE };
51
+ }
52
+ finally {
53
+ clearTimeout(timer);
54
+ }
55
+ }
56
+ export async function checkDesearchApiKey(apiKey) {
57
+ if (checkerOverride) {
58
+ return checkerOverride(apiKey);
59
+ }
60
+ return validateDesearchApiKey(apiKey);
61
+ }