Something went wrong. Try again.
An AI-music permissible frontend for plyr.fm.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock expo-web-browservi.mock('expo-web-browser', () => ({ openAuthSessionAsync: vi.fn(),}));
// Mock expo-auth-sessionvi.mock('expo-auth-session', () => ({ makeRedirectUri: vi.fn(() => 'plyr-dial://redirect'),}));
// Mock react-native Platformvi.mock('react-native', () => ({ Platform: { OS: 'web' },}));
// Mock global fetchconst mockFetch = vi.fn();vi.stubGlobal('fetch', mockFetch);
import * as WebBrowser from 'expo-web-browser';import { getAuthState, isAuthenticated, login, logout, getMe, authedFetch,} from '../lib/auth';
// We need to reset the module-level _authState between tests.// Since it's module-scoped, we'll use logout() to reset it.beforeEach(async () => { vi.clearAllMocks(); mockFetch.mockReset(); // Reset auth state by calling logout try { await logout(); } catch {}});
describe('auth.ts', () => { describe('getAuthState / isAuthenticated', () => { it('should start unauthenticated', () => { expect(isAuthenticated()).toBe(false); expect(getAuthState().sessionId).toBeNull(); });
it('should reflect authenticated state after login', async () => { // Mock the OAuth browser flow vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=exchange-token-123', });
// Mock the token exchange mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-abc' }), });
// Mock the /auth/me call mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'testuser', display_name: 'Test User' }), });
await login('testuser');
expect(isAuthenticated()).toBe(true); expect(getAuthState().sessionId).toBe('sess-abc'); expect(getAuthState().handle).toBe('testuser'); expect(getAuthState().displayName).toBe('Test User'); }); });
describe('login', () => { it('should complete full OAuth flow', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=exch-tok', });
// Token exchange mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-123' }), });
// /auth/me mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'myhandle', display_name: 'My Name' }), });
const state = await login('myhandle');
expect(state.sessionId).toBe('sess-123'); expect(state.handle).toBe('myhandle'); expect(state.displayName).toBe('My Name');
// Verify the exchange call expect(mockFetch).toHaveBeenCalledWith( 'https://api.plyr.fm/auth/exchange', expect.objectContaining({ method: 'POST', body: JSON.stringify({ token: 'exch-tok' }), }), ); });
it('should throw when browser auth is cancelled', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'cancel', url: undefined as any, });
await expect(login('test')).rejects.toThrow('Authentication cancelled or failed'); });
it('should throw when callback has no token', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?error=denied', });
await expect(login('test')).rejects.toThrow('No exchange token in callback'); });
it('should throw when token exchange fails', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=bad-token', });
mockFetch.mockResolvedValueOnce({ ok: false, status: 401, });
await expect(login('test')).rejects.toThrow('Token exchange failed: 401'); });
it('should still set session when /auth/me fails', async () => { vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=exch-tok', });
// Token exchange succeeds mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-456' }), });
// /auth/me fails mockFetch.mockResolvedValueOnce({ ok: false, status: 500, });
const state = await login('fallback');
expect(state.sessionId).toBe('sess-456'); expect(state.handle).toBe('fallback'); expect(state.displayName).toBeNull(); }); });
describe('logout', () => { it('should clear auth state', async () => { // First log in vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-out' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'x', display_name: 'X' }), });
await login('x'); expect(isAuthenticated()).toBe(true);
// Logout mockFetch.mockResolvedValueOnce({ ok: true }); await logout();
expect(isAuthenticated()).toBe(false); expect(getAuthState().sessionId).toBeNull(); });
it('should call the logout API endpoint', async () => { // Set up authenticated state vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-logout' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'y', display_name: 'Y' }), }); await login('y');
mockFetch.mockResolvedValueOnce({ ok: true }); await logout();
expect(mockFetch).toHaveBeenCalledWith( 'https://api.plyr.fm/auth/logout', expect.objectContaining({ method: 'POST', headers: expect.objectContaining({ Authorization: 'Bearer sess-logout', }), }), ); });
it('should clear state even if API call fails', async () => { // Set up authenticated state vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-fail' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'z', display_name: 'Z' }), }); await login('z');
// Logout API fails mockFetch.mockRejectedValueOnce(new Error('Network error'));
await logout();
expect(isAuthenticated()).toBe(false); });
it('should be a no-op when not authenticated', async () => { await logout(); expect(mockFetch).not.toHaveBeenCalled(); }); });
describe('getMe', () => { it('should throw when not authenticated', async () => { await expect(getMe()).rejects.toThrow('Not authenticated'); });
it('should fetch current user when authenticated', async () => { // Set up authenticated state vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-me' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'me', display_name: 'Me' }), }); await login('me');
// Now test getMe mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'me', display_name: 'Me', email: 'me@test.com' }), });
const user = await getMe(); expect(user.handle).toBe('me');
expect(mockFetch).toHaveBeenCalledWith( 'https://api.plyr.fm/auth/me', expect.objectContaining({ headers: expect.objectContaining({ Authorization: 'Bearer sess-me', }), }), ); }); });
describe('authedFetch', () => { it('should throw when not authenticated', async () => { await expect(authedFetch('/tracks')).rejects.toThrow('Not authenticated'); });
it('should include Authorization header when authenticated', async () => { // Set up authenticated state vi.mocked(WebBrowser.openAuthSessionAsync).mockResolvedValueOnce({ type: 'success', url: 'plyr-dial://redirect?token=tok', }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ session_id: 'sess-fetch' }), }); mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ handle: 'f', display_name: 'F' }), }); await login('f');
mockFetch.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) });
await authedFetch('/tracks', { method: 'POST' });
expect(mockFetch).toHaveBeenCalledWith( 'https://api.plyr.fm/tracks', expect.objectContaining({ method: 'POST', headers: expect.objectContaining({ Authorization: 'Bearer sess-fetch', 'Content-Type': 'application/json', }), }), ); }); });});