@lobu/gateway 3.0.5 → 3.0.6

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 (175) hide show
  1. package/package.json +2 -2
  2. package/src/__tests__/agent-config-routes.test.ts +254 -0
  3. package/src/__tests__/agent-history-routes.test.ts +72 -0
  4. package/src/__tests__/agent-routes.test.ts +68 -0
  5. package/src/__tests__/agent-schedules-routes.test.ts +59 -0
  6. package/src/__tests__/agent-settings-store.test.ts +323 -0
  7. package/src/__tests__/chat-instance-manager-slack.test.ts +204 -0
  8. package/src/__tests__/chat-response-bridge.test.ts +131 -0
  9. package/src/__tests__/config-memory-plugins.test.ts +92 -0
  10. package/src/__tests__/config-request-store.test.ts +127 -0
  11. package/src/__tests__/connection-routes.test.ts +144 -0
  12. package/src/__tests__/core-services-store-selection.test.ts +92 -0
  13. package/src/__tests__/docker-deployment.test.ts +1211 -0
  14. package/src/__tests__/embedded-deployment.test.ts +342 -0
  15. package/src/__tests__/grant-store.test.ts +148 -0
  16. package/src/__tests__/http-proxy.test.ts +281 -0
  17. package/src/__tests__/instruction-service.test.ts +37 -0
  18. package/src/__tests__/link-buttons.test.ts +112 -0
  19. package/src/__tests__/lobu.test.ts +32 -0
  20. package/src/__tests__/mcp-config-service.test.ts +347 -0
  21. package/src/__tests__/mcp-proxy.test.ts +696 -0
  22. package/src/__tests__/message-handler-bridge.test.ts +17 -0
  23. package/src/__tests__/model-selection.test.ts +172 -0
  24. package/src/__tests__/oauth-templates.test.ts +39 -0
  25. package/src/__tests__/platform-adapter-slack-send.test.ts +114 -0
  26. package/src/__tests__/platform-helpers-model-resolution.test.ts +253 -0
  27. package/src/__tests__/provider-inheritance.test.ts +212 -0
  28. package/src/__tests__/routes/cli-auth.test.ts +337 -0
  29. package/src/__tests__/routes/interactions.test.ts +121 -0
  30. package/src/__tests__/secret-proxy.test.ts +85 -0
  31. package/src/__tests__/session-manager.test.ts +572 -0
  32. package/src/__tests__/setup.ts +133 -0
  33. package/src/__tests__/skill-and-mcp-registry.test.ts +203 -0
  34. package/src/__tests__/slack-routes.test.ts +161 -0
  35. package/src/__tests__/system-config-resolver.test.ts +75 -0
  36. package/src/__tests__/system-message-limiter.test.ts +89 -0
  37. package/src/__tests__/system-skills-service.test.ts +362 -0
  38. package/src/__tests__/transcription-service.test.ts +222 -0
  39. package/src/__tests__/utils/rate-limiter.test.ts +102 -0
  40. package/src/__tests__/worker-connection-manager.test.ts +497 -0
  41. package/src/__tests__/worker-job-router.test.ts +722 -0
  42. package/src/api/index.ts +1 -0
  43. package/src/api/platform.ts +292 -0
  44. package/src/api/response-renderer.ts +157 -0
  45. package/src/auth/agent-metadata-store.ts +168 -0
  46. package/src/auth/api-auth-middleware.ts +69 -0
  47. package/src/auth/api-key-provider-module.ts +213 -0
  48. package/src/auth/base-provider-module.ts +201 -0
  49. package/src/auth/chatgpt/chatgpt-oauth-module.ts +185 -0
  50. package/src/auth/chatgpt/device-code-client.ts +218 -0
  51. package/src/auth/chatgpt/index.ts +1 -0
  52. package/src/auth/claude/oauth-module.ts +280 -0
  53. package/src/auth/cli/token-service.ts +249 -0
  54. package/src/auth/external/client.ts +560 -0
  55. package/src/auth/external/device-code-client.ts +225 -0
  56. package/src/auth/mcp/config-service.ts +392 -0
  57. package/src/auth/mcp/proxy.ts +1088 -0
  58. package/src/auth/mcp/string-substitution.ts +17 -0
  59. package/src/auth/mcp/tool-cache.ts +90 -0
  60. package/src/auth/oauth/base-client.ts +267 -0
  61. package/src/auth/oauth/client.ts +153 -0
  62. package/src/auth/oauth/credentials.ts +7 -0
  63. package/src/auth/oauth/providers.ts +69 -0
  64. package/src/auth/oauth/state-store.ts +150 -0
  65. package/src/auth/oauth-templates.ts +179 -0
  66. package/src/auth/provider-catalog.ts +220 -0
  67. package/src/auth/provider-model-options.ts +41 -0
  68. package/src/auth/settings/agent-settings-store.ts +565 -0
  69. package/src/auth/settings/auth-profiles-manager.ts +216 -0
  70. package/src/auth/settings/index.ts +12 -0
  71. package/src/auth/settings/model-preference-store.ts +52 -0
  72. package/src/auth/settings/model-selection.ts +135 -0
  73. package/src/auth/settings/resolved-settings-view.ts +298 -0
  74. package/src/auth/settings/template-utils.ts +44 -0
  75. package/src/auth/settings/token-service.ts +88 -0
  76. package/src/auth/system-env-store.ts +98 -0
  77. package/src/auth/user-agents-store.ts +68 -0
  78. package/src/channels/binding-service.ts +214 -0
  79. package/src/channels/index.ts +4 -0
  80. package/src/cli/gateway.ts +1304 -0
  81. package/src/cli/index.ts +74 -0
  82. package/src/commands/built-in-commands.ts +80 -0
  83. package/src/commands/command-dispatcher.ts +94 -0
  84. package/src/commands/command-reply-adapters.ts +27 -0
  85. package/src/config/file-loader.ts +618 -0
  86. package/src/config/index.ts +588 -0
  87. package/src/config/network-allowlist.ts +71 -0
  88. package/src/connections/chat-instance-manager.ts +1284 -0
  89. package/src/connections/chat-response-bridge.ts +618 -0
  90. package/src/connections/index.ts +7 -0
  91. package/src/connections/interaction-bridge.ts +831 -0
  92. package/src/connections/message-handler-bridge.ts +415 -0
  93. package/src/connections/platform-auth-methods.ts +15 -0
  94. package/src/connections/types.ts +84 -0
  95. package/src/gateway/connection-manager.ts +291 -0
  96. package/src/gateway/index.ts +700 -0
  97. package/src/gateway/job-router.ts +201 -0
  98. package/src/gateway-main.ts +200 -0
  99. package/src/index.ts +41 -0
  100. package/src/infrastructure/queue/index.ts +12 -0
  101. package/src/infrastructure/queue/queue-producer.ts +148 -0
  102. package/src/infrastructure/queue/redis-queue.ts +361 -0
  103. package/src/infrastructure/queue/types.ts +133 -0
  104. package/src/infrastructure/redis/system-message-limiter.ts +94 -0
  105. package/src/interactions/config-request-store.ts +198 -0
  106. package/src/interactions.ts +363 -0
  107. package/src/lobu.ts +311 -0
  108. package/src/metrics/prometheus.ts +159 -0
  109. package/src/modules/module-system.ts +179 -0
  110. package/src/orchestration/base-deployment-manager.ts +900 -0
  111. package/src/orchestration/deployment-utils.ts +98 -0
  112. package/src/orchestration/impl/docker-deployment.ts +620 -0
  113. package/src/orchestration/impl/embedded-deployment.ts +268 -0
  114. package/src/orchestration/impl/index.ts +8 -0
  115. package/src/orchestration/impl/k8s/deployment.ts +1061 -0
  116. package/src/orchestration/impl/k8s/helpers.ts +610 -0
  117. package/src/orchestration/impl/k8s/index.ts +1 -0
  118. package/src/orchestration/index.ts +333 -0
  119. package/src/orchestration/message-consumer.ts +584 -0
  120. package/src/orchestration/scheduled-wakeup.ts +704 -0
  121. package/src/permissions/approval-policy.ts +36 -0
  122. package/src/permissions/grant-store.ts +219 -0
  123. package/src/platform/file-handler.ts +66 -0
  124. package/src/platform/link-buttons.ts +57 -0
  125. package/src/platform/renderer-utils.ts +44 -0
  126. package/src/platform/response-renderer.ts +84 -0
  127. package/src/platform/unified-thread-consumer.ts +187 -0
  128. package/src/platform.ts +318 -0
  129. package/src/proxy/http-proxy.ts +752 -0
  130. package/src/proxy/proxy-manager.ts +81 -0
  131. package/src/proxy/secret-proxy.ts +402 -0
  132. package/src/proxy/token-refresh-job.ts +143 -0
  133. package/src/routes/internal/audio.ts +141 -0
  134. package/src/routes/internal/device-auth.ts +566 -0
  135. package/src/routes/internal/files.ts +226 -0
  136. package/src/routes/internal/history.ts +69 -0
  137. package/src/routes/internal/images.ts +127 -0
  138. package/src/routes/internal/interactions.ts +84 -0
  139. package/src/routes/internal/middleware.ts +23 -0
  140. package/src/routes/internal/schedule.ts +226 -0
  141. package/src/routes/internal/types.ts +22 -0
  142. package/src/routes/openapi-auto.ts +239 -0
  143. package/src/routes/public/agent-access.ts +23 -0
  144. package/src/routes/public/agent-config.ts +675 -0
  145. package/src/routes/public/agent-history.ts +422 -0
  146. package/src/routes/public/agent-schedules.ts +296 -0
  147. package/src/routes/public/agent.ts +1086 -0
  148. package/src/routes/public/agents.ts +373 -0
  149. package/src/routes/public/channels.ts +191 -0
  150. package/src/routes/public/cli-auth.ts +883 -0
  151. package/src/routes/public/connections.ts +574 -0
  152. package/src/routes/public/landing.ts +16 -0
  153. package/src/routes/public/oauth.ts +147 -0
  154. package/src/routes/public/settings-auth.ts +104 -0
  155. package/src/routes/public/slack.ts +173 -0
  156. package/src/routes/shared/agent-ownership.ts +101 -0
  157. package/src/routes/shared/token-verifier.ts +34 -0
  158. package/src/services/core-services.ts +1053 -0
  159. package/src/services/image-generation-service.ts +257 -0
  160. package/src/services/instruction-service.ts +318 -0
  161. package/src/services/mcp-registry.ts +94 -0
  162. package/src/services/platform-helpers.ts +287 -0
  163. package/src/services/session-manager.ts +262 -0
  164. package/src/services/settings-resolver.ts +74 -0
  165. package/src/services/system-config-resolver.ts +90 -0
  166. package/src/services/system-skills-service.ts +229 -0
  167. package/src/services/transcription-service.ts +684 -0
  168. package/src/session.ts +110 -0
  169. package/src/spaces/index.ts +1 -0
  170. package/src/spaces/space-resolver.ts +17 -0
  171. package/src/stores/in-memory-agent-store.ts +403 -0
  172. package/src/stores/redis-agent-store.ts +279 -0
  173. package/src/utils/public-url.ts +44 -0
  174. package/src/utils/rate-limiter.ts +94 -0
  175. package/tsconfig.json +33 -0
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Test setup and utilities for Gateway tests.
3
+ *
4
+ * Shared mocks (Redis, Queue, fetch, factories) live in @lobu/core fixtures.
5
+ * This file re-exports them and adds gateway-specific helpers.
6
+ */
7
+
8
+ import { createMockJob as _createMockJob } from "@lobu/core/testing";
9
+
10
+ export {
11
+ createInstructionContext,
12
+ createMockJob,
13
+ createWorkerConfig,
14
+ MockMessageQueue,
15
+ MockRedisClient,
16
+ mockFetch,
17
+ } from "@lobu/core/testing";
18
+
19
+ /**
20
+ * Mock Express Response for SSE testing (gateway-specific)
21
+ */
22
+ export class MockResponse {
23
+ private _ended = false;
24
+ private _written: string[] = [];
25
+ private _closeCallbacks: (() => void)[] = [];
26
+
27
+ write(chunk: string): boolean {
28
+ if (this._ended) {
29
+ throw new Error("Cannot write to ended response");
30
+ }
31
+ this._written.push(chunk);
32
+ return true;
33
+ }
34
+
35
+ end(): void {
36
+ this._ended = true;
37
+ }
38
+
39
+ onClose(callback: () => void): void {
40
+ this._closeCallbacks.push(callback);
41
+ }
42
+
43
+ simulateClose(): void {
44
+ for (const cb of this._closeCallbacks) cb();
45
+ }
46
+
47
+ isEnded(): boolean {
48
+ return this._ended;
49
+ }
50
+
51
+ getWritten(): string[] {
52
+ return this._written;
53
+ }
54
+
55
+ getLastWrite(): string | undefined {
56
+ return this._written[this._written.length - 1];
57
+ }
58
+
59
+ getAllWrites(): string {
60
+ return this._written.join("");
61
+ }
62
+
63
+ clearWrites(): void {
64
+ this._written = [];
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Test utilities
70
+ */
71
+ export class TestHelpers {
72
+ static createMockJob(overrides: any = {}): any {
73
+ return _createMockJob(overrides);
74
+ }
75
+
76
+ static async delay(ms: number): Promise<void> {
77
+ return new Promise((resolve) => setTimeout(resolve, ms));
78
+ }
79
+
80
+ static parseSSE(sse: string): { event: string; data: any }[] {
81
+ const events: { event: string; data: any }[] = [];
82
+ const lines = sse.split("\n");
83
+
84
+ let currentEvent = "";
85
+ let currentData = "";
86
+
87
+ for (const line of lines) {
88
+ if (line.startsWith("event:")) {
89
+ currentEvent = line.substring(6).trim();
90
+ } else if (line.startsWith("data:")) {
91
+ currentData = line.substring(5).trim();
92
+ } else if (line === "") {
93
+ if (currentEvent && currentData) {
94
+ try {
95
+ events.push({
96
+ event: currentEvent,
97
+ data: JSON.parse(currentData),
98
+ });
99
+ } catch {
100
+ events.push({
101
+ event: currentEvent,
102
+ data: currentData,
103
+ });
104
+ }
105
+ currentEvent = "";
106
+ currentData = "";
107
+ }
108
+ }
109
+ }
110
+
111
+ return events;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * Mock environment variables
117
+ */
118
+ const mockEnvVars = {
119
+ WORKER_STALE_TIMEOUT_MINUTES: "10",
120
+ PUBLIC_GATEWAY_URL: "https://test-gateway.example.com",
121
+ };
122
+
123
+ export function setupTestEnv(): void {
124
+ for (const [key, value] of Object.entries(mockEnvVars)) {
125
+ process.env[key] = value;
126
+ }
127
+ }
128
+
129
+ export function cleanupTestEnv(): void {
130
+ for (const key of Object.keys(mockEnvVars)) {
131
+ delete process.env[key];
132
+ }
133
+ }
@@ -0,0 +1,203 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { McpRegistryService } from "../services/mcp-registry";
3
+ import type { SystemConfigResolver } from "../services/system-config-resolver";
4
+
5
+ // --- McpRegistryService ---
6
+
7
+ function createMockResolver(
8
+ entries: Array<{
9
+ id: string;
10
+ name: string;
11
+ description: string;
12
+ type: "oauth" | "stdio" | "sse" | "api-key";
13
+ config: Record<string, unknown>;
14
+ }>
15
+ ) {
16
+ return {
17
+ getMcpRegistryServers: async () => entries,
18
+ } as unknown as SystemConfigResolver;
19
+ }
20
+
21
+ const mcpEntries = [
22
+ {
23
+ id: "github",
24
+ name: "GitHub",
25
+ description: "GitHub integration",
26
+ type: "stdio" as const,
27
+ config: { type: "stdio" },
28
+ },
29
+ {
30
+ id: "sentry",
31
+ name: "Sentry",
32
+ description: "Error tracking",
33
+ type: "sse" as const,
34
+ config: { type: "sse" },
35
+ },
36
+ {
37
+ id: "playwright",
38
+ name: "Playwright",
39
+ description: "Browser automation",
40
+ type: "stdio" as const,
41
+ config: {},
42
+ },
43
+ {
44
+ id: "notion",
45
+ name: "Notion",
46
+ description: "Notion workspace",
47
+ type: "oauth" as const,
48
+ config: {},
49
+ },
50
+ {
51
+ id: "linear",
52
+ name: "Linear",
53
+ description: "Issue tracker",
54
+ type: "api-key" as const,
55
+ config: {},
56
+ },
57
+ {
58
+ id: "slack",
59
+ name: "Slack",
60
+ description: "Slack messaging",
61
+ type: "oauth" as const,
62
+ config: {},
63
+ },
64
+ {
65
+ id: "jira",
66
+ name: "Jira",
67
+ description: "Project management",
68
+ type: "api-key" as const,
69
+ config: {},
70
+ },
71
+ ];
72
+
73
+ describe("McpRegistryService", () => {
74
+ test("getCurated returns entries matching curated IDs", async () => {
75
+ const service = new McpRegistryService(createMockResolver(mcpEntries));
76
+ const curated = await service.getCurated();
77
+
78
+ const ids = curated.map((e) => e.id);
79
+ for (const curatedId of McpRegistryService.CURATED_MCP_IDS) {
80
+ expect(ids).toContain(curatedId);
81
+ }
82
+ expect(curated).toHaveLength(5);
83
+ });
84
+
85
+ test("getCurated falls back to first 5 when no curated IDs match", async () => {
86
+ const noCuratedEntries = [
87
+ {
88
+ id: "custom1",
89
+ name: "Custom 1",
90
+ description: "Desc",
91
+ type: "sse" as const,
92
+ config: {},
93
+ },
94
+ {
95
+ id: "custom2",
96
+ name: "Custom 2",
97
+ description: "Desc",
98
+ type: "sse" as const,
99
+ config: {},
100
+ },
101
+ {
102
+ id: "custom3",
103
+ name: "Custom 3",
104
+ description: "Desc",
105
+ type: "sse" as const,
106
+ config: {},
107
+ },
108
+ {
109
+ id: "custom4",
110
+ name: "Custom 4",
111
+ description: "Desc",
112
+ type: "sse" as const,
113
+ config: {},
114
+ },
115
+ {
116
+ id: "custom5",
117
+ name: "Custom 5",
118
+ description: "Desc",
119
+ type: "sse" as const,
120
+ config: {},
121
+ },
122
+ {
123
+ id: "custom6",
124
+ name: "Custom 6",
125
+ description: "Desc",
126
+ type: "sse" as const,
127
+ config: {},
128
+ },
129
+ ];
130
+ const service = new McpRegistryService(
131
+ createMockResolver(noCuratedEntries)
132
+ );
133
+ const curated = await service.getCurated();
134
+
135
+ expect(curated).toHaveLength(5);
136
+ expect(curated.map((e) => e.id)).toEqual([
137
+ "custom1",
138
+ "custom2",
139
+ "custom3",
140
+ "custom4",
141
+ "custom5",
142
+ ]);
143
+ });
144
+
145
+ test("search matches by name, description, and id", async () => {
146
+ const service = new McpRegistryService(createMockResolver(mcpEntries));
147
+
148
+ const byName = await service.search("GitHub");
149
+ expect(byName.some((e) => e.id === "github")).toBe(true);
150
+
151
+ const byDesc = await service.search("Browser automation");
152
+ expect(byDesc.some((e) => e.id === "playwright")).toBe(true);
153
+
154
+ const byId = await service.search("linear");
155
+ expect(byId.some((e) => e.id === "linear")).toBe(true);
156
+ });
157
+
158
+ test("search respects limit", async () => {
159
+ const service = new McpRegistryService(createMockResolver(mcpEntries));
160
+ // "a" appears in many names/descriptions
161
+ const results = await service.search("a", 2);
162
+ expect(results.length).toBeLessThanOrEqual(2);
163
+ });
164
+
165
+ test("search with empty query returns all up to limit", async () => {
166
+ const service = new McpRegistryService(createMockResolver(mcpEntries));
167
+
168
+ const results = await service.search("", 3);
169
+ expect(results).toHaveLength(3);
170
+
171
+ const allResults = await service.search("");
172
+ expect(allResults).toHaveLength(mcpEntries.length);
173
+ });
174
+
175
+ test("getAll returns complete list", async () => {
176
+ const service = new McpRegistryService(createMockResolver(mcpEntries));
177
+ const all = await service.getAll();
178
+ expect(all).toHaveLength(mcpEntries.length);
179
+ });
180
+
181
+ test("getById returns specific entry", async () => {
182
+ const service = new McpRegistryService(createMockResolver(mcpEntries));
183
+
184
+ const entry = await service.getById("sentry");
185
+ expect(entry).not.toBeNull();
186
+ expect(entry!.name).toBe("Sentry");
187
+ });
188
+
189
+ test("getById returns null for unknown id", async () => {
190
+ const service = new McpRegistryService(createMockResolver(mcpEntries));
191
+ const entry = await service.getById("nonexistent");
192
+ expect(entry).toBeNull();
193
+ });
194
+
195
+ test("no resolver returns empty results", async () => {
196
+ const service = new McpRegistryService();
197
+
198
+ expect(await service.getCurated()).toEqual([]);
199
+ expect(await service.search("github")).toEqual([]);
200
+ expect(await service.getAll()).toEqual([]);
201
+ expect(await service.getById("github")).toBeNull();
202
+ });
203
+ });
@@ -0,0 +1,161 @@
1
+ import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
2
+ import { createSlackRoutes } from "../routes/public/slack";
3
+
4
+ class RouteRedisMock {
5
+ private store = new Map<string, string>();
6
+
7
+ async setex(key: string, _ttlSeconds: number, value: string): Promise<void> {
8
+ this.store.set(key, value);
9
+ }
10
+
11
+ async get(key: string): Promise<string | null> {
12
+ return this.store.get(key) ?? null;
13
+ }
14
+
15
+ async getdel(key: string): Promise<string | null> {
16
+ const value = this.store.get(key) ?? null;
17
+ this.store.delete(key);
18
+ return value;
19
+ }
20
+
21
+ async del(...keys: string[]): Promise<number> {
22
+ let removed = 0;
23
+ for (const key of keys) {
24
+ if (this.store.delete(key)) {
25
+ removed++;
26
+ }
27
+ }
28
+ return removed;
29
+ }
30
+ }
31
+
32
+ describe("slack routes", () => {
33
+ const originalClientId = process.env.SLACK_CLIENT_ID;
34
+ const originalScopes = process.env.SLACK_OAUTH_SCOPES;
35
+
36
+ let redis: RouteRedisMock;
37
+ let completeSlackOAuthInstall: ReturnType<typeof mock>;
38
+ let handleSlackAppWebhook: ReturnType<typeof mock>;
39
+ let router: ReturnType<typeof createSlackRoutes>;
40
+
41
+ beforeEach(() => {
42
+ process.env.SLACK_CLIENT_ID = "client-123";
43
+ process.env.SLACK_OAUTH_SCOPES = "chat:write,commands";
44
+
45
+ redis = new RouteRedisMock();
46
+ completeSlackOAuthInstall = mock(async () => ({
47
+ teamId: "T123",
48
+ teamName: "Acme",
49
+ connectionId: "conn-1",
50
+ }));
51
+ handleSlackAppWebhook = mock(async (request: Request) => {
52
+ const body = await request.text();
53
+ return new Response(`handled:${body}`);
54
+ });
55
+
56
+ router = createSlackRoutes({
57
+ getServices: () => ({
58
+ getQueue: () => ({
59
+ getRedisClient: () => redis,
60
+ }),
61
+ getPublicGatewayUrl: () => "https://gateway.example.com",
62
+ }),
63
+ completeSlackOAuthInstall,
64
+ handleSlackAppWebhook,
65
+ } as any);
66
+ });
67
+
68
+ afterEach(() => {
69
+ if (originalClientId === undefined) {
70
+ delete process.env.SLACK_CLIENT_ID;
71
+ } else {
72
+ process.env.SLACK_CLIENT_ID = originalClientId;
73
+ }
74
+
75
+ if (originalScopes === undefined) {
76
+ delete process.env.SLACK_OAUTH_SCOPES;
77
+ } else {
78
+ process.env.SLACK_OAUTH_SCOPES = originalScopes;
79
+ }
80
+ });
81
+
82
+ test("GET /slack/install redirects to Slack OAuth and stores state", async () => {
83
+ const response = await router.request("/slack/install");
84
+
85
+ expect(response.status).toBe(302);
86
+
87
+ const location = response.headers.get("location");
88
+ expect(location).toBeTruthy();
89
+
90
+ const redirectUrl = new URL(location!);
91
+ expect(redirectUrl.origin).toBe("https://slack.com");
92
+ expect(redirectUrl.pathname).toBe("/oauth/v2/authorize");
93
+ expect(redirectUrl.searchParams.get("client_id")).toBe("client-123");
94
+ expect(redirectUrl.searchParams.get("scope")).toBe("chat:write,commands");
95
+ expect(redirectUrl.searchParams.get("redirect_uri")).toBe(
96
+ "https://gateway.example.com/slack/oauth_callback"
97
+ );
98
+
99
+ const state = redirectUrl.searchParams.get("state");
100
+ expect(state).toBeTruthy();
101
+
102
+ const rawState = await redis.get(`slack:oauth:state:${state}`);
103
+ expect(rawState).toBeTruthy();
104
+ expect(JSON.parse(rawState!)).toEqual({
105
+ createdAt: expect.any(Number),
106
+ redirectUri: "https://gateway.example.com/slack/oauth_callback",
107
+ });
108
+ });
109
+
110
+ test("GET /slack/oauth_callback rejects invalid state", async () => {
111
+ const response = await router.request(
112
+ "/slack/oauth_callback?code=test-code&state=missing"
113
+ );
114
+ const body = await response.text();
115
+
116
+ expect(response.status).toBe(400);
117
+ expect(body).toContain("Authentication Failed");
118
+ expect(body).toContain("invalid or has expired");
119
+ expect(completeSlackOAuthInstall).not.toHaveBeenCalled();
120
+ });
121
+
122
+ test("GET /slack/oauth_callback completes install and clears state", async () => {
123
+ await redis.setex(
124
+ "slack:oauth:state:test-state",
125
+ 600,
126
+ JSON.stringify({
127
+ createdAt: Date.now(),
128
+ redirectUri: "https://gateway.example.com/slack/oauth_callback",
129
+ })
130
+ );
131
+
132
+ const response = await router.request(
133
+ "/slack/oauth_callback?code=test-code&state=test-state"
134
+ );
135
+ const body = await response.text();
136
+
137
+ expect(response.status).toBe(200);
138
+ expect(body).toContain("Slack installed");
139
+ expect(body).toContain("Workspace connected to Lobu:");
140
+ expect(body).toContain("Connection ID: conn-1");
141
+ expect(completeSlackOAuthInstall).toHaveBeenCalledTimes(1);
142
+ expect(completeSlackOAuthInstall.mock.calls[0]?.[1]).toBe(
143
+ "https://gateway.example.com/slack/oauth_callback"
144
+ );
145
+ expect(await redis.get("slack:oauth:state:test-state")).toBeNull();
146
+ });
147
+
148
+ test("POST /slack/events forwards requests to the chat manager", async () => {
149
+ const response = await router.request("/slack/events", {
150
+ method: "POST",
151
+ headers: {
152
+ "content-type": "application/json",
153
+ },
154
+ body: JSON.stringify({ team_id: "T123", type: "event_callback" }),
155
+ });
156
+
157
+ expect(response.status).toBe(200);
158
+ expect(await response.text()).toContain("handled:");
159
+ expect(handleSlackAppWebhook).toHaveBeenCalledTimes(1);
160
+ });
161
+ });
@@ -0,0 +1,75 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { ProviderConfigEntry, SkillConfig } from "@lobu/core";
3
+ import { SystemConfigResolver } from "../services/system-config-resolver";
4
+
5
+ class MockSystemSkillsService {
6
+ constructor(
7
+ private readonly providers: Record<string, ProviderConfigEntry>,
8
+ private readonly skills: SkillConfig[]
9
+ ) {}
10
+
11
+ async getProviderConfigs(): Promise<Record<string, ProviderConfigEntry>> {
12
+ return this.providers;
13
+ }
14
+
15
+ async getSystemSkills(): Promise<SkillConfig[]> {
16
+ return this.skills;
17
+ }
18
+ }
19
+
20
+ describe("SystemConfigResolver MCP and provider resolution", () => {
21
+ test("builds global MCP server map and registry entries from system skills", async () => {
22
+ const resolver = new SystemConfigResolver(
23
+ new MockSystemSkillsService(
24
+ {
25
+ groq: {
26
+ displayName: "Groq",
27
+ iconUrl: "https://example.com/groq.png",
28
+ envVarName: "GROQ_API_KEY",
29
+ upstreamBaseUrl: "https://api.groq.com/openai",
30
+ apiKeyInstructions: "Get key",
31
+ apiKeyPlaceholder: "gsk_...",
32
+ },
33
+ },
34
+ [
35
+ {
36
+ repo: "system/owletto",
37
+ name: "Owletto",
38
+ enabled: true,
39
+ description: "Memory MCP",
40
+ mcpServers: [
41
+ {
42
+ id: "owletto",
43
+ name: "Owletto",
44
+ url: "https://owletto.com/mcp",
45
+ },
46
+ { id: "local-tool", command: "mcp-local", args: ["--stdio"] },
47
+ ],
48
+ } as SkillConfig,
49
+ ]
50
+ ) as any
51
+ );
52
+
53
+ const globalMcp = await resolver.getGlobalMcpServers();
54
+ const registryEntries = await resolver.getMcpRegistryServers();
55
+ const providers = await resolver.getProviderConfigs();
56
+
57
+ expect(globalMcp.owletto).toEqual({
58
+ type: "sse",
59
+ url: "https://owletto.com/mcp",
60
+ });
61
+ expect(globalMcp["local-tool"]).toEqual({
62
+ type: "stdio",
63
+ command: "mcp-local",
64
+ args: ["--stdio"],
65
+ });
66
+
67
+ expect(registryEntries.map((entry) => entry.id)).toEqual([
68
+ "owletto",
69
+ "local-tool",
70
+ ]);
71
+ expect(registryEntries[1]?.type).toBe("stdio");
72
+
73
+ expect(Object.keys(providers)).toEqual(["groq"]);
74
+ });
75
+ });
@@ -0,0 +1,89 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { MockRedisClient } from "@lobu/core/testing";
3
+ import { SystemMessageLimiter } from "../infrastructure/redis/system-message-limiter";
4
+
5
+ describe("SystemMessageLimiter", () => {
6
+ test("sends once and suppresses subsequent sends within TTL", async () => {
7
+ const redis = new MockRedisClient() as any;
8
+ const limiter = new SystemMessageLimiter(redis, "test");
9
+
10
+ let sentCount = 0;
11
+ const sendFn = async () => {
12
+ sentCount += 1;
13
+ };
14
+
15
+ const first = await limiter.sendOnce("k", sendFn, {
16
+ sentTtlSeconds: 60,
17
+ lockTtlSeconds: 30,
18
+ });
19
+ const second = await limiter.sendOnce("k", sendFn, {
20
+ sentTtlSeconds: 60,
21
+ lockTtlSeconds: 30,
22
+ });
23
+
24
+ expect(first).toBe(true);
25
+ expect(second).toBe(false);
26
+ expect(sentCount).toBe(1);
27
+ });
28
+
29
+ test("suppresses concurrent sends using lock even before sent marker is written", async () => {
30
+ const redis = new MockRedisClient() as any;
31
+ const limiter = new SystemMessageLimiter(redis, "test");
32
+
33
+ let release!: () => void;
34
+ const gate = new Promise<void>((resolve) => {
35
+ release = resolve;
36
+ });
37
+
38
+ let started = 0;
39
+ const sendFn = async () => {
40
+ started += 1;
41
+ await gate;
42
+ };
43
+
44
+ const p1 = limiter.sendOnce("k2", sendFn, {
45
+ sentTtlSeconds: 60,
46
+ lockTtlSeconds: 30,
47
+ });
48
+ const p2 = limiter.sendOnce("k2", sendFn, {
49
+ sentTtlSeconds: 60,
50
+ lockTtlSeconds: 30,
51
+ });
52
+
53
+ // Ensure both have attempted to run; only one should have entered sendFn.
54
+ await new Promise((r) => setTimeout(r, 0));
55
+ expect(started).toBe(1);
56
+
57
+ release();
58
+ const [r1, r2] = await Promise.all([p1, p2]);
59
+ expect([r1, r2].filter(Boolean).length).toBe(1);
60
+ });
61
+
62
+ test("does not set sent marker on failure (allows retry)", async () => {
63
+ const redis = new MockRedisClient() as any;
64
+ const limiter = new SystemMessageLimiter(redis, "test");
65
+
66
+ let attempts = 0;
67
+ const sendFn = async () => {
68
+ attempts += 1;
69
+ throw new Error("fail");
70
+ };
71
+
72
+ await expect(
73
+ limiter.sendOnce("k3", sendFn, {
74
+ sentTtlSeconds: 60,
75
+ lockTtlSeconds: 30,
76
+ })
77
+ ).rejects.toThrow("fail");
78
+
79
+ // Next call should try again (not suppressed).
80
+ await expect(
81
+ limiter.sendOnce("k3", sendFn, {
82
+ sentTtlSeconds: 60,
83
+ lockTtlSeconds: 30,
84
+ })
85
+ ).rejects.toThrow("fail");
86
+
87
+ expect(attempts).toBe(2);
88
+ });
89
+ });