|
| 1 | +import { createHash, createHmac, timingSafeEqual } from "node:crypto"; |
| 2 | + |
| 3 | +export type AuthEnv = Record<string, string | undefined>; |
| 4 | + |
| 5 | +export type AuthCheckInput = { |
| 6 | + url?: string; |
| 7 | + authorization?: string | string[]; |
| 8 | + env?: AuthEnv; |
| 9 | +}; |
| 10 | + |
| 11 | +export type HttpAuthResponse = { |
| 12 | + status: number; |
| 13 | + headers: Record<string, string>; |
| 14 | + body: string; |
| 15 | +}; |
| 16 | + |
| 17 | +const TOKEN_PREFIX_LENGTH = 18; |
| 18 | + |
| 19 | +export function hasConfiguredAuth(env: AuthEnv = process.env): boolean { |
| 20 | + return Boolean( |
| 21 | + env.MCP_TOKEN_SIGNING_SECRET?.trim() || |
| 22 | + env.MCP_ACCESS_TOKEN_HASHES?.trim() || |
| 23 | + env.MCP_ACCESS_TOKENS?.trim(), |
| 24 | + ); |
| 25 | +} |
| 26 | + |
| 27 | +export function getUnauthorizedResponse(originUrl: string, method = "POST"): HttpAuthResponse { |
| 28 | + const isGet = method.toUpperCase() === "GET"; |
| 29 | + return { |
| 30 | + status: 401, |
| 31 | + headers: { |
| 32 | + "content-type": "application/json; charset=utf-8", |
| 33 | + "cache-control": "no-store", |
| 34 | + "www-authenticate": `Bearer realm="education-agent-skills", error="invalid_token", error_description="Hosted MCP access token required"`, |
| 35 | + "x-mcp-auth": isGet ? "required-fast-fail" : "required", |
| 36 | + }, |
| 37 | + body: JSON.stringify({ |
| 38 | + error: "Hosted MCP access token required", |
| 39 | + message: |
| 40 | + "This hosted MCP endpoint now requires an access token. Request one via the hosted access form, or use the free local/plugin installation options.", |
| 41 | + requestAccess: "https://docs.google.com/forms/d/e/1FAIpQLSdW1EdcmtjSPPq68Hx-bdth5hO2KNyjhAwEV9Ld0EwWL1Gr8Q/viewform", |
| 42 | + resource: originUrl, |
| 43 | + }), |
| 44 | + }; |
| 45 | +} |
| 46 | + |
| 47 | +export function getAuthorizedTokenPrefix(input: AuthCheckInput): string | null { |
| 48 | + const env = input.env ?? process.env; |
| 49 | + const token = extractToken(input.url, input.authorization); |
| 50 | + if (!token || !hasConfiguredAuth(env)) return null; |
| 51 | + if (isSignedTokenValid(token, env.MCP_TOKEN_SIGNING_SECRET)) { |
| 52 | + return token.slice(0, TOKEN_PREFIX_LENGTH); |
| 53 | + } |
| 54 | + if (isHashTokenValid(token, env.MCP_ACCESS_TOKEN_HASHES)) { |
| 55 | + return token.slice(0, TOKEN_PREFIX_LENGTH); |
| 56 | + } |
| 57 | + if (isPlainTokenValid(token, env.MCP_ACCESS_TOKENS)) { |
| 58 | + return token.slice(0, TOKEN_PREFIX_LENGTH); |
| 59 | + } |
| 60 | + return null; |
| 61 | +} |
| 62 | + |
| 63 | +export function extractToken(url?: string, authorization?: string | string[]): string | null { |
| 64 | + const header = Array.isArray(authorization) ? authorization[0] : authorization; |
| 65 | + const bearer = header?.match(/^Bearer\s+(.+)$/i)?.[1]?.trim(); |
| 66 | + if (bearer) return bearer; |
| 67 | + if (!url) return null; |
| 68 | + try { |
| 69 | + const parsed = new URL(url, "https://example.invalid"); |
| 70 | + return parsed.searchParams.get("token")?.trim() || null; |
| 71 | + } catch { |
| 72 | + return null; |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +function isSignedTokenValid(token: string, secret?: string): boolean { |
| 77 | + const cleanSecret = secret?.trim(); |
| 78 | + if (!cleanSecret) return false; |
| 79 | + const dot = token.lastIndexOf("."); |
| 80 | + if (dot < 1) return false; |
| 81 | + const payload = token.slice(0, dot); |
| 82 | + const signature = token.slice(dot + 1); |
| 83 | + if (!payload.startsWith("eas_live_") || !signature) return false; |
| 84 | + const expected = createHmac("sha256", cleanSecret).update(payload).digest("base64url"); |
| 85 | + return safeEqual(signature, expected); |
| 86 | +} |
| 87 | + |
| 88 | +function isHashTokenValid(token: string, hashes?: string): boolean { |
| 89 | + const allowed = splitList(hashes); |
| 90 | + if (allowed.length === 0) return false; |
| 91 | + const digest = createHash("sha256").update(token).digest("hex"); |
| 92 | + return allowed.some((hash) => safeEqual(digest, hash)); |
| 93 | +} |
| 94 | + |
| 95 | +function isPlainTokenValid(token: string, tokens?: string): boolean { |
| 96 | + const allowed = splitList(tokens); |
| 97 | + if (allowed.length === 0) return false; |
| 98 | + return allowed.some((allowedToken) => safeEqual(token, allowedToken)); |
| 99 | +} |
| 100 | + |
| 101 | +function splitList(raw?: string): string[] { |
| 102 | + return (raw ?? "") |
| 103 | + .split(/[\n,]/) |
| 104 | + .map((part) => part.trim()) |
| 105 | + .filter(Boolean); |
| 106 | +} |
| 107 | + |
| 108 | +function safeEqual(a: string, b: string): boolean { |
| 109 | + const aBuffer = Buffer.from(a); |
| 110 | + const bBuffer = Buffer.from(b); |
| 111 | + if (aBuffer.length !== bBuffer.length) return false; |
| 112 | + return timingSafeEqual(aBuffer, bBuffer); |
| 113 | +} |
0 commit comments