feat(mcp): OAuth 2.1 server for claude.ai remote connector; close plaintext-namespace bearer hole
在 arcrun-mcp worker 實作 MCP Authorization 規範(OAuth 2.1 + PKCE S256), 讓 claude.ai 遠端 connector 安全登入;並修掉「Bearer 明碼 namespace 直接放行」漏洞。 安全模型 - /authorize 同意頁以 owner secret(CF Secrets MCP_OWNER_SECRET)把關,只有 owner 知道 → 只知 URL 的人走不完 OAuth、拿不到 token。 - access_token 是 /mcp 唯一接受的 bearer(預設);明碼 namespace 舊路徑移除(步驟 5 直接 401)。 實作 endpoint(掛 worker 根路徑) - RFC 9728 /.well-known/oauth-protected-resource(+/mcp 變體)+ 401 帶 WWW-Authenticate: Bearer resource_metadata=... - RFC 8414 /.well-known/oauth-authorization-server(response_types=code, S256, none) - RFC 7591 /register(public client,無 secret,無狀態不落地) - GET/POST /authorize(PKCE S256 + owner-secret 閘 + redirect_uri 白名單) - POST /token(authorization_code + PKCE 驗證 → access_token 綁定 owner namespace) 儲存鐵律 - authorization code / access token → 短效 KV OAUTH_KV(key 用 SHA-256 hash、帶 TTL、code 一次性) - owner secret / static token → CF Secrets(非 KV、非明碼 var) - DCR client / refresh token → 不落地(無狀態 / 不實作,避免長效機密進 KV) 相容決策 - 本機 CLI/GUI/Claude Code → 用真祕密 MCP_STATIC_TOKEN(CF Secret)取代舊明碼 namespace - 官方 SaaS partner-key 路徑行為不變 - ALLOW_PLAINTEXT_NAMESPACE 逃生門預設關(僅遷移期) 驗證:tsc exit 0;vitest 42/42(oauth 22 + partner-auth 10 改測真實 middleware + 既有 10); wrangler deploy --dry-run 打包過、OAUTH_KV binding 正確識別。設計文件 mcp/OAUTH.md。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015d5jDbuqT5Htwv3Q88XXKk
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
// /authorize 同意頁:極簡單檔 HTML,要求輸入 owner 祕密才發碼。零外部資源。
|
||||
// 所有反射進 HTML 的 OAuth 參數都 escape,防 XSS(redirect_uri / state / client_id 由外部帶入)。
|
||||
|
||||
/** HTML attribute / text 跳脫。 */
|
||||
export function esc(s: string): string {
|
||||
return s
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
/** 同意頁需要 round-trip 回 POST /authorize 的隱藏欄位。 */
|
||||
export interface ConsentParams {
|
||||
client_id: string;
|
||||
redirect_uri: string;
|
||||
state: string;
|
||||
code_challenge: string;
|
||||
code_challenge_method: string;
|
||||
scope: string;
|
||||
resource: string;
|
||||
}
|
||||
|
||||
function hidden(name: string, value: string): string {
|
||||
return `<input type="hidden" name="${esc(name)}" value="${esc(value)}">`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 同意頁 HTML。`error` 有值時(如祕密錯誤)顯示紅字,但仍保留隱藏欄位讓 owner 重試。
|
||||
*/
|
||||
export function consentPage(p: ConsentParams, error?: string): string {
|
||||
const fields = [
|
||||
hidden("client_id", p.client_id),
|
||||
hidden("redirect_uri", p.redirect_uri),
|
||||
hidden("state", p.state),
|
||||
hidden("code_challenge", p.code_challenge),
|
||||
hidden("code_challenge_method", p.code_challenge_method),
|
||||
hidden("scope", p.scope),
|
||||
hidden("resource", p.resource),
|
||||
].join("\n ");
|
||||
|
||||
const errBlock = error
|
||||
? `<p class="err" role="alert">${esc(error)}</p>`
|
||||
: "";
|
||||
|
||||
return `<!doctype html>
|
||||
<html lang="zh-Hant">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Arcrun MCP 授權</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; }
|
||||
body { font-family: -apple-system, "Segoe UI", system-ui, sans-serif; max-width: 26rem;
|
||||
margin: 4rem auto; padding: 0 1.25rem; line-height: 1.6; }
|
||||
h1 { font-size: 1.25rem; }
|
||||
p.desc { color: #666; font-size: .95rem; }
|
||||
code { background: rgba(127,127,127,.15); padding: .1rem .35rem; border-radius: .25rem;
|
||||
font-size: .85rem; word-break: break-all; }
|
||||
label { display: block; margin: 1.25rem 0 .35rem; font-weight: 600; }
|
||||
input[type=password] { width: 100%; padding: .6rem .7rem; font-size: 1rem;
|
||||
border: 1px solid #8888; border-radius: .5rem; box-sizing: border-box; }
|
||||
button { margin-top: 1.25rem; width: 100%; padding: .7rem; font-size: 1rem; font-weight: 600;
|
||||
border: 0; border-radius: .5rem; background: #8a5f1e; color: #fff; cursor: pointer; }
|
||||
button:hover { background: #6f4c18; }
|
||||
p.err { color: #c0392b; font-weight: 600; }
|
||||
p.foot { color: #999; font-size: .8rem; margin-top: 2rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Arcrun MCP 授權</h1>
|
||||
<p class="desc">應用程式 <code>${esc(p.client_id)}</code> 想連上你的 Arcrun MCP,
|
||||
這會讓它能<strong>讀寫你的 KBDB 全部資料</strong>。</p>
|
||||
${errBlock}
|
||||
<form method="POST" action="/authorize">
|
||||
${fields}
|
||||
<label for="owner_secret">Owner 祕密</label>
|
||||
<input id="owner_secret" name="owner_secret" type="password" autocomplete="off"
|
||||
autofocus required placeholder="只有你知道的祕密">
|
||||
<button type="submit">授權連線</button>
|
||||
</form>
|
||||
<p class="foot">祕密不正確不會發出授權碼。此頁不儲存你的輸入。</p>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// OAuth 加密工具:PKCE S256 驗證、SHA-256 hash、隨機不可猜 token、常數時間比對。
|
||||
// 全走 Web Crypto(Workers / Node 18+ 全域 crypto.subtle),無外部依賴。
|
||||
|
||||
/** base64url 編碼(無 padding,RFC 7636 §A)。 */
|
||||
function base64UrlEncode(bytes: Uint8Array): string {
|
||||
let bin = "";
|
||||
for (const b of bytes) bin += String.fromCharCode(b);
|
||||
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
}
|
||||
|
||||
/** 產生密碼學等級隨機 token(bytes 位元組 → base64url 字串,預設 32 bytes = 256-bit)。 */
|
||||
export function randomToken(bytes = 32): string {
|
||||
const buf = new Uint8Array(bytes);
|
||||
crypto.getRandomValues(buf);
|
||||
return base64UrlEncode(buf);
|
||||
}
|
||||
|
||||
/** SHA-256 → base64url(PKCE code_challenge 用;RFC 7636 §4.2 BASE64URL(SHA256(verifier)))。 */
|
||||
export async function sha256Base64Url(input: string): Promise<string> {
|
||||
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
|
||||
return base64UrlEncode(new Uint8Array(digest));
|
||||
}
|
||||
|
||||
/** SHA-256 → hex(拿來當 KV key:不把可用的 raw token 直接當 key,KV list 也看不到明碼)。 */
|
||||
export async function sha256Hex(input: string): Promise<string> {
|
||||
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
|
||||
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* 常數時間字串比對(防 timing attack;比 owner secret / static token 用)。
|
||||
* 長度不同直接 false,但仍走完固定迴圈避免長度洩漏。
|
||||
*/
|
||||
export function constantTimeEqual(a: string, b: string): boolean {
|
||||
const ab = new TextEncoder().encode(a);
|
||||
const bb = new TextEncoder().encode(b);
|
||||
let diff = ab.length ^ bb.length;
|
||||
const len = Math.max(ab.length, bb.length);
|
||||
for (let i = 0; i < len; i++) {
|
||||
diff |= (ab[i] ?? 0) ^ (bb[i] ?? 0);
|
||||
}
|
||||
return diff === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 驗證 PKCE:BASE64URL(SHA256(code_verifier)) === code_challenge(僅支援 S256)。
|
||||
* method 非 "S256"(含缺省的 "plain")一律拒絕——OAuth 2.1 + 本 server 只宣告 S256。
|
||||
*/
|
||||
export async function verifyPkceS256(
|
||||
codeVerifier: string,
|
||||
codeChallenge: string,
|
||||
method: string | undefined,
|
||||
): Promise<boolean> {
|
||||
if (method !== "S256") return false;
|
||||
if (!codeVerifier || !codeChallenge) return false;
|
||||
// RFC 7636 §4.1:verifier 43–128 字元、[A-Za-z0-9-._~]。
|
||||
if (codeVerifier.length < 43 || codeVerifier.length > 128) return false;
|
||||
if (!/^[A-Za-z0-9\-._~]+$/.test(codeVerifier)) return false;
|
||||
const computed = await sha256Base64Url(codeVerifier);
|
||||
return constantTimeEqual(computed, codeChallenge);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// OAuth 探索文件(RFC 9728 Protected Resource Metadata、RFC 8414 Authorization Server Metadata)
|
||||
// 以「當前請求的 origin」動態組出——同一份碼在 mcp.arcrun.dev 與 arcrun-mcp.<sub>.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;
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
// OAuth 2.1 + PKCE server 路由。掛在 worker 根路徑(非 /mcp basePath),
|
||||
// 因為 well-known / authorize / token / register 都得在 origin 根,claude.ai 才發現得到。
|
||||
// 安全模型與相容決策見 mcp/OAUTH.md。
|
||||
import { Hono } from "hono";
|
||||
import type { Env as HonoBaseEnv } from "hono";
|
||||
import { Env } from "../types.js";
|
||||
import {
|
||||
randomToken,
|
||||
verifyPkceS256,
|
||||
constantTimeEqual,
|
||||
} from "./crypto.js";
|
||||
import {
|
||||
putAuthCode,
|
||||
consumeAuthCode,
|
||||
putAccessToken,
|
||||
AUTH_CODE_TTL_SECONDS,
|
||||
} from "./store.js";
|
||||
import {
|
||||
originOf,
|
||||
resourceUri,
|
||||
protectedResourceMetadata,
|
||||
authorizationServerMetadata,
|
||||
} from "./metadata.js";
|
||||
import { consentPage, ConsentParams } from "./consent.js";
|
||||
|
||||
const DEFAULT_TOKEN_TTL = 2592000; // 30 天
|
||||
const DEFAULT_REDIRECT_HOSTS = ["claude.ai", "claude.com", "anthropic.com"];
|
||||
|
||||
const CORS_JSON = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
||||
"Cache-Control": "no-store",
|
||||
} as const;
|
||||
|
||||
function ownerNamespace(env: Env): string {
|
||||
return env.MCP_OWNER_NAMESPACE || "leo";
|
||||
}
|
||||
|
||||
function tokenTtl(env: Env): number {
|
||||
const n = parseInt(env.MCP_TOKEN_TTL ?? "", 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : DEFAULT_TOKEN_TTL;
|
||||
}
|
||||
|
||||
/** redirect_uri 白名單檢查(OAuth 2.1:http 只准 localhost,其餘須 https 且 host 在白名單)。 */
|
||||
function isAllowedRedirect(uri: string, env: Env): boolean {
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(uri);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
const host = u.hostname.toLowerCase();
|
||||
const isLocal = host === "localhost" || host === "127.0.0.1" || host === "::1";
|
||||
if (u.protocol === "http:") return isLocal; // http 僅限本機
|
||||
if (u.protocol !== "https:") return false;
|
||||
if (isLocal) return true;
|
||||
const configured = (env.MCP_ALLOWED_REDIRECT_HOSTS ?? "")
|
||||
.split(",")
|
||||
.map((s) => s.trim().toLowerCase())
|
||||
.filter(Boolean);
|
||||
const list = configured.length ? configured : DEFAULT_REDIRECT_HOSTS;
|
||||
return list.some((h) => host === h || host.endsWith("." + h));
|
||||
}
|
||||
|
||||
/** 從 form 或 JSON body 讀參數(token/register 端點的 content-type 兩種都容忍)。 */
|
||||
async function readParams(req: Request): Promise<Record<string, string>> {
|
||||
const ct = req.headers.get("content-type") ?? "";
|
||||
try {
|
||||
if (ct.includes("application/json")) {
|
||||
const j = (await req.json()) as Record<string, unknown>;
|
||||
const out: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(j)) if (typeof v === "string") out[k] = v;
|
||||
return out;
|
||||
}
|
||||
const form = await req.formData();
|
||||
const out: Record<string, string> = {};
|
||||
for (const [k, v] of form.entries()) if (typeof v === "string") out[k] = v;
|
||||
return out;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
/** 組 redirect 回 client 的 URL(把 query 併進 redirect_uri)。 */
|
||||
function redirectWith(redirectUri: string, params: Record<string, string>): string {
|
||||
const u = new URL(redirectUri);
|
||||
for (const [k, v] of Object.entries(params)) u.searchParams.set(k, v);
|
||||
return u.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 掛載 OAuth 路由到根 app。呼叫端須把「MCP 端點以外」的根路徑交給此 app。
|
||||
* 泛型接受任何帶 `Bindings: Env` 的 Hono 實例(含額外 Variables),故可直接掛在主 app 上。
|
||||
*/
|
||||
export function registerOAuthRoutes<
|
||||
E extends HonoBaseEnv & { Bindings: Env },
|
||||
>(app: Hono<E>): void {
|
||||
// ── CORS 預檢 ───────────────────────────────────────────────────────────────
|
||||
app.options("/register", (c) => c.body(null, 204, CORS_JSON));
|
||||
app.options("/token", (c) => c.body(null, 204, CORS_JSON));
|
||||
app.options("/.well-known/oauth-protected-resource", (c) => c.body(null, 204, CORS_JSON));
|
||||
app.options("/.well-known/oauth-authorization-server", (c) => c.body(null, 204, CORS_JSON));
|
||||
|
||||
// ── RFC 9728 Protected Resource Metadata(根 + /mcp 路徑後綴變體)────────────────
|
||||
const prm = (c: { req: { url: string } }) =>
|
||||
protectedResourceMetadata(originOf(c.req.url));
|
||||
app.get("/.well-known/oauth-protected-resource", (c) =>
|
||||
c.json(prm(c), 200, CORS_JSON));
|
||||
app.get("/.well-known/oauth-protected-resource/mcp", (c) =>
|
||||
c.json(prm(c), 200, CORS_JSON));
|
||||
|
||||
// ── RFC 8414 Authorization Server Metadata(根 + /mcp 後綴變體)──────────────────
|
||||
const asm = (c: { req: { url: string } }) =>
|
||||
authorizationServerMetadata(originOf(c.req.url));
|
||||
app.get("/.well-known/oauth-authorization-server", (c) =>
|
||||
c.json(asm(c), 200, CORS_JSON));
|
||||
app.get("/.well-known/oauth-authorization-server/mcp", (c) =>
|
||||
c.json(asm(c), 200, CORS_JSON));
|
||||
|
||||
// ── RFC 7591 Dynamic Client Registration ───────────────────────────────────────
|
||||
// public client + PKCE → 不發 client_secret;且刻意「無狀態」不落地 client(見 OAUTH.md 相容決策)。
|
||||
app.post("/register", async (c) => {
|
||||
// DCR 一律 JSON(RFC 7591)。單次解析取 redirect_uris(陣列)+ client_name。
|
||||
let raw: { redirect_uris?: unknown; client_name?: unknown } = {};
|
||||
try {
|
||||
raw = (await c.req.raw.json()) as typeof raw;
|
||||
} catch {
|
||||
/* 無 / 非 JSON body:容忍,redirect_uris 視為空 */
|
||||
}
|
||||
const redirectUris: string[] = Array.isArray(raw.redirect_uris)
|
||||
? raw.redirect_uris.filter((x): x is string => typeof x === "string")
|
||||
: [];
|
||||
const clientName = typeof raw.client_name === "string" ? raw.client_name : "MCP Client";
|
||||
for (const uri of redirectUris) {
|
||||
if (!isAllowedRedirect(uri, c.env)) {
|
||||
return c.json(
|
||||
{ error: "invalid_redirect_uri", error_description: `redirect_uri not allowed: ${uri}` },
|
||||
400,
|
||||
CORS_JSON,
|
||||
);
|
||||
}
|
||||
}
|
||||
const clientId = "mcp_" + randomToken(16);
|
||||
return c.json(
|
||||
{
|
||||
client_id: clientId,
|
||||
client_id_issued_at: Math.floor(Date.now() / 1000),
|
||||
redirect_uris: redirectUris,
|
||||
grant_types: ["authorization_code"],
|
||||
response_types: ["code"],
|
||||
token_endpoint_auth_method: "none",
|
||||
client_name: clientName,
|
||||
},
|
||||
201,
|
||||
CORS_JSON,
|
||||
);
|
||||
});
|
||||
|
||||
// ── GET /authorize:呈現 owner 祕密同意頁 ───────────────────────────────────────
|
||||
app.get("/authorize", (c) => {
|
||||
const q = c.req.query();
|
||||
if (q.response_type !== "code") {
|
||||
return c.text("unsupported_response_type: only 'code' is supported", 400);
|
||||
}
|
||||
if (q.code_challenge_method !== "S256" || !q.code_challenge) {
|
||||
return c.text("invalid_request: PKCE S256 code_challenge required", 400);
|
||||
}
|
||||
if (!q.redirect_uri || !isAllowedRedirect(q.redirect_uri, c.env)) {
|
||||
// redirect_uri 本身可疑 → 絕不 redirect(防 open redirect),直接顯示錯誤。
|
||||
return c.text("invalid_request: redirect_uri missing or not allowed", 400);
|
||||
}
|
||||
if (!c.env.MCP_OWNER_SECRET) {
|
||||
return c.text("server_error: MCP_OWNER_SECRET not configured", 503);
|
||||
}
|
||||
const params: ConsentParams = {
|
||||
client_id: q.client_id ?? "",
|
||||
redirect_uri: q.redirect_uri,
|
||||
state: q.state ?? "",
|
||||
code_challenge: q.code_challenge,
|
||||
code_challenge_method: "S256",
|
||||
scope: q.scope ?? "mcp",
|
||||
resource: q.resource ?? resourceUri(originOf(c.req.url)),
|
||||
};
|
||||
return c.html(consentPage(params));
|
||||
});
|
||||
|
||||
// ── POST /authorize:驗 owner 祕密 → 發 authorization code → redirect ───────────
|
||||
app.post("/authorize", async (c) => {
|
||||
const p = await readParams(c.req.raw);
|
||||
const redirectUri = p.redirect_uri ?? "";
|
||||
// 再驗一次 redirect_uri(POST 的欄位是隱藏帶回來的,仍須擋竄改)。
|
||||
if (!redirectUri || !isAllowedRedirect(redirectUri, c.env)) {
|
||||
return c.text("invalid_request: redirect_uri not allowed", 400);
|
||||
}
|
||||
if (p.code_challenge_method !== "S256" || !p.code_challenge) {
|
||||
return c.text("invalid_request: PKCE S256 required", 400);
|
||||
}
|
||||
if (!c.env.MCP_OWNER_SECRET) {
|
||||
return c.text("server_error: MCP_OWNER_SECRET not configured", 503);
|
||||
}
|
||||
const consent: ConsentParams = {
|
||||
client_id: p.client_id ?? "",
|
||||
redirect_uri: redirectUri,
|
||||
state: p.state ?? "",
|
||||
code_challenge: p.code_challenge,
|
||||
code_challenge_method: "S256",
|
||||
scope: p.scope ?? "mcp",
|
||||
resource: p.resource ?? resourceUri(originOf(c.req.url)),
|
||||
};
|
||||
// ★ owner 祕密把關:錯誤不發碼、重顯同意頁。這是「只知 URL 的人進不來」的唯一閘。
|
||||
const supplied = p.owner_secret ?? "";
|
||||
if (!supplied || !constantTimeEqual(supplied, c.env.MCP_OWNER_SECRET)) {
|
||||
return c.html(consentPage(consent, "Owner 祕密不正確,請重試。"), 401);
|
||||
}
|
||||
if (!c.env.OAUTH_KV) {
|
||||
return c.text("server_error: OAUTH_KV not configured", 503);
|
||||
}
|
||||
const code = randomToken(32);
|
||||
await putAuthCode(c.env.OAUTH_KV, code, {
|
||||
client_id: consent.client_id,
|
||||
redirect_uri: redirectUri,
|
||||
code_challenge: consent.code_challenge,
|
||||
code_challenge_method: "S256",
|
||||
scope: consent.scope,
|
||||
resource: consent.resource,
|
||||
namespace: ownerNamespace(c.env),
|
||||
});
|
||||
const location = redirectWith(redirectUri, {
|
||||
code,
|
||||
...(consent.state ? { state: consent.state } : {}),
|
||||
});
|
||||
return c.redirect(location, 302);
|
||||
});
|
||||
|
||||
// ── POST /token:code + PKCE verifier → access_token ────────────────────────────
|
||||
app.post("/token", async (c) => {
|
||||
const p = await readParams(c.req.raw);
|
||||
const err = (code: string, desc: string, status = 400) =>
|
||||
c.json({ error: code, error_description: desc }, status as 400, CORS_JSON);
|
||||
|
||||
if (p.grant_type !== "authorization_code") {
|
||||
return err("unsupported_grant_type", "only authorization_code is supported");
|
||||
}
|
||||
if (!p.code || !p.code_verifier || !p.redirect_uri) {
|
||||
return err("invalid_request", "code, code_verifier and redirect_uri are required");
|
||||
}
|
||||
if (!c.env.OAUTH_KV) {
|
||||
return err("server_error", "OAUTH_KV not configured", 503);
|
||||
}
|
||||
const data = await consumeAuthCode(c.env.OAUTH_KV, p.code); // 一次性
|
||||
if (!data) {
|
||||
return err("invalid_grant", "authorization code invalid or expired");
|
||||
}
|
||||
if (data.redirect_uri !== p.redirect_uri) {
|
||||
return err("invalid_grant", "redirect_uri mismatch");
|
||||
}
|
||||
if (p.client_id && data.client_id && p.client_id !== data.client_id) {
|
||||
return err("invalid_grant", "client_id mismatch");
|
||||
}
|
||||
const pkceOk = await verifyPkceS256(p.code_verifier, data.code_challenge, data.code_challenge_method);
|
||||
if (!pkceOk) {
|
||||
return err("invalid_grant", "PKCE verification failed");
|
||||
}
|
||||
|
||||
const ttl = tokenTtl(c.env);
|
||||
const accessToken = randomToken(32);
|
||||
await putAccessToken(
|
||||
c.env.OAUTH_KV,
|
||||
accessToken,
|
||||
{
|
||||
namespace: data.namespace,
|
||||
client_id: data.client_id,
|
||||
scope: data.scope,
|
||||
aud: data.resource, // RFC 8707:綁定受眾 = 本 MCP server
|
||||
exp: Math.floor(Date.now() / 1000) + ttl,
|
||||
},
|
||||
ttl,
|
||||
);
|
||||
return c.json(
|
||||
{
|
||||
access_token: accessToken,
|
||||
token_type: "Bearer",
|
||||
expires_in: ttl,
|
||||
scope: data.scope,
|
||||
},
|
||||
200,
|
||||
CORS_JSON,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export { AUTH_CODE_TTL_SECONDS };
|
||||
@@ -0,0 +1,78 @@
|
||||
// OAuth 短效認證儲存(KV)。儲存鐵律(leo + wiki):
|
||||
// 只有「取得的暫時性認證」可進 KV,且帶 TTL——authorization code、access token 是也。
|
||||
// 長效機密(owner secret)走 CF Secrets,不進此處。DCR client 不落地(見 OAUTH.md 相容決策)。
|
||||
// KV key 一律用 SHA-256 hex(不把 raw code/token 當 key)→ 就算 KV list 也拿不到可用憑證。
|
||||
import { sha256Hex } from "./crypto.js";
|
||||
|
||||
/** authorization code 綁定的資料(一次性;/token 驗證後即刪)。 */
|
||||
export interface AuthCodeData {
|
||||
client_id: string;
|
||||
redirect_uri: string;
|
||||
code_challenge: string;
|
||||
code_challenge_method: string;
|
||||
scope: string;
|
||||
/** RFC 8707 resource:綁定 token 的目標 MCP server(audience)。 */
|
||||
resource: string;
|
||||
/** 換發後 token 綁定的資料分區(owner namespace)。 */
|
||||
namespace: string;
|
||||
}
|
||||
|
||||
/** access token 綁定的資料。 */
|
||||
export interface AccessTokenData {
|
||||
namespace: string;
|
||||
client_id: string;
|
||||
scope: string;
|
||||
/** token 的目標受眾(= 本 MCP server 的 canonical URI),驗證時比對。 */
|
||||
aud: string;
|
||||
/** 過期時間(epoch 秒),與 KV TTL 雙保險。 */
|
||||
exp: number;
|
||||
}
|
||||
|
||||
const CODE_PREFIX = "oauth:code:";
|
||||
const TOKEN_PREFIX = "oauth:tok:";
|
||||
/** authorization code 存活秒數(一次性、極短效)。 */
|
||||
export const AUTH_CODE_TTL_SECONDS = 600;
|
||||
|
||||
/** 存 authorization code(TTL 極短)。回傳 raw code 給 client。 */
|
||||
export async function putAuthCode(kv: KVNamespace, code: string, data: AuthCodeData): Promise<void> {
|
||||
const key = CODE_PREFIX + (await sha256Hex(code));
|
||||
await kv.put(key, JSON.stringify(data), { expirationTtl: AUTH_CODE_TTL_SECONDS });
|
||||
}
|
||||
|
||||
/** 取出並「消費」authorization code(一次性:讀到即刪,防重放)。找不到回 null。 */
|
||||
export async function consumeAuthCode(kv: KVNamespace, code: string): Promise<AuthCodeData | null> {
|
||||
const key = CODE_PREFIX + (await sha256Hex(code));
|
||||
const raw = await kv.get(key);
|
||||
if (!raw) return null;
|
||||
await kv.delete(key); // 一次性使用(OAuth 2.1:code 用過必失效)
|
||||
try {
|
||||
return JSON.parse(raw) as AuthCodeData;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 存 access token(TTL = ttlSeconds)。回傳 raw token 給 client。 */
|
||||
export async function putAccessToken(
|
||||
kv: KVNamespace,
|
||||
token: string,
|
||||
data: AccessTokenData,
|
||||
ttlSeconds: number,
|
||||
): Promise<void> {
|
||||
const key = TOKEN_PREFIX + (await sha256Hex(token));
|
||||
await kv.put(key, JSON.stringify(data), { expirationTtl: ttlSeconds });
|
||||
}
|
||||
|
||||
/** 查 access token → 綁定資料。找不到 / 過期回 null(KV TTL 到期會自動消失,另做 exp 雙檢)。 */
|
||||
export async function getAccessToken(kv: KVNamespace, token: string): Promise<AccessTokenData | null> {
|
||||
const key = TOKEN_PREFIX + (await sha256Hex(token));
|
||||
const raw = await kv.get(key);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const data = JSON.parse(raw) as AccessTokenData;
|
||||
if (typeof data.exp === "number" && data.exp * 1000 < Date.now()) return null;
|
||||
return data;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user