Skip to content
Draft
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
7 changes: 6 additions & 1 deletion app/listen/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,13 @@ export async function GET(
if (value) campaign.set(key, value.slice(0, 100));
}
const suffix = campaign.size ? `?${escape(campaign.toString())}` : "";
const spotifyUnconfigured =
config.capabilities?.spotify.clientConfiguration === "unconfigured";
const spotifyLabel = spotifyUnconfigured
? "Open player"
: "Sign in with Spotify";
return new Response(
`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(config.name)} · Recoup</title><link rel="stylesheet" href="/release-listen.css"></head><body><main>${config.artwork ? `<img src="${escape(config.artwork)}" alt="${escape(config.name)} artwork">` : ""}<h1>${escape(config.name)}</h1><p>Choose where to listen.</p>${config.spotifyUrl ? `<a class="spotify" href="/listen/${id}/spotify${suffix}">Sign in with Spotify</a><a class="fallback" href="${escape(config.spotifyUrl)}" rel="noopener noreferrer">Open Spotify</a>` : ""}${config.appleUrl ? `<a class="apple" href="/listen/${id}/apple_music${suffix}">Sign in with Apple</a><a class="fallback" href="${escape(config.appleUrl)}" rel="noopener noreferrer">Open Apple Music</a>` : ""}</main></body></html>`,
`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(config.name)} · Recoup</title><link rel="stylesheet" href="/release-listen.css"></head><body><main>${config.artwork ? `<img src="${escape(config.artwork)}" alt="${escape(config.name)} artwork">` : ""}<h1>${escape(config.name)}</h1><p>Choose where to listen.</p>${config.spotifyUrl ? `${spotifyUnconfigured ? "<p>Spotify sign-in is unavailable.</p>" : ""}${!spotifyUnconfigured || config.freePlayback === "audio" ? `<a class="spotify" href="/listen/${id}/spotify${suffix}">${spotifyLabel}</a>` : ""}<a class="fallback" href="${escape(config.spotifyUrl)}" rel="noopener noreferrer">Open Spotify</a>` : ""}${config.appleUrl ? `<a class="apple" href="/listen/${id}/apple_music${suffix}">Sign in with Apple</a><a class="fallback" href="${escape(config.appleUrl)}" rel="noopener noreferrer">Open Apple Music</a>` : ""}</main></body></html>`,
{
headers: {
"Content-Type": "text/html; charset=utf-8",
Expand Down
148 changes: 148 additions & 0 deletions lib/players/__tests__/playerCapabilities.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { getPlayerConfig } from "../getPlayerConfig";
import { GET } from "@/app/listen/[id]/route";
import { spotifyRuntimeHarness } from "@/lib/sites/__tests__/fixtures/spotifyRuntimeHarness";
const id = "10000000-0000-4000-8000-000000000001";
const capabilities = (configured = false) => ({
version: 1,
spotify: {
clientConfiguration: configured ? "configured" : "unconfigured",
releaseConfigured: true,
premiumEligibility: "unknown",
tokenStatus: "unknown",
scopeStatus: "unknown",
playbackSupport: "unknown",
},
});
const base = {
playerId: id,
name: "Release <img src=x>",
spotifyUrl: "https://open.spotify.com/track/abc",
appleUrl: "https://music.apple.com/us/album/song/123",
revision: 1,
freePlayback: "spotify",
};
beforeEach(() => vi.stubGlobal("fetch", vi.fn()));
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
});
function serve(value: unknown) {
vi.mocked(fetch).mockImplementation(async () => Response.json(value));
}
it("retains a validated v1 observation without exposing unexpected properties", async () => {
serve({
...base,
capabilities: { ...capabilities(), privateToken: "never" },
});
expect(await getPlayerConfig(id, new URLSearchParams())).toMatchObject({
capabilities: capabilities(),
});
const result = await getPlayerConfig(id, new URLSearchParams());
expect(result).not.toHaveProperty("capabilities.privateToken");
});
it.each([
undefined,
{ version: 2, spotify: { clientConfiguration: "unconfigured" } },
])("ignores legacy/future capability shapes (%j)", async (value) => {
serve({ ...base, capabilities: value });
expect(
(await getPlayerConfig(id, new URLSearchParams())).capabilities,
).toBeUndefined();
});
it.each([
{ version: 1 },
{ version: 1, spotify: { ...capabilities().spotify, tokenStatus: "valid" } },
{
version: 1,
spotify: { ...capabilities().spotify, releaseConfigured: "yes" },
},
])("rejects malformed v1 (%j)", async (value) => {
serve({ ...base, capabilities: value });
await expect(getPlayerConfig(id, new URLSearchParams())).rejects.toThrow();
});
it.each(["spotify", "audio"])(
"avoids an impossible sign-in invitation while retaining %s fallback",
async (mode) => {
serve({ ...base, freePlayback: mode, capabilities: capabilities() });
const response = await GET(
new Request(
"https://app.recoupable.dev/listen/" +
id +
"?campaign=%22%3E%3Cscript%3E",
),
{ params: Promise.resolve({ id }) },
);
const html = await response.text();
expect(html).toContain("Spotify sign-in is unavailable.");
expect(html).not.toContain("Sign in with Spotify");
expect(html).toContain("Open Spotify");
expect(html.includes("Open player")).toBe(mode === "audio");
expect(html).toContain("Sign in with Apple");
expect(html).toContain("Release &lt;img src=x&gt;");
expect(html).not.toContain("<script>");
expect(html).toContain("campaign=%22%3E%3Cscript%3E");
expect(response.headers.get("Cache-Control")).toBe("no-store");
expect(fetch).toHaveBeenCalledTimes(1);
expect(vi.mocked(fetch).mock.calls[0][1]).not.toHaveProperty("method");
expect(String(vi.mocked(fetch).mock.calls[0][0])).not.toContain("/session");
},
);
it.each([
undefined,
capabilities(true),
{ version: 2, spotify: { clientConfiguration: "unconfigured" } },
])(
"preserves configured/legacy/future chooser behavior (%j)",
async (value) => {
serve({ ...base, capabilities: value });
const html = await (
await GET(new Request("https://app.recoupable.dev/listen/" + id), {
params: Promise.resolve({ id }),
})
).text();
expect(html).toContain("Sign in with Spotify");
},
);
it("retains Apple-only choices", async () => {
serve({
...base,
spotifyUrl: null,
capabilities: {
...capabilities(),
spotify: { ...capabilities().spotify, releaseConfigured: false },
},
});
const html = await (
await GET(new Request("https://app.recoupable.dev/listen/" + id), {
params: Promise.resolve({ id }),
})
).text();
expect(html).not.toContain("Open Spotify");
expect(html).toContain("Sign in with Apple");
});
it.each([
[false, true],
[true, false],
])(
"capabilities never override a negative configuration guard (%s,%s)",
async (capConfigured, legacyConfigured) => {
const h = spotifyRuntimeHarness(false, null, "?authorize=tab");
Object.assign(h.ctx.document.body.dataset, {
playerConfig: JSON.stringify({
capabilities: capabilities(capConfigured),
spotify: {
configured: legacyConfigured,
clientId: "public",
redirectUri: "https://example.test/s/spotify/callback",
scopes: [],
},
}),
});
await h.run();
expect(h.nodes["spotify-connect"].disabled).toBe(true);
expect(h.fetch).not.toHaveBeenCalled();
expect(h.ctx.location.assign).not.toHaveBeenCalled();
expect(h.nodes["spotify-status"].textContent).toContain("not configured");
},
);
22 changes: 22 additions & 0 deletions lib/players/getPlayerConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,28 @@ const dsp = z
.url()
.refine((value) => new URL(value).protocol === "https:");
const configSchema = z.object({
capabilities: z.preprocess(
(value) =>
value &&
typeof value === "object" &&
"version" in value &&
value.version === 1
? value
: undefined,
z
.object({
version: z.literal(1),
spotify: z.object({
clientConfiguration: z.enum(["configured", "unconfigured"]),
releaseConfigured: z.boolean(),
premiumEligibility: z.literal("unknown"),
tokenStatus: z.literal("unknown"),
scopeStatus: z.literal("unknown"),
playbackSupport: z.literal("unknown"),
}),
})
.optional(),
),
playerId: z.string().uuid(),
name: z.string().max(120),
artwork: dsp.nullable().optional(),
Expand Down
21 changes: 21 additions & 0 deletions lib/sites/__tests__/spotifyFreeHandoff.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,24 @@ it("requests the API-configured permissions for registered-player authorization"
"streaming user-read-playback-state",
);
});

it("does not turn unconfigured audio mode into permission for uploaded playback", async () => {
const h = listeningHarness("free");
const audio = addUploadedAudio(h);
h.storage.clear();
const dataset = h.ctx.document.body.dataset as Record<string, string>;
const config = JSON.parse(dataset.playerConfig);
dataset.playerConfig = JSON.stringify({
...config,
capabilities: {
version: 1,
spotify: { clientConfiguration: "unconfigured" },
},
});
await h.run();
expect(h.nodes["spotify-connect"].disabled).toBe(true);
expect(dataset.playbackSource).not.toBe("audio");
expect(audio.play).not.toHaveBeenCalled();
expect(h.fetch).not.toHaveBeenCalled();
expect(h.head.appendChild).not.toHaveBeenCalled();
});
3 changes: 3 additions & 0 deletions public/sites-runtime.js
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,9 @@
const config = await configResponse.json();
if (
!config.configured ||
(playerConfig?.capabilities?.version === 1 &&
playerConfig.capabilities.spotify.clientConfiguration ===
"unconfigured") ||
(document.body.dataset.fanSite === "true" && !fanConnectUrl)
) {
connect.disabled = true;
Expand Down
Loading