Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(oauth): send the WWW-Authenticate challenge with a rejected Basic client credential
nirholasb607a4c8e395
diff --git a/api/oauth/[action].js b/api/oauth/[action].jsindex 01cf7af4c..325acd34a 100644--- a/api/oauth/[action].js+++ b/api/oauth/[action].js@@ -196,6 +196,19 @@ async function authenticateClient(req, form) {return { ok: true, client, clientId };}+// RFC 6749 §5.2: when a client authenticated with the Authorization header and+// the credentials are rejected, the 401 MUST carry a WWW-Authenticate challenge+// naming the same scheme. Without it the response is a malformed 401, and the+// HTTP clients that enforce that (fetch wrappers and OAuth libraries that retry+// on a challenge) either loop on the same bad secret or surface a transport+// error instead of "your client secret is wrong".+function invalidClientCredentials(req, res) {+ if (String(req.headers.authorization || '').toLowerCase().startsWith('basic ')) {+ res.setHeader('www-authenticate', 'Basic realm="oauth", error="invalid_client", error_description="bad client credentials"');+ }+ return error(res, 401, 'invalid_client', 'bad client credentials');+}+function isSubsetScope(requested, stored) {const allowed = new Set(stored.split(/\s+/).filter(Boolean));const asked = requested.split(/\s+/).filter(Boolean);@@ -213,9 +226,16 @@ async function handleToken(req, res) {const auth = await authenticateClient(req, form);if (!auth.ok) {if (auth.reason === 'unknown_client') return error(res, 400, 'invalid_client', 'unknown client');- return error(res, 401, 'invalid_client', 'bad client credentials');+ return invalidClientCredentials(req, res);}const client = auth.client;+ // RFC 8707 §2.2: the token request MAY repeat `resource`, and a server that+ // does not recognize the one it names MUST answer `invalid_target`. /oauth/+ // authorize has enforced that since the audience bug; the token endpoint+ // ignored the parameter, which reintroduced the exact failure canonicalResource+ // exists to prevent: a client naming another resource got a 200 and a token+ // whose `aud` was this server's, then hit 401s at every endpoint it tried.+ if (!canonicalResource(form.resource)) return error(res, 400, 'invalid_target', `unknown resource, this server only issues tokens for ${env.MCP_RESOURCE}`);const grantType = form.grant_type;if (grantType === 'authorization_code') {const { code, redirect_uri, code_verifier } = form;@@ -339,7 +359,27 @@ async function handleRegister(req, res) {// issued, with 0 meaning "never expires". Omitting it left a spec-following// client with no way to tell a non-expiring secret from a missing field, and// the secrets minted here genuinely have no expiry.- return json(res, 201, { client_id: clientId, ...(clientSecret ? { client_secret: clientSecret, client_secret_expires_at: 0 } : {}), client_id_issued_at: Math.floor(Date.now() / 1000), token_endpoint_auth_method: authMethod, redirect_uris: body.redirect_uris, grant_types: grantTypes, response_types: responseTypes, scope, client_name: body.client_name ?? 'MCP Client' });+ //+ // The same section makes the response the authoritative record of what was+ // registered, so it echoes every optional field that was actually stored.+ // Dropping logo_uri, client_uri, software_id and software_version told a+ // client its metadata had been rejected when the row above had just saved it,+ // and a client that re-registers to "fix" that gets a second client_id.+ return json(res, 201, {+ client_id: clientId,+ ...(clientSecret ? { client_secret: clientSecret, client_secret_expires_at: 0 } : {}),+ client_id_issued_at: Math.floor(Date.now() / 1000),+ token_endpoint_auth_method: authMethod,+ redirect_uris: body.redirect_uris,+ grant_types: grantTypes,+ response_types: responseTypes,+ scope,+ client_name: body.client_name ?? 'MCP Client',+ ...(body.client_uri ? { client_uri: body.client_uri } : {}),+ ...(body.logo_uri ? { logo_uri: body.logo_uri } : {}),+ ...(body.software_id ? { software_id: body.software_id } : {}),+ ...(body.software_version ? { software_version: body.software_version } : {}),+ });}// ── revoke ────────────────────────────────────────────────────────────────────@@ -358,7 +398,7 @@ async function handleRevoke(req, res) {const auth = await authenticateClient(req, form);if (!auth.ok) {if (auth.reason === 'unknown_client') return json(res, 200, {});- return error(res, 401, 'invalid_client', 'bad client credentials');+ return invalidClientCredentials(req, res);}// `token_type_hint` is advisory and RFC 7009 §2.1 requires extending the// search when the token is not found under the hinted type. Access tokens@@ -387,7 +427,7 @@ async function handleIntrospect(req, res) {const auth = await authenticateClient(req, form);if (!auth.ok) {if (auth.reason === 'unknown_client') return json(res, 200, { active: false });- return error(res, 401, 'invalid_client', 'bad client credentials');+ return invalidClientCredentials(req, res);}const clientId = auth.clientId;try {diff --git a/tests/oauth-endpoints.test.js b/tests/oauth-endpoints.test.jsindex 5b3e1653a..43bcc63a6 100644--- a/tests/oauth-endpoints.test.js+++ b/tests/oauth-endpoints.test.js@@ -404,6 +404,50 @@ describe('POST /oauth/token', () => {expect(res.statusCode).toBe(400);expect(res.json().error).toBe('unsupported_grant_type');});++ it('challenges a Basic-auth client whose secret is wrong, so the 401 is not malformed', async () => {+ // RFC 6749 section 5.2: a client that authenticated through the+ // Authorization header MUST get WWW-Authenticate back naming that scheme.+ await seedConfidentialClient();+ const res = await call('token', {+ method: 'POST',+ headers: basicHeader('mcp_test_client', 'guessed'),+ form: { grant_type: 'authorization_code', code: 'x', redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER },+ });+ expect(res.statusCode).toBe(401);+ expect(res.getHeader('www-authenticate')).toMatch(/^Basic realm="oauth"/);+ });++ it('omits the challenge when the bad secret arrived in the form, not the header', async () => {+ seedClient({ client_type: 'confidential', client_secret_hash: await sha256(CONFIDENTIAL_SECRET), token_endpoint_auth: 'client_secret_post' });+ const res = await call('token', { method: 'POST', form: { grant_type: 'authorization_code', client_id: 'mcp_test_client', client_secret: 'guessed', code: 'x', redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER } });+ expect(res.statusCode).toBe(401);+ expect(res.getHeader('www-authenticate')).toBeUndefined();+ });++ it('rejects a token request naming another resource instead of minting an unusable token', async () => {+ seedClient();+ const res = await call('token', { method: 'POST', form: { grant_type: 'authorization_code', client_id: 'mcp_test_client', code: 'x', redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER, resource: 'https://evil.example/api/mcp' } });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('invalid_target');+ });++ it('accepts the canonical resource on the token request, trailing slash and all', async () => {+ seedClient();+ const authorized = await approve();+ const code = new URL(authorized.getHeader('location')).searchParams.get('code');+ const res = await call('token', { method: 'POST', form: { grant_type: 'authorization_code', client_id: 'mcp_test_client', code, redirect_uri: 'https://client.example/cb', code_verifier: VERIFIER, resource: `${RESOURCE}/` } });+ expect(res.statusCode).toBe(200);+ expect((await verifyAccessToken(res.json().access_token)).aud).toBe(RESOURCE);+ });++ it('rejects a refresh exchange naming another resource', async () => {+ seedClient();+ const { refresh_token } = await issueTokens();+ const res = await call('token', { method: 'POST', form: { grant_type: 'refresh_token', client_id: 'mcp_test_client', refresh_token, resource: 'https://evil.example/api/mcp' } });+ expect(res.statusCode).toBe(400);+ expect(res.json().error).toBe('invalid_target');+ });});describe('POST /oauth/register', () => {@@ -437,6 +481,20 @@ describe('POST /oauth/register', () => {expect(res.json()).not.toHaveProperty('client_secret_expires_at');});+ it('echoes back the optional metadata it stored, so a client is not told its fields were dropped', async () => {+ // RFC 7591 section 3.2.1 makes the response the authoritative record of what+ // was registered. These four were saved to oauth_clients but never returned,+ // which reads as "rejected" and invites a re-registration under a new id.+ const sent = { redirect_uris: ['https://client.example/cb'], client_name: 'Probe', client_uri: 'https://client.example', logo_uri: 'https://client.example/logo.png', software_id: 'probe-cli', software_version: '2.1.0' };+ const out = (await call('register', { method: 'POST', jsonBody: sent })).json();+ expect(out).toMatchObject({ client_uri: sent.client_uri, logo_uri: sent.logo_uri, software_id: sent.software_id, software_version: sent.software_version });+ });++ it('leaves the optional metadata out entirely when the client sent none', async () => {+ const out = (await call('register', { method: 'POST', jsonBody: { redirect_uris: ['https://client.example/cb'] } })).json();+ for (const k of ['client_uri', 'logo_uri', 'software_id', 'software_version']) expect(out).not.toHaveProperty(k);+ });+it.each([['javascript:alert(document.cookie)'],['data:text/html,<script>alert(1)</script>'],@@ -519,6 +577,7 @@ describe('POST /oauth/revoke', () => {const res = await call('revoke', { method: 'POST', headers: basicHeader('mcp_test_client', 'guessed'), form: { token: refresh_token } });expect(res.statusCode).toBe(401);expect(res.json().error).toBe('invalid_client');+ expect(res.getHeader('www-authenticate')).toMatch(/^Basic realm="oauth"/);expect(db.refresh[0].revoked_at).toBeNull();});});@@ -576,6 +635,7 @@ describe('POST /oauth/introspect', () => {const res = await call('introspect', { method: 'POST', headers: basicHeader('mcp_test_client', 'guessed'), form: { token: tokens.access_token } });expect(res.statusCode).toBe(401);expect(res.json().error).toBe('invalid_client');+ expect(res.getHeader('www-authenticate')).toMatch(/^Basic realm="oauth"/);});});