diff options
author | Sebastian <sebasjm@gmail.com> | 2024-02-04 12:04:27 -0300 |
---|---|---|
committer | Sebastian <sebasjm@gmail.com> | 2024-02-05 09:18:22 -0300 |
commit | b71d6f2b11342bd22197289ad3872d8a341686b5 (patch) | |
tree | d263482af0121d87000476fd0306530a77580817 /packages/taler-wallet-webextension/src/platform/chrome.ts | |
parent | 83ff7de59b8a00b313ecb00f4c6150a37c38902f (diff) | |
download | wallet-core-b71d6f2b11342bd22197289ad3872d8a341686b5.tar.xz |
wip DD39: removed webRequest permission and changes made into demobank
Diffstat (limited to 'packages/taler-wallet-webextension/src/platform/chrome.ts')
-rw-r--r-- | packages/taler-wallet-webextension/src/platform/chrome.ts | 300 |
1 files changed, 27 insertions, 273 deletions
diff --git a/packages/taler-wallet-webextension/src/platform/chrome.ts b/packages/taler-wallet-webextension/src/platform/chrome.ts index 18d282342..d791a560f 100644 --- a/packages/taler-wallet-webextension/src/platform/chrome.ts +++ b/packages/taler-wallet-webextension/src/platform/chrome.ts @@ -28,6 +28,7 @@ import { BackgroundOperations } from "../wxApi.js"; import { BackgroundPlatformAPI, CrossBrowserPermissionsApi, + ExtensionNotificationType, ForegroundPlatformAPI, MessageFromBackend, MessageFromFrontend, @@ -60,27 +61,31 @@ const api: BackgroundPlatformAPI & ForegroundPlatformAPI = { useServiceWorkerAsBackgroundProcess, keepAlive, listenNetworkConnectionState, - registerTalerHeaderListener, - containsTalerHeaderListener, }; export default api; const logger = new Logger("chrome.ts"); -async function getSettingsFromStorage(): Promise<Settings> { - const data = await chrome.storage.local.get("wallet-settings"); - if (!data) return defaultSettings; - const settings = data["wallet-settings"]; - if (!settings) return defaultSettings; + +const WALLET_STORAGE_KEY = "wallet-settings"; + +function jsonParseOrDefault(unparsed: any, def: any) { + if (!unparsed) return def try { - const parsed = JSON.parse(settings); - return parsed; + return JSON.parse(unparsed); } catch (e) { - return defaultSettings; + return def; } } +async function getSettingsFromStorage(): Promise<Settings> { + const data = await chrome.storage.local.get(WALLET_STORAGE_KEY); + if (!data) return defaultSettings; + const settings = data[WALLET_STORAGE_KEY]; + return jsonParseOrDefault(settings, defaultSettings) +} + function keepAlive(callback: any): void { if (extensionIsManifestV3()) { chrome.alarms.create("wallet-worker", { periodInMinutes: 1 }); @@ -140,21 +145,8 @@ export function removeClipboardPermissions(): Promise<boolean> { }); } -function addPermissionsListener( - callback: (p: Permissions, lastError?: string) => void, -): void { - chrome.permissions.onAdded.addListener((perm: Permissions) => { - const lastError = chrome.runtime.lastError?.message; - callback(perm, lastError); - }); -} - function getPermissionsApi(): CrossBrowserPermissionsApi { return { - containsHostPermissions, - requestHostPermissions, - removeHostPermissions, - addPermissionsListener, requestClipboardPermissions, removeClipboardPermissions, containsClipboardPermissions, @@ -363,6 +355,18 @@ function registerAllIncomingConnections(): void { logger.error("error trying to save incoming connection", e); } }); + chrome.storage.onChanged.addListener((event) => { + if (event[WALLET_STORAGE_KEY]) { + sendMessageToAllChannels({ + type: "web-extension", + notification: { + type: ExtensionNotificationType.SettingsChange, + currentValue: jsonParseOrDefault(event[WALLET_STORAGE_KEY], defaultSettings) + } + }) + } + }) + } function listenToAllChannels( @@ -723,253 +727,3 @@ function listenNetworkConnectionState( }; } -type HeaderListenerFunc = ( - details: chrome.webRequest.WebResponseHeadersDetails, -) => void; -let currentHeaderListener: HeaderListenerFunc | undefined = undefined; - -// type TabListenerFunc = (tabId: number, info: chrome.tabs.TabChangeInfo) => void; -// let currentTabListener: TabListenerFunc | undefined = undefined; - - -function containsTalerHeaderListener(): boolean { - return ( - currentHeaderListener !== undefined - // || currentTabListener !== undefined - ); -} - -function headerListener( - details: chrome.webRequest.WebResponseHeadersDetails, -): chrome.webRequest.BlockingResponse | undefined { - logger.trace("header listener run", details.statusCode, chrome.runtime.lastError) - if (chrome.runtime.lastError) { - logger.error(JSON.stringify(chrome.runtime.lastError)); - return; - } - - if ( - details.statusCode === 402 || - details.statusCode === 202 || - details.statusCode === 200 - ) { - const values = (details.responseHeaders || []) - .filter((h) => h.name.toLowerCase() === "taler") - .map((h) => h.value) - .filter((value): value is string => !!value); - - const talerUri = values.length > 0 ? values[0] : undefined - if (talerUri) { - logger.info( - `Found a Taler URI in a response header for the request ${details.url} from tab ${details.tabId}: ${talerUri}`, - ); - parseTalerUriAndRedirect(details.tabId, talerUri); - return; - } - } - return details; -} -function parseTalerUriAndRedirect(tabId: number, maybeTalerUri: string): void { - const talerUri = maybeTalerUri.startsWith("ext+") - ? maybeTalerUri.substring(4) - : maybeTalerUri; - const uri = parseTalerUri(talerUri); - if (!uri) { - logger.warn( - `Response with HTTP 402 the Taler header but could not classify ${talerUri}`, - ); - return; - } - redirectTabToWalletPage( - tabId, - `/taler-uri/${encodeURIComponent(talerUri)}`, - ); -} - -/** - * Not needed anymore since SPA use taler support - */ - -// async function tabListener( -// tabId: number, -// info: chrome.tabs.TabChangeInfo, -// ): Promise<void> { -// if (tabId < 0) return; -// const tabLocationHasBeenUpdated = info.status === "complete"; -// const tabTitleHasBeenUpdated = info.title !== undefined; -// if (tabLocationHasBeenUpdated || tabTitleHasBeenUpdated) { -// const uri = await findTalerUriInTab(tabId); -// if (!uri) return; -// logger.info(`Found a Taler URI in the tab ${tabId}`); -// parseTalerUriAndRedirect(tabId, uri); -// } -// } - -/** - * unused, declarative redirect is not good enough - * - */ -// async function registerDeclarativeRedirect() { -// await chrome.declarativeNetRequest.updateDynamicRules({ -// removeRuleIds: [1], -// addRules: [ -// { -// id: 1, -// priority: 1, -// condition: { -// urlFilter: "https://developer.chrome.com/docs/extensions/mv2/", -// regexFilter: ".*taler_uri=([^&]*).*", -// // isUrlFilterCaseSensitive: false, -// // requestMethods: [chrome.declarativeNetRequest.RequestMethod.GET] -// // resourceTypes: [chrome.declarativeNetRequest.ResourceType.MAIN_FRAME], -// }, -// action: { -// type: chrome.declarativeNetRequest.RuleActionType.REDIRECT, -// redirect: { -// regexSubstitution: `chrome-extension://${chrome.runtime.id}/static/wallet.html?action=\\1`, -// }, -// }, -// }, -// ], -// }); -// } - -function registerTalerHeaderListener(): void { - logger.info("setting up header listener"); - - const prevHeaderListener = currentHeaderListener; - // const prevTabListener = currentTabListener; - - if ( - prevHeaderListener && - chrome?.webRequest?.onHeadersReceived?.hasListener(prevHeaderListener) - ) { - return; - // console.log("removming on header listener") - // chrome.webRequest.onHeadersReceived.removeListener(prevHeaderListener); - // chrome.webRequest.onCompleted.removeListener(prevHeaderListener); - // chrome.webRequest.onResponseStarted.removeListener(prevHeaderListener); - // chrome.webRequest.onErrorOccurred.removeListener(prevHeaderListener); - } - - // if ( - // prevTabListener && - // chrome?.tabs?.onUpdated?.hasListener(prevTabListener) - // ) { - // console.log("removming on tab listener") - // chrome.tabs.onUpdated.removeListener(prevTabListener); - // } - - console.log("headers on, disabled:", chrome?.webRequest?.onHeadersReceived === undefined) - if (chrome?.webRequest) { - if (extensionIsManifestV3()) { - chrome.webRequest.onHeadersReceived.addListener(headerListener, - { urls: ["<all_urls>"] }, - ["responseHeaders"] - ); - } else { - chrome.webRequest.onHeadersReceived.addListener(headerListener, - { urls: ["<all_urls>"] }, - ["responseHeaders"] - ); - } - // chrome.webRequest.onCompleted.addListener(headerListener, - // { urls: ["<all_urls>"] }, - // ["responseHeaders", "extraHeaders"] - // ); - // chrome.webRequest.onResponseStarted.addListener(headerListener, - // { urls: ["<all_urls>"] }, - // ["responseHeaders", "extraHeaders"] - // ); - // chrome.webRequest.onErrorOccurred.addListener(headerListener, - // { urls: ["<all_urls>"] }, - // ["extraHeaders"] - // ); - currentHeaderListener = headerListener; - } - - // const tabsEvent: chrome.tabs.TabUpdatedEvent | undefined = - // chrome?.tabs?.onUpdated; - // if (tabsEvent) { - // tabsEvent.addListener(tabListener); - // currentTabListener = tabListener; - // } - - //notify the browser about this change, this operation is expensive - chrome?.webRequest?.handlerBehaviorChanged(() => { - if (chrome.runtime.lastError) { - logger.error(JSON.stringify(chrome.runtime.lastError)); - } - }); -} - -const hostPermissions = { - permissions: ["webRequest"], - origins: ["http://*/*", "https://*/*"], -}; - -export function containsHostPermissions(): Promise<boolean> { - return new Promise((res, rej) => { - chrome.permissions.contains(hostPermissions, (resp) => { - const le = chrome.runtime.lastError?.message; - if (le) { - rej(le); - } - res(resp); - }); - }); -} - -export async function requestHostPermissions(): Promise<boolean> { - return new Promise((res, rej) => { - chrome.permissions.request(hostPermissions, (resp) => { - const le = chrome.runtime.lastError?.message; - if (le) { - rej(le); - } - res(resp); - }); - }); -} - -export async function removeHostPermissions(): Promise<boolean> { - //if there is a handler already, remove it - if ( - currentHeaderListener && - chrome?.webRequest?.onHeadersReceived?.hasListener(currentHeaderListener) - ) { - chrome.webRequest.onHeadersReceived.removeListener(currentHeaderListener); - } - // if ( - // currentTabListener && - // chrome?.tabs?.onUpdated?.hasListener(currentTabListener) - // ) { - // chrome.tabs.onUpdated.removeListener(currentTabListener); - // } - - currentHeaderListener = undefined; - // currentTabListener = undefined; - - //notify the browser about this change, this operation is expensive - if ("webRequest" in chrome) { - chrome.webRequest.handlerBehaviorChanged(() => { - if (chrome.runtime.lastError) { - logger.error(JSON.stringify(chrome.runtime.lastError)); - } - }); - } - - if (extensionIsManifestV3()) { - // Trying to remove host permissions with manifest >= v3 throws an error - return true; - } - return new Promise((res, rej) => { - chrome.permissions.remove(hostPermissions, (resp) => { - const le = chrome.runtime.lastError?.message; - if (le) { - rej(le); - } - res(resp); - }); - }); -}
\ No newline at end of file |