示例工程 11-main-process-services
11-main-process-services/app/main/services/shell-service.ts
import { ServiceError } from "../../shared/ipc";
export type ShellService = {
open(raw: string): Promise<{ url: string; dryRun: boolean }>;
};
export function createShellService(options: {
allowlist: string[];
openExternal: (url: string) => Promise<void>;
dryRun?: boolean;
}): ShellService {
return {
async open(raw: string) {
let url: URL;
try {
url = new URL(raw);
} catch {
throw new ServiceError("BAD_URL", "url 不是合法地址", "url");
}
if (url.protocol !== "https:") {
throw new ServiceError(
"URL_NOT_ALLOWED",
"只允许打开 https 链接",
"url",
);
}
if (url.username || url.password) {
throw new ServiceError(
"URL_NOT_ALLOWED",
"链接不能包含用户名或密码",
"url",
);
}
if (!options.allowlist.includes(url.hostname)) {
throw new ServiceError(
"URL_NOT_ALLOWED",
`host 不在白名单:${url.hostname}`,
"url",
);
}
const dryRun = options.dryRun ?? false;
if (!dryRun) await options.openExternal(url.toString());
return { url: url.toString(), dryRun };
},
};
}