Skip to content

Commit

Permalink
Merge pull request #131 from HunnySajid/feat/agent-url
Browse files Browse the repository at this point in the history
feat: validate agent url with health check
  • Loading branch information
rodolfomiranda committed Mar 8, 2024
2 parents d12fd39 + 751b0e9 commit 5ff5942
Show file tree
Hide file tree
Showing 7 changed files with 67 additions and 30 deletions.
4 changes: 3 additions & 1 deletion src/_locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,23 @@
"account.settings": "Settings",
"account.support": "support",
"action.back": "Back",
"action.click": "click",
"action.clickToRemove": "click to remove",
"action.connect": "Connect",
"action.create": "Create",
"action.createNew": "Create New",
"action.delete": "Delete",
"action.disconnect": "Disconnect",
"action.load": "Load",
"action.open": "open",
"action.open": "Open",
"action.save": "Save",
"action.select": "Select",
"action.toProceed": "to proceed",
"action.toSelectOther": "to select other",
"config.agentUrl.label": "Agent Url:",
"config.agentUrl.placeholder": "Enter agent url",
"config.error.enterUrl": "Enter a valid url",
"config.error.invalidAgentUrl": "Invalid agent url",
"config.error.invalidVendorUrl": "Invalid url, Vendor configuration not found",
"config.error.setUrl": "Vendor url is not set",
"config.error.vendorData.agentUrls": "response missing agent urls, contact support",
Expand Down
2 changes: 2 additions & 0 deletions src/_locales/es-419.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"account.settings": "Ajustes",
"account.support": "soporte",
"action.back": "Atrás",
"action.click": "hacer clic",
"action.clickToRemove": "haga clic para eliminar",
"action.connect": "Conectar",
"action.create": "Crear",
Expand All @@ -20,6 +21,7 @@
"config.agentUrl.label": "URL del agente:",
"config.agentUrl.placeholder": "Ingrese la URL del agente",
"config.error.enterUrl": "Introduce una URL válida",
"config.error.invalidAgentUrl": "URL de agente inválido",
"config.error.invalidVendorUrl": "URL no válida, configuración del proveedor no encontrada",
"config.error.setUrl": "La URL del proveedor no está configurada",
"config.error.vendorData.agentUrls": "URL de agentes faltantes de respuesta, comuníquese con el soporte",
Expand Down
2 changes: 2 additions & 0 deletions src/_locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"account.settings": "Ajustes",
"account.support": "soporte",
"action.back": "Atrás",
"action.click": "hacer clic",
"action.clickToRemove": "haga clic para eliminar",
"action.connect": "Conectar",
"action.create": "Crear",
Expand All @@ -20,6 +21,7 @@
"config.agentUrl.label": "URL del agente:",
"config.agentUrl.placeholder": "Ingrese la URL del agente",
"config.error.enterUrl": "Introduce una URL válida",
"config.error.invalidAgentUrl": "URL de agente inválido",
"config.error.invalidVendorUrl": "URL no válida, configuración del proveedor no encontrada",
"config.error.setUrl": "La URL del proveedor no está configurada",
"config.error.vendorData.agentUrls": "URL de agentes faltantes de respuesta, comuníquese con el soporte",
Expand Down
62 changes: 41 additions & 21 deletions src/pages/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { IMessage, IIdentifier, ICredential } from "@config/types";
import { senderIsPopup } from "@pages/background/utils";
import {
removeSlash,
getCurrentDomain,
getCurrentUrl,
setActionIcon,
} from "@pages/background/utils";
import {
Expand Down Expand Up @@ -57,7 +57,7 @@ chrome.runtime.onMessage.addListener(function (
message.subtype === "set-action-icon"
) {
chrome.action.setBadgeBackgroundColor({ color: "#008000" }, () => {
chrome.action.setBadgeText({ text: "^" });
chrome.action.setBadgeText({ text: "1" });
sendResponse({ data: { success: true } });
});
}
Expand Down Expand Up @@ -86,7 +86,7 @@ chrome.runtime.onMessage.addListener(function (
if (!vendorUrl) {
return;
}

const _vendorUrl = await configService.getUrl();
if (!_vendorUrl) {
try {
Expand All @@ -102,7 +102,7 @@ chrome.runtime.onMessage.addListener(function (
await configService.setUrl(vendorUrl);
} catch (error) {}
}

sendResponse({ data: { _vendorUrl } });
}

Expand Down Expand Up @@ -237,26 +237,46 @@ chrome.runtime.onMessage.addListener(function (
const signins = (await browserStorageService.getValue(
"signins"
)) as any[];
const currentDomain = await getCurrentDomain();

const currentUrl = await getCurrentUrl();
const { identifier, credential } = message.data;
const signinObj = {
identifier,
credential,
createdAt: new Date().getTime(),
updatedAt: new Date().getTime(),
domain: currentDomain!.origin,
};
if (signins && signins?.length) {
await browserStorageService.setValue("signins", [
...signins,
signinObj,
]);
let signinExists = false;
if (identifier && identifier.prefix) {
signinExists = signins?.find(
(signin) =>
signin.domain === currentUrl?.origin &&
signin?.identifier?.prefix === identifier.prefix
);
}

if (credential && credential.sad.d) {
signinExists = signins?.find(
(signin) =>
signin.domain === currentUrl?.origin &&
signin?.credential?.sad?.d === credential.sad.d
);
}

if (signinExists) {
sendResponse({ data: { signins: signins } });
} else {
await browserStorageService.setValue("signins", [signinObj]);
const signinObj = {
identifier,
credential,
createdAt: new Date().getTime(),
updatedAt: new Date().getTime(),
domain: currentUrl!.origin,
};
if (signins && signins?.length) {
await browserStorageService.setValue("signins", [
...signins,
signinObj,
]);
} else {
await browserStorageService.setValue("signins", [signinObj]);
}
const storageSignins = await browserStorageService.getValue("signins");
sendResponse({ data: { signins: storageSignins } });
}
const storageSignins = await browserStorageService.getValue("signins");
sendResponse({ data: { signins: storageSignins } });
}
if (
message.type === "create-resource" &&
Expand Down
5 changes: 2 additions & 3 deletions src/pages/background/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ export const senderIsPopup = (sender: chrome.runtime.MessageSender) => {

export const isValidUrl = (str: string) => {
try {
new URL(str);
return true;
return new URL(str);
} catch (err) {
return false;
}
Expand All @@ -24,7 +23,7 @@ export const getCurrentTab = (): Promise<chrome.tabs.Tab> => {
});
};

export const getCurrentDomain = async () => {
export const getCurrentUrl = async () => {
const currentTab = await getCurrentTab();
console.log("Current tab: ", currentTab);
return currentTab ? new URL(currentTab.url!) : null;
Expand Down
2 changes: 1 addition & 1 deletion src/pages/dialog/Dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export function Dialog({
onClick={handleClick}
className="font-bold text-sm cursor-pointer"
>
{formatMessage({ id: "action.open" })}{" "}
{formatMessage({ id: "action.click" })}{" "}
<span className="inline-block">
<img src={logo} className="h-4" alt="logo" />
</span>{" "}
Expand Down
20 changes: 16 additions & 4 deletions src/screens/config/config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ export function Config(props: any): JSX.Element {
const { formatMessage } = useIntl();
const { changeLocale, currentLocale } = useLocale();
const validUrlMsg = formatMessage({ id: "config.error.enterUrl" });
const invalidAgentUrlMsg = formatMessage({
id: "config.error.invalidAgentUrl",
});
const invalidVendorUrlError = formatMessage({
id: "config.error.invalidVendorUrl",
});
Expand All @@ -46,15 +49,24 @@ export function Config(props: any): JSX.Element {
}
};

const checkErrorAgentUrl = (_url: string) => {
if (!_url || !isValidUrl(_url)) {
const checkErrorAgentUrl = async (_url: string) => {
const urlObject = isValidUrl(_url);
if (!_url || !urlObject) {
setAgentUrlError(validUrlMsg);
return true;
}
if (urlObject && urlObject?.origin) {
try {
await (await fetch(`${urlObject?.origin}/health`)).json();
} catch (error) {
setAgentUrlError(invalidAgentUrlMsg);
return true;
}
}
};

const handleSetAgentUrl = async (_url: string) => {
const hasError = checkErrorAgentUrl(_url);
const hasError = await checkErrorAgentUrl(_url);
if (hasError) return;

await configService.setAgentUrl(_url);
Expand Down Expand Up @@ -95,7 +107,7 @@ export function Config(props: any): JSX.Element {
};

const handleBack = async () => {
const hasError = checkErrorAgentUrl(agentUrl);
const hasError = await checkErrorAgentUrl(agentUrl);
if (hasError) return;
props.handleBack();
};
Expand Down

0 comments on commit 5ff5942

Please sign in to comment.