Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions packages/core/src/auth/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'
import {AUTH_CODE_PARAM, DEFAULT_BASE} from './authConstants'
import {
getAuthCode,
getCleanedUrl,
getDefaultLocation,
getDefaultStorage,
getStorageEvents,
Expand Down Expand Up @@ -230,3 +231,36 @@ describe('getTokenFromLocation', () => {
expect(result).toBe(testToken)
})
})

describe('getCleanedUrl', () => {
it('removes only token from hash when it is the only param', () => {
const url = 'http://example.com/page#token=abc'
const cleaned = getCleanedUrl(url)
expect(cleaned).toBe('http://example.com/page')
})

it('removes only token from hash and preserves other hash params', () => {
const url = 'http://example.com/page#token=abc&foo=bar'
const cleaned = getCleanedUrl(url)
expect(cleaned).toBe('http://example.com/page#foo=bar')
})

it('removes token when it appears among multiple hash params', () => {
const url = 'http://example.com/page#foo=bar&token=abc&baz=qux'
const cleaned = getCleanedUrl(url)
expect(cleaned).toBe('http://example.com/page#foo=bar&baz=qux')
})

it('removes sid and url from query string while preserving others', () => {
const url =
'http://example.com/callback?sid=s1&url=https%3A%2F%2Freturn.example%2Fdone&x=1#token=abc'
const cleaned = getCleanedUrl(url)
expect(cleaned).toBe('http://example.com/callback?x=1')
})

it('preserves non key-value hash fragments', () => {
const url = 'http://example.com/page#section'
const cleaned = getCleanedUrl(url)
expect(cleaned).toBe('http://example.com/page#section')
})
})
12 changes: 10 additions & 2 deletions packages/core/src/auth/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,20 @@ export function getDefaultLocation(): string {
}

/**
* Cleans up the URL by removing the hash and the sid and url parameters.
* Cleans up the URL by removing the `token` from the hash and the `sid` and `url` search params.
* @internal
*/
export function getCleanedUrl(locationUrl: string): string {
const loc = new URL(locationUrl)
loc.hash = ''
// Remove only the `token` param from the hash while preserving other fragments
const rawHash = loc.hash.startsWith('#') ? loc.hash.slice(1) : loc.hash
if (rawHash && rawHash.includes('=')) {
const hashParams = new URLSearchParams(rawHash)
hashParams.delete('token')
hashParams.delete('withSid')
const nextHash = hashParams.toString()
loc.hash = nextHash ? `#${nextHash}` : ''
}
loc.searchParams.delete('sid')
loc.searchParams.delete('url')
return loc.toString()
Expand Down
Loading