fix(account): invalidate a rejected token on the account service mounted at rejection
- deepseek-account: the request credential's reject() re-resolves the account service through the resolving context, so a reload between a request and the destination's HTTP 401 still removes the stored grant; without a mounted service the grant stays for the next one to reject. resolveToken and rejectToken become private; the e2e sign-in stand-in and the generated API catalog follow. - llm-deepseek: routeCredential().resolve() publishes the grant's headers, value, and rejection only, keeping the adapter's onRequestError behind the seam. - web-deepseek-api: a route publishing an unparsable base URL becomes a misconfigured source instead of throwing from readiness or dispatch.
This commit is contained in:
1 parent
7d83af645c
commit
3ca18d169f
20 files changed
+162
-108
No files matched your search
@@ -142,8 +142,10 @@ it.skipIf(MODE === 'record')('reuses saved native Account Flash translations acr
|
||||
const account = scaffold.ctx.get('deepseekAccount')
|
||||
if (account === undefined) throw new Error('Shipped native Account service is absent')
|
||||
// Only credential acquisition is nondeterministic; the Loader-owned native route and wire remain real.
|
||||
const auth = vi.spyOn(account, 'resolveToken').mockImplementation(async (url: string) =>
|
||||
new URL(url).origin === origin ? 'paid-browser-fixture-token' : undefined)
|
||||
const auth = vi.spyOn(account, 'resolveRequestCredential').mockImplementation(async (url: string) =>
|
||||
new URL(url).origin === origin
|
||||
? { headers: { 'x-dsh-auth-token': 'paid-browser-fixture-token' }, value: 'paid-browser-fixture-token', reject: () => Promise.resolve() }
|
||||
: undefined)
|
||||
resources.restoreAuth = () => { auth.mockRestore() }
|
||||
scaffold.ctx.emit('llm/adapters-updated')
|
||||
const owner = [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'llm-deepseek-account')
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
en: 2302e2999588bac3
|
||||
zh: 5e0ac058b50036dc
|
||||
/deepseek-account/request-credentials:
|
||||
en: 76f2eb1df1948c8a
|
||||
zh: 70f698243f8e3ae8
|
||||
en: 808ace524e0dbc0b
|
||||
zh: c4268221fa4c1c09
|
||||
/deepseek-account/embedded-platform-credentials:
|
||||
en: 9a651d70acbe83a6
|
||||
zh: 4624b0299f5fdd8e
|
||||
/deepseek-account/cordis-api/deepseek-account-events/deepseek-account-signed-out-emit:
|
||||
en: b2c8c533124a121c
|
||||
zh: c2a5c227b5a01146
|
||||
en: 3065c17cb319f756
|
||||
zh: e69c2692a109c38b
|
||||
@@ -8,7 +8,7 @@ Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/accoun
|
||||
|
||||
## Request credentials
|
||||
|
||||
`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `resolveToken(url)` returns the bare token under the same policy for consumers that compose their own request, and `rejectToken(token)` is the invalidation `reject()` performs.
|
||||
`resolveRequestCredential(url)` is Host-only. It answers `undefined` while signed out, during credential removal, and for any destination outside the configured `inferenceOrigin`; otherwise it returns an `AccountRequestCredential` whose `headers` carry the token as `x-dsh-auth-token`, whose `value` is the bare token, and whose `reject()` removes the stored grant only while it still matches that token, containing storage failures so the caller reports the destination's rejection. The `deepseek-account` model route publishes this credential through `ctx.llm.routeCredential('deepseek-account')` ([LLM streaming](llm-streaming.md)); the DeepSeek web providers consume it there and, without that route, ask the account service directly. `reject()` runs on the account service mounted when it is called, so a reload between a request and the destination's answer still removes the grant; without a mounted service it leaves the grant for the next one to reject.
|
||||
|
||||
Model routes that bill the account register a running-task report with `registerRunningTaskReport(report)` inside `ctx.effect()`; `hasRunningAccountTasks()` answers true while any report does, so the sign-out confirmation can warn about work the sign-out interrupts. The route plugin owns cancellation of that work after `deepseek-account/signed-out`.
|
||||
|
||||
@@ -81,13 +81,6 @@ Account login, credentials, and client-safe Remote operations.
|
||||
*/
|
||||
@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise<boolean>
|
||||
|
||||
/**
|
||||
* Remove an inference-rejected token only while it still matches the stored login.
|
||||
* @param token - token captured by the rejected inference request.
|
||||
* @returns after matching credentials are removed and the expiry notification is emitted.
|
||||
*/
|
||||
async rejectToken(token: string): Promise<void>
|
||||
|
||||
/**
|
||||
* Read existing login identity without creating a device or returning credentials.
|
||||
* @returns optional device/account identifiers and the provider's OS version string.
|
||||
@@ -101,16 +94,10 @@ async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId;
|
||||
*/
|
||||
async getPlatformSession(): Promise<PlatformSession | null>
|
||||
|
||||
/**
|
||||
* Resolve a credential only for the inference origin allowed by the provider.
|
||||
* @param url - actual request destination or API base URL.
|
||||
* @returns stored token, or undefined for other origins or a signed-out account.
|
||||
*/
|
||||
async resolveToken(url: string): Promise<string | undefined>
|
||||
|
||||
/**
|
||||
* Release the account credential for one request to `url` as the request
|
||||
* carries it, together with its invalidation. Host-only.
|
||||
* carries it, together with its invalidation, which runs on the account
|
||||
* service mounted when it is called. Host-only.
|
||||
* @param url - actual request destination or API base URL.
|
||||
* @returns the request credential, or undefined for other origins or a signed-out account.
|
||||
*/
|
||||
@@ -229,6 +216,6 @@ Local grant removal has completed.
|
||||
Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
|
||||
The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveToken, resolveRequestCredential, registerRunningTaskReport, and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/account/deepseek-account/README.md).
|
||||
The account Service Definition exposes getState, getProfile, getBalance, getNotifications, getNotificationContent, reportNotificationEvent, startSignIn, cancelSignIn, signOut, watch, and Host-only resolveRequestCredential, registerRunningTaskReport, and getPlatformSession. The platform provider implements it with an AuthorizationFlow and a private GrantRecord. AccountView distinguishes stored presence from server validation; attempt IDs bind cancellation to one local flow. AccountUpdate carries a complete AccountView in state and a type of snapshot for initial or progress updates, or credentials-changed for credential writes and removal. Pending credential changes take priority over progress updates. See [the account package](../../packages/account/deepseek-account/README.md).
|
||||
|
||||
`AccountClientMetadata` carries `version` from the caller’s `DSH_CLIENT_VERSION`, its active UI `locale`, and `timezoneOffsetSeconds` sampled when the operation begins. The offset is local time minus UTC in seconds: UTC+8 is `28800`. It contains no credentials. Login attempts retain their initiating metadata through exchange and cancellation; sign-out retains its metadata for revocation retries.
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
## 请求凭据
|
||||
|
||||
`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`resolveToken(url)` 在同一策略下为自行组装请求的消费方返回裸 token,`rejectToken(token)` 则是 `reject()` 执行的失效操作。
|
||||
`resolveRequestCredential(url)` 仅限 Host。未登录、凭据删除进行中,以及目标地址不在配置的 `inferenceOrigin` 之内时,它回答 `undefined`;否则返回一个 `AccountRequestCredential`:`headers` 以 `x-dsh-auth-token` 携带 token,`value` 是裸 token,`reject()` 仅在已存授权仍与该 token 一致时删除它,并隔离存储失败,使调用方报告的是目标地址的拒绝。`deepseek-account` 模型路由通过 `ctx.llm.routeCredential('deepseek-account')`([LLM 流式](llm-streaming.zh.md))发布这份凭据;DeepSeek Web 提供方在那里消费它,没有该路由时直接询问账号服务。`reject()` 在被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会移除授权;没有挂载的服务时,授权留给下一个挂载的服务处理。
|
||||
|
||||
按账号计费的模型路由在 `ctx.effect()` 内用 `registerRunningTaskReport(report)` 注册运行中任务报告;只要有报告回答 true,`hasRunningAccountTasks()` 就回答 true,使退登确认能够提醒退登将打断的工作。`deepseek-account/signed-out` 之后取消这些工作由路由插件负责。
|
||||
|
||||
@@ -81,13 +81,6 @@ Account login, credentials, and client-safe Remote operations.
|
||||
*/
|
||||
@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise<boolean>
|
||||
|
||||
/**
|
||||
* Remove an inference-rejected token only while it still matches the stored login.
|
||||
* @param token - token captured by the rejected inference request.
|
||||
* @returns after matching credentials are removed and the expiry notification is emitted.
|
||||
*/
|
||||
async rejectToken(token: string): Promise<void>
|
||||
|
||||
/**
|
||||
* Read existing login identity without creating a device or returning credentials.
|
||||
* @returns optional device/account identifiers and the provider's OS version string.
|
||||
@@ -101,16 +94,10 @@ async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId;
|
||||
*/
|
||||
async getPlatformSession(): Promise<PlatformSession | null>
|
||||
|
||||
/**
|
||||
* Resolve a credential only for the inference origin allowed by the provider.
|
||||
* @param url - actual request destination or API base URL.
|
||||
* @returns stored token, or undefined for other origins or a signed-out account.
|
||||
*/
|
||||
async resolveToken(url: string): Promise<string | undefined>
|
||||
|
||||
/**
|
||||
* Release the account credential for one request to `url` as the request
|
||||
* carries it, together with its invalidation. Host-only.
|
||||
* carries it, together with its invalidation, which runs on the account
|
||||
* service mounted when it is called. Host-only.
|
||||
* @param url - actual request destination or API base URL.
|
||||
* @returns the request credential, or undefined for other origins or a signed-out account.
|
||||
*/
|
||||
@@ -229,6 +216,6 @@ Local grant removal has completed.
|
||||
Source: [`packages/account/deepseek-account/src/index.ts`](../../packages/account/deepseek-account/src/index.ts)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
|
||||
账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveToken、resolveRequestCredential、registerRunningTaskReport 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/account/deepseek-account/README.zh.md)。
|
||||
账号服务定义提供 getState、getProfile、getBalance、getNotifications、getNotificationContent、reportNotificationEvent、startSignIn、cancelSignIn、signOut、watch 及仅限 Host 的 resolveRequestCredential、registerRunningTaskReport 和 getPlatformSession。平台提供者使用 AuthorizationFlow 和私有 GrantRecord 实现这些操作。AccountView 区分本地存在与服务器验证;尝试 ID 将取消绑定到单次本地流程。AccountUpdate 的 state 携带完整 AccountView,type 为 snapshot 时表示首次或进度更新,为 credentials-changed 时表示凭据写入或删除。待发送的凭据变化优先于进度更新。参见[账号包](../../packages/account/deepseek-account/README.zh.md)。
|
||||
|
||||
`AccountClientMetadata` 携带调用方 `DSH_CLIENT_VERSION` 提供的 `version`、当前界面 `locale`,以及操作发起时采样的 `timezoneOffsetSeconds`。偏移为本地时间减 UTC 的秒数:UTC+8 对应 `28800`。其中不含凭证。登录申请在兑换及取消期间保留发起时的元数据;退出操作为撤销重试保留其元数据。
|
||||
@@ -9,8 +9,8 @@
|
||||
en: f0139803159ee9c9
|
||||
zh: 73bd5dfd53ed8d36
|
||||
/deepseek-routes-publish-the-credential-web-consumers-reuse/change:
|
||||
en: 7a63f24e07fb3d33
|
||||
zh: 99c64684a589088e
|
||||
en: 09ab43933a9e5950
|
||||
zh: a18da5d560cf0c9f
|
||||
/deepseek-routes-publish-the-credential-web-consumers-reuse/migration:
|
||||
en: 64ac045c8d9a1336
|
||||
zh: 4712f6eacd85a151
|
||||
@@ -9,13 +9,13 @@ English | [中文](guide.zh.md)
|
||||
|
||||
## Change
|
||||
|
||||
`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a value-free `configured(endpoint)` check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`.
|
||||
`LlmAdapter.routeCredential(provider)` and `LlmRuntime.routeCredential(provider)` publish a route's current credential as a `RouteCredential`: kind, resolved base URL, optional reference, a `configured(endpoint)` presence check, and `resolve(endpoint, signal)` returning a `RouteCredentialGrant` with protocol headers, the bare value, and an optional `reject()`.
|
||||
|
||||
`@deepseek-ai/dsh-llm-deepseek` no longer exports `resolveDeepSeekApiKey`, `deepSeekApiKeyConfigured`, `resolveDeepSeekAccountToken`, or `rejectDeepSeekAccountToken`. `DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` returns `DeepSeekRequestAuth | undefined`, and `DeepSeekRequestAuth` requires `value` beside `headers`; the new `missingCredential` and `credential` options name the missing-credential failure and the published credential. `createModelListingCache` takes `credential(url)` returning request headers, and its `load` is optional.
|
||||
|
||||
`@deepseek-ai/dsh-llm-deepseek-api-key` no longer exports `plainOptions` and `resolveAdapterOptions`; `@deepseek-ai/dsh-llm-deepseek-account` no longer exports `plainAccountOptions` and `resolveAccountOptions`. The account route plugin cancels its running Agents after sign-out and registers a running-task report.
|
||||
|
||||
`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)`; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`.
|
||||
`@deepseek-ai/dsh-deepseek-account` adds Host-only `resolveRequestCredential(url)` and `registerRunningTaskReport(report)` and makes `resolveToken(url)` and `rejectToken(token)` private; `hasRunningAccountTasks()` answers from registered reports and no longer reads `ctx.agents`. The package drops its `dsh-agent` and `dsh-llm` peer dependencies and moves from `packages/credentials/` to `packages/account/` under its unchanged name. `@deepseek-ai/dsh-credentials` adds `resolveCredentialRef(ctx, ref)` and `credentialRefConfigured(ctx, ref)`.
|
||||
|
||||
`@deepseek-ai/dsh-web-deepseek-api` drops its peer dependencies on `dsh-llm-deepseek`, both route plugins, and `cordis-plugin-loader`; `@deepseek-ai/dsh-web-search-deepseek` drops `dsh-llm-deepseek` and `dsh-deepseek-account` and adds `dsh-llm`. Both read route credentials through `ctx.llm.routeCredential()`, so an adapter registered under a DeepSeek route id without a published credential counts as no route. Without the account route, the Search and Fetch APIs send the account credential to the origin `DEEPSEEK_BASE_URL` names and reject a value that is not an HTTP(S) URL without embedded credentials. `DeepSeekSearchProviderOptions` replaces `resolveAccountToken` and `rejectAccountToken` with `resolveAccountCredential(endpoint)`.
|
||||
|
||||
|
||||
@@ -9,13 +9,13 @@ description: "DeepSeek 模型路由通过 ctx.llm.routeCredential() 发布自己
|
||||
|
||||
## 变更
|
||||
|
||||
`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、不读取值的 `configured(endpoint)` 检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。
|
||||
`LlmAdapter.routeCredential(provider)` 与 `LlmRuntime.routeCredential(provider)` 把路由当前的凭据发布为 `RouteCredential`:种类、解析后的基础地址、可选引用、`configured(endpoint)` 存在性检查,以及返回 `RouteCredentialGrant` 的 `resolve(endpoint, signal)`,授权包含协议请求头、裸值和可选的 `reject()`。
|
||||
|
||||
`@deepseek-ai/dsh-llm-deepseek` 不再导出 `resolveDeepSeekApiKey`、`deepSeekApiKeyConfigured`、`resolveDeepSeekAccountToken` 和 `rejectDeepSeekAccountToken`。`DeepSeekAdapterOptions.resolveAuth(connection, endpoint)` 返回 `DeepSeekRequestAuth | undefined`,且 `DeepSeekRequestAuth` 在 `headers` 之外要求 `value`;新增的 `missingCredential` 与 `credential` 选项分别命名凭据缺失的失败和发布的凭据。`createModelListingCache` 的 `credential(url)` 返回请求头,其 `load` 变为可选。
|
||||
|
||||
`@deepseek-ai/dsh-llm-deepseek-api-key` 不再导出 `plainOptions` 和 `resolveAdapterOptions`;`@deepseek-ai/dsh-llm-deepseek-account` 不再导出 `plainAccountOptions` 和 `resolveAccountOptions`。账号路由插件在退登后取消其运行中的 Agent,并注册运行中任务报告。
|
||||
|
||||
`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。
|
||||
`@deepseek-ai/dsh-deepseek-account` 新增仅限 Host 的 `resolveRequestCredential(url)` 与 `registerRunningTaskReport(report)`,并将 `resolveToken(url)` 与 `rejectToken(token)` 改为私有;`hasRunningAccountTasks()` 根据注册的报告作答,不再读取 `ctx.agents`。该包移除 `dsh-agent` 与 `dsh-llm` peer 依赖,并以不变的名字从 `packages/credentials/` 移至 `packages/account/`。`@deepseek-ai/dsh-credentials` 新增 `resolveCredentialRef(ctx, ref)` 与 `credentialRefConfigured(ctx, ref)`。
|
||||
|
||||
`@deepseek-ai/dsh-web-deepseek-api` 移除对 `dsh-llm-deepseek`、两个路由插件和 `cordis-plugin-loader` 的 peer 依赖;`@deepseek-ai/dsh-web-search-deepseek` 移除 `dsh-llm-deepseek` 与 `dsh-deepseek-account`,新增 `dsh-llm`。两者都通过 `ctx.llm.routeCredential()` 读取路由凭据,因此以 DeepSeek 路由 id 注册但不发布凭据的适配器视为没有路由。没有账号路由时,Search 与 Fetch API 把账号凭据发往 `DEEPSEEK_BASE_URL` 所指的 origin,并拒绝不是不含内嵌凭据的 HTTP(S) URL 的值。`DeepSeekSearchProviderOptions` 用 `resolveAccountCredential(endpoint)` 替换 `resolveAccountToken` 与 `rejectAccountToken`。
|
||||
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
en: 9dbb9bc3960a11fe
|
||||
zh: ed58987926489d3e
|
||||
/deepseek-ai-dsh-deepseek-account:
|
||||
en: 06fe55f319bd1b2c
|
||||
zh: 9559b712e50bbc73
|
||||
en: d5aad878bc7d3059
|
||||
zh: 3573506e849ad4d4
|
||||
/deepseek-ai-dsh-deepseek-account/summary:
|
||||
en: 28bcca957bf6abf4
|
||||
zh: 4a3fc8a59f2925bc
|
||||
@@ -15,8 +15,8 @@
|
||||
en: af856ba79fe31b8e
|
||||
zh: 15b7d1a5d1856de2
|
||||
/deepseek-ai-dsh-deepseek-account/use-this-package:
|
||||
en: 02b899ac5ad80227
|
||||
zh: 0cb4d6984ae6ed62
|
||||
en: 210ba1bd070bb8c4
|
||||
zh: 4e1286bff076a3b6
|
||||
/deepseek-ai-dsh-deepseek-account/understand-the-implementation:
|
||||
en: 76d2da2dab100ac3
|
||||
zh: 2c9404f27915daab
|
||||
|
||||
@@ -9,11 +9,11 @@ English | [中文](README.zh.md)
|
||||
|
||||
Every operation that reaches Platform takes the caller's `AccountClientMetadata`: the client version, the active UI language, and the UTC offset in seconds. The service derives the five Platform client headers from that metadata and the composition's platform, so each request reports the UI that made it instead of the last caller the Host saw. A new sign-in attempt captures the metadata for its initialization, exchange, and cancellation, and a joining caller never replaces it; sign-out captures the metadata for the revocation retries that outlive the request.
|
||||
|
||||
getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the model/file origin configured for resolveToken. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID; the snapshot issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot.
|
||||
getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the inference origin that `resolveRequestCredential` enforces. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID; the snapshot issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot.
|
||||
|
||||
`desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin.
|
||||
|
||||
Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that performs that removal after an HTTP 401 while containing storage failures; the account model route and the DeepSeek web providers use it instead of composing headers themselves.
|
||||
Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. `resolveRequestCredential(url)` releases the credential for one allowed destination as the request headers, the bare token, and a `reject()` that removes the stored grant after an HTTP 401 while it still matches that token, containing storage failures; the removal runs on the account service mounted when `reject()` is called, so a reload between the request and the destination's answer still removes the grant. The account model route and the DeepSeek web providers use it instead of composing headers themselves.
|
||||
|
||||
## Summary
|
||||
|
||||
@@ -32,7 +32,7 @@ Device identity reads validate the existing login device record and expose only
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
The service exposes its client-safe operations through the `account` Remote namespace. The application loads its generated `./remote` contribution; no separate controller is needed. Login, profile, balance, notification, sign-out-impact, and expiry operations remain available through `ctx.remote.account`. Remote `watch` omits the Host-only identity subscription option. `resolveToken`, `rejectToken`, `getPlatformSession`, and `getDeviceIdentity` remain Host-only.
|
||||
The service exposes its client-safe operations through the `account` Remote namespace. The application loads its generated `./remote` contribution; no separate controller is needed. Login, profile, balance, notification, sign-out-impact, and expiry operations remain available through `ctx.remote.account`. Remote `watch` omits the Host-only identity subscription option. `resolveRequestCredential`, `getPlatformSession`, and `getDeviceIdentity` remain Host-only.
|
||||
|
||||
`DeepSeekAccount` is the concrete service owning login, credentials, and Remote operations. The `/types` entry exposes types without loading the service implementation. `watch` returns complete state tagged as `snapshot` or `credentials-changed`; Host-only `watch(signal, true)` also receives profile-identity changes, while Remote subscriptions omit that option.
|
||||
|
||||
|
||||
@@ -9,11 +9,11 @@ kind: "package-reference"
|
||||
|
||||
每个到达 Platform 的操作都接收调用方的 `AccountClientMetadata`:客户端版本、当前界面语言和以秒为单位的 UTC 偏移。服务据此与组合出的平台推导五个 Platform 客户端请求头,因此每个请求报告的是发起它的界面,而不是 Host 上一次见到的调用方。新的登录申请会为该申请的初始化、兑换和取消捕获这份元数据,中途加入的调用方不会替换它;退登则为在请求之后继续进行的撤销重试捕获这份元数据。
|
||||
|
||||
getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 resolveToken 配置的模型及文件请求来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。
|
||||
getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 `resolveRequestCredential` 限定的推理来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。
|
||||
|
||||
`desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。
|
||||
|
||||
资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后执行上述清除并隔离存储失败。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。
|
||||
资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。`resolveRequestCredential(url)` 把一个允许目标的凭据以请求头、裸 token 和 `reject()` 的形式释放;`reject()` 在 HTTP 401 后、且存储的授权仍匹配该 token 时清除它并隔离存储失败;清除在 `reject()` 被调用时挂载的账号服务上执行,因此请求与目的地应答之间发生的重载仍会清除授权。账号模型路由和 DeepSeek Web 提供方使用它,而不自行组装请求头。
|
||||
|
||||
## 概述
|
||||
|
||||
@@ -32,7 +32,7 @@ getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导
|
||||
<a id="use-this-package"></a>
|
||||
## 使用此包
|
||||
|
||||
服务通过 `account` Remote 命名空间暴露可供客户端使用的操作。应用加载其生成的 `./remote` 贡献,无需单独的 controller。登录、资料、余额、通知、退出影响检查和凭据过期操作均通过 `ctx.remote.account` 调用。Remote `watch` 不接受仅供 Host 使用的身份订阅选项。`resolveToken`、`rejectToken`、`getPlatformSession` 和 `getDeviceIdentity` 仍仅供 Host 使用。
|
||||
服务通过 `account` Remote 命名空间暴露可供客户端使用的操作。应用加载其生成的 `./remote` 贡献,无需单独的 controller。登录、资料、余额、通知、退出影响检查和凭据过期操作均通过 `ctx.remote.account` 调用。Remote `watch` 不接受仅供 Host 使用的身份订阅选项。`resolveRequestCredential`、`getPlatformSession` 和 `getDeviceIdentity` 仍仅供 Host 使用。
|
||||
|
||||
`DeepSeekAccount` 是具体服务,拥有登录、凭证和 Remote 操作。`/types` 提供不加载服务实现的类型出口。`watch` 返回完整状态与 `snapshot` 或 `credentials-changed` 类型;仅 Host 的 `watch(signal, true)` 还接收资料身份变化,Remote 订阅不启用该选项。
|
||||
|
||||
|
||||
@@ -373,7 +373,7 @@ export class DeepSeekAccount extends TypertRemoteService {
|
||||
* @param token - token captured by the rejected inference request.
|
||||
* @returns after matching credentials are removed and the expiry notification is emitted.
|
||||
*/
|
||||
async rejectToken(token: string): Promise<void> {
|
||||
private async rejectToken(token: string): Promise<void> {
|
||||
const lifetime = this.detailsLifetime
|
||||
const stored = await this.readCurrentGrant(lifetime)
|
||||
if (stored?.token !== token || this.detailsLifetime !== lifetime) return
|
||||
@@ -450,7 +450,7 @@ export class DeepSeekAccount extends TypertRemoteService {
|
||||
* @param url - actual request destination or API base URL.
|
||||
* @returns stored token, or undefined for other origins or a signed-out account.
|
||||
*/
|
||||
async resolveToken(url: string): Promise<string | undefined> {
|
||||
private async resolveToken(url: string): Promise<string | undefined> {
|
||||
if (this.closed || this.removing !== undefined) return undefined
|
||||
const destination = new URL(url)
|
||||
if (destination.origin !== this.inferenceOrigin || destination.username || destination.password) return undefined
|
||||
@@ -470,18 +470,22 @@ export class DeepSeekAccount extends TypertRemoteService {
|
||||
|
||||
/**
|
||||
* Release the account credential for one request to `url` as the request
|
||||
* carries it, together with its invalidation. Host-only.
|
||||
* carries it, together with its invalidation, which runs on the account
|
||||
* service mounted when it is called. Host-only.
|
||||
* @param url - actual request destination or API base URL.
|
||||
* @returns the request credential, or undefined for other origins or a signed-out account.
|
||||
*/
|
||||
async resolveRequestCredential(url: string): Promise<AccountRequestCredential | undefined> {
|
||||
const token = await this.resolveToken(url)
|
||||
if (token === undefined) return undefined
|
||||
// The destination answers after a reload may have replaced this instance, so the rejection runs on the account
|
||||
// service mounted at that time; without one, the grant stays for the next mounted service to reject.
|
||||
const { ctx } = this
|
||||
return {
|
||||
headers: { [ACCOUNT_TOKEN_HEADER]: token },
|
||||
value: token,
|
||||
reject: async () => {
|
||||
try { await this.rejectToken(token) }
|
||||
try { await ctx.get('deepseekAccount')?.rejectToken(token) }
|
||||
catch (_credentialRemovalFailed) { /* The destination's rejection is the failure to report; the next rejection retries. */ }
|
||||
},
|
||||
}
|
||||
|
||||
@@ -122,7 +122,10 @@ export interface AccountRequestCredential {
|
||||
readonly value: string
|
||||
/**
|
||||
* Remove the stored token after the destination rejected it, unless a newer
|
||||
* sign-in replaced it. Storage failures are contained: the caller reports
|
||||
* sign-in replaced it. The removal runs on the account service mounted when
|
||||
* this is called, so a reload between the request and the rejection does
|
||||
* not keep the token; without a mounted service the token stays for the
|
||||
* next one to reject. Storage failures are contained: the caller reports
|
||||
* the destination's rejection, and the next rejection retries the removal.
|
||||
* @returns settlement after the removal attempt.
|
||||
*/
|
||||
|
||||
@@ -157,11 +157,12 @@ async function fixture(
|
||||
const authorization = ctx.plugin(AuthorizationService)
|
||||
await authorization
|
||||
await beforeAccount?.(ctx, origin)
|
||||
const provider = ctx.plugin(DeepSeekAccount, {
|
||||
const accountConfig = {
|
||||
platformOrigin: origin, inferenceOrigin, embeddedPageDist, desktopPlatform,
|
||||
allowLoopbackHttp: true, requestHeaders, accountRequestHeaders,
|
||||
rewriteBrowserOrigin, logoutRetryDelayMs: 1, balanceTimeoutMs,
|
||||
})
|
||||
}
|
||||
let provider = ctx.plugin(DeepSeekAccount, accountConfig)
|
||||
await provider
|
||||
cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose(); await web.dispose() })
|
||||
const account = ctx.deepseekAccount
|
||||
@@ -184,6 +185,13 @@ async function fixture(
|
||||
invalidateSummary: () => { normalWallets = [{ currency: 'CNY', balance: 'not-a-decimal' }] },
|
||||
normalWallets: (value: unknown) => { normalWallets = value },
|
||||
dispose: () => provider.dispose(), exchanged, release,
|
||||
/** Replace the account service as a settings reload does; the stored grant and the other services stay. */
|
||||
remount: async () => {
|
||||
await provider.dispose()
|
||||
provider = ctx.plugin(DeepSeekAccount, accountConfig)
|
||||
await provider
|
||||
return ctx.deepseekAccount
|
||||
},
|
||||
redirect: () => { redirect = true },
|
||||
hold: () => { hold = true },
|
||||
initResponse: (value: Record<string, unknown>) => { initOverride = value },
|
||||
@@ -267,7 +275,7 @@ it('stores a grant before redirecting, restores account presence, and signs out
|
||||
await f.account.getProfile(clientMetadata())
|
||||
expect(await f.account.getPlatformSession()).toEqual({ origin: f.origin, userId: 'test-user', token: 'dsh_mock_test',
|
||||
requestHeaders: {} })
|
||||
expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined()
|
||||
expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined()
|
||||
await f.account.signOut(clientMetadata())
|
||||
expect((await f.account.getState()).status).toBe('signed-out')
|
||||
expect(await f.account.getPlatformSession()).toBeNull()
|
||||
@@ -300,9 +308,9 @@ it('allows real account credentials only on the exact official HTTPS origin', as
|
||||
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({
|
||||
kind: 'grant', payload: { version: 1, issuer: 'https://platform.deepseek.com', token: 'test-account-token' },
|
||||
}))
|
||||
expect(await f.account.resolveToken('https://api.deepseek.com/v1')).toBe('test-account-token')
|
||||
expect((await f.account.resolveRequestCredential('https://api.deepseek.com/v1'))?.value).toBe('test-account-token')
|
||||
for (const url of ['http://api.deepseek.com', 'https://api.deepseek.com.evil.test', 'https://api.deepseek.com:8443', 'https://[email protected]']) {
|
||||
expect(await f.account.resolveToken(url)).toBeUndefined()
|
||||
expect(await f.account.resolveRequestCredential(url)).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -332,7 +340,32 @@ it('contains a storage failure while removing a rejected token', async () => {
|
||||
const credential = await f.account.resolveRequestCredential('http://inference.example.test:8094/v1/tools/search')
|
||||
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ kind: 'api-key', key: 'wrong-kind' }))
|
||||
await expect(credential!.reject()).resolves.toBeUndefined()
|
||||
await expect(f.account.rejectToken('test-account-token')).rejects.toThrow('account: storage')
|
||||
// The contained failure is the store's: it still holds the unreadable record.
|
||||
await expect(f.account.getState()).rejects.toThrow('account: storage')
|
||||
})
|
||||
|
||||
it('invalidates a rejected token through the account service mounted when the rejection runs', async () => {
|
||||
const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE)
|
||||
await storeAccount(f)
|
||||
const credential = await storedCredential(f)
|
||||
// A settings reload replaces the service between the request's dispatch and the destination's answer.
|
||||
const replacement = await f.remount()
|
||||
const published: string[] = []
|
||||
f.ctx.on('deepseek-account/signed-out', () => { published.push('signed-out') })
|
||||
await credential.reject()
|
||||
expect(published).toEqual(['signed-out'])
|
||||
expect((await replacement.getState()).status).toBe('signed-out')
|
||||
expect(await f.ctx.credentials.readRecord(credentialKey('deepseek-account-platform', 'default'))).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps a rejected token for the next mounted account service while none is mounted', async () => {
|
||||
const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE)
|
||||
await storeAccount(f)
|
||||
const credential = await storedCredential(f)
|
||||
await f.dispose()
|
||||
await expect(credential.reject()).resolves.toBeUndefined()
|
||||
expect(await f.ctx.credentials.readRecord(credentialKey('deepseek-account-platform', 'default')))
|
||||
.toMatchObject({ kind: 'grant', payload: { token: 'test-platform-grant' } })
|
||||
})
|
||||
|
||||
it('restricts platform destinations to the configured origin and route', () => {
|
||||
@@ -424,6 +457,16 @@ async function storeAccount(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
}))
|
||||
}
|
||||
|
||||
/** Inference origin a fixture allows a grant `storeAccount` wrote, which official inference refuses as development-issued. */
|
||||
const PRIVATE_INFERENCE = 'http://inference.example.test:8094'
|
||||
|
||||
/** The request credential of the stored grant, released for the private inference origin. */
|
||||
async function storedCredential(f: Awaited<ReturnType<typeof fixture>>) {
|
||||
const credential = await f.account.resolveRequestCredential(`${PRIVATE_INFERENCE}/v1/messages`)
|
||||
if (credential === undefined) throw new Error('missing stored credential')
|
||||
return credential
|
||||
}
|
||||
|
||||
it('queries Platform Web endpoints with the stored grant and projects only masked profile and separate recharge and bonus balances', async () => {
|
||||
const f = await fixture()
|
||||
expect(await readDetails(f.account)).toBeNull()
|
||||
@@ -454,7 +497,7 @@ it('publishes sign-out only after local grant removal and refuses token resoluti
|
||||
const observed: string[] = []
|
||||
f.ctx.on('deepseek-account/signed-out', () => { observed.push('signed-out') })
|
||||
const pending = f.account.signOut(clientMetadata())
|
||||
expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined()
|
||||
expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined()
|
||||
await pending
|
||||
expect(observed).toEqual(['signed-out'])
|
||||
expect((await f.account.getState()).status).toBe('signed-out')
|
||||
@@ -855,10 +898,10 @@ it('sends a development grant only to its configured inference origin', async ()
|
||||
await f.wait('waiting-browser')
|
||||
await fetch(f.callback(), { redirect: 'manual' })
|
||||
await f.wait('succeeded')
|
||||
expect(await f.account.resolveToken('http://inference.example.test:8094/api')).toBe('test-account-token')
|
||||
expect((await f.account.resolveRequestCredential('http://inference.example.test:8094/api'))?.value).toBe('test-account-token')
|
||||
for (const url of ['https://api.deepseek.com', 'http://inference.example.test:8095/api',
|
||||
'https://inference.example.test:8094/api', 'http://[email protected]:8094/api']) {
|
||||
expect(await f.account.resolveToken(url)).toBeUndefined()
|
||||
expect(await f.account.resolveRequestCredential(url)).toBeUndefined()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1117,14 +1160,14 @@ it.each([{ kind: 'api-key' as const, key: 'wrong-kind' }, { kind: 'grant' as con
|
||||
await expect(f.account.getState()).rejects.toThrow('account: storage')
|
||||
await expect(f.account.getProfile(clientMetadata())).rejects.toThrow('account: storage')
|
||||
await expect(f.account.getPlatformSession()).rejects.toThrow('account: storage')
|
||||
await expect(f.account.resolveToken('https://api.deepseek.com')).rejects.toThrow('account: storage')
|
||||
await expect(f.account.resolveRequestCredential('https://api.deepseek.com')).rejects.toThrow('account: storage')
|
||||
await expect(f.account.signOut(clientMetadata())).rejects.toThrow('account: storage')
|
||||
},
|
||||
)
|
||||
|
||||
it('returns no credentials when signed out or disposed', async () => {
|
||||
const f = await fixture()
|
||||
expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined()
|
||||
expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined()
|
||||
expect(await f.account.getPlatformSession()).toBeNull()
|
||||
await f.account.cancelSignIn('missing' as import('@deepseek-ai/dsh-deepseek-account').SignInAttemptId)
|
||||
await f.dispose()
|
||||
@@ -1139,7 +1182,7 @@ it('rejects sign-out and inference grants issued by another environment', async
|
||||
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({
|
||||
kind: 'grant', payload: { version: 1, token: 'real-token', issuer: 'https://other.example' },
|
||||
}))
|
||||
expect(await f.account.resolveToken('https://private.example')).toBeUndefined()
|
||||
expect(await f.account.resolveRequestCredential('https://private.example')).toBeUndefined()
|
||||
await expect(f.account.signOut(clientMetadata())).rejects.toThrow('account: protocol')
|
||||
})
|
||||
|
||||
@@ -1148,7 +1191,7 @@ it('never sends a development issuer grant to official inference', async () => {
|
||||
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({
|
||||
kind: 'grant', payload: { version: 1, token: 'real-token', issuer: f.origin },
|
||||
}))
|
||||
expect(await f.account.resolveToken('https://api.deepseek.com')).toBeUndefined()
|
||||
expect(await f.account.resolveRequestCredential('https://api.deepseek.com')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('merges account cookies when there are no base cookies', async () => {
|
||||
@@ -1632,13 +1675,14 @@ it('ignores a 401 whose response cleanup overlaps a credential replacement', asy
|
||||
})
|
||||
|
||||
it('expires an inference-rejected token without another Platform request', async () => {
|
||||
const f = await fixture()
|
||||
const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE)
|
||||
await storeAccount(f)
|
||||
const credential = await storedCredential(f)
|
||||
const published: string[] = []
|
||||
f.ctx.on('deepseek-account/signed-out', () => { published.push('signed-out') })
|
||||
f.ctx.on('deepseek-account/session-expired', () => { published.push('session-expired') })
|
||||
await f.account.rejectToken('test-platform-grant')
|
||||
await f.account.rejectToken('test-platform-grant')
|
||||
await credential.reject()
|
||||
await credential.reject()
|
||||
const state = await f.account.getState()
|
||||
expect({ status: state.status, published, detailRequests: f.detailRequests })
|
||||
.toMatchInlineSnapshot(`
|
||||
@@ -1654,17 +1698,24 @@ it('expires an inference-rejected token without another Platform request', async
|
||||
})
|
||||
|
||||
it('retains a replacement login when inference rejects the previous token', async () => {
|
||||
const f = await fixture()
|
||||
const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE)
|
||||
await f.ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({
|
||||
kind: 'grant', payload: { version: 1, issuer: f.origin, token: 'previous-platform-grant' },
|
||||
}))
|
||||
const previous = await storedCredential(f)
|
||||
await storeAccount(f)
|
||||
await f.account.rejectToken('previous-platform-grant')
|
||||
await previous.reject()
|
||||
expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' })
|
||||
expect(await f.ctx.credentials.readRecord(credentialKey('deepseek-account-platform', 'default')))
|
||||
.toMatchObject({ kind: 'grant', payload: { token: 'test-platform-grant' } })
|
||||
})
|
||||
|
||||
it('ignores an inference rejection while already signed out', async () => {
|
||||
const f = await fixture()
|
||||
await f.account.rejectToken('previous-platform-grant')
|
||||
const f = await fixture(undefined, {}, false, {}, PRIVATE_INFERENCE)
|
||||
await storeAccount(f)
|
||||
const credential = await storedCredential(f)
|
||||
await f.ctx.credentials.deleteRecord(credentialKey('deepseek-account-platform', 'default'))
|
||||
await credential.reject()
|
||||
expect(await f.account.getState()).toMatchObject({ status: 'signed-out' })
|
||||
expect(await f.account.getState()).not.toHaveProperty('signOutReason')
|
||||
})
|
||||
|
||||
@@ -1017,12 +1017,6 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
parameters: [{ name: 'id', description: 'notification the user interacted with.' }, { name: 'event', description: 'displayed frame, non-dismiss action click, or explicit dismissal.' }, { name: 'client', description: 'identity of the requesting UI for this call.' }],
|
||||
returns: 'true once the server accepts the event; false if signed out or credentials changed during the call.',
|
||||
},
|
||||
{
|
||||
signature: 'async rejectToken(token: string): Promise<void>',
|
||||
description: 'Remove an inference-rejected token only while it still matches the stored login.',
|
||||
parameters: [{ name: 'token', description: 'token captured by the rejected inference request.' }],
|
||||
returns: 'after matching credentials are removed and the expiry notification is emitted.',
|
||||
},
|
||||
{
|
||||
signature: 'async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>',
|
||||
description: 'Read existing login identity without creating a device or returning credentials.',
|
||||
@@ -1035,15 +1029,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
parameters: [],
|
||||
returns: 'a Host-only snapshot, or null while signed out or when the credential changed during the read.',
|
||||
},
|
||||
{
|
||||
signature: 'async resolveToken(url: string): Promise<string | undefined>',
|
||||
description: 'Resolve a credential only for the inference origin allowed by the provider.',
|
||||
parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }],
|
||||
returns: 'stored token, or undefined for other origins or a signed-out account.',
|
||||
},
|
||||
{
|
||||
signature: 'async resolveRequestCredential(url: string): Promise<AccountRequestCredential | undefined>',
|
||||
description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation. Host-only.',
|
||||
description: 'Release the account credential for one request to `url` as the request carries it, together with its invalidation, which runs on the account service mounted when it is called. Host-only.',
|
||||
parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }],
|
||||
returns: 'the request credential, or undefined for other origins or a signed-out account.',
|
||||
},
|
||||
|
||||
@@ -60,7 +60,11 @@ export class DeepSeekAdapter<C extends Connection = Connection> extends LlmAdapt
|
||||
configured: endpoint => publication.configured(connection, endpoint),
|
||||
resolve: async (endpoint, signal) => {
|
||||
signal?.throwIfAborted()
|
||||
return await this.dependencies.resolveAuth(connection, endpoint)
|
||||
const auth = await this.dependencies.resolveAuth(connection, endpoint)
|
||||
if (auth === undefined) return undefined
|
||||
// The adapter's failure classification stays behind the seam.
|
||||
const reject = auth.reject?.bind(auth)
|
||||
return { headers: auth.headers, value: auth.value, ...reject === undefined ? {} : { reject } }
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +142,10 @@ export interface DeepSeekAdapterOptions<Connection extends DeepSeekConnectionOpt
|
||||
* credential for the route's own endpoint; omission reports `MISSING_CREDENTIAL`.
|
||||
*/
|
||||
missingCredential?: (connection: Connection, provider: string) => LlmError
|
||||
/** Publish the route's credential through `routeCredential()`; omission publishes none. */
|
||||
/**
|
||||
* Publish the route's credential through `routeCredential()`, whose `resolve` forwards the headers, value, and
|
||||
* rejection of {@link resolveAuth} without its failure classification; omission publishes none.
|
||||
*/
|
||||
credential?: DeepSeekRouteCredentialOptions<Connection>
|
||||
/** Resolve the harness-home anonymous id shared with telemetry and feedback. */
|
||||
resolveUserId: () => AnonymousUserId
|
||||
|
||||
@@ -52,26 +52,36 @@ it('publishes no credential for a provider that declares none', async () => {
|
||||
})
|
||||
|
||||
it('publishes the declared credential from one configuration generation and resolves it per endpoint', async () => {
|
||||
const reject = vi.fn(() => Promise.resolve())
|
||||
const resolveAuth = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string): Promise<DeepSeekRequestAuth | undefined> =>
|
||||
endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k' } : undefined)
|
||||
endpoint === ALLOWED ? { headers: { 'x-fixture': 'k' }, value: 'k', reject, onRequestError: error => Promise.resolve(error) } : undefined)
|
||||
const configured = vi.fn(async (_connection: ResolvedDeepSeekOptions, endpoint: string) => endpoint === ALLOWED)
|
||||
const ctx = await route({ resolveAuth, credential: { kind: 'api-key', reference: () => 'FIXTURE_KEY', configured } })
|
||||
const credential = ctx.llm.routeCredential('fixture-route')
|
||||
expect(credential).toMatchObject({ kind: 'api-key', baseURL: BASE_URL, reference: 'FIXTURE_KEY' })
|
||||
await expect(credential!.configured(ALLOWED)).resolves.toBe(true)
|
||||
await expect(credential!.configured(OTHER)).resolves.toBe(false)
|
||||
await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' })
|
||||
// The grant carries the seam's fields only; the adapter's failure classification stays behind it.
|
||||
const grant = await credential!.resolve(ALLOWED)
|
||||
expect(Object.keys(grant!)).toEqual(['headers', 'value', 'reject'])
|
||||
expect(grant).toMatchObject({ headers: { 'x-fixture': 'k' }, value: 'k' })
|
||||
await grant!.reject!()
|
||||
expect(reject).toHaveBeenCalledTimes(1)
|
||||
await expect(credential!.resolve(OTHER)).resolves.toBeUndefined()
|
||||
await expect(credential!.resolve(ALLOWED, AbortSignal.abort(new Error('caller left')))).rejects.toThrow('caller left')
|
||||
expect(resolveAuth).toHaveBeenCalledTimes(2)
|
||||
expect(configured.mock.calls.map(([{ baseURL }]) => baseURL)).toEqual([BASE_URL, BASE_URL])
|
||||
})
|
||||
|
||||
it('omits the reference of a credential kind without one', async () => {
|
||||
const ctx = await route({ credential: { kind: 'account', configured: () => Promise.resolve(false) } })
|
||||
it('omits the reference of a credential kind without one and the rejection of a grant without one', async () => {
|
||||
const ctx = await route({
|
||||
resolveAuth: () => Promise.resolve({ headers: { 'x-fixture': 'k' }, value: 'k' }),
|
||||
credential: { kind: 'account', configured: () => Promise.resolve(false) },
|
||||
})
|
||||
const credential = ctx.llm.routeCredential('fixture-route')
|
||||
expect(credential).toMatchObject({ kind: 'account', baseURL: BASE_URL })
|
||||
expect(credential).not.toHaveProperty('reference')
|
||||
await expect(credential!.resolve(ALLOWED)).resolves.toEqual({ headers: { 'x-fixture': 'k' }, value: 'k' })
|
||||
})
|
||||
|
||||
it('fails a request without a credential before any network I/O, with the default diagnostic', async () => {
|
||||
|
||||
@@ -22,7 +22,7 @@ import type {} from '@deepseek-ai/dsh-agent'
|
||||
import { credentialRef, credentialRefConfigured, resolveCredentialRef, type CredentialRef } from '@deepseek-ai/dsh-credentials'
|
||||
import type {} from '@deepseek-ai/dsh-deepseek-account'
|
||||
import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
|
||||
import { assertUsableApiKey, type RouteCredential } from '@deepseek-ai/dsh-llm'
|
||||
import { assertUsableApiKey } from '@deepseek-ai/dsh-llm'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import type {} from '@deepseek-ai/dsh-web'
|
||||
import { DeepSeekFetchApiProvider } from './fetch.ts'
|
||||
@@ -258,13 +258,15 @@ function ruleSources(ctx: Context, capability: Capability, rule: Rule): DeepSeek
|
||||
* @param capability - the capability whose diagnostics a misconfigured source names.
|
||||
* @param provider - the route.
|
||||
* @returns the source; undefined when no mounted route publishes a credential as `provider`; a misconfigured source
|
||||
* when the route's settings do not resolve.
|
||||
* when the route's settings do not resolve or its published base URL does not parse.
|
||||
*/
|
||||
function routeSource(ctx: Context, capability: Capability, provider: RouteName): DeepSeekWebAuthSource | undefined {
|
||||
let credential: RouteCredential | undefined
|
||||
try { credential = ctx.get('llm')?.routeCredential(provider) }
|
||||
catch (error: unknown) { return misconfigured(capability, provider, error) }
|
||||
return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential }
|
||||
try {
|
||||
const credential = ctx.get('llm')?.routeCredential(provider)
|
||||
return credential === undefined ? undefined : { kind: 'route', baseURL: toolsBase(credential.baseURL), credential }
|
||||
} catch (error: unknown) {
|
||||
return misconfigured(capability, provider, error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -687,6 +687,17 @@ describe('route credential failures', () => {
|
||||
await expect(failure).rejects.toThrow('that provider\'s settings do not resolve: route resolver unavailable. Search did not send')
|
||||
expect(sent()).toEqual([])
|
||||
})
|
||||
|
||||
it('reports a route publishing an unparsable base URL as misconfigured, before readiness and without sending', async () => {
|
||||
const { ctx, sent } = await mount({
|
||||
routes: [{ provider: 'deepseek-official', publishedBaseURL: 'not a url' }], environment: { DEEPSEEK_API_KEY: 'chat-key' },
|
||||
})
|
||||
expect(await ready(ctx, 'search', 'deepseek-official')).toBe(false)
|
||||
const failure = operate(ctx, 'search', 'deepseek-official')
|
||||
await expect(failure).rejects.toMatchObject({ code: 'WEB_PROVIDER_MISCONFIGURED' })
|
||||
await expect(failure).rejects.toThrow('that provider\'s settings do not resolve: Invalid URL. Search did not send')
|
||||
expect(sent()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('billing settings', () => {
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface RouteRow {
|
||||
withoutCredential?: boolean
|
||||
/** Value `routeCredential()` throws instead of publishing. */
|
||||
throws?: unknown
|
||||
/** Base URL published in place of the resolved one, as a route publishing an unparsable base would. */
|
||||
publishedBaseURL?: string
|
||||
}
|
||||
|
||||
/** The credential `route` publishes, resolved from its config as the route plugin resolves it on each call. */
|
||||
@@ -32,7 +34,7 @@ function credentialOf(ctx: Context, route: RouteRow): RouteCredential {
|
||||
const resolved = resolveAdapterOptions(plainOptions(OfficialConfig(route.config ?? {})), environment)
|
||||
const ref = resolved.apiKeyEnv
|
||||
return {
|
||||
kind: 'api-key', baseURL: resolved.baseURL, reference: ref,
|
||||
kind: 'api-key', baseURL: route.publishedBaseURL ?? resolved.baseURL, reference: ref,
|
||||
configured: () => credentialRefConfigured(ctx, ref),
|
||||
resolve: async () => {
|
||||
const key = await resolveCredentialRef(ctx, ref)
|
||||
@@ -42,7 +44,7 @@ function credentialOf(ctx: Context, route: RouteRow): RouteCredential {
|
||||
}
|
||||
const resolved = resolveAccountOptions(plainAccountOptions(AccountConfig(route.config ?? {})), environment)
|
||||
return {
|
||||
kind: 'account', baseURL: resolved.protocol.baseURL,
|
||||
kind: 'account', baseURL: route.publishedBaseURL ?? resolved.protocol.baseURL,
|
||||
configured: async endpoint => (await ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint)) !== undefined,
|
||||
resolve: endpoint => ctx.get('deepseekAccount')?.resolveRequestCredential(endpoint) ?? Promise.resolve(undefined),
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user