Skip to content
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"docs:dev": "vitepress dev docs",
"docs:preview": "vitepress preview docs",
"get-contributors": "npx get-contributors cssnr/auto-auth -f docs/.vitepress/contributors.json",
"prettier": "npm run prettier:write",
"prettier:check": "npx prettier --check .",
"prettier:write": "npx prettier --write .",
"lint": "npx eslint src",
Expand Down
8 changes: 4 additions & 4 deletions src/components/HostModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ async function onSubmit() {

// existing
if (isAdding.value || hostRef.value !== originalHost.value) {
const existing = await Hosts.get(hostRef.value)
debug('existing:', existing)
if (existing) {
const exists = await Hosts.has(hostRef.value)
debug('existing:', exists)
if (exists) {
debug('Existing Host:', hostRef.value)
hostnameEl.value?.focus()
hostnameEl.value?.select()
Expand All @@ -100,7 +100,7 @@ async function onSubmit() {
if (!passRef.value) {
debug('No password')
passwordEl.value?.focus()
passInvalid.value = `${i18n.t('ui.text.password')} ${i18n.t('ui.text.password')}`
passInvalid.value = `${i18n.t('ui.text.password')} ${i18n.t('ui.text.invalid')}`
return
}

Expand Down
32 changes: 18 additions & 14 deletions src/entrypoints/auth/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { openOptions } from '@/utils/extension.ts'
import { getSession, saveKeyValue } from '@/utils/options.ts'
import { useOptions } from '@/composables/useOptions.ts'
import { showToast } from '@/composables/useToast.ts'
import { Hosts } from '@/utils/hosts.ts'
import { Hosts, findBestWildcardMatch } from '@/utils/hosts.ts'
import ToastAlerts from '@/components/ToastAlerts.vue'
import BackToTop from '@/components/BackToTop.vue'
import OptionsOffscreen from '@/components/OptionsOffscreen.vue'
Expand Down Expand Up @@ -93,6 +93,14 @@ function saveCredsChange(event?: Event) {
sessionStorage.setItem(hostRef.value, saveCreds.value ? '1' : '0')
}

async function populateFields(credsStr: string) {
const [username, password] = parseCreds(credsStr)
userRef.value = username
await nextTick()
usernameEl.value?.select()
passRef.value = password
}

onMounted(async () => {
// NOTE: Copied from VanillaJS...
const searchParams = new URLSearchParams(window.location.search)
Expand All @@ -117,24 +125,20 @@ onMounted(async () => {
debug('session:', session)

if (creds) {
debug('if creds:', creds)
hasSavedCreds.value = true
if (creds !== 'ignored') {
const [username, password] = parseCreds(creds)
userRef.value = username
debug('usernameEl.value:', usernameEl.value)
await nextTick()
usernameEl.value?.select()
passRef.value = password
debug('if creds:', creds)
await populateFields(creds)
}
} else if (hostRef.value in session) {
debug('else hostRef.value in session:', hostRef.value)
const [username, password] = parseCreds(session[hostRef.value])
userRef.value = username
debug('usernameEl.value:', usernameEl.value)
await nextTick()
usernameEl.value?.select()
passRef.value = password
await populateFields(session[hostRef.value])
} else {
const bestMatch = findBestWildcardMatch(hostRef.value, session)
if (bestMatch) {
debug('session wildcard match:', bestMatch)
await populateFields(bestMatch)
}
}

const link = document.querySelector<HTMLLinkElement>('link[rel*="icon"]')
Expand Down
16 changes: 11 additions & 5 deletions src/entrypoints/background/auth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { parseCreds } from '@/utils/creds.ts'
import { getOptions, getSession } from '@/utils/options.ts'
import { Hosts } from '@/utils/hosts.ts'
import { Hosts, findBestWildcardMatch } from '@/utils/hosts.ts'

// TODO: Logging

Expand All @@ -10,7 +10,11 @@ export function onAuthRequired(
details: chrome.webRequest.OnAuthRequiredDetails,
asyncCallback?: (response: chrome.webRequest.BlockingResponse) => void,
): chrome.webRequest.BlockingResponse | undefined {
processRequest(details, asyncCallback).catch(console.warn)
// TODO: if (!asyncCallback) throw - should be called here...
processRequest(details, asyncCallback).catch((e) => {
console.warn(e)
if (asyncCallback) asyncCallback({})
})
return undefined // returned so asyncCallback can be called
}

Expand Down Expand Up @@ -64,7 +68,7 @@ async function processRequest(
// Check if Request Already Processed
if (pendingRequests.includes(details.requestId)) {
console.log('%cAlready Processed requestId:', 'color: Orange', details.requestId)
hijackRequest(true)
return hijackRequest(true)
}
pendingRequests.push(details.requestId)

Expand All @@ -88,9 +92,11 @@ async function processRequest(
const session = await getSession()
// console.log('session:', session)

if (url.host in session) {
// Find session creds (exact or wildcard match)
const sessionCreds = session[url.host] ?? findBestWildcardMatch(url.host, session)
if (sessionCreds) {
console.log('%cSending Session Creds for:', 'color: SpringGreen', details.requestId)
const [username, password] = parseCreds(session[url.host])
const [username, password] = parseCreds(sessionCreds)
const authCredentials: chrome.webRequest.AuthCredentials = { username, password }
// console.log('authCredentials:', authCredentials)
return asyncCallback({ authCredentials })
Expand Down
70 changes: 46 additions & 24 deletions src/entrypoints/content/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { i18n } from '#imports'
import { defineContentScript } from 'wxt/utils/define-content-script'
import { Hosts } from '@/utils/hosts.ts'
import { Hosts, findBestWildcardMatch } from '@/utils/hosts.ts'

// TODO: Logging

Expand All @@ -27,33 +27,55 @@ export default defineContentScript({

async function onChanged(changes: Record<string, any>) {
// console.debug('content/index.ts - onChanged:', changes)
const items = changes[url.host[0]] // NOTE: Lazy Typing... in changes
if (!items) return
const oldCreds = items.oldValue?.[url.host]
const newCreds = items.newValue?.[url.host]
if (oldCreds !== newCreds) await processCreds(newCreds)
const exactItems = changes[url.host[0]] // NOTE: Lazy Typing... in changes
const wildcardItems = changes['*']

if (!exactItems && !wildcardItems) return

if (exactItems) {
const oldCreds = exactItems.oldValue?.[url.host]
const newCreds = exactItems.newValue?.[url.host]
if (oldCreds !== newCreds) {
// If exact match was removed, check if a wildcard still covers this host
if (!newCreds) {
const wildcard = findBestWildcardMatch(url.host, await Hosts.all())
return await processCreds(wildcard)
}
return await processCreds(newCreds)
}
}

if (wildcardItems) {
const oldWildcard = findBestWildcardMatch(url.host, wildcardItems.oldValue)
const newWildcard = findBestWildcardMatch(url.host, wildcardItems.newValue)
if (oldWildcard !== newWildcard) await processCreds(newWildcard)
}
}

async function processCreds(creds: any) {
// console.debug('processCreds - tabEnabled:', tabEnabled, '- creds:', creds)
if (creds) {
tabEnabled = true
if (creds === 'ignored') {
console.log('%cIgnored - Site is Ignored!', 'color: Gold')
await chrome.runtime.sendMessage({
badgeText: i18n.t('content.badge.off'),
badgeColor: 'yellow',
})
} else {
console.log('%cEnabled - Site Credentials Found.', 'color: LimeGreen')
await chrome.runtime.sendMessage({
badgeText: i18n.t('content.badge.on'),
badgeColor: 'green',
})
try {
if (creds) {
tabEnabled = true
if (creds === 'ignored') {
console.log('%cIgnored - Site is Ignored!', 'color: Gold')
await chrome.runtime.sendMessage({
badgeText: i18n.t('content.badge.off'),
badgeColor: 'yellow',
})
} else {
console.log('%cEnabled - Site Credentials Found.', 'color: LimeGreen')
await chrome.runtime.sendMessage({
badgeText: i18n.t('content.badge.on'),
badgeColor: 'green',
})
}
} else if (tabEnabled) {
console.log('%cDisabled - Site Credentials Removed.', 'color: Tomato')
tabEnabled = false
await chrome.runtime.sendMessage({ badgeText: '' })
}
} else if (tabEnabled) {
console.log('%cDisabled - Site Credentials Removed.', 'color: Tomato')
tabEnabled = false
await chrome.runtime.sendMessage({ badgeText: '' })
} catch {
// extension is reloaded, updated, or the page outlives the background script
}
}
30 changes: 18 additions & 12 deletions src/entrypoints/popup/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ debug('width:', width.value)

const options = useOptions()

const hostnameRef = ref('') // tab hostname
const tabHost = ref('') // original tab hostname
const hostnameRef = ref('') // matched hostname
const usernameRef = ref('') // saved username
const savedCreds = ref('') // has credentials

Expand All @@ -39,15 +40,21 @@ function deleteClick(host: string) {
}
}

function setMatch(match: { key: string; creds: string } | undefined) {
hostnameRef.value = match?.key ?? ''
savedCreds.value = match?.creds ?? ''
usernameRef.value = match ? parseCreds(match.creds)[0] : ''
}

// DUPLICATION: HostsTable.vue
async function deleteHost(host: string) {
debug('popup/App.vue - deleteHost:', host)
// const creds = hosts.value[host]
// debug('creds:', creds)
try {
await Hosts.delete(host)
savedCreds.value = '' // NOTE: These 2 lines are only differences
usernameRef.value = '' // NOTE: These 2 lines are only differences
const match = await Hosts.find(hostnameRef.value)
setMatch(match)
showToast(`${i18n.t('ui.text.removed')}: ${host}`, 'success')
} catch (e) {
const message = e instanceof Error ? e.message : i18n.t('import.errorUnknown')
Expand All @@ -57,9 +64,10 @@ async function deleteHost(host: string) {

async function onSubmit(host: string, user: string, pass: string, original?: string) {
debug('popup/App.vue - onSubmit:', host, user, pass, original)
await submitHost(host, user, pass, original)
savedCreds.value = `${user}:${pass}`
usernameRef.value = user
const success = await submitHost(host, user, pass, original)
if (!success) return
const match = original !== host ? await Hosts.find(tabHost.value) : { key: host, creds: `${user}:${pass}` }
setMatch(match)
}

onMounted(async () => {
Expand All @@ -68,12 +76,10 @@ onMounted(async () => {
if (!tab.url) return debug('No URL for Tab - No Access.')
const url = new URL(tab.url)
debug('url:', url)
hostnameRef.value = url.host
const creds = await Hosts.get(url.host)
debug('creds:', creds)
if (!creds) return debug('No Saved Creds for Host.')
savedCreds.value = creds
usernameRef.value = parseCreds(creds)[0]
tabHost.value = url.host
const match = await Hosts.find(url.host)
debug('match:', match)
setMatch(match)
})
</script>

Expand Down
Loading
Loading