Skip to content

Commit

Permalink
maybe?
Browse files Browse the repository at this point in the history
  • Loading branch information
pauldambra committed Nov 14, 2023
1 parent e3f67cf commit f723d39
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
40 changes: 39 additions & 1 deletion src/__tests__/storage.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,45 @@
import { window } from '../../src/utils/globals'
import { resetSessionStorageSupported, sessionStore } from '../storage'
import { resetSessionStorageSupported, seekFirstNonPublicSubDomain, sessionStore } from '../storage'

describe('sessionStore', () => {
describe('seekFirstNonPublicSubDomain', () => {
const mockDocumentDotCookie = {
value_: '',

get cookie() {
return this.value_
},

set cookie(value) {
//needs to refuse known public suffixes, like a browser would
// value arrives like dmn_chk_1699961248575=1;domain=.uk
const domain = value.split('domain=')
if (['.uk', '.com', '.au', '.com.au', '.co.uk'].includes(domain[1])) return
this.value_ += value + ';'
},
}
test.each([
{
candidate: 'www.google.co.uk',
expected: 'google.co.uk',
},
{
candidate: 'www.google.com',
expected: 'google.com',
},
{
candidate: 'www.google.com.au',
expected: 'google.com.au',
},
{
candidate: 'localhost',
expected: '',
},
])(`%s subdomain check`, ({ candidate, expected }) => {
expect(seekFirstNonPublicSubDomain(candidate, mockDocumentDotCookie)).toEqual(expected)
})
})

it('stores objects as strings', () => {
sessionStore.set('foo', { bar: 'baz' })
expect(sessionStore.get('foo')).toEqual('{"bar":"baz"}')
Expand Down
12 changes: 6 additions & 6 deletions src/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ const Y1970 = 'Thu, 01 Jan 1970 00:00:00 GMT'
*
* inspired by https://github.com/AngusFu/browser-root-domain
*/
function seekFirstNonPublicSubDomain(hostname: string): string {
// eslint-disable-next-line no-console
console.log('seekFirstNonPublicSubDomain:', hostname)
export function seekFirstNonPublicSubDomain(hostname: string, cookieJar = document): string {
if (['localhost', '127.0.0.1'].includes(hostname)) return ''

const list = hostname.split('.')
let len = list.length
const key = 'dmn_chk_' + +new Date()
Expand All @@ -33,11 +33,11 @@ function seekFirstNonPublicSubDomain(hostname: string): string {
const candidateCookieValue = key + '=1;domain=.' + candidate

// try to set cookie
document.cookie = candidateCookieValue
cookieJar.cookie = candidateCookieValue

if (R.test(document.cookie)) {
if (R.test(cookieJar.cookie)) {
// the cookie was accepted by the browser, remove the test cookie
document.cookie = candidateCookieValue + ';expires=' + Y1970
cookieJar.cookie = candidateCookieValue + ';expires=' + Y1970
return candidate
}
}
Expand Down

0 comments on commit f723d39

Please sign in to comment.