Skip to content

Commit

Permalink
Merge pull request #812 from ninoseki/refactoring
Browse files Browse the repository at this point in the history
Refactoring
  • Loading branch information
ninoseki authored May 18, 2024
2 parents f3f4fee + caf3bc7 commit 89c019f
Show file tree
Hide file tree
Showing 12 changed files with 142 additions and 134 deletions.
10 changes: 5 additions & 5 deletions src/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ export function createContextMenus(text: string, options: OptionsType): void {
// it tells action, query, type and target to the listener
const id = commandToID(command);
const title = commandToMessage(command);
chrome.contextMenus.create({ contexts, id, title });

if (options.debug) {
console.debug(`Mitaka: context menu:${id} created`);
}
chrome.contextMenus.create({ contexts, id, title }, () => {
if (options.debug) {
console.debug(`Mitaka: context menu:${id} created`);
}
});
}
}

Expand Down
13 changes: 8 additions & 5 deletions src/background/scan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ import { showNotification } from "~/background/notification";
import type { CommandRunner } from "~/command/runner";

export async function scan(runner: CommandRunner): Promise<void> {
const res = await runner.scan();
if (res.isOk()) {
await chrome.tabs.create({ url: res.value });
} else {
showNotification(res.error);
const resultAsync = runner.scan();
const result = await resultAsync;

if (result.isOk()) {
await chrome.tabs.create({ url: result.value });
return;
}

showNotification(result.error);
}
10 changes: 6 additions & 4 deletions src/background/search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,19 @@ export async function searchAll(runner: CommandRunner): Promise<void> {
for (const result of results) {
if (result.isOk()) {
await chrome.tabs.create({ url: result.value });
} else {
showNotification(result.error);
continue;
}

showNotification(result.error);
}
}

export async function search(runner: CommandRunner): Promise<void> {
const result = runner.search();
if (result.isOk()) {
await chrome.tabs.create({ url: result.value });
} else {
showNotification(result.error);
return;
}

showNotification(result.error);
}
40 changes: 13 additions & 27 deletions src/command/runner.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { err, ok, Result } from "neverthrow";
import { err, errAsync, ok, okAsync, Result, ResultAsync } from "neverthrow";

import type { OptionsType } from "~/schemas";
import { Selector } from "~/selector";
Expand Down Expand Up @@ -102,44 +102,35 @@ export class CommandRunner {
}

private scannerMap: ScannerMap = {
ip: async (
scanner: Scanner,
query: string,
): Promise<Result<string, string>> => {
ip: (scanner: Scanner, query: string) => {
return scanner.scanByIP(query);
},
domain: async (
scanner: Scanner,
query: string,
): Promise<Result<string, string>> => {
domain: (scanner: Scanner, query: string) => {
return scanner.scanByDomain(query);
},
url: async (
scanner: Scanner,
query: string,
): Promise<Result<string, string>> => {
url: (scanner: Scanner, query: string) => {
return scanner.scanByURL(query);
},
};

public async scan(): Promise<Result<string, string>> {
const getSlot = () => {
public scan(): ResultAsync<string, string> {
const getSlot = (): ResultAsync<SelectorSlot, string> => {
const selector: Selector = new Selector(this.command.query);
const slots: SelectorSlot[] = selector.getScannerSlots();
const slot = slots.find((s) => s.analyzer.name === this.command.name);

if (!slot) {
return err(`Slot for ${this.command.name} is missing`);
return errAsync(`Slot for ${this.command.name} is missing`);
}

if (!isScanner(slot.analyzer)) {
return err(`${slot.analyzer.name} is not a scanner`);
return errAsync(`${slot.analyzer.name} is not a scanner`);
}

return ok(slot);
return okAsync(slot);
};

const scan = async (slot: SelectorSlot) => {
const scan = (slot: SelectorSlot): ResultAsync<string, string> => {
const scanner = slot.analyzer as Scanner;

switch (scanner.name) {
Expand All @@ -158,17 +149,12 @@ export class CommandRunner {

if (slot.type in this.scannerMap) {
const fn = this.scannerMap[slot.type];
return await fn(scanner, slot.query);
return fn(scanner, slot.query);
}

return err("Something goes wrong");
return errAsync("Something goes wrong");
};

const result = await getSlot().asyncMap(scan);

if (result.isErr()) {
return err(result.error);
}
return result.value;
return getSlot().andThen(scan);
}
}
9 changes: 3 additions & 6 deletions src/options/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import { getFaviconURL } from "../utils";
const isInitialized = ref(false);
const synchedAt = ref<string>();
const searchableType = ref<SearchableType | undefined>(undefined);
const scannableType = ref<ScannableType | undefined>(undefined);
const searchableType = ref<SearchableType>();
const scannableType = ref<ScannableType>();
const options = reactive<OptionsType>({
debug: false,
Expand Down Expand Up @@ -243,10 +243,7 @@ watch(options, async (newOptions) => {
</div>
</div>
<div class="field">
<div
class="control"
v-if="scanner.hasAPIKey && isSelectedScanner(scanner)"
>
<div class="control" v-if="isSelectedScanner(scanner)">
<input
type="text"
class="input"
Expand Down
19 changes: 10 additions & 9 deletions src/scanner/base.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
import { err, Result } from "neverthrow";
import { errAsync, ResultAsync } from "neverthrow";

import type { ScannableType, Scanner } from "~/types";

export class Base implements Scanner {
public baseURL: string;
public name: string;
public supportedTypes: ScannableType[] = [];
public apiKey: string | undefined = undefined;
public apiKey?: string = undefined;
public apiKeyRequired: boolean = true;

public constructor() {
this.baseURL = "http://example.com";
this.name = "Base";
}

public setAPIKey(apiKey: string | undefined): void {
public setAPIKey(apiKey?: string): void {
this.apiKey = apiKey;
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async scanByURL(url: string): Promise<Result<string, string>> {
return err("Not implemented");
public scanByURL(url: string): ResultAsync<string, string> {
return errAsync("Not implemented");
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async scanByIP(url: string): Promise<Result<string, string>> {
return err("Not implemented");
public scanByIP(url: string): ResultAsync<string, string> {
return errAsync("Not implemented");
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
public async scanByDomain(url: string): Promise<Result<string, string>> {
return err("Not implemented");
public scanByDomain(url: string): ResultAsync<string, string> {
return errAsync("Not implemented");
}
}
9 changes: 5 additions & 4 deletions src/scanner/browserling.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ok, Result } from "neverthrow";
import { okAsync } from "neverthrow";

import type { ScannableType } from "~/types";
import { buildURL } from "~/utils";
Expand All @@ -9,16 +9,17 @@ export class Browserling extends Base {
public baseURL: string;
public name: string;
public supportedTypes: ScannableType[] = ["url"];
public apiKey: string | undefined = undefined;
public apiKey?: string = undefined;
public apiKeyRequired: boolean = false;

public constructor() {
super();
this.baseURL = "https://www.browserling.com";
this.name = "Browserling";
}

public async scanByURL(url: string): Promise<Result<string, string>> {
return ok(
scanByURL(url: string) {
return okAsync(
buildURL(this.baseURL, `/browse/win/7/ie/11/${encodeURIComponent(url)}`),
);
}
Expand Down
45 changes: 26 additions & 19 deletions src/scanner/hybridanalysis.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { err, ok, Result } from "neverthrow";
import { errAsync, ResultAsync } from "neverthrow";
import { z } from "zod";

import type { ScannableType } from "~/types";
Expand All @@ -17,21 +17,21 @@ export class HybridAnalysis extends Base {
public baseURL: string;
public name: string;
public supportedTypes: ScannableType[] = ["url"];
public apiKey: string | undefined = undefined;
public apiKey?: string = undefined;

public constructor() {
super();
this.baseURL = "https://www.hybrid-analysis.com";
this.name = "HybridAnalysis";
}

public setAPIKey(apiKey: string | undefined): void {
setAPIKey(apiKey: string): void {
this.apiKey = apiKey;
}

public async scanByURL(url: string): Promise<Result<string, string>> {
if (this.apiKey === undefined) {
return err("Please set your HybridAnalysis API key via the option.");
scanByURL(url: string) {
if (!this.apiKey) {
return errAsync("Please set your HybridAnalysis API key via the option.");
}

const formData = new FormData();
Expand All @@ -43,21 +43,28 @@ export class HybridAnalysis extends Base {
"user-agent": "Falcon Sandbox",
};

const res = await fetch(`${this.baseURL}/api/v2/quick-scan/url`, {
method: "POST",
headers,
body: formData,
});
const scan = async () => {
const res = await fetch(`${this.baseURL}/api/v2/quick-scan/url`, {
method: "POST",
headers,
body: formData,
});

const data = await res.json();
const data = await res.json();

if (!res.ok) {
const parsed = ErrorResponse.parse(data);
return err(parsed.message);
}
if (!res.ok) {
const parsed = ErrorResponse.parse(data);
throw Error(parsed.message);
}

const parsed = Response.parse(data);
const sha256: string = parsed.sha256;
return `https://www.hybrid-analysis.com/sample/${sha256}/`;
};

const parsed = Response.parse(data);
const sha256: string = parsed.sha256;
return ok(`https://www.hybrid-analysis.com/sample/${sha256}/`);
return ResultAsync.fromThrowable(
scan,
(err: unknown) => (err as Error).message,
)();
}
}
Loading

0 comments on commit 89c019f

Please sign in to comment.