Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/mcp/tools/players/registerGetReleasePlayerTool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ export function registerGetReleasePlayerTool(server: McpServer) {
server.registerTool(
"get_release_player",
{
description: "Read release player configuration, current revision and share/embed links.",
description:
"Read release player configuration, current revision and share/embed links. Capabilities v1 reports Spotify client/destination configuration; premium eligibility, token, scope and playback observations remain unknown.",
inputSchema: playerOperationSchemas.get,
annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },
},
Expand Down
22 changes: 22 additions & 0 deletions lib/players/__tests__/getPlayerCapabilities.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { afterEach, expect, it, vi } from "vitest";
import { getPlayerCapabilities } from "../getPlayerCapabilities";
afterEach(() => vi.unstubAllEnvs());
it.each([
["", null],
["", "https://open.spotify.com/track/abc"],
["public-client-id", null],
["public-client-id", "https://open.spotify.com/track/abc"],
])("projects only configuration, never fan observations (%s, %s)", (client, release) => {
vi.stubEnv("SITES_SPOTIFY_CLIENT_ID", client as string);
expect(getPlayerCapabilities(release)).toEqual({
version: 1,
spotify: {
clientConfiguration: client ? "configured" : "unconfigured",
releaseConfigured: !!release,
premiumEligibility: "unknown",
tokenStatus: "unknown",
scopeStatus: "unknown",
playbackSupport: "unknown",
},
});
});
71 changes: 71 additions & 0 deletions lib/players/__tests__/processPlayerOperation.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
import { beforeEach, expect, it, vi } from "vitest";
import { processPlayerOperation } from "../processPlayerOperation";
import { afterEach } from "vitest";
import { NextRequest, NextResponse } from "next/server";
import { playerOperationHandler } from "../playerOperationHandler";
import { getPlayerToolHandler } from "@/lib/mcp/tools/players/getPlayerToolHandler";
import { getToolResultSuccess } from "@/lib/mcp/getToolResultSuccess";
import { SiteError } from "@/lib/sites/SiteError";
const auth = vi.hoisted(() => ({ http: vi.fn(), mcp: vi.fn() }));
vi.mock("@/lib/auth/validateAuthContext", () => ({ validateAuthContext: auth.http }));
vi.mock("@/lib/mcp/resolveAccountId", () => ({ resolveAccountId: auth.mcp }));
vi.mock("../readPlayerReport", () => ({ readPlayerReport: vi.fn() }));
vi.mock("../readPlayerFans", () => ({ readPlayerFans: vi.fn() }));
vi.mock("../readWorkspacePlayerFans", () => ({ readWorkspacePlayerFans: vi.fn() }));
vi.mock("@/lib/sites/activity/limitSiteRequest", () => ({ limitSiteRequest: vi.fn() }));
const mocks = vi.hoisted(() => ({
access: vi.fn(),
Expand Down Expand Up @@ -55,6 +67,7 @@ it("derives ownership and creates a disabled reusable release player", async ()
created_by: owner,
}),
);
expect(result).not.toHaveProperty("capabilities");
expect(result).toHaveProperty("listenUrl", `https://app.recoupable.dev/listen/${artist}`);
});
it("blocks an artist outside the workspace", async () => {
Expand Down Expand Up @@ -138,6 +151,7 @@ it("paginates the workspace catalog instead of silently truncating it", async ()
const result = await processPlayerOperation(owner, "list", { offset: 100, limit: 1 });
expect(mocks.list).toHaveBeenCalledWith(owner, 100, 1);
expect(result).toMatchObject({ offset: 100, limit: 1, nextOffset: 101 });
expect(result).not.toHaveProperty("capabilities");
});

it("stores the owner-selected fallback and rejects non-owned audio before creating", async () => {
Expand Down Expand Up @@ -215,3 +229,60 @@ it("can unpublish or change a title without rechecking unchanged audio", async (
processPlayerOperation(owner, "update", { id: artist, revision: 1, enabled: true }),
).rejects.toThrow("Storage unavailable");
});

it("returns the same capabilities through real HTTP and MCP get domains", async () => {
vi.stubEnv("SITES_SPOTIFY_CLIENT_ID", "");
vi.stubEnv("PLAYER_APP_ORIGIN", "not-an-origin");
mocks.select.mockResolvedValue({
id: artist,
owner_id: owner,
enabled: false,
spotify_url: "https://open.spotify.com/track/abc",
});
auth.http.mockResolvedValue({ accountId: owner });
auth.mcp.mockResolvedValue({ accountId: owner });
const response = await playerOperationHandler(
new NextRequest("https://api.example/api/players/" + artist),
"get",
{ id: artist },
);
expect(response.status).toBe(200);
expect(response.headers.get("Cache-Control")).toBe("private, no-store");
const body = await response.json();
expect(body.capabilities).toEqual({
version: 1,
spotify: {
clientConfiguration: "unconfigured",
releaseConfigured: true,
premiumEligibility: "unknown",
tokenStatus: "unknown",
scopeStatus: "unknown",
playbackSupport: "unknown",
},
});
const tool = await getPlayerToolHandler("get")({ id: artist }, { authInfo: {} });
expect(tool).toEqual(getToolResultSuccess(body));
expect(body.player.enabled).toBe(false);
});
it("preserves HTTP/MCP authentication and ownership denial before player read results", async () => {
auth.http.mockResolvedValue(NextResponse.json({ error: "Unauthorized" }, { status: 401 }));
auth.mcp.mockResolvedValue({ accountId: null });
expect(
(await playerOperationHandler(new NextRequest("https://api.example"), "get", { id: artist }))
.status,
).toBe(401);
expect(await getPlayerToolHandler("get")({ id: artist }, {})).toMatchObject({ isError: true });
expect(mocks.select).not.toHaveBeenCalled();
auth.http.mockResolvedValue({ accountId: owner });
mocks.select.mockResolvedValue({ owner_id: "another-owner" });
expect(
(await playerOperationHandler(new NextRequest("https://api.example"), "get", { id: artist }))
.status,
).toBe(404);
mocks.access.mockRejectedValueOnce(new SiteError(403, "Workspace denied"));
expect(
(await playerOperationHandler(new NextRequest("https://api.example"), "get", { id: artist }))
.status,
).toBe(403);
});
afterEach(() => vi.unstubAllEnvs());
76 changes: 75 additions & 1 deletion lib/players/__tests__/publicPlayer.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { beforeEach, expect, it, vi } from "vitest";
import { GET as publicGet } from "@/app/api/players/public/[id]/route";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { getPublicPlayer } from "../getPublicPlayer";
const m = vi.hoisted(() => ({
select: vi.fn(),
Expand Down Expand Up @@ -101,3 +102,76 @@ it("exposes configured audio only to Spotify provider sessions, not the chooser
await getPublicPlayer(id, { provider: "apple_music", parent: "https://artist.example" }, true),
).toMatchObject({ audioUrl: null });
});

it.each(["", "public-client-id"])(
"exposes credential-free capabilities without creating a session (%s)",
async client => {
vi.stubEnv("SITES_SPOTIFY_CLIENT_ID", client);
vi.stubEnv("PLAYER_APP_ORIGIN", "https://app.recoupable.dev");
const result = await getPublicPlayer(id, {});
expect(result).toMatchObject({
capabilities: {
version: 1,
spotify: {
clientConfiguration: client ? "configured" : "unconfigured",
releaseConfigured: true,
premiumEligibility: "unknown",
tokenStatus: "unknown",
scopeStatus: "unknown",
playbackSupport: "unknown",
},
},
});
expect(result).not.toHaveProperty("spotify");
expect(result).not.toHaveProperty("flow");
expect(m.insert).not.toHaveBeenCalled();
},
);
it("retains capability unknowns on fresh and resumed provider sessions", async () => {
vi.stubEnv("SITES_SPOTIFY_CLIENT_ID", "");
const first = await getPublicPlayer(
id,
{ provider: "spotify", parent: "https://artist.example" },
true,
);
expect(first).toMatchObject({
spotify: { configured: false },
capabilities: { spotify: { clientConfiguration: "unconfigured", tokenStatus: "unknown" } },
});
expect(m.insert).toHaveBeenCalledTimes(1);
if (!("flow" in first)) throw new Error("Expected session");
m.session.mockResolvedValue({ ...m.insert.mock.calls[0][0], provider: "spotify" });
const resumed = await getPublicPlayer(
id,
{ provider: "spotify", parent: "https://artist.example", flow: first.flow },
true,
);
expect(resumed).toMatchObject({ flow: first.flow, capabilities: first.capabilities });
expect(m.insert).toHaveBeenCalledTimes(1);
});

afterEach(() => {
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});

it("keeps metadata GET credential-free, no-store and free of provider/session work", async () => {
const fetch = vi.fn();
vi.stubGlobal("fetch", fetch);
const response = await publicGet(new Request("https://api.example/api/players/public/" + id), {
params: Promise.resolve({ id }),
});
expect(response.status).toBe(200);
expect(response.headers.get("Cache-Control")).toBe("no-store");
const body = await response.json();
expect(body.capabilities.version).toBe(1);
expect(body).not.toHaveProperty("spotify");
expect(body).not.toHaveProperty("flow");
expect(m.insert).not.toHaveBeenCalled();
expect(fetch).not.toHaveBeenCalled();
});
it("preserves invalid public origin configuration failure", async () => {
vi.stubEnv("PLAYER_APP_ORIGIN", "invalid");
await expect(getPublicPlayer(id, {})).rejects.toThrow();
expect(m.insert).not.toHaveBeenCalled();
});
16 changes: 16 additions & 0 deletions lib/players/getPlayerCapabilities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/** Configuration observations only; never proof of fan eligibility or playback authority. */
export function getPlayerCapabilities(spotifyUrl: string | null) {
return {
version: 1 as const,
spotify: {
clientConfiguration: process.env.SITES_SPOTIFY_CLIENT_ID
? ("configured" as const)
: ("unconfigured" as const),
releaseConfigured: !!spotifyUrl,
premiumEligibility: "unknown" as const,
tokenStatus: "unknown" as const,
scopeStatus: "unknown" as const,
playbackSupport: "unknown" as const,
},
};
}
12 changes: 12 additions & 0 deletions lib/players/getPlayerReadResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { getPlayerCapabilities } from "./getPlayerCapabilities";
import { getPlayerLinks } from "./getPlayerLinks";
import type { ReleasePlayer } from "./schema";

/** Project the player only after the caller has verified workspace ownership. */
export function getPlayerReadResponse(player: ReleasePlayer) {
return {
player,
...getPlayerLinks(player.id),
capabilities: getPlayerCapabilities(player.spotify_url),
};
}
2 changes: 2 additions & 0 deletions lib/players/getPublicPlayer.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getPlayerCapabilities } from "./getPlayerCapabilities";
import { randomUUID } from "node:crypto";
import { z } from "zod";
import { selectReleasePlayer } from "@/lib/supabase/release_players/selectReleasePlayer";
Expand Down Expand Up @@ -43,6 +44,7 @@ export async function getPublicPlayer(id: string, input: unknown, createSession
appleUrl: player.apple_url,
revision: player.revision,
freePlayback: player.free_playback ?? "spotify",
capabilities: getPlayerCapabilities(player.spotify_url),
};
if (!query.provider) return result;
const release = query.provider === "spotify" ? player.spotify_url : player.apple_url;
Expand Down
3 changes: 2 additions & 1 deletion lib/players/processPlayerOperation.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getPlayerReadResponse } from "./getPlayerReadResponse";
import { requirePlayerAudio } from "./requirePlayerAudio";
import { limitSiteRequest } from "@/lib/sites/activity/limitSiteRequest";
import { z } from "zod";
Expand Down Expand Up @@ -60,7 +61,7 @@ export async function processPlayerOperation(
const id = z.object({ id: z.string().uuid() }).parse(input).id;
const player = await selectReleasePlayer(id);
if (!player || player.owner_id !== owner) throw new SiteError(404, "Player not found");
if (operation === "get") return { player, ...getPlayerLinks(player.id) };
if (operation === "get") return getPlayerReadResponse(player);
const update = playerOperationSchemas.update.parse(input);
if (player.revision !== update.revision)
throw new SiteError(409, "Player changed; read the latest revision");
Expand Down
Loading