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 = {}) => ({ 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 }[] = []; vi.stubGlobal( 'fetch', routeFetch([ [ /api\.music\.apple\.com\/v1\/me\/storefront/, (url, init) => (calls.push({ url, headers: init?.headers as Record }), 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 }), 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); }); });