fix(frontend): keep HMAC secret visible for copy after save

API principal HMAC secrets are write-only from the server, so users could
not copy a newly generated or rotated key before the input was cleared.
Retain the plaintext in-session after save, simplify secret field controls,
and add copy guidance across locales.
This commit is contained in:
wizardchen
2026-07-07 16:38:11 +08:00
committed by lyingbug
parent 974231190c
commit f7b427009d
5 changed files with 99 additions and 42 deletions
+2 -1
View File
@@ -5862,7 +5862,8 @@ export default {
tokenHeaderDesc: 'Clients send the backend-signed JWT in this fixed header.', tokenHeaderDesc: 'Clients send the backend-signed JWT in this fixed header.',
hmacSecret: 'HMAC secret', hmacSecret: 'HMAC secret',
hmacSecretDesc: 'Same secret stored in WeKnora; used only on your backend to sign JWTs—never send it as a request header.', hmacSecretDesc: 'Same secret stored in WeKnora; used only on your backend to sign JWTs—never send it as a request header.',
secretConfigured: 'Secret configured; enter a new value to rotate', secretConfigured: 'Secret configured (not shown again); enter a new value to rotate',
secretSavedCopyHint: 'Secret saved. Copy it to your backend now — you will not be able to view it again after leaving this page.',
generateSecret: 'Generate secret', generateSecret: 'Generate secret',
hmacSecretResetConfirmTitle: 'Reset HMAC secret?', hmacSecretResetConfirmTitle: 'Reset HMAC secret?',
hmacSecretResetConfirmBody: 'After reset, the old HMAC secret is revoked immediately. Every backend service signing JWTs with the old secret must switch to the new secret to keep signed-token calls working. This action cannot be undone.', hmacSecretResetConfirmBody: 'After reset, the old HMAC secret is revoked immediately. Every backend service signing JWTs with the old secret must switch to the new secret to keep signed-token calls working. This action cannot be undone.',
+2 -1
View File
@@ -5873,7 +5873,8 @@ export default {
tokenHeaderDesc: "클라이언트는 이 고정 헤더에 백엔드가 서명한 JWT를 전달합니다.", tokenHeaderDesc: "클라이언트는 이 고정 헤더에 백엔드가 서명한 JWT를 전달합니다.",
hmacSecret: "HMAC secret", hmacSecret: "HMAC secret",
hmacSecretDesc: "WeKnora에 저장된 것과 동일한 secret. 백엔드에서 JWT 서명에만 사용하며 요청 헤더로 보내지 않습니다.", hmacSecretDesc: "WeKnora에 저장된 것과 동일한 secret. 백엔드에서 JWT 서명에만 사용하며 요청 헤더로 보내지 않습니다.",
secretConfigured: "Secret configured; enter a new value to rotate", secretConfigured: "Secret configured (not shown again); enter a new value to rotate",
secretSavedCopyHint: "Secret saved. Copy it to your backend now — you will not be able to view it again after leaving this page.",
generateSecret: "Secret 생성", generateSecret: "Secret 생성",
hmacSecretResetConfirmTitle: "HMAC secret을 재설정할까요?", hmacSecretResetConfirmTitle: "HMAC secret을 재설정할까요?",
hmacSecretResetConfirmBody: "재설정하면 기존 HMAC secret은 즉시 무효화됩니다. 기존 secret으로 JWT를 서명하는 모든 백엔드 서비스는 새 secret으로 교체해야 서명 토큰 호출을 계속 사용할 수 있습니다. 이 작업은 되돌릴 수 없습니다.", hmacSecretResetConfirmBody: "재설정하면 기존 HMAC secret은 즉시 무효화됩니다. 기존 secret으로 JWT를 서명하는 모든 백엔드 서비스는 새 secret으로 교체해야 서명 토큰 호출을 계속 사용할 수 있습니다. 이 작업은 되돌릴 수 없습니다.",
+2 -1
View File
@@ -5694,7 +5694,8 @@ export default {
tokenHeaderDesc: 'Клиент передаёт JWT, подписанный backend, в этом фиксированном заголовке.', tokenHeaderDesc: 'Клиент передаёт JWT, подписанный backend, в этом фиксированном заголовке.',
hmacSecret: 'HMAC secret', hmacSecret: 'HMAC secret',
hmacSecretDesc: 'Тот же secret, что в WeKnora; только для подписи JWT на backend — не отправляйте его в заголовке запроса.', hmacSecretDesc: 'Тот же secret, что в WeKnora; только для подписи JWT на backend — не отправляйте его в заголовке запроса.',
secretConfigured: 'Secret настроен; введите новое значение для ротации', secretConfigured: 'Secret настроен (повторно не показывается); введите новое значение для ротации',
secretSavedCopyHint: 'Secret сохранён. Скопируйте его в backend сейчас — после ухода со страницы просмотреть его будет нельзя.',
generateSecret: 'Сгенерировать secret', generateSecret: 'Сгенерировать secret',
hmacSecretResetConfirmTitle: 'Сбросить HMAC secret?', hmacSecretResetConfirmTitle: 'Сбросить HMAC secret?',
hmacSecretResetConfirmBody: 'После сброса старый HMAC secret немедленно перестанет действовать. Все backend-сервисы, подписывающие JWT старым secret, должны перейти на новый secret, чтобы вызовы signed token продолжили работать. Это действие нельзя отменить.', hmacSecretResetConfirmBody: 'После сброса старый HMAC secret немедленно перестанет действовать. Все backend-сервисы, подписывающие JWT старым secret, должны перейти на новый secret, чтобы вызовы signed token продолжили работать. Это действие нельзя отменить.',
+2 -1
View File
@@ -5875,7 +5875,8 @@ export default {
tokenHeaderDesc: "客户端在该固定请求头中携带后端签发的 JWT。", tokenHeaderDesc: "客户端在该固定请求头中携带后端签发的 JWT。",
hmacSecret: "HMAC 密钥", hmacSecret: "HMAC 密钥",
hmacSecretDesc: "与 WeKnora 保存的同一份密钥;仅用于后端签发 JWT,不要作为请求头发送。", hmacSecretDesc: "与 WeKnora 保存的同一份密钥;仅用于后端签发 JWT,不要作为请求头发送。",
secretConfigured: "已配置密钥;输入新值可轮换", secretConfigured: "已配置密钥(不可回看);输入新值可轮换",
secretSavedCopyHint: "密钥已保存,请立即复制到后端配置。离开本页后将无法再次查看。",
generateSecret: "生成密钥", generateSecret: "生成密钥",
hmacSecretResetConfirmTitle: "确认重置 HMAC 密钥?", hmacSecretResetConfirmTitle: "确认重置 HMAC 密钥?",
hmacSecretResetConfirmBody: "重置后,旧的 HMAC 密钥会立即失效,所有使用旧密钥签发 JWT 的后端服务必须更换为新密钥才可继续通过签名 Token 调用。此操作不可撤销。", hmacSecretResetConfirmBody: "重置后,旧的 HMAC 密钥会立即失效,所有使用旧密钥签发 JWT 的后端服务必须更换为新密钥才可继续通过签名 Token 调用。此操作不可撤销。",
@@ -249,36 +249,46 @@
<label>{{ $t('integrations.api.hmacSecret') }}</label> <label>{{ $t('integrations.api.hmacSecret') }}</label>
<p>{{ $t('integrations.api.hmacSecretDesc') }}</p> <p>{{ $t('integrations.api.hmacSecretDesc') }}</p>
</div> </div>
<div class="secret-control"> <div class="secret-field">
<t-input <div class="secret-control">
v-model="secretInput" <t-input
:type="showHMACSecret ? 'text' : 'password'" v-model="secretInput"
class="mono-input" :type="secretInputType"
:placeholder="config?.has_hmac_secret ? $t('integrations.api.secretConfigured') : ''" class="mono-input secret-mono-input"
@blur="triggerAutoSave" :placeholder="config?.has_hmac_secret && !secretInput.trim() ? $t('integrations.api.secretConfigured') : ''"
/> @blur="triggerAutoSave"
<t-button size="small" variant="text" @click="showHMACSecret = !showHMACSecret"> />
<t-icon :name="showHMACSecret ? 'browse-off' : 'browse'" /> <t-button
</t-button> v-if="secretInput.trim()"
<t-button size="small"
size="small" variant="text"
variant="text" @click="showHMACSecret = !showHMACSecret"
:title="$t('integrations.api.copy')" >
:disabled="!secretInput.trim()" <t-icon :name="showHMACSecret ? 'browse-off' : 'browse'" />
@click="copy(secretInput)" </t-button>
> <t-button
<t-icon name="file-copy" /> v-if="secretInput.trim()"
</t-button> size="small"
<t-button variant="text"
size="small" :title="$t('integrations.api.copy')"
variant="text" @click="copy(secretInput)"
theme="danger" >
:title="$t('integrations.api.generateSecret')" <t-icon name="file-copy" />
:loading="saving" </t-button>
@click="confirmGenerateSecret" <t-button
> size="small"
<t-icon name="refresh" /> variant="text"
</t-button> theme="danger"
:title="$t('integrations.api.generateSecret')"
:loading="saving"
@click="confirmGenerateSecret"
>
<t-icon name="refresh" />
</t-button>
</div>
<p v-if="showSecretSavedHint" class="secret-saved-hint">
{{ $t('integrations.api.secretSavedCopyHint') }}
</p>
</div> </div>
</div> </div>
</div> </div>
@@ -588,6 +598,8 @@ const apiKeyCreating = ref(false)
const knowledgeBasesLoading = ref(false) const knowledgeBasesLoading = ref(false)
const knowledgeBases = ref<Array<{ id: string; name: string }>>([]) const knowledgeBases = ref<Array<{ id: string; name: string }>>([])
const secretInput = ref('') const secretInput = ref('')
/** Plaintext of the last secret successfully saved in this page session. */
const lastSavedSecretInput = ref('')
const exampleTab = ref<'jwt' | 'curl'>('curl') const exampleTab = ref<'jwt' | 'curl'>('curl')
const agents = ref<CustomAgent[]>([]) const agents = ref<CustomAgent[]>([])
const agentsLoading = ref(false) const agentsLoading = ref(false)
@@ -862,6 +874,11 @@ const tokenHeaderName = computed(() => DEFAULT_TOKEN_HEADER_NAME)
const directHeaderName = computed(() => DEFAULT_DIRECT_HEADER_NAME) const directHeaderName = computed(() => DEFAULT_DIRECT_HEADER_NAME)
const secretInputType = computed(() => {
if (!secretInput.value.trim()) return 'text'
return showHMACSecret.value ? 'text' : 'password'
})
const canAutoSave = computed(() => { const canAutoSave = computed(() => {
if (!tenantId.value) return false if (!tenantId.value) return false
if (form.mode === 'signed_token') { if (form.mode === 'signed_token') {
@@ -883,15 +900,24 @@ const knowledgeBaseOptions = computed(() => knowledgeBases.value.map((kb) => ({
value: kb.id, value: kb.id,
}))) })))
const hasUnsavedSecretChange = computed(() => {
const trimmed = secretInput.value.trim()
if (!trimmed) return false
return trimmed !== lastSavedSecretInput.value
})
const showSecretSavedHint = computed(() => {
const trimmed = secretInput.value.trim()
return trimmed !== '' && trimmed === lastSavedSecretInput.value
})
const hasUnsavedPrincipalChanges = computed(() => { const hasUnsavedPrincipalChanges = computed(() => {
const cfg = config.value const cfg = config.value
if (!cfg) return false if (!cfg) return false
return ( return (
form.mode !== cfg.mode form.mode !== cfg.mode
|| form.require_direct_header !== cfg.require_direct_header || form.require_direct_header !== cfg.require_direct_header
// A non-empty input always means the user intends to set a new secret; || hasUnsavedSecretChange.value
// the existing secret is never echoed back so any typed value is a change.
|| secretInput.value.trim() !== ''
) )
}) })
@@ -1039,6 +1065,7 @@ async function load() {
// The plaintext secret is never returned; start with an empty input and // The plaintext secret is never returned; start with an empty input and
// rely on config.has_hmac_secret to reflect whether one is configured. // rely on config.has_hmac_secret to reflect whether one is configured.
secretInput.value = '' secretInput.value = ''
lastSavedSecretInput.value = ''
ensurePlaygroundAgent() ensurePlaygroundAgent()
} catch (err: any) { } catch (err: any) {
error.value = err?.message || t('integrations.api.loadFailed') error.value = err?.message || t('integrations.api.loadFailed')
@@ -1162,19 +1189,25 @@ async function saveIfNeeded(options: { showSuccess?: boolean } = {}) {
signed_token_header_name: DEFAULT_TOKEN_HEADER_NAME, signed_token_header_name: DEFAULT_TOKEN_HEADER_NAME,
require_direct_header: form.require_direct_header, require_direct_header: form.require_direct_header,
} }
// Only send the secret when the user typed a new one; otherwise the // Only send the secret when the user entered a new value; otherwise the
// backend keeps the stored value untouched. // backend keeps the stored value untouched.
if (secretInput.value.trim() !== '') { const secretBeingSaved = hasUnsavedSecretChange.value ? secretInput.value.trim() : ''
payload.hmac_secret = secretInput.value.trim() if (secretBeingSaved) {
payload.hmac_secret = secretBeingSaved
} }
const resp = await updateAPIPrincipalConfig(tenantId.value, payload) const resp = await updateAPIPrincipalConfig(tenantId.value, payload)
if (!resp.success || !resp.data) { if (!resp.success || !resp.data) {
throw new Error(resp.message || t('integrations.api.saveFailed')) throw new Error(resp.message || t('integrations.api.saveFailed'))
} }
config.value = resp.data config.value = resp.data
secretInput.value = '' if (secretBeingSaved) {
lastSavedSecretInput.value = secretBeingSaved
showHMACSecret.value = true
}
if (options.showSuccess) { if (options.showSuccess) {
MessagePlugin.success(t('integrations.api.saveSuccess')) MessagePlugin.success(
secretBeingSaved ? t('integrations.api.secretSavedCopyHint') : t('integrations.api.saveSuccess'),
)
} }
return true return true
} catch (err: any) { } catch (err: any) {
@@ -2157,6 +2190,13 @@ onBeforeUnmount(stopPlayground)
} }
} }
.secret-field {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.secret-control { .secret-control {
display: flex; display: flex;
align-items: center; align-items: center;
@@ -2168,11 +2208,24 @@ onBeforeUnmount(stopPlayground)
min-width: 0; min-width: 0;
} }
.secret-mono-input {
:deep(.t-input__suffix) {
display: none;
}
}
:deep(.t-button) { :deep(.t-button) {
flex: 0 0 auto; flex: 0 0 auto;
} }
} }
.secret-saved-hint {
margin: 0;
font-size: 12px;
line-height: 1.5;
color: var(--td-warning-color);
}
@media (max-width: 640px) { @media (max-width: 640px) {
.config-row { .config-row {
grid-template-columns: 1fr; grid-template-columns: 1fr;