GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix sse auth and transform timeout 2h · stackpress/stackpress@a8c1707

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/stackpress-ai
    • src/scripts
      • sse.ts
    • tests
      • sse.test.ts
      • transform.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/stackpress-ai/src/scripts/sse.ts‎

Copy file name to clipboardExpand all lines: packages/stackpress-ai/src/scripts/sse.ts
+38-7Lines changed: 38 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,16 @@ import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
66
import type Server from '@stackpress/ingest/Server';
77
//client
88
import type {
9+
AuthContext,
910
McpPlugin,
1011
McpServer,
1112
McpSseSession,
12-
Promiser
13+
Promiser,
14+
ToolResolverServer
1315
} from '../types.js';
1416
import {
1517
readJsonBody,
18+
resolveListAuth,
1619
sendText
1720
} from '../helpers.js';
1821

@@ -63,6 +66,8 @@ export function shouldAttachSseToServer(ctx: Server) {
6366
export class McpSseServer {
6467
//this shutdown handle is exposed so the caller can stop the server cleanly
6568
public readonly shutdown: () => Promise<void>;
69+
//this callback resolves one caller auth context from a raw request
70+
protected _authResolver: (req: IncomingMessage) => Promise<AuthContext>;
6671
//this endpoint accepts the initial SSE connection request
6772
protected _endpoint: string;
6873
//this flag prevents the shutdown path from running more than once
@@ -87,13 +92,15 @@ export class McpSseServer {
8792
*/
8893
public constructor(
8994
factory: McpPlugin,
95+
authResolver: (req: IncomingMessage) => Promise<AuthContext>,
9096
host: string,
9197
port: number,
9298
endpoint: string,
9399
messages: string,
94100
promiser: Promiser<void>
95101
) {
96102
this._factory = factory;
103+
this._authResolver = authResolver;
97104
this._host = host;
98105
this._port = port;
99106
this._endpoint = endpoint;
@@ -161,8 +168,8 @@ export class McpSseServer {
161168
/**
162169
* Resolve one MCP server instance from the registered factory.
163170
*/
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);
166173

167174
//if config produced no tools, fail loudly so the CLI does not hang
168175
if (!server) {
@@ -214,7 +221,7 @@ export class McpSseServer {
214221

215222
//for GET on the SSE endpoint, start one long-lived event stream session
216223
if (req.method === 'GET' && url.pathname === this._endpoint) {
217-
await this._handleSseConnection(res);
224+
await this._handleSseConnection(req, res);
218225
return;
219226
}
220227

@@ -240,14 +247,18 @@ export class McpSseServer {
240247
/**
241248
* Open one SSE session and register it in the live session map.
242249
*/
243-
protected async _handleSseConnection(res: ServerResponse) {
250+
protected async _handleSseConnection(
251+
req: IncomingMessage,
252+
res: ServerResponse
253+
) {
254+
const auth = await this._authResolver(req);
244255
//first build one MCP tool server from the registered factory
245-
const server = await this._createServer();
256+
const server = await this._createServer(auth);
246257

247258
//then pair it with one SSE transport bound to the response stream
248259
const transport = new SSEServerTransport(this._messages, res);
249260
const sessionId = transport.sessionId;
250-
this._sessions[sessionId] = { server, transport };
261+
this._sessions[sessionId] = { auth, server, transport };
251262

252263
//when the transport closes, remove its session from the lookup table
253264
transport.onclose = async () => {
@@ -271,11 +282,18 @@ export default async function sse(ctx: Server) {
271282

272283
const factory = ctx.plugin<McpPlugin>('mcp');
273284
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+
);
274291

275292
//then keep the event open until the underlying HTTP service closes
276293
return new Promise<void>(async (resolve, reject) => {
277294
const transport = new McpSseServer(
278295
factory,
296+
authResolver,
279297
host,
280298
port,
281299
endpoint,
@@ -302,8 +320,13 @@ export function attachSseToServer(ctx: Server) {
302320

303321
attachable[key] = true;
304322
const factory = ctx.plugin<McpPlugin>('mcp');
323+
const authResolver = async (req: IncomingMessage) => resolveListAuth(
324+
ctx as ToolResolverServer,
325+
header(req, 'authorization') || undefined
326+
);
305327
const transport = new McpSseServer(
306328
factory,
329+
authResolver,
307330
host,
308331
port,
309332
endpoint,
@@ -341,3 +364,11 @@ export function attachSseToServer(ctx: Server) {
341364
}
342365
});
343366
}
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

‎packages/stackpress-ai/tests/sse.test.ts‎

Copy file name to clipboardExpand all lines: packages/stackpress-ai/tests/sse.test.ts
+99-6Lines changed: 99 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
expectJson,
1515
MockResponse
1616
} from './helpers.js';
17+
import type { AuthContext } from '../src/types.js';
1718

1819
type MessageResponse = {
1920
jsonrpc: '2.0';
@@ -47,6 +48,7 @@ type TestTransport = {
4748
//this narrowed session map lets the subclass update protected state without
4849
// leaning on any-casts.
4950
type SessionStore = Record<string, {
51+
auth: AuthContext,
5052
server: { close: () => Promise<void> },
5153
transport: TestTransport
5254
}>;
@@ -75,9 +77,13 @@ class TestSseServer extends McpSseServer {
7577
/**
7678
* Create one fake SSE session and immediately write a handshake response.
7779
*/
78-
protected override async _handleSseConnection(res: ServerResponse) {
80+
protected override async _handleSseConnection(
81+
req: IncomingMessage,
82+
res: ServerResponse
83+
) {
7984
this.created++;
8085
const sessionId = `sse-${this.created}`;
86+
const auth = await this._authResolver(req);
8187
const server = {
8288
close: async () => undefined
8389
};
@@ -108,16 +114,21 @@ class TestSseServer extends McpSseServer {
108114
}
109115
};
110116

111-
sessions[sessionId] = { server, transport };
117+
sessions[sessionId] = { auth, server, transport };
112118
res.statusCode = 200;
113119
res.setHeader('Content-Type', 'text/event-stream');
114120
res.end(`event: endpoint\ndata: ${JSON.stringify({ sessionId })}\n\n`);
115121
}
116122
}
117123

118-
function makeServer() {
124+
function makeServer(
125+
authResolver: (req: IncomingMessage) => Promise<AuthContext> = async () => {
126+
return { kind: 'public' };
127+
}
128+
) {
119129
return new TestSseServer(
120130
async () => null,
131+
authResolver,
121132
'127.0.0.1',
122133
17759,
123134
'/sse',
@@ -137,7 +148,8 @@ type ConfigStub = {
137148
path<T>(key: string, fallback?: T): T
138149
},
139150
on?: (event: string, listener: Function) => void,
140-
plugin?: <T = unknown>(name: string) => T
151+
plugin?: <T = unknown>(name: string) => T,
152+
listener?: () => Function | undefined
141153
};
142154

143155
/**
@@ -158,7 +170,10 @@ function makeCtx(config: Record<string, unknown> = {}) {
158170
/**
159171
* Create one minimal attached-server stub that captures the request listener.
160172
*/
161-
function makeAttachCtx(config: Record<string, unknown> = {}) {
173+
function makeAttachCtx(
174+
config: Record<string, unknown> = {},
175+
pluginFactory?: <T = unknown>(name: string) => T
176+
) {
162177
let listener: Function | undefined;
163178
const ctx: ConfigStub & {
164179
listener: () => Function | undefined
@@ -173,7 +188,10 @@ function makeAttachCtx(config: Record<string, unknown> = {}) {
173188
listener = callback;
174189
}
175190
},
176-
plugin<T = unknown>() {
191+
plugin<T = unknown>(name: string) {
192+
if (pluginFactory) {
193+
return pluginFactory<T>(name);
194+
}
177195
return (async () => null) as T;
178196
},
179197
listener() {
@@ -315,6 +333,81 @@ describe('ai/sse', () => {
315333
expect(resolved.port).to.equal(18888);
316334
});
317335

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+
318411
it('should stop and abort the queue after an attached message request is handled', async () => {
319412
const ctx = makeAttachCtx({
320413
'mcp.sse.route': '/sse',
Collapse file

‎packages/stackpress-ai/tests/transform.test.ts‎

Copy file name to clipboardExpand all lines: packages/stackpress-ai/tests/transform.test.ts
+8-19Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -5,32 +5,21 @@ import path from 'node:path';
55
//modules
66
import { expect } from 'chai';
77
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';
118
import { createProject } from 'stackpress-schema/transform/helpers';
129
//client
1310
import generate from '../src/transform/index.js';
1411

1512
/**
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.
1715
*/
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(
2318
path.dirname(new URL(import.meta.url).pathname),
24-
'../../../templates/blog/schema.idea'
19+
'../../../templates/blog/.build/revisions/1781761934981.json'
2520
);
26-
const server = http({ cwd });
27-
const loader = new FileLoader(server.loader.fs, server.loader.cwd);
28-
const transformer = new Transformer(idea, loader);
2921

30-
return {
31-
schema: await transformer.schema(),
32-
transformer
33-
};
22+
return JSON.parse(fs.readFileSync(revision, 'utf-8')) as Record<string, unknown>;
3423
}
3524

3625
describe('ai/transform', () => {
@@ -44,7 +33,7 @@ describe('ai/transform', () => {
4433
);
4534
const project = await createProject(tmpdir);
4635
const directory = project.createDirectory(tmpdir);
47-
const { schema, transformer } = await makeBlogSchema();
36+
const schema = loadBlogSchema();
4837

4938
await generate({
5039
config: {},
@@ -53,7 +42,7 @@ describe('ai/transform', () => {
5342
project,
5443
schema,
5544
terminal: {} as never,
56-
transformer
45+
transformer: {} as never
5746
});
5847

5948
//inspect the generated registry surface the runtime depends on.

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.