Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

feat(common): implement current env value fallback to initial value (#6503)

Anwarul Islam5afa1a5f23b2
diff --git a/packages/hoppscotch-common/src/components/collections/ImportExport.vue b/packages/hoppscotch-common/src/components/collections/ImportExport.vue
index 051886f2f..24e19eb4a 100644
--- a/packages/hoppscotch-common/src/components/collections/ImportExport.vue
+++ b/packages/hoppscotch-common/src/components/collections/ImportExport.vue
@@ -45,7 +45,7 @@ import {
flushUnmatchedRefIdsFromTree,
populateLocalStoresFromCollectionTree,
stripCollectionTreeForStore,
-} from "~/helpers/secretVariables"
+} from "~/helpers/clientLocalVariables"
import IconInsomnia from "~icons/hopp/insomnia"
import IconPostman from "~icons/hopp/postman"
diff --git a/packages/hoppscotch-common/src/components/collections/documentation/PublishDocSnapshotPreview.vue b/packages/hoppscotch-common/src/components/collections/documentation/PublishDocSnapshotPreview.vue
index 4ecc9a479..6b81de21f 100644
--- a/packages/hoppscotch-common/src/components/collections/documentation/PublishDocSnapshotPreview.vue
+++ b/packages/hoppscotch-common/src/components/collections/documentation/PublishDocSnapshotPreview.vue
@@ -429,14 +429,9 @@ const fetchSnapshotPreview = async () => {
const parsedVars =
typeof rawEnvVars === "string" ? JSON.parse(rawEnvVars) : rawEnvVars
if (Array.isArray(parsedVars)) {
- snapshotEnvironmentVariables.value = parsedVars.map((v) => {
- const normalized = translateToNewEnvironmentVariables(v)
- // Ensure currentValue falls back to initialValue
- return {
- ...normalized,
- currentValue: normalized.currentValue || normalized.initialValue,
- }
- })
+ snapshotEnvironmentVariables.value = parsedVars.map((v) =>
+ translateToNewEnvironmentVariables(v)
+ )
}
} catch (e) {
console.error("Error parsing snapshot environment variables:", e)
diff --git a/packages/hoppscotch-common/src/components/collections/documentation/index.vue b/packages/hoppscotch-common/src/components/collections/documentation/index.vue
index 6100f360f..16dfdf72b 100644
--- a/packages/hoppscotch-common/src/components/collections/documentation/index.vue
+++ b/packages/hoppscotch-common/src/components/collections/documentation/index.vue
@@ -270,7 +270,7 @@ import {
import { updateTeamCollection } from "~/helpers/backend/mutations/TeamCollection"
import { updateTeamRequest } from "~/helpers/backend/mutations/TeamRequest"
-import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"
+import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import {
CollectionDataProps,
getSingleTeamCollectionJSON,
@@ -736,7 +736,7 @@ const saveCollectionDocumentation = async () => {
const data: CollectionDataProps = {
auth: collection.auth || { authType: "inherit", authActive: true },
headers: collection.headers || [],
- variables: stripSecretVariableValuesForWire(collection.variables || []),
+ variables: stripClientLocalValuesForWire(collection.variables || []),
description: documentationDescription.value,
preRequestScript: collection.preRequestScript || "",
testScript: collection.testScript || "",
@@ -832,7 +832,7 @@ const saveCollectionDocumentationById = async (
const data: CollectionDataProps = {
auth: collectionData.auth || { authType: "inherit", authActive: true },
headers: collectionData.headers || [],
- variables: stripSecretVariableValuesForWire(
+ variables: stripClientLocalValuesForWire(
collectionData.variables || []
),
description: documentation,
diff --git a/packages/hoppscotch-common/src/components/collections/graphql/Collection.vue b/packages/hoppscotch-common/src/components/collections/graphql/Collection.vue
index 14803af49..b901d246e 100644
--- a/packages/hoppscotch-common/src/components/collections/graphql/Collection.vue
+++ b/packages/hoppscotch-common/src/components/collections/graphql/Collection.vue
@@ -250,7 +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 { flushLocalStoresForCollectionTree } from "~/helpers/clientLocalVariables"
import { handleTokenValidation } from "~/helpers/handleTokenValidation"
import { GQLTabService } from "~/services/tab/graphql"
import IconCheckCircle from "~icons/lucide/check-circle"
diff --git a/packages/hoppscotch-common/src/components/collections/graphql/Folder.vue b/packages/hoppscotch-common/src/components/collections/graphql/Folder.vue
index 2b710b144..f134c0a42 100644
--- a/packages/hoppscotch-common/src/components/collections/graphql/Folder.vue
+++ b/packages/hoppscotch-common/src/components/collections/graphql/Folder.vue
@@ -235,7 +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 { flushLocalStoresForCollectionTree } from "~/helpers/clientLocalVariables"
import { GQLTabService } from "~/services/tab/graphql"
import IconCheckCircle from "~icons/lucide/check-circle"
import IconCopy from "~icons/lucide/copy"
diff --git a/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue b/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue
index f1b72ccc9..9733bab96 100644
--- a/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue
+++ b/packages/hoppscotch-common/src/components/collections/graphql/ImportExport.vue
@@ -40,7 +40,7 @@ import {
ensureRefIds,
populateLocalStoresFromCollectionTree,
stripCollectionTreeForStore,
-} from "~/helpers/secretVariables"
+} from "~/helpers/clientLocalVariables"
const t = useI18n()
const toast = useToast()
diff --git a/packages/hoppscotch-common/src/components/collections/index.vue b/packages/hoppscotch-common/src/components/collections/index.vue
index efa2785e9..d0b241070 100644
--- a/packages/hoppscotch-common/src/components/collections/index.vue
+++ b/packages/hoppscotch-common/src/components/collections/index.vue
@@ -412,8 +412,8 @@ import {
flushLocalStoresForCollectionTree,
flushLocalStoresForTeamCollectionTree,
stripCollectionTreeForStore,
- stripSecretVariableValuesForWire,
-} from "~/helpers/secretVariables"
+ stripClientLocalValuesForWire,
+} from "~/helpers/clientLocalVariables"
const t = useI18n()
const toast = useToast()
@@ -3615,7 +3615,7 @@ const setCollectionProperties = (newCollection: {
currentEnvironmentValueService.addEnvironment(storeKey, nonSecretVariables)
- collection.variables = stripSecretVariableValuesForWire(filteredVariables)
+ collection.variables = stripClientLocalValuesForWire(filteredVariables)
}
if (collectionsType.value.type === "my-collections") {
diff --git a/packages/hoppscotch-common/src/components/environments/Add.vue b/packages/hoppscotch-common/src/components/environments/Add.vue
index 1a9ec22c8..7f47f6d8b 100644
--- a/packages/hoppscotch-common/src/components/environments/Add.vue
+++ b/packages/hoppscotch-common/src/components/environments/Add.vue
@@ -79,7 +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 { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import {
setGlobalEnvVariables,
updateEnvironment,
@@ -206,7 +206,7 @@ const addEnvironment = async () => {
await pipe(
updateTeamEnvironment(
- JSON.stringify(stripSecretVariableValuesForWire(newVariables)),
+ JSON.stringify(stripClientLocalValuesForWire(newVariables)),
scope.value.environment.id,
scope.value.environment.environment.name
),
@@ -223,8 +223,10 @@ const addEnvironment = async () => {
key: editingName.value,
currentValue: editingValue.value,
isSecret: false,
- varIndex:
- scope.value.environment.environment.variables.length - 1,
+ // The new variable is appended at index `length` of the
+ // pre-append array; `length - 1` collided with the previous
+ // last variable's slot.
+ varIndex: scope.value.environment.environment.variables.length,
}
)
}
diff --git a/packages/hoppscotch-common/src/components/environments/ImportExport.vue b/packages/hoppscotch-common/src/components/environments/ImportExport.vue
index b1a168d53..583234acc 100644
--- a/packages/hoppscotch-common/src/components/environments/ImportExport.vue
+++ b/packages/hoppscotch-common/src/components/environments/ImportExport.vue
@@ -13,8 +13,8 @@ import { Environment, generateUniqueRefId } from "@hoppscotch/data"
import {
populateLocalStoresFromVariables,
promoteInitialValueForImport,
- stripSecretVariableValuesForWire,
-} from "~/helpers/secretVariables"
+ stripClientLocalValuesForWire,
+} from "~/helpers/clientLocalVariables"
import * as E from "fp-ts/Either"
import { ref } from "vue"
@@ -418,7 +418,7 @@ const handleImportToStore = async (
])
// Append stripped imports; varIndex aligns with the hydrated entries.
- stripSecretVariableValuesForWire(importedGlobals).forEach(
+ stripClientLocalValuesForWire(importedGlobals).forEach(
({ key, initialValue, currentValue, secret }) => {
addGlobalEnvVariable({ key, initialValue, currentValue, secret })
}
@@ -446,7 +446,7 @@ const handleImportToStore = async (
const strippedEnvironments = envsWithIds.map((env) => ({
...env,
- variables: stripSecretVariableValuesForWire(env.variables),
+ variables: stripClientLocalValuesForWire(env.variables),
}))
appendEnvironments(strippedEnvironments)
toast.success(t("state.file_imported"))
@@ -462,7 +462,7 @@ const importToTeams = async (content: Environment[]) => {
for (const [, env] of content.entries()) {
const res = createTeamEnvironment(
- JSON.stringify(stripSecretVariableValuesForWire(env.variables)),
+ JSON.stringify(stripClientLocalValuesForWire(env.variables)),
props.teamId as string,
env.name
)()
diff --git a/packages/hoppscotch-common/src/components/environments/Selector.vue b/packages/hoppscotch-common/src/components/environments/Selector.vue
index a553ab2de..590e2e404 100644
--- a/packages/hoppscotch-common/src/components/environments/Selector.vue
+++ b/packages/hoppscotch-common/src/components/environments/Selector.vue
@@ -258,16 +258,10 @@
{{ variable.key }}
</span>
<span class="min-w-[4rem] w-full truncate text-secondaryLight">
- <template v-if="variable.secret"> ******** </template>
- <template v-else>
- {{ variable.initialValue }}
- </template>
+ {{ variable.initialValue }}
</span>
<span class="min-w-[4rem] w-full truncate text-secondaryLight">
- <template v-if="variable.secret"> ******** </template>
- <template v-else>
- {{ variable.currentValue }}
- </template>
+ {{ variable.currentValue }}
</span>
</div>
<div v-if="globalEnvs.length === 0" class="text-secondaryLight">
@@ -327,16 +321,10 @@
{{ variable.key }}
</span>
<span class="min-w-[4rem] w-full truncate text-secondaryLight">
- <template v-if="variable.secret"> ******** </template>
- <template v-else>
- {{ variable.initialValue }}
- </template>
+ {{ variable.initialValue }}
</span>
<span class="min-w-[4rem] w-full truncate text-secondaryLight">
- <template v-if="variable.secret"> ******** </template>
- <template v-else>
- {{ variable.currentValue }}
- </template>
+ {{ variable.currentValue }}
</span>
</div>
<div
@@ -379,6 +367,8 @@ import {
} from "~/newstore/environments"
import { useLocalState } from "~/newstore/localstate"
import { CurrentValueService } from "~/services/current-environment-value.service"
+import { SecretEnvironmentService } from "~/services/secret-environment.service"
+import { maskSecretValue } from "~/helpers/utils/secretMask"
import { WorkspaceService } from "~/services/workspace.service"
import IconCheck from "~icons/lucide/check"
import IconEdit from "~icons/lucide/edit"
@@ -426,6 +416,8 @@ const workspace = workspaceService.currentWorkspace
const currentEnvironmentValueService = useService(CurrentValueService)
+const secretEnvironmentService = useService(SecretEnvironmentService)
+
// TeamList-Adapter
const teamListAdapter = workspaceService.acquireTeamListAdapter(null)
const myTeams = useReadonlyStream(teamListAdapter.teamList$, null)
@@ -696,27 +688,45 @@ const globalVals = useReadonlyStream(globalEnv$, {
variables: [],
} as GlobalEnvironment)
-const globalEnvs = computed(() => {
- return (globalVals.value?.variables ?? []).map((variable, index) => ({
+// Resolve each variable's display values. Secrets are masked by length (an
+// unset secret renders empty, not a fixed `********`) so the popover matches the
+// env tooltip and never claims a value exists when it doesn't.
+const resolveDisplayVariable = (
+ variable: Environment["variables"][number],
+ envID: string,
+ index: number
+) => {
+ if (variable.secret) {
+ const secretValue =
+ secretEnvironmentService.getSecretEnvironmentVariableValue(envID, index)
+ return {
+ ...variable,
+ initialValue: maskSecretValue(secretValue?.initialValue),
+ currentValue: maskSecretValue(secretValue?.value),
+ }
+ }
+ return {
...variable,
currentValue:
currentEnvironmentValueService.getEnvironmentVariableValue(
- "Global",
+ envID,
index
) ?? "",
- }))
+ }
+}
+
+const globalEnvs = computed(() => {
+ return (globalVals.value?.variables ?? []).map((variable, index) =>
+ resolveDisplayVariable(variable, "Global", index)
+ )
})
const environmentVariables = computed(() => {
if (selectedEnv.value.variables && selectedEnv.value.id) {
- return selectedEnv.value.variables.map((variable, index) => ({
- ...variable,
- currentValue:
- currentEnvironmentValueService.getEnvironmentVariableValue(
- selectedEnv.value.id ?? "",
- index
- ) ?? "",
- }))
+ const envID = selectedEnv.value.id
+ return selectedEnv.value.variables.map((variable, index) =>
+ resolveDisplayVariable(variable, envID, index)
+ )
}
return []
})
diff --git a/packages/hoppscotch-common/src/components/environments/index.vue b/packages/hoppscotch-common/src/components/environments/index.vue
index a74cafac6..5f3604528 100644
--- a/packages/hoppscotch-common/src/components/environments/index.vue
+++ b/packages/hoppscotch-common/src/components/environments/index.vue
@@ -57,7 +57,7 @@
<script setup lang="ts">
import { useReadonlyStream, useStream } from "@composables/stream"
import { Environment, GlobalEnvironment } from "@hoppscotch/data"
-import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"
+import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import { useService } from "dioc/vue"
import * as TE from "fp-ts/TaskEither"
import { pipe } from "fp-ts/function"
@@ -274,7 +274,7 @@ const duplicateGlobalEnvironment = async () => {
await pipe(
createTeamEnvironment(
JSON.stringify(
- stripSecretVariableValuesForWire(globalEnvironment.value.variables)
+ stripClientLocalValuesForWire(globalEnvironment.value.variables)
),
workspace.value.teamID,
`Global - ${t("action.duplicate")}`
diff --git a/packages/hoppscotch-common/src/components/environments/my/Details.vue b/packages/hoppscotch-common/src/components/environments/my/Details.vue
index 3843229cc..be0769f53 100644
--- a/packages/hoppscotch-common/src/components/environments/my/Details.vue
+++ b/packages/hoppscotch-common/src/components/environments/my/Details.vue
@@ -241,7 +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 { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import { uniqueID } from "~/helpers/utils/uniqueID"
import {
createEnvironment,
@@ -592,7 +592,7 @@ const saveEnvironment = () => {
currentEnvironmentValueService.addEnvironment("Global", nonSecretVariables)
}
- const variables = stripSecretVariableValuesForWire(filteredVariables)
+ const variables = stripClientLocalValuesForWire(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.vue
index 94f23d95f..73acd399b 100644
--- a/packages/hoppscotch-common/src/components/environments/teams/Details.vue
+++ b/packages/hoppscotch-common/src/components/environments/teams/Details.vue
@@ -254,7 +254,7 @@ import {
updateTeamEnvironment,
} from "~/helpers/backend/mutations/TeamEnvironment"
import { GQLError } from "~/helpers/backend/GQLClient"
-import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"
+import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import { TeamEnvironment } from "~/helpers/teams/TeamEnvironment"
import { useColorMode } from "~/composables/theming"
import { platform } from "~/platform"
@@ -555,7 +555,7 @@ const saveEnvironment = async () => {
)
)
- const variables = stripSecretVariableValuesForWire(filteredVariables)
+ const variables = stripClientLocalValuesForWire(filteredVariables)
const environmentUpdated: Environment = {
v: 2,
diff --git a/packages/hoppscotch-common/src/components/http/Codegen.vue b/packages/hoppscotch-common/src/components/http/Codegen.vue
index 912dfa49e..10f6424fe 100644
--- a/packages/hoppscotch-common/src/components/http/Codegen.vue
+++ b/packages/hoppscotch-common/src/components/http/Codegen.vue
@@ -132,7 +132,10 @@ import {
resolvesEnvsInBody,
} from "~/helpers/utils/EffectiveURL"
import { getAggregateEnvsWithCurrentValue } from "~/newstore/environments"
-import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"
+import {
+ getEffectiveVariablesForRequest,
+ filterNonEmptyEnvironmentVariables,
+} from "~/helpers/utils/environments"
import { useService } from "dioc/vue"
import cloneDeep from "lodash-es/cloneDeep"
@@ -145,7 +148,6 @@ import IconCheck from "~icons/lucide/check"
import IconWrapText from "~icons/lucide/wrap-text"
import { asyncComputed } from "@vueuse/core"
import { getDefaultRESTRequest } from "~/helpers/rest/default"
-import { filterNonEmptyEnvironmentVariables } from "~/helpers/RequestRunner"
const t = useI18n()
diff --git a/packages/hoppscotch-common/src/components/http/Headers.vue b/packages/hoppscotch-common/src/components/http/Headers.vue
index 3ffa1d982..33cca6c6e 100644
--- a/packages/hoppscotch-common/src/components/http/Headers.vue
+++ b/packages/hoppscotch-common/src/components/http/Headers.vue
@@ -279,8 +279,10 @@ import {
getComputedHeaders,
} from "~/helpers/utils/EffectiveURL"
import { isDragDropAllowed, DragDropEvent } from "~/helpers/dragDropValidation"
-import { filterNonEmptyEnvironmentVariables } from "~/helpers/RequestRunner"
-import { normalizeAggregateEnvs } from "~/helpers/utils/environments"
+import {
+ filterNonEmptyEnvironmentVariables,
+ normalizeAggregateEnvs,
+} from "~/helpers/utils/environments"
import {
AggregateEnvironment,
aggregateEnvsWithCurrentValue$,
diff --git a/packages/hoppscotch-common/src/components/http/RequestTab.vue b/packages/hoppscotch-common/src/components/http/RequestTab.vue
index ce25ae0e8..8cf5acb38 100644
--- a/packages/hoppscotch-common/src/components/http/RequestTab.vue
+++ b/packages/hoppscotch-common/src/components/http/RequestTab.vue
@@ -47,10 +47,16 @@ const envs = useReadonlyStream(
)
const resolvedEnvs = computed(() => {
+ // `showSecretCollectionValues = false` keeps inherited collection secrets
+ // masked in this display list (consumed by the headers/auth preview and the
+ // request field editors), matching the other display/preview consumers.
+ // Execution/resolution callers (codegen, auth request builder) keep the
+ // default `true` because they need the resolved value, not a mask.
return getEffectiveVariablesForRequest(
tab.value.document.request.requestVariables,
tab.value.document.inheritedProperties?.variables,
- envs.value
+ envs.value,
+ false
)
})
diff --git a/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue b/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue
index 33e5e1dea..d619ee011 100644
--- a/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue
+++ b/packages/hoppscotch-common/src/components/http/example/ResponseTab.vue
@@ -45,10 +45,15 @@ const envs = useReadonlyStream(
)
const resolvedEnvs = computed(() => {
+ // `showSecretCollectionValues = false` keeps inherited collection secrets
+ // masked in this display list, matching the other display/preview consumers.
+ // Execution/resolution callers (codegen, auth request builder) keep the
+ // default `true` because they need the resolved value, not a mask.
return getEffectiveVariablesForRequest(
tab.value.document.response.originalRequest.requestVariables,
tab.value.document.inheritedProperties?.variables,
- envs.value
+ envs.value,
+ false
)
})
diff --git a/packages/hoppscotch-common/src/components/smart/EnvInput.vue b/packages/hoppscotch-common/src/components/smart/EnvInput.vue
index c9487df64..1a1e79821 100644
--- a/packages/hoppscotch-common/src/components/smart/EnvInput.vue
+++ b/packages/hoppscotch-common/src/components/smart/EnvInput.vue
@@ -102,6 +102,7 @@ import { RESTTabService } from "~/services/tab/rest"
import { syntaxTree } from "@codemirror/language"
import { uniqueID } from "~/helpers/utils/uniqueID"
import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"
+import { maskSecretValue } from "~/helpers/utils/secretMask"
const t = useI18n()
@@ -406,8 +407,8 @@ const envVars = computed(() => {
sourceEnvID,
}) => ({
key,
- currentValue: secret ? "********" : currentValue,
- initialValue: secret ? "********" : initialValue,
+ currentValue: secret ? maskSecretValue(currentValue) : currentValue,
+ initialValue: secret ? maskSecretValue(initialValue) : initialValue,
sourceEnv: sourceEnv ?? "",
sourceEnvID,
secret,
@@ -462,7 +463,13 @@ function envAutoCompletion(context: CompletionContext) {
return {
label: `<<${envKey}>>`,
- info: env?.currentValue ?? "",
+ // Mask secrets here too: the computed branch (URL/Body, no `:envs`)
+ // carries raw secret values, so an unmasked `info` would leak them in
+ // the completion panel. Display shows `currentValue` as-is (empty stays
+ // empty); the current→initial fallback happens only at execution time.
+ info: env?.secret
+ ? maskSecretValue(env.currentValue)
+ : (env?.currentValue ?? ""),
apply: completionText,
}
})
diff --git a/packages/hoppscotch-common/src/composables/useMockServer.ts b/packages/hoppscotch-common/src/composables/useMockServer.ts
index 13f6a9778..27bead548 100644
--- a/packages/hoppscotch-common/src/composables/useMockServer.ts
+++ b/packages/hoppscotch-common/src/composables/useMockServer.ts
@@ -31,7 +31,7 @@ import {
loadMockServers,
} from "~/newstore/mockServers"
import { CurrentValueService } from "~/services/current-environment-value.service"
-import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"
+import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import { TeamCollectionsService } from "~/services/team-collection.service"
import { WorkspaceService } from "~/services/workspace.service"
@@ -283,9 +283,7 @@ export function useMockServer() {
await pipe(
updateTeamEnvironment(
- JSON.stringify(
- stripSecretVariableValuesForWire(normalizedVariables)
- ),
+ JSON.stringify(stripClientLocalValuesForWire(normalizedVariables)),
existingEnv.id,
existingEnv.environment.name
),
@@ -328,7 +326,7 @@ export function useMockServer() {
await pipe(
createTeamEnvironment(
- JSON.stringify(stripSecretVariableValuesForWire(variables)),
+ JSON.stringify(stripClientLocalValuesForWire(variables)),
teamID,
envName
),
diff --git a/packages/hoppscotch-common/src/helpers/RequestRunner.ts b/packages/hoppscotch-common/src/helpers/RequestRunner.ts
index c83622e13..887431493 100644
--- a/packages/hoppscotch-common/src/helpers/RequestRunner.ts
+++ b/packages/hoppscotch-common/src/helpers/RequestRunner.ts
@@ -40,6 +40,7 @@ import {
getGlobalVariables,
SelectedEnvironmentIndex,
setGlobalEnvVariables,
+ setSelectedEnvironmentIndex,
updateEnvironment,
} from "~/newstore/environments"
import { platform } from "~/platform"
@@ -63,7 +64,14 @@ import {
import { HoppRESTResponse } from "./types/HoppRESTResponse"
import { HoppTestData, HoppTestResult } from "./types/HoppTestResult"
import { getEffectiveRESTRequest } from "./utils/EffectiveURL"
-import { getCombinedEnvVariables } from "./utils/environments"
+import {
+ getCombinedEnvVariables,
+ filterNonEmptyEnvironmentVariables,
+} from "./utils/environments"
+import {
+ nonSecretKeysOf,
+ frozenInitialValueForWire,
+} from "./utils/scriptEnvWriteback"
import { transformInheritedCollectionVariablesToAggregateEnv } from "./utils/inheritedCollectionVarTransformer"
import { isJSONContentType } from "./utils/contenttypes"
import { applyScriptRequestUpdates } from "./experimental-sandbox-integration"
@@ -186,12 +194,16 @@ export const getTestableBody = (
}
/**
- * Combines the environment variables from the request and the selected, global, and temporary environments.
+ * Combines the request, collection, and environment (temporary/selected/global)
+ * variables into a single precedence-ordered list. Order is precedence: earlier
+ * entries win, and de-duplication (keeping the first non-empty occurrence) is
+ * applied later by `filterNonEmptyEnvironmentVariables`.
* The priority is as follows:
* 1. Request variables
- * 2. Temporary variables (if any)
- * 3. Selected environment variables
- * 4. Global environment variables
+ * 2. Collection variables (inherited)
+ * 3. Temporary variables (if any)
+ * 4. Selected environment variables
+ * 5. Global environment variables
* @param variables The environment variables to combine
* @returns The combined environment variables
*/
@@ -226,7 +238,12 @@ export const executedResponses$ = new Subject<
const updateEnvironments = (
envs: Environment["variables"],
type: "global" | "selected",
- initialEnvID?: string
+ initialEnvID?: string,
+ // Keys that existed as NON-secret variables before this run (see
+ // `nonSecretKeysOf`). Used to freeze the shared `initialValue`: a script only
+ // ever changes `currentValue`, so a pre-existing non-secret var keeps its
+ // default while a script-created (or since-demoted-secret) key goes out empty.
+ existingNonSecretKeys?: ReadonlySet<string>
) => {
const envID =
type === "selected" ? initialEnvID || getCurrentEnvironment().id : "Global"
@@ -269,10 +286,18 @@ const updateEnvironments = (
// `currentEnvironmentValueService` (populated above); the wire payload
// gets it cleared so test-script env updates can't leak per-user state
// into the team backend.
+ //
+ // The shared `initialValue` is the editor's to change, never a script's:
+ // a pre-existing non-secret var keeps its own default; a script-created
+ // (or since-demoted-secret) key goes out empty, so a per-user/runtime
+ // value — or a resolved secret — can't become a shared default. Keyed by
+ // membership (not a value lookup), so duplicate keys keep their own value.
return {
key: e.key,
secret: e.secret ?? false,
- initialValue: e.initialValue ?? "",
+ initialValue: existingNonSecretKeys
+ ? frozenInitialValueForWire(e, existingNonSecretKeys)
+ : (e.initialValue ?? ""),
currentValue: "",
}
})
@@ -326,53 +351,6 @@ const getEnvironmentVariableValue = (
)
}
-/**
- * Set currentValue as initialValue if currentValue is empty
- * This is set just for request runtime and it will not be persisted.
- * @param env The environment variable to be transformed
- * @returns The transformed environment variable with currentValue set to initialValue if empty
- */
-const getTransformedEnvs = (
- env: Environment["variables"][number]
-): Environment["variables"][number] => {
- return {
- ...env,
- currentValue: env.currentValue || env.initialValue,
- }
-}
-
-/**
- * Transforms the environment list to a list with unique keys with value
- * and set currentValue as initialValue if currentValue is empty.
- * @param envs The environment list to be transformed
- * @returns The transformed environment list with keys with value
- */
-export const filterNonEmptyEnvironmentVariables = (
- envs: Environment["variables"]
-): Environment["variables"] => {
- const envsMap = new Map<string, Environment["variables"][number]>()
- envs.forEach((env) => {
- const transformedEnv = getTransformedEnvs(env)
-
- if (envsMap.has(transformedEnv.key)) {
- const existingEnv = envsMap.get(transformedEnv.key)
-
- if (
- existingEnv &&
- "currentValue" in existingEnv &&
- existingEnv.currentValue === "" &&
- transformedEnv.currentValue !== ""
- ) {
- envsMap.set(transformedEnv.key, transformedEnv)
- }
- } else {
- envsMap.set(transformedEnv.key, transformedEnv)
- }
- })
-
- return Array.from(envsMap.values())
-}
-
const delegatePreRequestScriptRunner = (
request: HoppRESTRequest,
envs: {
@@ -736,7 +714,9 @@ function updateEnvsAfterTestScript(
if (globalChanged) {
const globalEnvVariables = updateEnvironments(
runResult.right.envs.global,
- "global"
+ "global",
+ undefined,
+ nonSecretKeysOf(initialEnvsForComparison.global)
)
setGlobalEnvVariables({
@@ -749,7 +729,8 @@ function updateEnvsAfterTestScript(
const selectedEnvVariables = updateEnvironments(
cloneDeep(runResult.right.envs.selected),
"selected",
- initialEnvID
+ initialEnvID,
+ nonSecretKeysOf(initialEnvsForComparison.selected)
)
if (initialEnvironmentIndex.type === "MY_ENV") {
@@ -775,6 +756,26 @@ function updateEnvsAfterTestScript(
envName
)
)()
+
+ // Team envs have no local store dispatch (unlike `updateEnvironment` for
+ // MY_ENV), so `currentEnvironment$` — and the aggregate stream feeding the
+ // request field highlights/tooltips — would stay stale until the team-env
+ // subscription round-trips. Optimistically refresh the selected index so
+ // the new values show immediately. Guarded so a mid-request env switch
+ // isn't clobbered.
+ const selected = environmentsStore.value.selectedEnvironmentIndex
+ if (
+ selected.type === "TEAM_ENV" &&
+ selected.teamEnvID === initialEnvironmentIndex.teamEnvID
+ ) {
+ setSelectedEnvironmentIndex({
+ ...selected,
+ environment: {
+ ...selected.environment,
+ variables: selectedEnvVariables,
+ },
+ })
+ }
}
}
}
@@ -1106,9 +1107,14 @@ const resolveEnvVars = (
(v.secret
? secretMeta?.value
: getEnvironmentVariableValue(envID, index)) ?? "",
- // fallback to var initialValue if secretMeta is not found
- initialValue:
- (v.secret ? secretMeta?.initialValue : "") ?? v.initialValue,
+ // For a secret, use the secret store's initialValue (falling back to the
+ // definition's when the store has no entry); for a non-secret, use the
+ // definition's initialValue directly. The old `: ""` branch produced a
+ // non-nullish "", short-circuiting the `?? v.initialValue` fallback so
+ // every non-secret resolved to an empty initialValue.
+ initialValue: v.secret
+ ? (secretMeta?.initialValue ?? v.initialValue)
+ : v.initialValue,
}
})
diff --git a/packages/hoppscotch-common/src/helpers/__tests__/secretVariables.spec.ts b/packages/hoppscotch-common/src/helpers/__tests__/clientLocalVariables.spec.ts
similarity index 97%
rename from packages/hoppscotch-common/src/helpers/__tests__/secretVariables.spec.ts
rename to packages/hoppscotch-common/src/helpers/__tests__/clientLocalVariables.spec.ts
index d770ee5c7..f01fa1235 100644
--- a/packages/hoppscotch-common/src/helpers/__tests__/secretVariables.spec.ts
+++ b/packages/hoppscotch-common/src/helpers/__tests__/clientLocalVariables.spec.ts
@@ -11,14 +11,14 @@ import {
populateLocalStoresFromCollectionTree,
populateLocalStoresFromVariables,
repopulateLoadedCollectionTree,
- stripSecretVariableValuesForWire,
-} from "../secretVariables"
+ stripClientLocalValuesForWire,
+} from "../clientLocalVariables"
const ENTITY_ID = "entity-1"
-describe("stripSecretVariableValuesForWire", () => {
+describe("stripClientLocalValuesForWire", () => {
it("clears both initialValue and currentValue for secret variables", () => {
- const result = stripSecretVariableValuesForWire([
+ const result = stripClientLocalValuesForWire([
{
key: "token",
initialValue: "should-be-stripped",
@@ -37,12 +37,12 @@ describe("stripSecretVariableValuesForWire", () => {
])
})
- it("keeps both initialValue and currentValue for non-secret variables", () => {
- const result = stripSecretVariableValuesForWire([
+ it("clears currentValue for non-secret variables (per-user, client-local) but keeps initialValue", () => {
+ const result = stripClientLocalValuesForWire([
{
key: "host",
initialValue: "https://api.example.com",
- currentValue: "https://staging.example.com",
+ currentValue: "https://my-laptop.local",
secret: false,
},
])
@@ -51,7 +51,7 @@ describe("stripSecretVariableValuesForWire", () => {
{
key: "host",
initialValue: "https://api.example.com",
- currentValue: "https://staging.example.com",
+ currentValue: "",
secret: false,
},
])
@@ -62,19 +62,20 @@ describe("stripSecretVariableValuesForWire", () => {
{
key: "x",
initialValue: "v",
- currentValue: "v",
+ currentValue: "c",
secret: false,
// hypothetical future field
description: "the X variable",
},
]
- const [out] = stripSecretVariableValuesForWire(input)
+ const [out] = stripClientLocalValuesForWire(input)
expect(out.description).toBe("the X variable")
+ expect(out.currentValue).toBe("")
})
it("returns an empty array for empty input", () => {
- expect(stripSecretVariableValuesForWire([])).toEqual([])
+ expect(stripClientLocalValuesForWire([])).toEqual([])
})
})
diff --git a/packages/hoppscotch-common/src/helpers/auth/index.ts b/packages/hoppscotch-common/src/helpers/auth/index.ts
index f34023859..02103ce95 100644
--- a/packages/hoppscotch-common/src/helpers/auth/index.ts
+++ b/packages/hoppscotch-common/src/helpers/auth/index.ts
@@ -2,7 +2,11 @@ import { getService } from "~/modules/dioc"
import { RESTTabService } from "~/services/tab/rest"
import { parseTemplateStringE } from "@hoppscotch/data"
import * as E from "fp-ts/Either"
-import { getCombinedEnvVariables } from "../utils/environments"
+import {
+ getEffectiveVariablesForRequest,
+ filterNonEmptyEnvironmentVariables,
+} from "../utils/environments"
+import { getAggregateEnvsWithCurrentValue } from "~/newstore/environments"
export const replaceTemplateStringsInObjectValues = <
T extends Record<string, unknown>,
@@ -10,33 +14,21 @@ export const replaceTemplateStringsInObjectValues = <
obj: T,
source: "REST" | "GQL" = "REST"
) => {
- const envs = getCombinedEnvVariables()
- const restTabsService = getService(RESTTabService)
-
- const requestVariables =
- source === "REST" &&
- restTabsService.currentActiveTab.value.document.type === "request"
- ? restTabsService.currentActiveTab.value.document.request.requestVariables.map(
- ({ key, value }) => ({
- key,
- initialValue: value,
- currentValue: value,
- secret: false,
- })
- )
- : []
-
- // Ensure request variables are prioritized by removing any selected/global environment variables with the same key
- const selectedEnvVars = envs.selected.filter(
- ({ key }) =>
- !requestVariables.some(({ key: reqVarKey }) => reqVarKey === key)
+ const document = getService(RESTTabService).currentActiveTab.value.document
+
+ // Only a REST request tab has request/collection variables.
+ const isRESTRequest = source === "REST" && document.type === "request"
+
+ // Resolve like a sent request: request > collection > environment precedence,
+ // active request vars only. The current→initial fallback happens in
+ // `parseTemplateStringE`.
+ const envVars = filterNonEmptyEnvironmentVariables(
+ getEffectiveVariablesForRequest(
+ isRESTRequest ? document.request.requestVariables : [],
+ isRESTRequest ? document.inheritedProperties?.variables : [],
+ getAggregateEnvsWithCurrentValue()
+ )
)
- const globalEnvVars = envs.global.filter(
- ({ key }) =>
- !requestVariables.some(({ key: reqVarKey }) => reqVarKey === key)
- )
-
- const envVars = [...selectedEnvVars, ...globalEnvVars, ...requestVariables]
const newObj: Partial<T> = {}
diff --git a/packages/hoppscotch-common/src/helpers/backend/helpers.ts b/packages/hoppscotch-common/src/helpers/backend/helpers.ts
index 52e5fa40b..2e3243d7e 100644
--- a/packages/hoppscotch-common/src/helpers/backend/helpers.ts
+++ b/packages/hoppscotch-common/src/helpers/backend/helpers.ts
@@ -18,7 +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 { stripCollectionTreeForStore } from "~/helpers/clientLocalVariables"
import {
ExportAsJsonDocument,
ExportCollectionToJsonDocument,
diff --git a/packages/hoppscotch-common/src/helpers/secretVariables.ts b/packages/hoppscotch-common/src/helpers/clientLocalVariables.ts
similarity index 58%
rename from packages/hoppscotch-common/src/helpers/secretVariables.ts
rename to packages/hoppscotch-common/src/helpers/clientLocalVariables.ts
index e8658be3e..43046ec22 100644
--- a/packages/hoppscotch-common/src/helpers/secretVariables.ts
+++ b/packages/hoppscotch-common/src/helpers/clientLocalVariables.ts
@@ -13,47 +13,31 @@ type SecretCapableVariable = {
}
/**
- * Strip raw values that must never reach the backend before the wire write.
- *
- * For SECRET variables we clear BOTH `initialValue` and `currentValue` — the
- * secret value lives only in the local secret store (see #6279).
- *
- * For NON-SECRET variables `currentValue` is a normal, syncable value and
- * MUST be preserved on the wire — otherwise environment / global-env updates
- * persist an empty `currentValue` and the value is lost on reload.
+ * Strip client-local values before a wire write (backend mutations, exports,
+ * store documents): a secret's value lives only in `SecretEnvironmentService`
+ * (#6279), and `currentValue` is a per-user override in `CurrentValueService`.
+ * Both are persisted locally and resolve via the currentValue→initialValue
+ * fallback, so only the non-secret `initialValue` — the shared default —
+ * rides the wire.
*/
-export const stripSecretVariableValuesForWire = <
- T extends SecretCapableVariable,
->(
+export const stripClientLocalValuesForWire = <T extends SecretCapableVariable>(
variables: T[]
): T[] =>
variables.map((v) => ({
...v,
initialValue: v.secret ? "" : v.initialValue,
- currentValue: v.secret ? "" : v.currentValue,
+ currentValue: "",
}))
/**
- * Seed the local secret + currentValue stores from raw variables.
- *
- * IMPORTANT: pass RAW (pre-strip) inputs. A stripped SECRET variable has
- * empty `initialValue` / `currentValue` and will persist as blank.
+ * Seed the local secret + currentValue stores from RAW (pre-strip) variables —
+ * stripped inputs would persist as blanks.
*
- * ─── `??` 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.
+ * `??` (not `||`) is load-bearing: on rehydration an explicit `""` means
+ * "user deliberately cleared" and must not be resurrected from `initialValue`.
+ * Import payloads (where `""` means "stripped on wire") are promoted upstream
+ * by `promoteInitialValueForImport` — route new import paths through that
+ * instead of changing this function.
*/
export const populateLocalStoresFromVariables = (
entityId: string,
@@ -95,15 +79,10 @@ export const populateLocalStoresFromVariables = (
}
/**
- * Foreign-import convention normalizer for variables exported with
- * `currentValue: ""` and the real value in `initialValue` — Postman /
- * Insomnia format, plus legacy Hoppscotch exports from before non-secret
- * `currentValue` was preserved on the wire. 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.
+ * Promote `initialValue` into an empty `currentValue` — the wire shape
+ * produced by `stripClientLocalValuesForWire`, also the Postman / Insomnia
+ * format. Idempotent. The global-env rehydration path skips this on purpose:
+ * there `""` means "user deliberately cleared".
*/
export const promoteInitialValueForImport = (
variables: readonly SecretCapableVariable[]
@@ -123,15 +102,11 @@ export const populateLocalStoresFromCollectionTree = (
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`.
+ // Unreachable when callers run `ensureRefIds` upstream; warn so a
+ // future caller that skips it is debuggable instead of silently
+ // dropping secrets. (`repopulateLoadedCollectionTree` bypasses this
+ // branch — its missing-ref-id gap is warned in selfhost-web's
+ // `importToPersonalWorkspace`.)
console.warn(
"[populateLocalStoresFromCollectionTree] collection has no `_ref_id`; secret values will not be persisted locally",
collection.name
@@ -152,7 +127,7 @@ export const stripCollectionTreeForStore = (
collection: HoppCollection
): HoppCollection => ({
...collection,
- variables: stripSecretVariableValuesForWire(collection.variables ?? []),
+ variables: stripClientLocalValuesForWire(collection.variables ?? []),
folders: (collection.folders ?? []).map(stripCollectionTreeForStore),
})
@@ -168,10 +143,9 @@ export const indexCollectionsByRefId = (
}
/**
- * 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`.
+ * Re-seed local stores after bulk-import by `_ref_id` (round-tripped via
+ * `data._ref_id` at every level) — the backend may reorder, so array index
+ * is unusable. Unpaired nodes fall through to `flushUnmatchedRefIdsFromTree`.
*/
export const repopulateLoadedCollectionTree = (
loaded: HoppCollection,
@@ -180,9 +154,6 @@ export const repopulateLoadedCollectionTree = (
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 ?? [])
@@ -219,11 +190,10 @@ export const flushLocalStoresForCollectionTree = (
}
/**
- * 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.
+ * Flush store entries for `_ref_id`s in `tree` that aren't in `keptRefIds`.
+ * Cleans up orphans after `repopulateLoadedCollectionTree` on old SH backends
+ * that drop the `data._ref_id` round-trip (entries were seeded under refIds
+ * the loaded tree, now on fresh UUIDs, can't reach).
*/
export const flushUnmatchedRefIdsFromTree = (
tree: HoppCollection[],
@@ -245,11 +215,9 @@ export const flushUnmatchedRefIdsFromTree = (
}
/**
- * 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.
+ * Flush a team-collection subtree by backend `id`, walking `children`
+ * (team shape — not `HoppCollection.folders`) so nested folders' entries
+ * aren't left orphaned on delete.
*/
type TeamCollectionNode = {
id: string
diff --git a/packages/hoppscotch-common/src/helpers/collection/collection.ts b/packages/hoppscotch-common/src/helpers/collection/collection.ts
index 0bd7b7c7d..0e892631d 100644
--- a/packages/hoppscotch-common/src/helpers/collection/collection.ts
+++ b/packages/hoppscotch-common/src/helpers/collection/collection.ts
@@ -8,7 +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 { stripClientLocalValuesForWire } from "../clientLocalVariables"
import { CollectionDataProps } from "../backend/helpers"
import { CollectionFolder } from "../backend/queries/PublishedDocs"
@@ -311,7 +311,7 @@ export function transformCollectionForImport(
const data: CollectionDataProps = {
auth: collection.auth,
headers: collection.headers,
- variables: stripSecretVariableValuesForWire(collection.variables ?? []),
+ variables: stripClientLocalValuesForWire(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`.
diff --git a/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts b/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts
index ffc04c7cc..89b3bbb51 100644
--- a/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts
+++ b/packages/hoppscotch-common/src/helpers/editor/extensions/HoppEnvironment.ts
@@ -32,7 +32,10 @@ import IconVariable from "~icons/lucide/variable?raw"
import IconLibrary from "~icons/lucide/library?raw"
import { isComment } from "./helpers"
-import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"
+import {
+ getEffectiveVariablesForRequest,
+ filterNonEmptyEnvironmentVariables,
+} from "~/helpers/utils/environments"
import {
ENV_VAR_NAME_REGEX,
HOPP_ENVIRONMENT_REGEX,
@@ -42,6 +45,7 @@ import {
constrainTooltipToViewport,
createTooltipValueRow,
} from "~/helpers/utils/tooltip"
+import { maskSecretValue } from "~/helpers/utils/secretMask"
const HOPP_ENV_HIGHLIGHT =
"cursor-help transition rounded px-1 focus:outline-none mx-0.5 env-highlight"
@@ -57,32 +61,6 @@ const secretEnvironmentService = getService(SecretEnvironmentService)
const currentEnvironmentValueService = getService(CurrentValueService)
const restTabs = getService(RESTTabService)
-/**
- * Transforms the environment list to a list with unique keys with value
- * @param envs The environment list to be transformed
- * @returns The transformed environment list with keys with value
- */
-const filterNonEmptyEnvironmentVariables = (
- envs: AggregateEnvironment[]
-): AggregateEnvironment[] => {
- const envsMap = new Map<string, AggregateEnvironment>()
- envs.forEach((env) => {
- if (envsMap.has(env.key)) {
- const existingEnv = envsMap.get(env.key)
- if (
- existingEnv?.currentValue === "" &&
- existingEnv?.initialValue === "" &&
- (env.currentValue || env.initialValue)
- ) {
- envsMap.set(env.key, env)
- }
- } else {
- envsMap.set(env.key, env)
- }
- })
- return Array.from(envsMap.values())
-}
-
const cursorTooltipField = (aggregateEnvs: AggregateEnvironment[]) =>
hoverTooltip(
(view, pos, side) => {
@@ -141,7 +119,6 @@ const cursorTooltipField = (aggregateEnvs: AggregateEnvironment[]) =>
)?.currentValue || tooltipEnv?.currentValue
: tooltipEnv?.currentValue
- const isSecret = tooltipEnv?.secret === true
const hasSource = Boolean(tooltipEnv?.sourceEnv)
const tooltipSourceEnvID =
@@ -161,15 +138,21 @@ const cursorTooltipField = (aggregateEnvs: AggregateEnvironment[]) =>
tooltipEnv?.key ?? ""
)
- // Display secret values as "******" when stored; if no secret is saved, show "Empty" placeholders instead
+ // Secret-ness follows the resolved variable itself, so the preview matches
+ // what the request actually sends. For a duplicate key with a secret and a
+ // non-secret sibling, whichever wins resolution (first non-empty by
+ // position) is what executes — masking a non-secret winner just because a
+ // secret sibling shares its key made the tooltip disagree with execution.
+ const isSecret = tooltipEnv?.secret === true
+
if (isSecret) {
if (hasSecretValueStored && hasSecretInitialValueStored) {
- envInitialValue = "******"
- envCurrentValue = "******"
+ envInitialValue = maskSecretValue(envInitialValue)
+ envCurrentValue = maskSecretValue(envCurrentValue)
} else if (!hasSecretValueStored && hasSecretInitialValueStored) {
- envInitialValue = "******"
+ envInitialValue = maskSecretValue(envInitialValue)
} else if (hasSecretValueStored && !hasSecretInitialValueStored) {
- envCurrentValue = "******"
+ envCurrentValue = maskSecretValue(envCurrentValue)
} else {
envInitialValue = "Empty"
envCurrentValue = "Empty"
@@ -178,19 +161,27 @@ const cursorTooltipField = (aggregateEnvs: AggregateEnvironment[]) =>
envInitialValue = "Not Found"
envCurrentValue = "Not Found"
} else {
- // Parse templates only if needed and values are not already masked
- if (!envCurrentValue && envInitialValue) {
+ // Resolve each column independently so a variable that has BOTH an
+ // initial and a current value still previews resolved values (matching
+ // what the runner resolves), instead of leaving `<<...>>` unparsed when
+ // both are set. Empty values are skipped so they stay empty.
+ // `maskValue = true`: a non-secret wrapper like `Bearer <<apiKey>>` must
+ // render its nested SECRET reference masked, never as raw plaintext.
+ if (envInitialValue) {
const parsedInitial = parseTemplateStringE(
envInitialValue,
- aggregateEnvs
+ aggregateEnvs,
+ true
)
envInitialValue = E.isLeft(parsedInitial)
? "error"
: parsedInitial.right
- } else if (!envInitialValue && envCurrentValue) {
+ }
+ if (envCurrentValue) {
const parsedCurrent = parseTemplateStringE(
envCurrentValue,
- aggregateEnvs
+ aggregateEnvs,
+ true
)
envCurrentValue = E.isLeft(parsedCurrent)
? "error"
diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/environment.ts b/packages/hoppscotch-common/src/helpers/import-export/export/environment.ts
index cb28e344e..c3823d63b 100644
--- a/packages/hoppscotch-common/src/helpers/import-export/export/environment.ts
+++ b/packages/hoppscotch-common/src/helpers/import-export/export/environment.ts
@@ -3,7 +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 { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import { initializeDownloadFile } from "."
const getEnvironmentJSON = (
@@ -41,7 +41,7 @@ export const transformEnvironmentVariables = ({
id,
v,
name,
- variables: stripSecretVariableValuesForWire(variables),
+ variables: stripClientLocalValuesForWire(variables),
}
}
diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/environments.ts b/packages/hoppscotch-common/src/helpers/import-export/export/environments.ts
index ac77877be..5909bbdb0 100644
--- a/packages/hoppscotch-common/src/helpers/import-export/export/environments.ts
+++ b/packages/hoppscotch-common/src/helpers/import-export/export/environments.ts
@@ -1,10 +1,10 @@
import { Environment } from "@hoppscotch/data"
-import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"
+import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
export const environmentsExporter = (myEnvironments: Environment[]) => {
const stripped = myEnvironments.map((env) => ({
...env,
- variables: stripSecretVariableValuesForWire(env.variables),
+ variables: stripClientLocalValuesForWire(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.ts
index 0d24b316e..55b1820c4 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,6 @@
import { HoppCollection } from "@hoppscotch/data"
import { stripRefIdReplacer } from "."
-import { stripCollectionTreeForStore } from "~/helpers/secretVariables"
+import { stripCollectionTreeForStore } from "~/helpers/clientLocalVariables"
export const gqlCollectionsExporter = (gqlCollections: HoppCollection[]) => {
const stripped = gqlCollections.map(stripCollectionTreeForStore)
diff --git a/packages/hoppscotch-common/src/helpers/import-export/export/myCollections.ts b/packages/hoppscotch-common/src/helpers/import-export/export/myCollections.ts
index d0f576c09..d67e3429a 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,6 @@
import { HoppCollection } from "@hoppscotch/data"
import { stripRefIdReplacer } from "."
-import { stripCollectionTreeForStore } from "~/helpers/secretVariables"
+import { stripCollectionTreeForStore } from "~/helpers/clientLocalVariables"
export const myCollectionsExporter = (myCollections: HoppCollection[]) => {
const stripped = myCollections.map(stripCollectionTreeForStore)
diff --git a/packages/hoppscotch-common/src/helpers/utils/__tests__/scriptEnvWriteback.spec.ts b/packages/hoppscotch-common/src/helpers/utils/__tests__/scriptEnvWriteback.spec.ts
new file mode 100644
index 000000000..4e70c9f89
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/utils/__tests__/scriptEnvWriteback.spec.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from "vitest"
+
+import {
+ nonSecretKeysOf,
+ frozenInitialValueForWire,
+} from "../scriptEnvWriteback"
+
+describe("nonSecretKeysOf", () => {
+ it("includes non-secret keys and excludes secret keys", () => {
+ const keys = nonSecretKeysOf([
+ { key: "host", secret: false },
+ { key: "token", secret: true },
+ { key: "region", secret: false },
+ ])
+ expect([...keys].sort()).toEqual(["host", "region"])
+ expect(keys.has("token")).toBe(false)
+ })
+
+ it("treats a missing secret flag as non-secret", () => {
+ expect(nonSecretKeysOf([{ key: "a" }]).has("a")).toBe(true)
+ })
+
+ it("dedupes duplicate keys to a single membership entry", () => {
+ const keys = nonSecretKeysOf([
+ { key: "x", secret: false },
+ { key: "x", secret: false },
+ ])
+ expect(keys.size).toBe(1)
+ expect(keys.has("x")).toBe(true)
+ })
+})
+
+describe("frozenInitialValueForWire", () => {
+ it("keeps a pre-existing non-secret var's own initialValue (default preserved)", () => {
+ const existing = new Set(["host"])
+ expect(
+ frozenInitialValueForWire({ key: "host", initialValue: "prod" }, existing)
+ ).toBe("prod")
+ })
+
+ it("blanks a key the script created this run (absent from the set)", () => {
+ expect(
+ frozenInitialValueForWire(
+ { key: "created", initialValue: "runtime" },
+ new Set()
+ )
+ ).toBe("")
+ })
+
+ it("blanks a key that was secret pre-run and got demoted (absent from the non-secret set)", () => {
+ // e.g. pw.env.unset("host"); pw.env.set("host", "x") on a secret `host`.
+ // `nonSecretKeysOf` excluded it, so it's treated as created → empty default.
+ const existingNonSecret = nonSecretKeysOf([{ key: "host", secret: true }])
+ expect(
+ frozenInitialValueForWire(
+ { key: "host", initialValue: "leaked" },
+ existingNonSecret
+ )
+ ).toBe("")
+ })
+
+ it("gives duplicate keys their OWN initialValue (membership, not a value lookup)", () => {
+ // The bug this guards against: a Map keyed by name collapsed duplicates
+ // last-wins, pushing the wrong default to a shared team env.
+ const existing = new Set(["x"])
+ expect(
+ frozenInitialValueForWire({ key: "x", initialValue: "A" }, existing)
+ ).toBe("A")
+ expect(
+ frozenInitialValueForWire({ key: "x", initialValue: "B" }, existing)
+ ).toBe("B")
+ })
+
+ it("treats a missing initialValue as empty", () => {
+ expect(frozenInitialValueForWire({ key: "host" }, new Set(["host"]))).toBe(
+ ""
+ )
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/utils/__tests__/secretMask.spec.ts b/packages/hoppscotch-common/src/helpers/utils/__tests__/secretMask.spec.ts
new file mode 100644
index 000000000..0a65fb2fa
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/utils/__tests__/secretMask.spec.ts
@@ -0,0 +1,19 @@
+import { describe, expect, test } from "vitest"
+import { maskSecretValue } from "../secretMask"
+
+describe("maskSecretValue", () => {
+ test("masks each character with a single '*', preserving length", () => {
+ expect(maskSecretValue("abc")).toBe("***")
+ expect(maskSecretValue("super-secret-123")).toBe("*".repeat(16))
+ })
+
+ test("returns an empty string for an empty value (so unset stays distinguishable)", () => {
+ expect(maskSecretValue("")).toBe("")
+ })
+
+ test("treats null/undefined as empty rather than masking", () => {
+ expect(maskSecretValue(null)).toBe("")
+ expect(maskSecretValue(undefined)).toBe("")
+ expect(maskSecretValue()).toBe("")
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/utils/__tests__/variablePrecedence.spec.ts b/packages/hoppscotch-common/src/helpers/utils/__tests__/variablePrecedence.spec.ts
index 353d6f7f0..7af47d648 100644
--- a/packages/hoppscotch-common/src/helpers/utils/__tests__/variablePrecedence.spec.ts
+++ b/packages/hoppscotch-common/src/helpers/utils/__tests__/variablePrecedence.spec.ts
@@ -1,11 +1,16 @@
import { describe, expect, test } from "vitest"
-import { Environment, HoppRESTAuth } from "@hoppscotch/data"
+import {
+ Environment,
+ HoppRESTAuth,
+ parseTemplateString,
+ parseBodyEnvVariables,
+} from "@hoppscotch/data"
import {
getEffectiveVariablesForRequest,
normalizeAggregateEnvs,
+ filterNonEmptyEnvironmentVariables,
} from "../environments"
import { getComputedAuthHeaders } from "../EffectiveURL"
-import { filterNonEmptyEnvironmentVariables } from "~/helpers/RequestRunner"
import { AggregateEnvironment } from "~/newstore/environments"
import { HoppInheritedProperty } from "../../types/HoppInheritedProperties"
@@ -140,6 +145,65 @@ describe("inherited collection auth — variable precedence in the preview", ()
expect(await authHeaderFor(vars)).toBe(`Basic ${btoa("env-token:pw")}`)
})
+
+ // Auth/OAuth resolution goes through this same pipeline (see
+ // `replaceTemplateStringsInObjectValues` in helpers/auth). An INACTIVE request
+ // variable must be dropped, not shadow a real environment variable.
+ test("an inactive request variable does not shadow the environment variable", async () => {
+ const vars = filterNonEmptyEnvironmentVariables(
+ getEffectiveVariablesForRequest(
+ [{ key: "token", value: "should-be-ignored", active: false }],
+ [],
+ [envVar("token", "env-token")]
+ )
+ )
+
+ expect(await authHeaderFor(vars)).toBe(`Basic ${btoa("env-token:pw")}`)
+ })
+
+ test("currentValue falls back to initialValue if currentValue is empty", async () => {
+ const vars = filterNonEmptyEnvironmentVariables(
+ getEffectiveVariablesForRequest(
+ [],
+ [],
+ [
+ {
+ key: "token",
+ currentValue: "",
+ initialValue: "fallback-token",
+ secret: false,
+ sourceEnv: "Test Env",
+ },
+ ]
+ )
+ )
+
+ expect(await authHeaderFor(vars)).toBe(`Basic ${btoa("fallback-token:pw")}`)
+ })
+
+ // Precedence must use the *effective* value (current || initial), not the raw
+ // current value. A fully-empty request variable should fall through to a lower
+ // env variable that only has an initialValue. The environment inspector relies
+ // on this too, so it doesn't flag such a variable as "empty".
+ test("empty higher-precedence var falls through to a lower one that only has an initialValue", async () => {
+ const vars = filterNonEmptyEnvironmentVariables(
+ getEffectiveVariablesForRequest(
+ [{ key: "token", value: "", active: true }],
+ [],
+ [
+ {
+ key: "token",
+ currentValue: "",
+ initialValue: "env-init",
+ secret: false,
+ sourceEnv: "Test Env",
+ },
+ ]
+ )
+ )
+
+ expect(await authHeaderFor(vars)).toBe(`Basic ${btoa("env-init:pw")}`)
+ })
})
describe("normalizeAggregateEnvs (legacy { key, value } rows)", () => {
@@ -176,3 +240,37 @@ describe("normalizeAggregateEnvs (legacy { key, value } rows)", () => {
)
})
})
+
+// The current→initial fallback lives in the resolvers (single source of truth):
+// resolving `<<var>>` uses currentValue, falling back to initialValue when empty.
+// This covers every execution path (auth, body, url, params, scripts) since they
+// all route through these two functions. Display surfaces read `currentValue`
+// directly and never call these, so an empty current value stays empty on screen.
+describe("resolver current→initial fallback (single source of truth)", () => {
+ const vars: Environment["variables"] = [
+ { key: "emptyCur", currentValue: "", initialValue: "init", secret: false },
+ { key: "both", currentValue: "cur", initialValue: "init", secret: false },
+ { key: "allEmpty", currentValue: "", initialValue: "", secret: false },
+ { key: "zeroish", currentValue: "0", initialValue: "init", secret: false },
+ ]
+
+ test("parseTemplateString: empty currentValue resolves to initialValue", () => {
+ expect(parseTemplateString("<<emptyCur>>", vars)).toBe("init")
+ })
+
+ test("parseTemplateString: non-empty currentValue wins over initialValue", () => {
+ expect(parseTemplateString("<<both>>", vars)).toBe("cur")
+ })
+
+ test("parseTemplateString: both empty resolves to empty string", () => {
+ expect(parseTemplateString("<<allEmpty>>", vars)).toBe("")
+ })
+
+ test('parseTemplateString: a real "0" currentValue is kept, not treated as empty', () => {
+ expect(parseTemplateString("<<zeroish>>", vars)).toBe("0")
+ })
+
+ test("parseBodyEnvVariables: empty currentValue resolves to initialValue", () => {
+ expect(parseBodyEnvVariables("token=<<emptyCur>>", vars)).toBe("token=init")
+ })
+})
diff --git a/packages/hoppscotch-common/src/helpers/utils/environments.ts b/packages/hoppscotch-common/src/helpers/utils/environments.ts
index cb705924f..265469dfb 100644
--- a/packages/hoppscotch-common/src/helpers/utils/environments.ts
+++ b/packages/hoppscotch-common/src/helpers/utils/environments.ts
@@ -109,8 +109,11 @@ export const transformRequestVariablesToAggregateEnv = (
// Builds the precedence-ordered variable list for resolving `<<var>>` templates:
// request → collection → environment (highest first). Matches the runtime's
// `combineEnvVariables` ordering, so previews stay in sync with execution. Not
-// de-duplicated — wrap with `filterNonEmptyEnvironmentVariables` for the runtime's
-// empty-value fall-through. `showSecretCollectionValues=false` keeps inherited
+// de-duplicated — wrap with `filterNonEmptyEnvironmentVariables` so an empty
+// higher-precedence variable falls through to a lower-precedence one. (The
+// current→initial value fallback itself happens later, at resolution time in
+// `getResolvedVariableValue`, invoked by `parseTemplateStringE`.)
+// `showSecretCollectionValues=false` keeps inherited
// collection secrets masked (used by the inspector / autocomplete).
export const getEffectiveVariablesForRequest = (
requestVariables: HoppRESTRequestVariable[] | undefined,
@@ -128,10 +131,46 @@ export const getEffectiveVariablesForRequest = (
return [...requestVars, ...collectionVars, ...environmentVars]
}
+/**
+ * De-duplicates a precedence-ordered variable list by key, keeping the first
+ * occurrence unless it has no effective value and a later one does — so an empty
+ * higher-precedence variable falls through to a lower-precedence one. Values are
+ * left untouched; the current→initial fallback is applied at resolution time in
+ * `getResolvedVariableValue` (via `parseTemplateStringE`). Shared by the request
+ * runner, the editor highlighter, and the environment inspector so all three
+ * agree on precedence.
+ */
+export const filterNonEmptyEnvironmentVariables = <
+ T extends { key: string; currentValue?: string; initialValue?: string },
+>(
+ envs: T[]
+): T[] => {
+ const hasEffectiveValue = (env: T): boolean =>
+ Boolean(env.currentValue || env.initialValue)
+
+ const envsMap = new Map<string, T>()
+ envs.forEach((env) => {
+ if (envsMap.has(env.key)) {
+ const existingEnv = envsMap.get(env.key)
+ if (
+ existingEnv &&
+ !hasEffectiveValue(existingEnv) &&
+ hasEffectiveValue(env)
+ ) {
+ envsMap.set(env.key, env)
+ }
+ } else {
+ envsMap.set(env.key, env)
+ }
+ })
+
+ return Array.from(envsMap.values())
+}
+
/**
* Defensively normalizes possibly-legacy env rows to the v2 `AggregateEnvironment`
* shape (preserving any extra fields), so consumers like
- * `filterNonEmptyEnvironmentVariables` / `parseTemplateString` always see a
+ * `filterNonEmptyEnvironmentVariables` / `parseTemplateStringE` always see a
* `currentValue`/`initialValue`. Legacy rows shaped `{ key, value }` (e.g. older
* embed callers) lack those fields and would otherwise resolve to an empty string.
*/
diff --git a/packages/hoppscotch-common/src/helpers/utils/scriptEnvWriteback.ts b/packages/hoppscotch-common/src/helpers/utils/scriptEnvWriteback.ts
new file mode 100644
index 000000000..409dfc48d
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/utils/scriptEnvWriteback.ts
@@ -0,0 +1,37 @@
+/**
+ * Pure helpers for deciding what a post-request/test-script environment
+ * writeback may send to the backend.
+ *
+ * The rule: a test script may only ever change a variable's per-user
+ * `currentValue` (client-local); the shared `initialValue` that syncs to the
+ * backend is never authored by a script — it is preserved for a pre-existing
+ * NON-secret variable and cleared for one the script created (so a script's
+ * runtime value, or a resolved secret, can't become a team-wide default). The
+ * `initialValue` field is the environment editor's to change.
+ */
+
+/**
+ * Keys that existed as NON-secret variables before this run. Secret keys are
+ * excluded on purpose: a secret's `initialValue` must never surface as a
+ * plaintext default, and a variable a script demotes from secret to non-secret
+ * (unset + recreate) must be treated as freshly created.
+ */
+export const nonSecretKeysOf = (
+ vars: readonly { key: string; secret?: boolean }[]
+): Set<string> => new Set(vars.filter((v) => !v.secret).map((v) => v.key))
+
+/**
+ * The `initialValue` a NON-secret variable should carry on the env-sync wire
+ * after a script run. Membership-only (never a keyed value lookup), so
+ * duplicate keys each keep their OWN `initialValue` rather than collapsing to a
+ * single value.
+ *
+ * - key existed pre-run as non-secret → keep the variable's own `initialValue`
+ * (a script only touched `currentValue`; the shared default is unchanged).
+ * - key is new this run (created), or was secret and got demoted → `""`.
+ */
+export const frozenInitialValueForWire = (
+ variable: { key: string; initialValue?: string },
+ existingNonSecretKeys: ReadonlySet<string>
+): string =>
+ existingNonSecretKeys.has(variable.key) ? (variable.initialValue ?? "") : ""
diff --git a/packages/hoppscotch-common/src/helpers/utils/secretMask.ts b/packages/hoppscotch-common/src/helpers/utils/secretMask.ts
new file mode 100644
index 000000000..4fad5509e
--- /dev/null
+++ b/packages/hoppscotch-common/src/helpers/utils/secretMask.ts
@@ -0,0 +1,13 @@
+/**
+ * Masks a secret value for display by replacing it with `*` characters — one
+ * per character — so the mask length matches the value's length.
+ *
+ * An empty value is returned as an empty string rather than a mask, so callers
+ * can still tell an unset secret apart from a stored one (e.g. the env tooltip
+ * shows "Empty" instead of a mask).
+ *
+ * @param value - The raw secret value to mask. May be empty, `null`, or `undefined`.
+ * @returns A string of `*` the same length as `value`, or `""` when `value` is empty or nullish.
+ */
+export const maskSecretValue = (value?: string | null): string =>
+ "*".repeat(value?.length ?? 0)
diff --git a/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.ts b/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.ts
index 1d6a1c1d3..4c5d206aa 100644
--- a/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.ts
+++ b/packages/hoppscotch-common/src/lib/sync/collections/gqlCollections.sync.ts
@@ -27,7 +27,7 @@ import { getSyncInitFunction, StoreSyncDefinitionOf } from ".."
import { createMapper } from "../mapper"
import { applyDuplicatedCollectionResult, moveOrReorderRequests } from "./sync"
import { ReqType } from "~/helpers/backend/graphql"
-import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"
+import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
// gqlCollectionsMapper uses the collectionPath as the local identifier
// Helper function to transform HoppCollection to backend format
@@ -38,7 +38,7 @@ const transformCollectionForBackend = (collection: HoppCollection): any => {
authActive: true,
},
headers: collection.headers ?? [],
- variables: stripSecretVariableValuesForWire(collection.variables ?? []),
+ variables: stripClientLocalValuesForWire(collection.variables ?? []),
_ref_id: collection._ref_id,
}
@@ -72,7 +72,7 @@ const recursivelySyncCollections = async (
authActive: true,
},
headers: collection.headers ?? [],
- variables: stripSecretVariableValuesForWire(collection.variables ?? []),
+ variables: stripClientLocalValuesForWire(collection.variables ?? []),
_ref_id: collection._ref_id,
}
const res = await createGQLRootUserCollection(
@@ -118,7 +118,7 @@ const recursivelySyncCollections = async (
authActive: true,
},
headers: collection.headers ?? [],
- variables: stripSecretVariableValuesForWire(collection.variables ?? []),
+ variables: stripClientLocalValuesForWire(collection.variables ?? []),
_ref_id: collection._ref_id,
}
@@ -265,7 +265,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<
const data = {
auth: collection.auth,
headers: collection.headers,
- variables: stripSecretVariableValuesForWire(collection.variables),
+ variables: stripClientLocalValuesForWire(collection.variables),
_ref_id: collection._ref_id,
}
@@ -312,7 +312,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<
const data = {
auth: folder.auth,
headers: folder.headers,
- variables: stripSecretVariableValuesForWire(folder.variables),
+ variables: stripClientLocalValuesForWire(folder.variables),
_ref_id: folder._ref_id,
}
diff --git a/packages/hoppscotch-common/src/lib/sync/collections/import.ts b/packages/hoppscotch-common/src/lib/sync/collections/import.ts
index ef95b7dca..c1ff5b19f 100644
--- a/packages/hoppscotch-common/src/lib/sync/collections/import.ts
+++ b/packages/hoppscotch-common/src/lib/sync/collections/import.ts
@@ -9,8 +9,8 @@ import {
populateLocalStoresFromCollectionTree,
repopulateLoadedCollectionTree,
stripCollectionTreeForStore,
- stripSecretVariableValuesForWire,
-} from "~/helpers/secretVariables"
+ stripClientLocalValuesForWire,
+} from "~/helpers/clientLocalVariables"
import {
appendGraphqlCollections,
appendRESTCollections,
@@ -168,7 +168,7 @@ export function translateToPersonalCollectionFormat(x: HoppCollection) {
const data: CollectionDataProps = {
auth: x.auth,
headers: x.headers,
- variables: stripSecretVariableValuesForWire(x.variables ?? []),
+ variables: stripClientLocalValuesForWire(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,
diff --git a/packages/hoppscotch-common/src/lib/sync/collections/sync.ts b/packages/hoppscotch-common/src/lib/sync/collections/sync.ts
index fb40ea581..eb66acdc2 100644
--- a/packages/hoppscotch-common/src/lib/sync/collections/sync.ts
+++ b/packages/hoppscotch-common/src/lib/sync/collections/sync.ts
@@ -23,7 +23,7 @@ import {
import * as E from "fp-ts/Either"
import { ReqType, SortOptions } from "~/helpers/backend/graphql"
-import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"
+import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import {
editGraphqlCollection,
editGraphqlFolder,
@@ -51,7 +51,7 @@ const transformCollectionForBackend = (collection: HoppCollection): any => {
authActive: true,
},
headers: collection.headers ?? [],
- variables: stripSecretVariableValuesForWire(collection.variables ?? []),
+ variables: stripClientLocalValuesForWire(collection.variables ?? []),
_ref_id: collection._ref_id,
description: collection.description ?? null,
}
@@ -282,7 +282,7 @@ const recursivelySyncCollections = async (
authActive: true,
},
headers: collection.headers ?? [],
- variables: stripSecretVariableValuesForWire(collection.variables ?? []),
+ variables: stripClientLocalValuesForWire(collection.variables ?? []),
_ref_id: collection._ref_id,
description: collection.description ?? null,
}
@@ -327,7 +327,7 @@ const recursivelySyncCollections = async (
authActive: true,
},
headers: collection.headers ?? [],
- variables: stripSecretVariableValuesForWire(collection.variables ?? []),
+ variables: stripClientLocalValuesForWire(collection.variables ?? []),
_ref_id: collection._ref_id,
description: collection.description ?? null,
}
@@ -474,7 +474,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<
const data = {
auth: collection.auth,
headers: collection.headers,
- variables: stripSecretVariableValuesForWire(collection.variables),
+ variables: stripClientLocalValuesForWire(collection.variables),
_ref_id: collection._ref_id,
description: collection.description ?? null,
}
@@ -558,7 +558,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<
const data = {
auth: folder.auth,
headers: folder.headers,
- variables: stripSecretVariableValuesForWire(folder.variables),
+ variables: stripClientLocalValuesForWire(folder.variables),
_ref_id: folder._ref_id,
description: folder.description,
}
diff --git a/packages/hoppscotch-common/src/lib/sync/environments/sync.ts b/packages/hoppscotch-common/src/lib/sync/environments/sync.ts
index 6e7af09f0..7cbf28d4e 100644
--- a/packages/hoppscotch-common/src/lib/sync/environments/sync.ts
+++ b/packages/hoppscotch-common/src/lib/sync/environments/sync.ts
@@ -8,7 +8,7 @@ import { getSettingSubject, settingsStore } from "~/newstore/settings"
import * as E from "fp-ts/Either"
import { Environment } from "@hoppscotch/data"
-import { stripSecretVariableValuesForWire } from "~/helpers/secretVariables"
+import { stripClientLocalValuesForWire } from "~/helpers/clientLocalVariables"
import { getService } from "~/modules/dioc"
import { CurrentValueService } from "~/services/current-environment-value.service"
import { SecretEnvironmentService } from "~/services/secret-environment.service"
@@ -47,7 +47,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<
try {
const res = await createUserEnvironment(
name,
- JSON.stringify(stripSecretVariableValuesForWire(variables))
+ JSON.stringify(stripClientLocalValuesForWire(variables))
)
if (E.isRight(res)) {
@@ -87,9 +87,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<
// invariant can't rely on callers.
const res = await createUserEnvironment(
env.name,
- JSON.stringify(
- stripSecretVariableValuesForWire(env.variables ?? [])
- )
+ JSON.stringify(stripClientLocalValuesForWire(env.variables ?? []))
)
if (E.isRight(res)) {
@@ -134,9 +132,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<
const res = await createUserEnvironment(
`${environmentToDuplicate.name} - Duplicate`,
JSON.stringify(
- stripSecretVariableValuesForWire(
- environmentToDuplicate.variables ?? []
- )
+ stripClientLocalValuesForWire(environmentToDuplicate.variables ?? [])
)
)
@@ -158,7 +154,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<
backendId,
updatedEnv.name,
JSON.stringify(
- stripSecretVariableValuesForWire(updatedEnv.variables ?? [])
+ stripClientLocalValuesForWire(updatedEnv.variables ?? [])
)
)()
}
@@ -189,7 +185,7 @@ export const storeSyncDefinition: StoreSyncDefinitionOf<
}
const payload = JSON.stringify({
v: 2,
- variables: stripSecretVariableValuesForWire(variables),
+ variables: stripClientLocalValuesForWire(variables),
})
// Feature-detect a platform-provided global-env updater. Newer
// backends (cloud) split the global update into a dedicated
diff --git a/packages/hoppscotch-common/src/pages/import.vue b/packages/hoppscotch-common/src/pages/import.vue
index f51b7f237..851fa1cbe 100644
--- a/packages/hoppscotch-common/src/pages/import.vue
+++ b/packages/hoppscotch-common/src/pages/import.vue
@@ -18,7 +18,7 @@ import {
ensureRefIds,
populateLocalStoresFromCollectionTree,
stripCollectionTreeForStore,
-} from "~/helpers/secretVariables"
+} from "~/helpers/clientLocalVariables"
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
import { IMPORTER_INVALID_FILE_FORMAT } from "~/helpers/import-export/import"
diff --git a/packages/hoppscotch-common/src/pages/view/_id/_version.vue b/packages/hoppscotch-common/src/pages/view/_id/_version.vue
index ea93548eb..40374dbb7 100644
--- a/packages/hoppscotch-common/src/pages/view/_id/_version.vue
+++ b/packages/hoppscotch-common/src/pages/view/_id/_version.vue
@@ -247,14 +247,9 @@ const fetchDocs = async (docId: string, version: string) => {
const parsed =
typeof rawEnvVars === "string" ? JSON.parse(rawEnvVars) : rawEnvVars
if (Array.isArray(parsed)) {
- parsedEnvironmentVariables.value = parsed.map((v) => {
- const normalized = translateToNewEnvironmentVariables(v)
- // Ensure currentValue falls back to initialValue
- return {
- ...normalized,
- currentValue: normalized.currentValue || normalized.initialValue,
- }
- })
+ parsedEnvironmentVariables.value = parsed.map((v) =>
+ translateToNewEnvironmentVariables(v)
+ )
}
} catch (e) {
console.error("Error parsing environment variables:", e)
diff --git a/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/environment.inspector.spec.ts b/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/environment.inspector.spec.ts
index a5e63383c..4e5f9a8a0 100644
--- a/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/environment.inspector.spec.ts
+++ b/packages/hoppscotch-common/src/services/inspection/inspectors/__tests__/environment.inspector.spec.ts
@@ -5,6 +5,7 @@ import { InspectionService } from "../../index"
import { getDefaultRESTRequest } from "~/helpers/rest/default"
import { ref } from "vue"
import { CurrentValueService } from "~/services/current-environment-value.service"
+import { SecretEnvironmentService } from "~/services/secret-environment.service"
vi.mock("~/modules/i18n", () => ({
__esModule: true,
@@ -29,6 +30,12 @@ vi.mock("~/newstore/environments", async () => {
initialValue: "",
secret: false,
},
+ {
+ key: "SECRET_ENV_VAR",
+ currentValue: "",
+ initialValue: "",
+ secret: true,
+ },
]),
getCurrentEnvironment: () => ({
id: "1",
@@ -365,5 +372,41 @@ describe("EnvironmentInspectorService", () => {
expect(result.value).toHaveLength(0)
})
+
+ it("should not flag a secret variable whose current value is empty but has an initial value", () => {
+ const container = new TestContainer()
+ container.bindMock(SecretEnvironmentService, {
+ hasSecretValue: vi.fn(() => false),
+ hasSecretInitialValue: vi.fn(() => true),
+ })
+ const envInspector = container.bind(EnvironmentInspectorService)
+
+ const req = ref({
+ ...getDefaultRESTRequest(),
+ endpoint: "<<SECRET_ENV_VAR>>",
+ })
+
+ const result = envInspector.getInspections(req)
+
+ expect(result.value).toHaveLength(0)
+ })
+
+ it("should flag a secret variable that has neither a current nor an initial value", () => {
+ const container = new TestContainer()
+ container.bindMock(SecretEnvironmentService, {
+ hasSecretValue: vi.fn(() => false),
+ hasSecretInitialValue: vi.fn(() => false),
+ })
+ const envInspector = container.bind(EnvironmentInspectorService)
+
+ const req = ref({
+ ...getDefaultRESTRequest(),
+ endpoint: "<<SECRET_ENV_VAR>>",
+ })
+
+ const result = envInspector.getInspections(req)
+
+ expect(result.value).toHaveLength(1)
+ })
})
})
diff --git a/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts b/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts
index f9f41c7b1..6a23642ed 100644
--- a/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts
+++ b/packages/hoppscotch-common/src/services/inspection/inspectors/environment.inspector.ts
@@ -13,7 +13,6 @@ import {
HoppRESTResponseOriginalRequest,
} from "@hoppscotch/data"
import {
- AggregateEnvironment,
aggregateEnvsWithCurrentValue$,
getCurrentEnvironment,
getSelectedEnvironmentType,
@@ -23,7 +22,10 @@ import { useStreamStatic } from "~/composables/stream"
import { SecretEnvironmentService } from "~/services/secret-environment.service"
import { RESTTabService } from "~/services/tab/rest"
import { CurrentValueService } from "~/services/current-environment-value.service"
-import { getEffectiveVariablesForRequest } from "~/helpers/utils/environments"
+import {
+ getEffectiveVariablesForRequest,
+ filterNonEmptyEnvironmentVariables,
+} from "~/helpers/utils/environments"
import { HOPP_ENVIRONMENT_REGEX } from "~/helpers/environment-regex"
const isENVInString = (str: string) => HOPP_ENVIRONMENT_REGEX.test(str)
@@ -146,31 +148,6 @@ export class EnvironmentInspectorService extends Service implements Inspector {
return newErrors
}
- /**
- * Keeps only unique environment variables and prefers ones with values.
- * @param envs The environment list to be transformed
- * @returns The transformed environment list with keys with value
- */
- private filterNonEmptyEnvironmentVariables = (
- envs: AggregateEnvironment[]
- ): AggregateEnvironment[] => {
- const envsMap = new Map<string, AggregateEnvironment>()
-
- envs.forEach((env) => {
- if (envsMap.has(env.key)) {
- const existingEnv = envsMap.get(env.key)
- // Replace if existing is empty and this one has a value
- if (existingEnv?.currentValue === "" && env.currentValue !== "") {
- envsMap.set(env.key, env)
- }
- } else {
- envsMap.set(env.key, env)
- }
- })
-
- return Array.from(envsMap.values())
- }
-
/**
* Looks for variables that exist but are empty (no value or secret).
* Suggests adding a value for them.
@@ -202,7 +179,7 @@ export class EnvironmentInspectorService extends Service implements Inspector {
// request → collection → environment, matching the request runner's
// precedence and non-empty resolution (single source of truth)
- const environmentVariables = this.filterNonEmptyEnvironmentVariables(
+ const environmentVariables = filterNonEmptyEnvironmentVariables(
getEffectiveVariablesForRequest(
currentTabRequest?.requestVariables,
currentTab.document.type === "request" ||
@@ -223,10 +200,12 @@ export class EnvironmentInspectorService extends Service implements Inspector {
? env.sourceEnvID!
: currentSelectedEnvironment.id
- const hasSecretEnv = this.secretEnvs.hasSecretValue(
- sourceEnvID,
- env.key
- )
+ // A secret counts as "has a value" when either its current or its
+ // initial secret value is set — the initial value is the resolution
+ // fallback, so an empty current value alone isn't an empty variable.
+ const hasSecretEnv =
+ this.secretEnvs.hasSecretValue(sourceEnvID, env.key) ||
+ this.secretEnvs.hasSecretInitialValue(sourceEnvID, env.key)
const hasValue =
this.currentEnvs.hasValue(
diff --git a/packages/hoppscotch-data/src/environment/index.ts b/packages/hoppscotch-data/src/environment/index.ts
index a00e4cfb3..b08473dc5 100644
--- a/packages/hoppscotch-data/src/environment/index.ts
+++ b/packages/hoppscotch-data/src/environment/index.ts
@@ -52,6 +52,20 @@ const ENV_EXPAND_LOOP = "ENV_EXPAND_LOOP" as const
export const EnvironmentSchemaVersion = 2
+/**
+ * Resolves the effective value of an environment variable while expanding
+ * `<<var>>` templates: the current value is what's in use, but an empty current
+ * value falls back to the initial value (which acts as the default).
+ *
+ * This is the single place the current→initial fallback lives for execution /
+ * resolution. Surfaces that display the raw current value must NOT go through
+ * here — they read `currentValue` directly so an empty value stays empty.
+ */
+const getResolvedVariableValue = (variable: {
+ currentValue?: string
+ initialValue?: string
+}): string => variable.currentValue || variable.initialValue || ""
+
export function parseBodyEnvVariablesE(
body: string,
env: Environment["variables"]
@@ -75,7 +89,7 @@ export function parseBodyEnvVariablesE(
const foundEnv = env.find((envVar) => envVar.key === variableName)
if (foundEnv && "currentValue" in foundEnv) {
- return foundEnv.currentValue
+ return getResolvedVariableValue(foundEnv)
}
return key
})
@@ -135,6 +149,9 @@ export function parseTemplateStringE(
const variable = variables.find((x) => x && x.key === p1)
if (variable && "currentValue" in variable) {
+ // Current value in use, falling back to the initial value when empty.
+ const resolvedValue = getResolvedVariableValue(variable)
+
// Show the key if it is a secret and explicitly specified
if (variable.secret && showKeyIfSecret) {
isSecret = true
@@ -142,18 +159,9 @@ export function parseTemplateStringE(
}
// Mask the value if it is a secret and explicitly specified
if (variable.secret && maskValue) {
- return "*".repeat(
- (
- variable as {
- secret: true
- initialValue: string
- currentValue: string
- key: string
- }
- ).currentValue.length
- )
+ return "*".repeat(resolvedValue.length)
}
- return variable.currentValue
+ return resolvedValue
}
if (showKeyIfNotFound) {