Add Spotiverse Spotify credential custody

This commit is contained in:
Meta Vens 2026-06-02 16:25:38 +01:00
commit e2a2f20693
15 changed files with 373 additions and 12 deletions

View file

@ -141,9 +141,40 @@ const streampixelsProfile: AppProfile = {
},
};
const spotiverseProfile: AppProfile = {
slug: "spotiverse",
displayName: "Spotiverse",
profileVersion: "2026-06-02",
identityProviders: ["spotify"],
entitlementSources: [],
managedConnectionProviders: ["spotify"],
capabilities: [
{
key: "spotify_player_read",
mode: "shared",
summary: "May read the linked Spotify account playback, queue, and device state.",
sharedRule: identityFacts.authenticated,
},
{
key: "spotify_queue_add",
mode: "shared",
summary: "May request add-to-queue through the Spotiverse command boundary.",
sharedRule: identityFacts.authenticated,
},
],
evaluateSharedCapabilities(context) {
if (!context.facts.has(identityFacts.authenticated)) {
return [];
}
return ["spotify_player_read", "spotify_queue_add"];
},
};
export const appProfiles: Record<AppSlug, AppProfile> = {
repixelizer: repixelizerProfile,
streampixels: streampixelsProfile,
spotiverse: spotiverseProfile,
};
export function getAppProfile(appSlug: AppSlug): AppProfile {

View file

@ -467,6 +467,10 @@ function acceptsBackendPolicy(appSlug: AppSlug, handoff: OAuthHandoff): boolean
return handoff.callbackUrl === "https://repixelizer.gamecult.org/api/auth/heimdall/callback";
}
if (appSlug === "spotiverse") {
return handoff.callbackUrl === "http://127.0.0.1:8796/auth/heimdall/callback";
}
return false;
}

View file

@ -1,8 +1,8 @@
export const providers = ["discord", "patreon", "github", "twitch", "youtube"] as const;
export const providers = ["discord", "patreon", "github", "twitch", "youtube", "spotify"] as const;
export type Provider = (typeof providers)[number];
export const appSlugs = ["repixelizer", "streampixels"] as const;
export const appSlugs = ["repixelizer", "streampixels", "spotiverse"] as const;
export type AppSlug = (typeof appSlugs)[number];

View file

@ -487,6 +487,108 @@ async function refreshYouTubeAccessToken(options: {
return tokenSet;
}
async function exchangeSpotifyAuthorizationCode(options: {
config: HeimdallConfig;
code: string;
redirectUri: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.spotify;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Spotify OAuth is not fully configured.");
}
const basicAuth = Buffer.from(`${providerConfig.clientId}:${providerConfig.clientSecret}`).toString("base64");
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://accounts.spotify.com/api/token",
{
method: "POST",
headers: {
Authorization: `Basic ${basicAuth}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "authorization_code",
code: options.code,
redirect_uri: options.redirectUri,
}),
},
"Spotify token exchange failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function refreshSpotifyAccessToken(options: {
config: HeimdallConfig;
refreshToken: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.spotify;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Spotify OAuth is not fully configured.");
}
const basicAuth = Buffer.from(`${providerConfig.clientId}:${providerConfig.clientSecret}`).toString("base64");
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://accounts.spotify.com/api/token",
{
method: "POST",
headers: {
Authorization: `Basic ${basicAuth}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: options.refreshToken,
}),
},
"Spotify token refresh failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function resolveDiscordIdentity(options: { accessToken: string }): Promise<ResolvedIdentity> {
const user = await fetchJson<{
id: string;
@ -740,6 +842,47 @@ async function resolveYouTubeIdentity(options: { accessToken: string }): Promise
return identity;
}
async function resolveSpotifyIdentity(options: { accessToken: string }): Promise<ResolvedIdentity> {
const profile = await fetchJson<{
id?: string;
display_name?: string;
email?: string;
images?: Array<{ url?: string }>;
uri?: string;
}>(
"https://api.spotify.com/v1/me",
{
headers: {
Authorization: `Bearer ${options.accessToken}`,
},
},
"Spotify identity lookup failed"
);
if (!profile.id) {
throw new Error("Spotify identity response did not include a user id.");
}
const identity: ResolvedIdentity = {
provider: "spotify",
providerUserId: profile.id,
username: profile.id,
displayName: profile.display_name ?? profile.id,
profile: profile as unknown as Record<string, unknown>,
};
if (profile.email) {
identity.primaryEmail = profile.email;
}
const avatarUrl = profile.images?.find((image) => image.url)?.url;
if (avatarUrl) {
identity.avatarUrl = avatarUrl;
}
return identity;
}
async function evaluateDiscordEntitlements(options: {
config: HeimdallConfig;
callback: OAuthCallbackContext;
@ -991,6 +1134,15 @@ const youtubeRuntime: OAuthProviderRuntime = {
},
};
const spotifyRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: exchangeSpotifyAuthorizationCode,
refreshAccessToken: refreshSpotifyAccessToken,
resolveIdentity: resolveSpotifyIdentity,
async evaluateEntitlements() {
return { facts: [], snapshots: [] };
},
};
const notImplementedRuntime: OAuthProviderRuntime = {
async exchangeAuthorizationCode() {
throw new Error("Provider callback exchange is not implemented yet.");
@ -1012,5 +1164,6 @@ export function createOAuthRuntimeRegistry(): OAuthRuntimeRegistry {
github: notImplementedRuntime,
twitch: twitchRuntime,
youtube: youtubeRuntime,
spotify: spotifyRuntime,
};
}

View file

@ -69,6 +69,19 @@ export const providerCatalog: Record<Provider, ProviderDescriptor> = {
prompt: "consent",
},
},
spotify: {
key: "spotify",
displayName: "Spotify",
authorizationEndpoint: "https://accounts.spotify.com/authorize",
defaultScopes: [
"user-read-currently-playing",
"user-read-playback-state",
"user-modify-playback-state",
],
roles: ["identity", "managed_credential"],
clientIdEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_ID",
clientSecretEnv: "GC_ACCESS_PROVIDER_SPOTIFY_CLIENT_SECRET",
},
};
export function buildAuthorizationUrl(options: {