mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
refactor(server): move health, discovery and consent-COOP behind the container
This commit is contained in:
@@ -59,6 +59,7 @@ import { resetTestDb, resetRateLimits } from '../helpers/test-db';
|
||||
import { createUser } from '../helpers/factories';
|
||||
import { authCookie } from '../helpers/auth';
|
||||
import { createOAuthClient, getUserByAccessToken } from '../../src/nest/oauth/oauth.bridge';
|
||||
import { ALL_SCOPES } from '../../src/mcp/scopes';
|
||||
import { OauthService } from '../../src/nest/oauth/oauth.service';
|
||||
import { DatabaseService } from '../../src/nest/database/database.service';
|
||||
import { AddonsService } from '../../src/nest/addons/addons.service';
|
||||
@@ -164,6 +165,87 @@ describe('DCR scope optional — ChatGPT compatibility (issue #959 bug 2)', () =
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Platform/discovery parity pins — byte-level oracles for the MCP/OAuth mount
|
||||
// migration (these must pass identically before AND after the routes move
|
||||
// behind the Nest container).
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('platform/discovery parity pins', () => {
|
||||
it('PLAT-PIN-001 — GET /api/health returns the exact probe body + Cache-Control', async () => {
|
||||
const res = await request(app).get('/api/health');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['cache-control']).toBe('no-store, must-revalidate');
|
||||
expect(res.body).toEqual({ status: 'ok' });
|
||||
});
|
||||
|
||||
it('PLAT-PIN-002 — openid-configuration is the AS metadata plus userinfo_endpoint, exactly', async () => {
|
||||
const res = await request(app).get('/.well-known/openid-configuration');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
issuer: 'https://trek.example.com',
|
||||
authorization_endpoint: 'https://trek.example.com/oauth/authorize',
|
||||
token_endpoint: 'https://trek.example.com/oauth/token',
|
||||
revocation_endpoint: 'https://trek.example.com/oauth/revoke',
|
||||
registration_endpoint: 'https://trek.example.com/oauth/register',
|
||||
response_types_supported: ['code'],
|
||||
grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'],
|
||||
code_challenge_methods_supported: ['S256'],
|
||||
token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],
|
||||
scopes_supported: ALL_SCOPES,
|
||||
userinfo_endpoint: 'https://trek.example.com/oauth/userinfo',
|
||||
});
|
||||
});
|
||||
|
||||
it('PLAT-PIN-003 — flat oauth-protected-resource is the exact 5-key RFC 9728 document', async () => {
|
||||
const res = await request(app).get('/.well-known/oauth-protected-resource');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
resource: 'https://trek.example.com/mcp',
|
||||
authorization_servers: ['https://trek.example.com'],
|
||||
bearer_methods_supported: ['header'],
|
||||
scopes_supported: ALL_SCOPES,
|
||||
resource_name: 'TREK MCP',
|
||||
});
|
||||
});
|
||||
|
||||
it('PLAT-PIN-004 — every /.well-known/* path 404s with an EMPTY body when MCP is disabled', async () => {
|
||||
setMcpEnabled(false);
|
||||
for (const path of [
|
||||
'/.well-known/openid-configuration',
|
||||
'/.well-known/oauth-protected-resource',
|
||||
'/.well-known/oauth-authorization-server',
|
||||
]) {
|
||||
const res = await request(app).get(path);
|
||||
expect(res.status, path).toBe(404);
|
||||
expect(res.text, path).toBe('');
|
||||
}
|
||||
});
|
||||
|
||||
it('PLAT-PIN-005 — an unhandled /.well-known path gets the JSON 404, never SPA HTML', async () => {
|
||||
const res = await request(app).get('/.well-known/does-not-exist');
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'not_found' });
|
||||
});
|
||||
|
||||
it('PLAT-PIN-006 — /.well-known/ (trailing slash) also gets the JSON 404', async () => {
|
||||
const res = await request(app).get('/.well-known/');
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'not_found' });
|
||||
});
|
||||
|
||||
it('PLAT-PIN-007 — bare /.well-known falls through to the router 404 envelope', async () => {
|
||||
const res = await request(app).get('/.well-known');
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Cannot GET /.well-known' });
|
||||
});
|
||||
|
||||
it('PLAT-PIN-008 — /oauth/consent responses carry the relaxed COOP header', async () => {
|
||||
const res = await request(app).get('/oauth/consent');
|
||||
expect(res.headers['cross-origin-opener-policy']).toBe('unsafe-none');
|
||||
});
|
||||
});
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// POST /oauth/token — authorization_code grant
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
|
||||
const h = vi.hoisted(() => ({
|
||||
getMcpSafeUrl: vi.fn(() => 'https://trek.example.test'),
|
||||
// The SDK factory returns a tagged middleware so tests can identify delegation
|
||||
// without running real router wiring.
|
||||
metaRouter: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../src/app-config', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../src/app-config')>();
|
||||
return { ...actual, getMcpSafeUrl: h.getMcpSafeUrl };
|
||||
});
|
||||
vi.mock('@modelcontextprotocol/sdk/server/auth/router', () => ({
|
||||
mcpAuthMetadataRouter: vi.fn(() => h.metaRouter),
|
||||
}));
|
||||
|
||||
import { mcpAuthMetadataRouter } from '@modelcontextprotocol/sdk/server/auth/router';
|
||||
import { DiscoveryMetadataService } from '../../../src/nest/platform/discovery-metadata.service';
|
||||
import {
|
||||
MCP_METADATA_MIDDLEWARE,
|
||||
createMcpMetadataMiddleware,
|
||||
mcpMetadataMiddlewareProvider,
|
||||
} from '../../../src/nest/platform/mcp-metadata.middleware';
|
||||
import { ConsentCoopMiddleware } from '../../../src/nest/platform/consent-coop.middleware';
|
||||
import { DiscoveryController } from '../../../src/nest/platform/discovery.controller';
|
||||
import { PlatformModule } from '../../../src/nest/platform/platform.module';
|
||||
import { ALL_SCOPES } from '../../../src/mcp/scopes';
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
|
||||
function makeRes() {
|
||||
const res = {
|
||||
statusCode: 200,
|
||||
body: undefined as unknown,
|
||||
headers: {} as Record<string, string>,
|
||||
ended: false,
|
||||
status: vi.fn(function (this: typeof res, c: number) { this.statusCode = c; return this; }),
|
||||
json: vi.fn(function (this: typeof res, b: unknown) { this.body = b; return this; }),
|
||||
end: vi.fn(function (this: typeof res) { this.ended = true; return this; }),
|
||||
setHeader: vi.fn(function (this: typeof res, k: string, v: string) { this.headers[k] = v; return this; }),
|
||||
};
|
||||
return res;
|
||||
}
|
||||
|
||||
function addons(enabled: boolean) {
|
||||
return { isAddonEnabled: vi.fn(() => enabled) } as unknown as AddonsService;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
h.getMcpSafeUrl.mockReturnValue('https://trek.example.test');
|
||||
});
|
||||
|
||||
describe('DiscoveryMetadataService', () => {
|
||||
it('DISC-001: builds the RFC 8414 AS metadata from the live safe URL', () => {
|
||||
const meta = new DiscoveryMetadataService().getOAuthMetadata();
|
||||
expect(meta).toEqual({
|
||||
issuer: 'https://trek.example.test',
|
||||
authorization_endpoint: 'https://trek.example.test/oauth/authorize',
|
||||
token_endpoint: 'https://trek.example.test/oauth/token',
|
||||
revocation_endpoint: 'https://trek.example.test/oauth/revoke',
|
||||
registration_endpoint: 'https://trek.example.test/oauth/register',
|
||||
response_types_supported: ['code'],
|
||||
grant_types_supported: ['authorization_code', 'refresh_token', 'client_credentials'],
|
||||
code_challenge_methods_supported: ['S256'],
|
||||
token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],
|
||||
scopes_supported: ALL_SCOPES,
|
||||
});
|
||||
});
|
||||
|
||||
it('DISC-002: trims trailing slashes off the configured base URL', () => {
|
||||
h.getMcpSafeUrl.mockReturnValue('https://trek.example.test///');
|
||||
expect(new DiscoveryMetadataService().getOAuthMetadata().issuer).toBe('https://trek.example.test');
|
||||
});
|
||||
|
||||
it('DISC-003: caches the metadata after the first lazy build', () => {
|
||||
const svc = new DiscoveryMetadataService();
|
||||
const first = svc.getOAuthMetadata();
|
||||
expect(svc.getOAuthMetadata()).toBe(first);
|
||||
expect(h.getMcpSafeUrl).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('DISC-004: builds the SDK metadata router once, pointing at the /mcp resource', () => {
|
||||
const svc = new DiscoveryMetadataService();
|
||||
expect(svc.getMetaRouter()).toBe(h.metaRouter);
|
||||
expect(svc.getMetaRouter()).toBe(h.metaRouter);
|
||||
expect(mcpAuthMetadataRouter).toHaveBeenCalledTimes(1);
|
||||
const opts = vi.mocked(mcpAuthMetadataRouter).mock.calls[0][0];
|
||||
expect(opts.resourceServerUrl.href).toBe('https://trek.example.test/mcp');
|
||||
expect(opts.resourceName).toBe('TREK MCP');
|
||||
expect(opts.scopesSupported).toEqual(ALL_SCOPES);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMcpMetadataMiddleware', () => {
|
||||
it('DISC-010: 404s a /.well-known path with an empty body when MCP is disabled', () => {
|
||||
const mw = createMcpMetadataMiddleware(new DiscoveryMetadataService(), addons(false));
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
mw({ path: '/.well-known/oauth-authorization-server' } as never, res as never, next);
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.ended).toBe(true);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
expect(h.metaRouter).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('DISC-011: delegates a /.well-known path to the SDK router when MCP is enabled', () => {
|
||||
const mw = createMcpMetadataMiddleware(new DiscoveryMetadataService(), addons(true));
|
||||
const next = vi.fn();
|
||||
mw({ path: '/.well-known/oauth-authorization-server' } as never, makeRes() as never, next);
|
||||
expect(h.metaRouter).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('DISC-012: delegates non-well-known paths without consulting the addon gate', () => {
|
||||
const gate = addons(false);
|
||||
const mw = createMcpMetadataMiddleware(new DiscoveryMetadataService(), gate);
|
||||
mw({ path: '/api/trips' } as never, makeRes() as never, vi.fn());
|
||||
expect(gate.isAddonEnabled).not.toHaveBeenCalled();
|
||||
expect(h.metaRouter).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('DISC-013: the factory provider wires the token to the factory with its two deps', () => {
|
||||
expect(mcpMetadataMiddlewareProvider.provide).toBe(MCP_METADATA_MIDDLEWARE);
|
||||
expect(mcpMetadataMiddlewareProvider.useFactory).toBe(createMcpMetadataMiddleware);
|
||||
expect(mcpMetadataMiddlewareProvider.inject.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ConsentCoopMiddleware', () => {
|
||||
it('DISC-020: relaxes COOP then continues', () => {
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
new ConsentCoopMiddleware().use({} as never, res as never, next);
|
||||
expect(res.headers['Cross-Origin-Opener-Policy']).toBe('unsafe-none');
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('DiscoveryController', () => {
|
||||
function controller(enabled = true) {
|
||||
return new DiscoveryController(new DiscoveryMetadataService(), addons(enabled));
|
||||
}
|
||||
|
||||
it('DISC-030: openid-configuration is the AS metadata plus userinfo_endpoint', () => {
|
||||
const res = makeRes();
|
||||
controller().openidConfiguration(res as never);
|
||||
const body = res.body as { issuer: string; userinfo_endpoint: string };
|
||||
expect(body.issuer).toBe('https://trek.example.test');
|
||||
expect(body.userinfo_endpoint).toBe('https://trek.example.test/oauth/userinfo');
|
||||
});
|
||||
|
||||
it('DISC-031: flat oauth-protected-resource 404s empty when MCP is disabled', () => {
|
||||
const res = makeRes();
|
||||
controller(false).protectedResource(res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.ended).toBe(true);
|
||||
});
|
||||
|
||||
it('DISC-032: flat oauth-protected-resource serves the PRM document when enabled', () => {
|
||||
const res = makeRes();
|
||||
controller().protectedResource(res as never);
|
||||
expect(res.body).toEqual({
|
||||
resource: 'https://trek.example.test/mcp',
|
||||
authorization_servers: ['https://trek.example.test'],
|
||||
bearer_methods_supported: ['header'],
|
||||
scopes_supported: ALL_SCOPES,
|
||||
resource_name: 'TREK MCP',
|
||||
});
|
||||
});
|
||||
|
||||
it('DISC-033: the catchall answers 404 JSON, never throwing into the SPA fallback', () => {
|
||||
const res = makeRes();
|
||||
controller().wellKnownFallback(res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'not_found' });
|
||||
});
|
||||
|
||||
it('DISC-034: /.well-known/ (trailing slash) gets the same 404 JSON', () => {
|
||||
const res = makeRes();
|
||||
controller().wellKnownRoot({ path: '/.well-known/' } as never, res as never);
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'not_found' });
|
||||
});
|
||||
|
||||
it('DISC-035: bare /.well-known reproduces the framework 404 (SpaFallback route)', () => {
|
||||
const req = { path: '/.well-known', method: 'GET', originalUrl: '/.well-known' };
|
||||
expect(() => controller().wellKnownRoot(req as never, makeRes() as never))
|
||||
.toThrowError(new NotFoundException('Cannot GET /.well-known'));
|
||||
});
|
||||
|
||||
it('DISC-036: route declaration order keeps the concrete documents ahead of the catchalls', () => {
|
||||
// Nest registers routes in method-declaration order; the catchall must not
|
||||
// shadow the concrete documents.
|
||||
const names = Object.getOwnPropertyNames(DiscoveryController.prototype).filter((n) => n !== 'constructor');
|
||||
expect(names.indexOf('openidConfiguration')).toBeLessThan(names.indexOf('wellKnownRoot'));
|
||||
expect(names.indexOf('protectedResource')).toBeLessThan(names.indexOf('wellKnownRoot'));
|
||||
expect(names.indexOf('wellKnownRoot')).toBeLessThan(names.indexOf('wellKnownFallback'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('PlatformModule', () => {
|
||||
it('DISC-040: applies the consent COOP middleware to the /oauth/consent prefix', () => {
|
||||
const forRoutes = vi.fn();
|
||||
const consumer = { apply: vi.fn(() => ({ forRoutes })) };
|
||||
new PlatformModule().configure(consumer as never);
|
||||
expect(consumer.apply).toHaveBeenCalledWith(ConsentCoopMiddleware);
|
||||
expect(forRoutes).toHaveBeenCalledWith('oauth/consent');
|
||||
});
|
||||
});
|
||||
@@ -70,4 +70,17 @@ describe('FeaturesController (GET /api/health/features)', () => {
|
||||
expect(Reflect.getMetadata('path', FeaturesController)).toBe('api/health');
|
||||
expect(Reflect.getMetadata('path', FeaturesController.prototype.features)).toBe('features');
|
||||
});
|
||||
|
||||
it('FEAT-009: GET /api/health writes the exact probe bytes (legacy parity)', () => {
|
||||
const { controller } = make(true, true);
|
||||
const res = {
|
||||
headers: {} as Record<string, string>,
|
||||
body: undefined as unknown,
|
||||
setHeader: vi.fn(function (this: { headers: Record<string, string> }, k: string, v: string) { this.headers[k] = v; }),
|
||||
json: vi.fn(function (this: { body: unknown }, b: unknown) { this.body = b; }),
|
||||
};
|
||||
controller.health(res as never);
|
||||
expect(res.headers['Cache-Control']).toBe('no-store, must-revalidate');
|
||||
expect(res.body).toEqual({ status: 'ok' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,12 +5,10 @@ import { NotFoundException } from '@nestjs/common';
|
||||
const h = vi.hoisted(() => ({
|
||||
verifyJwtAndLoadUser: vi.fn(),
|
||||
isAddonEnabled: vi.fn(),
|
||||
getMcpSafeUrl: vi.fn(() => 'https://trek.example.test'),
|
||||
dbPrepare: vi.fn(),
|
||||
existsSync: vi.fn(),
|
||||
// SDK middleware spies — each returns a tagged handler so we can identify which
|
||||
// app.use call received it.
|
||||
metaRouter: vi.fn(),
|
||||
authorizeHandler: vi.fn(),
|
||||
registerHandler: vi.fn(),
|
||||
mcpHandler: vi.fn(),
|
||||
@@ -21,16 +19,9 @@ vi.mock('../../../src/db/database', () => ({ db: { prepare: h.dbPrepare } }));
|
||||
vi.mock('../../../src/mcp', () => ({ mcpHandler: h.mcpHandler }));
|
||||
vi.mock('../../../src/mcp/oauthProvider', () => ({ trekOAuthProvider: {}, trekClientsStore: {} }));
|
||||
vi.mock('../../../src/nest/addons/addons.bridge', () => ({ isAddonEnabled: h.isAddonEnabled }));
|
||||
vi.mock('../../../src/app-config', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../../src/app-config')>();
|
||||
return { ...actual, getMcpSafeUrl: h.getMcpSafeUrl };
|
||||
});
|
||||
|
||||
// SDK router/handler factories return distinct tagged middleware so we never hit
|
||||
// real new URL(...) wiring during registration.
|
||||
vi.mock('@modelcontextprotocol/sdk/server/auth/router', () => ({
|
||||
mcpAuthMetadataRouter: vi.fn(() => h.metaRouter),
|
||||
}));
|
||||
// SDK handler factories return distinct tagged middleware so we never hit real
|
||||
// wiring during registration.
|
||||
vi.mock('@modelcontextprotocol/sdk/server/auth/handlers/authorize', () => ({
|
||||
authorizationHandler: vi.fn(() => h.authorizeHandler),
|
||||
}));
|
||||
@@ -101,7 +92,6 @@ function makeRes() {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
h.getMcpSafeUrl.mockReturnValue('https://trek.example.test');
|
||||
});
|
||||
|
||||
describe('applyPlatformUploads', () => {
|
||||
@@ -234,91 +224,6 @@ describe('applyPlatformTransport', () => {
|
||||
return calls;
|
||||
}
|
||||
|
||||
it('GET /api/health sets no-store and returns ok', () => {
|
||||
const calls = build();
|
||||
const health = calls.find((c) => c.method === 'get' && c.path === '/api/health')!.handlers[0];
|
||||
const res = makeRes();
|
||||
health({}, res);
|
||||
expect(res.headers['Cache-Control']).toBe('no-store, must-revalidate');
|
||||
expect(res.body).toEqual({ status: 'ok' });
|
||||
});
|
||||
|
||||
describe('the /.well-known metadata middleware', () => {
|
||||
function wellKnownMw(calls: ReturnType<typeof build>) {
|
||||
// first app.use with no path, registered right after /api/health
|
||||
return calls.find((c) => c.method === 'use' && c.path === undefined)!.handlers[0];
|
||||
}
|
||||
|
||||
it('404s a /.well-known path when MCP is disabled', () => {
|
||||
h.isAddonEnabled.mockReturnValue(false);
|
||||
const mw = wellKnownMw(build());
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
mw({ path: '/.well-known/oauth-authorization-server' }, res, next);
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('delegates to the SDK meta router for a non-well-known path', () => {
|
||||
h.isAddonEnabled.mockReturnValue(true);
|
||||
const mw = wellKnownMw(build());
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
mw({ path: '/anything' }, res, next);
|
||||
expect(h.metaRouter).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('delegates to the SDK meta router for a well-known path when MCP is enabled', () => {
|
||||
h.isAddonEnabled.mockReturnValue(true);
|
||||
const mw = wellKnownMw(build());
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
mw({ path: '/.well-known/oauth-authorization-server' }, res, next);
|
||||
expect(h.metaRouter).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('GET /.well-known/openid-configuration returns AS metadata + userinfo_endpoint', () => {
|
||||
const calls = build();
|
||||
const handler = calls.find((c) => c.path === '/.well-known/openid-configuration')!.handlers[0];
|
||||
const res = makeRes();
|
||||
handler({}, res);
|
||||
const body = res.body as { issuer: string; userinfo_endpoint: string };
|
||||
expect(body.issuer).toBe('https://trek.example.test');
|
||||
expect(body.userinfo_endpoint).toBe('https://trek.example.test/oauth/userinfo');
|
||||
});
|
||||
|
||||
it('trims trailing slashes off the configured base URL', () => {
|
||||
h.getMcpSafeUrl.mockReturnValue('https://trek.example.test///');
|
||||
const calls = build();
|
||||
const handler = calls.find((c) => c.path === '/.well-known/openid-configuration')!.handlers[0];
|
||||
const res = makeRes();
|
||||
handler({}, res);
|
||||
expect((res.body as { issuer: string }).issuer).toBe('https://trek.example.test');
|
||||
});
|
||||
|
||||
describe('GET /.well-known/oauth-protected-resource (flat)', () => {
|
||||
function handler() {
|
||||
return build().find((c) => c.method === 'get' && c.path === '/.well-known/oauth-protected-resource')!.handlers[0];
|
||||
}
|
||||
|
||||
it('404 when MCP is disabled', () => {
|
||||
h.isAddonEnabled.mockReturnValue(false);
|
||||
const res = makeRes();
|
||||
handler()({}, res);
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('returns the PRM document when MCP is enabled', () => {
|
||||
h.isAddonEnabled.mockReturnValue(true);
|
||||
const res = makeRes();
|
||||
handler()({}, res);
|
||||
const body = res.body as { resource: string; authorization_servers: string[] };
|
||||
expect(body.resource).toBe('https://trek.example.test/mcp');
|
||||
expect(body.authorization_servers).toEqual(['https://trek.example.test']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mcpAddonGate (used on /oauth/authorize + /oauth/register)', () => {
|
||||
function gate() {
|
||||
// The gate is the first handler on the /oauth/authorize use registration.
|
||||
@@ -357,60 +262,6 @@ describe('applyPlatformTransport', () => {
|
||||
expect(calls.find((c) => c.method === 'get' && c.path === '/mcp')!.handlers[0]).toBe(h.mcpHandler);
|
||||
expect(calls.find((c) => c.method === 'delete' && c.path === '/mcp')!.handlers[0]).toBe(h.mcpHandler);
|
||||
});
|
||||
|
||||
describe('the terminal /.well-known JSON-404 middleware', () => {
|
||||
function mw() {
|
||||
// The pathless app.use registered after the /mcp routes.
|
||||
const calls = build();
|
||||
const pathless = calls.filter((c) => c.method === 'use' && c.path === undefined);
|
||||
// first pathless = meta router; second = the JSON 404.
|
||||
return pathless[1].handlers[0];
|
||||
}
|
||||
|
||||
it('404 JSON for an unhandled /.well-known path', () => {
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
mw()({ path: '/.well-known/unknown' }, res, next);
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'not_found' });
|
||||
expect(next).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('calls next() for any non-well-known path', () => {
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
mw()({ path: '/dashboard' }, res, next);
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('the /oauth/consent middleware relaxes COOP then continues', () => {
|
||||
const calls = build();
|
||||
const mw = calls.find((c) => c.method === 'use' && c.path === '/oauth/consent')!.handlers[0];
|
||||
const res = makeRes();
|
||||
const next = vi.fn();
|
||||
mw({}, res, next);
|
||||
expect(res.headers['Cross-Origin-Opener-Policy']).toBe('unsafe-none');
|
||||
expect(next).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('caches the OAuth metadata + SDK router across requests (lazy init runs once)', async () => {
|
||||
const router = await import('@modelcontextprotocol/sdk/server/auth/router');
|
||||
const calls = build();
|
||||
const openid = calls.find((c) => c.path === '/.well-known/openid-configuration')!.handlers[0];
|
||||
h.getMcpSafeUrl.mockClear();
|
||||
openid({}, makeRes());
|
||||
openid({}, makeRes());
|
||||
// getMcpSafeUrl is only consulted on the first lazy build of the metadata.
|
||||
expect(h.getMcpSafeUrl).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Trigger the meta router lazy build twice; the SDK factory runs once.
|
||||
const metaMw = calls.find((c) => c.method === 'use' && c.path === undefined)!.handlers[0];
|
||||
h.isAddonEnabled.mockReturnValue(true);
|
||||
metaMw({ path: '/x' }, makeRes(), vi.fn());
|
||||
metaMw({ path: '/y' }, makeRes(), vi.fn());
|
||||
expect(router.mcpAuthMetadataRouter).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('applyPlatformStatic', () => {
|
||||
|
||||
Reference in New Issue
Block a user