// OAuth 探索文件(RFC 9728 Protected Resource Metadata、RFC 8414 Authorization Server Metadata) // 以「當前請求的 origin」動態組出——同一份碼在 mcp.arcrun.dev 與 arcrun-mcp..workers.dev 都正確。 /** 從請求 URL 取 origin(scheme://host),canonical 用小寫 scheme/host。 */ export function originOf(reqUrl: string): string { const u = new URL(reqUrl); return `${u.protocol.toLowerCase()}//${u.host.toLowerCase()}`; } /** 本 MCP server 的 canonical resource URI(RFC 8707 audience)——MCP 端點在 /mcp。 */ export function resourceUri(origin: string): string { return `${origin}/mcp`; } /** RFC 9728 Protected Resource Metadata。 */ export function protectedResourceMetadata(origin: string) { return { resource: resourceUri(origin), authorization_servers: [origin], scopes_supported: ["mcp"], bearer_methods_supported: ["header"], }; } /** RFC 8414 Authorization Server Metadata(本 worker 同時是 AS)。 */ export function authorizationServerMetadata(origin: string) { return { issuer: origin, authorization_endpoint: `${origin}/authorize`, token_endpoint: `${origin}/token`, registration_endpoint: `${origin}/register`, response_types_supported: ["code"], grant_types_supported: ["authorization_code"], code_challenge_methods_supported: ["S256"], token_endpoint_auth_methods_supported: ["none"], // public client + PKCE scopes_supported: ["mcp"], }; } /** * RFC 9728 §5.1 WWW-Authenticate 回應標頭——401 時指向 protected-resource metadata, * claude.ai 靠這個發現 OAuth authorization server。 */ export function wwwAuthenticateHeader(origin: string, error?: string): string { const metaUrl = `${origin}/.well-known/oauth-protected-resource`; let h = `Bearer resource_metadata="${metaUrl}"`; if (error) h += `, error="${error}"`; return h; }