fix(settings): show masked saved keys and restore environment auth

This commit is contained in:
Magolor committed 2026-11-06 16:58:49 +08:00
1 parent 7e00f186e2
commit 334a76ef88
33 files changed
+484 -88

No files matched your search

@@ -1,9 +1,14 @@
/** Web DeepSeek configuration, credential reuse, and saved model selection. */
/** Web provider credentials, environment fallback, and DeepSeek model selection. */
import { readFile } from 'node:fs/promises'
import { once } from 'node:events'
import { createServer } from 'node:http'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium, webkit, type Browser, type Page } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { BlockAssembler, createUserMessage, type StreamChunk } from '@deepseek-ai/dsh-llm'
import { credentialRef } from '@deepseek-ai/dsh-credentials'
import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import {
captureStableAria, compareOrRefreshGolden, launchWebScaffold,
watchConsole, webSnapshotMode, type WebScaffold,
@@ -12,6 +17,109 @@ import { openSettings, connectFreshWorkspaceZh, saveFailureShot, ZH_BROWSER_LOCA
const EXPECTED = fileURLToPath(new URL('./expected/deepseek-messages-settings/', import.meta.url))
it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', 'openai', 'clear-fixture'])(
'clears the saved %s key and sends the next request with environment authentication', async (provider) => {
const messages = provider === 'deepseek-official'
const google = provider === 'google'
const ref = credentialRef(messages ? 'DEEPSEEK_API_KEY' : `${provider.toUpperCase().replaceAll('-', '_')}_API_KEY`)
const envRef = google ? 'GEMINI_API_KEY' : ref
const calls: { path: string; key: string | undefined }[] = []
const server = createServer((request, response) => {
request.on('end', () => {
const key = request.headers[messages ? 'x-api-key' : google ? 'x-goog-api-key' : 'authorization']
calls.push({ path: request.url ?? '', key: typeof key === 'string' ? key : undefined })
const events = messages ? [
{ type: 'message_start', message: { id: 'clear', type: 'message', role: 'assistant', model: 'clear-model', content: [], usage: { input_tokens: 1, output_tokens: 0 } } },
{ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
{ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'connection-ok' } },
{ type: 'content_block_stop', index: 0 },
{ type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } },
{ type: 'message_stop' },
] : google ? [{ candidates: [{ content: { role: 'model', parts: [{ text: 'connection-ok' }] }, finishReason: 'STOP' }] }]
: [{ id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { content: 'connection-ok' }, finish_reason: null }] },
{ id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }]
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(events.map(event => `data: ${JSON.stringify(event)}\n\n`).join(''))
})
request.resume()
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
let scaffold: WebScaffold | undefined
let browser: Browser | undefined
try {
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('Missing credential test listener')
const baseURL = `http://127.0.0.1:${String(address.port)}/configured`
scaffold = await launchWebScaffold({
deepSeekMissingCredential: true,
openInAppEnvironment: createLaunchEnvironmentSnapshot([{ source: 'process', values: { [envRef]: 'fixture-environment-key' } }]),
})
const profile = { apiKeyEnv: ref, baseURL, models: [{ id: 'clear-model' }],
...messages || google ? {} : { api: 'openai-completions' } }
await scaffold.ctx.settings.mutate(messages ? 'llm-deepseek' : 'llm-pi-ai', [{
op: 'set', path: messages ? [] : ['providers', provider], value: profile,
}])
await scaffold.ctx.credentials.set(ref, 'fixture-saved-key')
const runtime = scaffold.ctx
const generate = async (): Promise<void> => {
const assembler = new BlockAssembler()
const chunks: StreamChunk[] = []
for await (const chunk of runtime.llm.stream({ provider, model: 'clear-model',
messages: [createUserMessage({ content: [{ type: 'text', text: 'Reply connection-ok' }], source: { kind: 'user' } })] })) {
chunks.push(chunk)
assembler.push(chunk)
}
expect(assembler.message({ provider, model: 'clear-model' }).content, JSON.stringify(chunks))
.toContainEqual({ type: 'text', text: 'connection-ok' })
}
await generate()
browser = await chromium.launch()
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
await page.goto(scaffold.authenticatedUrl)
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true })
await edit.click()
const key = dialog.getByLabel('API 密钥', { exact: true })
await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).click()
expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`)
await dialog.getByText('保存后清除已保存密钥,并使用环境认证', { exact: true }).waitFor()
expect((await runtime.credentials.resolve(ref))?.source).toBe('file')
if (messages) await compareOrRefreshGolden(join(EXPECTED, 'clear-key.expected.md'),
await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode())
await dialog.getByRole('button', { name: '取消', exact: true }).click()
expect((await runtime.credentials.resolve(ref))?.source).toBe('file')
await edit.click()
await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).click()
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await expect.poll(() => key.count()).toBe(0)
await generate()
expect(calls).toHaveLength(2)
expect(calls[0]?.key).toBe(messages || google ? 'fixture-saved-key' : 'Bearer fixture-saved-key')
expect(calls[1]).toEqual({ path: calls[0]?.path,
key: messages || google ? 'fixture-environment-key' : 'Bearer fixture-environment-key' })
expect(calls[1]?.path).toContain('/configured/')
expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).not.toContain('fixture-saved-key')
await edit.click()
await dialog.getByText(`已检测到环境变量(${envRef})`, { exact: true }).waitFor()
await dialog.getByText('自定义设置', { exact: true }).click()
expect(await dialog.getByLabel('API 地址', { exact: true }).inputValue()).toBe(baseURL)
expect(await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).count()).toBe(0)
} finally {
try { await browser?.close() } finally {
try { await scaffold?.close() } finally {
await new Promise<void>((resolve, reject) => server.close((error) => {
if (error === undefined) resolve()
else reject(error)
}))
}
}
}
},
)
it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])(
'keeps a foreign model drag from editing another provider input in $name', async ({ engine }) => {
const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true })
@@ -90,6 +198,10 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
expect(await dialog.getByText('DeepSeek', { exact: true }).count()).toBe(1)
await dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click()
const messages = dialog
const key = messages.getByLabel('API 密钥', { exact: true })
expect(await key.inputValue()).toBe('')
expect(await key.getAttribute('placeholder')).toBe('留空保留现有认证(已保存 API key)')
await messages.getByText('已保存 API key:sk-m…ding', { exact: true }).waitFor()
await messages.getByText('自定义设置', { exact: true }).click()
expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder'))
.toBe('https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)')
@@ -114,6 +226,17 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett
expect(credentials).toContain('DEEPSEEK_API_KEY: sk-e2e-messages')
expect(credentials).not.toContain('DEEPSEEK_MESSAGES_API_KEY')
expect(await page.locator('body').innerText()).not.toContain('sk-e2e-')
await dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }).click()
expect(await key.inputValue()).toBe('')
await messages.getByText('已保存 API key:sk-e…ages', { exact: true }).waitFor()
expect(await key.getAttribute('type')).toBe('password')
await key.fill('sk-cancelled-replacement')
expect(await messages.getByText('已保存 API key:sk-e…ages', { exact: true }).count()).toBe(0)
await key.fill('')
await messages.getByText('已保存 API key:sk-e…ages', { exact: true }).waitFor()
await messages.getByRole('button', { name: '保存', exact: true }).click()
await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor()
expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).toBe(credentials)
await page.keyboard.press('Escape')
await connectFreshWorkspaceZh(page, scaffold.workspaceCwd, 'messages-settings-e2e')
await page.getByRole('button', { name: /^选择模型/ }).click()
@@ -16,8 +16,10 @@
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- button "清除已保存密钥"
- textbox "API 密钥":
- /placeholder: 留空使用已保存凭据
- /placeholder: 留空保留现有认证(已保存 API key)
- paragraph: 已保存 API key:sk-m…ding
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
@@ -0,0 +1,26 @@
- dialog "设置":
- text: 设置
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: DeepSeek
- img "API 密钥已配置"
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- button "撤销清除"
- textbox "API 密钥":
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
- paragraph: 保存后清除已保存密钥,并使用环境认证
- group: 自定义设置
- button "取消"
- button "保存"
- button "添加模型提供商"
@@ -16,8 +16,10 @@
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- button "清除已保存密钥"
- textbox "API 密钥":
- /placeholder: 留空使用已保存凭据
- /placeholder: 留空保留现有认证(已保存 API key)
- paragraph: 已保存 API key:dsh_…test
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
@@ -16,8 +16,10 @@
- button "编辑 DeepSeek (deepseek-official)": 编辑
- text: DeepSeek deepseek-official API 密钥
- button "认证说明": "?"
- button "清除已保存密钥"
- textbox "API 密钥":
- /placeholder: 留空使用已保存凭据
- /placeholder: 留空保留现有认证(已保存 API key)
- paragraph: 已保存 API key:dsh_…test
- group:
- text: 自定义设置 API 地址
- textbox "API 地址":
+1 -1
View File
@@ -221,7 +221,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized'))
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click()
await dialog.getByPlaceholder('留空使用已保存凭据', { exact: true }).waitFor({ timeout: 10_000 })
await dialog.getByPlaceholder('留空保留现有认证(已保存 API key)', { exact: true }).waitFor({ timeout: 10_000 })
expect(await dialog.textContent()).not.toContain('API 密钥来源:')
expect(await dialog.textContent()).not.toMatch(/oauth/i)
await dialog.getByText('自定义设置').click()
@@ -86,7 +86,8 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
await compareOrRefreshGolden(MISSING_EXPECTED, initial, MODE)
const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}`
// Keep the displayed prefix and suffix stable while the credential remains unique.
const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}_test`
await keyInput.fill(secret)
await credentialStep.getByRole('button', { name: '保存并继续' }).click()
await credentialStep.waitFor({ state: 'detached', timeout: 15_000 })
@@ -115,7 +116,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await expect.poll(
() => configuredInput.getAttribute('placeholder'),
{ timeout: 10_000 },
).toBe('留空使用已保存凭据')
).toBe('留空保留现有认证(已保存 API key)')
const secondReloadWarnings = tripwire.warnings.length
await page.reload({ waitUntil: 'load' })
@@ -257,7 +258,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
await expect.poll(
() => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'),
{ timeout: 10_000 },
).toBe('留空使用已保存凭据')
).toBe('留空保留现有认证(已保存 API key)')
const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE)
await settings.getByRole('button', { name: '保存', exact: true }).click()
+2 -2
View File
@@ -40,8 +40,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` |
| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` |
| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:101`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` |
| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:89`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` |
| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` |
| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` |
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) |
+2 -2
View File
@@ -42,8 +42,8 @@
| `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` |
| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` |
| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` |
| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:101`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` |
| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:89`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` |
| `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` |
| `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` |
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) |
+2 -2
View File
@@ -12,8 +12,8 @@
en: baaab4bca76bea6b
zh: 54ccdc03ffd44f63
/user-credentials/description:
en: f7b09588c0f34952
zh: 1b93d673c5bf6a80
en: 5150dd250ea3a4b2
zh: 944d0fffca37dec5
/user-credentials/change-commits:
en: 464315a953330eb2
zh: d9815591f3abc2cb
+5 -3
View File
@@ -32,19 +32,21 @@ interface ResolvedCredential {
## Description
`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again.
`describe(ref)` reports whether a reference resolves, its source, writability, and an optional masked preview of a managed credential. It never returns the full value or an ambient credential preview. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again.
```ts type-equiv
/**
* Source and writability facts for one reference, safe for configuration UIs —
* never the value. The view has no slot a value could ride in, which is what
* lets the whole read half cross the Remote wire.
* never the full value. Providers may include a masked preview of a managed
* credential; ambient credentials do not expose a preview.
*/
interface CredentialInfo {
/** Whether resolving the reference would currently return a value. */
configured: boolean
/** Source layer currently supplying the value; absent while unconfigured. */
source?: string
/** Masked managed value for display only; short values must be fully masked. */
preview?: string
/** Whether the active provider can write this reference. */
writable: boolean
}
+5 -3
View File
@@ -32,19 +32,21 @@ interface ResolvedCredential {
## 描述
`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。
`describe(ref)` 报告引用是否可解析、来源、可写性,以及可选的托管凭据脱敏摘要。它不返回完整值,也不提供环境凭据摘要。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。
```ts type-equiv
/**
* Source and writability facts for one reference, safe for configuration UIs —
* never the value. The view has no slot a value could ride in, which is what
* lets the whole read half cross the Remote wire.
* never the full value. Providers may include a masked preview of a managed
* credential; ambient credentials do not expose a preview.
*/
interface CredentialInfo {
/** Whether resolving the reference would currently return a value. */
configured: boolean
/** Source layer currently supplying the value; absent while unconfigured. */
source?: string
/** Masked managed value for display only; short values must be fully masked. */
preview?: string
/** Whether the active provider can write this reference. */
writable: boolean
}
+2 -2
View File
@@ -9,8 +9,8 @@
en: 44852da64a6a39ec
zh: 4c280e428f0fec08
/configure-models/add-a-third-party-provider:
en: f6fb44a85dc5e4dd
zh: 2b86ea4492c32ed7
en: 2bfca1d989fce463
zh: f86948426dad32b0
/configure-models/add-a-custom-model-api:
en: 1f55d7d94cbfbd80
zh: 94e5a8bc7625d760
+2 -2
View File
@@ -20,9 +20,9 @@ Choose **Add model provider**. The card opens on **Third-party model provider**:
The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference.
A saved credential uses the placeholder **Leave blank to use saved credentials**, with no status text below the input. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials.
A saved credential uses the placeholder **Leave blank to keep current authentication (API key saved)** and a green masked-key preview below the empty input. Select **Clear saved key**, then **Save**, to remove the stored override and use environment authentication. **Undo clear** or **Cancel** preserves the key. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials.
A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Stored credentials remain write-only.
A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only.
## Add a custom model API
+2 -2
View File
@@ -20,9 +20,9 @@
认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。
已保存凭据使用**留空使用已保存凭据**占位文字,输入框下方不显示状态文字。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。
已保存凭据使用**留空保留现有认证(已保存 API key)**占位文字,在空输入框下方显示绿色的密钥脱敏摘要。选择**清除已保存密钥**,再点**保存**,即可移除存储覆盖并使用环境认证。**撤销清除**或**取消**会保留密钥。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。
密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。已保存凭据仍保持只写。
密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。
## 添加自定义模型 API
@@ -46,6 +46,7 @@ function projectCredentialInfo(info: CredentialInfo): CredentialInfo {
return {
configured: info.configured,
...info.source === undefined ? {} : { source: info.source },
...info.preview === undefined ? {} : { preview: info.preview },
writable: info.writable,
}
}
@@ -14,6 +14,16 @@ class LeakyCredentials extends MemoryCredentials {
}
}
/** A managed provider returning a display preview alongside an undeclared secret. */
class PreviewCredentials extends MemoryCredentials {
override describe(): Promise<CredentialInfo> {
return Promise.resolve({
configured: true, source: 'file', writable: true,
preview: 'sk-m…abcd', value: 'sk-managed-secret-abcd',
} as CredentialInfo)
}
}
/** A store whose write rejects with a bare string, the way some client libraries do. */
class LiteralRejectingCredentials extends MemoryCredentials {
override async set(): Promise<void> {
@@ -105,6 +115,15 @@ describe('the credentials Remote namespace a configuration surface calls', () =>
expect(JSON.stringify(described)).not.toContain('sk-leaked')
})
it('returns the masked preview without the original stored credential', async () => {
const controller = await boot({}, PreviewCredentials)
const described = await controller.describe(['DEEPSEEK_API_KEY'])
expect(described.DEEPSEEK_API_KEY).toEqual({
configured: true, source: 'file', writable: true, preview: 'sk-m…abcd',
})
expect(JSON.stringify(described)).not.toContain('sk-managed-secret-abcd')
})
it('stores and removes through the same references the batch describes', async () => {
const controller = await boot()
await controller.set('DEEPSEEK_API_KEY', 'sk-live')
@@ -18,11 +18,11 @@
en: db5aaf7f702e1f0c
zh: 409a78c14fb2b6e3
/deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys:
en: f4817eb2e3537ed9
zh: e589c193fa85473f
en: c4865eabb48e3839
zh: 66f5c6698845112f
/deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider:
en: a0501172f15c3286
zh: 6dfa112f215b2d3d
en: 19fbfafb53ea1593
zh: 880f6703111383fd
/deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers:
en: 59472e717c2f87be
zh: dc2a51a5a40138bc
+3 -3
View File
@@ -41,15 +41,15 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo
### API keys
API-key inputs start empty and use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Stored credentials are never read into the input.
API-key inputs start empty and use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting.
The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `<ROUTE>_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the credential variables of the route's `nativeAuth`, excluding `baseURLEnv` address variables, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material.
The editor uses redacted `CredentialInfo` to choose the saved-credential placeholder or environment detection, without displaying a credential-source label. Refreshing the snapshot updates an open editor without a separate probe. The hint never receives a credential value or changes field writability.
The editor uses redacted `CredentialInfo` to choose the saved-credential placeholder or environment detection, without displaying a credential-source label. Refreshing the snapshot updates an open editor without a separate probe. The hint receives only a Host-masked preview of a saved key and never changes field writability.
### Editing a provider
A blank key field offers a saved credential when one is detected, with no status text below the input; otherwise it offers environment authentication. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client.
A blank key field preserves existing authentication. A saved credential shows a green notice with its masked preview below the input; providers without a preview show only that a key is saved. Otherwise the field offers environment authentication. **Clear saved key** stages removal until Save; Undo or Cancel preserves the key. Entering a new key replaces the removal draft. A catalog route drops its user-layer derived reference to restore native authentication; explicit aliases, inherited references, and custom routes retain their reference for environment fallback. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client.
An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice.
@@ -41,15 +41,15 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会
### API 密钥
API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存凭据从不读入输入框。
API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。
编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `<ROUTE>_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 凭据变量,并排除 `baseURLEnv` 地址变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。
编辑器使用脱敏 `CredentialInfo` 选择已保存凭据的占位文字或环境检测,不显示凭据来源标签。快照刷新会更新打开的编辑器,无需单独探测。提示从不接收凭据值,也不改变字段的可写性。
编辑器使用脱敏 `CredentialInfo` 选择已保存凭据的占位文字或环境检测,不显示凭据来源标签。快照刷新会更新打开的编辑器,无需单独探测。提示只接收 Host 生成的已保存密钥脱敏摘要,不改变字段的可写性。
### 编辑提供商
密钥字段留空时,已检测到已保存凭据则提示使用该凭据,输入框下方不显示状态文字;否则提示使用环境认证。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。
密钥字段留空时保留现有认证。已保存凭据在输入框下方显示绿色提示及脱敏摘要;提供方未提供摘要时,只提示已保存密钥。否则提示使用环境认证。**清除已保存密钥**将删除操作暂存到「保存」时执行;撤销或取消会保留密钥。输入新密钥会替换待删除草稿。目录路由会移除用户层中的派生引用以恢复原生认证;显式别名、继承引用和自定义路由保留原引用以使用环境后备。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。
目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。
@@ -199,7 +199,10 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
const { mode } = retryPolicyDefaults(schema, node, schema.getPath(namespace.base, path))
return { ...loaded, retryPolicy: { ...policy, mode } }
})
const [keyDraft, setKeyDraft] = useState('')
// An empty string preserves authentication; a reference stages its removal.
const [keyDraft, setKeyDraft] = useState<string | { readonly ref: string }>('')
const keyText = typeof keyDraft === 'string' ? keyDraft : ''
const keyRemoval = typeof keyDraft === 'string' ? undefined : keyDraft
const [busy, setBusy] = useState(false)
const [listBusy, setListBusy] = useState(false)
const { onBusyChange } = props
@@ -242,6 +245,8 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
? schema.deletePath(current, [key])
: schema.setPath(current, [key], value))
}
const clearsDerivedRef = keyRemoval !== undefined && layout === 'pi-ai'
&& props.nativeAuth !== undefined && stringAt(draft, 'apiKeyEnv') === deriveKeyRef(props.provider)
// The model list is validated by the same per-row checker for both families,
// so a bad row is named by its position rather than by a blanket message.
@@ -274,18 +279,18 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
const retryFailure = retryNode === undefined || retryDefaults === undefined || props.credentialOnly === true
? undefined
: retryPolicyFailure(schema, retryNode, schema.getPath(draft, ['retryPolicy']), retryDefaults, t)
const keyFailure = apiKeyFailure(keyDraft)
const keyFailure = apiKeyFailure(keyText)
// What a probe or a write must carry: the typed key with paste whitespace
// removed. A blank field yields an empty string, which both call sites read
// as "no key supplied" rather than as a key — that is how a card whose
// provider already has a stored key is edited without re-entering it.
const keyValue = keyDraft.trim()
const keyValue = keyText.trim()
// A route whose protocol cannot authenticate without a key needs a key reference or a typed key.
const protocolNeedsKeyHere = layout === 'pi-ai' && protocolNeedsKey(probeApi)
&& stringAt(draft, 'apiKeyEnv') === undefined && stringAt(fallback, 'apiKeyEnv') === undefined
const protocolKeyMissing = protocolNeedsKeyHere && keyValue.length === 0
const credentialRequiredFailure = (props.credentialRequired === true
&& keyDraft.length > 0 && keyValue.length === 0) || protocolKeyMissing
&& keyText.length > 0 && keyValue.length === 0) || protocolKeyMissing
? 'keyRequired' as const
: undefined
const shownKeyFailure = credentialRequiredFailure ?? keyFailure
@@ -308,12 +313,16 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
*/
const applyOnce = async (): Promise<string | undefined> => {
const ns = namespace.ns
// A catalog provider returns to native authentication when this page's
// derived reference is removed. Explicit aliases and custom routes keep
// their reference so its environment fallback remains addressable.
const profileDraft = clearsDerivedRef ? schema.deletePath(draft, ['apiKeyEnv']) : draft
// A pi-ai profile names the conventional reference only when this page is
// about to store a key. Otherwise the provider keeps its native auth path.
const next = layout === 'pi-ai' && stringAt(draft, 'apiKeyEnv') === undefined
&& stringAt(fallback, 'apiKeyEnv') === undefined && keyValue.length > 0
? schema.setPath(draft, ['apiKeyEnv'], keyRef)
: draft
const next = layout === 'pi-ai' && stringAt(profileDraft, 'apiKeyEnv') === undefined
&& stringAt(schema.getPath(namespace.base, settingsPath), 'apiKeyEnv') === undefined && keyValue.length > 0
? schema.setPath(profileDraft, ['apiKeyEnv'], keyRef)
: profileDraft
if (props.credentialOnly !== true) {
// The same checker gates the submit button, so a card cannot reach this
// with a bad row; it stays because the schema check below would refuse
@@ -346,7 +355,10 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
setExpectedRevision(written.view.revision)
setDraft(next)
}
if (keyValue.length > 0) {
if (keyRemoval !== undefined) {
const removed = await operations.removeCredential(keyRemoval.ref)
if (removed !== undefined) return removed
} else if (keyValue.length > 0) {
const stored = await operations.storeCredential(keyRef, keyValue)
if (stored !== undefined) return stored
}
@@ -410,7 +422,9 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
// A named reference is the only credential the adapter reads for this
// route. Without one, a catalog route authenticates the way the directory
// reports, and a declared route sends no key at all.
const namedRef = stringAt(fallback, 'apiKeyEnv')
const namedRef = clearsDerivedRef
? stringAt(schema.getPath(namespace.base, settingsPath), 'apiKeyEnv')
: stringAt(fallback, 'apiKeyEnv')
const nativeAuth = namedRef === undefined ? props.nativeAuth : undefined
// Display method-neutral references without changing the adapter's lookup.
const authRefs = namedRef === undefined
@@ -424,12 +438,18 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
const detectedRef = detected?.[0]
const detectedVisibleRef = detectedRef === undefined || !visibleRefs.includes(detectedRef) ? undefined : detectedRef
const missingRefs = checkedRefs.length > 0 && checkedRefs.every(([, info]) => info?.configured === false)
const savedCredential = detected?.[1]?.source === 'file'
const credentialHint = keyDraft.length > 0 || savedCredential || keyHint === undefined || props.credentialRequired === true
const savedPreview = detected?.[1]?.preview
const savedCredential = detected?.[1]?.source === 'file' || savedPreview !== undefined
const removalRef = keyRemoval?.ref ?? detectedRef
const credentialHint = keyText.length > 0 || props.credentialRequired === true
? undefined
: t(detectedRef === undefined ? missingRefs ? 'keyFallbackMissing' : 'keyFallbackUnchecked'
: detectedVisibleRef === undefined ? 'keyFallbackDetectedHidden' : 'keyFallbackDetected')
.replace('{hint}', () => detectedVisibleRef ?? keyHint)
: keyRemoval !== undefined ? t('keyRemovePending')
: keyHint === undefined ? undefined
: savedCredential
? savedPreview === undefined ? t('keySaved') : t('keySavedPreview').replace('{preview}', () => savedPreview)
: t(detectedRef === undefined ? missingRefs ? 'keyFallbackMissing' : 'keyFallbackUnchecked'
: detectedVisibleRef === undefined ? 'keyFallbackDetectedHidden' : 'keyFallbackDetected')
.replace('{hint}', () => detectedVisibleRef ?? keyHint)
const keyHelp = visibleRefs.length === 0
? undefined
: t('keyHelp').replace('{env}', () => visibleRefs.join(' / '))
@@ -442,7 +462,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
const keylessNativeAuth = nativeAuth?.env.length === 0 && nativeAuth.oauth
const keyPlaceholder = keyHint === undefined || props.credentialRequired === true
? t('keyPlaceholder')
: t(savedCredential ? 'keyPlaceholderSaved' : 'keyPlaceholderFallback').replace('{hint}', () => keyHint)
: t(keyRemoval === undefined && savedCredential ? 'keyPlaceholderSaved' : 'keyPlaceholderFallback').replace('{hint}', () => keyHint)
/** What both family editors take: the rows, whose layer owns them, and the two writes. */
const catalogProps = {
models,
@@ -462,10 +482,19 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
<span className={styles['fieldLabel']}>
{t('keyInput')}
{authHelp}
{keyText.length === 0 && props.credentialRequired !== true && removalRef !== undefined
&& (keyRemoval !== undefined || (savedCredential && detected?.[1]?.writable === true))
? <button
type="button"
className={styles['linkButton']}
disabled={disabled}
onClick={() => { setKeyDraft(keyRemoval !== undefined ? '' : { ref: removalRef }) }}
>{t(keyRemoval !== undefined ? 'keyRemoveUndo' : 'keyRemove')}</button>
: null}
</span>
<ApiKeyInput
t={t}
value={keyDraft}
value={keyText}
placeholder={keyPlaceholder}
aria-label={t('keyInput')}
aria-invalid={shownKeyFailure !== undefined && !protocolKeyMissing}
@@ -475,7 +504,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
disabled={disabled}
onChange={(event) => { setKeyDraft(event.target.value) }}
/>
{credentialHint === undefined ? null : <p id={`${props.provider}-credential-hint`} className={styles[missingRefs ? 'notice' : detectedRef === undefined ? 'advancedHint' : 'savedNotice']}>{credentialHint}</p>}
{credentialHint === undefined ? null : <p id={`${props.provider}-credential-hint`} className={styles[keyRemoval !== undefined || missingRefs ? 'notice' : detectedRef === undefined ? 'advancedHint' : 'savedNotice']}>{credentialHint}</p>}
{/* A key the protocol requires is a requirement still to meet, not a fault. */}
{shownKeyFailure === undefined
? null
@@ -597,7 +626,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode {
reasoningLevelsOnly={reasoning.levelsOnly}
defaultInput={Array.isArray(defaultInput) ? defaultInput : undefined}
probe={probe}
probeBlocked={shownKeyFailure}
probeBlocked={keyRemoval !== undefined ? 'keyRemovePending' : shownKeyFailure}
operations={operations}
onBusyChange={setListBusy}
/>
@@ -41,7 +41,12 @@ export const en = {
keyHide: 'Hide secret',
keyPlaceholder: 'Enter your API key',
keyPlaceholderFallback: 'Leave blank to use env as auth ({hint})',
keyPlaceholderSaved: 'Leave blank to use saved credentials',
keyPlaceholderSaved: 'Leave blank to keep current authentication (API key saved)',
keySaved: 'API key saved',
keySavedPreview: 'API key saved: {preview}',
keyRemove: 'Clear saved key',
keyRemoveUndo: 'Undo clear',
keyRemovePending: 'Save to clear the saved key and use environment authentication.',
keyFallbackMissing: 'Env var not detected. Enter an API key, or configure {hint} in your env.',
keyFallbackDetected: 'Env var detected. ({hint})',
keyFallbackDetectedHidden: 'Env var detected.',
@@ -217,7 +222,12 @@ export const zh: { [Key in keyof typeof en]: string } = {
keyHide: '隐藏密钥',
keyPlaceholder: '输入 API 密钥',
keyPlaceholderFallback: '留空使用环境认证({hint})',
keyPlaceholderSaved: '留空使用已保存凭据',
keyPlaceholderSaved: '留空保留现有认证(已保存 API key)',
keySaved: '已保存 API key',
keySavedPreview: '已保存 API key:{preview}',
keyRemove: '清除已保存密钥',
keyRemoveUndo: '撤销清除',
keyRemovePending: '保存后清除已保存密钥,并使用环境认证',
keyFallbackMissing: '未检测到环境变量。请填写 API 密钥,或设置环境变量 {hint}。',
keyFallbackDetected: '已检测到环境变量({hint})',
keyFallbackDetectedHidden: '已检测到环境变量',
@@ -390,7 +400,12 @@ export const ja = {
'keyHide': 'シークレットを非表示',
'keyPlaceholder': 'APIキーを入力',
'keyPlaceholderFallback': '空欄のままにすると環境変数を認証に使用します ({hint})',
'keyPlaceholderSaved': '空欄のままにすると保存済みの認証情報を使用します',
'keyPlaceholderSaved': '空欄のままにすると現在の認証を保持します(APIキー保存済み)',
keySaved: 'APIキー保存済み',
keySavedPreview: 'APIキー保存済み: {preview}',
keyRemove: '保存済みキーを削除',
keyRemoveUndo: '削除を取り消す',
keyRemovePending: '保存すると保存済みキーを削除し、環境変数の認証を使用します。',
'keyFallbackMissing': '環境変数が検出されません。APIキーを入力するか、環境変数に{hint}を設定してください。',
'keyFallbackDetected': '環境変数を検出しました。({hint})',
'keyFallbackDetectedHidden': '環境変数を検出しました。',
@@ -563,7 +578,12 @@ export const es = {
keyHide: 'Ocultar secreto',
keyPlaceholder: 'Ingrese su clave API',
keyPlaceholderFallback: 'Déjelo en blanco para usar env como autenticación ({hint})',
keyPlaceholderSaved: 'Déjelo en blanco para usar las credenciales guardadas',
keyPlaceholderSaved: 'Déjelo en blanco para conservar la autenticación actual (clave API guardada)',
keySaved: 'Clave API guardada',
keySavedPreview: 'Clave API guardada: {preview}',
keyRemove: 'Borrar clave guardada',
keyRemoveUndo: 'Deshacer borrado',
keyRemovePending: 'Guarde para borrar la clave guardada y usar la autenticación del entorno.',
keyFallbackMissing: 'No se detectó la variable de entorno. Ingrese una clave API o configure {hint} en su entorno.',
keyFallbackDetected: 'Se detectó var env. ({hint})',
keyFallbackDetectedHidden: 'Se detectó var env.',
@@ -736,7 +756,12 @@ export const fr = {
keyHide: 'Cacher le secret',
keyPlaceholder: 'Entrez votre clé API',
keyPlaceholderFallback: 'Laissez vide pour utiliser env comme authentification ({hint})',
keyPlaceholderSaved: "Laissez vide pour utiliser les informations d'identification enregistrées",
keyPlaceholderSaved: 'Laissez vide pour conserver l’authentification actuelle (clé API enregistrée)',
keySaved: 'Clé API enregistrée',
keySavedPreview: 'Clé API enregistrée : {preview}',
keyRemove: 'Effacer la clé enregistrée',
keyRemoveUndo: 'Annuler l’effacement',
keyRemovePending: 'Enregistrez pour effacer la clé enregistrée et utiliser l’authentification de l’environnement.',
keyFallbackMissing: "Var d'environnement non détectée. Entrez une clé API ou configurez {hint} dans votre environnement.",
keyFallbackDetected: "Var d'environnement détectée. ({hint})",
keyFallbackDetectedHidden: "Var d'environnement détectée.",
@@ -909,7 +934,12 @@ export const de = {
keyHide: 'Geheimnis verbergen',
keyPlaceholder: 'Geben Sie Ihren API-Schlüssel ein',
keyPlaceholderFallback: 'Lassen Sie das Feld leer, um env als Authentifizierung zu verwenden ({hint})',
keyPlaceholderSaved: 'Lassen Sie das Feld leer, um gespeicherte Anmeldeinformationen zu verwenden',
keyPlaceholderSaved: 'Leer lassen, um die aktuelle Authentifizierung beizubehalten (API-Schlüssel gespeichert)',
keySaved: 'API-Schlüssel gespeichert',
keySavedPreview: 'API-Schlüssel gespeichert: {preview}',
keyRemove: 'Gespeicherten Schlüssel löschen',
keyRemoveUndo: 'Löschen rückgängig machen',
keyRemovePending: 'Speichern, um den gespeicherten Schlüssel zu löschen und die Umgebungsauthentifizierung zu verwenden.',
keyFallbackMissing: 'Umgebungsvariable nicht erkannt. Geben Sie einen API-Schlüssel ein oder konfigurieren Sie {hint} in Ihrer Umgebung.',
keyFallbackDetected: 'Umgebungsvariable erkannt. ({hint})',
keyFallbackDetectedHidden: 'Umgebungsvariable erkannt.',
@@ -1082,7 +1112,12 @@ export const ru = {
keyHide: 'Скрыть секрет',
keyPlaceholder: 'Введите свой ключ API',
keyPlaceholderFallback: 'Оставьте пустым, чтобы использовать env в качестве аутентификации ({hint})',
keyPlaceholderSaved: 'Оставьте поле пустым, чтобы использовать сохраненные учетные данные.',
keyPlaceholderSaved: 'Оставьте поле пустым, чтобы сохранить текущую аутентификацию (API-ключ сохранён)',
keySaved: 'API-ключ сохранён',
keySavedPreview: 'API-ключ сохранён: {preview}',
keyRemove: 'Удалить сохранённый ключ',
keyRemoveUndo: 'Отменить удаление',
keyRemovePending: 'Сохраните, чтобы удалить сохранённый ключ и использовать аутентификацию из окружения.',
keyFallbackMissing: 'Переменная Env не обнаружена. Введите ключ API или настройте {hint} в своей среде.',
keyFallbackDetected: 'Обнаружена переменная Env. ({hint})',
keyFallbackDetectedHidden: 'Обнаружена переменная Env.',
@@ -1255,7 +1290,12 @@ export const pt = {
keyHide: 'Ocultar segredo',
keyPlaceholder: 'Insira sua chave API',
keyPlaceholderFallback: 'Deixe em branco para usar env como autenticação ({hint})',
keyPlaceholderSaved: 'Deixe em branco para usar credenciais salvas',
keyPlaceholderSaved: 'Deixe em branco para manter a autenticação atual (chave API salva)',
keySaved: 'Chave API salva',
keySavedPreview: 'Chave API salva: {preview}',
keyRemove: 'Limpar chave salva',
keyRemoveUndo: 'Desfazer limpeza',
keyRemovePending: 'Salve para limpar a chave salva e usar a autenticação do ambiente.',
keyFallbackMissing: 'Env var não detectado. Insira uma chave API ou configure {hint} em seu ambiente.',
keyFallbackDetected: 'Variável de ambiente detectada. ({hint})',
keyFallbackDetectedHidden: 'Variável de ambiente detectada.',
@@ -2204,14 +2204,14 @@ describe('apiKeyFailure', () => {
})
})
it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows only the blank-input environment detection for source %s', (source) => {
it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows the existing authentication with a blank input for source %s', (source) => {
renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), {
credential: { configured: true, source, writable: true },
})
const hint = en.keyFallbackDetected.replace('{hint}', 'OPENAI_API_KEY')
const input = screen.getByLabelText<HTMLInputElement>(en.keyInput)
expect(screen.queryByText(/^API key source:/)).toBeNull()
if (source === 'file') expect(screen.queryByText(hint)).toBeNull()
if (source === 'file') expect(screen.getByText(en.keySaved)).toBeTruthy()
else expect(screen.getAllByText(hint)).toHaveLength(1)
expect(input.value).toBe('')
expect(input.placeholder)
@@ -2221,10 +2221,135 @@ it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows only the bla
expect(screen.queryByText(/^API key source:/)).toBeNull()
expect(input.getAttribute('aria-describedby')).toBeNull()
fireEvent.change(input, { target: { value: '' } })
if (source === 'file') expect(screen.queryByText(hint)).toBeNull()
if (source === 'file') expect(screen.getByText(en.keySaved)).toBeTruthy()
else expect(screen.getAllByText(hint)).toHaveLength(1)
})
it.each(['openai', 'anthropic', 'google', 'deepseek', 'acme-gateway'])('shows only a saved-key preview for %s and preserves it when the draft is cleared', (provider) => {
const preview = 'sk-m…abcd'
const hint = en.keySavedPreview.replace('{preview}', preview)
renderPiAiEditor(provider, piAiNamespaceWith(provider, { apiKeyEnv: 'TEAM_API_KEY' }), {
credential: { configured: true, source: 'file', writable: true, preview },
})
const input = screen.getByLabelText<HTMLInputElement>(en.keyInput)
expect(input.value).toBe('')
expect(input.type).toBe('password')
expect(input.placeholder).toBe(en.keyPlaceholderSaved)
const notice = screen.getByText(hint)
expect(input.getAttribute('aria-describedby')).toBe(notice.id)
expect(screen.queryByLabelText(en.keyReveal)).toBeNull()
fireEvent.change(input, { target: { value: 'replacement-key' } })
expect(screen.queryByText(hint)).toBeNull()
fireEvent.change(input, { target: { value: '' } })
expect(screen.getByText(hint)).toBeTruthy()
expect(input.value).toBe('')
})
it('uses a managed preview from a credential provider with its own source label', () => {
renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), {
credential: { configured: true, source: 'keychain', writable: true, preview: 'sk-m…abcd' },
})
expect(screen.getByText(en.keySavedPreview.replace('{preview}', 'sk-m…abcd'))).toBeTruthy()
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).placeholder).toBe(en.keyPlaceholderSaved)
expect(screen.queryByText(/Env var detected/)).toBeNull()
})
it('stages key removal and lets Undo or Cancel retain the saved credential', async () => {
const { unset, set } = await mountSection()
fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) }))
fireEvent.click(screen.getByRole('button', { name: en.keyRemove }))
expect(screen.getByText(en.keyRemovePending)).toBeTruthy()
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).placeholder)
.toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY'))
expect(screen.queryByText(en.keySaved)).toBeNull()
expect(unset).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: en.keyRemoveUndo }))
expect(screen.getByText(en.keySaved)).toBeTruthy()
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).placeholder).toBe(en.keyPlaceholderSaved)
fireEvent.click(screen.getByRole('button', { name: en.keyRemove }))
fireEvent.click(screen.getByRole('button', { name: en.cancel }))
expect(unset).not.toHaveBeenCalled()
expect(set).not.toHaveBeenCalled()
})
it.each([
['google', 'GOOGLE_API_KEY', { env: ['GEMINI_API_KEY'], oauth: false }, true],
['openai', 'TEAM_API_KEY', { env: ['OPENAI_API_KEY'], oauth: false }, false],
['acme', 'ACME_API_KEY', undefined, false],
] as const)('clears %s through its saved reference and preserves the endpoint', async (provider, ref, nativeAuth, removesReference) => {
const { face, unset, set, mutate } = scriptedFace()
const namespace = piAiNamespaceWith(provider, { apiKeyEnv: ref, baseURL: 'https://gateway.example/v1' })
const closed = vi.fn()
render(<ProviderEditor provider={provider} displayName={provider} namespace={namespace}
settingsPath={['providers', provider]} schema={settingsSchema} operations={operationsWith(face)}
t={t} readOnly={false} onClose={closed} {...nativeAuth === undefined ? {} : { nativeAuth }}
credential={{ configured: true, source: 'file', writable: true }} />)
fireEvent.click(screen.getByRole('button', { name: en.keyRemove }))
expect(screen.getByLabelText<HTMLInputElement>(en.keyInput).placeholder)
.toBe(en.keyPlaceholderFallback.replace('{hint}', removesReference && nativeAuth !== undefined ? nativeAuth.env[0] : ref))
fireEvent.click(screen.getByText(en.customized))
expect(screen.getByRole<HTMLButtonElement>('button', { name: en.fetchModels }).disabled).toBe(true)
fireEvent.click(screen.getByRole('button', { name: en.apply }))
await waitFor(() => { expect(closed).toHaveBeenCalledWith(true) })
expect(unset).toHaveBeenCalledExactlyOnceWith(ref)
expect(set).not.toHaveBeenCalled()
if (removesReference) expect(mutate.mock.calls[0]?.[1])
.toEqual([{ op: 'unset', path: ['providers', provider, 'apiKeyEnv'] }])
else expect(mutate).not.toHaveBeenCalled()
})
it('can replace a key after its removal was refused, without losing its derived reference', async () => {
const namespace = piAiNamespaceWith('google', { apiKeyEnv: 'GOOGLE_API_KEY' })
const written = { ...namespace, revision: namespace.revision + 1,
user: { providers: { google: {} } }, value: { providers: { google: {} } } }
const mutate: ReturnType<typeof vi.fn> = vi.fn(() => Promise.resolve(remoteOk(written)))
const { face, unset, set } = scriptedFace({
mutate, unset: vi.fn(() => Promise.resolve(remoteFail('credential store locked'))),
})
render(<ProviderEditor provider="google" displayName="Google" namespace={namespace}
settingsPath={['providers', 'google']} schema={settingsSchema} operations={operationsWith(face)}
t={t} readOnly={false} onClose={vi.fn()} nativeAuth={{ env: ['GEMINI_API_KEY'], oauth: false }}
credential={{ configured: true, source: 'file', writable: true }} />)
fireEvent.click(screen.getByRole('button', { name: en.keyRemove }))
fireEvent.click(screen.getByRole('button', { name: en.apply }))
await screen.findByText('credential store locked')
expect(screen.getByText(en.keyRemovePending)).toBeTruthy()
fireEvent.change(screen.getByLabelText(en.keyInput), { target: { value: 'new-key' } })
fireEvent.click(screen.getByRole('button', { name: en.apply }))
await waitFor(() => { expect(set).toHaveBeenCalledExactlyOnceWith('GOOGLE_API_KEY', 'new-key') })
expect(unset).toHaveBeenCalledTimes(1)
expect(mutate.mock.calls[1]?.[1]).toEqual([
{ op: 'set', path: ['providers', 'google', 'apiKeyEnv'], value: 'GOOGLE_API_KEY' },
])
})
it('clears the selected reference when refreshed metadata names a different credential', async () => {
const { face, unset, mutate } = scriptedFace()
const props: ProviderEditorProps = {
provider: 'openai', displayName: 'OpenAI', namespace: piAiNamespaceWith('openai', { apiKeyEnv: 'OLD_KEY' }),
settingsPath: ['providers', 'openai'], schema: settingsSchema, operations: operationsWith(face),
t, readOnly: false, onClose: vi.fn(), credential: { configured: true, source: 'file', writable: true },
}
const view = render(<ProviderEditor {...props} />)
fireEvent.click(screen.getByRole('button', { name: en.keyRemove }))
view.rerender(<ProviderEditor {...props} namespace={piAiNamespaceWith('openai', { apiKeyEnv: 'NEW_KEY' })} />)
fireEvent.click(screen.getByRole('button', { name: en.apply }))
await waitFor(() => { expect(unset).toHaveBeenCalledExactlyOnceWith('OLD_KEY') })
expect(mutate).not.toHaveBeenCalled()
})
it('clears the detected native key instead of an unused derived reference', async () => {
const { face, unset, mutate } = scriptedFace()
render(<ProviderEditor provider="google" displayName="Google" namespace={piAiNamespaceWith('google', {})}
settingsPath={['providers', 'google']} schema={settingsSchema} operations={operationsWith(face)}
t={t} readOnly={false} onClose={vi.fn()} nativeAuth={{ env: ['GEMINI_API_KEY'], oauth: false }}
credentialChecks={{ GEMINI_API_KEY: { configured: true, source: 'file', writable: true } }} />)
fireEvent.click(screen.getByRole('button', { name: en.keyRemove }))
fireEvent.click(screen.getByRole('button', { name: en.apply }))
await waitFor(() => { expect(unset).toHaveBeenCalledExactlyOnceWith('GEMINI_API_KEY') })
expect(mutate).not.toHaveBeenCalled()
})
it.each([
['unconfigured', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: false, source: 'env', writable: true }],
['unknown source', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: true, source: 'oauth', writable: true }],
@@ -24,8 +24,8 @@
en: fccad7d354c2af71
zh: 5b95b5890e21f80f
/deepseek-ai-dsh-credentials-local/use-this-package/storing-and-removing-keys:
en: 5e3d45470142b9dd
zh: 1f8358f987769d3a
en: 892c025758def492
zh: 2b04ea8dabee95aa
/deepseek-ai-dsh-credentials-local/use-this-package/where-keys-come-from:
en: a55fac148b62e007
zh: fdb3d19ccae676ee
@@ -60,11 +60,11 @@ declare const ctx: Context
const ref = credentialRef('DEEPSEEK_API_KEY')
await ctx.credentials.set(ref, 'sk-…') // save
await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value
await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value
await ctx.credentials.unset(ref) // remove
```
A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the value itself. Records persist in the same file, addressed by `<owner>/<id>` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`).
A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the full value. Stored keys longer than 12 characters expose only their first and last four characters in `preview`; shorter keys are fully masked. Environment credentials have no preview. Records persist in the same file, addressed by `<owner>/<id>` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`).
### Where keys come from
@@ -60,11 +60,11 @@ declare const ctx: Context
const ref = credentialRef('DEEPSEEK_API_KEY')
await ctx.credentials.set(ref, 'sk-…') // save
await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value
await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value
await ctx.credentials.unset(ref) // remove
```
你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回值本身。记录也持久化在同一文件中:插件按 `<owner>/<id>` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。
你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回完整值。超过 12 个字符的已保存密钥只在 `preview` 中显示首尾各四个字符;较短密钥全部遮住。环境凭据不提供摘要。记录也持久化在同一文件中:插件按 `<owner>/<id>` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。
### 密钥从哪里来
@@ -633,7 +633,10 @@ export class LocalCredentialProvider extends CredentialProvider {
override describe(ref: CredentialRef): Promise<CredentialInfo> {
const stored = this.values.get(ref)
if (stored !== undefined) return Promise.resolve({ configured: true, source: 'file', writable: true })
if (stored !== undefined) return Promise.resolve({
configured: true, source: 'file', writable: true,
preview: stored.length > 12 ? `${stored.slice(0, 4)}…${stored.slice(-4)}` : '••••••••',
})
// Every reference is writable: a set writes the managed file, which
// outranks every fallback, and an unset exposes the fallback again.
if (this.inherited(ref) !== undefined) return Promise.resolve({ configured: true, source: 'env', writable: true })
@@ -59,6 +59,23 @@ describe('resolveSpec', () => {
})
describe('layering and reads', () => {
it.each([
['a', '••••••••'],
['123456789012', '••••••••'],
['1234567890123', '1234…0123'],
['sk-managed-secret-abcd', 'sk-m…abcd'],
])('describes a stored credential with a masked preview (%s)', async (value, preview) => {
const dir = await tempDir()
const ctx = await boot({ path: join(dir, '.credentials.yaml'), watch: false })
await ctx.credentials.set(KEY, value)
const info = await ctx.credentials.describe(KEY)
expect(info).toEqual({ configured: true, source: 'file', writable: true, preview })
expect(info.preview).not.toBe(value)
expect(await ctx.credentials.resolve(KEY)).toEqual({ value, source: 'file' })
await ctx.credentials.unset(KEY)
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: false, writable: true })
})
it('treats an absent file as an empty writable store', async () => {
const dir = await tempDir()
const ctx = await boot({ path: join(dir, '.credentials.yaml'), watch: false })
@@ -73,7 +90,7 @@ describe('layering and reads', () => {
const ctx = await boot({ path, watch: false })
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'plain', source: 'file' })
expect(await ctx.credentials.resolve(OTHER)).toEqual({ value: 'with space', source: 'file' })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' })
})
it('lets the managed file win over a non-empty process environment', async () => {
@@ -83,7 +100,7 @@ describe('layering and reads', () => {
const ctx = await boot({ path, watch: false })
vi.stubEnv('DSH_CRED_TEST', 'from-env')
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-file', source: 'file' })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' })
})
it('treats an empty environment value as absent, falling through to the file', async () => {
@@ -93,7 +110,7 @@ describe('layering and reads', () => {
const ctx = await boot({ path, watch: false })
vi.stubEnv('DSH_CRED_TEST', '')
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' })
})
it('fails boot loud when the document exists but cannot be read', async () => {
@@ -131,7 +148,7 @@ describe('layer ladder', () => {
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' })
// A key sitting in the user's .env does not make the stored one
// unwritable.
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' })
await expect(ctx.credentials.set(KEY, 'rotated')).resolves.toBeUndefined()
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'rotated', source: 'file' })
})
@@ -230,7 +247,7 @@ describe('layer ladder', () => {
{ source: 'user-env', path: '/home/.dsh/.env', values: { DSH_CRED_TEST: 'from-user-env' } },
])
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' })
await expect(ctx.credentials.set(KEY, 'next')).resolves.toBeUndefined()
expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'next', source: 'file' })
})
@@ -382,7 +399,7 @@ describe('document writes', () => {
const reread = await boot({ path, watch: false })
expect(await reread.credentials.resolve(KEY)).toEqual({ value: multiLine, source: 'file' })
expect(await reread.credentials.resolve(OTHER)).toEqual({ value: mixedQuotes, source: 'file' })
expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true })
expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: 'line… two' })
})
it('unsets only the owning entry, with its own annotation, and keeps an absent unset silent', async () => {
@@ -24,8 +24,8 @@
en: 8f3500119608f91b
zh: 147fdb5389affbc0
/deepseek-ai-dsh-credentials/use-this-package/storing-checking-and-removing-keys:
en: fa334e2d4438e0b6
zh: 009b9252ed046886
en: d354985614dafc0d
zh: 3ff9fdd480521283
/deepseek-ai-dsh-credentials/use-this-package/storing-updating-and-removing-records:
en: 300c3f1f13abdca4
zh: ec7a6486ac88889c
+2 -2
View File
@@ -53,12 +53,12 @@ declare const ctx: Context
const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded
const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined
const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value
const info = await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value
await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks
await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again
```
Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value.
Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the full value. A provider may supply a masked `preview` for a managed key; ambient credentials have no preview.
### Storing, updating, and removing records
@@ -53,12 +53,12 @@ declare const ctx: Context
const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded
const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined
const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value
const info = await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value
await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks
await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again
```
用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。
用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回完整值。提供方可为托管密钥提供脱敏的 `preview`;环境凭据不提供摘要。
### 存储、更新与移除记录
@@ -61,14 +61,16 @@ export type CredentialRecord = ApiKeyRecord | GrantRecord
/**
* Source and writability facts for one reference, safe for configuration UIs —
* never the value. The view has no slot a value could ride in, which is what
* lets the whole read half cross the Remote wire.
* never the full value. Providers may include a masked preview of a managed
* credential; ambient credentials do not expose a preview.
*/
export interface CredentialInfo {
/** Whether resolving the reference would currently return a value. */
configured: boolean
/** Source layer currently supplying the value; absent while unconfigured. */
source?: string
/** Masked managed value for display only; short values must be fully masked. */
preview?: string
/** Whether the active provider can write this reference. */
writable: boolean
}
@@ -6280,7 +6280,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'CredentialInfo',
declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n writable: boolean;\n}',
declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n preview?: string;\n writable: boolean;\n}',
},
{
name: 'CredentialKey',