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: stop secret variable values from leaking to backend (#6279)
Nivedin44f58d13c86c
diff --git a/packages/hoppscotch-common/src/components/collections/ImportExport.vue b/packages/hoppscotch-common/src/components/collections/ImportExport.vueindex 485d2bc5f..056d1c1f5 100644--- a/packages/hoppscotch-common/src/components/collections/ImportExport.vue+++ b/packages/hoppscotch-common/src/components/collections/ImportExport.vue@@ -35,6 +35,12 @@ import AllCollectionImport from "~/components/importExport/ImportExportSteps/Allimport { useI18n } from "~/composables/i18n"import { useToast } from "~/composables/toast"import { appendRESTCollections, restCollections$ } from "~/newstore/collections"+import {+ ensureRefIds,+ flushUnmatchedRefIdsFromTree,+ populateLocalStoresFromCollectionTree,+ stripCollectionTreeForStore,+} from "~/helpers/secretVariables"import IconInsomnia from "~icons/hopp/insomnia"import IconPostman from "~icons/hopp/postman"@@ -50,7 +56,10 @@ import { getTeamCollectionJSON } from "~/helpers/backend/helpers"import { platform } from "~/platform"-import { initializeDownloadFile } from "~/helpers/import-export/export"+import {+ initializeDownloadFile,+ stripRefIdReplacer,+} from "~/helpers/import-export/export"import { gistExporter } from "~/helpers/import-export/export/gist"import { myCollectionsExporter } from "~/helpers/import-export/export/myCollections"import { teamCollectionsExporter } from "~/helpers/import-export/export/teamCollections"@@ -121,7 +130,11 @@ const handleImportToStore = async (collections: HoppCollection[]) => {*/const importToPersonalWorkspace = (collections: HoppCollection[]) => {// Remove old id from the imported collection and folders and transform it to new collection format- const sanitizedCollections = collections.map(sanitizeCollection)+ const sanitizedCollections = collections+ .map(sanitizeCollection)+ .map(ensureRefIds)++ sanitizedCollections.forEach(populateLocalStoresFromCollectionTree)if (platform.sync.collections.importToPersonalWorkspace &&@@ -134,14 +147,17 @@ const importToPersonalWorkspace = (collections: HoppCollection[]) => {)}- appendRESTCollections(sanitizedCollections)+ appendRESTCollections(sanitizedCollections.map(stripCollectionTreeForStore))return E.right({ success: true })}/**- * Import collections to teams workspace- * No need to sanitize the collections before importing to teams workspace because the BE handles this and add the new id to the collection and folders- * @param collections Collections to import+ * Import collections to teams workspace. Stamps `_ref_id` and seeds the+ * device-local secret stores under it; on the team-collection-added+ * subscription, `TeamCollectionsService.addCollection` migrates entries+ * from `_ref_id` to the backend-assigned `id`. Wire payload is stripped+ * of secrets via `transformCollectionForImport`; secrets stay+ * device-local per the team-isolation model.*/const importToTeamsWorkspace = async (collections: HoppCollection[]) => {if (!hasTeamWriteAccess.value || !selectedTeamID.value) {@@ -150,7 +166,10 @@ const importToTeamsWorkspace = async (collections: HoppCollection[]) => {})}- const transformedCollection = collections.map((collection) =>+ const collectionsWithRefIds = collections.map(ensureRefIds)+ collectionsWithRefIds.forEach(populateLocalStoresFromCollectionTree)++ const transformedCollection = collectionsWithRefIds.map((collection) =>transformCollectionForImport(collection))@@ -159,11 +178,16 @@ const importToTeamsWorkspace = async (collections: HoppCollection[]) => {selectedTeamID.value)()- return E.isRight(res)- ? E.right({ success: true })- : E.left({- success: false,- })+ if (E.isLeft(res)) {+ // Backend rejected — flush ONLY `_ref_id`-keyed entries we just+ // seeded. `flushLocalStoresForCollectionTree` would also delete by+ // `node.id`, which could be a live backend id from a same-workspace+ // re-import and would wipe existing collections' in-memory secrets.+ // Empty `keptRefIds` ⇒ every `_ref_id` in the tree is flushed.+ flushUnmatchedRefIdsFromTree(collectionsWithRefIds, new Set())+ return E.left({ success: false })+ }+ return E.right({ success: true })}const emit = defineEmits<{@@ -831,7 +855,8 @@ const getCollectionJSON = async () => {}if (props.collectionsType.type === "my-collections") {- return E.right(JSON.stringify(myCollections.value, null, 2))+ const stripped = myCollections.value.map(stripCollectionTreeForStore)+ return E.right(JSON.stringify(stripped, stripRefIdReplacer, 2))}return E.left("INVALID_SELECTED_TEAM_OR_INVALID_COLLECTION_TYPE")diff --git a/packages/hoppscotch-common/src/components/collections/documentation/index.vue b/packages/hoppscotch-common/src/components/collections/documentation/index.vueindex c82ecbb1f..6100f360f 100644--- a/packages/hoppscotch-common/src/components/collections/documentation/index.vue+++ b/packages/hoppscotch-common/src/components/collections/documentation/index.vue@@ -270,6 +270,7 @@ import {import { updateTeamCollection } from "~/helpers/backend/mutations/TeamCollection"import { updateTeamRequest } from "~/helpers/backend/mutations/TeamRequest"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"import {CollectionDataProps,getSingleTeamCollectionJSON,@@ -735,7 +736,7 @@ const saveCollectionDocumentation = async () => {const data: CollectionDataProps = {auth: collection.auth || { authType: "inherit", authActive: true },headers: collection.headers || [],- variables: collection.variables || [],+ variables: stripSecretVariableValuesForWire(collection.variables || []),description: documentationDescription.value,preRequestScript: collection.preRequestScript || "",testScript: collection.testScript || "",@@ -831,7 +832,9 @@ const saveCollectionDocumentationById = async (const data: CollectionDataProps = {auth: collectionData.auth || { authType: "inherit", authActive: true },headers: collectionData.headers || [],- variables: collectionData.variables || [],+ variables: stripSecretVariableValuesForWire(+ collectionData.variables || []+ ),description: documentation,preRequestScript: collectionData.preRequestScript || "",testScript: collectionData.testScript || "",diff --git a/packages/hoppscotch-common/src/components/collections/graphql/Collection.vue b/packages/hoppscotch-common/src/components/collections/graphql/Collection.vueindex df4d38b36..14803af49 100644--- a/packages/hoppscotch-common/src/components/collections/graphql/Collection.vue+++ b/packages/hoppscotch-common/src/components/collections/graphql/Collection.vue@@ -250,6 +250,7 @@ import { useService } from "dioc/vue"import { computed, ref } from "vue"import { Picked } from "~/helpers/types/HoppPicked"import { removeGraphqlCollection } from "~/newstore/collections"+import { flushLocalStoresForCollectionTree } from "~/helpers/secretVariables"import { handleTokenValidation } from "~/helpers/handleTokenValidation"import { GQLTabService } from "~/services/tab/graphql"import IconCheckCircle from "~icons/lucide/check-circle"@@ -382,6 +383,8 @@ const removeCollection = async () => {tab.value.document.isDirty = true}+ flushLocalStoresForCollectionTree(props.collection)+removeGraphqlCollection(props.collectionIndex, props.collection.id)toast.success(`${t("state.deleted")}`)}diff --git a/packages/hoppscotch-common/src/components/collections/graphql/Folder.vue b/packages/hoppscotch-common/src/components/collections/graphql/Folder.vueindex a2cb4e381..2b710b144 100644--- a/packages/hoppscotch-common/src/components/collections/graphql/Folder.vue+++ b/packages/hoppscotch-common/src/components/collections/graphql/Folder.vue@@ -235,6 +235,7 @@ import { computed, ref } from "vue"import { handleTokenValidation } from "~/helpers/handleTokenValidation"import { Picked } from "~/helpers/types/HoppPicked"import { removeGraphqlFolder } from "~/newstore/collections"+import { flushLocalStoresForCollectionTree } from "~/helpers/secretVariables"import { GQLTabService } from "~/services/tab/graphql"import IconCheckCircle from "~icons/lucide/check-circle"import IconCopy from "~icons/lucide/copy"@@ -345,6 +346,8 @@ const removeFolder = async () => {tab.value.document.isDirty = true}+ flushLocalStoresForCollectionTree(props.folder)+removeGraphqlFolder(props.folderPath, props.folder.id)toast.success(t("state.deleted"))}diff --git a/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue b/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vueindex 08f857042..77ebdf16c 100644--- a/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue+++ b/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue@@ -35,6 +35,11 @@ import { gistExporter } from "~/helpers/import-export/export/gist"import { computed } from "vue"import { hoppGQLImporter } from "~/helpers/import-export/import/hopp"import { ReqType } from "~/helpers/backend/graphql"+import {+ ensureRefIds,+ populateLocalStoresFromCollectionTree,+ stripCollectionTreeForStore,+} from "~/helpers/secretVariables"const t = useI18n()const toast = useToast()@@ -191,10 +196,8 @@ const GqlCollectionsGistExporter: ImporterOrExporter = {const accessToken = currentUser.value?.accessTokenif (accessToken) {- const res = await gistExporter(- JSON.stringify(gqlCollections.value),- accessToken- )+ const stripped = gqlCollections.value.map(stripCollectionTreeForStore)+ const res = await gistExporter(JSON.stringify(stripped), accessToken)if (E.isLeft(res)) {toast.error(t("export.failed"))@@ -233,17 +236,22 @@ const showImportFailedError = () => {}const handleImportToStore = (gqlCollections: HoppCollection[]) => {+ const collectionsWithRefIds = gqlCollections.map(ensureRefIds)+ collectionsWithRefIds.forEach(populateLocalStoresFromCollectionTree)+if (platform.sync.collections.importToPersonalWorkspace &¤tUser.value) {return platform.sync.collections.importToPersonalWorkspace(- gqlCollections,+ collectionsWithRefIds,ReqType.Gql)}- appendGraphqlCollections(gqlCollections)+ appendGraphqlCollections(+ collectionsWithRefIds.map(stripCollectionTreeForStore)+ )toast.success(t("state.file_imported"))}diff --git a/packages/hoppscotch-common/src/components/collections/index.vue b/packages/hoppscotch-common/src/components/collections/index.vueindex f9387c91f..88a964efa 100644--- a/packages/hoppscotch-common/src/components/collections/index.vue+++ b/packages/hoppscotch-common/src/components/collections/index.vue@@ -399,6 +399,12 @@ import { CurrentValueService } from "~/services/current-environment-value.servicimport { TeamCollectionsService } from "~/services/team-collection.service"import { SortOptions } from "~/helpers/backend/graphql"import { CurrentSortValuesService } from "~/services/current-sort.service"+import {+ flushLocalStoresForCollectionTree,+ flushLocalStoresForTeamCollectionTree,+ stripCollectionTreeForStore,+ stripSecretVariableValuesForWire,+} from "~/helpers/secretVariables"const t = useI18n()const toast = useToast()@@ -1992,15 +1998,8 @@ const onRemoveCollection = async () => {toast.success(t("state.deleted"))displayConfirmModal(false)- // delete the secret collection variables- // and current collection variables value if the collection is removedif (collectionToRemove) {- secretEnvironmentService.deleteSecretEnvironment(- collectionToRemove._ref_id ?? `${collectionIndex}`- )- currentEnvironmentValueService.deleteEnvironment(- collectionToRemove._ref_id ?? `${collectionIndex}`- )+ flushLocalStoresForCollectionTree(collectionToRemove)}} else if (hasTeamWriteAccess.value) {const collectionID = editingCollectionID.value@@ -2015,12 +2014,20 @@ const onRemoveCollection = async () => {emit("select", null)}+ // Capture the subtree BEFORE the mutation so the+ // team-collection-removed subscription can't drop it from FE state+ // before we flush nested entries.+ const subtreeSnapshot =+ teamCollectionService.findCollectionByID(collectionID)+removeTeamCollectionOrFolder(collectionID).then(() => {resetTeamRequestsContext()- // delete the secret collection variables- // and current collection variables value if the collection is removed- if (collectionID) {+ if (subtreeSnapshot) {+ flushLocalStoresForTeamCollectionTree(subtreeSnapshot)+ } else if (collectionID) {+ // Snapshot miss (already removed from tree). Flush at least the+ // top-level id so the secret service doesn't leak this entry.secretEnvironmentService.deleteSecretEnvironment(collectionID)currentEnvironmentValueService.deleteEnvironment(collectionID)}@@ -2053,8 +2060,6 @@ const onRemoveFolder = async () => {emit("select", null)}- const folderIndex = pathToLastIndex(folderPath)-const folderToRemove = folderPath? navigateToFolderWithIndexPath(restCollectionStore.value.state,@@ -2075,15 +2080,8 @@ const onRemoveFolder = async () => {toast.success(t("state.deleted"))displayConfirmModal(false)- // delete the secret collection variables- // and current collection variables value if the collection is removedif (folderToRemove) {- secretEnvironmentService.deleteSecretEnvironment(- folderToRemove.id ?? `${folderIndex}`- )- currentEnvironmentValueService.deleteEnvironment(- folderToRemove.id ?? `${folderIndex}`- )+ flushLocalStoresForCollectionTree(folderToRemove)}} else if (hasTeamWriteAccess.value) {const collectionID = editingCollectionID.value@@ -2098,12 +2096,15 @@ const onRemoveFolder = async () => {emit("select", null)}+ const subtreeSnapshot =+ teamCollectionService.findCollectionByID(collectionID)+removeTeamCollectionOrFolder(collectionID).then(() => {resetTeamRequestsContext()- // delete the secret collection variables- // and current collection variables value if the collection is removed- if (collectionID) {+ if (subtreeSnapshot) {+ flushLocalStoresForTeamCollectionTree(subtreeSnapshot)+ } else if (collectionID) {secretEnvironmentService.deleteSecretEnvironment(collectionID)currentEnvironmentValueService.deleteEnvironment(collectionID)}@@ -3155,7 +3156,11 @@ const initializeDownloadCollection = async (*/const exportData = async (collection: HoppCollection | TeamCollection) => {if (collectionsType.value.type === "my-collections") {- const collectionJSON = JSON.stringify(collection, stripRefIdReplacer, 2)+ const collectionJSON = JSON.stringify(+ stripCollectionTreeForStore(collection as HoppCollection),+ stripRefIdReplacer,+ 2+ )// Strip `export {};\n` from `testScript` and `preRequestScript` fieldsconst cleanedCollectionJSON =@@ -3179,7 +3184,7 @@ const exportData = async (collection: HoppCollection | TeamCollection) => {async (coll) => {const hoppColl = teamCollToHoppRESTColl(coll)const collectionJSONString = JSON.stringify(- hoppColl,+ stripCollectionTreeForStore(hoppColl),stripRefIdReplacer,2)@@ -3235,6 +3240,26 @@ const getCurrentValue = ()?.currentValue}+/**+ * Restore both `initialValue` and `currentValue` for a secret variable from+ * the local secret store. Both fields are blanked at the wire boundary+ * before the variable is sent to the backend, so when the user reopens the+ * Properties modal we re-populate from `secretEnvironmentService`.+ * Returns null for non-secret variables (callers fall back to existing+ * current-value lookup) or when the slot has no entry in the secret store.+ */+const getSecretValues = (+ isSecret: boolean,+ varIndex: number,+ collectionID: string+): { value: string; initialValue: string } | null => {+ if (!isSecret) return null+ return secretEnvironmentService.getSecretEnvironmentVariableValue(+ collectionID,+ varIndex+ )+}+const editProperties = async (payload: {collectionIndex: stringcollection: HoppCollection | TeamCollection@@ -3272,14 +3297,15 @@ const editProperties = async (payload: {const collectionVariables = pipe((collection as HoppCollection).variables ?? [],A.mapWithIndex((index, e) => {+ const storeID = (collection as HoppCollection)._ref_id ?? collectionId!+ const stored = getSecretValues(e.secret, index, storeID)return {...e,currentValue:- getCurrentValue(- e.secret,- index,- (collection as HoppCollection)._ref_id ?? collectionId!- ) ?? e.currentValue,+ stored?.value ??+ getCurrentValue(e.secret, index, storeID) ??+ e.currentValue,+ initialValue: stored?.initialValue ?? e.initialValue,}}))@@ -3333,10 +3359,14 @@ const editProperties = async (payload: {const collectionVariables = pipe((data.variables ?? []) as HoppCollectionVariable[],A.mapWithIndex((index, e) => {+ const stored = getSecretValues(e.secret, index, collectionId!)return {...e,currentValue:- getCurrentValue(e.secret, index, collectionId!) ?? e.currentValue,+ stored?.value ??+ getCurrentValue(e.secret, index, collectionId!) ??+ e.currentValue,+ initialValue: stored?.initialValue ?? e.initialValue,}}))@@ -3399,6 +3429,7 @@ const setCollectionProperties = (newCollection: {? O.some({key: e.key,value: e.currentValue,+ initialValue: e.initialValue,varIndex: i,}): O.none@@ -3419,24 +3450,17 @@ const setCollectionProperties = (newCollection: {))- secretEnvironmentService.addSecretEnvironment(- collection._ref_id ?? collectionId!,- secretVariables- )+ // Mirror the read-side keying in `editProperties`.+ const storeKey =+ collectionsType.value.type === "team-collections"+ ? collectionId!+ : (collection._ref_id ?? collectionId!)- currentEnvironmentValueService.addEnvironment(- collection._ref_id ?? collectionId!,- nonSecretVariables- )+ secretEnvironmentService.addSecretEnvironment(storeKey, secretVariables)- //set current value and secret values to empty string- collection.variables = pipe(- filteredVariables,- A.map((e) => ({- ...e,- currentValue: "",- }))- )+ currentEnvironmentValueService.addEnvironment(storeKey, nonSecretVariables)++ collection.variables = stripSecretVariableValuesForWire(filteredVariables)}if (collectionsType.value.type === "my-collections") {@@ -3451,7 +3475,7 @@ const setCollectionProperties = (newCollection: {})toast.success(t("collection.properties_updated"))} else if (hasTeamWriteAccess.value && collectionId) {- const data = {+ const data: CollectionDataProps = {auth: collection.auth ?? {authType: "inherit",authActive: true,diff --git a/packages/hoppscotch-common/src/components/environments/Add.vue b/packages/hoppscotch-common/src/components/environments/Add.vueindex 71dedb1da..1a9ec22c8 100644--- a/packages/hoppscotch-common/src/components/environments/Add.vue+++ b/packages/hoppscotch-common/src/components/environments/Add.vue@@ -79,6 +79,7 @@ import { useToast } from "~/composables/toast"import { GQLError } from "~/helpers/backend/GQLClient"import { updateTeamEnvironment } from "~/helpers/backend/mutations/TeamEnvironment"import { getEnvActionErrorMessage } from "~/helpers/error-messages"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"import {setGlobalEnvVariables,updateEnvironment,@@ -205,7 +206,7 @@ const addEnvironment = async () => {await pipe(updateTeamEnvironment(- JSON.stringify(newVariables),+ JSON.stringify(stripSecretVariableValuesForWire(newVariables)),scope.value.environment.id,scope.value.environment.environment.name),diff --git a/packages/hoppscotch-common/src/components/environments/ImportExport.vue b/packages/hoppscotch-common/src/components/environments/ImportExport.vueindex 7db641fa2..b1a168d53 100644--- a/packages/hoppscotch-common/src/components/environments/ImportExport.vue+++ b/packages/hoppscotch-common/src/components/environments/ImportExport.vue@@ -9,7 +9,12 @@</template><script setup lang="ts">-import { Environment, NonSecretEnvironment } from "@hoppscotch/data"+import { Environment, generateUniqueRefId } from "@hoppscotch/data"+import {+ populateLocalStoresFromVariables,+ promoteInitialValueForImport,+ stripSecretVariableValuesForWire,+} from "~/helpers/secretVariables"import * as E from "fp-ts/Either"import { ref } from "vue"@@ -24,8 +29,12 @@ import {addGlobalEnvVariable,appendEnvironments,environments$,+ getGlobalVariables,} from "~/newstore/environments"+import { useService } from "dioc/vue"+import { CurrentValueService } from "~/services/current-environment-value.service"+import { SecretEnvironmentService } from "~/services/secret-environment.service"import { GQLError } from "~/helpers/backend/GQLClient"import { CreateTeamEnvironmentMutation } from "~/helpers/backend/graphql"import { createTeamEnvironment } from "~/helpers/backend/mutations/TeamEnvironment"@@ -56,6 +65,9 @@ const props = defineProps<{const myEnvironments = useReadonlyStream(environments$, [])+const currentEnvironmentValueService = useService(CurrentValueService)+const secretEnvironmentService = useService(SecretEnvironmentService)+const currentUser = useReadonlyStream(platform.auth.getCurrentUserStream(),platform.auth.getCurrentUser()@@ -358,17 +370,85 @@ const showImportFailedError = () => {const handleImportToStore = async (environments: Environment[],- globalEnvs: NonSecretEnvironment[] = []+ globalEnvs: Environment[] = []) => {- // Add global envs to the store- globalEnvs.forEach(({ variables }) => {- variables.forEach(({ key, initialValue, currentValue, secret }) => {- addGlobalEnvVariable({ key, initialValue, currentValue, secret })- })- })+ // Per-env populate happens inside MY_ENV / TEAMS branches below, each+ // keyed appropriately. Globals share the single `"Global"` key and must+ // merge with existing entries — hydrate, concat, populate once.+ if (globalEnvs.length > 0) {+ const importedGlobals = globalEnvs.flatMap(({ variables }) => variables)++ const existingHydrated: Environment["variables"] = getGlobalVariables().map(+ (v, i) => {+ if (v.secret) {+ const stored = secretEnvironmentService.getSecretEnvironmentVariable(+ "Global",+ i+ )+ return {+ ...v,+ initialValue: stored?.initialValue ?? "",+ currentValue: stored?.value ?? "",+ }+ }+ const stored = currentEnvironmentValueService.getEnvironmentVariable(+ "Global",+ i+ )+ return {+ ...v,+ currentValue: stored?.currentValue ?? v.currentValue,+ }+ }+ )++ // `populateLocalStoresFromVariables` is a full replace for `"Global"`.+ // Relies on the sync path above (`getGlobalVariables()` → hydrate →+ // concat) running with no awaits in between — a future refactor that+ // introduces one between the snapshot and this call would silently+ // drop any global added meanwhile.+ //+ // Promote on the IMPORTED slice only (not `existingHydrated`) so a+ // legacy export shape (`initialValue` set, `currentValue: ""`) lands+ // its secrets correctly, while user-cleared existing globals stay+ // cleared per the rehydration semantic.+ populateLocalStoresFromVariables("Global", [+ ...existingHydrated,+ ...promoteInitialValueForImport(importedGlobals),+ ])++ // Append stripped imports; varIndex aligns with the hydrated entries.+ stripSecretVariableValuesForWire(importedGlobals).forEach(+ ({ key, initialValue, currentValue, secret }) => {+ addGlobalEnvVariable({ key, initialValue, currentValue, secret })+ }+ )+ }if (props.environmentType === "MY_ENV") {- appendEnvironments(environments)+ // Always stamp a fresh temp id, even if the export carried one —+ // re-using the exported `id` would land the populate on a store+ // entry already owned by the original environment (then the sync+ // remap would migrate that entry away, blanking the original's+ // secrets). A fresh id guarantees no collision with anything in+ // the store before the sync handler creates the new backend row.+ const envsWithIds = environments.map((env) => ({+ ...env,+ id: generateUniqueRefId("env"),+ }))++ envsWithIds.forEach((env) => {+ populateLocalStoresFromVariables(+ env.id,+ promoteInitialValueForImport(env.variables)+ )+ })++ const strippedEnvironments = envsWithIds.map((env) => ({+ ...env,+ variables: stripSecretVariableValuesForWire(env.variables),+ }))+ appendEnvironments(strippedEnvironments)toast.success(t("state.file_imported"))} else {await importToTeams(environments)@@ -382,7 +462,7 @@ const importToTeams = async (content: Environment[]) => {for (const [, env] of content.entries()) {const res = createTeamEnvironment(- JSON.stringify(env.variables),+ JSON.stringify(stripSecretVariableValuesForWire(env.variables)),props.teamId as string,env.name)()@@ -392,6 +472,17 @@ const importToTeams = async (content: Environment[]) => {const res = await Promise.all(envImportPromises)+ // Populate local stores keyed by the new backend env ID — this device+ // retains the raw values; the team DB row stays clean.+ res.forEach((entry, index) => {+ if (E.isRight(entry)) {+ populateLocalStoresFromVariables(+ entry.right.createTeamEnvironment.id,+ promoteInitialValueForImport(content[index].variables)+ )+ }+ })+const failedImports = res.some((r) => E.isLeft(r))if (failedImports) {diff --git a/packages/hoppscotch-common/src/components/environments/Selector.vue b/packages/hoppscotch-common/src/components/environments/Selector.vueindex 66692ff7e..a553ab2de 100644--- a/packages/hoppscotch-common/src/components/environments/Selector.vue+++ b/packages/hoppscotch-common/src/components/environments/Selector.vue@@ -691,10 +691,13 @@ onMounted(() => {const envSelectorActions = ref<TippyComponent | null>(null)const envQuickPeekActions = ref<TippyComponent | null>(null)-const globalVals = useReadonlyStream(globalEnv$, {} as GlobalEnvironment)+const globalVals = useReadonlyStream(globalEnv$, {+ v: 2,+ variables: [],+} as GlobalEnvironment)const globalEnvs = computed(() => {- return globalVals.value.variables.map((variable, index) => ({+ return (globalVals.value?.variables ?? []).map((variable, index) => ({...variable,currentValue:currentEnvironmentValueService.getEnvironmentVariableValue(diff --git a/packages/hoppscotch-common/src/components/environments/index.vue b/packages/hoppscotch-common/src/components/environments/index.vueindex c1a8e67a5..a74cafac6 100644--- a/packages/hoppscotch-common/src/components/environments/index.vue+++ b/packages/hoppscotch-common/src/components/environments/index.vue@@ -57,6 +57,7 @@<script setup lang="ts">import { useReadonlyStream, useStream } from "@composables/stream"import { Environment, GlobalEnvironment } from "@hoppscotch/data"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"import { useService } from "dioc/vue"import * as TE from "fp-ts/TaskEither"import { pipe } from "fp-ts/function"@@ -76,12 +77,16 @@ import TeamEnvironmentAdapter from "~/helpers/teams/TeamEnvironmentAdapter"import {createEnvironment,deleteEnvironment,+ environmentsStore,getGlobalVariables,getSelectedEnvironmentIndex,globalEnv$,selectedEnvironmentIndex$,setSelectedEnvironmentIndex,} from "~/newstore/environments"+import { getService } from "~/modules/dioc"+import { SecretEnvironmentService } from "~/services/secret-environment.service"+import { CurrentValueService } from "~/services/current-environment-value.service"import { useLocalState } from "~/newstore/localstate"import { platform } from "~/platform"import { TeamWorkspace, WorkspaceService } from "~/services/workspace.service"@@ -101,7 +106,10 @@ const environmentType = ref<EnvironmentsChooseType>({selectedTeam: undefined,})-const globalEnv = useReadonlyStream(globalEnv$, {} as GlobalEnvironment)+const globalEnv = useReadonlyStream(globalEnv$, {+ v: 2,+ variables: [],+} as GlobalEnvironment)const globalEnvironment = computed<Environment>(() => ({v: 2 as const,@@ -265,7 +273,9 @@ const duplicateGlobalEnvironment = async () => {await pipe(createTeamEnvironment(- JSON.stringify(globalEnvironment.value.variables),+ JSON.stringify(+ stripSecretVariableValuesForWire(globalEnvironment.value.variables)+ ),workspace.value.teamID,`Global - ${t("action.duplicate")}`),@@ -276,6 +286,9 @@ const duplicateGlobalEnvironment = async () => {toast.error(t(getEnvActionErrorMessage(err)))},() => {+ // Secret variable values are intentionally NOT copied to the+ // duplicated environment — duplicates start fresh on secrets per+ // the per-entity secret model.toast.success(t("environment.duplicated"))})@@ -294,23 +307,41 @@ const duplicateGlobalEnvironment = async () => {toast.success(`${t("environment.duplicated")}`)}+const secretEnvironmentService = getService(SecretEnvironmentService)+const currentEnvironmentValueService = getService(CurrentValueService)+const removeSelectedEnvironment = () => {const selectedEnvIndex = getSelectedEnvironmentIndex()if (selectedEnvIndex?.type === "NO_ENV_SELECTED") returnif (selectedEnvIndex?.type === "MY_ENV") {- deleteEnvironment(selectedEnvIndex.index)+ // Pass envID so the selfhost sync handler can call the backend delete+ // for already-synced envs. The handler internally guards against the+ // create-window race (`pendingTempEnvIds` set in `sync.ts`) so a temp+ // `uniqueID()` here won't 404; only real backend ids reach the wire.+ const envID =+ environmentsStore.value.environments[selectedEnvIndex.index]?.id+ deleteEnvironment(selectedEnvIndex.index, envID)+ if (envID) {+ secretEnvironmentService.deleteSecretEnvironment(envID)+ currentEnvironmentValueService.deleteEnvironment(envID)+ }toast.success(`${t("state.deleted")}`)}if (selectedEnvIndex?.type === "TEAM_ENV") {+ const teamEnvID = selectedEnvIndex.teamEnvIDpipe(- deleteTeamEnvironment(selectedEnvIndex.teamEnvID),+ deleteTeamEnvironment(teamEnvID),TE.match((err: GQLError<string>) => {console.error(err)},() => {+ // Same lifecycle hygiene as MY_ENV — flush after backend+ // success so the secret service doesn't retain the entry.+ secretEnvironmentService.deleteSecretEnvironment(teamEnvID)+ currentEnvironmentValueService.deleteEnvironment(teamEnvID)toast.success(`${t("team_environment.deleted")}`)})diff --git a/packages/hoppscotch-common/src/components/environments/my/Details.vue b/packages/hoppscotch-common/src/components/environments/my/Details.vueindex 271c70b71..3843229cc 100644--- a/packages/hoppscotch-common/src/components/environments/my/Details.vue+++ b/packages/hoppscotch-common/src/components/environments/my/Details.vue@@ -241,6 +241,7 @@ import * as E from "fp-ts/Either"import * as O from "fp-ts/Option"import { flow, pipe } from "fp-ts/function"import { ComputedRef, computed, ref, watch } from "vue"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"import { uniqueID } from "~/helpers/utils/uniqueID"import {createEnvironment,@@ -361,7 +362,10 @@ const clearIcon = refAutoReset<typeof IconTrash2 | typeof IconDone>(1000)-const globalEnv = useReadonlyStream(globalEnv$, {} as GlobalEnvironment)+const globalEnv = useReadonlyStream(globalEnv$, {+ v: 2,+ variables: [],+} as GlobalEnvironment)type SelectedEnv = "variables" | "secret"@@ -570,39 +574,25 @@ const saveEnvironment = () => {))- if (secretVariables.length > 0) {- if (editingID.value) {- secretEnvironmentService.addSecretEnvironment(- editingID.value,- secretVariables- )- } else if (props.editingEnvironmentIndex === "Global") {- secretEnvironmentService.addSecretEnvironment("Global", secretVariables)- }- }- if (nonSecretVariables.length > 0) {- if (editingID.value) {- currentEnvironmentValueService.addEnvironment(- editingID.value,- nonSecretVariables- )- } else if (props.editingEnvironmentIndex === "Global") {- currentEnvironmentValueService.addEnvironment(- "Global",- nonSecretVariables- )- }+ // Always write to both stores (even when an array is empty) so a save+ // that removes secrets/non-secrets clears the prior entries instead of+ // leaving stale values keyed by old `varIndex` slots — `addSecretEnvironment`+ // / `addEnvironment` are `Map.set` replacements, not merges.+ if (editingID.value) {+ secretEnvironmentService.addSecretEnvironment(+ editingID.value,+ secretVariables+ )+ currentEnvironmentValueService.addEnvironment(+ editingID.value,+ nonSecretVariables+ )+ } else if (props.editingEnvironmentIndex === "Global") {+ secretEnvironmentService.addSecretEnvironment("Global", secretVariables)+ currentEnvironmentValueService.addEnvironment("Global", nonSecretVariables)}- const variables = pipe(- filteredVariables,- A.map((e) => ({- key: e.key,- secret: e.secret,- initialValue: e.secret ? "" : e.initialValue,- currentValue: "",- }))- )+ const variables = stripSecretVariableValuesForWire(filteredVariables)const environmentUpdated: Environment = {v: 2,diff --git a/packages/hoppscotch-common/src/components/environments/teams/Details.vue b/packages/hoppscotch-common/src/components/environments/teams/Details.vueindex e146f0b34..94f23d95f 100644--- a/packages/hoppscotch-common/src/components/environments/teams/Details.vue+++ b/packages/hoppscotch-common/src/components/environments/teams/Details.vue@@ -254,6 +254,7 @@ import {updateTeamEnvironment,} from "~/helpers/backend/mutations/TeamEnvironment"import { GQLError } from "~/helpers/backend/GQLClient"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"import { TeamEnvironment } from "~/helpers/teams/TeamEnvironment"import { useColorMode } from "~/composables/theming"import { platform } from "~/platform"@@ -353,7 +354,10 @@ const vars = ref<EnvironmentVariable[]>([const secretEnvironmentService = useService(SecretEnvironmentService)const currentEnvironmentValueService = useService(CurrentValueService)-const globalEnv = useReadonlyStream(globalEnv$, {} as GlobalEnvironment)+const globalEnv = useReadonlyStream(globalEnv$, {+ v: 2,+ variables: [],+} as GlobalEnvironment)const secretVars = computed(() =>pipe(@@ -551,15 +555,7 @@ const saveEnvironment = async () => {))- const variables = pipe(- filteredVariables,- A.map((e) => ({- key: e.key,- secret: e.secret,- initialValue: e.secret ? "" : e.initialValue,- currentValue: "",- }))- )+ const variables = stripSecretVariableValuesForWire(filteredVariables)const environmentUpdated: Environment = {v: 2,@@ -612,26 +608,24 @@ const saveEnvironment = async () => {return}- if (editingID.value) {- secretEnvironmentService.addSecretEnvironment(- editingID.value,- secretVariables- )-- currentEnvironmentValueService.addEnvironment(- editingID.value,- nonSecretVariables- )-- // If the user is a viewer, we don't need to update the environment in BE- // just update the secret environment and current environment in the local storage- if (props.isViewer) {- hideModal()- toast.success(`${t("environment.updated")}`)+ // Viewers don't sync to backend — update local stores immediately+ // and exit. For non-viewers, defer the store writes to the backend+ // success callback (mirrors the "new" branch above) so local state+ // stays in sync with the persisted payload if the mutation fails.+ if (props.isViewer) {+ if (editingID.value) {+ secretEnvironmentService.addSecretEnvironment(+ editingID.value,+ secretVariables+ )+ currentEnvironmentValueService.addEnvironment(+ editingID.value,+ nonSecretVariables+ )}- }-- if (!props.isViewer) {+ hideModal()+ toast.success(`${t("environment.updated")}`)+ } else {await pipe(updateTeamEnvironment(JSON.stringify(environmentUpdated.variables),@@ -645,6 +639,16 @@ const saveEnvironment = async () => {isLoading.value = false},() => {+ if (editingID.value) {+ secretEnvironmentService.addSecretEnvironment(+ editingID.value,+ secretVariables+ )+ currentEnvironmentValueService.addEnvironment(+ editingID.value,+ nonSecretVariables+ )+ }hideModal()toast.success(`${t("environment.updated")}`)diff --git a/packages/hoppscotch-common/src/components/http/TestResult.vue b/packages/hoppscotch-common/src/components/http/TestResult.vueindex 5bd5e6f3c..cf84cf798 100644--- a/packages/hoppscotch-common/src/components/http/TestResult.vue+++ b/packages/hoppscotch-common/src/components/http/TestResult.vue@@ -314,7 +314,10 @@ const selectedEnvironmentIndex = useStream(setSelectedEnvironmentIndex)-const globalEnvVars = useReadonlyStream(globalEnv$, {} as GlobalEnvironment)+const globalEnvVars = useReadonlyStream(globalEnv$, {+ v: 2,+ variables: [],+} as GlobalEnvironment)const noEnvSelected = computed(() => selectedEnvironmentIndex.value.type === "NO_ENV_SELECTED"diff --git a/packages/hoppscotch-common/src/components/http/test/TestResult.vue b/packages/hoppscotch-common/src/components/http/test/TestResult.vueindex 7fa61c41e..34b54973f 100644--- a/packages/hoppscotch-common/src/components/http/test/TestResult.vue+++ b/packages/hoppscotch-common/src/components/http/test/TestResult.vue@@ -276,7 +276,10 @@ const selectedEnvironmentIndex = useStream(setSelectedEnvironmentIndex)-const globalEnvVars = useReadonlyStream(globalEnv$, {} as GlobalEnvironment)+const globalEnvVars = useReadonlyStream(globalEnv$, {+ v: 2,+ variables: [],+} as GlobalEnvironment)const noEnvSelected = computed(() => selectedEnvironmentIndex.value.type === "NO_ENV_SELECTED"diff --git a/packages/hoppscotch-common/src/composables/useMockServer.ts b/packages/hoppscotch-common/src/composables/useMockServer.tsindex 32102249f..8e02423da 100644--- a/packages/hoppscotch-common/src/composables/useMockServer.ts+++ b/packages/hoppscotch-common/src/composables/useMockServer.ts@@ -30,6 +30,7 @@ import {loadMockServers,} from "~/newstore/mockServers"import { CurrentValueService } from "~/services/current-environment-value.service"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"import { TeamCollectionsService } from "~/services/team-collection.service"import { WorkspaceService } from "~/services/workspace.service"@@ -281,7 +282,9 @@ export function useMockServer() {await pipe(updateTeamEnvironment(- JSON.stringify(normalizedVariables),+ JSON.stringify(+ stripSecretVariableValuesForWire(normalizedVariables)+ ),existingEnv.id,existingEnv.environment.name),@@ -323,7 +326,11 @@ export function useMockServer() {]await pipe(- createTeamEnvironment(JSON.stringify(variables), teamID, envName),+ createTeamEnvironment(+ JSON.stringify(stripSecretVariableValuesForWire(variables)),+ teamID,+ envName+ ),TE.match((error) => {console.error("Failed to create team environment:", error)diff --git a/packages/hoppscotch-common/src/helpers/RequestRunner.ts b/packages/hoppscotch-common/src/helpers/RequestRunner.tsindex b4aba50cd..2a276042e 100644--- a/packages/hoppscotch-common/src/helpers/RequestRunner.ts+++ b/packages/hoppscotch-common/src/helpers/RequestRunner.ts@@ -134,7 +134,9 @@ export const captureInitialEnvironmentState = (): InitialEnvironmentState => {// Capture the initial environment nameconst initialEnvName = getCurrentEnvironment().name- // Capture the initial script environment state (the environment passed to scripts)+ // Snapshot for the post-script diff. Both this and the sandbox receive+ // secret-hydrated values from `getCombinedEnvVariables`, so reading a+ // secret doesn't show up as a change in `hasScopeChanges`.const initialEnvs = getCombinedEnvVariables()const initialEnvsForComparison: TestResult["envs"] = {global: initialEnvs.global,@@ -239,11 +241,14 @@ const updateEnvironments = (initialValue: e.initialValue ?? "",})- // For secret variables, keep the initialValue but clear currentValue for storage+ // Secret values stay client-side only (they were saved into the+ // local secret service above). Both `initialValue` and+ // `currentValue` are cleared on the wire payload so the secret+ // never leaves the device.return {key: e.key,secret: e.secret,- initialValue: e.initialValue ?? "",+ initialValue: "",currentValue: "",}}@@ -255,12 +260,16 @@ const updateEnvironments = (currentValue: e.currentValue ?? "",})- // For non-secret variables, preserve both initialValue and currentValue+ // `currentValue` is per-user/per-session by Hoppscotch convention and+ // is never persisted server-side. The actual value lives in the local+ // `currentEnvironmentValueService` (populated above); the wire payload+ // gets it cleared so test-script env updates can't leak per-user state+ // into the team backend.return {key: e.key,secret: e.secret ?? false,initialValue: e.initialValue ?? "",- currentValue: e.currentValue ?? "",+ currentValue: "",}}))@@ -637,6 +646,7 @@ export function runRESTRequest$(combinedResult,initialEnvironmentIndex,initialEnvName,+ initialEnvsForComparison,initialEnvID)}@@ -699,97 +709,83 @@ function updateEnvsAfterTestScript(runResult: E.Right<SandboxTestResult>,initialEnvironmentIndex: SelectedEnvironmentIndex,initialEnvName: string,+ initialEnvsForComparison: TestResult["envs"],initialEnvID?: string) {- const globalEnvVariables = updateEnvironments(- runResult.right.envs.global,- "global"+ // Gate each writeback on whether its own scope actually changed. The outer+ // `hasEnvironmentChanges` guard is an OR across both scopes, so without+ // these per-scope checks a script that touched only the selected env would+ // still trigger an `updateUserEnvironment` round-trip for the unchanged+ // globals (and the same happens the other way for TEAM_ENV).+ const globalChanged = hasScopeChanges(+ initialEnvsForComparison.global,+ runResult.right.envs.global)-- setGlobalEnvVariables({- v: 2,- variables: globalEnvVariables,- })-- const selectedEnvVariables = updateEnvironments(- cloneDeep(runResult.right.envs.selected),- "selected",- initialEnvID+ const selectedChanged = hasScopeChanges(+ initialEnvsForComparison.selected,+ runResult.right.envs.selected)- if (initialEnvironmentIndex.type === "MY_ENV") {- const env = getEnvironment({- type: "MY_ENV",- index: initialEnvironmentIndex.index,- })- updateEnvironment(initialEnvironmentIndex.index, {- name: env.name,+ if (globalChanged) {+ const globalEnvVariables = updateEnvironments(+ runResult.right.envs.global,+ "global"+ )++ setGlobalEnvVariables({v: 2,- id: "id" in env ? env.id : "",- variables: selectedEnvVariables,+ variables: globalEnvVariables,})- } else if (initialEnvironmentIndex.type === "TEAM_ENV") {- // Use the initial environment name to avoid issues when environment changes during request execution- // adding a fallback to current environment name just in case so it's not null- const envName = initialEnvName ?? getCurrentEnvironment().name- pipe(- updateTeamEnvironment(- JSON.stringify(selectedEnvVariables),- initialEnvironmentIndex.teamEnvID,- envName- )- )()+ }++ if (selectedChanged) {+ const selectedEnvVariables = updateEnvironments(+ cloneDeep(runResult.right.envs.selected),+ "selected",+ initialEnvID+ )++ if (initialEnvironmentIndex.type === "MY_ENV") {+ const env = getEnvironment({+ type: "MY_ENV",+ index: initialEnvironmentIndex.index,+ })+ updateEnvironment(initialEnvironmentIndex.index, {+ name: env.name,+ v: 2,+ id: "id" in env ? env.id : "",+ variables: selectedEnvVariables,+ })+ } else if (initialEnvironmentIndex.type === "TEAM_ENV") {+ // Use the initial environment name to avoid issues when environment changes during request execution+ // adding a fallback to current environment name just in case so it's not null+ const envName = initialEnvName ?? getCurrentEnvironment().name+ // `updateEnvironments` above already returns wire-shaped variables+ pipe(+ updateTeamEnvironment(+ JSON.stringify(selectedEnvVariables),+ initialEnvironmentIndex.teamEnvID,+ envName+ )+ )()+ }}}-/**- * Checks if there are any changes between two environment states by comparing- * the initial environment state with the final environment state.- * @param initialEnvs The environment state at the start- * @param finalEnvs The environment state after changes- * @returns true if there are any environment changes, false otherwise- */+const hasScopeChanges = (+ initial: Environment["variables"],+ final: Environment["variables"]+): boolean =>+ getAddedEnvVariables(initial, final).length > 0 ||+ getRemovedEnvVariables(initial, final).length > 0 ||+ getUpdatedEnvVariables(initial, final).length > 0+const hasEnvironmentChanges = (initialEnvs: TestResult["envs"],finalEnvs: TestResult["envs"]-): boolean => {- // Check global environment changes- const globalAdditions = getAddedEnvVariables(- initialEnvs.global,- finalEnvs.global- )- const globalDeletions = getRemovedEnvVariables(- initialEnvs.global,- finalEnvs.global- )- const globalUpdations = getUpdatedEnvVariables(- initialEnvs.global,- finalEnvs.global- )-- // Check selected environment changes- const selectedAdditions = getAddedEnvVariables(- initialEnvs.selected,- finalEnvs.selected- )- const selectedDeletions = getRemovedEnvVariables(- initialEnvs.selected,- finalEnvs.selected- )- const selectedUpdations = getUpdatedEnvVariables(- initialEnvs.selected,- finalEnvs.selected- )-- return (- globalAdditions.length > 0 ||- globalDeletions.length > 0 ||- globalUpdations.length > 0 ||- selectedAdditions.length > 0 ||- selectedDeletions.length > 0 ||- selectedUpdations.length > 0- )-}+): boolean =>+ hasScopeChanges(initialEnvs.global, finalEnvs.global) ||+ hasScopeChanges(initialEnvs.selected, finalEnvs.selected)const getCookieJarEntries = () => {// Exclusive to the Desktop App@@ -940,6 +936,7 @@ export async function runTestRunnerRequest(postRequestScriptResult,initialEnvironmentIndex,initialEnvName,+ initialEnvsForComparison,initialEnvID)}diff --git a/packages/hoppscotch-common/src/helpers/__tests__/globalEnvShape.spec.ts b/packages/hoppscotch-common/src/helpers/__tests__/globalEnvShape.spec.tsnew file mode 100644index 000000000..450676ccc--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/__tests__/globalEnvShape.spec.ts@@ -0,0 +1,84 @@+import { describe, expect, it } from "vitest"+import { coerceGlobalEnvironment } from "../globalEnvShape"++describe("coerceGlobalEnvironment", () => {+ it("passes through a valid v2 wrapper unchanged", () => {+ const wrapper = {+ v: 2 as const,+ variables: [+ { key: "k", initialValue: "i", currentValue: "c", secret: false },+ ],+ }++ expect(coerceGlobalEnvironment(wrapper)).toBe(wrapper)+ })++ it("wraps a bare variables array (legacy / older-backend shape)", () => {+ const bareArray = [+ { key: "k", initialValue: "i", currentValue: "c", secret: false },+ ]++ expect(coerceGlobalEnvironment(bareArray)).toEqual({+ v: 2,+ variables: bareArray,+ })+ })++ it("returns an empty wrapper for null", () => {+ expect(coerceGlobalEnvironment(null)).toEqual({ v: 2, variables: [] })+ })++ it("returns an empty wrapper for undefined", () => {+ expect(coerceGlobalEnvironment(undefined)).toEqual({ v: 2, variables: [] })+ })++ it("returns an empty wrapper for an object with non-array variables", () => {+ expect(+ coerceGlobalEnvironment({ v: 2, variables: "not-an-array" })+ ).toEqual({ v: 2, variables: [] })+ })++ it("returns an empty wrapper for an object missing variables", () => {+ expect(coerceGlobalEnvironment({ v: 2 })).toEqual({ v: 2, variables: [] })+ })++ it("rebuilds with v:2 when an object has a variables array but missing v", () => {+ const variables = [+ { key: "k", initialValue: "i", currentValue: "c", secret: false },+ ]+ expect(coerceGlobalEnvironment({ variables })).toEqual({+ v: 2,+ variables,+ })+ })++ it("rebuilds with v:2 when an object has a variables array but a non-2 v", () => {+ const variables = [+ { key: "k", initialValue: "i", currentValue: "c", secret: false },+ ]+ expect(coerceGlobalEnvironment({ v: 1, variables })).toEqual({+ v: 2,+ variables,+ })+ expect(coerceGlobalEnvironment({ v: "2", variables })).toEqual({+ v: 2,+ variables,+ })+ })++ it("returns an empty wrapper for a primitive", () => {+ expect(coerceGlobalEnvironment("string")).toEqual({+ v: 2,+ variables: [],+ })+ expect(coerceGlobalEnvironment(42)).toEqual({ v: 2, variables: [] })+ })++ it("preserves an empty variables array (does not collapse to a fresh wrapper)", () => {+ const wrapper = { v: 2 as const, variables: [] }+ // Identity check: when the input is already a valid wrapper we want+ // to pass it through, not re-allocate, so downstream `===` checks /+ // distinctUntilChanged comparisons stay stable.+ expect(coerceGlobalEnvironment(wrapper)).toBe(wrapper)+ })+})diff --git a/packages/hoppscotch-common/src/helpers/__tests__/secretVariables.spec.ts b/packages/hoppscotch-common/src/helpers/__tests__/secretVariables.spec.tsnew file mode 100644index 000000000..607fb2f0c--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/__tests__/secretVariables.spec.ts@@ -0,0 +1,773 @@+import { HoppCollection } from "@hoppscotch/data"+import { beforeEach, describe, expect, it } from "vitest"++import { getService } from "~/modules/dioc"+import { CurrentValueService } from "~/services/current-environment-value.service"+import { SecretEnvironmentService } from "~/services/secret-environment.service"+import {+ flushLocalStoresForTeamCollectionTree,+ flushUnmatchedRefIdsFromTree,+ indexCollectionsByRefId,+ populateLocalStoresFromCollectionTree,+ populateLocalStoresFromVariables,+ repopulateLoadedCollectionTree,+ stripSecretVariableValuesForWire,+} from "../secretVariables"++const ENTITY_ID = "entity-1"++describe("stripSecretVariableValuesForWire", () => {+ it("clears both initialValue and currentValue for secret variables", () => {+ const result = stripSecretVariableValuesForWire([+ {+ key: "token",+ initialValue: "should-be-stripped",+ currentValue: "should-be-stripped",+ secret: true,+ },+ ])++ expect(result).toEqual([+ {+ key: "token",+ initialValue: "",+ currentValue: "",+ secret: true,+ },+ ])+ })++ it("keeps initialValue but clears currentValue for non-secret variables", () => {+ const result = stripSecretVariableValuesForWire([+ {+ key: "host",+ initialValue: "https://api.example.com",+ currentValue: "https://staging.example.com",+ secret: false,+ },+ ])++ expect(result).toEqual([+ {+ key: "host",+ initialValue: "https://api.example.com",+ currentValue: "",+ secret: false,+ },+ ])+ })++ it("preserves extra fields on each variable (forward-compatible with future schemas)", () => {+ const input = [+ {+ key: "x",+ initialValue: "v",+ currentValue: "v",+ secret: false,+ // hypothetical future field+ description: "the X variable",+ },+ ]++ const [out] = stripSecretVariableValuesForWire(input)+ expect(out.description).toBe("the X variable")+ })++ it("returns an empty array for empty input", () => {+ expect(stripSecretVariableValuesForWire([])).toEqual([])+ })+})++describe("populateLocalStoresFromVariables", () => {+ let secretService: SecretEnvironmentService+ let currentValueService: CurrentValueService++ beforeEach(() => {+ secretService = getService(SecretEnvironmentService)+ currentValueService = getService(CurrentValueService)+ secretService.secretEnvironments.delete(ENTITY_ID)+ currentValueService.environments.delete(ENTITY_ID)+ })++ it("writes secret variables to SecretEnvironmentService", () => {+ populateLocalStoresFromVariables(ENTITY_ID, [+ {+ key: "token",+ initialValue: "init-secret",+ currentValue: "current-secret",+ secret: true,+ },+ ])++ expect(secretService.getSecretEnvironment(ENTITY_ID)).toEqual([+ {+ key: "token",+ value: "current-secret",+ initialValue: "init-secret",+ varIndex: 0,+ },+ ])+ })++ it("writes non-secret currentValue entries to CurrentValueService", () => {+ populateLocalStoresFromVariables(ENTITY_ID, [+ {+ key: "host",+ initialValue: "https://api.example.com",+ currentValue: "https://staging.example.com",+ secret: false,+ },+ ])++ expect(currentValueService.getEnvironment(ENTITY_ID)).toEqual([+ {+ key: "host",+ currentValue: "https://staging.example.com",+ varIndex: 0,+ isSecret: false,+ },+ ])+ })++ it("preserves an explicit empty currentValue for non-secrets", () => {+ // `""` is a meaningful "user cleared this" value — must NOT fall+ // through to `initialValue`. Only nullish (missing) currentValue+ // triggers the fallback.+ populateLocalStoresFromVariables(ENTITY_ID, [+ {+ key: "host",+ initialValue: "https://api.example.com",+ currentValue: "",+ secret: false,+ },+ ])++ expect(currentValueService.getEnvironment(ENTITY_ID)).toEqual([+ {+ key: "host",+ currentValue: "",+ varIndex: 0,+ isSecret: false,+ },+ ])+ })++ it("falls back to initialValue when non-secret currentValue is absent", () => {+ // Missing (undefined) currentValue — not an explicit clear — falls+ // through to `initialValue`.+ populateLocalStoresFromVariables(ENTITY_ID, [+ {+ key: "host",+ initialValue: "https://api.example.com",+ currentValue: undefined as unknown as string,+ secret: false,+ },+ ])++ expect(currentValueService.getEnvironment(ENTITY_ID)).toEqual([+ {+ key: "host",+ currentValue: "https://api.example.com",+ varIndex: 0,+ isSecret: false,+ },+ ])+ })++ it("preserves an explicit empty currentValue for secrets", () => {+ // An explicit `""` is a deliberate clear and must not be resurrected+ // from `initialValue` — otherwise rehydrating an existing global where+ // the user cleared `currentValue` while keeping `initialValue` would+ // silently restore the old secret on the next import/merge.+ populateLocalStoresFromVariables(ENTITY_ID, [+ {+ key: "token",+ initialValue: "old-secret",+ currentValue: "",+ secret: true,+ },+ ])++ expect(secretService.getSecretEnvironment(ENTITY_ID)).toEqual([+ {+ key: "token",+ value: "",+ initialValue: "old-secret",+ varIndex: 0,+ },+ ])+ })++ it("falls back to initialValue for secrets when currentValue is absent", () => {+ // Nullish (missing) `currentValue` — distinct from an explicit clear —+ // falls through to `initialValue`. Covers the legacy `hoppEnv` import+ // shape where only `initialValue` is present on the entry.+ populateLocalStoresFromVariables(ENTITY_ID, [+ {+ key: "token",+ initialValue: "imported-secret",+ currentValue: undefined as unknown as string,+ secret: true,+ },+ ])++ expect(secretService.getSecretEnvironment(ENTITY_ID)).toEqual([+ {+ key: "token",+ value: "imported-secret",+ initialValue: "imported-secret",+ varIndex: 0,+ },+ ])+ })++ it("preserves the variable index for mixed secret + non-secret entries", () => {+ populateLocalStoresFromVariables(ENTITY_ID, [+ {+ key: "host",+ initialValue: "init-host",+ currentValue: "cur-host",+ secret: false,+ },+ {+ key: "token",+ initialValue: "init-token",+ currentValue: "cur-token",+ secret: true,+ },+ {+ key: "version",+ initialValue: "v1",+ currentValue: "v2",+ secret: false,+ },+ ])++ expect(secretService.getSecretEnvironment(ENTITY_ID)).toEqual([+ {+ key: "token",+ value: "cur-token",+ initialValue: "init-token",+ varIndex: 1,+ },+ ])+ expect(currentValueService.getEnvironment(ENTITY_ID)).toEqual([+ {+ key: "host",+ currentValue: "cur-host",+ varIndex: 0,+ isSecret: false,+ },+ {+ key: "version",+ currentValue: "v2",+ varIndex: 2,+ isSecret: false,+ },+ ])+ })++ it("is a no-op when entityId is empty", () => {+ populateLocalStoresFromVariables("", [+ {+ key: "token",+ initialValue: "init",+ currentValue: "cur",+ secret: true,+ },+ ])++ expect(secretService.getSecretEnvironment("")).toBeUndefined()+ })++ it("writes empty arrays to both stores when variables is empty (clears stale)", () => {+ // First populate with secrets + non-secrets+ populateLocalStoresFromVariables(ENTITY_ID, [+ { key: "s", initialValue: "v", currentValue: "v", secret: true },+ { key: "n", initialValue: "v", currentValue: "v", secret: false },+ ])++ // Re-populate with empty variables — should wipe both stores+ populateLocalStoresFromVariables(ENTITY_ID, [])++ expect(secretService.getSecretEnvironment(ENTITY_ID)).toEqual([])+ expect(currentValueService.getEnvironment(ENTITY_ID)).toEqual([])+ })++ it("writes empty array to CurrentValueService when all entries are secret", () => {+ populateLocalStoresFromVariables(ENTITY_ID, [+ {+ key: "a",+ initialValue: "a",+ currentValue: "a",+ secret: true,+ },+ ])++ expect(currentValueService.getEnvironment(ENTITY_ID)).toEqual([])+ })++ it("writes empty array to SecretEnvironmentService when no entries are secret", () => {+ populateLocalStoresFromVariables(ENTITY_ID, [+ {+ key: "a",+ initialValue: "a",+ currentValue: "a",+ secret: false,+ },+ ])++ expect(secretService.getSecretEnvironment(ENTITY_ID)).toEqual([])+ })++ it("re-populating with fewer secrets clears the previous secret entries", () => {+ populateLocalStoresFromVariables(ENTITY_ID, [+ { key: "old1", initialValue: "1", currentValue: "1", secret: true },+ { key: "old2", initialValue: "2", currentValue: "2", secret: true },+ ])++ populateLocalStoresFromVariables(ENTITY_ID, [+ { key: "new", initialValue: "3", currentValue: "3", secret: true },+ ])++ expect(secretService.getSecretEnvironment(ENTITY_ID)).toEqual([+ {+ key: "new",+ value: "3",+ initialValue: "3",+ varIndex: 0,+ },+ ])+ })+})++describe("populateLocalStoresFromCollectionTree", () => {+ let secretService: SecretEnvironmentService+ let currentValueService: CurrentValueService++ beforeEach(() => {+ secretService = getService(SecretEnvironmentService)+ currentValueService = getService(CurrentValueService)+ secretService.secretEnvironments.clear()+ currentValueService.environments.clear()+ })++ const buildCollection = (+ refId: string,+ variables: HoppCollection["variables"],+ folders: HoppCollection[] = []+ ): HoppCollection => ({+ v: 12,+ name: `coll-${refId}`,+ _ref_id: refId,+ folders,+ requests: [],+ auth: { authType: "inherit", authActive: true },+ headers: [],+ variables,+ description: null,+ preRequestScript: "",+ testScript: "",+ })++ it("populates the secret store for the root collection", () => {+ populateLocalStoresFromCollectionTree(+ buildCollection("root", [+ { key: "tok", initialValue: "init", currentValue: "cur", secret: true },+ ])+ )++ expect(secretService.getSecretEnvironment("root")).toEqual([+ {+ key: "tok",+ value: "cur",+ initialValue: "init",+ varIndex: 0,+ },+ ])+ })++ it("recurses into nested folders, populating each by its own _ref_id", () => {+ const child = buildCollection("child-1", [+ {+ key: "child-tok",+ initialValue: "ci",+ currentValue: "cc",+ secret: true,+ },+ ])+ const grandchild = buildCollection("gc-1", [+ { key: "gc-tok", initialValue: "gi", currentValue: "gc", secret: true },+ ])+ child.folders = [grandchild]++ populateLocalStoresFromCollectionTree(+ buildCollection(+ "root",+ [+ {+ key: "r-tok",+ initialValue: "ri",+ currentValue: "rc",+ secret: true,+ },+ ],+ [child]+ )+ )++ expect(secretService.getSecretEnvironment("root")).toBeDefined()+ expect(secretService.getSecretEnvironment("child-1")).toBeDefined()+ expect(secretService.getSecretEnvironment("gc-1")).toEqual([+ {+ key: "gc-tok",+ value: "gc",+ initialValue: "gi",+ varIndex: 0,+ },+ ])+ })++ it("skips a node that has no _ref_id but still recurses into its folders", () => {+ const child = buildCollection("child-1", [+ { key: "tok", initialValue: "i", currentValue: "c", secret: true },+ ])++ const root = buildCollection("placeholder", [], [child])+ delete (root as Partial<HoppCollection>)._ref_id++ populateLocalStoresFromCollectionTree(root)++ expect(secretService.getSecretEnvironment("child-1")).toBeDefined()+ expect(secretService.getSecretEnvironment("placeholder")).toBeUndefined()+ })++ it("promotes initialValue to value for foreign-import secrets (Postman/Insomnia)", () => {+ // `postman.ts` and `insomnia/insomniaColl.ts` set `currentValue: ""` while+ // putting the secret in `initialValue`. The collection-tree populate must+ // promote so the imported secret survives in the secret service.+ populateLocalStoresFromCollectionTree(+ buildCollection("postman-style", [+ {+ key: "api_key",+ initialValue: "pm-secret",+ currentValue: "",+ secret: true,+ },+ ])+ )++ expect(secretService.getSecretEnvironment("postman-style")).toEqual([+ {+ key: "api_key",+ value: "pm-secret",+ initialValue: "pm-secret",+ varIndex: 0,+ },+ ])+ })+})++describe("indexCollectionsByRefId + repopulateLoadedCollectionTree", () => {+ let secretService: SecretEnvironmentService+ let currentValueService: CurrentValueService++ beforeEach(() => {+ secretService = getService(SecretEnvironmentService)+ currentValueService = getService(CurrentValueService)+ secretService.secretEnvironments.clear()+ currentValueService.environments.clear()+ })++ const buildCollection = (+ refId: string,+ variables: HoppCollection["variables"],+ folders: HoppCollection[] = []+ ): HoppCollection => ({+ v: 12,+ name: `coll-${refId}`,+ _ref_id: refId,+ folders,+ requests: [],+ auth: { authType: "inherit", authActive: true },+ headers: [],+ variables,+ description: null,+ preRequestScript: "",+ testScript: "",+ })++ // The key invariant: if the backend reorders the loaded tree, the+ // repopulate logic must still pair each loaded node with its original+ // by `_ref_id` rather than by array index. Otherwise secrets would+ // re-key onto the wrong collection.+ it("re-keys secrets by ref-id when the loaded tree is reordered", () => {+ const originalA = buildCollection("ref-a", [+ { key: "a-tok", initialValue: "ai", currentValue: "ac", secret: true },+ ])+ const originalB = buildCollection("ref-b", [+ { key: "b-tok", initialValue: "bi", currentValue: "bc", secret: true },+ ])++ const originalsByRefId = new Map<string, HoppCollection>()+ indexCollectionsByRefId([originalA, originalB], originalsByRefId)++ // Backend round-trip: same ref-ids preserved via `data._ref_id`,+ // but order is reversed. Variables on the loaded tree are stripped+ // (initialValue: "" for secrets, currentValue: "" everywhere).+ const stripped = (refId: string, key: string) =>+ buildCollection(refId, [+ { key, initialValue: "", currentValue: "", secret: true },+ ])+ const loadedReordered = [+ stripped("ref-b", "b-tok"),+ stripped("ref-a", "a-tok"),+ ]++ loadedReordered.forEach((c) =>+ repopulateLoadedCollectionTree(c, originalsByRefId)+ )++ expect(secretService.getSecretEnvironment("ref-a")).toEqual([+ { key: "a-tok", value: "ac", initialValue: "ai", varIndex: 0 },+ ])+ expect(secretService.getSecretEnvironment("ref-b")).toEqual([+ { key: "b-tok", value: "bc", initialValue: "bi", varIndex: 0 },+ ])+ })++ it("indexes nested folders into the same flat map", () => {+ const grandchild = buildCollection("gc", [])+ const child = buildCollection("child", [], [grandchild])+ const root = buildCollection("root", [], [child])++ const map = new Map<string, HoppCollection>()+ indexCollectionsByRefId([root], map)++ expect([...map.keys()].sort()).toEqual(["child", "gc", "root"])+ expect(map.get("gc")).toBe(grandchild)+ })++ it("skips loaded nodes whose ref-id is absent from the original index", () => {+ const original = buildCollection("ref-a", [+ { key: "a-tok", initialValue: "ai", currentValue: "ac", secret: true },+ ])+ const map = new Map<string, HoppCollection>()+ indexCollectionsByRefId([original], map)++ // Backend dropped the ref-id round-trip on this node — the loaded+ // tree carries a fresh ref-id that the original index doesn't know.+ const orphanLoaded = buildCollection("ref-a-fresh", [+ { key: "a-tok", initialValue: "", currentValue: "", secret: true },+ ])++ repopulateLoadedCollectionTree(orphanLoaded, map)++ // Nothing was populated for the unknown ref-id, and the original's+ // ref-id is also untouched (no spurious cross-population).+ expect(secretService.getSecretEnvironment("ref-a-fresh")).toBeUndefined()+ expect(secretService.getSecretEnvironment("ref-a")).toBeUndefined()+ })++ it("recurses through nested folders and re-keys each by its own ref-id", () => {+ const childOriginal = buildCollection("child", [+ { key: "ck", initialValue: "ci", currentValue: "cc", secret: true },+ ])+ const rootOriginal = buildCollection(+ "root",+ [{ key: "rk", initialValue: "ri", currentValue: "rc", secret: true }],+ [childOriginal]+ )++ const map = new Map<string, HoppCollection>()+ indexCollectionsByRefId([rootOriginal], map)++ // Loaded tree from backend: same ref-ids, stripped variables.+ const childLoaded = buildCollection("child", [+ { key: "ck", initialValue: "", currentValue: "", secret: true },+ ])+ const rootLoaded = buildCollection(+ "root",+ [{ key: "rk", initialValue: "", currentValue: "", secret: true }],+ [childLoaded]+ )++ repopulateLoadedCollectionTree(rootLoaded, map)++ expect(secretService.getSecretEnvironment("root")).toEqual([+ { key: "rk", value: "rc", initialValue: "ri", varIndex: 0 },+ ])+ expect(secretService.getSecretEnvironment("child")).toEqual([+ { key: "ck", value: "cc", initialValue: "ci", varIndex: 0 },+ ])+ })++ it("promotes foreign-import secrets when re-seeding after backend round-trip", () => {+ // Selfhost-web personal-workspace flow: user imports a Postman collection,+ // backend round-trip succeeds, then `repopulateLoadedCollectionTree` re-seeds+ // local stores from the pre-strip original. The original still carries the+ // Postman convention (`currentValue: ""` + `initialValue: "X"` for secrets),+ // so the re-seed must promote — otherwise the round-trip would overwrite+ // the secret service entry that the earlier collection-tree populate set.+ const original = buildCollection("ref-pm", [+ {+ key: "api_key",+ initialValue: "pm-secret",+ currentValue: "",+ secret: true,+ },+ ])++ const map = new Map<string, HoppCollection>()+ indexCollectionsByRefId([original], map)++ const loaded = buildCollection("ref-pm", [+ { key: "api_key", initialValue: "", currentValue: "", secret: true },+ ])++ repopulateLoadedCollectionTree(loaded, map)++ expect(secretService.getSecretEnvironment("ref-pm")).toEqual([+ {+ key: "api_key",+ value: "pm-secret",+ initialValue: "pm-secret",+ varIndex: 0,+ },+ ])+ })+})++describe("flushUnmatchedRefIdsFromTree", () => {+ let secretService: SecretEnvironmentService+ let currentValueService: CurrentValueService++ beforeEach(() => {+ secretService = getService(SecretEnvironmentService)+ currentValueService = getService(CurrentValueService)+ secretService.secretEnvironments.clear()+ currentValueService.environments.clear()+ })++ const buildCollection = (+ refId: string,+ variables: HoppCollection["variables"],+ folders: HoppCollection[] = []+ ): HoppCollection => ({+ v: 12,+ name: `coll-${refId}`,+ _ref_id: refId,+ folders,+ requests: [],+ auth: { authType: "inherit", authActive: true },+ headers: [],+ variables,+ description: null,+ preRequestScript: "",+ testScript: "",+ })++ it("deletes entries whose `_ref_id` is not in the kept set", () => {+ secretService.addSecretEnvironment("ref-orphan", [+ { key: "k", value: "v", initialValue: "v", varIndex: 0 },+ ])+ currentValueService.addEnvironment("ref-orphan", [+ { key: "k", currentValue: "v", varIndex: 0, isSecret: false },+ ])++ flushUnmatchedRefIdsFromTree([buildCollection("ref-orphan", [])], new Set())++ expect(secretService.getSecretEnvironment("ref-orphan")).toBeUndefined()+ expect(currentValueService.getEnvironment("ref-orphan")).toBeUndefined()+ })++ it("keeps entries whose `_ref_id` is in the kept set", () => {+ secretService.addSecretEnvironment("ref-kept", [+ { key: "k", value: "v", initialValue: "v", varIndex: 0 },+ ])++ flushUnmatchedRefIdsFromTree(+ [buildCollection("ref-kept", [])],+ new Set(["ref-kept"])+ )++ expect(secretService.getSecretEnvironment("ref-kept")).toBeDefined()+ })++ it("recurses into folders, flushing each unmatched descendant", () => {+ secretService.addSecretEnvironment("ref-root", [+ { key: "k", value: "v", initialValue: "v", varIndex: 0 },+ ])+ secretService.addSecretEnvironment("ref-child", [+ { key: "k", value: "v", initialValue: "v", varIndex: 0 },+ ])+ secretService.addSecretEnvironment("ref-kept", [+ { key: "k", value: "v", initialValue: "v", varIndex: 0 },+ ])++ const child = buildCollection("ref-child", [])+ const root = buildCollection("ref-root", [], [child])+ const kept = buildCollection("ref-kept", [])++ flushUnmatchedRefIdsFromTree([root, kept], new Set(["ref-kept"]))++ expect(secretService.getSecretEnvironment("ref-root")).toBeUndefined()+ expect(secretService.getSecretEnvironment("ref-child")).toBeUndefined()+ expect(secretService.getSecretEnvironment("ref-kept")).toBeDefined()+ })+})++describe("flushLocalStoresForTeamCollectionTree", () => {+ let secretService: SecretEnvironmentService+ let currentValueService: CurrentValueService++ beforeEach(() => {+ secretService = getService(SecretEnvironmentService)+ currentValueService = getService(CurrentValueService)+ secretService.secretEnvironments.clear()+ currentValueService.environments.clear()+ })++ it("deletes the top-level entry by team backend `id`", () => {+ secretService.addSecretEnvironment("team-coll-1", [+ { key: "k", value: "v", initialValue: "v", varIndex: 0 },+ ])+ currentValueService.addEnvironment("team-coll-1", [+ { key: "k", currentValue: "v", varIndex: 0, isSecret: false },+ ])++ flushLocalStoresForTeamCollectionTree({+ id: "team-coll-1",+ children: null,+ })++ expect(secretService.getSecretEnvironment("team-coll-1")).toBeUndefined()+ expect(currentValueService.getEnvironment("team-coll-1")).toBeUndefined()+ })++ it("recurses into `children` and flushes every descendant", () => {+ secretService.addSecretEnvironment("root", [+ { key: "k", value: "v", initialValue: "v", varIndex: 0 },+ ])+ secretService.addSecretEnvironment("child-1", [+ { key: "k", value: "v", initialValue: "v", varIndex: 0 },+ ])+ secretService.addSecretEnvironment("grandchild", [+ { key: "k", value: "v", initialValue: "v", varIndex: 0 },+ ])++ flushLocalStoresForTeamCollectionTree({+ id: "root",+ children: [+ {+ id: "child-1",+ children: [{ id: "grandchild", children: null }],+ },+ ],+ })++ expect(secretService.getSecretEnvironment("root")).toBeUndefined()+ expect(secretService.getSecretEnvironment("child-1")).toBeUndefined()+ expect(secretService.getSecretEnvironment("grandchild")).toBeUndefined()+ })+})diff --git a/packages/hoppscotch-common/src/helpers/backend/helpers.ts b/packages/hoppscotch-common/src/helpers/backend/helpers.tsindex e75312c84..52e5fa40b 100644--- a/packages/hoppscotch-common/src/helpers/backend/helpers.ts+++ b/packages/hoppscotch-common/src/helpers/backend/helpers.ts@@ -18,6 +18,7 @@ import { getI18n } from "~/modules/i18n"import { TeamCollection } from "../teams/TeamCollection"import { TeamRequest } from "../teams/TeamRequest"import { GQLError, runGQLQuery } from "./GQLClient"+import { stripCollectionTreeForStore } from "~/helpers/secretVariables"import {ExportAsJsonDocument,ExportCollectionToJsonDocument,@@ -42,6 +43,12 @@ export type CollectionDataProps = {description: string | nullpreRequestScript: stringtestScript: string+ // Stable local-store key, round-tripped via `data._ref_id`. The wire+ // payload is opaque to the backend, which just echoes it back; the FE+ // uses it to pair populated secret-store entries to the backend `id`+ // (personal) or to migrate from `_ref_id` to backend `id` (team+ // collection import).+ _ref_id?: string}export const BACKEND_PAGE_SIZE = 10@@ -268,6 +275,8 @@ export const teamCollToHoppRESTColl = (headers: [],variables: [],description: null,+ preRequestScript: "",+ testScript: "",}const {@@ -318,7 +327,9 @@ export const getTeamCollectionJSON = async (teamID: string) => {return E.left(t("error.no_collections_to_export"))}- const hoppCollections = collections.map(teamCollectionJSONToHoppRESTColl)+ const hoppCollections = collections+ .map(teamCollectionJSONToHoppRESTColl)+ .map(stripCollectionTreeForStore)return E.right(JSON.stringify(hoppCollections, stripRefIdReplacer, 2))}@@ -373,5 +384,11 @@ export const getSingleTeamCollectionJSON = async (return E.left(errorMsg)}- return E.right(JSON.stringify(result.right, null, 2))+ return E.right(+ JSON.stringify(+ stripCollectionTreeForStore(result.right),+ stripRefIdReplacer,+ 2+ )+ )}diff --git a/packages/hoppscotch-common/src/helpers/collection/collection.ts b/packages/hoppscotch-common/src/helpers/collection/collection.tsindex f56c656ce..0bd7b7c7d 100644--- a/packages/hoppscotch-common/src/helpers/collection/collection.ts+++ b/packages/hoppscotch-common/src/helpers/collection/collection.ts@@ -8,6 +8,7 @@ import { RESTTabService } from "~/services/tab/rest"import { GQLTabService } from "~/services/tab/graphql"import { TeamCollectionsService } from "~/services/team-collection.service"import { cascadeParentCollectionForProperties } from "~/newstore/collections"+import { stripSecretVariableValuesForWire } from "../secretVariables"import { CollectionDataProps } from "../backend/helpers"import { CollectionFolder } from "../backend/queries/PublishedDocs"@@ -298,6 +299,7 @@ export function getFoldersByPath(/*** Transforms a collection to the format expected by team or personal collections.* BE expects CollectionFolder format with a data field containing auth, headers, variables, and description.+ ** @param collection The collection to transform* @returns The transformed collection*/@@ -309,7 +311,11 @@ export function transformCollectionForImport(const data: CollectionDataProps = {auth: collection.auth,headers: collection.headers,- variables: collection.variables,+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),+ // Round-trip the local-store key so the team-collection-added handler+ // (`TeamCollectionsService.addCollection`) can migrate the importer's+ // secret entries from this `_ref_id` to the backend-assigned `id`.+ _ref_id: collection._ref_id,description: collection.description,preRequestScript: collection.preRequestScript ?? "",testScript: collection.testScript ?? "",diff --git a/packages/hoppscotch-common/src/helpers/curl/__tests__/curlparser.spec.js b/packages/hoppscotch-common/src/helpers/curl/__tests__/curlparser.spec.jsindex 6b82956b7..a8ffa7455 100644--- a/packages/hoppscotch-common/src/helpers/curl/__tests__/curlparser.spec.js+++ b/packages/hoppscotch-common/src/helpers/curl/__tests__/curlparser.spec.js@@ -40,6 +40,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -151,6 +152,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -170,6 +172,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -196,6 +199,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -228,6 +232,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -260,6 +265,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -292,6 +298,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -324,6 +331,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -354,6 +362,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -387,6 +396,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -422,6 +432,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -493,6 +504,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -523,6 +535,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -588,6 +601,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -637,6 +651,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -688,6 +703,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -704,6 +720,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -730,6 +747,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -749,6 +767,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -775,6 +794,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -794,6 +814,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -820,6 +841,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -844,6 +866,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -866,6 +889,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -889,6 +913,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -911,6 +936,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -944,6 +970,7 @@ const samples = [testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -978,6 +1005,7 @@ data2: {"type":"test2","typeId":"123"}`,testScript: "",requestVariables: [],responses: {},+ description: null,}),},{@@ -1026,6 +1054,7 @@ data2: {"type":"test2","typeId":"123"}`,testScript: "",requestVariables: [],responses: {},+ description: null,}),},]diff --git a/packages/hoppscotch-common/src/helpers/curl/curlparser.ts b/packages/hoppscotch-common/src/helpers/curl/curlparser.tsindex d721c4db0..f3d06f472 100644--- a/packages/hoppscotch-common/src/helpers/curl/curlparser.ts+++ b/packages/hoppscotch-common/src/helpers/curl/curlparser.ts@@ -244,5 +244,6 @@ export const parseCurlCommand = (curlCommand: string) => {body: finalBody,requestVariables: defaultRESTReq.requestVariables,responses: {},+ description: defaultRESTReq.description,})}diff --git a/packages/hoppscotch-common/src/helpers/globalEnvShape.ts b/packages/hoppscotch-common/src/helpers/globalEnvShape.tsnew file mode 100644index 000000000..756eaba95--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/globalEnvShape.ts@@ -0,0 +1,44 @@+import {+ GLOBAL_ENV_LATEST_VERSION,+ type GlobalEnvironment,+} from "@hoppscotch/data"++/**+ * Coerce any value to a valid latest-version `GlobalEnvironment` wrapper.+ * Accepts the wrapper itself, a bare variables array (legacy/older+ * backends), or malformed input. Passes the wrapper through identity-+ * preserving when `v` already matches; schema migration is verzod's job+ * on the load path, not this dispatcher boundary.+ */+export const coerceGlobalEnvironment = (+ entries: unknown+): GlobalEnvironment => {+ if (Array.isArray(entries)) {+ return {+ v: GLOBAL_ENV_LATEST_VERSION,+ variables: entries,+ } as GlobalEnvironment+ }+ if (+ entries &&+ typeof entries === "object" &&+ "variables" in entries &&+ Array.isArray((entries as { variables: unknown }).variables)+ ) {+ const wrapper = entries as {+ v?: unknown+ variables: GlobalEnvironment["variables"]+ }+ if (wrapper.v === GLOBAL_ENV_LATEST_VERSION) {+ return wrapper as GlobalEnvironment+ }+ return {+ v: GLOBAL_ENV_LATEST_VERSION,+ variables: wrapper.variables,+ } as GlobalEnvironment+ }+ return {+ v: GLOBAL_ENV_LATEST_VERSION,+ variables: [],+ } as GlobalEnvironment+}diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/environment.ts b/packages/hoppscotch-common/src/helpers/import-export/export/environment.tsindex ffbcd05b4..cb28e344e 100644--- a/packages/hoppscotch-common/src/helpers/import-export/export/environment.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/export/environment.ts@@ -3,6 +3,7 @@ import * as E from "fp-ts/Either"import { cloneDeep } from "lodash-es"import { TeamEnvironment } from "~/helpers/teams/TeamEnvironment"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"import { initializeDownloadFile } from "."const getEnvironmentJSON = (@@ -27,7 +28,9 @@ const getEnvironmentJSON = (: undefined}-// Apply necessary transformations prior to environment exports+// Apply necessary transformations prior to environment exports.+// Strips `initialValue` for `secret: true` variables AND clears+// `currentValue` for all variables.export const transformEnvironmentVariables = ({id,v,@@ -38,18 +41,7 @@ export const transformEnvironmentVariables = ({id,v,name,- variables: variables.map((variable) => {- const { key, secret, initialValue } = variable-- // Eliminate `currentValue` field for secret environment variables and currentValue-- return {- key,- secret,- initialValue,- currentValue: variable.secret ? "" : (variable.currentValue ?? ""),- }- }),+ variables: stripSecretVariableValuesForWire(variables),}}diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/environments.ts b/packages/hoppscotch-common/src/helpers/import-export/export/environments.tsindex c8554b625..ac77877be 100644--- a/packages/hoppscotch-common/src/helpers/import-export/export/environments.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/export/environments.ts@@ -1,5 +1,10 @@import { Environment } from "@hoppscotch/data"+import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"export const environmentsExporter = (myEnvironments: Environment[]) => {- return JSON.stringify(myEnvironments, null, 2)+ const stripped = myEnvironments.map((env) => ({+ ...env,+ variables: stripSecretVariableValuesForWire(env.variables),+ }))+ return JSON.stringify(stripped, null, 2)}diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/gqlCollections.ts b/packages/hoppscotch-common/src/helpers/import-export/export/gqlCollections.tsindex 6a15cc054..0d24b316e 100644--- a/packages/hoppscotch-common/src/helpers/import-export/export/gqlCollections.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/export/gqlCollections.ts@@ -1,6 +1,8 @@import { HoppCollection } from "@hoppscotch/data"import { stripRefIdReplacer } from "."+import { stripCollectionTreeForStore } from "~/helpers/secretVariables"export const gqlCollectionsExporter = (gqlCollections: HoppCollection[]) => {- return JSON.stringify(gqlCollections, stripRefIdReplacer, 2)+ const stripped = gqlCollections.map(stripCollectionTreeForStore)+ return JSON.stringify(stripped, stripRefIdReplacer, 2)}diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/myCollections.ts b/packages/hoppscotch-common/src/helpers/import-export/export/myCollections.tsindex cea76e226..d0f576c09 100644--- a/packages/hoppscotch-common/src/helpers/import-export/export/myCollections.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/export/myCollections.ts@@ -1,6 +1,8 @@import { HoppCollection } from "@hoppscotch/data"import { stripRefIdReplacer } from "."+import { stripCollectionTreeForStore } from "~/helpers/secretVariables"export const myCollectionsExporter = (myCollections: HoppCollection[]) => {- return JSON.stringify(myCollections, stripRefIdReplacer, 2)+ const stripped = myCollections.map(stripCollectionTreeForStore)+ return JSON.stringify(stripped, stripRefIdReplacer, 2)}diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/__tests__/postmanEnv.spec.ts b/packages/hoppscotch-common/src/helpers/import-export/import/__tests__/postmanEnv.spec.tsnew file mode 100644index 000000000..788772ab2--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/import-export/import/__tests__/postmanEnv.spec.ts@@ -0,0 +1,104 @@+import * as E from "fp-ts/Either"+import { describe, expect, it } from "vitest"++import { postmanEnvImporter } from "../postmanEnv"++const runImport = async (envs: object[]) => {+ const result = await postmanEnvImporter([JSON.stringify(envs)])()+ if (E.isLeft(result)) throw new Error(`importer failed: ${result.left}`)+ return result.right+}++describe("postmanEnvImporter — secret flag handling", () => {+ it('recognizes the legacy `type: "secret"` shape (older Postman exports)', async () => {+ const [env] = await runImport([+ {+ name: "Legacy",+ values: [+ {+ key: "API_KEY",+ value: "old-secret-value",+ type: "secret",+ enabled: true,+ },+ {+ key: "URL",+ value: "https://example.com",+ type: "default",+ enabled: true,+ },+ ],+ },+ ])++ expect(env.variables).toEqual([+ expect.objectContaining({ key: "API_KEY", secret: true }),+ expect.objectContaining({ key: "URL", secret: false }),+ ])+ })++ it('recognizes the Postman 12+ `secret: true` boolean (with `type: "default"`)', async () => {+ const [env] = await runImport([+ {+ name: "PET_STORE",+ values: [+ {+ key: "baseUrl-secret",+ value: "",+ type: "default",+ enabled: true,+ secret: true,+ },+ {+ key: "baseUrl-not-secret",+ value: "baseUrl-not-secret",+ type: "default",+ enabled: true,+ },+ ],+ },+ ])++ expect(env.variables).toEqual([+ expect.objectContaining({ key: "baseUrl-secret", secret: true }),+ expect.objectContaining({ key: "baseUrl-not-secret", secret: false }),+ ])+ })++ it("treats a variable as secret when EITHER signal is present", async () => {+ const [env] = await runImport([+ {+ name: "Mixed",+ values: [+ // Both signals — still secret+ {+ key: "BOTH",+ value: "x",+ type: "secret",+ secret: true,+ enabled: true,+ },+ // Only legacy+ { key: "LEGACY", value: "x", type: "secret", enabled: true },+ // Only new+ {+ key: "NEW",+ value: "x",+ type: "default",+ secret: true,+ enabled: true,+ },+ // Neither — not secret+ { key: "PLAIN", value: "x", type: "default", enabled: true },+ ],+ },+ ])++ expect(env.variables.map((v) => [v.key, v.secret])).toEqual([+ ["BOTH", true],+ ["LEGACY", true],+ ["NEW", true],+ ["PLAIN", false],+ ])+ })+})diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/postman.ts b/packages/hoppscotch-common/src/helpers/import-export/import/postman.tsindex 0245eae42..8f3f2c585 100644--- a/packages/hoppscotch-common/src/helpers/import-export/import/postman.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/import/postman.ts@@ -121,11 +121,17 @@ const getHoppCollVariables = (variable.key.length > 0),A.map((variable) => {+ // Postman 12+ uses `secret: true`; older exports use `type: "secret"`.+ // The SDK's types don't surface the new flag, so read it off raw.+ const isSecret =+ variable.type === "secret" ||+ (variable as { secret?: boolean }).secret === true+return <HoppCollectionVariable>{key: replacePMVarTemplating(variable.key ?? ""),initialValue: replacePMVarTemplating(variable.value ?? ""),currentValue: "",- secret: variable.type === "secret",+ secret: isSecret,}}))diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/postmanEnv.ts b/packages/hoppscotch-common/src/helpers/import-export/import/postmanEnv.tsindex 5c004e009..76c85a59a 100644--- a/packages/hoppscotch-common/src/helpers/import-export/import/postmanEnv.ts+++ b/packages/hoppscotch-common/src/helpers/import-export/import/postmanEnv.ts@@ -15,6 +15,8 @@ const postmanEnvSchema = z.object({key: z.string(),value: z.string(),type: z.string(),+ // Postman 12+ uses `secret: true`; older exports use `type: "secret"`.+ secret: z.boolean().optional(),})),})@@ -49,17 +51,17 @@ export const postmanEnvImporter = (contents: string[]) => {return TE.left(IMPORTER_INVALID_FILE_FORMAT)}- // Convert `values` to `variables` to match the format expected by the system+ // Treat as secret on legacy `type: "secret"` OR Postman 12+ `secret: true`.const environments: Environment[] = validationResult.data.map(({ name, values }) => ({id: uniqueID(),v: EnvironmentSchemaVersion,name,- variables: values.map(({ key, value, type }) => ({+ variables: values.map(({ key, value, type, secret }) => ({key,initialValue: replacePMVarTemplating(value),currentValue: replacePMVarTemplating(value),- secret: type === "secret",+ secret: type === "secret" || secret === true,})),}))diff --git a/packages/hoppscotch-common/src/helpers/mockServer/exampleCollection.ts b/packages/hoppscotch-common/src/helpers/mockServer/exampleCollection.tsindex a69aeef03..c1341ad1e 100644--- a/packages/hoppscotch-common/src/helpers/mockServer/exampleCollection.ts+++ b/packages/hoppscotch-common/src/helpers/mockServer/exampleCollection.ts@@ -88,6 +88,7 @@ export function createExamplePetStoreCollection(],},},+ description: null,}),// GET - Get a single pet by ID@@ -137,6 +138,7 @@ export function createExamplePetStoreCollection(],},},+ description: null,}),// POST - Create a new pet@@ -213,6 +215,7 @@ export function createExamplePetStoreCollection(],},},+ description: null,}),// PUT - Update an existing pet@@ -283,6 +286,7 @@ export function createExamplePetStoreCollection(],},},+ description: null,}),// DELETE - Delete a pet@@ -311,6 +315,7 @@ export function createExamplePetStoreCollection(headers: [],},},+ description: null,}),]diff --git a/packages/hoppscotch-common/src/helpers/mockServer/exampleMockCollection.ts b/packages/hoppscotch-common/src/helpers/mockServer/exampleMockCollection.tsindex a4f85bae1..6d0e4f9b9 100644--- a/packages/hoppscotch-common/src/helpers/mockServer/exampleMockCollection.ts+++ b/packages/hoppscotch-common/src/helpers/mockServer/exampleMockCollection.ts@@ -4,6 +4,7 @@ import * as E from "fp-ts/Either"import {HoppRESTRequest,RESTReqSchemaVersion,+ generateUniqueRefId,makeCollection,} from "@hoppscotch/data"import { createNewRootCollection } from "~/helpers/backend/mutations/TeamCollection"@@ -72,6 +73,7 @@ export function getExampleMockRequests(): HoppRESTRequest[] {auth: oauthAuth,requestVariables: [],responses: {},+ description: "",},// updatePet request{@@ -90,6 +92,7 @@ export function getExampleMockRequests(): HoppRESTRequest[] {auth: oauthAuth,requestVariables: [],responses: {},+ description: "",},// findByStatus request{@@ -115,6 +118,7 @@ export function getExampleMockRequests(): HoppRESTRequest[] {auth: oauthAuth,requestVariables: [],responses: {},+ description: "",},// getPetById request{@@ -139,6 +143,7 @@ export function getExampleMockRequests(): HoppRESTRequest[] {},requestVariables: [],responses: {},+ description: "",},// updatePetWithForm request{@@ -157,6 +162,7 @@ export function getExampleMockRequests(): HoppRESTRequest[] {auth: oauthAuth,requestVariables: [],responses: {},+ description: "",},// deletePet request{@@ -182,6 +188,7 @@ export function getExampleMockRequests(): HoppRESTRequest[] {auth: oauthAuth,requestVariables: [],responses: {},+ description: "",},]@@ -249,7 +256,6 @@ export async function createMockCollectionForTeam(export async function createMockCollectionForPersonal(collectionName: string): Promise<E.Either<string, { id: string; name: string }>> {- // Prepare collection dataconst data = {auth: {authType: "inherit" as const,@@ -257,6 +263,10 @@ export async function createMockCollectionForPersonal(},headers: [],variables: [],+ _ref_id: generateUniqueRefId("coll"),+ description: null,+ preRequestScript: "",+ testScript: "",}// Create the root collection using GraphQL mutationdiff --git a/packages/hoppscotch-common/src/helpers/rest/default.ts b/packages/hoppscotch-common/src/helpers/rest/default.tsindex bca3b59cc..d420f13bb 100644--- a/packages/hoppscotch-common/src/helpers/rest/default.ts+++ b/packages/hoppscotch-common/src/helpers/rest/default.ts@@ -19,4 +19,5 @@ export const getDefaultRESTRequest = (): HoppRESTRequest => ({},requestVariables: [],responses: {},+ description: null,})diff --git a/packages/hoppscotch-common/src/helpers/secretVariables.ts b/packages/hoppscotch-common/src/helpers/secretVariables.tsnew file mode 100644index 000000000..38f335190--- /dev/null+++ b/packages/hoppscotch-common/src/helpers/secretVariables.ts@@ -0,0 +1,266 @@+import { generateUniqueRefId, type HoppCollection } from "@hoppscotch/data"++import { getService } from "../modules/dioc"+import { CurrentValueService } from "../services/current-environment-value.service"+import { SecretEnvironmentService } from "../services/secret-environment.service"++/** Shape shared by collection and environment variables. */+type SecretCapableVariable = {+ key: string+ initialValue: string+ currentValue: string+ secret: boolean+}++/**+ * Clear `initialValue` for secrets and `currentValue` for all variables+ * before the wire write. Raw values live only in the local secret store.+ */+export const stripSecretVariableValuesForWire = <+ T extends SecretCapableVariable,+>(+ variables: T[]+): T[] =>+ variables.map((v) => ({+ ...v,+ initialValue: v.secret ? "" : v.initialValue,+ currentValue: "",+ }))++/**+ * Seed the local secret + currentValue stores from raw variables.+ *+ * IMPORTANT: pass RAW (pre-strip) inputs. A stripped variable has empty+ * `initialValue` / `currentValue` and will persist as blank.+ *+ * ─── `??` vs `||` — read before "fixing" this ───+ * Both branches below use `??` so an explicit `""` is preserved. This is+ * the correct semantic for the REHYDRATION path (`""` means "user+ * deliberately cleared" — must not be resurrected from `initialValue`).+ *+ * For the IMPORT path, `""` means "stripped on wire" and the real value+ * lives in `initialValue`. That gap is bridged at the import-site+ * boundary by `promoteInitialValueForImport` (called from+ * `populateLocalStoresFromCollectionTree`, `repopulateLoadedCollectionTree`,+ * and the env-import callers in `environments/ImportExport.vue`).+ *+ * Do not switch these to `||` — that re-introduces the rehydration+ * regression for both secrets and non-secrets. If a new import path+ * silently stores blanks, the fix is to route it through+ * `promoteInitialValueForImport` upstream, not to change this function.+ */+export const populateLocalStoresFromVariables = (+ entityId: string,+ variables: readonly SecretCapableVariable[]+) => {+ if (!entityId) return++ const secretEnvironmentService = getService(SecretEnvironmentService)+ const currentEnvironmentValueService = getService(CurrentValueService)++ const secrets = variables.flatMap((v, index) =>+ v.secret+ ? [+ {+ key: v.key,+ value: v.currentValue ?? v.initialValue ?? "",+ initialValue: v.initialValue ?? "",+ varIndex: index,+ },+ ]+ : []+ )++ const nonSecrets = variables.flatMap((v, index) =>+ !v.secret+ ? [+ {+ key: v.key,+ currentValue: v.currentValue ?? v.initialValue ?? "",+ varIndex: index,+ isSecret: false as const,+ },+ ]+ : []+ )++ secretEnvironmentService.addSecretEnvironment(entityId, secrets)+ currentEnvironmentValueService.addEnvironment(entityId, nonSecrets)+}++/**+ * Foreign-import convention normalizer for BOTH secret and non-secret+ * variables. The wire strip blanks `currentValue` for everything and (for+ * secrets) `initialValue`; non-secret `initialValue` is preserved. So a+ * Hoppscotch / Postman / Insomnia exported file lands with+ * `currentValue: ""` and (for non-secrets) `initialValue: "value"`. Promote+ * so the local stores see the imported value.+ *+ * The global-env rehydration path bypasses this step intentionally — there+ * `""` means "user deliberately cleared," not "value lives in initialValue."+ * Idempotent — promoted entries are unchanged on a second pass.+ */+export const promoteInitialValueForImport = (+ variables: readonly SecretCapableVariable[]+): SecretCapableVariable[] =>+ variables.map((v) =>+ !v.currentValue && v.initialValue+ ? { ...v, currentValue: v.initialValue }+ : v+ )++export const populateLocalStoresFromCollectionTree = (+ collection: HoppCollection+) => {+ if (collection._ref_id) {+ populateLocalStoresFromVariables(+ collection._ref_id,+ promoteInitialValueForImport(collection.variables ?? [])+ )+ } else {+ // All current callers of THIS function run `ensureRefIds` upstream+ // so this should be unreachable; the warn exists so a future caller+ // that skips it is debuggable instead of silently dropping secrets.+ // Scope note: the equivalent "missing ref-id" case on the+ // backstop-repopulate path is NOT covered here —+ // `repopulateLoadedCollectionTree` calls `populateLocalStoresFromVariables`+ // directly and bypasses this branch. That gap is covered by the+ // `unpairedCount` warning in+ // `selfhost-web/.../web/import.ts:importToPersonalWorkspace`.+ console.warn(+ "[populateLocalStoresFromCollectionTree] collection has no `_ref_id`; secret values will not be persisted locally",+ collection.name+ )+ }+ ;(collection.folders ?? []).forEach(populateLocalStoresFromCollectionTree)+}++/** Fresh node objects + `folders` arrays; other fields alias the input. */+export const ensureRefIds = (collection: HoppCollection): HoppCollection => ({+ ...collection,+ _ref_id: collection._ref_id ?? generateUniqueRefId("coll"),+ folders: (collection.folders ?? []).map(ensureRefIds),+})++/** Reallocates `variables` and `folders`; other fields alias the input. */+export const stripCollectionTreeForStore = (+ collection: HoppCollection+): HoppCollection => ({+ ...collection,+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),+ folders: (collection.folders ?? []).map(stripCollectionTreeForStore),+})++/** Flat `_ref_id → collection` index across a tree. Mutates `out`. */+export const indexCollectionsByRefId = (+ collections: HoppCollection[],+ out: Map<string, HoppCollection>+) => {+ collections.forEach((c) => {+ if (c._ref_id) out.set(c._ref_id, c)+ if (c.folders?.length) indexCollectionsByRefId(c.folders, out)+ })+}++/**+ * Re-seed local stores after bulk-import using `_ref_id` (round-tripped+ * via `data._ref_id`) instead of array index — backend may reorder.+ * Assumes the backend preserves `data._ref_id` at EVERY level (root ++ * nested folders); unpaired nodes fall through to `flushUnmatchedRefIdsFromTree`.+ */+export const repopulateLoadedCollectionTree = (+ loaded: HoppCollection,+ originalsByRefId: Map<string, HoppCollection>+) => {+ if (loaded._ref_id) {+ const original = originalsByRefId.get(loaded._ref_id)+ if (original) {+ // Same promote as `populateLocalStoresFromCollectionTree` — `original`+ // is the pre-strip input tree, which for Postman/Insomnia imports+ // still carries the secret in `initialValue` with `currentValue: ""`.+ populateLocalStoresFromVariables(+ loaded._ref_id,+ promoteInitialValueForImport(original.variables ?? [])+ )+ }+ }+ ;(loaded.folders ?? []).forEach((loadedFolder) => {+ repopulateLoadedCollectionTree(loadedFolder, originalsByRefId)+ })+}++/**+ * Flush every node's local-store entries on delete. Flushes by both+ * `_ref_id` (personal) and `id` (team); services no-op on missing keys.+ */+export const flushLocalStoresForCollectionTree = (+ collection: HoppCollection+) => {+ const secretEnvironmentService = getService(SecretEnvironmentService)+ const currentEnvironmentValueService = getService(CurrentValueService)++ const walk = (node: HoppCollection) => {+ if (node._ref_id) {+ secretEnvironmentService.deleteSecretEnvironment(node._ref_id)+ currentEnvironmentValueService.deleteEnvironment(node._ref_id)+ }+ if (node.id) {+ secretEnvironmentService.deleteSecretEnvironment(node.id)+ currentEnvironmentValueService.deleteEnvironment(node.id)+ }+ ;(node.folders ?? []).forEach(walk)+ }+ walk(collection)+}++/**+ * Flush local-store entries keyed by `_ref_id`s in `tree` that aren't+ * present in `keptRefIds`. Used after `repopulateLoadedCollectionTree`+ * to clean up orphans on old SH backends that drop the `data._ref_id`+ * round-trip — upstream populate seeded entries under originals' refIds+ * that the loaded tree (with fresh UUIDs) can't reach.+ */+export const flushUnmatchedRefIdsFromTree = (+ tree: HoppCollection[],+ keptRefIds: ReadonlySet<string>+) => {+ const secretEnvironmentService = getService(SecretEnvironmentService)+ const currentEnvironmentValueService = getService(CurrentValueService)++ const walk = (nodes: HoppCollection[]) => {+ nodes.forEach((node) => {+ if (node._ref_id && !keptRefIds.has(node._ref_id)) {+ secretEnvironmentService.deleteSecretEnvironment(node._ref_id)+ currentEnvironmentValueService.deleteEnvironment(node._ref_id)+ }+ walk(node.folders ?? [])+ })+ }+ walk(tree)+}++/**+ * Recursive flush for a team-collection subtree. Walks `children` (not+ * `folders` — different shape from `HoppCollection`) and deletes each+ * descendant's secret/current entries by backend `id`. Without this,+ * deleting a team collection leaves nested folders' secrets orphaned in+ * the secret service.+ */+type TeamCollectionNode = {+ id: string+ children: TeamCollectionNode[] | null | undefined+}++export const flushLocalStoresForTeamCollectionTree = (+ collection: TeamCollectionNode+) => {+ const secretEnvironmentService = getService(SecretEnvironmentService)+ const currentEnvironmentValueService = getService(CurrentValueService)++ const walk = (node: TeamCollectionNode) => {+ secretEnvironmentService.deleteSecretEnvironment(node.id)+ currentEnvironmentValueService.deleteEnvironment(node.id)+ ;(node.children ?? []).forEach(walk)+ }+ walk(collection)+}diff --git a/packages/hoppscotch-common/src/newstore/collections.ts b/packages/hoppscotch-common/src/newstore/collections.tsindex 1db29f39d..ee8212801 100644--- a/packages/hoppscotch-common/src/newstore/collections.ts+++ b/packages/hoppscotch-common/src/newstore/collections.ts@@ -695,7 +695,7 @@ const restCollectionDispatchers = defineDispatchers({_ref_id: generateUniqueRefId("coll"),}- newCollection.folders = newCollection.folders.map((folder) =>+ newCollection.folders = (newCollection.folders ?? []).map((folder) =>recursiveChangeRefIdToAvoidConflicts(folder))@@ -1155,13 +1155,30 @@ const gqlCollectionDispatchers = defineDispatchers({if (collection) {const name = `${collection.name} - ${t("action.duplicate")}`- const duplicatedCollection = {+ // Re-stamp `_ref_id` recursively so the duplicate doesn't alias the+ // original's local secret-store entries — sharing a `_ref_id` would+ // mean editing secrets on the duplicate mutates the source. Mirrors+ // the REST `duplicateCollection` dispatcher above.+ function recursiveChangeRefIdToAvoidConflicts(+ coll: HoppCollection+ ): HoppCollection {+ const next = {+ ...coll,+ _ref_id: generateUniqueRefId("coll"),+ }+ next.folders = (next.folders ?? []).map(+ recursiveChangeRefIdToAvoidConflicts+ )+ return next+ }++ const duplicatedCollection = recursiveChangeRefIdToAvoidConflicts({...cloneDeep(collection),name,...(collection.id? { id: `${collection.id}-duplicate-collection` }: {}),- }+ })if (isRootCollection) {newState.push(duplicatedCollection)diff --git a/packages/hoppscotch-common/src/newstore/environments.ts b/packages/hoppscotch-common/src/newstore/environments.tsindex de313c896..501272e57 100644--- a/packages/hoppscotch-common/src/newstore/environments.ts+++ b/packages/hoppscotch-common/src/newstore/environments.ts@@ -14,6 +14,7 @@ import DispatchingStore, {} from "~/newstore/DispatchingStore"import { CurrentValueService } from "~/services/current-environment-value.service"import { SecretEnvironmentService } from "~/services/secret-environment.service"+import { coerceGlobalEnvironment } from "~/helpers/globalEnvShape"export type SelectedEnvironmentIndex =| { type: "NO_ENV_SELECTED" }@@ -309,8 +310,10 @@ const dispatchers = defineDispatchers({}},setGlobalVariables(_, { entries }: { entries: GlobalEnvironment }) {+ // Coerce at the wire-into-store boundary — TS dispatchers are erased+ // at runtime; a malformed value would corrupt `state.globals`.return {- globals: entries,+ globals: coerceGlobalEnvironment(entries),}},// eslint-disable-next-line @typescript-eslint/no-unused-vars@@ -469,8 +472,7 @@ export const aggregateEnvs$: Observable<AggregateEnvironment[]> = combineLatest(})}})-- globalEnv.variables.forEach((variable) => {+ ;(globalEnv?.variables ?? []).forEach((variable) => {const { key, secret } = variableconst currentValue ="currentValue" in variable ? variable.currentValue : ""@@ -578,7 +580,9 @@ export function getAggregateEnvsWithCurrentValue() {currentEnv.id,index) ?? currentValue,- initialValue: x.initialValue ?? initialValue,+ // Use the local resolved value — `x.initialValue ?? initialValue`+ // would pin `""` for stripped secrets and skip the store hydration.+ initialValue,secret: x.secret,sourceEnv: currentEnv.name,}@@ -606,7 +610,7 @@ export function getAggregateEnvsWithCurrentValue() {"Global",index) ?? currentValue,- initialValue: x.initialValue ?? initialValue,+ initialValue,secret: x.secret,sourceEnv: "Global",}@@ -635,7 +639,7 @@ export const aggregateEnvsWithCurrentValue$: Observable<})})- selectedEnv?.variables.map((x, index) => {+ selectedEnv?.variables.forEach((x, index) => {let currentValue = x.currentValuelet initialValue = x.initialValueif (x.secret) {@@ -658,13 +662,13 @@ export const aggregateEnvsWithCurrentValue$: Observable<selectedEnv.id,index) ?? currentValue,- initialValue: x.initialValue ?? initialValue,+ // Use the local resolved value — see note on `aggregateEnvs$`.+ initialValue,secret: x.secret,sourceEnv: selectedEnv.name,})})-- globalEnv.variables.map((x, index) => {+ ;(globalEnv?.variables ?? []).forEach((x, index) => {let currentValue = x.currentValuelet initialValue = x.initialValueif (x.secret) {@@ -687,7 +691,7 @@ export const aggregateEnvsWithCurrentValue$: Observable<"Global",index) ?? currentValue,- initialValue: x.initialValue ?? initialValue,+ initialValue,secret: x.secret,sourceEnv: "Global",})@@ -749,7 +753,11 @@ export function getLegacyGlobalEnvironment(): Environment | null {}export function getGlobalVariables(): GlobalEnvironmentVariable[] {- return environmentsStore.value.globals.variables.map(+ // Defensive `?? []` — the dispatcher normalizes `state.globals` to a+ // valid wrapper, but if state somehow ended up corrupt (e.g. before+ // a normalization fix shipped), we'd rather return an empty list than+ // crash every consumer of this function.+ return (environmentsStore.value.globals?.variables ?? []).map((env: GlobalEnvironmentVariable) => {if (env.key && "currentValue" in env && !("secret" in env)) {return {diff --git a/packages/hoppscotch-common/src/pages/import.vue b/packages/hoppscotch-common/src/pages/import.vueindex 3ce0fd3e2..f51b7f237 100644--- a/packages/hoppscotch-common/src/pages/import.vue+++ b/packages/hoppscotch-common/src/pages/import.vue@@ -14,6 +14,11 @@ import * as E from "fp-ts/Either"import { pipe } from "fp-ts/function"import { HoppCollection } from "@hoppscotch/data"import { appendRESTCollections } from "~/newstore/collections"+import {+ ensureRefIds,+ populateLocalStoresFromCollectionTree,+ stripCollectionTreeForStore,+} from "~/helpers/secretVariables"import { useI18n } from "@composables/i18n"import { useToast } from "@composables/toast"import { IMPORTER_INVALID_FILE_FORMAT } from "~/helpers/import-export/import"@@ -111,7 +116,14 @@ const handleImportFailure = (error: ImportCollectionsError) => {}const handleImportSuccess = (collections: HoppCollection[]) => {- appendRESTCollections(collections)+ // Mirror the modal-import path: stamp `_ref_id`s, persist any raw+ // secret values to the local secret store, then append the stripped+ // tree to newstore so localStorage / future syncs stay clean.+ const withRefIds = collections.map(ensureRefIds)++ withRefIds.forEach(populateLocalStoresFromCollectionTree)+ appendRESTCollections(withRefIds.map(stripCollectionTreeForStore))+toast.success(t("import.import_from_url_success").toString())}diff --git a/packages/hoppscotch-common/src/services/current-environment-value.service.ts b/packages/hoppscotch-common/src/services/current-environment-value.service.tsindex 566802689..4edaa97fb 100644--- a/packages/hoppscotch-common/src/services/current-environment-value.service.ts+++ b/packages/hoppscotch-common/src/services/current-environment-value.service.ts@@ -124,14 +124,17 @@ export class CurrentValueService extends Service {}/**- * Used to update the ID of a environment.- * Used while syncing with the server.- * @param oldID old ID of the environment- * @param newID new ID of the environment+ * Migrate entries from `oldID` to `newID`. Skips the `set` when nothing+ * exists under `oldID` so a no-op migrate doesn't clobber `newID`.*/public updateEnvironmentID(oldID: string, newID: string) {+ // No-op when keys match — otherwise the get→set→delete sequence would+ // erase the just-written entry.+ if (oldID === newID) returnconst vars = this.getEnvironment(oldID)- this.environments.set(newID, vars || [])+ if (vars !== undefined) {+ this.environments.set(newID, vars)+ }this.environments.delete(oldID)}diff --git a/packages/hoppscotch-common/src/services/secret-environment.service.ts b/packages/hoppscotch-common/src/services/secret-environment.service.tsindex e4f2313e1..ae5a1365a 100644--- a/packages/hoppscotch-common/src/services/secret-environment.service.ts+++ b/packages/hoppscotch-common/src/services/secret-environment.service.ts@@ -115,14 +115,17 @@ export class SecretEnvironmentService extends Service {}/**- * Used to update the ID of a secret environment.- * Used while syncing with the server.- * @param oldID old ID of the environment- * @param newID new ID of the environment+ * Migrate entries from `oldID` to `newID`. Skips the `set` when nothing+ * exists under `oldID` so a no-op migrate doesn't clobber `newID`.*/public updateSecretEnvironmentID(oldID: string, newID: string) {+ // No-op when keys match — without this guard the get→set→delete+ // sequence would erase the just-written entry for `oldID === newID`.+ if (oldID === newID) returnconst secretVars = this.getSecretEnvironment(oldID)- this.secretEnvironments.set(newID, secretVars || [])+ if (secretVars !== undefined) {+ this.secretEnvironments.set(newID, secretVars)+ }this.secretEnvironments.delete(oldID)}diff --git a/packages/hoppscotch-common/src/services/team-collection.service.ts b/packages/hoppscotch-common/src/services/team-collection.service.tsindex d4d0833fe..a10852454 100644--- a/packages/hoppscotch-common/src/services/team-collection.service.ts+++ b/packages/hoppscotch-common/src/services/team-collection.service.ts@@ -173,6 +173,16 @@ export class TeamCollectionsService extends Service<void> {this.collectionLoadingWatcher()}+ /**+ * Look up a `TeamCollection` subtree by backend `id` in the current tree.+ * Useful before a delete mutation so callers can capture the subtree for+ * recursive cleanup (e.g. flushing nested secret-store entries) without+ * racing the delete subscription.+ */+ public findCollectionByID(id: string): TeamCollection | null {+ return findCollInTree(this.collections.value, id)+ }+/*** Watches for loading collections and updates inherited properties once loading is done*/@@ -288,12 +298,42 @@ export class TeamCollectionsService extends Service<void> {}}+ // Migrate device-local secret entries seeded by `importToTeamsWorkspace`+ // under the importer-stamped `_ref_id` to the backend-assigned `id`.+ // No-op on devices that didn't seed (migration helpers skip when+ // nothing exists under the old key).+ this.migrateImportedSecretEntries(collection)+// Add to entity ids setthis.entityIDs.add(`collection-${collection.id}`)this.collections.value = [...tree]}+ // Relies on the backend preserving `data._ref_id` at every level —+ // each nested folder's `teamCollectionAdded` event must carry its own+ // `data._ref_id` for migration to fire. A backend that drops nested+ // `data` would leave per-folder entries orphaned under `_ref_id`.+ private migrateImportedSecretEntries(collection: TeamCollection) {+ if (!collection.data) return+ try {+ const parsed = JSON.parse(collection.data) as { _ref_id?: unknown }+ if (typeof parsed._ref_id !== "string" || !parsed._ref_id) return+ this.secretEnvironmentService.updateSecretEnvironmentID(+ parsed._ref_id,+ collection.id+ )+ this.currentEnvironmentValueService.updateEnvironmentID(+ parsed._ref_id,+ collection.id+ )+ } catch {+ // Malformed `data` — skip migration; the secret service stays+ // keyed by `_ref_id` and the imported secrets aren't accessible+ // via the team `id`. Rare; only happens on a malformed backend.+ }+ }+/*** Loads the root collections of the current team* @param replace Whether to replace the existing collections or append to themdiff --git a/packages/hoppscotch-data/src/global-environment/index.ts b/packages/hoppscotch-data/src/global-environment/index.tsindex 3b78a5c73..d6817a3b7 100644--- a/packages/hoppscotch-data/src/global-environment/index.ts+++ b/packages/hoppscotch-data/src/global-environment/index.ts@@ -10,8 +10,10 @@ const versionedObject = z.object({v: z.number(),})+export const GLOBAL_ENV_LATEST_VERSION = 2 as const+export const GlobalEnvironment = createVersionedEntity({- latestVersion: 2,+ latestVersion: GLOBAL_ENV_LATEST_VERSION,versionMap: {0: V0_VERSION,1: V1_VERSION,diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/gqlCollections.sync.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/gqlCollections.sync.tsindex c1144d98a..1ef267968 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/gqlCollections.sync.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/gqlCollections.sync.ts@@ -14,6 +14,8 @@ import {HoppRESTRequest,} from "@hoppscotch/data"+import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"+import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"import { createMapper } from "@app/lib/sync/mapper"@@ -43,7 +45,7 @@ const transformCollectionForBackend = (collection: HoppCollection): any => {authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -80,7 +82,7 @@ const recursivelySyncCollections = async (authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -134,7 +136,7 @@ const recursivelySyncCollections = async (authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -287,7 +289,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: collection.auth,headers: collection.headers,- variables: collection.variables,+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -336,7 +338,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: folder.auth,headers: folder.headers,- variables: folder.variables,+ variables: stripSecretVariableValuesForWire(folder.variables ?? []),_ref_id: folder._ref_id,description: folder.description ?? null,preRequestScript: folder.preRequestScript ?? "",diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/sync.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/sync.tsindex 9e0d44bf1..7fb998600 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/sync.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/collections/desktop/sync.ts@@ -15,6 +15,8 @@ import {HoppRESTRequest,} from "@hoppscotch/data"+import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"+import { getSyncInitFunction, StoreSyncDefinitionOf } from "@app/lib/sync"import { createMapper } from "@app/lib/sync/mapper"import {@@ -45,7 +47,7 @@ const transformCollectionForBackend = (collection: HoppCollection): any => {authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -82,7 +84,7 @@ const recursivelySyncCollections = async (authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -131,7 +133,7 @@ const recursivelySyncCollections = async (authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -280,7 +282,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: collection.auth,headers: collection.headers,- variables: collection.variables,+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -365,7 +367,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: folder.auth,headers: folder.headers,- variables: folder.variables,+ variables: stripSecretVariableValuesForWire(folder.variables ?? []),_ref_id: folder._ref_id,description: folder.description ?? null,preRequestScript: folder.preRequestScript ?? "",diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/web/gqlCollections.sync.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/web/gqlCollections.sync.tsindex 8151d011a..42db9ab16 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/web/gqlCollections.sync.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/collections/web/gqlCollections.sync.ts@@ -14,6 +14,8 @@ import {HoppRESTRequest,} from "@hoppscotch/data"+import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"+import { getSyncInitFunction, type StoreSyncDefinitionOf } from "@app/lib/sync"import { createMapper } from "@app/lib/sync/mapper"@@ -43,7 +45,7 @@ const transformCollectionForBackend = (collection: HoppCollection): any => {authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -80,7 +82,7 @@ const recursivelySyncCollections = async (authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -134,7 +136,7 @@ const recursivelySyncCollections = async (authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -287,7 +289,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: collection.auth,headers: collection.headers,- variables: collection.variables,+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -336,7 +338,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: folder.auth,headers: folder.headers,- variables: folder.variables,+ variables: stripSecretVariableValuesForWire(folder.variables ?? []),_ref_id: folder._ref_id,description: folder.description ?? null,preRequestScript: folder.preRequestScript ?? "",diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/web/import.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/web/import.tsindex 8ae5154f7..2a41eaa6e 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/web/import.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/collections/web/import.ts@@ -3,8 +3,17 @@ import {appendGraphqlCollections,appendRESTCollections,} from "@hoppscotch/common/newstore/collections"+import { generateUniqueRefId, HoppCollection } from "@hoppscotch/data"+import {+ ensureRefIds,+ flushUnmatchedRefIdsFromTree,+ indexCollectionsByRefId,+ populateLocalStoresFromCollectionTree,+ repopulateLoadedCollectionTree,+ stripCollectionTreeForStore,+ stripSecretVariableValuesForWire,+} from "@hoppscotch/common/helpers/secretVariables"import { CollectionDataProps } from "@hoppscotch/common/helpers/backend/helpers"-import { HoppCollection } from "@hoppscotch/data"import * as E from "fp-ts/Either"import {exportedCollectionToHoppCollection,@@ -15,14 +24,22 @@ import { importUserCollectionsFromJSON } from "./api"import { runDispatchWithOutSyncing } from "@app/lib/sync"/**- * Platform-specific import function for selfhost-web that uses the correct nested collection queries+ * Platform-specific import for selfhost-web. Self-contained — re-stamps+ * ref-ids and repopulates local stores on both backend success (via+ * `repopulateLoadedCollectionTree`, paired by `_ref_id`) and failure;+ * never from the stripped wire payload (raw values are gone by then).+ * The Vue caller normally pre-runs `ensureRefIds` ++ * `populateLocalStoresFromCollectionTree` upstream too; the overlap is+ * intentional defense-in-depth, not a caller contract.*/export const importToPersonalWorkspace = async (collections: HoppCollection[],reqType: ReqType) => {+ const collectionsWithRefIds = collections.map(ensureRefIds)+try {- const transformedCollection = collections.map((collection) =>+ const transformedCollection = collectionsWithRefIds.map((collection) =>translateToPersonalCollectionFormat(collection))@@ -32,19 +49,81 @@ export const importToPersonalWorkspace = async ()if (E.isRight(res)) {- await loadImportedUserCollections(+ const loaded = await loadImportedUserCollections(res.right.importUserCollectionsFromJSON.exportedCollection,res.right.importUserCollectionsFromJSON.collectionType === "REST"? "REST": "GQL")++ // Backstop populate: pair loaded → original by `_ref_id` (round-tripped+ // via `data._ref_id`), not by index — backend may reorder. Canonical+ // populate already ran upstream; missing ref-ids are skipped.+ const originalsByRefId = new Map<string, HoppCollection>()+ indexCollectionsByRefId(collectionsWithRefIds, originalsByRefId)++ // Collect ALL loaded ref-ids (root + nested folders) so the warning+ // and the flush both detect nested-level round-trip failures —+ // `exportedCollectionToHoppCollection` backfills missing+ // `data._ref_id` with fresh UUIDs, so a root-only check would miss+ // a buggy backend that dropped `_ref_id` for nested folders.+ const loadedRefIds = new Set<string>()+ const collectRefIds = (cs: HoppCollection[]) => {+ cs.forEach((c) => {+ if (c._ref_id) loadedRefIds.add(c._ref_id)+ collectRefIds(c.folders ?? [])+ })+ }+ collectRefIds(loaded)++ let unpairedCount = 0+ const countUnpaired = (cs: HoppCollection[]) => {+ cs.forEach((c) => {+ if (c._ref_id && !loadedRefIds.has(c._ref_id)) unpairedCount+++ countUnpaired(c.folders ?? [])+ })+ }+ countUnpaired(collectionsWithRefIds)++ if (unpairedCount > 0) {+ console.warn(+ `[importToPersonalWorkspace] ${unpairedCount} collection node(s) ` ++ `did not pair to originals by \`_ref_id\` (backend likely dropped ` ++ `\`data._ref_id\` at those levels); imported secret values for ` ++ `those nodes will not persist and need to be re-entered.`+ )+ }++ loaded.forEach((loadedColl) => {+ repopulateLoadedCollectionTree(loadedColl, originalsByRefId)+ })++ // Flush orphans left under originals' refIds when the backend dropped+ // `data._ref_id` for some nodes — their entries would otherwise+ // accumulate in localStorage unreachable from the loaded tree. Runs+ // AFTER `repopulateLoadedCollectionTree` so paired entries (re-seeded+ // under their refIds) aren't deleted.+ flushUnmatchedRefIdsFromTree(collectionsWithRefIds, loadedRefIds)+return E.right({ success: true })}- // Backend import failed, fall back to local storage- return appendCollectionsToStore(collections, reqType)+ // Backend failed — defensively populate local stores from the raw+ // (pre-strip) tree before appending the stripped tree to newstore.+ // The canonical caller already populated upstream, so this is+ // idempotent in the normal flow; it exists so a future caller that+ // forgets the upstream populate doesn't silently lose secrets on+ // backend failure.+ collectionsWithRefIds.forEach(populateLocalStoresFromCollectionTree)+ return appendCollectionsToStore(+ collectionsWithRefIds.map(stripCollectionTreeForStore),+ reqType+ )} catch {- // On any error, fall back to local storage- return appendCollectionsToStore(collections, reqType)+ collectionsWithRefIds.forEach(populateLocalStoresFromCollectionTree)+ return appendCollectionsToStore(+ collectionsWithRefIds.map(stripCollectionTreeForStore),+ reqType+ )}}@@ -60,7 +139,15 @@ export const appendCollectionsToStore = (return E.right({ success: true })}+/**+ * Strip + reshape for the personal-workspace import wire payload.+ *+ * Does NOT populate local stores — the caller is responsible (see+ * `importToPersonalWorkspace`'s contract).+ */export function translateToPersonalCollectionFormat(x: HoppCollection) {+ const refId = x._ref_id ?? generateUniqueRefId("coll")+const folders: HoppCollection[] = (x.folders ?? []).map(translateToPersonalCollectionFormat)@@ -68,49 +155,62 @@ export function translateToPersonalCollectionFormat(x: HoppCollection) {const data: CollectionDataProps = {auth: x.auth,headers: x.headers,- variables: x.variables,- description: x.description,+ variables: stripSecretVariableValuesForWire(x.variables ?? []),+ // Lives inside `data` so it round-trips the backend — the top-level+ // `_ref_id` on the wire is dropped, only `data._ref_id` is echoed back.+ _ref_id: refId,+ description: x.description ?? null,preRequestScript: x.preRequestScript ?? "",testScript: x.testScript ?? "",}- const obj = {+ return {...x,+ // Carry the resolved `refId` at top level too (not just inside `data`)+ // so the post-translation object is internally consistent even when+ // `x._ref_id` was missing on the input. Wire-irrelevant — backend+ // only reads `data._ref_id` — but matches the invariant other code+ // expects of a `HoppCollection`.+ _ref_id: refId,+ // Override the spread's top-level `variables` with the stripped copy+ // — without this, the raw secret values would still travel in the+ // HTTP body even though the backend only reads `data.variables`.+ // Reuses `data.variables` so we don't strip twice.+ variables: data.variables,folders,data,}-- return obj}export async function loadImportedUserCollections(collectionsJSONString: string,collectionType: "REST" | "GQL"-) {+): Promise<HoppCollection[]> {const importedCollections = (JSON.parse(collectionsJSONString) as Array<ExportedUserCollectionGQL | ExportedUserCollectionREST>).map((collection) => ({ v: 1, ...collection }))++ // NOTE: backend-returned objects whose variables have already been stripped+ // (initialValue/currentValue cleared for secrets). Returned so callers can+ // pair them back to originals by `_ref_id` for repopulation — do NOT pass+ // these as the source of secret values.+ const hoppCollections = importedCollections.map(+ (collection) =>+ exportedCollectionToHoppCollection(+ collection,+ collectionType+ ) as HoppCollection+ )+runDispatchWithOutSyncing(() => {- collectionType === "REST"- ? appendRESTCollections(- importedCollections.map(- (collection) =>- exportedCollectionToHoppCollection(- collection,- "REST"- ) as HoppCollection- )- )- : appendGraphqlCollections(- importedCollections.map(- (collection) =>- exportedCollectionToHoppCollection(- collection,- "GQL"- ) as HoppCollection- )- )+ if (collectionType === "REST") {+ appendRESTCollections(hoppCollections)+ } else {+ appendGraphqlCollections(hoppCollections)+ }})++ return hoppCollections}diff --git a/packages/hoppscotch-selfhost-web/src/platform/collections/web/sync.ts b/packages/hoppscotch-selfhost-web/src/platform/collections/web/sync.tsindex 0a5b93f09..303bf10d2 100644--- a/packages/hoppscotch-selfhost-web/src/platform/collections/web/sync.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/collections/web/sync.ts@@ -15,6 +15,8 @@ import {HoppRESTRequest,} from "@hoppscotch/data"+import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"+import { getSyncInitFunction, StoreSyncDefinitionOf } from "@app/lib/sync"import { createMapper } from "@app/lib/sync/mapper"import {@@ -45,7 +47,7 @@ const transformCollectionForBackend = (collection: HoppCollection): any => {authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -82,7 +84,7 @@ const recursivelySyncCollections = async (authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -133,7 +135,7 @@ const recursivelySyncCollections = async (authActive: true,},headers: collection.headers ?? [],- variables: collection.variables ?? [],+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -282,7 +284,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: collection.auth,headers: collection.headers,- variables: collection.variables,+ variables: stripSecretVariableValuesForWire(collection.variables ?? []),_ref_id: collection._ref_id,description: collection.description ?? null,preRequestScript: collection.preRequestScript ?? "",@@ -368,7 +370,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const data = {auth: folder.auth,headers: folder.headers,- variables: folder.variables,+ variables: stripSecretVariableValuesForWire(folder.variables ?? []),_ref_id: folder._ref_id,description: folder.description,preRequestScript: folder.preRequestScript ?? "",diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/api.ts b/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/api.tsindex 2ce32bed6..31ddd9921 100644--- a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/api.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/api.ts@@ -29,8 +29,6 @@ import {UserEnvironmentDeletedDocument,} from "@app/api/generated/graphql"-import { Environment } from "@hoppscotch/data"-export const createUserEnvironment = (name: string, variables: string) =>runMutation<CreateUserEnvironmentMutation,@@ -41,9 +39,15 @@ export const createUserEnvironment = (name: string, variables: string) =>variables,})()+// `variables` is the pre-stringified JSON payload — callers decide which+// shape to serialise (a bare `Environment.variables` array for regular+// envs, a `GlobalEnvironment` wrapper `{ v, variables }` for the global+// env). Mirrors `createUserEnvironment` and lets the global-env caller+// preserve the wrapper shape on the wire without a union type / cast.export const updateUserEnvironment = (id: string,- { name, variables }: Environment+ name: string,+ variables: string) =>runMutation<UpdateUserEnvironmentMutation,@@ -52,7 +56,7 @@ export const updateUserEnvironment = (>(UpdateUserEnvironmentDocument, {id,name,- variables: JSON.stringify(variables),+ variables,})export const deleteUserEnvironment = (id: string) =>diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/index.ts b/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/index.tsindex b0044718a..251f9650a 100644--- a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/index.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/index.ts@@ -119,15 +119,21 @@ async function loadGlobalEnvironments() {const globalEnv = res.right.me.globalEnvironmentsif (globalEnv) {- const globalEnvVariableEntries = JSON.parse(globalEnv.variables)+ const parsed = JSON.parse(globalEnv.variables)- const result = entityReference(GlobalEnvironment).safeParse(- globalEnvVariableEntries- )+ // Parse ladder: wrapper → wrap-bare-array → empty wrapper.+ let result = entityReference(GlobalEnvironment).safeParse(parsed)++ if (!result.success && Array.isArray(parsed)) {+ result = entityReference(GlobalEnvironment).safeParse({+ v: 2,+ variables: parsed,+ })+ }runDispatchWithOutSyncing(() => {setGlobalEnvVariables(- result.success ? result.data : globalEnvVariableEntries+ result.success ? result.data : { v: 2, variables: [] })setGlobalEnvID(globalEnv.id)})@@ -181,7 +187,22 @@ function setupUserEnvironmentUpdatedSubscription() {// handle the case for global environmentsif (isGlobal) {runDispatchWithOutSyncing(() => {- setGlobalEnvVariables(JSON.parse(variables))+ const parsed = JSON.parse(variables)++ // Mirror the load path: try as-is first (so v0 bare arrays still+ // migrate via verzod), only wrap a bare array as a v2 envelope+ // when the as-is parse fails (the broken-intermediate-state case).+ let result = entityReference(GlobalEnvironment).safeParse(parsed)+ if (!result.success && Array.isArray(parsed)) {+ result = entityReference(GlobalEnvironment).safeParse({+ v: 2,+ variables: parsed,+ })+ }++ setGlobalEnvVariables(+ result.success ? result.data : { v: 2, variables: [] }+ )})} else {// handle the case for normal environmentsdiff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/sync.ts b/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/sync.tsindex 04dd3e26a..b28d65887 100644--- a/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/sync.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/environments/desktop/sync.ts@@ -20,6 +20,7 @@ import {deleteUserEnvironment,updateUserEnvironment,} from "./api"+import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"import { SecretEnvironmentService } from "@hoppscotch/common/services/secret-environment.service"import { getService } from "@hoppscotch/common/modules/dioc"import { CurrentValueService } from "@hoppscotch/common/services/current-environment-value.service"@@ -30,29 +31,42 @@ export const globalEnvironmentMapper = createMapper<number, string>()const secretEnvironmentService = getService(SecretEnvironmentService)const currentEnvironmentValueService = getService(CurrentValueService)+// Tracks env ids that are still client-side temporary (`uniqueID()`) while+// the backend create is in flight. `deleteEnvironment` skips the backend+// call when the id is in this set — preventing a spurious 404 during the+// create-then-delete race window. Real backend ids are never added here,+// so deleting an already-synced env always fires the backend mutation.+const pendingTempEnvIds = new Set<string>()+export const storeSyncDefinition: StoreSyncDefinitionOf<typeof environmentsStore> = {async createEnvironment({ name, variables }) {const lastCreatedEnvIndex = environmentsStore.value.environments.length - 1+ const tempId = environmentsStore.value.environments[lastCreatedEnvIndex]?.id+ if (!tempId) return+ pendingTempEnvIds.add(tempId)- const res = await createUserEnvironment(name, JSON.stringify(variables))-- if (E.isRight(res)) {- const id = res.right.createUserEnvironment.id-- secretEnvironmentService.updateSecretEnvironmentID(- environmentsStore.value.environments[lastCreatedEnvIndex].id,- id+ try {+ const res = await createUserEnvironment(+ name,+ JSON.stringify(stripSecretVariableValuesForWire(variables)))- currentEnvironmentValueService.updateEnvironmentID(- environmentsStore.value.environments[lastCreatedEnvIndex].id,- id- )+ if (E.isRight(res)) {+ const id = res.right.createUserEnvironment.id++ // Use the captured `tempId` (not a re-read of the array) so the+ // migration still works if the env list shifted during the await.+ // Matches the pattern in `appendEnvironments` below.+ secretEnvironmentService.updateSecretEnvironmentID(tempId, id)+ currentEnvironmentValueService.updateEnvironmentID(tempId, id)- environmentsStore.value.environments[lastCreatedEnvIndex].id = id- removeDuplicateEntry(id)+ environmentsStore.value.environments[lastCreatedEnvIndex].id = id+ removeDuplicateEntry(id)+ }+ } finally {+ pendingTempEnvIds.delete(tempId)}},async appendEnvironments({ envs }) {@@ -64,16 +78,46 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const envId = ++appendStart;(async function () {- const res = await createUserEnvironment(- env.name,- JSON.stringify(env.variables)- )-- if (E.isRight(res)) {- const id = res.right.createUserEnvironment.id- environmentsStore.value.environments[envId].id = id-- removeDuplicateEntry(id)+ // Capture temp id before backend overwrites it — local stores were+ // populated under this id at import time; we remap, not re-populate.+ const tempId = environmentsStore.value.environments[envId]?.id+ if (!tempId) return+ pendingTempEnvIds.add(tempId)++ try {+ // Strip at the wire-write boundary even though the import caller+ // pre-strips — `appendEnvironments` is a public store API; the+ // invariant can't rely on callers.+ const res = await createUserEnvironment(+ env.name,+ JSON.stringify(+ stripSecretVariableValuesForWire(env.variables ?? [])+ )+ )++ if (E.isRight(res)) {+ const id = res.right.createUserEnvironment.id++ secretEnvironmentService.updateSecretEnvironmentID(tempId, id)+ currentEnvironmentValueService.updateEnvironmentID(tempId, id)++ environmentsStore.value.environments[envId].id = id+ removeDuplicateEntry(id)+ } else {+ // Backend rejected — leave local-store entries intact under+ // `tempId` so the env in newstore (which still references+ // `tempId`) continues to render secrets for this session.+ // Reload will drop the env from newstore; the orphaned+ // entries persist but are bounded (one per failed import).+ console.error("[appendEnvironments] backend rejected create")+ }+ } catch (e) {+ // Caught here so the fire-and-forget IIFE doesn't surface an+ // "unhandled promise rejection." Same in-session preservation+ // as the `E.isLeft` branch.+ console.error("[appendEnvironments] backend create threw", e)+ } finally {+ pendingTempEnvIds.delete(tempId)}})()})@@ -82,43 +126,78 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const environmentToDuplicate = environmentsStore.value.environments.find((_, index) => index === envIndex)+ if (!environmentToDuplicate) returnconst lastCreatedEnvIndex = environmentsStore.value.environments.length - 1+ const tempId = environmentsStore.value.environments[lastCreatedEnvIndex]?.id+ if (!tempId) return+ pendingTempEnvIds.add(tempId)- if (environmentToDuplicate) {+ try {const res = await createUserEnvironment(- `${environmentToDuplicate?.name} - Duplicate`,- JSON.stringify(environmentToDuplicate?.variables)+ `${environmentToDuplicate.name} - Duplicate`,+ JSON.stringify(+ stripSecretVariableValuesForWire(+ environmentToDuplicate.variables ?? []+ )+ ))if (E.isRight(res)) {const id = res.right.createUserEnvironment.idenvironmentsStore.value.environments[lastCreatedEnvIndex].id = id+ // Duplicates start fresh on secrets per the per-entity model.removeDuplicateEntry(id)}+ } finally {+ pendingTempEnvIds.delete(tempId)}},updateEnvironment({ envIndex, updatedEnv }) {const backendId = environmentsStore.value.environments[envIndex].idif (backendId) {- updateUserEnvironment(backendId, updatedEnv)()+ updateUserEnvironment(+ backendId,+ updatedEnv.name,+ JSON.stringify(+ stripSecretVariableValuesForWire(updatedEnv.variables ?? [])+ )+ )()}},async deleteEnvironment({ envID }) {- if (envID) {+ // Skip when the id belongs to an env whose backend create is still in+ // flight — sending the temp `uniqueID()` would 404 and the backend+ // create would still complete, orphaning a row. Already-synced envs+ // are never in `pendingTempEnvIds`, so this only filters the race+ // window; normal deletes fire the backend mutation.+ if (envID && !pendingTempEnvIds.has(envID)) {await deleteUserEnvironment(envID)()}},setGlobalVariables({ entries }) {const backendId = getGlobalVariableID()if (backendId) {- updateUserEnvironment(backendId, {- name: "",- variables: entries,- id: "",- v: 2,- })()+ // Bail on malformed input — syncing the dispatcher-coerced `[]`+ // would clear backend globals irreversibly. Leaving FE/BE desynced+ // is recoverable (reload re-hydrates from backend), data loss is+ // not. The dispatcher's coerce only protects FE state.+ const variables = entries?.variables+ if (!Array.isArray(variables)) {+ console.error(+ "[setGlobalVariables] unexpected variables shape, skipping sync"+ )+ return+ }+ updateUserEnvironment(+ backendId,+ "",+ JSON.stringify({+ v: 2,+ variables: stripSecretVariableValuesForWire(variables),+ })+ )()}},clearGlobalVariables() {@@ -127,6 +206,10 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<if (backendId) {clearGlobalEnvironmentVariables(backendId)}++ // Flush "Global" entries so a later add doesn't alias stale `varIndex`.+ secretEnvironmentService.addSecretEnvironment("Global", [])+ currentEnvironmentValueService.addEnvironment("Global", [])},}diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/web/api.ts b/packages/hoppscotch-selfhost-web/src/platform/environments/web/api.tsindex 2ce32bed6..31ddd9921 100644--- a/packages/hoppscotch-selfhost-web/src/platform/environments/web/api.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/environments/web/api.ts@@ -29,8 +29,6 @@ import {UserEnvironmentDeletedDocument,} from "@app/api/generated/graphql"-import { Environment } from "@hoppscotch/data"-export const createUserEnvironment = (name: string, variables: string) =>runMutation<CreateUserEnvironmentMutation,@@ -41,9 +39,15 @@ export const createUserEnvironment = (name: string, variables: string) =>variables,})()+// `variables` is the pre-stringified JSON payload — callers decide which+// shape to serialise (a bare `Environment.variables` array for regular+// envs, a `GlobalEnvironment` wrapper `{ v, variables }` for the global+// env). Mirrors `createUserEnvironment` and lets the global-env caller+// preserve the wrapper shape on the wire without a union type / cast.export const updateUserEnvironment = (id: string,- { name, variables }: Environment+ name: string,+ variables: string) =>runMutation<UpdateUserEnvironmentMutation,@@ -52,7 +56,7 @@ export const updateUserEnvironment = (>(UpdateUserEnvironmentDocument, {id,name,- variables: JSON.stringify(variables),+ variables,})export const deleteUserEnvironment = (id: string) =>diff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/web/index.ts b/packages/hoppscotch-selfhost-web/src/platform/environments/web/index.tsindex 0b4f800b0..96aee23c2 100644--- a/packages/hoppscotch-selfhost-web/src/platform/environments/web/index.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/environments/web/index.ts@@ -119,15 +119,21 @@ async function loadGlobalEnvironments() {const globalEnv = res.right.me.globalEnvironmentsif (globalEnv) {- const globalEnvVariableEntries = JSON.parse(globalEnv.variables)+ const parsed = JSON.parse(globalEnv.variables)- const result = entityReference(GlobalEnvironment).safeParse(- globalEnvVariableEntries- )+ // Parse ladder: wrapper → wrap-bare-array → empty wrapper.+ let result = entityReference(GlobalEnvironment).safeParse(parsed)++ if (!result.success && Array.isArray(parsed)) {+ result = entityReference(GlobalEnvironment).safeParse({+ v: 2,+ variables: parsed,+ })+ }runDispatchWithOutSyncing(() => {setGlobalEnvVariables(- result.success ? result.data : globalEnvVariableEntries+ result.success ? result.data : { v: 2, variables: [] })setGlobalEnvID(globalEnv.id)})@@ -181,7 +187,22 @@ function setupUserEnvironmentUpdatedSubscription() {// handle the case for global environmentsif (isGlobal) {runDispatchWithOutSyncing(() => {- setGlobalEnvVariables(JSON.parse(variables))+ const parsed = JSON.parse(variables)++ // Mirror the load path: try as-is first (so v0 bare arrays still+ // migrate via verzod), only wrap a bare array as a v2 envelope+ // when the as-is parse fails (the broken-intermediate-state case).+ let result = entityReference(GlobalEnvironment).safeParse(parsed)+ if (!result.success && Array.isArray(parsed)) {+ result = entityReference(GlobalEnvironment).safeParse({+ v: 2,+ variables: parsed,+ })+ }++ setGlobalEnvVariables(+ result.success ? result.data : { v: 2, variables: [] }+ )})} else {// handle the case for normal environmentsdiff --git a/packages/hoppscotch-selfhost-web/src/platform/environments/web/sync.ts b/packages/hoppscotch-selfhost-web/src/platform/environments/web/sync.tsindex 2229ca19c..b28d65887 100644--- a/packages/hoppscotch-selfhost-web/src/platform/environments/web/sync.ts+++ b/packages/hoppscotch-selfhost-web/src/platform/environments/web/sync.ts@@ -20,6 +20,7 @@ import {deleteUserEnvironment,updateUserEnvironment,} from "./api"+import { stripSecretVariableValuesForWire } from "@hoppscotch/common/helpers/secretVariables"import { SecretEnvironmentService } from "@hoppscotch/common/services/secret-environment.service"import { getService } from "@hoppscotch/common/modules/dioc"import { CurrentValueService } from "@hoppscotch/common/services/current-environment-value.service"@@ -30,28 +31,42 @@ export const globalEnvironmentMapper = createMapper<number, string>()const secretEnvironmentService = getService(SecretEnvironmentService)const currentEnvironmentValueService = getService(CurrentValueService)+// Tracks env ids that are still client-side temporary (`uniqueID()`) while+// the backend create is in flight. `deleteEnvironment` skips the backend+// call when the id is in this set — preventing a spurious 404 during the+// create-then-delete race window. Real backend ids are never added here,+// so deleting an already-synced env always fires the backend mutation.+const pendingTempEnvIds = new Set<string>()+export const storeSyncDefinition: StoreSyncDefinitionOf<typeof environmentsStore> = {async createEnvironment({ name, variables }) {const lastCreatedEnvIndex = environmentsStore.value.environments.length - 1+ const tempId = environmentsStore.value.environments[lastCreatedEnvIndex]?.id+ if (!tempId) return+ pendingTempEnvIds.add(tempId)- const res = await createUserEnvironment(name, JSON.stringify(variables))+ try {+ const res = await createUserEnvironment(+ name,+ JSON.stringify(stripSecretVariableValuesForWire(variables))+ )- if (E.isRight(res)) {- const id = res.right.createUserEnvironment.id+ if (E.isRight(res)) {+ const id = res.right.createUserEnvironment.id- secretEnvironmentService.updateSecretEnvironmentID(- environmentsStore.value.environments[lastCreatedEnvIndex].id,- id- )- currentEnvironmentValueService.updateEnvironmentID(- environmentsStore.value.environments[lastCreatedEnvIndex].id,- id- )+ // Use the captured `tempId` (not a re-read of the array) so the+ // migration still works if the env list shifted during the await.+ // Matches the pattern in `appendEnvironments` below.+ secretEnvironmentService.updateSecretEnvironmentID(tempId, id)+ currentEnvironmentValueService.updateEnvironmentID(tempId, id)- environmentsStore.value.environments[lastCreatedEnvIndex].id = id- removeDuplicateEntry(id)+ environmentsStore.value.environments[lastCreatedEnvIndex].id = id+ removeDuplicateEntry(id)+ }+ } finally {+ pendingTempEnvIds.delete(tempId)}},async appendEnvironments({ envs }) {@@ -63,16 +78,46 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const envId = ++appendStart;(async function () {- const res = await createUserEnvironment(- env.name,- JSON.stringify(env.variables)- )-- if (E.isRight(res)) {- const id = res.right.createUserEnvironment.id- environmentsStore.value.environments[envId].id = id-- removeDuplicateEntry(id)+ // Capture temp id before backend overwrites it — local stores were+ // populated under this id at import time; we remap, not re-populate.+ const tempId = environmentsStore.value.environments[envId]?.id+ if (!tempId) return+ pendingTempEnvIds.add(tempId)++ try {+ // Strip at the wire-write boundary even though the import caller+ // pre-strips — `appendEnvironments` is a public store API; the+ // invariant can't rely on callers.+ const res = await createUserEnvironment(+ env.name,+ JSON.stringify(+ stripSecretVariableValuesForWire(env.variables ?? [])+ )+ )++ if (E.isRight(res)) {+ const id = res.right.createUserEnvironment.id++ secretEnvironmentService.updateSecretEnvironmentID(tempId, id)+ currentEnvironmentValueService.updateEnvironmentID(tempId, id)++ environmentsStore.value.environments[envId].id = id+ removeDuplicateEntry(id)+ } else {+ // Backend rejected — leave local-store entries intact under+ // `tempId` so the env in newstore (which still references+ // `tempId`) continues to render secrets for this session.+ // Reload will drop the env from newstore; the orphaned+ // entries persist but are bounded (one per failed import).+ console.error("[appendEnvironments] backend rejected create")+ }+ } catch (e) {+ // Caught here so the fire-and-forget IIFE doesn't surface an+ // "unhandled promise rejection." Same in-session preservation+ // as the `E.isLeft` branch.+ console.error("[appendEnvironments] backend create threw", e)+ } finally {+ pendingTempEnvIds.delete(tempId)}})()})@@ -81,43 +126,78 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<const environmentToDuplicate = environmentsStore.value.environments.find((_, index) => index === envIndex)+ if (!environmentToDuplicate) returnconst lastCreatedEnvIndex = environmentsStore.value.environments.length - 1+ const tempId = environmentsStore.value.environments[lastCreatedEnvIndex]?.id+ if (!tempId) return+ pendingTempEnvIds.add(tempId)- if (environmentToDuplicate) {+ try {const res = await createUserEnvironment(- `${environmentToDuplicate?.name} - Duplicate`,- JSON.stringify(environmentToDuplicate?.variables)+ `${environmentToDuplicate.name} - Duplicate`,+ JSON.stringify(+ stripSecretVariableValuesForWire(+ environmentToDuplicate.variables ?? []+ )+ ))if (E.isRight(res)) {const id = res.right.createUserEnvironment.idenvironmentsStore.value.environments[lastCreatedEnvIndex].id = id+ // Duplicates start fresh on secrets per the per-entity model.removeDuplicateEntry(id)}+ } finally {+ pendingTempEnvIds.delete(tempId)}},updateEnvironment({ envIndex, updatedEnv }) {const backendId = environmentsStore.value.environments[envIndex].idif (backendId) {- updateUserEnvironment(backendId, updatedEnv)()+ updateUserEnvironment(+ backendId,+ updatedEnv.name,+ JSON.stringify(+ stripSecretVariableValuesForWire(updatedEnv.variables ?? [])+ )+ )()}},async deleteEnvironment({ envID }) {- if (envID) {+ // Skip when the id belongs to an env whose backend create is still in+ // flight — sending the temp `uniqueID()` would 404 and the backend+ // create would still complete, orphaning a row. Already-synced envs+ // are never in `pendingTempEnvIds`, so this only filters the race+ // window; normal deletes fire the backend mutation.+ if (envID && !pendingTempEnvIds.has(envID)) {await deleteUserEnvironment(envID)()}},setGlobalVariables({ entries }) {const backendId = getGlobalVariableID()if (backendId) {- updateUserEnvironment(backendId, {- name: "",- variables: entries,- id: "",- v: 2,- })()+ // Bail on malformed input — syncing the dispatcher-coerced `[]`+ // would clear backend globals irreversibly. Leaving FE/BE desynced+ // is recoverable (reload re-hydrates from backend), data loss is+ // not. The dispatcher's coerce only protects FE state.+ const variables = entries?.variables+ if (!Array.isArray(variables)) {+ console.error(+ "[setGlobalVariables] unexpected variables shape, skipping sync"+ )+ return+ }+ updateUserEnvironment(+ backendId,+ "",+ JSON.stringify({+ v: 2,+ variables: stripSecretVariableValuesForWire(variables),+ })+ )()}},clearGlobalVariables() {@@ -126,6 +206,10 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<if (backendId) {clearGlobalEnvironmentVariables(backendId)}++ // Flush "Global" entries so a later add doesn't alias stale `varIndex`.+ secretEnvironmentService.addSecretEnvironment("Global", [])+ currentEnvironmentValueService.addEnvironment("Global", [])},}