GeezerVison is showing github.com — fix sse auth and transform timeout 2h · stackpress/stackpress@a8c1707
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/stackpress-ai/src/scripts/sse.ts +38-7Lines changed: 38 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -6,13 +6,16 @@ import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'; | 6 | 6 | import type Server from '@stackpress/ingest/Server'; | 7 | 7 | //client | 8 | 8 | import type { | | 9 | + AuthContext, | 9 | 10 | McpPlugin, | 10 | 11 | McpServer, | 11 | 12 | McpSseSession, | 12 | | - Promiser | | 13 | + Promiser, | | 14 | + ToolResolverServer | 13 | 15 | } from '../types.js'; | 14 | 16 | import { | 15 | 17 | readJsonBody, | | 18 | + resolveListAuth, | 16 | 19 | sendText | 17 | 20 | } from '../helpers.js'; | 18 | 21 |
| @@ -63,6 +66,8 @@ export function shouldAttachSseToServer(ctx: Server) { | 63 | 66 | export class McpSseServer { | 64 | 67 | //this shutdown handle is exposed so the caller can stop the server cleanly | 65 | 68 | public readonly shutdown: () => Promise<void>; | | 69 | + //this callback resolves one caller auth context from a raw request | | 70 | + protected _authResolver: (req: IncomingMessage) => Promise<AuthContext>; | 66 | 71 | //this endpoint accepts the initial SSE connection request | 67 | 72 | protected _endpoint: string; | 68 | 73 | //this flag prevents the shutdown path from running more than once | @@ -87,13 +92,15 @@ export class McpSseServer { | 87 | 92 | */ | 88 | 93 | public constructor( | 89 | 94 | factory: McpPlugin, | | 95 | + authResolver: (req: IncomingMessage) => Promise<AuthContext>, | 90 | 96 | host: string, | 91 | 97 | port: number, | 92 | 98 | endpoint: string, | 93 | 99 | messages: string, | 94 | 100 | promiser: Promiser<void> | 95 | 101 | ) { | 96 | 102 | this._factory = factory; | | 103 | + this._authResolver = authResolver; | 97 | 104 | this._host = host; | 98 | 105 | this._port = port; | 99 | 106 | this._endpoint = endpoint; | @@ -161,8 +168,8 @@ export class McpSseServer { | 161 | 168 | /** | 162 | 169 | * Resolve one MCP server instance from the registered factory. | 163 | 170 | */ | 164 | | - protected async _createServer(): Promise<McpServer> { | 165 | | - const server = await this._factory(); | | 171 | + protected async _createServer(auth: AuthContext): Promise<McpServer> { | | 172 | + const server = await this._factory(auth); | 166 | 173 |
| 167 | 174 | //if config produced no tools, fail loudly so the CLI does not hang | 168 | 175 | if (!server) { | @@ -214,7 +221,7 @@ export class McpSseServer { | 214 | 221 |
| 215 | 222 | //for GET on the SSE endpoint, start one long-lived event stream session | 216 | 223 | if (req.method === 'GET' && url.pathname === this._endpoint) { | 217 | | - await this._handleSseConnection(res); | | 224 | + await this._handleSseConnection(req, res); | 218 | 225 | return; | 219 | 226 | } | 220 | 227 |
| @@ -240,14 +247,18 @@ export class McpSseServer { | 240 | 247 | /** | 241 | 248 | * Open one SSE session and register it in the live session map. | 242 | 249 | */ | 243 | | - protected async _handleSseConnection(res: ServerResponse) { | | 250 | + protected async _handleSseConnection( | | 251 | + req: IncomingMessage, | | 252 | + res: ServerResponse | | 253 | + ) { | | 254 | + const auth = await this._authResolver(req); | 244 | 255 | //first build one MCP tool server from the registered factory | 245 | | - const server = await this._createServer(); | | 256 | + const server = await this._createServer(auth); | 246 | 257 |
| 247 | 258 | //then pair it with one SSE transport bound to the response stream | 248 | 259 | const transport = new SSEServerTransport(this._messages, res); | 249 | 260 | const sessionId = transport.sessionId; | 250 | | - this._sessions[sessionId] = { server, transport }; | | 261 | + this._sessions[sessionId] = { auth, server, transport }; | 251 | 262 |
| 252 | 263 | //when the transport closes, remove its session from the lookup table | 253 | 264 | transport.onclose = async () => { | @@ -271,11 +282,18 @@ export default async function sse(ctx: Server) { | 271 | 282 |
| 272 | 283 | const factory = ctx.plugin<McpPlugin>('mcp'); | 273 | 284 | const { endpoint, host, messages, port } = resolveSseConfig(ctx); | | 285 | + //build one connection-level auth resolver so each SSE session binds to | | 286 | + // the bearer token presented on the initial event-stream request. | | 287 | + const authResolver = async (req: IncomingMessage) => resolveListAuth( | | 288 | + ctx as ToolResolverServer, | | 289 | + header(req, 'authorization') || undefined | | 290 | + ); | 274 | 291 |
| 275 | 292 | //then keep the event open until the underlying HTTP service closes | 276 | 293 | return new Promise<void>(async (resolve, reject) => { | 277 | 294 | const transport = new McpSseServer( | 278 | 295 | factory, | | 296 | + authResolver, | 279 | 297 | host, | 280 | 298 | port, | 281 | 299 | endpoint, | @@ -302,8 +320,13 @@ export function attachSseToServer(ctx: Server) { | 302 | 320 |
| 303 | 321 | attachable[key] = true; | 304 | 322 | const factory = ctx.plugin<McpPlugin>('mcp'); | | 323 | + const authResolver = async (req: IncomingMessage) => resolveListAuth( | | 324 | + ctx as ToolResolverServer, | | 325 | + header(req, 'authorization') || undefined | | 326 | + ); | 305 | 327 | const transport = new McpSseServer( | 306 | 328 | factory, | | 329 | + authResolver, | 307 | 330 | host, | 308 | 331 | port, | 309 | 332 | endpoint, | @@ -341,3 +364,11 @@ export function attachSseToServer(ctx: Server) { | 341 | 364 | } | 342 | 365 | }); | 343 | 366 | } | | 367 | + | | 368 | +/** | | 369 | + * Read one header value from a Node request, normalizing array values. | | 370 | + */ | | 371 | +function header(req: IncomingMessage, name: string) { | | 372 | + const value = req.headers[name.toLowerCase()]; | | 373 | + return Array.isArray(value) ? value[0] : value ?? null; | | 374 | +} |
Collapse file Copy file name to clipboardExpand all lines: packages/stackpress-ai/tests/sse.test.ts +99-6Lines changed: 99 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -14,6 +14,7 @@ import { | 14 | 14 | expectJson, | 15 | 15 | MockResponse | 16 | 16 | } from './helpers.js'; | | 17 | +import type { AuthContext } from '../src/types.js'; | 17 | 18 |
| 18 | 19 | type MessageResponse = { | 19 | 20 | jsonrpc: '2.0'; | @@ -47,6 +48,7 @@ type TestTransport = { | 47 | 48 | //this narrowed session map lets the subclass update protected state without | 48 | 49 | // leaning on any-casts. | 49 | 50 | type SessionStore = Record<string, { | | 51 | + auth: AuthContext, | 50 | 52 | server: { close: () => Promise<void> }, | 51 | 53 | transport: TestTransport | 52 | 54 | }>; | @@ -75,9 +77,13 @@ class TestSseServer extends McpSseServer { | 75 | 77 | /** | 76 | 78 | * Create one fake SSE session and immediately write a handshake response. | 77 | 79 | */ | 78 | | - protected override async _handleSseConnection(res: ServerResponse) { | | 80 | + protected override async _handleSseConnection( | | 81 | + req: IncomingMessage, | | 82 | + res: ServerResponse | | 83 | + ) { | 79 | 84 | this.created++; | 80 | 85 | const sessionId = `sse-${this.created}`; | | 86 | + const auth = await this._authResolver(req); | 81 | 87 | const server = { | 82 | 88 | close: async () => undefined | 83 | 89 | }; | @@ -108,16 +114,21 @@ class TestSseServer extends McpSseServer { | 108 | 114 | } | 109 | 115 | }; | 110 | 116 |
| 111 | | - sessions[sessionId] = { server, transport }; | | 117 | + sessions[sessionId] = { auth, server, transport }; | 112 | 118 | res.statusCode = 200; | 113 | 119 | res.setHeader('Content-Type', 'text/event-stream'); | 114 | 120 | res.end(`event: endpoint\ndata: ${JSON.stringify({ sessionId })}\n\n`); | 115 | 121 | } | 116 | 122 | } | 117 | 123 |
| 118 | | -function makeServer() { | | 124 | +function makeServer( | | 125 | + authResolver: (req: IncomingMessage) => Promise<AuthContext> = async () => { | | 126 | + return { kind: 'public' }; | | 127 | + } | | 128 | +) { | 119 | 129 | return new TestSseServer( | 120 | 130 | async () => null, | | 131 | + authResolver, | 121 | 132 | '127.0.0.1', | 122 | 133 | 17759, | 123 | 134 | '/sse', | @@ -137,7 +148,8 @@ type ConfigStub = { | 137 | 148 | path<T>(key: string, fallback?: T): T | 138 | 149 | }, | 139 | 150 | on?: (event: string, listener: Function) => void, | 140 | | - plugin?: <T = unknown>(name: string) => T | | 151 | + plugin?: <T = unknown>(name: string) => T, | | 152 | + listener?: () => Function | undefined | 141 | 153 | }; | 142 | 154 |
| 143 | 155 | /** | @@ -158,7 +170,10 @@ function makeCtx(config: Record<string, unknown> = {}) { | 158 | 170 | /** | 159 | 171 | * Create one minimal attached-server stub that captures the request listener. | 160 | 172 | */ | 161 | | -function makeAttachCtx(config: Record<string, unknown> = {}) { | | 173 | +function makeAttachCtx( | | 174 | + config: Record<string, unknown> = {}, | | 175 | + pluginFactory?: <T = unknown>(name: string) => T | | 176 | +) { | 162 | 177 | let listener: Function | undefined; | 163 | 178 | const ctx: ConfigStub & { | 164 | 179 | listener: () => Function | undefined | @@ -173,7 +188,10 @@ function makeAttachCtx(config: Record<string, unknown> = {}) { | 173 | 188 | listener = callback; | 174 | 189 | } | 175 | 190 | }, | 176 | | - plugin<T = unknown>() { | | 191 | + plugin<T = unknown>(name: string) { | | 192 | + if (pluginFactory) { | | 193 | + return pluginFactory<T>(name); | | 194 | + } | 177 | 195 | return (async () => null) as T; | 178 | 196 | }, | 179 | 197 | listener() { | @@ -315,6 +333,81 @@ describe('ai/sse', () => { | 315 | 333 | expect(resolved.port).to.equal(18888); | 316 | 334 | }); | 317 | 335 |
| | 336 | + it('should bind bearer auth from the initial sse connection', async () => { | | 337 | + const auth = { | | 338 | + kind: 'app', | | 339 | + token: { token: 'app-1:secret-1', id: 'app-1', secret: 'secret-1' }, | | 340 | + application: { id: 'app-1', scopes: [ 'articles.read' ], secret: 'secret-1' } | | 341 | + } satisfies AuthContext; | | 342 | + const calls: AuthContext[] = []; | | 343 | + const ctx = makeAttachCtx( | | 344 | + { | | 345 | + mcp: {}, | | 346 | + 'mcp.sse.route': '/sse', | | 347 | + 'mcp.messages': '/messages' | | 348 | + }, | | 349 | + name => { | | 350 | + if (name !== 'mcp') { | | 351 | + return null as never; | | 352 | + } | | 353 | + return (async (resolved?: AuthContext) => { | | 354 | + calls.push(resolved || { kind: 'public' }); | | 355 | + return { | | 356 | + connect: async () => undefined | | 357 | + }; | | 358 | + }) as never; | | 359 | + } | | 360 | + ); | | 361 | + const applicationCtx = { | | 362 | + config: { | | 363 | + path<T>(key: string, fallback?: T) { | | 364 | + const config = { | | 365 | + mcp: {}, | | 366 | + 'mcp.sse.route': '/sse', | | 367 | + 'mcp.messages': '/messages' | | 368 | + } as Record<string, unknown>; | | 369 | + return (key in config ? config[key] : fallback) as T; | | 370 | + }, | | 371 | + has() { | | 372 | + return true; | | 373 | + } | | 374 | + }, | | 375 | + resolve<T = unknown>(event: string) { | | 376 | + if (event === 'application-detail') { | | 377 | + return Promise.resolve({ results: auth.application as T }); | | 378 | + } | | 379 | + return Promise.resolve(null); | | 380 | + } | | 381 | + }; | | 382 | + | | 383 | + attachSseToServer(Object.assign(ctx, applicationCtx) as never); | | 384 | + const requestListener = ctx.listener(); | | 385 | + expect(requestListener).to.be.a('function'); | | 386 | + | | 387 | + await requestListener!({ | | 388 | + req: { | | 389 | + data() { | | 390 | + return null; | | 391 | + }, | | 392 | + resource: makeAttachedRequest({ | | 393 | + method: 'GET', | | 394 | + url: '/sse', | | 395 | + headers: { | | 396 | + host: 'localhost', | | 397 | + authorization: 'Bearer app-1:secret-1' | | 398 | + } | | 399 | + }) | | 400 | + }, | | 401 | + res: { | | 402 | + resource: makeAttachedResponse(), | | 403 | + stop() {} | | 404 | + } | | 405 | + }); | | 406 | + | | 407 | + expect(calls).to.have.length(1); | | 408 | + expect(calls[0]).to.deep.equal(auth); | | 409 | + }); | | 410 | + | 318 | 411 | it('should stop and abort the queue after an attached message request is handled', async () => { | 319 | 412 | const ctx = makeAttachCtx({ | 320 | 413 | 'mcp.sse.route': '/sse', | |
Collapse file Copy file name to clipboardExpand all lines: packages/stackpress-ai/tests/transform.test.ts +8-19Lines changed: 8 additions & 19 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -5,32 +5,21 @@ import path from 'node:path'; | 5 | 5 | //modules | 6 | 6 | import { expect } from 'chai'; | 7 | 7 | import { describe, it } from 'mocha'; | 8 | | -import FileLoader from '@stackpress/lib/FileLoader'; | 9 | | -import { Transformer } from '@stackpress/idea-transformer'; | 10 | | -import { server as http } from '@stackpress/ingest/http'; | 11 | 8 | import { createProject } from 'stackpress-schema/transform/helpers'; | 12 | 9 | //client | 13 | 10 | import generate from '../src/transform/index.js'; | 14 | 11 |
| 15 | 12 | /** | 16 | | - * Build one transformer pointed at the real blog schema fixture. | | 13 | + * Load one persisted blog schema revision so the test exercises real template | | 14 | + * metadata without paying the full transformer parse cost on every run. | 17 | 15 | */ | 18 | | -async function makeBlogSchema() { | 19 | | - //point the transformer at the real blog schema so the test exercises the | 20 | | - // same model metadata the template uses in practice. | 21 | | - const cwd = process.cwd(); | 22 | | - const idea = path.resolve( | | 16 | +function loadBlogSchema() { | | 17 | + const revision = path.resolve( | 23 | 18 | path.dirname(new URL(import.meta.url).pathname), | 24 | | - '../../../templates/blog/schema.idea' | | 19 | + '../../../templates/blog/.build/revisions/1781761934981.json' | 25 | 20 | ); | 26 | | - const server = http({ cwd }); | 27 | | - const loader = new FileLoader(server.loader.fs, server.loader.cwd); | 28 | | - const transformer = new Transformer(idea, loader); | 29 | 21 |
| 30 | | - return { | 31 | | - schema: await transformer.schema(), | 32 | | - transformer | 33 | | - }; | | 22 | + return JSON.parse(fs.readFileSync(revision, 'utf-8')) as Record<string, unknown>; | 34 | 23 | } | 35 | 24 |
| 36 | 25 | describe('ai/transform', () => { | @@ -44,7 +33,7 @@ describe('ai/transform', () => { | 44 | 33 | ); | 45 | 34 | const project = await createProject(tmpdir); | 46 | 35 | const directory = project.createDirectory(tmpdir); | 47 | | - const { schema, transformer } = await makeBlogSchema(); | | 36 | + const schema = loadBlogSchema(); | 48 | 37 |
| 49 | 38 | await generate({ | 50 | 39 | config: {}, | @@ -53,7 +42,7 @@ describe('ai/transform', () => { | 53 | 42 | project, | 54 | 43 | schema, | 55 | 44 | terminal: {} as never, | 56 | | - transformer | | 45 | + transformer: {} as never | 57 | 46 | }); | 58 | 47 |
| 59 | 48 | //inspect the generated registry surface the runtime depends on. | |
|