Spaces:
Running
Running
Update server.js
Browse files33 unmodified lines3435363738394041424344454621 unmodified lines686970717273743 unmodified lines78798081828384855 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511614 unmodified lines13113213313413513613740 unmodified lines1781791801811821833 unmodified lines18718818919019119241 unmodified lines23423523623723823924024124224324424524624724824925025125225314 unmodified lines26826927027127227327427527627727827930 unmodified lines31031131231331431531627 unmodified lines34434534634734834935033 unmodified linesapp.use((req, res, next) => {const auth = req.headers.authorization ? `present(len=${req.headers.authorization.length})` : "none";const ct = req.headers["content-type"] || "none";console.log(`[REQ] ${req.method} ${req.originalUrl} ct=${ct} auth=${auth}`);res.on("finish", () => {console.log(`[RES] ${req.method} ${req.originalUrl} -> ${res.statusCode}`);});next();});21 unmodified linesissuer: ob,authorization_endpoint: `${ob}/authorize`,token_endpoint: `${ob}/token`,token_endpoint_auth_methods_supported: ["client_secret_basic"],response_types_supported: ["code"],grant_types_supported: ["authorization_code", "refresh_token"],scopes_supported: ["mcp", "offline_access", "openid", "email"],3 unmodified linesfunction protectedResourceMetadata(req) {const b = absBase(req);const resource = `${b}/sse`; // ChatGPTが resource=.../sse を渡してくるconst as = oauthBase(req); // /sse ベースにも追随return {resource,authorization_servers: [as],5 unmodified lines/* ===============================Well-known endpoints================================ */function regWellKnown(path, fn) {app.get(path, fn);}// OAuth AS discoveryregWellKnown("/.well-known/oauth-authorization-server", (req, res) => res.json(oauthMetadata(req)));regWellKnown("/.well-known/oauth-authorization-server/*", (req, res) => res.json(oauthMetadata(req)));regWellKnown("/.well-known/openid-configuration", (req, res) => res.json(oauthMetadata(req)));regWellKnown("/.well-known/openid-configuration/*", (req, res) => res.json(oauthMetadata(req)));regWellKnown("/sse/.well-known/oauth-authorization-server", (req, res) => res.json(oauthMetadata(req)));regWellKnown("/sse/.well-known/oauth-authorization-server/*", (req, res) => res.json(oauthMetadata(req)));regWellKnown("/sse/.well-known/openid-configuration", (req, res) => res.json(oauthMetadata(req)));regWellKnown("/sse/.well-known/openid-configuration/*", (req, res) => res.json(oauthMetadata(req)));// OAuth protected resource metadataregWellKnown("/.well-known/oauth-protected-resource", (req, res) => res.json(protectedResourceMetadata(req)));regWellKnown("/.well-known/oauth-protected-resource/*", (req, res) => res.json(protectedResourceMetadata(req)));regWellKnown("/sse/.well-known/oauth-protected-resource", (req, res) => res.json(protectedResourceMetadata(req)));regWellKnown("/sse/.well-known/oauth-protected-resource/*", (req, res) => res.json(protectedResourceMetadata(req)));/* ===============================OAuth endpoints (authorize/token)14 unmodified lines}function verifyPkceIfPresent(stored, code_verifier) {if (!stored?.code_challenge) return true; // challengeが無いならPKCEなし扱いで通すif (!code_verifier) return false;const method = (stored.code_challenge_method || "plain").toString().toLowerCase();40 unmodified linesapp.get("/authorize", handleAuthorize);app.get("/sse/authorize", handleAuthorize);function parseBasic(req) {const auth = req.headers.authorization || "";if (!auth.startsWith("Basic ")) return null;3 unmodified linesreturn { id: decoded.slice(0, idx), secret: decoded.slice(idx + 1) };}async function mintAccessToken(req, aud) {const iss = oauthBase(req);const now = Math.floor(Date.now() / 1000);41 unmodified lines}async function handleToken(req, res) {// OAuth推奨ヘッダ(クライアントが厳しいとこれが効く)res.setHeader("Cache-Control", "no-store");res.setHeader("Pragma", "no-cache");const basic = parseBasic(req);if (!basic) return res.status(401).send("missing basic auth");if (basic.id !== CLIENT_ID || basic.secret !== CLIENT_SECRET) return res.status(401).send("bad client");const bodyKeys = Object.keys(req.body || {});const grantType = (req.body?.grant_type || "authorization_code").toString();const resource = (req.body?.resource || "").toString();const aud = resource || `${absBase(req)}/sse`;console.log(`[TOKEN_REQ] grant_type=${grantType} keys=${bodyKeys.join(",")} aud=${aud} iss=${oauthBase(req)}`);if (grantType === "refresh_token") {const access_token = await mintAccessToken(req, aud);14 unmodified linesconst stored = codeStore.get(code);// redirect_uri が両方ある場合だけ厳密一致(片方欠けたら“通す”優先)if (stored?.redirect_uri && redirect_uri && stored.redirect_uri !== redirect_uri) {return res.status(400).send("redirect_uri mismatch");}// PKCE が来ていて challenge もあるなら検証if (stored && stored.code_challenge) {if (!verifyPkceIfPresent(stored, code_verifier)) {return res.status(400).send("pkce verification failed");30 unmodified linesconst h = req.headers.authorization || "";if (!h.startsWith("Bearer ")) return res.status(401).send("missing bearer");try {// aud/iss は緩め(署名が合えばOK)で通すawait jwtVerify(h.slice(7), JWT_SECRET, { clockTolerance: "5s" });next();} catch {27 unmodified lines/* ===============================SSE transport================================ */const transports = new Map(); // sessionId -> SSEServerTransportapp.get("/sse", requireBearer, async (req, res) => {const transport = new SSEServerTransport("/messages", res);33 unmodified lines3435363738394041424321 unmodified lines65666768697071723 unmodified lines76777879808182835 unmodified lines899091929394959697989910010110210310410510610710810911011111211311414 unmodified lines12913013113213313413540 unmodified lines1761771781791801811823 unmodified lines18618718818919019119219319419519619719819920020120220320420520620720820941 unmodified lines25125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428514 unmodified lines30030130230330430530630730830931031130 unmodified lines34234334434534634727 unmodified lines37537637737837938038133 unmodified linesapp.use((req, res, next) => {const auth = req.headers.authorization ? `present(len=${req.headers.authorization.length})` : "none";const ct = req.headers["content-type"] || "none";console.log(`[REQ] ${req.method} ${req.originalUrl} ct=${ct} auth=${auth}`);res.on("finish", () => {console.log(`[RES] ${req.method} ${req.originalUrl} -> ${res.statusCode}`);});next();});21 unmodified linesissuer: ob,authorization_endpoint: `${ob}/authorize`,token_endpoint: `${ob}/token`,// ★重要:basic と post の両方を宣言(ChatGPT実装差を吸収)token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"],response_types_supported: ["code"],grant_types_supported: ["authorization_code", "refresh_token"],scopes_supported: ["mcp", "offline_access", "openid", "email"],3 unmodified linesfunction protectedResourceMetadata(req) {const b = absBase(req);const resource = `${b}/sse`;const as = oauthBase(req);return {resource,authorization_servers: [as],5 unmodified lines/* ===============================Well-known endpoints================================ */function regGet(path, fn) {app.get(path, fn);}// OAuth AS discoveryregGet("/.well-known/oauth-authorization-server", (req, res) => res.json(oauthMetadata(req)));regGet("/.well-known/oauth-authorization-server/*", (req, res) => res.json(oauthMetadata(req)));regGet("/.well-known/openid-configuration", (req, res) => res.json(oauthMetadata(req)));regGet("/.well-known/openid-configuration/*", (req, res) => res.json(oauthMetadata(req)));regGet("/sse/.well-known/oauth-authorization-server", (req, res) => res.json(oauthMetadata(req)));regGet("/sse/.well-known/oauth-authorization-server/*", (req, res) => res.json(oauthMetadata(req)));regGet("/sse/.well-known/openid-configuration", (req, res) => res.json(oauthMetadata(req)));regGet("/sse/.well-known/openid-configuration/*", (req, res) => res.json(oauthMetadata(req)));// OAuth protected resource metadataregGet("/.well-known/oauth-protected-resource", (req, res) => res.json(protectedResourceMetadata(req)));regGet("/.well-known/oauth-protected-resource/*", (req, res) => res.json(protectedResourceMetadata(req)));regGet("/sse/.well-known/oauth-protected-resource", (req, res) => res.json(protectedResourceMetadata(req)));regGet("/sse/.well-known/oauth-protected-resource/*", (req, res) => res.json(protectedResourceMetadata(req)));/* ===============================OAuth endpoints (authorize/token)14 unmodified lines}function verifyPkceIfPresent(stored, code_verifier) {if (!stored?.code_challenge) return true;if (!code_verifier) return false;const method = (stored.code_challenge_method || "plain").toString().toLowerCase();40 unmodified linesapp.get("/authorize", handleAuthorize);app.get("/sse/authorize", handleAuthorize);// ---- client auth helpers ----function parseBasic(req) {const auth = req.headers.authorization || "";if (!auth.startsWith("Basic ")) return null;3 unmodified linesreturn { id: decoded.slice(0, idx), secret: decoded.slice(idx + 1) };}function readClientCreds(req) {// 1) client_secret_basicconst basic = parseBasic(req);if (basic) return { method: "basic", id: basic.id, secret: basic.secret };// 2) client_secret_postconst id = (req.body?.client_id || "").toString();const secret = (req.body?.client_secret || "").toString();if (id || secret) return { method: "post", id, secret };return { method: "none", id: "", secret: "" };}function safeBool(b) {return b ? "yes" : "no";}// ---- token minting ----async function mintAccessToken(req, aud) {const iss = oauthBase(req);const now = Math.floor(Date.now() / 1000);41 unmodified lines}async function handleToken(req, res) {// OAuth推奨ヘッダres.setHeader("Cache-Control", "no-store");res.setHeader("Pragma", "no-cache");const creds = readClientCreds(req);const idOk = creds.id === CLIENT_ID;const secretOk = creds.secret === CLIENT_SECRET;// ★ここが今回の核心:401の理由を判別できるようにログ(秘密は出さない)console.log(`[TOKEN_AUTH] method=${creds.method} id_present=${safeBool(!!creds.id)} secret_present=${safeBool(!!creds.secret)} id_ok=${safeBool(idOk)} secret_ok=${safeBool(secretOk)}`);if (!idOk || !secretOk) {// ChatGPTが UI に入れた client_id/secret とサーバ側 Secrets が一致しているかをまず疑うreturn res.status(401).send("invalid_client");}const bodyKeys = Object.keys(req.body || {});const grantType = (req.body?.grant_type || "authorization_code").toString();const resource = (req.body?.resource || "").toString();const aud = resource || `${absBase(req)}/sse`;console.log(`[TOKEN_REQ] grant_type=${grantType} keys=${bodyKeys.join(",")} aud=${aud} iss=${oauthBase(req)}`);if (grantType === "refresh_token") {const access_token = await mintAccessToken(req, aud);14 unmodified linesconst stored = codeStore.get(code);// redirect_uri が両方ある場合だけ厳密一致if (stored?.redirect_uri && redirect_uri && stored.redirect_uri !== redirect_uri) {return res.status(400).send("redirect_uri mismatch");}// PKCE: challengeが保存されている場合のみ検証if (stored && stored.code_challenge) {if (!verifyPkceIfPresent(stored, code_verifier)) {return res.status(400).send("pkce verification failed");30 unmodified linesconst h = req.headers.authorization || "";if (!h.startsWith("Bearer ")) return res.status(401).send("missing bearer");try {await jwtVerify(h.slice(7), JWT_SECRET, { clockTolerance: "5s" });next();} catch {27 unmodified lines/* ===============================SSE transport================================ */const transports = new Map();app.get("/sse", requireBearer, async (req, res) => {const transport = new SSEServerTransport("/messages", res);
server.js+60-29