import { describe, expect, it } from 'vitest' import { callbackFromUpdate, oauthRedirectUri, replacedSession } from './authflow' const REDIRECT = oauthRedirectUri('degljbilkggdpbobomfbgnellecgbkjj') describe('oauthRedirectUri', () => { it('matches the redirect_uri registered in the client metadata', () => { expect(REDIRECT).toBe('https://degljbilkggdpbobomfbgnellecgbkjj.chromiumapp.org/oauth2') }) }) describe('callbackFromUpdate', () => { it('finds the callback in changeInfo.url', () => { const url = `${REDIRECT}?code=abc&state=xyz` expect(callbackFromUpdate(REDIRECT, { url }, {})).toBe(url) }) it('finds the callback in pendingUrl while the navigation is provisional', () => { const url = `${REDIRECT}?code=abc` expect(callbackFromUpdate(REDIRECT, {}, { pendingUrl: url, url: 'https://pds.example/consent' })).toBe(url) }) it('finds the callback in the committed tab url', () => { const url = `${REDIRECT}?error=access_denied` expect(callbackFromUpdate(REDIRECT, { url: undefined }, { url })).toBe(url) }) it('ignores consent-page navigations', () => { expect( callbackFromUpdate(REDIRECT, { url: 'https://pds.example/oauth/authorize?x=1' }, {}), ).toBeUndefined() }) it('ignores lookalike paths on the redirect host', () => { expect(callbackFromUpdate(REDIRECT, { url: `${REDIRECT}x?code=abc` }, {})).toBeUndefined() }) it('accepts the bare redirect with no query', () => { expect(callbackFromUpdate(REDIRECT, { url: REDIRECT }, {})).toBe(REDIRECT) }) // Firefox turns the failed navigation into its own error page and keeps the // attempted URL in `u`, so the callback is one decode away rather than // visible as the tab URL. it('unwraps the original URL from a Firefox about:neterror page', () => { const url = `${REDIRECT}?code=abc&state=xyz` const neterror = `about:neterror?e=dnsNotFound&u=${encodeURIComponent(url)}&d=firefox` expect(callbackFromUpdate(REDIRECT, { url: neterror }, {})).toBe(url) }) it('finds the wrapped callback in the committed tab url too', () => { const url = `${REDIRECT}?error=access_denied` const neterror = `about:neterror?e=dnsNotFound&u=${encodeURIComponent(url)}` expect(callbackFromUpdate(REDIRECT, {}, { url: neterror })).toBe(url) }) it('ignores a neterror page for some other failed navigation', () => { const neterror = `about:neterror?e=dnsNotFound&u=${encodeURIComponent('https://pds.example/oauth/authorize?x=1')}` expect(callbackFromUpdate(REDIRECT, { url: neterror }, {})).toBeUndefined() }) }) describe('replacedSession', () => { it('retires the previous account after a switch', () => { expect(replacedSession({ did: 'did:plc:old' }, { did: 'did:plc:new' })).toBe('did:plc:old') }) it('keeps a fresh sign-in when there was nothing before', () => { expect(replacedSession(undefined, { did: 'did:plc:new' })).toBeUndefined() }) it('never revokes a re-sign-in to the same account (same sub, same stored session)', () => { expect(replacedSession({ did: 'did:plc:same' }, { did: 'did:plc:same' })).toBeUndefined() }) })