Add Apple Music, Last.fm sign-in, and a fallback for Spotify's account cap

- Apple Music: sign MusicKit developer tokens (ES256 via node:crypto),
  accept the Music User Token from the iOS app, and poll recently played.
  Apple has no now-playing API or play timestamps, so a new top song is
  shown as playing for its length; connecting records a baseline so an
  old song isn't announced as current
- Last.fm web auth ("Sign in with Last.fm") instead of typing a
  username; session key stored encrypted
- Spotify accounts rejected by the 5-user development cap are sent back
  with error=spotify_limited instead of a 500, so apps can offer
  Spotify via Last.fm

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MzFywujuH9TiuXbr9vjoX8
This commit is contained in:
2026-10-04 07:12:19 -04:00
co-authored by Claude Opus 5.5
parent 0b7907146d
commit ca97f1c3ac
11 changed files with 545 additions and 6 deletions
+169
View File
@@ -0,0 +1,169 @@
import { createPublicKey, verify } from 'node:crypto';
import { eq } from 'drizzle-orm';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { db, schema } from '../src/db';
import { appleDeveloperToken, resetAppleTokenCache } from '../src/lib/appleMusic';
import { appleMusicProvider } from '../src/providers/appleMusic';
import { ProviderAuthError } from '../src/providers/types';
import { bearer, createUser, json, routeFetch, useTestApp } from './helpers';
const app = useTestApp();
afterEach(() => vi.unstubAllGlobals());
const song = (id: string, name: string, extra: Record<string, unknown> = {}) => ({
id,
type: 'songs',
attributes: {
name,
artistName: 'Joy Division',
albumName: 'Closer',
durationInMillis: 240_000,
isrc: 'GBAAA8000001',
url: `https://music.apple.com/us/album/closer/1?i=${id}`,
artwork: { url: 'https://is1-ssl.mzstatic.com/image/thumb/x/{w}x{h}bb.jpg' },
...extra,
},
});
function stubApple(recent: () => unknown[], status = 200) {
const calls: { url: string; headers: Record<string, string> }[] = [];
vi.stubGlobal(
'fetch',
routeFetch([
[
/api\.music\.apple\.com\/v1\/me\/storefront/,
(url, init) => (calls.push({ url, headers: init?.headers as Record<string, string> }), json({ data: [{ id: 'us', attributes: { name: 'United States' } }] }, status)),
],
[
/api\.music\.apple\.com\/v1\/me\/recent\/played\/tracks/,
(url, init) => (calls.push({ url, headers: init?.headers as Record<string, string> }), json({ data: recent() }, status)),
],
]),
);
return calls;
}
async function connect(token: string) {
return app().inject({
method: 'POST',
url: '/connections/apple-music',
headers: bearer(token),
payload: { musicUserToken: 'music-user-token-from-ios-0123456789' },
});
}
describe('Apple Music developer token', () => {
it('is an ES256 JWT signed with the MusicKit key', () => {
resetAppleTokenCache();
const [header, payload, signature] = appleDeveloperToken().split('.');
expect(JSON.parse(Buffer.from(header!, 'base64url').toString())).toEqual({ alg: 'ES256', kid: 'KEYID12345' });
const claims = JSON.parse(Buffer.from(payload!, 'base64url').toString());
expect(claims.iss).toBe('TEAMID1234');
expect(claims.exp - claims.iat).toBeLessThanOrEqual(15_777_000); // Apple's 6-month maximum
const ok = verify(
'sha256',
Buffer.from(`${header}.${payload}`),
{ key: createPublicKey(process.env.APPLE_TEST_PUBLIC_KEY!), dsaEncoding: 'ieee-p1363' },
Buffer.from(signature!, 'base64url'),
);
expect(ok).toBe(true);
});
it('is cached rather than re-signed on every request', () => {
resetAppleTokenCache();
expect(appleDeveloperToken()).toBe(appleDeveloperToken());
});
it('is only handed to signed-in users', async () => {
expect((await app().inject({ url: '/connections/apple-music/developer-token' })).statusCode).toBe(401);
const { token } = await createUser(app(), 'alice');
const res = await app().inject({ url: '/connections/apple-music/developer-token', headers: bearer(token) });
expect(res.json().token.split('.')).toHaveLength(3);
});
});
describe('connecting Apple Music', () => {
it('validates the token, stores it encrypted, and baselines the last played song', async () => {
const calls = stubApple(() => [song('100', 'Atmosphere')]);
const { token, user } = await createUser(app(), 'alice');
const res = await connect(token);
expect(res.statusCode).toBe(200);
expect(res.json()).toMatchObject({ provider: 'apple_music', displayName: 'Apple Music (United States)', status: 'active' });
expect(calls[0]!.headers['Music-User-Token']).toBe('music-user-token-from-ios-0123456789');
expect(calls[0]!.headers.Authorization).toMatch(/^Bearer ey/);
const [row] = await db.select().from(schema.connections).where(eq(schema.connections.userId, user.id));
expect(row!.accessTokenEnc).not.toContain('music-user-token');
expect(row!.meta).toMatchObject({ storefront: 'us', lastSeenId: '100' });
});
it('rejects a token Apple refuses', async () => {
stubApple(() => [], 401);
const { token } = await createUser(app(), 'alice');
expect((await connect(token)).statusCode).toBe(401);
});
});
describe('Apple Music polling', () => {
async function connected(recent: { current: object[] }) {
stubApple(() => recent.current);
const { token, user } = await createUser(app(), 'alice');
await connect(token);
const load = async () => (await db.select().from(schema.connections).where(eq(schema.connections.userId, user.id)))[0]!;
return { load, user };
}
it("doesn't announce the song that was already last-played when connecting", async () => {
const recent: { current: object[] } = { current: [song('100', 'Atmosphere')] };
const { load } = await connected(recent);
expect(await appleMusicProvider.poll(await load())).toBeNull();
});
it('announces a newly played song with its Apple Music link, ISRC and artwork', async () => {
const recent: { current: object[] } = { current: [song('100', 'Atmosphere')] };
const { load } = await connected(recent);
recent.current = [song('200', 'Decades')];
const result = await appleMusicProvider.poll(await load());
expect(result).toMatchObject({
isPlaying: true,
track: {
title: 'Decades',
artist: 'Joy Division',
isrc: 'GBAAA8000001',
durationMs: 240_000,
artworkUrl: 'https://is1-ssl.mzstatic.com/image/thumb/x/600x600bb.jpg',
links: { apple_music: { id: '200', url: 'https://music.apple.com/us/album/closer/1?i=200' } },
},
});
});
it('keeps it playing for the song length, then stops', async () => {
const recent: { current: object[] } = { current: [song('100', 'Atmosphere')] };
const { load } = await connected(recent);
recent.current = [song('200', 'Decades')];
await appleMusicProvider.poll(await load());
expect((await appleMusicProvider.poll(await load()))?.isPlaying).toBe(true);
const conn = await load();
await db
.update(schema.connections)
.set({ meta: { ...(conn.meta as object), lastSeenAt: Date.now() - 240_000 - 31_000 } })
.where(eq(schema.connections.id, conn.id));
expect(await appleMusicProvider.poll(await load())).toBeNull();
});
it('library uploads play without a store link', async () => {
const recent: { current: object[] } = { current: [song('100', 'Atmosphere')] };
const { load } = await connected(recent);
recent.current = [{ id: 'i.abc', type: 'library-songs', attributes: { name: 'Home Demo', artistName: 'Me' } }];
const result = await appleMusicProvider.poll(await load());
expect(result?.track).toMatchObject({ title: 'Home Demo', links: undefined, isrc: null });
});
it('flags an expired Music User Token as needing reconnect', async () => {
const recent: { current: object[] } = { current: [song('100', 'Atmosphere')] };
const { load } = await connected(recent);
stubApple(() => [], 403);
await expect(appleMusicProvider.poll(await load())).rejects.toBeInstanceOf(ProviderAuthError);
});
});
+87
View File
@@ -0,0 +1,87 @@
import { createHash } from 'node:crypto';
import { eq } from 'drizzle-orm';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { db, schema } from '../src/db';
import { decrypt } from '../src/lib/crypto';
import { lastfmSignature } from '../src/providers/lastfm';
import { bearer, createUser, json, routeFetch, useTestApp } from './helpers';
const app = useTestApp();
afterEach(() => vi.unstubAllGlobals());
const stateFrom = (url: string) => decodeURIComponent(url).match(/state=([^&]+)/)![1]!;
describe('Last.fm sign-in', () => {
it('signs requests per the Last.fm rules: sorted name+value pairs, secret appended, md5', () => {
const expected = createHash('md5').update('api_keykmethodmtokent' + 's').digest('hex');
expect(lastfmSignature({ token: 't', method: 'm', api_key: 'k' }, 's')).toBe(expected);
});
it('runs the web auth flow and stores the username and session key', async () => {
let sessionUrl = '';
vi.stubGlobal(
'fetch',
routeFetch([[/auth\.getSession/, (url) => ((sessionUrl = url), json({ session: { name: 'RJ', key: 'sk-123', subscriber: 0 } }))]]),
);
const { token, user } = await createUser(app(), 'alice');
const start = await app().inject({
method: 'POST',
url: '/connections/lastfm/authorize',
headers: bearer(token),
payload: { client: 'mobile', returnTo: 'musicshare://settings' },
});
const authUrl = new URL(start.json().url);
expect(authUrl.host).toBe('www.last.fm');
expect(authUrl.searchParams.get('api_key')).toBe('test-lastfm-key');
const cb = new URL(authUrl.searchParams.get('cb')!);
expect(cb.href).toMatch(/^https:\/\/api\.test\/connections\/lastfm\/callback\?state=/);
const done = await app().inject({ url: `/connections/lastfm/callback?state=${stateFrom(cb.href)}&token=lfm-token` });
expect(done.statusCode).toBe(302);
expect(done.headers.location).toBe('musicshare://settings?connected=lastfm');
const params = new URL(sessionUrl).searchParams;
expect(params.get('api_sig')).toBe(
lastfmSignature({ api_key: 'test-lastfm-key', method: 'auth.getSession', token: 'lfm-token' }, 'test-lastfm-secret'),
);
const [row] = await db.select().from(schema.connections).where(eq(schema.connections.userId, user.id));
expect(row).toMatchObject({ provider: 'lastfm', externalUserId: 'RJ' });
expect(decrypt(row!.accessTokenEnc!)).toBe('sk-123');
});
it('returns to the app with an error if the user cancels', async () => {
const { token } = await createUser(app(), 'alice');
const start = await app().inject({ method: 'POST', url: '/connections/lastfm/authorize', headers: bearer(token), payload: { client: 'web' } });
const state = stateFrom(new URL(start.json().url).searchParams.get('cb')!);
const done = await app().inject({ url: `/connections/lastfm/callback?state=${state}` });
expect(done.headers.location).toMatch(/^http:\/\/web\.test\/settings\?error=/);
});
it('rejects replayed or forged states', async () => {
expect((await app().inject({ url: '/connections/lastfm/callback?state=forged&token=x' })).statusCode).toBe(400);
});
});
describe('Spotify sign-in during the limited beta', () => {
it('sends users who are not on the allowlist back with a friendly error instead of failing', async () => {
vi.stubGlobal(
'fetch',
routeFetch([
[/accounts\.spotify\.com\/api\/token/, () => json({ access_token: 'a', refresh_token: 'r', expires_in: 3600 })],
[/api\.spotify\.com\/v1\/me$/, () => json({ error: { status: 403, message: 'User not registered in the Developer Dashboard' } }, 403)],
]),
);
const { token } = await createUser(app(), 'alice');
const start = await app().inject({
method: 'POST',
url: '/connections/spotify/authorize',
headers: bearer(token),
payload: { client: 'mobile', returnTo: 'musicshare://settings' },
});
const state = new URL(start.json().url).searchParams.get('state');
const done = await app().inject({ url: `/connections/spotify/callback?state=${state}&code=abc` });
expect(done.statusCode).toBe(302);
expect(done.headers.location).toBe('musicshare://settings?error=spotify_limited');
expect(await db.select().from(schema.connections)).toHaveLength(0);
});
});