Devlog Jan 29: OAuth Implementation & Telegram
This week focused on implementing comprehensive OAuth 2.0 middleware and enhancing Telegram bot integration with webhook support.
OAuth 2.0 Middleware Implementation
Middleware Layer
We added a robust OAuth middleware that intercepts requests and validates tokens:
// src/lib/server/middleware/oauth-middleware.ts
import type { Handle } from '@sveltejs/kit';
import { verifyOAuthToken } from '$lib/server/services/oauth-service';
export const handleOAuth: Handle = async ({ event, resolve }) => {
const authHeader = event.request.headers.get('authorization');
if (authHeader?.startsWith('Bearer ')) {
const token = authHeader.substring(7);
const session = await verifyOAuthToken(token);
if (session) {
event.locals.oauthSession = session;
}
}
return resolve(event);
};
OAuth Services
The OAuth service handles the core business logic:
generateClientCredentials(): Creates new client credentialsvalidateRedirectUri(): Ensures redirect URIs match registered valuescreateAuthorizationCode(): Generates short-lived authorization codesexchangeCodeForToken(): Implements the token exchange flowverifyToken(): Validates access tokensrevokeToken(): Invalidates tokens
Token Management
Access tokens are stored with expiration metadata:
interface OAuthToken {
id: string;
clientId: string;
accessToken: string;
refreshToken?: string;
expiresAt: Date;
scopes: string[];
}
Telegram Bot Webhook Support
Webhook Auto-Configuration
We implemented automatic webhook configuration for Telegram bots:
// src/lib/server/telegram/webhook.ts
export async function setupTelegramWebhook(botToken: string, webhookUrl: string) {
const response = await fetch(`https://api.telegram.org/bot${botToken}/setWebhook`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: webhookUrl })
});
const data = await response.json();
if (!data.ok) {
throw new Error(`Failed to set webhook: ${data.description}`);
}
return data;
}
Webhook Endpoint
The webhook endpoint receives and processes Telegram updates:
// src/routes/api/telegram/webhook/+server.ts
import type { RequestHandler } from './$types';
import { handleTelegramUpdate } from '$lib/server/telegram/handler';
export const POST: RequestHandler = async ({ request }) => {
const update = await request.json();
await handleTelegramUpdate(update);
return new Response('OK', { status: 200 });
};
Session Linking
Telegram sessions are now linked to AI sessions for continuity:
interface TelegramSession {
id: string;
telegramChatId: string;
aiSessionId: string;
createdAt: Date;
lastActiveAt: Date;
}
OAuth Protected Resource Metadata Endpoints
Discovery Endpoints
We added standard OAuth discovery endpoints at .well-known locations:
// src/routes/.well-known/oauth-authorization-server/+server.ts
export const GET: RequestHandler = async () => {
const baseUrl = PUBLIC_BASE_URL;
return json({
issuer: baseUrl,
authorization_endpoint: `${baseUrl}/api/ai/mcp/oauth/authorize`,
token_endpoint: `${baseUrl}/api/ai/mcp/oauth/token`,
registration_endpoint: `${baseUrl}/api/ai/mcp/oauth/register`,
revocation_endpoint: `${baseUrl}/api/ai/mcp/oauth/revoke`,
response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'refresh_token'],
token_endpoint_auth_methods_supported: ['client_secret_basic', 'client_secret_post'],
code_challenge_methods_supported: ['S256']
});
};
Protected Metadata
OAuth-protected resources expose metadata about available MCP tools:
// src/routes/api/ai/mcp/oauth/resources/+server.ts
export const GET: RequestHandler = async ({ locals }) => {
const session = locals.oauthSession;
if (!session) {
return error(401, 'Unauthorized');
}
const resources = await getMcpResources(session.scopes);
return json(resources);
};
Database Schema Updates
New tables were added to support OAuth:
CREATE TABLE oauth_clients (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
secret TEXT,
redirect_uris TEXT NOT NULL,
scopes TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE oauth_tokens (
id TEXT PRIMARY KEY,
client_id TEXT NOT NULL REFERENCES oauth_clients(id),
access_token TEXT NOT NULL,
refresh_token TEXT,
expires_at TIMESTAMP NOT NULL,
scopes TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
What's Next
Next week we'll be diving into MCP (Model Context Protocol) implementation, including:
- MCP server implementation using official SDK
- JSON-RPC utilities and transport layer
- Security features including rate limiting and caching
Interested in OAuth integration? Check out the OAuth 2.0 Announcement for user-facing documentation.
