Files
musicshare/apps/api/test/apple-music.test.ts
chrisandClaude Opus 5.5 ca97f1c3ac 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
2026-10-04 07:12:19 -04:00

170 lines
7.1 KiB
TypeScript

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);
});
});