keryx 0.46.0 → 0.48.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.
package/README.md CHANGED
@@ -123,7 +123,7 @@ bun install
123
123
  bun dev
124
124
  ```
125
125
 
126
- Requires Bun, PostgreSQL, and Redis. See the [Getting Started guide](https://keryxjs.com/guide/) for full setup instructions.
126
+ Requires Bun, PostgreSQL, and Redis. See the [Getting Started guide](https://keryxjs.com/guide/) for full setup instructions (including running without Postgres or Redis for quick prototypes).
127
127
 
128
128
  ### Developing the framework itself
129
129
 
package/actions/status.ts CHANGED
@@ -7,7 +7,7 @@ import packageJSON from "../package.json";
7
7
  export class Status implements Action {
8
8
  name = "status";
9
9
  description =
10
- "Returns server health and runtime information including the server name, process ID, package version, uptime in milliseconds, memory consumption in MB, and dependency health checks for the database and Redis. Does not require authentication.";
10
+ "Returns server health and runtime information including the server name, process ID, package version, uptime in milliseconds, memory consumption in MB, and dependency health checks for the database and Redis. A check is `null` when that dependency is disabled (e.g. no `DATABASE_URL`), and disabled checks do not affect `healthy`. Does not require authentication.";
11
11
  inputs = z.object({});
12
12
  web = { route: "/status", method: HTTP_METHOD.GET };
13
13
  tracing = false;
@@ -16,13 +16,15 @@ export class Status implements Action {
16
16
  const consumedMemoryMB =
17
17
  Math.round((process.memoryUsage().heapUsed / 1024 / 1024) * 100) / 100;
18
18
 
19
- let databaseHealthy = false;
20
- try {
21
- if (api.db?.db) {
19
+ // `null` = the database is disabled, so it is not part of the health verdict.
20
+ let databaseHealthy: boolean | null = null;
21
+ if (api.db?.enabled) {
22
+ databaseHealthy = false;
23
+ try {
22
24
  await api.db.db.execute(sql`SELECT NOW()`);
23
25
  databaseHealthy = true;
24
- }
25
- } catch {}
26
+ } catch {}
27
+ }
26
28
 
27
29
  let redisHealthy = false;
28
30
  try {
@@ -32,7 +34,7 @@ export class Status implements Action {
32
34
  }
33
35
  } catch {}
34
36
 
35
- const healthy = databaseHealthy && redisHealthy;
37
+ const healthy = databaseHealthy !== false && redisHealthy;
36
38
 
37
39
  return {
38
40
  name: api.process.name,
package/classes/Action.ts CHANGED
@@ -97,6 +97,15 @@ export type McpActionConfig = {
97
97
  * via `ui` implies a tool unless `tool` is explicitly `false`.
98
98
  */
99
99
  tool?: boolean;
100
+ /**
101
+ * Allow anonymous MCP clients to use this action. Only takes effect when the
102
+ * server runs with `MCP_AUTH_MODE=optional`: a client without a bearer token
103
+ * may then call this tool, read this resource or prompt, or load this MCP App
104
+ * UI. Anonymous calls to non-public actions get a 401 challenge so the client
105
+ * can authenticate. Has no effect in the default `required` mode, and never
106
+ * changes HTTP/WebSocket access — that is still governed by `middleware`.
107
+ */
108
+ public?: boolean;
100
109
  /** Tag as the OAuth login action */
101
110
  isLoginAction?: boolean;
102
111
  /** Tag as the OAuth signup action */
@@ -1,7 +1,8 @@
1
1
  import { loadFromEnvIfSet } from "../util/config";
2
2
 
3
3
  export const configDatabase = {
4
- connectionString: await loadFromEnvIfSet("DATABASE_URL", "x"),
4
+ /** Postgres connection URL. Empty (the default) or `"none"` runs without a database. */
5
+ connectionString: await loadFromEnvIfSet("DATABASE_URL", ""),
5
6
  autoMigrate: await loadFromEnvIfSet("DATABASE_AUTO_MIGRATE", true),
6
7
  pool: {
7
8
  max: await loadFromEnvIfSet("DATABASE_POOL_MAX", 10),
@@ -19,4 +19,14 @@ export const configRateLimit = {
19
19
  "RATE_LIMIT_OAUTH_REGISTER_WINDOW_MS",
20
20
  3_600_000,
21
21
  ),
22
+ /** Stricter limit on new anonymous MCP sessions (`initialize` without a token), per IP per window. */
23
+ mcpAnonymousInitLimit: await loadFromEnvIfSet(
24
+ "RATE_LIMIT_MCP_ANON_INIT_LIMIT",
25
+ 10,
26
+ ),
27
+ /** Window for the anonymous MCP session-creation rate limit (default: 1 minute). */
28
+ mcpAnonymousInitWindowMs: await loadFromEnvIfSet(
29
+ "RATE_LIMIT_MCP_ANON_INIT_WINDOW_MS",
30
+ 60_000,
31
+ ),
22
32
  };
@@ -4,6 +4,12 @@ import { loadFromEnvIfSet } from "../../util/config";
4
4
  export const configServerMcp = {
5
5
  enabled: await loadFromEnvIfSet("MCP_SERVER_ENABLED", false),
6
6
  route: await loadFromEnvIfSet("MCP_SERVER_ROUTE", "/mcp"),
7
+ // `"required"` (default): every MCP request must carry a valid OAuth bearer
8
+ // token. `"optional"`: requests without a token are served as anonymous
9
+ // sessions that may only use actions marked `mcp.public`; calling anything
10
+ // else returns a 401 challenge so the client can authenticate and upgrade
11
+ // the session. An invalid or expired token is always rejected with 401.
12
+ authMode: await loadFromEnvIfSet("MCP_AUTH_MODE", "required"),
7
13
  allowedOrigins: await loadFromEnvIfSet(
8
14
  "MCP_ALLOWED_ORIGINS",
9
15
  [
@@ -59,4 +65,11 @@ export const configServerMcp = {
59
65
  // registry is shared, any node in a cluster can serve any session until it
60
66
  // expires. Defaults to 24 hours.
61
67
  sessionTtl: await loadFromEnvIfSet("MCP_SESSION_TTL", 60 * 60 * 24),
68
+ // Idle TTL (seconds) for anonymous sessions (`authMode: "optional"`), kept
69
+ // shorter than `sessionTtl` so floods of throwaway sessions age out quickly.
70
+ // A session that upgrades to an authenticated one switches to `sessionTtl`.
71
+ anonymousSessionTtl: await loadFromEnvIfSet(
72
+ "MCP_ANONYMOUS_SESSION_TTL",
73
+ 60 * 60,
74
+ ),
62
75
  };
package/index.ts CHANGED
@@ -86,7 +86,7 @@ export {
86
86
  } from "./util/swaggerSchemaGenerator";
87
87
  export { toMarkdown } from "./util/toMarkdown";
88
88
  export type { DbOrTransaction, Transaction } from "./util/transaction";
89
- export { withTransaction } from "./util/transaction";
89
+ export { assertDatabaseEnabled, withTransaction } from "./util/transaction";
90
90
  export {
91
91
  isSecret,
92
92
  paginationInputs,
@@ -14,6 +14,7 @@ import { ErrorType, TypedError } from "../classes/TypedError";
14
14
  import { config } from "../config";
15
15
  import {
16
16
  formatConnectionStringForLogging,
17
+ isDatabaseDisabled,
17
18
  throwConnectionError,
18
19
  } from "../util/connectionString";
19
20
  import { globModuleExports } from "../util/glob";
@@ -72,6 +73,15 @@ declare module "keryx" {
72
73
  }
73
74
  }
74
75
 
76
+ /**
77
+ * Initializer that connects Drizzle ORM to Postgres, runs migrations, and exposes
78
+ * `api.db.db` (the Drizzle instance), `api.db.pool` and `api.db.schema`.
79
+ *
80
+ * An empty `DATABASE_URL` (or `"none"`) disables the database: nothing connects, no
81
+ * migrations run, `api.db.enabled` is `false`, and `api.db.db` / `api.db.pool` stay
82
+ * unset. Helpers that need a database (`withTransaction`, `TransactionMiddleware`,
83
+ * `zIdOrModel`) then throw a clear `TypedError` instead.
84
+ */
75
85
  export class DB extends Initializer {
76
86
  constructor() {
77
87
  super(namespace);
@@ -91,12 +101,27 @@ export class DB extends Initializer {
91
101
  generateMigrations: this.generateMigrations,
92
102
  clearDatabase: this.clearDatabase,
93
103
  schema,
104
+ /** `false` when `DATABASE_URL` is empty or `"none"` and no database is connected. */
105
+ enabled: false,
94
106
  },
95
107
  dbContainer,
96
108
  );
97
109
  }
98
110
 
99
111
  async start() {
112
+ if (isDatabaseDisabled(config.database.connectionString)) {
113
+ api.db.enabled = false;
114
+ logger.warn('database disabled (DATABASE_URL is empty or "none")');
115
+ const tableCount = Object.keys(api.db.schema).length;
116
+ if (tableCount > 0) {
117
+ logger.warn(
118
+ `${tableCount} table(s) found in ${SCHEMA_DIR}/ will not be available without a database`,
119
+ );
120
+ }
121
+ return;
122
+ }
123
+
124
+ api.db.enabled = true;
100
125
  api.db.pool = new Pool({
101
126
  connectionString: config.database.connectionString,
102
127
  ...config.database.pool,
@@ -216,6 +241,7 @@ export class DB extends Initializer {
216
241
 
217
242
  /**
218
243
  * Erase all the tables in the active database. Will fail on production environments.
244
+ * A no-op when the database is disabled.
219
245
  */
220
246
  async clearDatabase(restartIdentity = true, cascade = true) {
221
247
  if (Bun.env.NODE_ENV === "production") {
@@ -225,6 +251,8 @@ export class DB extends Initializer {
225
251
  });
226
252
  }
227
253
 
254
+ if (!api.db.enabled) return;
255
+
228
256
  const { rows } = await api.db.db.execute(
229
257
  sql`SELECT tablename FROM pg_tables WHERE schemaname = CURRENT_SCHEMA`,
230
258
  );
@@ -10,6 +10,10 @@ import { api, logger } from "../api";
10
10
  import { Initializer } from "../classes/Initializer";
11
11
  import { ErrorType, TypedError } from "../classes/TypedError";
12
12
  import { config } from "../config";
13
+ import {
14
+ checkRateLimit,
15
+ rateLimitExceededResponse,
16
+ } from "../middleware/rateLimit";
13
17
  import { ansi } from "../util/ansi";
14
18
  import {
15
19
  buildCorsHeaders,
@@ -20,10 +24,14 @@ import {
20
24
  import { resolveMcpAppUiResources } from "../util/mcpAppBundler";
21
25
  import {
22
26
  adoptMcpSession,
27
+ buildAnonymousMcpAuthInfo,
23
28
  createMcpServer,
29
+ findMcpTargetAction,
24
30
  forgetMcpSession,
25
31
  formatToolName,
26
32
  handleTransportRequest,
33
+ isAnonymousMcpAuth,
34
+ isMcpAccessAllowed,
27
35
  isMcpSessionAuthorizedForChannel,
28
36
  MCP_JSONRPC_ERROR,
29
37
  type McpAuthInfo,
@@ -35,6 +43,8 @@ import {
35
43
  refreshMcpSessionTtl,
36
44
  sanitizeSchemaForMcp,
37
45
  terminateMcpSession,
46
+ unlockMcpServer,
47
+ upgradeAnonymousMcpSession,
38
48
  validateJsonRpcPayload,
39
49
  writeMcpSessionRecord,
40
50
  } from "../util/mcpServer";
@@ -67,6 +77,83 @@ export type OnMcpDisconnectHook = (sessionId: string) => Promise<void> | void;
67
77
 
68
78
  const namespace = "mcp";
69
79
 
80
+ /** A live, node-local MCP session: its transport, owning client, and server. */
81
+ export type McpTransportEntry = {
82
+ transport: WebStandardStreamableHTTPServerTransport;
83
+ /** OAuth client id that owns the session (the anonymous sentinel if anonymous). */
84
+ clientId: string;
85
+ /** The `McpServer` connected to `transport`. */
86
+ mcpServer: McpServer;
87
+ /**
88
+ * `true` while the server still hides non-public entries from an anonymous
89
+ * session; cleared (via `unlockMcpServer`) once the session upgrades.
90
+ */
91
+ anonymous: boolean;
92
+ };
93
+
94
+ /** Whether a parsed POST body (single message or batch) contains an `initialize` request. */
95
+ function containsInitializeRequest(body: unknown): boolean {
96
+ return Array.isArray(body)
97
+ ? body.some(isInitializeRequest)
98
+ : isInitializeRequest(body);
99
+ }
100
+
101
+ /**
102
+ * Build the 401 response that sends an MCP client into the OAuth flow: a
103
+ * `WWW-Authenticate` challenge pointing at the protected resource metadata
104
+ * (RFC 9728). Returned when a token is missing (in `required` mode), invalid or
105
+ * expired (always), or when an anonymous request targets a protected action or
106
+ * an authenticated session (in `optional` mode).
107
+ */
108
+ function mcpAuthChallenge(
109
+ req: Request,
110
+ corsHeaders: Record<string, string>,
111
+ ): Response {
112
+ const origin = getExternalOrigin(req, new URL(req.url));
113
+ const resourceMetadataUrl = `${origin}/.well-known/oauth-protected-resource${config.server.mcp.route}`;
114
+ return mcpJsonResponse(
115
+ { error: "Authentication required" },
116
+ 401,
117
+ corsHeaders,
118
+ {
119
+ "WWW-Authenticate": `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp"`,
120
+ },
121
+ );
122
+ }
123
+
124
+ /**
125
+ * Rate-limit an anonymous MCP request by IP: every request counts against the
126
+ * unauthenticated limit, and a session-creating `initialize` also counts
127
+ * against the stricter anonymous-session limit.
128
+ *
129
+ * @returns A 429 response if a limit is exceeded, otherwise `undefined`.
130
+ */
131
+ async function checkAnonymousMcpRateLimit(
132
+ ip: string,
133
+ isInitialize: boolean,
134
+ corsHeaders: Record<string, string>,
135
+ ): Promise<Response | undefined> {
136
+ if (!config.rateLimit.enabled) return undefined;
137
+ const keyPrefix = config.rateLimit.keyPrefix;
138
+ const info = await checkRateLimit(`ip:${ip}`, false, {
139
+ keyPrefix: `${keyPrefix}:mcp-anon`,
140
+ });
141
+ if (info.retryAfter !== undefined) {
142
+ return rateLimitExceededResponse(info, corsHeaders);
143
+ }
144
+ if (isInitialize) {
145
+ const initInfo = await checkRateLimit(`ip:${ip}`, false, {
146
+ limit: config.rateLimit.mcpAnonymousInitLimit,
147
+ windowMs: config.rateLimit.mcpAnonymousInitWindowMs,
148
+ keyPrefix: `${keyPrefix}:mcp-anon-init`,
149
+ });
150
+ if (initInfo.retryAfter !== undefined) {
151
+ return rateLimitExceededResponse(initInfo, corsHeaders);
152
+ }
153
+ }
154
+ return undefined;
155
+ }
156
+
70
157
  /**
71
158
  * Resolve the protocol version an `initialize` request body (single message or
72
159
  * batch) actually negotiates, so it can be stored in the shared session registry
@@ -125,13 +212,7 @@ export class McpInitializer extends Initializer {
125
212
  // Per-session auth context, so a broadcast is delivered only to sessions
126
213
  // whose user is authorized for its channel (see sendNotification).
127
214
  const mcpServerAuth = new Map<McpServer, McpSessionAuth>();
128
- const transports = new Map<
129
- string,
130
- {
131
- transport: WebStandardStreamableHTTPServerTransport;
132
- clientId: string;
133
- }
134
- >();
215
+ const transports = new Map<string, McpTransportEntry>();
135
216
 
136
217
  // Deliver a PubSub broadcast to MCP sessions as a logging notification, but
137
218
  // ONLY to sessions whose user is authorized to subscribe to the broadcast's
@@ -264,35 +345,30 @@ export class McpInitializer extends Initializer {
264
345
  return new Response(null, { status: 405, headers: corsHeaders });
265
346
  }
266
347
 
267
- // Extract and verify Bearer token for auth
348
+ // Extract and verify the Bearer token. A token that is present but
349
+ // invalid or expired is always rejected with 401 (the spec requires it),
350
+ // never downgraded to anonymous access.
268
351
  let authInfo: McpAuthInfo | undefined;
269
352
  const authHeader = req.headers.get("authorization");
270
353
  if (authHeader?.startsWith("Bearer ")) {
271
354
  const token = authHeader.slice(7);
272
355
  const tokenData = await api.oauth.verifyAccessToken(token);
273
- if (tokenData) {
274
- authInfo = {
275
- token,
276
- clientId: tokenData.clientId,
277
- scopes: tokenData.scopes ?? [],
278
- extra: { userId: tokenData.userId, ip },
279
- };
280
- }
281
- }
282
-
283
- // Require authentication — return 401 so MCP clients initiate the OAuth flow
284
- if (!authInfo) {
285
- const origin = getExternalOrigin(req, new URL(req.url));
286
- const resourceMetadataUrl = `${origin}/.well-known/oauth-protected-resource${config.server.mcp.route}`;
287
- return mcpJsonResponse(
288
- { error: "Authentication required" },
289
- 401,
290
- corsHeaders,
291
- {
292
- "WWW-Authenticate": `Bearer resource_metadata="${resourceMetadataUrl}", scope="mcp"`,
293
- },
294
- );
356
+ if (!tokenData) return mcpAuthChallenge(req, corsHeaders);
357
+ authInfo = {
358
+ token,
359
+ clientId: tokenData.clientId,
360
+ scopes: tokenData.scopes ?? [],
361
+ extra: { userId: tokenData.userId, ip },
362
+ };
363
+ } else if (config.server.mcp.authMode === "optional") {
364
+ // No token, but anonymous access is enabled: serve the request as an
365
+ // anonymous session limited to `mcp.public` actions.
366
+ authInfo = buildAnonymousMcpAuthInfo(ip);
367
+ } else {
368
+ // Require authentication — return 401 so MCP clients initiate the OAuth flow
369
+ return mcpAuthChallenge(req, corsHeaders);
295
370
  }
371
+ const isAnonymous = isAnonymousMcpAuth(authInfo);
296
372
 
297
373
  const sessionId = req.headers.get("mcp-session-id");
298
374
 
@@ -326,15 +402,35 @@ export class McpInitializer extends Initializer {
326
402
  }
327
403
  }
328
404
 
405
+ if (isAnonymous) {
406
+ const limited = await checkAnonymousMcpRateLimit(
407
+ ip,
408
+ method === "POST" && !sessionId && containsInitializeRequest(body),
409
+ corsHeaders,
410
+ );
411
+ if (limited) return limited;
412
+
413
+ // Step-up: an anonymous call to a protected tool, prompt, or resource
414
+ // gets a 401 challenge before dispatch, so the client runs the OAuth
415
+ // flow and retries with a token (which upgrades the session below).
416
+ if (method === "POST") {
417
+ const messages = Array.isArray(body) ? body : [body];
418
+ const needsAuth = messages.some((message) => {
419
+ const action = findMcpTargetAction(message);
420
+ return (
421
+ action !== undefined && !isMcpAccessAllowed(action, authInfo)
422
+ );
423
+ });
424
+ if (needsAuth) return mcpAuthChallenge(req, corsHeaders);
425
+ }
426
+ }
427
+
329
428
  if (method === "POST" && !sessionId) {
330
429
  // Only an `initialize` request may create a new session. Any other
331
430
  // request without a session id is a protocol error → 400. We must gate
332
431
  // here rather than delegating, otherwise a non-initialize POST spins up
333
432
  // an McpServer that never initializes and leaks into `mcpServers`.
334
- const isInit = Array.isArray(body)
335
- ? body.some(isInitializeRequest)
336
- : isInitializeRequest(body);
337
- if (!isInit) {
433
+ if (!containsInitializeRequest(body)) {
338
434
  return mcpJsonResponse(
339
435
  { error: "Mcp-Session-Id header required" },
340
436
  400,
@@ -344,7 +440,7 @@ export class McpInitializer extends Initializer {
344
440
  const protocolVersion = negotiateInitProtocolVersion(body);
345
441
 
346
442
  // New session — create a new McpServer + transport
347
- const mcpServer = createMcpServer();
443
+ const mcpServer = createMcpServer({ anonymous: isAnonymous });
348
444
  mcpServers.push(mcpServer);
349
445
  // Capture the session's auth context so channel-broadcast delivery can
350
446
  // authorize this session (see sendNotification).
@@ -366,8 +462,14 @@ export class McpInitializer extends Initializer {
366
462
  clientId: sessionClientId,
367
463
  protocolVersion,
368
464
  createdAt: Date.now(),
465
+ ...(isAnonymous ? { anonymous: true } : {}),
466
+ });
467
+ transports.set(sid, {
468
+ transport,
469
+ clientId: sessionClientId,
470
+ mcpServer,
471
+ anonymous: isAnonymous,
369
472
  });
370
- transports.set(sid, { transport, clientId: sessionClientId });
371
473
  for (const hook of api.hooks.mcp.onConnectHooks) {
372
474
  await hook(sid);
373
475
  }
@@ -398,7 +500,7 @@ export class McpInitializer extends Initializer {
398
500
  // The shared Redis registry — not the node-local map — is the source of
399
501
  // truth for session existence and ownership, so a request that a load
400
502
  // balancer routes to any node resolves consistently.
401
- const record = await readMcpSessionRecord(sessionId);
503
+ let record = await readMcpSessionRecord(sessionId);
402
504
  if (!record) {
403
505
  // Unknown/expired session → 404 (the client's cue to re-`initialize`).
404
506
  // Evict any stale local transport so it can never bypass this gate.
@@ -414,7 +516,31 @@ export class McpInitializer extends Initializer {
414
516
  );
415
517
  }
416
518
 
417
- if (record.clientId !== authInfo.clientId) {
519
+ if (record.anonymous && !isAnonymous) {
520
+ // Upgrade: the first request on an anonymous session that carries a
521
+ // valid token rebinds the session to that token's client (with the
522
+ // authenticated TTL). The swap is atomic, so only one client can
523
+ // ever claim a given anonymous session.
524
+ const current = await upgradeAnonymousMcpSession(
525
+ sessionId,
526
+ record,
527
+ authInfo.clientId,
528
+ );
529
+ if (!current) {
530
+ return mcpJsonResponse(
531
+ { error: "Session not found" },
532
+ 404,
533
+ corsHeaders,
534
+ );
535
+ }
536
+ record = current;
537
+ }
538
+
539
+ if (isAnonymous && !record.anonymous) {
540
+ // Never downgrade an authenticated session to anonymous access.
541
+ return mcpAuthChallenge(req, corsHeaders);
542
+ }
543
+ if (!isAnonymous && record.clientId !== authInfo.clientId) {
418
544
  return mcpJsonResponse(
419
545
  { error: "Token does not match session" },
420
546
  403,
@@ -431,10 +557,26 @@ export class McpInitializer extends Initializer {
431
557
  record.clientId,
432
558
  record.protocolVersion,
433
559
  { userId: authInfo.extra?.userId, ip },
560
+ record.anonymous === true,
434
561
  );
435
562
  }
436
563
 
437
- await refreshMcpSessionTtl(sessionId);
564
+ // The session has been upgraded (here or on another node) but this
565
+ // node's server still hides protected entries: rebind its broadcast
566
+ // auth to the token's user and reveal everything.
567
+ const local = transports.get(sessionId);
568
+ if (local?.anonymous && !record.anonymous) {
569
+ local.anonymous = false;
570
+ local.clientId = record.clientId;
571
+ api.mcp.mcpServerAuth.set(local.mcpServer, {
572
+ clientId: record.clientId,
573
+ userId: authInfo.extra?.userId,
574
+ ip,
575
+ });
576
+ unlockMcpServer(local.mcpServer);
577
+ }
578
+
579
+ await refreshMcpSessionTtl(sessionId, record.anonymous);
438
580
 
439
581
  for (const hook of api.hooks.mcp.onMessageHooks) {
440
582
  await hook(sessionId);
@@ -1,7 +1,10 @@
1
1
  import { api } from "../api";
2
2
  import { Initializer } from "../classes/Initializer";
3
3
  import { config } from "../config";
4
- import { checkRateLimit } from "../middleware/rateLimit";
4
+ import {
5
+ checkRateLimit,
6
+ rateLimitExceededResponse,
7
+ } from "../middleware/rateLimit";
5
8
  import {
6
9
  appendHeaders,
7
10
  buildCorsHeaders,
@@ -121,22 +124,7 @@ export class OAuthInitializer extends Initializer {
121
124
  : undefined;
122
125
  const info = await checkRateLimit(`ip:${ip}`, false, overrides);
123
126
  if (info.retryAfter !== undefined) {
124
- return new Response(
125
- JSON.stringify({
126
- error: "rate_limit_exceeded",
127
- error_description: `Rate limit exceeded. Try again in ${info.retryAfter} seconds.`,
128
- }),
129
- {
130
- status: 429,
131
- headers: {
132
- "Content-Type": "application/json",
133
- "Retry-After": String(info.retryAfter),
134
- "X-RateLimit-Limit": String(info.limit),
135
- "X-RateLimit-Remaining": "0",
136
- "X-RateLimit-Reset": String(info.resetAt),
137
- },
138
- },
139
- );
127
+ return rateLimitExceededResponse(info);
140
128
  }
141
129
  }
142
130
 
@@ -5,6 +5,7 @@ import { config } from "../config";
5
5
 
6
6
  import {
7
7
  formatConnectionStringForLogging,
8
+ isMemoryRedis,
8
9
  throwConnectionError,
9
10
  } from "../util/connectionString";
10
11
 
@@ -21,6 +22,12 @@ declare module "keryx" {
21
22
  * Initializer that manages two Redis connections: `redis` for general commands and
22
23
  * `subscription` for PubSub. Both are created during `start()` and closed during `stop()`.
23
24
  * Exposes `api.redis.redis` and `api.redis.subscription` as ioredis `RedisClient` instances.
25
+ *
26
+ * When `REDIS_URL` uses the `memory:` scheme (e.g. `memory://`), both clients are
27
+ * in-process `ioredis-mock` instances that share one dataset instead of connections to
28
+ * a Redis server. Tasks, PubSub, presence, sessions and rate limiting all keep working,
29
+ * but state lives only in this process: it is not shared with other processes and is
30
+ * lost when the process exits. `api.redis.inMemory` reports which mode is active.
24
31
  */
25
32
  export class Redis extends Initializer {
26
33
  constructor() {
@@ -28,14 +35,29 @@ export class Redis extends Initializer {
28
35
  }
29
36
 
30
37
  async initialize() {
31
- const redisContainer = {} as {
38
+ const redisContainer = { inMemory: false } as {
32
39
  redis: RedisClient;
33
40
  subscription: RedisClient;
41
+ /** `true` when `REDIS_URL` selected the in-process `memory://` Redis. */
42
+ inMemory: boolean;
34
43
  };
35
44
  return redisContainer;
36
45
  }
37
46
 
38
47
  async start() {
48
+ api.redis.inMemory = isMemoryRedis(config.redis.connectionString);
49
+
50
+ if (api.redis.inMemory) {
51
+ // Loaded on demand so apps using a real Redis never pay for ioredis-mock's Lua VM.
52
+ const { default: RedisMock } = await import("ioredis-mock");
53
+ api.redis.redis = new RedisMock();
54
+ api.redis.subscription = new RedisMock();
55
+ logger.warn(
56
+ "using in-memory redis (REDIS_URL=memory://): state is kept in this process only, is not shared with other processes, and is lost on restart",
57
+ );
58
+ return;
59
+ }
60
+
39
61
  api.redis.redis = new RedisClient(config.redis.connectionString);
40
62
  api.redis.subscription = new RedisClient(config.redis.connectionString);
41
63
 
@@ -100,10 +100,21 @@ export class Resque extends Initializer {
100
100
  this.dependsOn = ["redis", "db", "actions", "process", "hooks"];
101
101
  }
102
102
 
103
+ /**
104
+ * Connection options shared by the resque Queue, Scheduler and Workers. They all reuse
105
+ * `api.redis.redis`. With the in-memory Redis, `pkg: "ioredis-mock"` tells node-resque
106
+ * to skip its `cjson`-based Lua script (unsupported by ioredis-mock) and fall back to
107
+ * plain commands when workers pop jobs.
108
+ */
109
+ connectionOptions = () => ({
110
+ redis: api.redis.redis,
111
+ ...(api.redis.inMemory ? { pkg: "ioredis-mock" } : {}),
112
+ });
113
+
103
114
  /** Create and connect the resque `Queue` instance (used for enqueuing jobs). */
104
115
  startQueue = async () => {
105
116
  api.resque.queue = new Queue(
106
- { connection: { redis: api.redis.redis } },
117
+ { connection: this.connectionOptions() },
107
118
  api.resque.jobs,
108
119
  );
109
120
 
@@ -125,7 +136,7 @@ export class Resque extends Initializer {
125
136
  startScheduler = async () => {
126
137
  if (config.tasks.enabled === true) {
127
138
  api.resque.scheduler = new Scheduler({
128
- connection: { redis: api.redis.redis },
139
+ connection: this.connectionOptions(),
129
140
  timeout: config.tasks.timeout,
130
141
  stuckWorkerTimeout: config.tasks.stuckWorkerTimeout,
131
142
  retryStuckJobs: config.tasks.retryStuckJobs,
@@ -177,7 +188,7 @@ export class Resque extends Initializer {
177
188
  while (id < config.tasks.taskProcessors) {
178
189
  const worker = new Worker(
179
190
  {
180
- connection: { redis: api.redis.redis },
191
+ connection: this.connectionOptions(),
181
192
  queues: Array.isArray(config.tasks.queues)
182
193
  ? config.tasks.queues
183
194
  : await config.tasks.queues(),