Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
fix(desktop): probe auth before instance resume (#6587)
Shreyas430cc08572b7
diff --git a/packages/hoppscotch-desktop/package.json b/packages/hoppscotch-desktop/package.jsonindex 22ec4cbf9..95d9d78d8 100644--- a/packages/hoppscotch-desktop/package.json+++ b/packages/hoppscotch-desktop/package.json@@ -7,6 +7,8 @@"dev": "vite","build": "vue-tsc --noEmit && vite build","preview": "vite preview",+ "test": "vitest --run",+ "test:watch": "vitest","tauri": "tauri","lint": "eslint src","lint:ts": "vue-tsc --noEmit",@@ -19,7 +21,8 @@"dev:full": "pnpm tauri dev","build:full": "pnpm tauri build","dev:portable": "pnpm tauri dev -- --no-default-features --features portable",- "build:portable": "pnpm tauri build -- --no-default-features --features portable"+ "build:portable": "pnpm tauri build -- --no-default-features --features portable",+ "do-test": "pnpm run test"},"dependencies": {"@fontsource-variable/inter": "5.2.8",@@ -57,6 +60,7 @@"eslint-plugin-prettier": "5.5.6","eslint-plugin-vue": "10.9.2","globals": "16.5.0",+ "jsdom": "27.4.0","postcss": "8.5.15","sass": "1.101.0","tailwindcss": "3.4.16",@@ -64,6 +68,7 @@"unplugin-icons": "22.5.0","unplugin-vue-components": "30.0.0","vite": "7.3.2",+ "vitest": "4.1.10","vue-tsc": "2.2.0"}}diff --git a/packages/hoppscotch-desktop/src/composables/__tests__/useAppInitialization.spec.ts b/packages/hoppscotch-desktop/src/composables/__tests__/useAppInitialization.spec.tsnew file mode 100644index 000000000..814a7beaa--- /dev/null+++ b/packages/hoppscotch-desktop/src/composables/__tests__/useAppInitialization.spec.ts@@ -0,0 +1,172 @@+import { beforeEach, describe, expect, it, vi } from "vitest"++import type { Instance } from "@hoppscotch/common/platform/instance"++type LoadCall = { bundleName: string; host?: string }++const { load, download, close } = vi.hoisted(() => ({+ load: vi.fn<+ (opts: { bundleName: string; host?: string }) => Promise<unknown>+ >(async () => ({ success: true, windowLabel: "instance" })),+ download: vi.fn<(opts: { serverUrl: string }) => Promise<unknown>>(+ async () => ({+ version: "26.7.0",+ bundleName: "acme",+ })+ ),+ close: vi.fn<(opts: { windowLabel: string }) => void>(),+}))++vi.mock("@hoppscotch/plugin-appload", () => ({ load, download, close }))++vi.mock("@tauri-apps/api/app", () => ({+ getVersion: async () => "26.7.0",+}))++vi.mock("@tauri-apps/api/core", () => ({+ invoke: async () => undefined,+}))++vi.mock("~/services/instance-store-migration.service", () => ({+ InstanceStoreMigrationService: {+ getInstance: () => ({+ initialize: async () => undefined,+ getMigrationStatus: () => ({ value: { status: "completed" } }),+ getMigrationError: () => ({ value: null }),+ }),+ },+}))++vi.mock("@hoppscotch/common/composables/desktop-settings", () => ({+ useDesktopSettings: () => ({+ ready: async () => undefined,+ settings: { zoomLevel: 1.0 },+ }),+}))++// One in-memory value per store key, standing in for the Tauri store the+// launcher and the instance webviews share on disk.+const store = {+ connectionState: null as unknown,+ recentInstances: [] as Instance[],+ instanceAuthFailure: null as string | null,+}++const resource = <K extends keyof typeof store>(key: K) => ({+ get: async () => store[key],+ set: async (value: (typeof store)[K]) => {+ store[key] = value+ },+ watch: async () => () => undefined,+})++vi.mock("~/services/persistence.service", () => ({+ DesktopPersistenceService: {+ getInstance: () => ({+ connectionState: resource("connectionState"),+ recentInstances: resource("recentInstances"),+ instanceAuthFailure: resource("instanceAuthFailure"),+ init: async () => ({ _tag: "Right", right: undefined }),+ }),+ },+}))++const { useAppInitialization } = await import("../useAppInitialization")++const ORG_INSTANCE: Instance = {+ kind: "cloud-org",+ serverUrl: "https://acme.example.com",+ displayName: "Acme",+ version: "26.7.0",+ lastUsed: "2026-08-20T00:00:00.000Z",+ bundleName: "Hoppscotch",+}++// A cloud-org resume calls `load` with the instance's `serverUrl` as `host`,+// where the vendored fallback calls it with no host at all, so the presence+// of `host` is what separates the two outcomes.+const resumedHosts = () =>+ load.mock.calls+ .map(([opts]) => (opts as LoadCall).host)+ .filter((host): host is string => host !== undefined)++describe("loadRecent auth probe", () => {+ beforeEach(() => {+ store.connectionState = { status: "connected", instance: ORG_INSTANCE }+ store.recentInstances = [ORG_INSTANCE]+ store.instanceAuthFailure = null+ load.mockClear()+ close.mockClear()+ })++ // The launcher read side ships ahead of the enterprise writer that records+ // a failure, so on every OSS launch the record is absent and startup has+ // to behave as it did before the probe existed. Adding the writer later+ // fails this test if it changes that.+ it("resumes the connected instance when no auth failure is recorded", async () => {+ await useAppInitialization().loadRecent()++ expect(resumedHosts()).toEqual([ORG_INSTANCE.serverUrl])+ })++ it("resumes when the recorded failure belongs to another instance", async () => {+ store.instanceAuthFailure = "https://other.example.com"++ await useAppInitialization().loadRecent()++ expect(resumedHosts()).toEqual([ORG_INSTANCE.serverUrl])+ })++ it("resumes when the record is unreadable", async () => {+ const initialization = useAppInitialization()+ vi.spyOn(+ initialization.persistence.instanceAuthFailure,+ "get"+ ).mockRejectedValueOnce(new Error("store unavailable"))++ await initialization.loadRecent()++ expect(resumedHosts()).toEqual([ORG_INSTANCE.serverUrl])+ })++ // The contract the enterprise writer targets. A recorded failure for the+ // instance about to be resumed routes startup to the vendored app, whose+ // header renders the instance switcher, and the record is consumed so a+ // later manual reconnect is not blocked.+ it("loads vendored and clears the record on a matching failure", async () => {+ store.instanceAuthFailure = ORG_INSTANCE.serverUrl++ await useAppInitialization().loadRecent()++ expect(resumedHosts()).toEqual([])+ expect(load).toHaveBeenCalledWith(+ expect.objectContaining({ bundleName: "Hoppscotch" })+ )+ expect(store.instanceAuthFailure).toBeNull()+ })++ // The webview and the launcher record the same server through different+ // flows, so the two spellings have to compare equal.+ it("matches a recorded failure that differs by case and trailing slash", async () => {+ store.instanceAuthFailure = "https://ACME.example.com/desktop-app-server/"++ await useAppInitialization().loadRecent()++ expect(resumedHosts()).toEqual([])+ })++ // `vendored` runs offline and default `cloud` stays usable signed out, so+ // neither is probed and a stale record cannot divert them.+ it("skips the probe for instances that need no auth", async () => {+ const staleRecord = "https://acme.example.com"+ store.instanceAuthFailure = staleRecord+ store.connectionState = {+ status: "connected",+ instance: { ...ORG_INSTANCE, kind: "cloud" },+ }++ await useAppInitialization().loadRecent()++ expect(store.instanceAuthFailure).toBe(staleRecord)+ })+})diff --git a/packages/hoppscotch-desktop/src/composables/useAppInitialization.ts b/packages/hoppscotch-desktop/src/composables/useAppInitialization.tsindex 7b1255482..89d560212 100644--- a/packages/hoppscotch-desktop/src/composables/useAppInitialization.ts+++ b/packages/hoppscotch-desktop/src/composables/useAppInitialization.ts@@ -35,6 +35,22 @@ export enum AppState {LOADED = "loaded",}+const DESKTOP_APP_SERVER_PATH = "/desktop-app-server"++// One spelling of an instance URL. The same server is written as+// `https://Acme.example.com/`, `https://acme.example.com` and with the+// `/desktop-app-server` suffix depending on which flow recorded it, so+// every comparison between a stored URL and an instance's `serverUrl`+// normalizes both sides first.+const normalizeServerUrl = (u: string) => {+ let n = u.toLowerCase()+ while (n.endsWith("/")) n = n.slice(0, -1)+ if (n.endsWith(DESKTOP_APP_SERVER_PATH))+ n = n.slice(0, -DESKTOP_APP_SERVER_PATH.length)+ while (n.endsWith("/")) n = n.slice(0, -1)+ return n+}+export function useAppInitialization() {const persistence = DesktopPersistenceService.getInstance()const migration = InstanceStoreMigrationService.getInstance()@@ -220,15 +236,7 @@ export function useAppInitialization() {version: dlResp.version,bundleName: dlResp.bundleName,}- const DESKTOP_APP_SERVER_PATH = "/desktop-app-server"- const normUrl = (u: string) => {- let n = u.toLowerCase()- while (n.endsWith("/")) n = n.slice(0, -1)- if (n.endsWith(DESKTOP_APP_SERVER_PATH))- n = n.slice(0, -DESKTOP_APP_SERVER_PATH.length)- while (n.endsWith("/")) n = n.slice(0, -1)- return n- }+ const normUrl = normalizeServerUrltry {const recentInstances = await persistence.recentInstances.get()await persistence.recentInstances.set(@@ -295,6 +303,84 @@ export function useAppInitialization() {}}+ // Only cloud-org and self-hosted (`on-prem`) instances require auth.+ // `vendored` runs fully offline and `cloud` (default cloud) stays usable+ // while signed out, so neither can leave the user on a login-required+ // screen and neither needs an auth probe before resuming.+ const isAuthRequiringInstance = (instance: Instance): boolean =>+ instance.kind === "cloud-org" || instance.kind === "on-prem"++ // The auth session for an instance is stored in that instance's webview+ // (its `localStorage` bearer tokens), a context the launcher window cannot+ // read, so the launcher cannot verify the session over the network on its+ // own. Instead the webview records the instance's `serverUrl` under+ // `instanceAuthFailure` when its auth flow routes to the login-required+ // screen. Reading that record here is the launcher's auth probe, a match+ // means the last resume of this instance ended unable to+ // authenticate, so resuming again would route straight back to the same+ // screen with the main window already closed. Returning false lets startup+ // continue to the vendored app instead, whose header renders the+ // instance switcher.+ const probeInstanceAuth = async (instance: Instance): Promise<boolean> => {+ if (!isAuthRequiringInstance(instance)) return true++ try {+ const failedUrl = await persistence.instanceAuthFailure.get()+ if (+ failedUrl &&+ normalizeServerUrl(failedUrl) === normalizeServerUrl(instance.serverUrl)+ ) {+ return false+ }+ return true+ } catch (err) {+ // A degraded store must not block a resume that would otherwise+ // succeed, so treat an unreadable record as "no known failure".+ console.warn("Failed to read instance auth-failure record:", err)+ return true+ }+ }++ // Resume `instance` unless its auth-failure record blocks it. A blocked+ // resume loads the vendored app, which persists its own connection state,+ // so the user reaches the instance switcher rather than the login-required+ // screen the failed instance would route to. Returns true once startup is+ // handled here (resume started, or the vendored redirect ran), and false+ // when the resume threw so the caller can try the next candidate.+ const clearInstanceAuthFailure = async () => {+ try {+ await persistence.instanceAuthFailure.set(null)+ } catch (err) {+ console.warn("Failed to clear instance auth-failure record:", err)+ }+ }++ const tryResumeInstance = async (instance: Instance): Promise<boolean> => {+ if (!(await probeInstanceAuth(instance))) {+ mainDiag(+ `loadRecent: auth probe failed for ${instance.displayName}, loading vendored`+ )+ await loadVendoredInstance()+ // The record is a one-shot, so a later manual reconnect through the+ // switcher is not blocked once the user re-authenticates. Clearing it+ // waits for the vendored app to be up, which `loadVendoredInstance`+ // reports through `appState` rather than by throwing. Dropping it+ // before that would let the next launch resume the same instance with+ // nothing left to record that its auth had failed.+ if (appState.value !== AppState.ERROR) {+ await clearInstanceAuthFailure()+ }+ return true+ }+ try {+ await loadVendoredIfMatches(instance)+ return true+ } catch (err) {+ console.warn("Failed to resume instance:", err)+ return false+ }+ }+const loadRecent = async () => {try {statusMessage.value = "Loading application..."@@ -322,16 +408,12 @@ export function useAppInitialization() {mainDiag(`loadRecent: resuming connected instance: kind=${connectionState.instance.kind}, displayName=${connectionState.instance.displayName}`)+ // A `connected` status persists across restarts, so without the+ // auth probe in `tryResumeInstance` an auth-gated instance whose+ // last resume could not authenticate would be resumed again on+ // every launch, routing back to the login-required screen.statusMessage.value = `Connecting to ${connectionState.instance.displayName}...`- try {- await loadVendoredIfMatches(connectionState.instance)- return- } catch (err) {- console.warn(- "Failed to load previously connected instance:",- err- )- }+ if (await tryResumeInstance(connectionState.instance)) return}break@@ -343,12 +425,7 @@ export function useAppInitialization() {connectionState.target)if (targetInstance) {- try {- await loadVendoredIfMatches(targetInstance)- return- } catch (err) {- console.warn("Failed to resume connection:", err)- }+ if (await tryResumeInstance(targetInstance)) return}}break@@ -367,12 +444,7 @@ export function useAppInitialization() {if (mostRecentInstance) {statusMessage.value = `Connecting to ${mostRecentInstance.displayName}...`- try {- await loadVendoredIfMatches(mostRecentInstance)- return- } catch (err) {- console.warn("Failed to load most recent instance:", err)- }+ if (await tryResumeInstance(mostRecentInstance)) return}console.log("No recent instances found, loading vendored as fallback")diff --git a/packages/hoppscotch-desktop/src/services/persistence.service.ts b/packages/hoppscotch-desktop/src/services/persistence.service.tsindex adbf4c259..2281f1f23 100644--- a/packages/hoppscotch-desktop/src/services/persistence.service.ts+++ b/packages/hoppscotch-desktop/src/services/persistence.service.ts@@ -34,6 +34,7 @@ export const STORE_KEYS = {UPDATE_STATE: UPDATE_STATE_STORE_KEY,CONNECTION_STATE: "connectionState",RECENT_INSTANCES: "recentInstances",+ INSTANCE_AUTH_FAILURE: "instanceAuthFailure",SCHEMA_VERSION: "schema_version",// Legacy key. Written by portable builds in schema v1. Read only by the// v1 to v2 migration. All other code uses `DESKTOP_SETTINGS`.@@ -219,6 +220,15 @@ export class DesktopPersistenceService {readonly updateState: StoreResource<UpdateState | null>readonly connectionState: StoreResource<PersistedConnectionState | null>readonly recentInstances: StoreResource<Instance[]>+ // Cross-context record of the last instance whose auth flow failed.+ // Written by an instance's webview when it routes to its login-required+ // screen, read by the launcher on the next startup so it can skip resuming+ // an instance it has no way to authenticate and continue to the vendored+ // app's switcher. Set to the failing `serverUrl`, or `null` when there is no+ // pending failure. The launcher window cannot verify the session itself+ // because the bearer tokens are in the instance webview's `localStorage`,+ // a separate context, so this shared record is the only auth signal it has.+ readonly instanceAuthFailure: StoreResource<string | null>private constructor() {this.desktopSettings = createStoreResource(@@ -245,6 +255,12 @@ export class DesktopPersistenceService {z.array(INSTANCE_SCHEMA),() => [])+ this.instanceAuthFailure = createStoreResource(+ STORE_NAMESPACE,+ STORE_KEYS.INSTANCE_AUTH_FAILURE,+ z.string().nullable(),+ () => null+ )}public static getInstance(): DesktopPersistenceService {diff --git a/packages/hoppscotch-desktop/vitest.config.mts b/packages/hoppscotch-desktop/vitest.config.mtsnew file mode 100644index 000000000..6d818a9d9--- /dev/null+++ b/packages/hoppscotch-desktop/vitest.config.mts@@ -0,0 +1,16 @@+import { defineConfig } from "vitest/config"+import * as path from "path"++export default defineConfig({+ test: {+ // `mainDiag` reads `window.__TAURI_INTERNALS__` on every launcher+ // step, so the launcher code needs a DOM even in a unit run.+ environment: "jsdom",+ },+ resolve: {+ alias: {+ "~": path.resolve(__dirname, "src"),+ "@hoppscotch/common": path.resolve(__dirname, "../hoppscotch-common/src"),+ },+ },+})diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 9a0d37e3a..72966c4b0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1144,6 +1144,9 @@ importers:globals:specifier: 16.5.0version: 16.5.0+ jsdom:+ specifier: 27.4.0+ version: 27.4.0(@noble/[email protected])postcss:specifier: 8.5.18version: 8.5.18@@ -1165,6 +1168,9 @@ importers:vite:specifier: 7.3.2version: 7.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])+ vitest:+ specifier: 4.1.10+ version: 4.1.10(@types/[email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))vue-tsc:specifier: 2.2.0version: 2.2.0([email protected])