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
feat(sh-admin): surface which config fields block saving (#6385)
Nivedinafc98e99574f
diff --git a/packages/hoppscotch-sh-admin/src/components/settings/AuthConfigurations.vue b/packages/hoppscotch-sh-admin/src/components/settings/AuthConfigurations.vueindex 6ba2318f0..560f49971 100644--- a/packages/hoppscotch-sh-admin/src/components/settings/AuthConfigurations.vue+++ b/packages/hoppscotch-sh-admin/src/components/settings/AuthConfigurations.vue@@ -13,6 +13,8 @@<HoppSmartTabid="auth-providers":label="t('configs.auth_providers.oauth')"+ :indicator="subTabHasError('auth-providers')"+ indicator-variant="error"><div class="pb-8 px-4"><SettingsOAuthProviderConfigurations@@ -62,7 +64,12 @@</div></HoppSmartTab>- <HoppSmartTab id="token" :label="t('configs.auth_providers.token.title')">+ <HoppSmartTab+ id="token"+ :label="t('configs.auth_providers.token.title')"+ :indicator="subTabHasError('token')"+ indicator-variant="error"+ ><div class="pb-8 px-4"><SettingsAuthToken v-model:config="workingConfigs" /></div>@@ -75,10 +82,20 @@import { useVModel } from '@vueuse/core';import { computed, onMounted, ref } from 'vue';import { useI18n } from '~/composables/i18n';-import { ServerConfigs } from '~/helpers/configs';+import {+ ConfigSubTab,+ ServerConfigs,+ tabHasConfigIssue,+ useConfigValidation,+} from '~/helpers/configs';const t = useI18n();+const { configValidationIssues } = useConfigValidation();++const subTabHasError = (subTab: ConfigSubTab) =>+ tabHasConfigIssue(configValidationIssues.value, 'auth', subTab);+const props = defineProps<{config: ServerConfigs;}>();@@ -95,7 +112,7 @@ const workingConfigs = useVModel(props, 'config', emit);// Check if SMTP is activated but not saved yet. Used to track if SMTP was enabled after the last save.const isSMTPActivated = computed(- () => workingConfigs.value?.mailConfigs.enabled ?? false+ () => workingConfigs.value?.mailConfigs.enabled ?? false,);// Check if Email authentication is enableddiff --git a/packages/hoppscotch-sh-admin/src/components/settings/AuthToken.vue b/packages/hoppscotch-sh-admin/src/components/settings/AuthToken.vueindex 3749bd471..59bd8aa53 100644--- a/packages/hoppscotch-sh-admin/src/components/settings/AuthToken.vue+++ b/packages/hoppscotch-sh-admin/src/components/settings/AuthToken.vue@@ -32,6 +32,9 @@placeholder="e.g., your-secret-key":autofocus="false"class="!my-2 !bg-primaryLight flex-1 border border-divider rounded"+ :class="{+ '!border-red-500': isConfigFieldErrored('token', 'jwt_secret'),+ }"input-styles="!border-0 ":type="isMasked('jwt_secret') ? 'password' : 'text'">@@ -53,6 +56,11 @@placeholder="e.g., 10 (salt complexity)":autofocus="false"class="!my-2 !bg-primaryLight flex-1"+ :input-styles="+ isConfigFieldErrored('token', 'token_salt_complexity')+ ? '!border-red-500'+ : ''+ "type="number"@update:model-value="validateNumberValue(@@ -70,6 +78,11 @@placeholder="e.g., 3 (in hour)":autofocus="false"class="!my-2 !bg-primaryLight flex-1"+ :input-styles="+ isConfigFieldErrored('token', 'magic_link_token_validity')+ ? '!border-red-500'+ : ''+ "type="number"@update:model-value="validateNumberValue(@@ -87,6 +100,11 @@placeholder="e.g., 604800000 (in milliseconds)":autofocus="false"class="!my-2 !bg-primaryLight flex-1"+ :input-styles="+ isConfigFieldErrored('token', 'refresh_token_validity')+ ? '!border-red-500'+ : ''+ "type="number"@update:model-value="validateNumberValue(@@ -104,6 +122,11 @@placeholder="e.g., 86400000 (in milliseconds)":autofocus="false"class="!my-2 !bg-primaryLight flex-1"+ :input-styles="+ isConfigFieldErrored('token', 'access_token_validity')+ ? '!border-red-500'+ : ''+ "type="number"@update:model-value="validateNumberValue(@@ -122,6 +145,10 @@:autofocus="false"input-styles="!border-0 "class="!my-2 !bg-primaryLight flex-1 border border-divider rounded"+ :class="{+ '!border-red-500':+ isConfigFieldErrored('token', 'session_secret'),+ }":type="isMasked('session_secret') ? 'password' : 'text'"><template #button>@@ -142,6 +169,10 @@placeholder="e.g., connect_sid":autofocus="false"class="!my-2 !bg-primaryLight flex-1 border border-divider rounded"+ :class="{+ '!border-red-500':+ isConfigFieldErrored('token', 'session_cookie_name'),+ }"/><p class="my-1 text-secondaryLight">{{ t('configs.auth_providers.token.session_cookie_name_help') }}@@ -159,7 +190,11 @@import { useVModel } from '@vueuse/core';import { computed, ref } from 'vue';import { useI18n } from '~/composables/i18n';-import { ServerConfigs } from '~/helpers/configs';+import {+ ServerConfigs,+ isNotValidNumber,+ useConfigValidation,+} from '~/helpers/configs';import IconHelpCircle from '~icons/lucide/help-circle';import IconEye from '~icons/lucide/eye';import IconEyeOff from '~icons/lucide/eye-off';@@ -168,6 +203,8 @@ import { useToast } from '~/composables/toast';const t = useI18n();const toast = useToast();+const { isConfigFieldErrored } = useConfigValidation();+const props = defineProps<{config: ServerConfigs;}>();@@ -195,9 +232,12 @@ const toggleMask = (fieldKey: string) => {const isMasked = (fieldKey: string) => maskState.value[fieldKey];+// Reuse the save-guard validator (isNotValidNumber) so the inline toast and the+// save block agree: these numeric token fields must be positive integers (>= 1).+// parseInt would accept "1.5" (→ 1) and pass silently here, only for the save to+// be blocked later. Only the numeric fields call this; the secret inputs aren't.const validateNumberValue = (value: string | number) => {- const num = typeof value === 'string' ? parseInt(value, 10) : value;- if (isNaN(num) || num <= 0) {+ if (isNotValidNumber(value)) {toast.error(t('configs.invalid_number'));}};diff --git a/packages/hoppscotch-sh-admin/src/components/settings/OAuthProviderConfigurations.vue b/packages/hoppscotch-sh-admin/src/components/settings/OAuthProviderConfigurations.vueindex aa11a9840..115495def 100644--- a/packages/hoppscotch-sh-admin/src/components/settings/OAuthProviderConfigurations.vue+++ b/packages/hoppscotch-sh-admin/src/components/settings/OAuthProviderConfigurations.vue@@ -52,6 +52,12 @@":autofocus="false"class="!my-2 !bg-primaryLight flex-1 border border-divider rounded"+ :class="{+ '!border-red-500': isConfigFieldErrored(+ provider.name,+ field.key,+ ),+ }"input-styles="!border-0"><template #button>@@ -80,7 +86,11 @@import { useVModel } from '@vueuse/core';import { reactive } from 'vue';import { useI18n } from '~/composables/i18n';-import { ServerConfigs, SsoAuthProviders } from '~/helpers/configs';+import {+ ServerConfigs,+ SsoAuthProviders,+ useConfigValidation,+} from '~/helpers/configs';import { makeReadableKey } from '~/helpers/utils/readableKey';import IconCircleHelp from '~icons/lucide/circle-help';import IconEye from '~icons/lucide/eye';@@ -88,6 +98,8 @@ import IconEyeOff from '~icons/lucide/eye-off';const t = useI18n();+const { isConfigFieldErrored } = useConfigValidation();+const props = defineProps<{config: ServerConfigs;}>();diff --git a/packages/hoppscotch-sh-admin/src/components/settings/ProxyURLConfiguration.vue b/packages/hoppscotch-sh-admin/src/components/settings/ProxyURLConfiguration.vueindex c303feb2c..d817f055a 100644--- a/packages/hoppscotch-sh-admin/src/components/settings/ProxyURLConfiguration.vue+++ b/packages/hoppscotch-sh-admin/src/components/settings/ProxyURLConfiguration.vue@@ -19,6 +19,11 @@:placeholder="t('configs.proxy_url_configs.url_placeholder')":autofocus="false"class="!my-2 !bg-primaryLight w-full max-w-xs"+ :input-styles="+ isConfigFieldErrored('proxy', 'proxy_app_url')+ ? '!border-red-500'+ : ''+ "/><HoppButtonSecondary@@ -46,17 +51,20 @@<script setup lang="ts">import { useVModel } from '@vueuse/core';-import { computed, watch } from 'vue';+import { computed } from 'vue';import { useI18n } from '~/composables/i18n';import {- hasInputValidationFailed,+ isFieldEmpty,isValidProxyUrl,ServerConfigs,+ useConfigValidation,} from '~/helpers/configs';import IconHelpCircle from '~icons/lucide/help-circle';const t = useI18n();+const { isConfigFieldErrored } = useConfigValidation();+const props = defineProps<{config: ServerConfigs;}>();@@ -76,16 +84,14 @@ const proxyConfigs = computed({},});-// Input Validation — uses the shared regex helper so the UI accepts exactly-// what the backend's validateUrl will (and what the kernel store will persist).-// Empty is also flagged here so the inline error banner appears in-context,-// matching the app-side Proxy.vue behavior. AreAnyConfigFieldsEmpty still-// blocks save for empty, but this gives the user a visible field-level signal.+// Drives the inline "invalid format" banner, mirroring the save guard's format+// branch: only a non-empty, malformed URL is flagged. An empty value is a+// "required" issue, so the banner stays hidden — even on a fresh, untouched load.const fieldErrors = computed(() => {const errors: Record<string, boolean> = {};const value = proxyConfigs.value?.fields.proxy_app_url ?? '';- errors.proxy_app_url = !isValidProxyUrl(value);+ errors.proxy_app_url = !isFieldEmpty(value) && !isValidProxyUrl(value);return errors;});@@ -93,16 +99,4 @@ const fieldErrors = computed(() => {const getFieldError = (fieldKey: keyof ServerConfigs['proxyUrlConfigs']['fields'],) => fieldErrors.value[fieldKey];--// `immediate: true` so a pre-existing invalid stored value (e.g. junk left-// over from earlier flows) flags the global save guard on mount, not just-// after the user re-types the field.-watch(- fieldErrors,- (errors) => {- hasInputValidationFailed.value.proxyUrl =- Object.values(errors).some(Boolean);- },- { immediate: true },-);</script>diff --git a/packages/hoppscotch-sh-admin/src/components/settings/RateLimit.vue b/packages/hoppscotch-sh-admin/src/components/settings/RateLimit.vueindex 874f483e6..d6afd29d7 100644--- a/packages/hoppscotch-sh-admin/src/components/settings/RateLimit.vue+++ b/packages/hoppscotch-sh-admin/src/components/settings/RateLimit.vue@@ -33,6 +33,11 @@placeholder="e.g., 60 (in seconds)":autofocus="false"class="!my-2 !bg-primaryLight flex-1"+ :input-styles="+ isConfigFieldErrored('rate_limit', 'rate_limit_ttl')+ ? '!border-red-500'+ : ''+ "@update:model-value="validateNumberValue(rateLimitConfig.fields.rate_limit_ttl)"@@ -45,6 +50,11 @@placeholder="e.g., 100 (requests per TTL)":autofocus="false"class="!my-2 !bg-primaryLight flex-1"+ :input-styles="+ isConfigFieldErrored('rate_limit', 'rate_limit_max')+ ? '!border-red-500'+ : ''+ "@update:model-value="validateNumberValue(rateLimitConfig.fields.rate_limit_max)"@@ -63,12 +73,18 @@ import { useVModel } from '@vueuse/core';import { computed } from 'vue';import { useI18n } from '~/composables/i18n';import { useToast } from '~/composables/toast';-import { ServerConfigs } from '~/helpers/configs';+import {+ ServerConfigs,+ isNotValidNumber,+ useConfigValidation,+} from '~/helpers/configs';import IconHelpCircle from '~icons/lucide/help-circle';const t = useI18n();const toast = useToast();+const { isConfigFieldErrored } = useConfigValidation();+const props = defineProps<{config: ServerConfigs;}>();@@ -85,9 +101,11 @@ const rateLimitConfig = computed({set: (value) => (workingConfigs.value.rateLimitConfigs = value),});+// Reuse the save-guard validator so the inline toast and the save block agree:+// rate-limit values must be positive integers (>= 1). parseInt would accept+// "1.5" (→ 1) and pass silently here, only for the save to be blocked later.const validateNumberValue = (value: string | number) => {- const num = typeof value === 'string' ? parseInt(value, 10) : value;- if (isNaN(num) || num <= 0) {+ if (isNotValidNumber(value)) {toast.error(t('configs.invalid_number'));}};diff --git a/packages/hoppscotch-sh-admin/src/components/settings/SmtpConfiguration.vue b/packages/hoppscotch-sh-admin/src/components/settings/SmtpConfiguration.vueindex ad4648446..5a4a8a024 100644--- a/packages/hoppscotch-sh-admin/src/components/settings/SmtpConfiguration.vue+++ b/packages/hoppscotch-sh-admin/src/components/settings/SmtpConfiguration.vue@@ -61,6 +61,12 @@:type="isMasked(field.key) ? 'password' : 'text'":autofocus="false"class="!my-2 !bg-primaryLight flex-1 border border-divider rounded"+ :class="{+ '!border-red-500': isConfigFieldErrored(+ 'email',+ field.key,+ ),+ }"input-styles="!border-0"><template #button>@@ -99,6 +105,11 @@:type="isMasked(field.key) ? 'password' : 'text'":autofocus="false"class="!my-2 !bg-primaryLight flex-1 border border-divider rounded"+ :class="{+ '!border-red-500': isConfigFieldErrored(+ 'email', field.key,+ ),+ }"input-styles="!border-0"><template #button>@@ -122,6 +133,12 @@:type="isMasked('mailer_from_address') ? 'password' : 'text'":autofocus="false"class="!my-2 !bg-primaryLight flex-1 border border-divider rounded"+ :class="{+ '!border-red-500': isConfigFieldErrored(+ 'email',+ 'mailer_from_address',+ ),+ }"input-styles="!border-0"><template #button>@@ -156,6 +173,11 @@:type="isMasked(field.key) ? 'password' : 'text'":autofocus="false"class="!my-2 !bg-primaryLight flex-1 border border-divider rounded"+ :class="{+ '!border-red-500': isConfigFieldErrored(+ 'email', field.key,+ ),+ }"input-styles="!border-0"><template #button>@@ -187,6 +209,11 @@:type="isMasked(field.key) ? 'password' : 'text'":autofocus="false"class="!my-2 !bg-primaryLight flex-1 border border-divider rounded"+ :class="{+ '!border-red-500': isConfigFieldErrored(+ 'email', field.key,+ ),+ }"input-styles="!border-0"><template #button>@@ -236,10 +263,14 @@<script setup lang="ts">import { useVModel } from '@vueuse/core';-import { computed, reactive, watch } from 'vue';+import { computed, reactive } from 'vue';import { useI18n } from '~/composables/i18n';import { useSmtpAuthTypeSwitch } from '~/composables/useSmtpAuthTypeSwitch';-import { hasInputValidationFailed, ServerConfigs } from '~/helpers/configs';+import {+ isFieldEmpty,+ ServerConfigs,+ useConfigValidation,+} from '~/helpers/configs';import IconEye from '~icons/lucide/eye';import IconEyeOff from '~icons/lucide/eye-off';import IconHelpCircle from '~icons/lucide/help-circle';@@ -248,6 +279,8 @@ import IconShield from '~icons/lucide/shield';const t = useI18n();+const { isConfigFieldErrored } = useConfigValidation();+const props = defineProps<{config: ServerConfigs;}>();@@ -377,12 +410,16 @@ const isMasked = (fieldKey: keyof ServerConfigs['mailConfigs']['fields']) =>const toggleCheckbox = (field: CheckboxField) =>(smtpConfigs.value.fields[field.key] = !smtpConfigs.value.fields[field.key]);-// Input Validation+// Drives the inline banner on the SMTP URL. Border + save guard read from+// getConfigValidationIssues (helpers/configs), same rule.const fieldErrors = computed(() => {const errors: Record<string, boolean> = {};- if (smtpConfigs.value?.fields.mailer_smtp_url) {- const value = smtpConfigs.value.fields.mailer_smtp_url;+ const value = smtpConfigs.value?.fields.mailer_smtp_url;+ // Reuse the single-source isFieldEmpty so the banner's notion of "empty"+ // (whitespace-only included) stays identical to getConfigValidationIssues —+ // a truthiness test would flag ' ' and disagree with the save guard.+ if (value && !isFieldEmpty(value)) {errors.mailer_smtp_url =!value.startsWith('smtp://') && !value.startsWith('smtps://');}@@ -392,10 +429,6 @@ const fieldErrors = computed(() => {const getFieldError = (fieldKey: StringFieldKey) => fieldErrors.value[fieldKey];-watch(fieldErrors, (errors) => {- hasInputValidationFailed.value.smtpUrl = Object.values(errors).some(Boolean);-});-const LOGIN_KEYS: StringFieldKey[] = ['mailer_smtp_user','mailer_smtp_password',diff --git a/packages/hoppscotch-sh-admin/src/composables/useConfigHandler.ts b/packages/hoppscotch-sh-admin/src/composables/useConfigHandler.tsindex 47e14b4b5..596d10665 100644--- a/packages/hoppscotch-sh-admin/src/composables/useConfigHandler.ts+++ b/packages/hoppscotch-sh-admin/src/composables/useConfigHandler.ts@@ -20,7 +20,6 @@ import {import {ALL_CONFIGS,CUSTOM_MAIL_CONFIGS,- ConfigSection,ConfigTransform,GITHUB_CONFIGS,GOOGLE_CONFIGS,@@ -29,19 +28,14 @@ import {MOCK_SERVER_CONFIGS,PROXY_URL_CONFIGS,ServerConfigs,- TOKEN_VALIDATION_CONFIGS,UpdatedConfigs,+ isFieldEmpty,+ isValidSessionCookieName,} from '~/helpers/configs';import { getCompiledErrorMessage } from '~/helpers/errors';import { useToast } from './toast';import { useClientHandler } from './useClientHandler';-const COOKIE_NAME_REGEX = /^[A-Za-z0-9_-]+$/;--const OPTIONAL_TOKEN_FIELD_KEYS = new Set(- TOKEN_VALIDATION_CONFIGS.filter((cfg) => cfg.optional).map((cfg) => cfg.key)-);-/** Composable that handles all operations related to server configurations* @param updatedConfigs A Config Object containing the updated configs*/@@ -230,148 +224,6 @@ export function useConfigHandler(updatedConfigs?: ServerConfigs) {const isCustomMailConfigEnabled =updatedConfigs?.mailConfigs.fields.mailer_use_custom_configs;- /*- Check if any of the config fields are empty- */- const isFieldEmpty = (field: string | boolean) => {- if (typeof field === 'boolean' || typeof field === 'number') {- return false;- }- return field.trim() === '';- };-- /**- * This is used to validate number fields, ensuring they are not NaN or less than or equal to zero.- * It checks if the field is a number or a numeric string, and returns true if it is not valid.- * @param field Field value to validate- * @returns Boolean indicating if the field is not valid- */- const isNotValidNumber = (field: string | boolean | number) => {- if (typeof field === 'boolean') {- return false;- }-- // Accept numbers or numeric strings (e.g., "1000"), but not non-numeric strings (e.g., "abc")- if (typeof field === 'number') {- return isNaN(field);- }-- if (typeof field === 'string') {- // Trim and check if the string is a valid number- const trimmed = field.trim();- if (trimmed === '') return true;- return isNaN(Number(trimmed));- }-- return true;- };-- /**- * Check if the field is not valid- * This is used to validate number fields, ensuring they are not NaN or less than or equal to zero.- * @param field Field value to validate- * @returns Boolean indicating if the field is valid- */- const isFieldNotValid = (field: string | boolean) => {- if (typeof field === 'boolean') {- return false;- }-- const num = Number(field);- if (isNaN(num) && typeof field === 'string') {- return field.trim() === '';- }-- return num <= 0;- };-- const AreAnyConfigFieldsEmpty = (config: ServerConfigs): boolean => {- const sections: Array<ConfigSection> = [- config.providers.github,- config.providers.google,- config.providers.microsoft,- config.mailConfigs,- config.rateLimitConfigs,- config.tokenConfigs,- config.proxyUrlConfigs,- ];-- const hasSectionWithEmptyFields = sections.some((section) => {- if (section.name === 'email') {- const { mailer_use_custom_configs, ...otherFields } = section.fields;-- // SMTP user and password are optional as a pair (both or neither)- const optionalMailerKeys = ['mailer_smtp_user', 'mailer_smtp_password'];- // OAuth2 fields are always optional and auth_type has a default- const oauth2Keys = [- 'mailer_smtp_auth_type',- 'mailer_smtp_oauth2_user',- 'mailer_smtp_oauth2_client_id',- 'mailer_smtp_oauth2_client_secret',- 'mailer_smtp_oauth2_refresh_token',- 'mailer_smtp_oauth2_access_url',- ];- const excludeKeys = mailer_use_custom_configs- ? ['mailer_smtp_url', ...optionalMailerKeys, ...oauth2Keys]- : [- 'mailer_smtp_host',- 'mailer_smtp_port',- 'mailer_smtp_user',- 'mailer_smtp_password',- ...oauth2Keys,- ];-- return (- section.enabled &&- Object.entries(otherFields).some(- ([key, value]) =>- isFieldEmpty(value) && !excludeKeys.includes(key)- )- );- }-- // This section has no enabled property, so we check fields directly- // for a valid number (>0) or non-empty string- if (section.name === 'token') {- return Object.entries(section.fields).some(- ([key, value]) =>- !OPTIONAL_TOKEN_FIELD_KEYS.has(key) && isFieldNotValid(value)- );- }-- // For rate limit section, we want to check if the values are not valid numbers- // and not empty strings- if (section.name === 'rate_limit')- return Object.values(section.fields).some(isNotValidNumber);-- // Proxy URL section has no enabled toggle; ensure it isn't left empty- if (section.name === 'proxy_app_url')- return Object.values(section.fields).some(isFieldEmpty);-- return (- section.enabled && Object.values(section.fields).some(isFieldEmpty)- );- });-- return hasSectionWithEmptyFields;- };-- const hasPartialSmtpCredentials = (config: ServerConfigs): boolean => {- if (!config.mailConfigs.enabled) return false;-- const fields = config.mailConfigs.fields;- if (!fields.mailer_use_custom_configs) return false;-- // Enforced regardless of auth_type: the backend validates the pair- // on every save, so stale login values left behind after switching- // to the OAuth2 tab would still be rejected. Surface this in the FE- // toast so users know to clear those fields before saving.- const hasUser = fields.mailer_smtp_user.trim() !== '';- const hasPass = fields.mailer_smtp_password.trim() !== '';-- return hasUser !== hasPass;- };-// Extract the mail config fields (excluding the custom mail config fields)const mailConfigFields = Object.fromEntries(Object.entries(updatedConfigs?.mailConfigs.fields ?? {}).filter(([key]) => {@@ -655,8 +507,8 @@ export function useConfigHandler(updatedConfigs?: ServerConfigs) {const sessionCookieName = String(updatedConfigs?.tokenConfigs.fields.session_cookie_name || '');- // Validate cookie name: allow empty (falls back to default), else enforce pattern- if (sessionCookieName && !COOKIE_NAME_REGEX.test(sessionCookieName)) {+ // Keep save-time toast behavior aligned with proactive validation.+ if (sessionCookieName && !isValidSessionCookieName(sessionCookieName)) {toast.error(t('configs.auth_providers.token.session_cookie_name_invalid'));return false;}@@ -727,7 +579,5 @@ export function useConfigHandler(updatedConfigs?: ServerConfigs) {fetchingAllowedAuthProviders,infraConfigsError,allowedAuthProvidersError,- AreAnyConfigFieldsEmpty,- hasPartialSmtpCredentials,};}diff --git a/packages/hoppscotch-sh-admin/src/helpers/configs.ts b/packages/hoppscotch-sh-admin/src/helpers/configs.tsindex eb05938be..10cc70b84 100644--- a/packages/hoppscotch-sh-admin/src/helpers/configs.ts+++ b/packages/hoppscotch-sh-admin/src/helpers/configs.ts@@ -1,17 +1,6 @@-import { ref } from 'vue';+import { inject, provide, ref, type InjectionKey, type Ref } from 'vue';import { InfraConfigEnum } from './backend/graphql';-export type InputValidationStatus = {- proxyUrl: boolean;- smtpUrl: boolean;-};--// Check if any input validation has failed-export const hasInputValidationFailed = ref<InputValidationStatus>({- proxyUrl: false,- smtpUrl: false,-});-export type SsoAuthProviders = 'google' | 'microsoft' | 'github';export type ServerConfigs = {@@ -140,6 +129,10 @@ export type Config = {key: string;// Marks fields that are optional and should be excluded from mandatory validationoptional?: boolean;+ // Marks free-form secret strings (e.g. JWT/session secrets). Validated as+ // non-empty only — never coerced to a number — so a numeric-looking secret+ // like "0" or "1.5" stays valid (the backend stores these as opaque strings).+ secret?: boolean;};export const GOOGLE_CONFIGS: Config[] = [@@ -305,10 +298,12 @@ export const TOKEN_VALIDATION_CONFIGS: Config[] = [{name: InfraConfigEnum.JwtSecret,key: 'jwt_secret',+ secret: true,},{name: InfraConfigEnum.SessionSecret,key: 'session_secret',+ secret: true,},{name: InfraConfigEnum.SessionCookieName,@@ -354,6 +349,12 @@ export const PROXY_URL_REGEX = /^(http|https):\/\/[^ "]+$/;export const isValidProxyUrl = (value: string): boolean =>PROXY_URL_REGEX.test(value);+// Mirrors the backend cookie-name validation.+export const SESSION_COOKIE_NAME_REGEX = /^[A-Za-z0-9_-]+$/;++export const isValidSessionCookieName = (value: string): boolean =>+ SESSION_COOKIE_NAME_REGEX.test(value);+export const ALL_CONFIGS = [GOOGLE_CONFIGS,MICROSOFT_CONFIGS,@@ -367,3 +368,355 @@ export const ALL_CONFIGS = [MOCK_SERVER_CONFIGS,PROXY_URL_CONFIGS,];++// Token fields that are optional and excluded from mandatory validation.+export const OPTIONAL_TOKEN_FIELD_KEYS = new Set(+ TOKEN_VALIDATION_CONFIGS.filter((cfg) => cfg.optional).map((cfg) => cfg.key)+);++// Token fields that are free-form secrets — validated as non-empty only, never+// numerically (see Config.secret). Everything else in the section is numeric.+export const TOKEN_SECRET_FIELD_KEYS = new Set(+ TOKEN_VALIDATION_CONFIGS.filter((cfg) => cfg.secret).map((cfg) => cfg.key)+);++export const isFieldEmpty = (field: string | boolean | number): boolean => {+ if (typeof field === 'boolean' || typeof field === 'number') return false;+ return field.trim() === '';+};++// Rate-limit rule: the backend requires positive integers (>= 1) for both+// RATE_LIMIT_TTL and RATE_LIMIT_MAX, so blanks, non-numerics, decimals, zero,+// and negatives are all invalid. Boolean short-circuits to valid to keep the+// shared field-union signature (these fields are always numeric in practice).+export const isNotValidNumber = (field: string | boolean | number): boolean => {+ if (typeof field === 'boolean') return false;+ const num = typeof field === 'number' ? field : Number(field.trim());+ if (!Number.isFinite(num)) return true;+ return !Number.isInteger(num) || num < 1;+};++// Single source of truth for config validation. `getConfigValidationIssues` drives+// the save guard, tab dots, field borders, and blocked-save console.+// Add a field: render it and wire `isConfigFieldErrored` from `useConfigValidation()` — no edits here, the section loops are generic.+// Add a section/tab: push from a new block below, extend `ConfigSectionId`/`ConfigTab`, and add `:indicator` in `settings.vue`.++export type ConfigTab = 'auth' | 'smtp' | 'proxy' | 'rate-limit';+export type ConfigSubTab = 'auth-providers' | 'token';+export type ConfigSectionId =+ | SsoAuthProviders+ | 'email'+ | 'token'+ | 'rate_limit'+ | 'proxy';++// What's wrong with a value; maps via GUARD_BY_KIND to its save guard / toast.+export type ConfigIssueKind =+ | 'empty' // required field left blank+ | 'invalid-number' // numeric field present but not a positive integer (>= 1)+ | 'invalid-format' // value present but malformed (e.g. proxy / SMTP URL)+ | 'incomplete'; // interdependent pair only half-filled (SMTP user/pass)++export type ConfigGuard = 'required' | 'format' | 'smtp-pair';++// `invalid-number` sits with `invalid-format` under the `format` guard, not+// `required`: the field isn't empty, it holds a bad value, so it should tip the+// "invalid values" toast rather than "fill all the fields". Only truly blank+// fields (`empty`) map to `required`.+const GUARD_BY_KIND: Record<ConfigIssueKind, ConfigGuard> = {+ empty: 'required',+ 'invalid-number': 'format',+ 'invalid-format': 'format',+ incomplete: 'smtp-pair',+};++export type ConfigValidationIssue = {+ tab: ConfigTab;+ subTab?: ConfigSubTab;+ section: ConfigSectionId;+ fieldKey: string;+ envVar: string; // matching InfraConfig env var, e.g. PROXY_APP_URL+ kind: ConfigIssueKind;+};++const lookupEnvVar = (configs: Config[], key: string): string =>+ configs.find((cfg) => cfg.key === key)?.name ?? '';++const emptyOrInvalidNumber = (+ value: string | boolean | number+): ConfigIssueKind =>+ typeof value === 'string' && value.trim() === ''+ ? 'empty'+ : 'invalid-number';++const PROVIDER_CONFIGS: Record<SsoAuthProviders, Config[]> = {+ google: GOOGLE_CONFIGS,+ github: GITHUB_CONFIGS,+ microsoft: MICROSOFT_CONFIGS,+};++export const getConfigValidationIssues = (+ config: ServerConfigs+): ConfigValidationIssue[] => {+ const issues: ConfigValidationIssue[] = [];++ // SSO providers → auth › auth-providers+ // Only validate enabled providers — a disabled provider with blank fields+ // is intentional config and must not block saves elsewhere.+ (Object.keys(PROVIDER_CONFIGS) as SsoAuthProviders[]).forEach((name) => {+ const provider = config.providers[name];+ if (!provider.enabled) return;++ Object.entries(provider.fields).forEach(([fieldKey, value]) => {+ if (isFieldEmpty(value)) {+ issues.push({+ tab: 'auth',+ subTab: 'auth-providers',+ section: name,+ fieldKey,+ envVar: lookupEnvVar(PROVIDER_CONFIGS[name], fieldKey),+ kind: 'empty',+ });+ }+ });+ });++ // Mail / SMTP → smtp+ // Only runs when SMTP is enabled. Three concerns are checked separately:+ // 1. required-empty (generic loop, mode-aware exclude list)+ // 2. URL format (basic mode only — smtp:// or smtps://)+ // 3. SMTP user/password pair completeness (custom mode)+ const mail = config.mailConfigs;+ if (mail.enabled) {+ const useCustom = mail.fields.mailer_use_custom_configs;+ // user/password are optional but only as a pair — see (3) below.+ const optionalMailerKeys = ['mailer_smtp_user', 'mailer_smtp_password'];+ // OAuth2 is opt-in; these never block a save on their own.+ const oauth2Keys = [+ 'mailer_smtp_auth_type',+ 'mailer_smtp_oauth2_user',+ 'mailer_smtp_oauth2_client_id',+ 'mailer_smtp_oauth2_client_secret',+ 'mailer_smtp_oauth2_refresh_token',+ 'mailer_smtp_oauth2_access_url',+ ];+ // Required-field set depends on mode:+ // custom-ON → host + port + from_address (URL excluded; not used)+ // custom-OFF → URL + from_address (host/port/user/password excluded)+ // OAuth2 fields are excluded in both modes (always optional).+ const excludeKeys = useCustom+ ? ['mailer_smtp_url', ...optionalMailerKeys, ...oauth2Keys]+ : [+ 'mailer_smtp_host',+ 'mailer_smtp_port',+ 'mailer_smtp_user',+ 'mailer_smtp_password',+ ...oauth2Keys,+ ];++ // (1) Required-empty: iterate every mail field and flag the non-excluded+ // ones that are blank. `mailer_use_custom_configs` is a toggle (not a+ // validatable field); `isFieldEmpty` is a no-op for booleans so TLS/secure+ // flags pass through without comment.+ Object.entries(mail.fields).forEach(([fieldKey, value]) => {+ if (fieldKey === 'mailer_use_custom_configs') return;+ if (excludeKeys.includes(fieldKey)) return;+ if (isFieldEmpty(value)) {+ issues.push({+ tab: 'smtp',+ section: 'email',+ fieldKey,+ envVar: lookupEnvVar(+ [...MAIL_CONFIGS, ...CUSTOM_MAIL_CONFIGS],+ fieldKey+ ),+ kind: 'empty',+ });+ }+ });++ // (2) URL format — basic mode only. nodemailer's `createTransport` accepts+ // smtp:// or smtps:// only. In custom mode the URL is hidden and never sent+ // (see the transform in useConfigHandler), so a stale/malformed value must+ // not block the save. Emptiness is owned by the required-empty loop above;+ // flagging empty here too would double-classify and tip the wrong toast.+ const smtpUrl = mail.fields.mailer_smtp_url;+ if (+ !useCustom &&+ !isFieldEmpty(smtpUrl) &&+ !smtpUrl.startsWith('smtp://') &&+ !smtpUrl.startsWith('smtps://')+ ) {+ issues.push({+ tab: 'smtp',+ section: 'email',+ fieldKey: 'mailer_smtp_url',+ envVar: lookupEnvVar(MAIL_CONFIGS, 'mailer_smtp_url'),+ kind: 'invalid-format',+ });+ }++ // (3) SMTP user/password must be provided together or not at all — the+ // backend (validateSmtpCredentialPair) rejects a half-filled pair with+ // INFRA_CONFIG_INVALID_INPUT, so mirror it here to surface the precise+ // toast instead of a generic backend error. Only relevant in custom mode+ // (basic mode embeds credentials in the URL).+ if (useCustom) {+ const hasUser = mail.fields.mailer_smtp_user.trim() !== '';+ const hasPass = mail.fields.mailer_smtp_password.trim() !== '';+ if (hasUser !== hasPass) {+ const missingKey = hasUser+ ? 'mailer_smtp_password'+ : 'mailer_smtp_user';+ issues.push({+ tab: 'smtp',+ section: 'email',+ fieldKey: missingKey,+ envVar: lookupEnvVar(CUSTOM_MAIL_CONFIGS, missingKey),+ kind: 'incomplete',+ });+ }+ }+ }++ // Token validity → auth › token+ // Mixed-shape section validated per field identity (not value shape):+ // - secret strings (jwt_secret, session_secret) only need to be non-empty,+ // so a numeric-looking secret like "0" or "1.5" stays valid;+ // - the numeric fields (salt complexity, token validities) must be positive+ // integers (>= 1) to match the backend.+ // `session_cookie_name` is format-validated separately below.+ Object.entries(config.tokenConfigs.fields).forEach(([fieldKey, value]) => {+ if (OPTIONAL_TOKEN_FIELD_KEYS.has(fieldKey)) return;+ const invalid = TOKEN_SECRET_FIELD_KEYS.has(fieldKey)+ ? isFieldEmpty(value)+ : isNotValidNumber(value);+ if (invalid) {+ issues.push({+ tab: 'auth',+ subTab: 'token',+ section: 'token',+ fieldKey,+ envVar: lookupEnvVar(TOKEN_VALIDATION_CONFIGS, fieldKey),+ kind: emptyOrInvalidNumber(value),+ });+ }+ });++ // Empty falls back to the backend default; only flag malformed non-empty.+ const sessionCookieName =+ config.tokenConfigs.fields.session_cookie_name ?? '';+ if (+ !isFieldEmpty(sessionCookieName) &&+ !isValidSessionCookieName(sessionCookieName)+ ) {+ issues.push({+ tab: 'auth',+ subTab: 'token',+ section: 'token',+ fieldKey: 'session_cookie_name',+ envVar: lookupEnvVar(TOKEN_VALIDATION_CONFIGS, 'session_cookie_name'),+ kind: 'invalid-format',+ });+ }++ // Rate limit → rate-limit+ // Both fields are unconditionally required numerics — no enable toggle.+ Object.entries(config.rateLimitConfigs.fields).forEach(([fieldKey, value]) => {+ if (isNotValidNumber(value)) {+ issues.push({+ tab: 'rate-limit',+ section: 'rate_limit',+ fieldKey,+ envVar: lookupEnvVar(RATE_LIMIT_CONFIGS, fieldKey),+ kind: emptyOrInvalidNumber(value),+ });+ }+ });++ // Proxy URL → proxy+ // Required unconditionally (no enable toggle). The if/else ordering matters:+ // an empty value also fails `isValidProxyUrl`, so we classify it as 'empty'+ // first so it tips the input_empty toast (same priority as pre-refactor),+ // not the input_validation_error toast.+ const proxyUrl = config.proxyUrlConfigs.fields.proxy_app_url ?? '';+ if (isFieldEmpty(proxyUrl)) {+ issues.push({+ tab: 'proxy',+ section: 'proxy',+ fieldKey: 'proxy_app_url',+ envVar: lookupEnvVar(PROXY_URL_CONFIGS, 'proxy_app_url'),+ kind: 'empty',+ });+ } else if (!isValidProxyUrl(proxyUrl)) {+ issues.push({+ tab: 'proxy',+ section: 'proxy',+ fieldKey: 'proxy_app_url',+ envVar: lookupEnvVar(PROXY_URL_CONFIGS, 'proxy_app_url'),+ kind: 'invalid-format',+ });+ }++ return issues;+};++// True when any issue maps to the given save guard.+export const hasGuardIssue = (+ issues: ConfigValidationIssue[],+ guard: ConfigGuard+): boolean => issues.some((issue) => GUARD_BY_KIND[issue.kind] === guard);++// Proactive — drives indicator dots without waiting for a save attempt.+export const tabHasConfigIssue = (+ issues: ConfigValidationIssue[],+ tab: ConfigTab,+ subTab?: ConfigSubTab+): boolean =>+ issues.some(+ (issue) => issue.tab === tab && (!subTab || issue.subTab === subTab)+ );++/* Provide/inject (not module singleton) so an unscoped consumer throws loudly instead of+ reading empty state. `configEdited` mirrors `settings.vue`'s `isConfigUpdated` (gates borders+ to typing-time); `configValidationIssues` is rebuilt by its deep watch on `workingConfigs`. */+export type ConfigValidationContext = {+ configEdited: Ref<boolean>;+ configValidationIssues: Ref<ConfigValidationIssue[]>;+};++const CONFIG_VALIDATION_KEY: InjectionKey<ConfigValidationContext> =+ Symbol('config-validation');++// Called once by the owner (settings.vue); returns the refs so it can drive+// its watchers.+export const provideConfigValidation = (): ConfigValidationContext => {+ const context: ConfigValidationContext = {+ configEdited: ref(false),+ configValidationIssues: ref<ConfigValidationIssue[]>([]),+ };+ provide(CONFIG_VALIDATION_KEY, context);+ return context;+};++// Called by any descendant; throws when no provider is above it, so a consumer+// outside settings.vue fails loudly instead of silently reading empty state.+export const useConfigValidation = () => {+ const context = inject(CONFIG_VALIDATION_KEY);+ if (!context) {+ throw new Error(+ 'useConfigValidation() must be used under a component that called ' ++ 'provideConfigValidation() (settings.vue). These config components read ' ++ 'validation state from that provider and cannot be mounted standalone.'+ );+ }++ // Border lights up once the form is edited and the field has a live issue.+ const isConfigFieldErrored = (section: ConfigSectionId, fieldKey: string) =>+ context.configEdited.value &&+ context.configValidationIssues.value.some(+ (issue) => issue.section === section && issue.fieldKey === fieldKey+ );++ return { ...context, isConfigFieldErrored };+};diff --git a/packages/hoppscotch-sh-admin/src/pages/settings.vue b/packages/hoppscotch-sh-admin/src/pages/settings.vueindex 8407d7bb2..f188f12f3 100644--- a/packages/hoppscotch-sh-admin/src/pages/settings.vue+++ b/packages/hoppscotch-sh-admin/src/pages/settings.vue@@ -18,11 +18,21 @@<div v-else-if="workingConfigs" class="flex flex-col py-8"><HoppSmartTabs v-model="selectedOptionTab" render-inactive-tabs>- <HoppSmartTab id="auth" :label="t('configs.tabs.auth')">+ <HoppSmartTab+ id="auth"+ :label="t('configs.tabs.auth')"+ :indicator="tabHasError('auth')"+ indicator-variant="error"+ ><SettingsAuthConfigurations v-model:config="workingConfigs" /></HoppSmartTab>- <HoppSmartTab id="smtp" :label="t('configs.tabs.smtp')">+ <HoppSmartTab+ id="smtp"+ :label="t('configs.tabs.smtp')"+ :indicator="tabHasError('smtp')"+ indicator-variant="error"+ ><div class="pb-8 px-4 flex flex-col space-y-8 divide-y divide-divider"><SettingsSmtpConfiguration v-model:config="workingConfigs" /></div>@@ -31,13 +41,23 @@<HoppSmartTab :id="'token'" :label="t('configs.tabs.infra_tokens')"><Tokens /></HoppSmartTab>- <HoppSmartTab id="proxy" :label="t('configs.tabs.proxy')">+ <HoppSmartTab+ id="proxy"+ :label="t('configs.tabs.proxy')"+ :indicator="tabHasError('proxy')"+ indicator-variant="error"+ ><SettingsProxyURLConfigurationclass="pb-8 px-4"v-model:config="workingConfigs"/></HoppSmartTab>- <HoppSmartTab :id="'rate-limit'" :label="t('configs.tabs.rate_limit')">+ <HoppSmartTab+ :id="'rate-limit'"+ :label="t('configs.tabs.rate_limit')"+ :indicator="tabHasError('rate-limit')"+ indicator-variant="error"+ ><SettingsRateLimit v-model:config="workingConfigs" /></HoppSmartTab><HoppSmartTab id="miscellaneous" :label="t('configs.tabs.miscellaneous')">@@ -75,15 +95,24 @@<script setup lang="ts">import { isEqual } from 'lodash-es';-import { computed, ref } from 'vue';+import { computed, ref, watch } from 'vue';import { useI18n } from '~/composables/i18n';import { useToast } from '~/composables/toast';import { useConfigHandler } from '~/composables/useConfigHandler';-import { hasInputValidationFailed } from '~/helpers/configs';+import {+ ConfigTab,+ getConfigValidationIssues,+ hasGuardIssue,+ provideConfigValidation,+ tabHasConfigIssue,+} from '~/helpers/configs';const t = useI18n();const toast = useToast();+// Fresh validation context per mount; children inject for field-level borders.+const { configEdited, configValidationIssues } = provideConfigValidation();+const showSaveChangesModal = ref(false);const initiateServerRestart = ref(false);@@ -107,8 +136,6 @@ const {infraConfigsError,fetchingAllowedAuthProviders,allowedAuthProvidersError,- AreAnyConfigFieldsEmpty,- hasPartialSmtpCredentials,} = useConfigHandler();// Check if the configs have been updated@@ -118,32 +145,90 @@ const isConfigUpdated = computed(() =>: false,);-// Check if any of the fields in workingConfigs are empty-const areAnyFieldsEmpty = computed(() =>- workingConfigs.value ? AreAnyConfigFieldsEmpty(workingConfigs.value) : false,+// Gates the field-border surface so borders appear while typing, not on load.+watch(isConfigUpdated, (edited) => (configEdited.value = edited), {+ immediate: true,+});++// Keep the issue list live so borders, tab dots, and guards all see the latest.+watch(+ workingConfigs,+ (configs) => {+ configValidationIssues.value = configs+ ? getConfigValidationIssues(configs)+ : [];+ },+ { deep: true, immediate: true },);-const triggerSaveChangesModal = () => {- if (areAnyFieldsEmpty.value) {- return toast.error(t('configs.input_empty'));- }+const blockedByEmptyField = computed(() =>+ hasGuardIssue(configValidationIssues.value, 'required'),+);+const blockedByPartialSmtp = computed(() =>+ hasGuardIssue(configValidationIssues.value, 'smtp-pair'),+);+const blockedByInvalidInput = computed(() =>+ hasGuardIssue(configValidationIssues.value, 'format'),+);- if (workingConfigs.value && hasPartialSmtpCredentials(workingConfigs.value)) {- return toast.error(t('configs.mail_configs.smtp_auth_incomplete'));- }+// Proactive — shows even before any edit so hidden blockers stay visible.+const tabHasError = (tab: ConfigTab) =>+ tabHasConfigIssue(configValidationIssues.value, tab);++// Names the offending fields in the console for support cross-reference.+const logConfigValidationIssues = () => {+ const issues = configValidationIssues.value;+ if (!issues.length) return;++ const rows = issues.map((issue) => ({+ tab: issue.subTab ? `${issue.tab} › ${issue.subTab}` : issue.tab,+ field: issue.fieldKey,+ envVar: issue.envVar,+ issue: issue.kind,+ }));++ // eslint-disable-next-line no-console+ console.warn(+ `[Hoppscotch Admin] Save blocked — ${issues.length} configuration field(s) need attention:`,+ );+ // eslint-disable-next-line no-console+ console.table(rows);+};- // Check if any of the input validations have failed- if (Object.values(hasInputValidationFailed.value).some(Boolean)) {- return toast.error(t('configs.input_validation_error'));+// Logs diagnostics and surfaces the highest-priority blocking toast, returning+// true when a guard fired (save must halt) and false when every guard passes.+// Shared by the Save click and the post-confirm restart so the modal-confirm+// path enforces the same full guard set as opening the modal — not just the+// empty-field subset.+const surfaceSaveBlockers = (): boolean => {+ const blocked =+ blockedByEmptyField.value ||+ blockedByPartialSmtp.value ||+ blockedByInvalidInput.value;++ if (!blocked) return false;++ logConfigValidationIssues();++ if (blockedByEmptyField.value) {+ toast.error(t('configs.input_empty'));+ } else if (blockedByPartialSmtp.value) {+ toast.error(t('configs.mail_configs.smtp_auth_incomplete'));+ } else if (blockedByInvalidInput.value) {+ toast.error(t('configs.input_validation_error'));}++ return true;+};++const triggerSaveChangesModal = () => {+ if (surfaceSaveBlockers()) return;showSaveChangesModal.value = true;};const restartServer = () => {- if (areAnyFieldsEmpty.value) {- return toast.error(t('configs.input_empty'));- }- initiateServerRestart.value = true;+ if (surfaceSaveBlockers()) return;showSaveChangesModal.value = false;+ initiateServerRestart.value = true;};</script>