diff --git a/gui/src/api/index.ts b/gui/src/api/index.ts index 0bde6529..6a739eec 100644 --- a/gui/src/api/index.ts +++ b/gui/src/api/index.ts @@ -42,7 +42,12 @@ export const deleteTouch = (touches: Which[]) => // The editor sends `which: null` for a new node, as the old page did; the // key stays in the body. Saving one node has no time limit, a batch has. export const postImport = ( - body: { url: string; kind?: string; which?: Which | null }, + body: { + url: string; + kind?: string; + which?: Which | null; + bypassProxy?: boolean; + }, timeout: number = timeouts.import, ) => call({ url: "import", method: "post", data: body, timeout }); @@ -52,8 +57,12 @@ export const getSharingAddress = (touch: Which) => method: "get", params: { touch }, }); -export const putSubscription = (which: Which) => - call({ url: "subscription", method: "put", data: which }); +export const putSubscription = (which: Which, bypassProxy = false) => + call({ + url: "subscription", + method: "put", + data: bypassProxy ? { ...which, bypassProxy: true } : which, + }); export const patchSubscription = (body: Record) => call({ url: "subscription", method: "patch", data: body }); export const getPingLatency = (whiches: Which[]) => diff --git a/gui/src/api/types.ts b/gui/src/api/types.ts index 231d4894..68eb94a4 100644 --- a/gui/src/api/types.ts +++ b/gui/src/api/types.ts @@ -40,6 +40,10 @@ export interface TouchSubscription { info: string; servers: TouchServer[]; autoSelect: boolean; + updateMode?: "disabled" | "on_start" | "at_interval" | "interval_failsafe"; + updateIntervalMinutes?: number; + failureIntervalMinutes?: number; + allowDirectRecovery?: boolean; } /** touch.Touch */ diff --git a/gui/src/composables/index.ts b/gui/src/composables/index.ts index f4d6a919..3288a7be 100644 --- a/gui/src/composables/index.ts +++ b/gui/src/composables/index.ts @@ -18,3 +18,4 @@ export { useTraffic } from "./useTraffic"; export { useOutboundGroups } from "./useOutboundGroups"; export { useUnsavedGuard } from "./useUnsavedGuard"; export { useHotkeys, focusInput } from "./useHotkeys"; +export { useSubscriptionBypass } from "./useSubscriptionBypass"; diff --git a/gui/src/composables/useSubscriptionBypass.spec.ts b/gui/src/composables/useSubscriptionBypass.spec.ts new file mode 100644 index 00000000..1d3a8859 --- /dev/null +++ b/gui/src/composables/useSubscriptionBypass.spec.ts @@ -0,0 +1,125 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { defineComponent, h } from "vue"; +import { flushPromises, type VueWrapper } from "@vue/test-utils"; +import type * as Api from "@/api"; +import { getSetting } from "@/api"; +import ConfirmDialog from "@/components/hosts/ConfirmDialog.vue"; +import { mountWithApp } from "@/test/mount"; +import { useAppStore, type Running } from "@/stores/app"; +import { closeAllDialogs, closeDialog, dialogState } from "./useDialog"; +import { useSubscriptionBypass } from "./useSubscriptionBypass"; + +vi.mock("@/api", async (original) => ({ + ...(await original()), + getSetting: vi.fn(), +})); + +let wrapper: VueWrapper; +let chooseBypass: (all?: boolean) => Promise; + +const Probe = defineComponent({ + setup() { + chooseBypass = useSubscriptionBypass(); + return () => h("div"); + }, +}); + +function setting(proxyModeWhenSubscribe?: string) { + return { + setting: { + transparent: "close", + transparentType: "tproxy", + pacMode: "whitelist", + logLevel: "info", + proxyModeWhenSubscribe, + }, + localGFWListVersion: "", + localGeositeVersion: "", + }; +} + +beforeEach(() => { + vi.clearAllMocks(); + closeAllDialogs(); + wrapper = mountWithApp(Probe); +}); + +afterEach(() => { + wrapper.unmount(); + closeAllDialogs(); +}); + +describe("useSubscriptionBypass", () => { + test.each(["checking", "running", "paused"])( + "uses the configured route without loading settings while the core is %s", + async (running) => { + useAppStore().setRunning(running); + + await expect(chooseBypass()).resolves.toBe(false); + + expect(getSetting).not.toHaveBeenCalled(); + expect(dialogState.stack).toHaveLength(0); + }, + ); + + test("uses direct mode without asking when the core is stopped", async () => { + useAppStore().setRunning("stopped"); + vi.mocked(getSetting).mockResolvedValue(setting("direct")); + + await expect(chooseBypass()).resolves.toBe(false); + + expect(getSetting).toHaveBeenCalledOnce(); + expect(dialogState.stack).toHaveLength(0); + }); + + test.each(["proxy", "pac"])( + "returns true after confirmation for stopped-core %s mode", + async (mode) => { + useAppStore().setRunning("stopped"); + vi.mocked(getSetting).mockResolvedValue(setting(mode)); + + const result = chooseBypass(); + await flushPromises(); + const dialog = dialogState.stack.at(-1)!; + expect(dialog.component).toBe(ConfirmDialog); + expect(dialog.props).toMatchObject({ + message: "The core is stopped. Update without the proxy?", + confirmText: "Yes", + cancelText: "No", + }); + + closeDialog(dialog.id, true); + await expect(result).resolves.toBe(true); + }, + ); + + test("returns null when direct access is declined", async () => { + useAppStore().setRunning("stopped"); + vi.mocked(getSetting).mockResolvedValue(setting("proxy")); + + const result = chooseBypass(); + await flushPromises(); + closeDialog(dialogState.stack.at(-1)!.id, false); + + await expect(result).resolves.toBeNull(); + }); + + test("words the confirmation for every subscription when asked for all", async () => { + useAppStore().setRunning("stopped"); + vi.mocked(getSetting).mockResolvedValue(setting("proxy")); + + const result = chooseBypass(true); + await flushPromises(); + const dialog = dialogState.stack.at(-1)!; + expect(dialog.component).toBe(ConfirmDialog); + expect(dialog.props).toMatchObject({ + message: "The core is stopped. Update all subscriptions without the proxy?", + confirmText: "Yes", + cancelText: "No", + }); + + closeDialog(dialog.id, true); + await expect(result).resolves.toBe(true); + }); +}); diff --git a/gui/src/composables/useSubscriptionBypass.ts b/gui/src/composables/useSubscriptionBypass.ts new file mode 100644 index 00000000..a79abc5c --- /dev/null +++ b/gui/src/composables/useSubscriptionBypass.ts @@ -0,0 +1,26 @@ +import { getSetting } from "@/api"; +import { useAppStore } from "@/stores/app"; +import { useI18n } from "vue-i18n"; +import { useConfirm } from "./useConfirm"; + +/** Returns true for a confirmed one-request direct fetch, false for the configured route, and null on cancel. */ +export function useSubscriptionBypass() { + const store = useAppStore(); + const confirm = useConfirm(); + const { t } = useI18n(); + + return async (all = false): Promise => { + if (store.running !== "stopped") return false; + const mode = (await getSetting()).setting.proxyModeWhenSubscribe; + if (mode !== "proxy" && mode !== "pac") return false; + return (await confirm({ + message: all + ? t("subscription.coreStoppedDirectAll") + : t("subscription.coreStoppedDirect"), + confirmText: t("operations.yes"), + cancelText: t("operations.no"), + })) + ? true + : null; + }; +} diff --git a/gui/src/dialogs/Import.spec.ts b/gui/src/dialogs/Import.spec.ts new file mode 100644 index 00000000..bef734d6 --- /dev/null +++ b/gui/src/dialogs/Import.spec.ts @@ -0,0 +1,90 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, test, vi } from "vitest"; +import { flushPromises, type VueWrapper } from "@vue/test-utils"; +import type * as Api from "@/api"; +import { getSetting, postImport } from "@/api"; +import { + closeAllDialogs, + closeDialog, + dialogState, +} from "@/composables/useDialog"; +import { closeAllNotices } from "@/composables/useNotify"; +import { useAppStore } from "@/stores/app"; +import { mountWithApp } from "@/test/mount"; +import ImportDialog from "./Import.vue"; + +vi.mock("@/api", async (original) => ({ + ...(await original()), + getSetting: vi.fn(), + postImport: vi.fn(), +})); + +let wrapper: VueWrapper; +const address = "https://subscription.example/list"; + +beforeEach(() => { + vi.clearAllMocks(); + closeAllDialogs(); + closeAllNotices(); + vi.mocked(getSetting).mockResolvedValue({ + setting: { + transparent: "close", + transparentType: "tproxy", + pacMode: "whitelist", + logLevel: "info", + proxyModeWhenSubscribe: "proxy", + }, + localGFWListVersion: "", + localGeositeVersion: "", + }); + vi.mocked(postImport).mockResolvedValue({} as never); + wrapper = mountWithApp(ImportDialog, { + props: { kind: "subscription" }, + }); + useAppStore().setRunning("stopped"); +}); + +afterEach(() => { + wrapper.unmount(); + closeAllDialogs(); + closeAllNotices(); +}); + +async function submit() { + await wrapper.get("textarea").setValue(address); + await wrapper + .findAll("button") + .find((button) => button.text() === "Import")! + .trigger("click"); + await flushPromises(); +} + +describe("subscription import with a stopped core", () => { + test("sends one explicit proxy bypass after Yes", async () => { + await submit(); + expect(postImport).not.toHaveBeenCalled(); + + closeDialog(dialogState.stack.at(-1)!.id, true); + await flushPromises(); + + expect(postImport).toHaveBeenCalledExactlyOnceWith({ + url: address, + kind: "subscription", + bypassProxy: true, + }); + expect(wrapper.emitted("close")).toEqual([[true]]); + }); + + test("keeps the import open and sends nothing after No", async () => { + await submit(); + + closeDialog(dialogState.stack.at(-1)!.id, false); + await flushPromises(); + + expect(postImport).not.toHaveBeenCalled(); + expect(wrapper.emitted("close")).toBeUndefined(); + expect(wrapper.get("textarea").element.value).toBe( + address, + ); + }); +}); diff --git a/gui/src/dialogs/Import.vue b/gui/src/dialogs/Import.vue index 6959c5fe..8d389c18 100644 --- a/gui/src/dialogs/Import.vue +++ b/gui/src/dialogs/Import.vue @@ -9,6 +9,7 @@ import { postImport } from "@/api"; import { ApiError } from "@/api/client"; import { errorText } from "@/api/errors"; import { useNotify } from "@/composables/useNotify"; +import { useSubscriptionBypass } from "@/composables/useSubscriptionBypass"; defineOptions({ name: "ImportDialog" }); const props = defineProps<{ @@ -18,6 +19,7 @@ const props = defineProps<{ const emit = defineEmits<{ close: [imported?: boolean] }>(); const { t } = useI18n(); const notify = useNotify(); +const subscriptionBypass = useSubscriptionBypass(); const kind = ref<"server" | "subscription">(props.kind ?? "server"); const text = ref(""); @@ -28,7 +30,14 @@ async function submit(url = text.value.trim()) { if (!url || importing.value) return; importing.value = true; try { - await postImport({ url, kind: kind.value }); + const bypassProxy = + kind.value === "subscription" ? await subscriptionBypass() : false; + if (bypassProxy === null) return; + await postImport({ + url, + kind: kind.value, + ...(bypassProxy ? { bypassProxy: true } : {}), + }); notify.success(t("import.success")); emit("close", true); } catch (err) { diff --git a/gui/src/dialogs/Subscription.spec.ts b/gui/src/dialogs/Subscription.spec.ts new file mode 100644 index 00000000..866d7c2c --- /dev/null +++ b/gui/src/dialogs/Subscription.spec.ts @@ -0,0 +1,174 @@ +// @vitest-environment happy-dom +import { afterEach, expect, test, vi } from "vitest"; +import { flushPromises, type VueWrapper } from "@vue/test-utils"; +import { VSelect, VSwitch } from "vuetify/components"; +import type * as Api from "@/api"; +import type { TouchSubscription } from "@/api/types"; +import { patchSubscription } from "@/api"; +import { mountWithApp } from "@/test/mount"; +import Subscription from "./Subscription.vue"; + +vi.mock("@/api", async (original) => ({ + ...(await original()), + patchSubscription: vi.fn().mockResolvedValue(undefined), +})); +let wrapper: VueWrapper; +afterEach(() => { + wrapper?.unmount(); + vi.clearAllMocks(); +}); + +const subscription = { + id: 1, + _type: "subscription" as const, + host: "example.test", + status: "", + info: "", + address: "https://example.test/sub", + remarks: "keep", + servers: [], + autoSelect: false, + updateMode: "disabled" as const, + updateIntervalMinutes: 0, + failureIntervalMinutes: 1, +}; + +test("offers four modes and only shows fields required by the mode", async () => { + wrapper = mountWithApp(Subscription, { props: { subscription } }); + const mode = wrapper.findComponent(VSelect); + expect(mode.props("items")).toHaveLength(4); + expect(wrapper.findAll('input[type="number"]')).toHaveLength(0); + expect(wrapper.findAllComponents(VSwitch)).toHaveLength(1); + expect( + wrapper + .findAllComponents(VSwitch) + .some( + (control) => + control.props("label") === + "Ignore subscription download routing during recovery", + ), + ).toBe(false); + + mode.vm.$emit("update:modelValue", "at_interval"); + await flushPromises(); + expect(wrapper.findAll('input[type="number"]')).toHaveLength(1); + expect( + wrapper + .findAllComponents(VSwitch) + .some( + (control) => + control.props("label") === + "Ignore subscription download routing during recovery", + ), + ).toBe(false); + + mode.vm.$emit("update:modelValue", "interval_failsafe"); + await flushPromises(); + const inputs = wrapper.findAll('input[type="number"]'); + expect(inputs).toHaveLength(2); + expect( + wrapper + .findAllComponents(VSwitch) + .find( + (control) => + control.props("label") === + "Ignore subscription download routing during recovery", + )! + .props("modelValue"), + ).toBe(false); + await inputs[0].setValue("15"); + await inputs[1].setValue("2"); + await wrapper + .findAll("button") + .find((button) => button.text() === "Save and Apply")! + .trigger("click"); + await flushPromises(); + expect(patchSubscription).toHaveBeenCalledWith({ + subscription: { + ...subscription, + updateMode: "interval_failsafe", + updateIntervalMinutes: 15, + failureIntervalMinutes: 2, + allowDirectRecovery: false, + }, + }); +}); + +test("persists explicit direct-recovery consent and restores it when reopening", async () => { + wrapper = mountWithApp(Subscription, { + props: { + subscription: { + ...subscription, + updateMode: "interval_failsafe", + updateIntervalMinutes: 15, + }, + }, + }); + wrapper + .findAllComponents(VSwitch) + .find( + (control) => + control.props("label") === + "Ignore subscription download routing during recovery", + )! + .vm.$emit("update:modelValue", true); + await flushPromises(); + await wrapper + .findAll("button") + .find((button) => button.text() === "Save and Apply")! + .trigger("click"); + await flushPromises(); + const saved = vi.mocked(patchSubscription).mock.calls[0][0] + .subscription as TouchSubscription; + expect(saved.allowDirectRecovery).toBe(true); + wrapper.unmount(); + wrapper = mountWithApp(Subscription, { props: { subscription: saved } }); + expect( + wrapper + .findAllComponents(VSwitch) + .find( + (control) => + control.props("label") === + "Ignore subscription download routing during recovery", + )! + .props("modelValue"), + ).toBe(true); + wrapper + .findAllComponents(VSwitch) + .find( + (control) => + control.props("label") === + "Ignore subscription download routing during recovery", + )! + .vm.$emit("update:modelValue", false); + await flushPromises(); + await wrapper + .findAll("button") + .find((button) => button.text() === "Save and Apply")! + .trigger("click"); + await flushPromises(); + expect(vi.mocked(patchSubscription).mock.calls[1][0].subscription).toEqual( + expect.objectContaining({ allowDirectRecovery: false }), + ); +}); + +test.each(["", "0", "0.5"])( + "rejects invalid regular interval %s", + async (value) => { + wrapper = mountWithApp(Subscription, { + props: { + subscription: { + ...subscription, + updateMode: "at_interval" as const, + }, + }, + }); + await wrapper.find('input[type="number"]').setValue(value); + await wrapper + .findAll("button") + .find((button) => button.text() === "Save and Apply")! + .trigger("click"); + await flushPromises(); + expect(patchSubscription).not.toHaveBeenCalled(); + }, +); diff --git a/gui/src/dialogs/Subscription.vue b/gui/src/dialogs/Subscription.vue index 9efa1b5a..83b6269a 100644 --- a/gui/src/dialogs/Subscription.vue +++ b/gui/src/dialogs/Subscription.vue @@ -1,8 +1,6 @@