Skip to content

Commit

Permalink
✨ Add alert element in prompt popup
Browse files Browse the repository at this point in the history
  • Loading branch information
ssakone committed Dec 28, 2023
1 parent 893a45f commit c8fd935
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 119 deletions.
189 changes: 97 additions & 92 deletions src/lib/controllers/browser.controller.ts
Original file line number Diff line number Diff line change
@@ -1,99 +1,104 @@
import { getDuration } from "$lib/utility";
import { web } from "$lib/utility";
import { getDuration } from '$lib/utility';
import { web } from '$lib/utility';

import type { Browser } from "$lib/types";
import type { Browser } from '$lib/types';

const createBrowserController = (): Browser => {
const get = async (key: string): Promise<{ [key: string]: unknown }> => {
try {
const result = await web?.storage?.local?.get(key);
return result;
} catch (err) {
return Promise.reject(err);
}
};
const set = async (items: { [key: string]: unknown }): Promise<void> => {
try {
const result = await web?.storage?.local?.set(items);
return result;
} catch (err) {
return Promise.reject(err);
}
};
const get = async (key: string): Promise<{ [key: string]: unknown }> => {
try {
const result = await web?.storage?.local?.get(key);
return result;
} catch (err) {
return Promise.reject(err);
}
};
const set = async (items: { [key: string]: unknown }): Promise<void> => {
try {
const result = await web?.storage?.local?.set(items);
return result;
} catch (err) {
return Promise.reject(err);
}
};

const getCurrentTab = async (): Promise<chrome.tabs.Tab> => {
return new Promise((resolve) => {
web.tabs.query({ active: true, currentWindow: true }, (tabs: chrome.tabs.Tab[]) =>
resolve(tabs[0])
);
});
};
const injectJsInTab = async (tab: chrome.tabs.Tab, jsFileName: string): Promise<void> => {
try {
const getCurrentTab = async (): Promise<chrome.tabs.Tab> => {
return new Promise((resolve) => {
web.tabs.query({ active: true, currentWindow: true }, (tabs: chrome.tabs.Tab[]) =>
resolve(tabs[0])
);
});
};
const injectJsInTab = async (tab: chrome.tabs.Tab, jsFileName: string): Promise<void> => {
try {
await web.scripting.executeScript({
target: { tabId: tab.id as number },
files: [jsFileName]
});
return;
} catch (e) {
console.error(tab.id, tab.url);
console.error('Error injecting Nostr Provider', e);
return Promise.reject(e);
}
};
const injectJsinAllTabs = async (jsFileName: string): Promise<void> => {
return new Promise((resolve) => {
web.tabs.query({}, function (tabs: chrome.tabs.Tab[]) {
tabs.forEach(async (tab) => {
try {
if (tab.url?.startsWith('chrome://') || tab.url?.startsWith('chrome-extension://'))
return;
await injectJsInTab(tab, jsFileName);
} catch (e) {
console.log('Error injecting Nostr Provider', e);
}
});
resolve();
});
});
};
const createWindow = async (url: string): Promise<chrome.windows.Window> => {
return web.windows.create({
url: web.runtime.getURL(url),
width: 400,
height: 580,
type: 'popup'
});
};

await web.scripting.executeScript({
target: { tabId: tab.id as number },
files: [jsFileName]
});
return;
} catch (e) {
console.error(tab.id, tab.url)
console.error('Error injecting Nostr Provider', e);
return Promise.reject(e);
}
};
const injectJsinAllTabs = async (jsFileName: string): Promise<void> => {
return new Promise((resolve) => {
web.tabs.query({}, function (tabs: chrome.tabs.Tab[]) {
tabs.forEach(async (tab) => {
try {
if (tab.url?.startsWith('chrome://') || tab.url?.startsWith('chrome-extension://'))
return;
await injectJsInTab(tab, jsFileName);
} catch (e) {
console.log('Error injecting Nostr Provider', e);
}
});
resolve();
});
});
};
const createWindow = async (url: string): Promise<chrome.windows.Window> => {
return web.windows.create({
url: web.runtime.getURL(url),
width: 400,
height: 500,
type: 'popup'
});
};
const sendAuthorizationResponse = (
yes: boolean,
choice: number,
url: string | undefined,
requestId: string | undefined
) => {
return web.runtime.sendMessage({
prompt: true,
response: {
status: yes ? 'success' : 'error',
error: !yes,
permission: {
always: choice === 1,
duration: getDuration(choice),
accept: yes,
reject: !yes
}
},
ext: 'keys.band',
url,
requestId
});
};

const sendAuthorizationResponse = (
yes: boolean,
choice: number,
url: string | undefined,
requestId: string | undefined
) => {
return web.runtime.sendMessage({
prompt: true,
response: {
status: yes ? 'success' : 'error',
error: !yes,
permission: {
always: choice === 1,
duration: getDuration(choice),
accept: yes,
reject: !yes
}
},
ext: 'keys.band',
url,
requestId
});
};
return {
get,
set,
getCurrentTab,
injectJsInTab,
injectJsinAllTabs,
createWindow,
sendAuthorizationResponse
};
};


return { get, set, getCurrentTab, injectJsInTab, injectJsinAllTabs, createWindow, sendAuthorizationResponse };
}


export const browserController: Browser = createBrowserController();
export const browserController: Browser = createBrowserController();
46 changes: 19 additions & 27 deletions src/lib/services/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,15 @@ const switchIcon = async (activeInfo: { tabId: number }) => {
path: 'assets/logo-off.png'
});
}
}

};

web.runtime.onInstalled.addListener(() => BrowserUtil.injectJsinAllTabs('content.js'));
web.runtime.onStartup.addListener(() => BrowserUtil.injectJsinAllTabs('content.js'));
web.tabs.onActivated.addListener(async (activeInfo) => switchIcon(activeInfo));
BrowserUtil.getCurrentTab().then((tab) => switchIcon({ tabId: tab.id as number }));

const responders: Responders = {};
let requestQueue: any[] = [];
const requestQueue: any[] = [];

const hasWebSiteAlreadyLogged = async (domain: string): Promise<Profile> => {
const allUsers = get(await profileController.loadProfiles()) as Profile[];
Expand All @@ -61,8 +60,8 @@ const hasWebSiteAlreadyLogged = async (domain: string): Promise<Profile> => {
}
}

return currentProfile || await background.getUserProfile();
}
return currentProfile || (await background.getUserProfile());
};

const makeResponse = async (type: string, data: any) => {
await profileController.loadProfiles();
Expand Down Expand Up @@ -210,7 +209,11 @@ const buildResponseMessage = (message: Message, response: any): any => {
};

/*eslint no-async-promise-executor: 0*/
async function manageRequest(message: Message, resolver: any = null, next: boolean = false): Promise<any> {
async function manageRequest(
message: Message,
resolver: any = null,
next: boolean = false
): Promise<any> {
return new Promise(async (res) => {
const resolve: Promise<any> | any = resolver || res;

Expand All @@ -219,24 +222,10 @@ async function manageRequest(message: Message, resolver: any = null, next: boole

if (next === false) {
requestQueue.push({ message, resolver: resolve });
return
return;
}

const hasLogged = await hasWebSiteAlreadyLogged(domain);
console.log(hasLogged, user, domain, message);
if (hasLogged.id !== user.id) {
requestQueue = []
return resolve(
buildResponseMessage(message, {
error: {
message: 'User rejected the request',
stack: 'User rejected the request',
errorCode: 'invalid_public_key',
user: hasLogged.name || ''
}
})
);
}
const previousProfile = await hasWebSiteAlreadyLogged(domain);

if (user.data?.privateKey === undefined)
return Promise.resolve(
Expand All @@ -249,6 +238,8 @@ async function manageRequest(message: Message, resolver: any = null, next: boole
);

const access: AllowKind = await isAllow(domain);
if (message.type === 'getPublicKey')
if (previousProfile.id !== user.id) access === AllowKind.Nothing;

switch (access) {
case AllowKind.AlWaysAllow:
Expand Down Expand Up @@ -303,11 +294,11 @@ async function manageRequest(message: Message, resolver: any = null, next: boole
url: message.url,
requestId: message.id,
type: message.type,
data: message.params.event || message.params || '{}' || ''
data: message.params.event || message.params || '{}' || '',
previousProfile
});

await BrowserUtil.createWindow('popup.html?query=' + btoa(dataId));

});
}

Expand All @@ -317,7 +308,7 @@ const proceedNextRequest = async () => {
const { message, resolver } = requestQueue.shift();
manageRequest(message, resolver, true);
}
}
};

setInterval(async () => proceedNextRequest(), 100);

Expand All @@ -333,9 +324,10 @@ web.runtime.onMessage.addListener((message: Message, sender: MessageSender, send
})
.catch((err) => {
console.error(err);
}).finally(() => {
proceedNextRequest();
})
.finally(() => {
proceedNextRequest();
});
clearInterval(i);
}, Math.random() * 100);
}
Expand Down
1 change: 1 addition & 0 deletions src/lib/types/background.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ interface PopupParams {
requestId?: string | undefined;
origin?: string;
permissions?: string[];
previousProfile?: Profile;
}

interface SessionManager {
Expand Down
11 changes: 11 additions & 0 deletions src/routes/popup/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@

<div class="w-full h-full flex flex-col p-4 mx-auto items-center dark:bg-[#222222] bg-white">
{#if parameter?.url}
{#if 'previousProfile' in parameter && parameter.previousProfile.id !== $userProfile.id}
<span
class="alert alert-warning bg-yellow-300 text-black mb-2 flex flex-row items-center text-sm p-2 gap-2"
>
<Icon icon="pixelarticons:alert" width={56} />
<span>
You are using another account for this request <br />
Previous profile: {parameter.previousProfile.name}
</span>
</span>
{/if}
<div class="w-full bg-surface-400 rounded-lg dark:bg-black bg-opacity-50 h-[72px]">
<div
class="text-gray-800 dark:text-gray-400 text-opacity-70 font-semibold leading-4 tracking-[3px] flex flex-row items-center gap-2 p-2"
Expand Down

0 comments on commit c8fd935

Please sign in to comment.