Skip to content

Commit ce58234

Browse files
committed
auth examples - demo flag, configs
1 parent 4c29404 commit ce58234

5 files changed

Lines changed: 50 additions & 38 deletions

File tree

examples/server/src/elicitationUrlExample.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ let authMiddleware = null;
235235
const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`);
236236
const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`);
237237

238-
setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: true });
238+
setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: true, demoMode: true });
239239

240240
// Add protected resource metadata route to the MCP server
241241
// This allows clients to discover the auth server

examples/server/src/simpleStreamableHttp.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -527,7 +527,7 @@ if (useOAuth) {
527527
const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`);
528528
const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`);
529529

530-
setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: strictOAuth });
530+
setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: strictOAuth, demoMode: true });
531531

532532
// Add protected resource metadata route to the MCP server
533533
// This allows clients to discover the auth server

examples/shared/src/auth.ts

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
import { randomBytes } from 'node:crypto';
1111

12+
import type { BetterAuthOptions } from 'better-auth';
1213
import { betterAuth } from 'better-auth';
1314
import { mcp } from 'better-auth/plugins';
1415
import Database from 'better-sqlite3';
@@ -173,6 +174,7 @@ export interface CreateDemoAuthOptions {
173174
baseURL: string;
174175
resource?: string;
175176
loginPage?: string;
177+
demoMode: boolean;
176178
}
177179

178180
/**
@@ -186,7 +188,7 @@ export interface CreateDemoAuthOptions {
186188
* @see https://www.better-auth.com/docs/plugins/mcp
187189
*/
188190
export function createDemoAuth(options: CreateDemoAuthOptions) {
189-
const { baseURL, resource, loginPage = '/sign-in' } = options;
191+
const { baseURL, resource, loginPage = '/sign-in', demoMode } = options;
190192

191193
// Use in-memory SQLite database for demo purposes
192194
// Note: All data is lost on restart - demo only!
@@ -214,28 +216,30 @@ export function createDemoAuth(options: CreateDemoAuthOptions) {
214216
baseURL,
215217
// eslint-disable-next-line @typescript-eslint/no-explicit-any
216218
database: db as any, // Type cast to avoid exposing better-sqlite3 in exported types
217-
trustedOrigins: ['*'],
219+
trustedOrigins: [baseURL.toString()],
218220
// Basic email+password for demo
219221
emailAndPassword: {
220222
enabled: true,
221223
requireEmailVerification: false
222224
},
223225
plugins: [mcpPlugin],
224226
// Enable verbose logging for demo/debugging
225-
logger: {
226-
disabled: false,
227-
level: 'debug',
228-
log: (level, message, ...args) => {
229-
const timestamp = new Date().toISOString();
230-
const prefix = `[Auth ${level.toUpperCase()}]`;
231-
if (args.length > 0) {
232-
console.log(`${timestamp} ${prefix} ${message}`, ...args);
233-
} else {
234-
console.log(`${timestamp} ${prefix} ${message}`);
235-
}
236-
}
237-
}
238-
});
227+
logger: demoMode
228+
? {
229+
disabled: false,
230+
level: 'debug',
231+
log: (level, message, ...args) => {
232+
const timestamp = new Date().toISOString();
233+
const prefix = `[Auth ${level.toUpperCase()}]`;
234+
if (args.length > 0) {
235+
console.log(`${timestamp} ${prefix} ${message}`, ...args);
236+
} else {
237+
console.log(`${timestamp} ${prefix} ${message}`);
238+
}
239+
}
240+
}
241+
: undefined
242+
} satisfies BetterAuthOptions);
239243
}
240244

241245
/**

examples/shared/src/authServer.ts

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ export interface SetupAuthServerOptions {
2121
authServerUrl: URL;
2222
mcpServerUrl: URL;
2323
strictResource?: boolean;
24+
/**
25+
* Examples should be used for **demo** only and not for production purposes, however this mode disables some logging and other features.
26+
*/
27+
demoMode: boolean;
2428
}
2529

2630
// Store auth instance globally so it can be used for token verification
@@ -75,13 +79,14 @@ async function ensureDemoUserExists(auth: DemoAuth): Promise<void> {
7579
* @param options - Server configuration
7680
*/
7781
export function setupAuthServer(options: SetupAuthServerOptions): void {
78-
const { authServerUrl, mcpServerUrl } = options;
82+
const { authServerUrl, mcpServerUrl, demoMode } = options;
7983

8084
// Create better-auth instance with MCP plugin
8185
const auth = createDemoAuth({
8286
baseURL: authServerUrl.toString().replace(/\/$/, ''),
8387
resource: mcpServerUrl.toString(),
84-
loginPage: '/sign-in'
88+
loginPage: '/sign-in',
89+
demoMode: demoMode
8590
});
8691

8792
// Store globally for token verification
@@ -111,23 +116,25 @@ export function setupAuthServer(options: SetupAuthServerOptions): void {
111116
console.log(`${timestamp} [Auth Request] Content-Type: ${req.headers['content-type']}`);
112117
}
113118

114-
// Log response when it finishes
115-
const originalSend = res.send.bind(res);
116-
res.send = function (body) {
117-
console.log(`${timestamp} [Auth Response] ${res.statusCode} ${req.url}`);
118-
if (res.statusCode >= 400 && body) {
119-
try {
120-
const parsed = typeof body === 'string' ? JSON.parse(body) : body;
121-
console.log(`${timestamp} [Auth Response] Error:`, parsed);
122-
} catch {
123-
// Not JSON, log as-is if short
124-
if (typeof body === 'string' && body.length < 200) {
125-
console.log(`${timestamp} [Auth Response] Body: ${body}`);
119+
if (demoMode) {
120+
// Log response when it finishes
121+
const originalSend = res.send.bind(res);
122+
res.send = function (body) {
123+
console.log(`${timestamp} [Auth Response] ${res.statusCode} ${req.url}`);
124+
if (res.statusCode >= 400 && body) {
125+
try {
126+
const parsed = typeof body === 'string' ? JSON.parse(body) : body;
127+
console.log(`${timestamp} [Auth Response] Error:`, parsed);
128+
} catch {
129+
// Not JSON, log as-is if short
130+
if (typeof body === 'string' && body.length < 200) {
131+
console.log(`${timestamp} [Auth Response] Body: ${body}`);
132+
}
126133
}
127134
}
128-
}
129-
return originalSend(body);
130-
};
135+
return originalSend(body);
136+
};
137+
}
131138
next();
132139
});
133140

@@ -137,7 +144,6 @@ export function setupAuthServer(options: SetupAuthServerOptions): void {
137144

138145
// OAuth metadata endpoints using better-auth's built-in handlers
139146
authApp.get('/.well-known/oauth-authorization-server', toNodeHandler(oAuthDiscoveryMetadata(auth)));
140-
authApp.get('/.well-known/oauth-protected-resource', toNodeHandler(oAuthProtectedResourceMetadata(auth)));
141147

142148
// Body parsers for non-better-auth routes (like /sign-in)
143149
authApp.use(express.json());

examples/shared/test/demoInMemoryOAuthProvider.test.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ describe('createDemoAuth', () => {
1616
const validOptions: CreateDemoAuthOptions = {
1717
baseURL: 'http://localhost:3001',
1818
resource: 'http://localhost:3000/mcp',
19-
loginPage: '/sign-in'
19+
loginPage: '/sign-in',
20+
demoMode: true
2021
};
2122

2223
it('creates a better-auth instance with MCP plugin', () => {
@@ -27,7 +28,8 @@ describe('createDemoAuth', () => {
2728

2829
it('uses default loginPage when not specified', () => {
2930
const options: CreateDemoAuthOptions = {
30-
baseURL: 'http://localhost:3001'
31+
baseURL: 'http://localhost:3001',
32+
demoMode: true
3133
};
3234
const auth = createDemoAuth(options);
3335
expect(auth).toBeDefined();

0 commit comments

Comments
 (0)