fix(web): preserve reviewed pairing behavior after rebase

This commit is contained in:
EricMoin committed 2026-11-19 21:27:14 +08:00
1 parent f4f10e05f9
commit aab288650b
62 files changed
+433 -93

No files matched your search

+9 -3
View File
@@ -176,10 +176,16 @@ it('lets a paired mobile browser approve another device and keeps denied or canc
}
const mode = webSnapshotMode()
const applicationUrl = new URL(scaffold.authenticatedUrl)
const tokenPlaceholder = `${applicationUrl.origin}${applicationUrl.pathname}?token=xxx`
expect(await applicant.locator('#token').getAttribute('placeholder')).toBe(tokenPlaceholder)
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/request.expected.md', import.meta.url)),
(await captureStableAria(applicant, 'main', scaffold.workspaceCwd, {
replacements: [[code, '{{pairing-code}}'], [new URL(scaffold.baseUrl).host, '{{authority}}']],
replacements: [
[tokenPlaceholder, '{{application-url}}?token=xxx'],
[code, '{{pairing-code}}'], [new URL(scaffold.baseUrl).host, '{{authority}}'],
],
})).replace(/\d+:\d{2}/gu, '{{remaining}}'), mode,
)
await compareOrRefreshGolden(
@@ -349,7 +355,7 @@ it('keeps one Remote connection panel, its QR invitation, and login link while a
await expect.poll(() => navigation.count()).toBe(1)
await navigation.click()
const section = owner.getByRole('region', { name: '远程连接', exact: true })
const loginLink = section.getByRole('region', { name: '链接登录', exact: true }).locator('code')
const loginLink = section.getByRole('region', { name: '访问地址', exact: true }).locator('code')
await expect.poll(() => loginLink.innerText()).toBe(fixture.authenticatedUrl)
const approvals = section.getByRole('region', { name: '配对申请', exact: true })
await approvals.waitFor()
@@ -510,7 +516,7 @@ it('keeps Token and pairing usable on the same page after a QR exchange fails',
await failure.waitFor()
expect(new URL(applicant.url()).hash).toBe('')
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
const token = applicant.getByLabel('登录令牌或链接', { exact: true })
const token = applicant.locator('#token')
expect(await token.isEnabled()).toBe(true)
expect(await applicant.locator('#token-submit').isEnabled()).toBe(true)
expect(await applicant.getByRole('button', { name: '申请配对', exact: true }).isEnabled()).toBe(true)
@@ -1,21 +1,20 @@
- region "远程连接":
- heading "远程连接" [level=2]
- paragraph: 通过以下方式,在其他设备上登录并使用 DeepSeek Harness。
- region "访问地址":
- heading "访问地址" [level=3]
- code: {{access-address}}?token={{login-token}}
- button "复制链接"
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "重新生成"
- button "取消"
- img "一次性登录二维码"
- paragraph:
- text: 扫码后直接登录
- timer: {{seconds}} 秒后过期
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- paragraph: HTTP 会明文传输登录凭据,请仅在可信网络中使用
- region "链接登录":
- heading "链接登录" [level=3]
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
- code: {{access-address}}?token={{login-token}}
- button "复制链接"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -2,10 +2,12 @@
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 请用以下任意方式验证登录
- text: 登录令牌或链接
- textbox "登录令牌或链接"
- paragraph: 登录令牌位于此 Host 启动时输出的 URL 中
- button "继续"
- form "输入登录令牌或链接":
- heading "输入登录令牌或链接" [level=2]
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- textbox "输入登录令牌或链接":
- /placeholder: {{application-url}}?token=xxx
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
@@ -2,10 +2,12 @@
- region "Connect to this Host":
- heading "Connect to this Host" [level=1]
- paragraph: Use one of the methods below to sign in.
- text: Login token or link
- textbox "Login token or link"
- paragraph: Find the token in the URL printed when this Host started.
- button "Continue"
- form "Enter a login token or link":
- heading "Enter a login token or link" [level=2]
- paragraph: On a signed-in device, copy the link from Settings → Remote connection and paste it here.
- textbox "Enter a login token or link":
- /placeholder: {{application-url}}?token=xxx
- button "Continue"
- region "Pair this device":
- heading "Pair this device" [level=2]
- paragraph: After requesting, open Settings → Remote connection on another signed-in device. Match the pairing code and approve to sign in here automatically.
@@ -2,10 +2,12 @@
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 请用以下任意方式验证登录
- text: 登录令牌或链接
- textbox "登录令牌或链接"
- paragraph: 登录令牌位于此 Host 启动时输出的 URL 中
- button "继续"
- form "输入登录令牌或链接":
- heading "输入登录令牌或链接" [level=2]
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- textbox "输入登录令牌或链接":
- /placeholder: {{application-url}}?token=xxx
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
@@ -2,10 +2,12 @@
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 请用以下任意方式验证登录
- text: 登录令牌或链接
- textbox "登录令牌或链接"
- paragraph: 登录令牌位于此 Host 启动时输出的 URL 中
- button "继续"
- form "输入登录令牌或链接":
- heading "输入登录令牌或链接" [level=2]
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- textbox "输入登录令牌或链接":
- /placeholder: {{application-url}}?token=xxx
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
@@ -8,3 +8,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -8,3 +8,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -8,3 +8,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -8,3 +8,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -8,3 +8,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -16,3 +16,6 @@
- timer: {{seconds}} 秒后过期
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -8,3 +8,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -10,3 +10,6 @@
- button "重新生成"
- status:
- paragraph: 二维码已过期,请生成新二维码登录
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -10,3 +10,6 @@
- button "重新生成"
- status:
- paragraph: 二维码已过期,请生成新二维码登录
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -15,6 +15,9 @@
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- paragraph: HTTP 会明文传输登录凭据,请仅在可信网络中使用
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- region "连接选项":
- heading "连接选项" [level=3]
- button "刷新连接状态"
@@ -15,3 +15,6 @@
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- paragraph: HTTP 会明文传输登录凭据,请仅在可信网络中使用
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -18,3 +18,6 @@
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- paragraph: HTTP 会明文传输登录凭据,请仅在可信网络中使用
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -8,3 +8,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -10,3 +10,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -10,3 +10,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -10,3 +10,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -8,3 +8,6 @@
- region "二维码登录":
- heading "二维码登录" [level=3]
- button "生成二维码"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -14,3 +14,6 @@
- timer: {{seconds}} 秒后过期
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -14,3 +14,6 @@
- timer: {{seconds}} 秒后过期
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -14,3 +14,6 @@
- timer: {{seconds}} 秒后过期
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -14,3 +14,6 @@
- timer: {{seconds}} 秒后过期
- paragraph: 请勿分享登录二维码
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -6,3 +6,6 @@
- heading "访问地址" [level=3]
- code: {{access-address}}
- button "复制链接"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -4,3 +4,6 @@
- heading "访问地址" [level=3]
- alert: 无法加载远程连接设置,请重试
- button "重试"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -6,3 +6,6 @@
- heading "访问地址" [level=3]
- code: {{access-address}}
- button "复制链接"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -6,3 +6,6 @@
- heading "访问地址" [level=3]
- code: {{access-address}}
- button "复制链接"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -6,3 +6,6 @@
- heading "访问地址" [level=3]
- code: {{access-address}}
- button "复制链接"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
@@ -9,3 +9,6 @@
- heading "二维码登录" [level=3]
- button "重新生成"
- status: 二维码已使用,请在手机上确认是否已登录
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
+4 -1
View File
@@ -80,10 +80,13 @@ it('recognizes a delivered browser session when the pairing result crosses the l
await applicant.clock.fastForward(ticket.expiresInMs)
await expect.poll(() => applicant.evaluate(() => document.documentElement.dataset.sessionCheckStatus)).toBe('200')
await applicant.locator('#auth-pair-panel[data-state="checking"]').waitFor()
const applicationUrl = new URL(scaffold.authenticatedUrl)
const tokenPlaceholder = `${applicationUrl.origin}${applicationUrl.pathname}?token=xxx`
expect(await applicant.locator('#token').getAttribute('placeholder')).toBe(tokenPlaceholder)
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/completion-checking.expected.md', import.meta.url)),
await captureStableAria(applicant, 'main', scaffold.workspaceCwd, {
replacements: [[code, '{{pairing-code}}']],
replacements: [[tokenPlaceholder, '{{application-url}}?token=xxx'], [code, '{{pairing-code}}']],
}), webSnapshotMode(),
)
await applicant.evaluate(() => { globalThis.dispatchEvent(new Event('release-pairing-completion')) })
+6 -1
View File
@@ -71,9 +71,14 @@ it.each(['zh', 'en'])('recovers and replaces a request from the same browser and
await applicant.locator('#auth-pair-panel[data-state="error"]').waitFor()
expect(await applicant.locator('#auth-pair-retry').count()).toBe(0)
expect(await applicant.locator('#auth-pair-request').isEnabled()).toBe(true)
const applicationUrl = new URL(scaffold.authenticatedUrl)
const tokenPlaceholder = `${applicationUrl.origin}${applicationUrl.pathname}?token=xxx`
expect(await applicant.locator('#token').getAttribute('placeholder')).toBe(tokenPlaceholder)
await compareOrRefreshGolden(
fileURLToPath(new URL(`./expected/device-pairing/recovery-error.${language}.expected.md`, import.meta.url)),
await captureStableAria(applicant, 'main', scaffold.workspaceCwd, { replacements: [[replacement, '{{pairing-code}}']] }),
await captureStableAria(applicant, 'main', scaffold.workspaceCwd, {
replacements: [[tokenPlaceholder, '{{application-url}}?token=xxx'], [replacement, '{{pairing-code}}']],
}),
webSnapshotMode(),
)
const screenshots = process.env.DSH_PAIRING_SCREENSHOT_DIR
+8 -2
View File
@@ -137,6 +137,7 @@ async function waitForPairingList(pairing: Locator): Promise<void> {
}
async function snapshot(page: Page, fixture: RemoteConnectionFixture, name: string, addressUrl = fixture.authenticatedUrl): Promise<void> {
await waitForPairingList(page.getByRole('region', { name: '配对申请', exact: true }))
await expect.poll(() => page.getByRole('region', { name: '访问地址', exact: true }).locator('code').textContent()).toBe(addressUrl)
const section = page.getByRole('region', { name: '远程连接', exact: true })
await assertAddressLayout(section, true)
@@ -454,9 +455,12 @@ describe('web e2e: one-use QR browser login', () => {
await expect.poll(() => address.locator('code').textContent()).toBe(plainUrl)
const notice = section.getByRole('status').filter({ hasText: warning })
await notice.getByText(warning, { exact: true }).waitFor()
expect(await section.getByRole('region').count()).toBe(1)
expect(await section.getByRole('heading', { level: 3 }).allTextContents()).toEqual(['访问地址'])
const pairing = section.getByRole('region', { name: '配对申请', exact: true })
await waitForPairingList(pairing)
expect(await section.getByRole('region').count()).toBe(2)
expect(await section.getByRole('heading', { level: 3 }).allTextContents()).toEqual(['访问地址', '配对申请'])
expect(await address.getByText(warning, { exact: true }).count()).toBe(0)
expect(await pairing.getByText(warning, { exact: true }).count()).toBe(0)
expect(await section.getByRole('region', { name: '二维码登录', exact: true }).count()).toBe(0)
expect(await section.getByRole('img').count()).toBe(0)
const copy = address.getByRole('button', { name: '复制链接', exact: true })
@@ -502,6 +506,7 @@ describe('web e2e: one-use QR browser login', () => {
expect(await retry.isEnabled()).toBe(true)
expect((await retry.boundingBox())!.height).toBe(28)
expect(await section.getByRole('region', { name: '二维码登录', exact: true }).count()).toBe(0)
await waitForPairingList(pairing)
await compareOrRefreshGolden(join(EXPECTED, 'unreachable-load-failed.expected.md'),
await captureStableAria(page, 'section[aria-label="远程连接"]', scaffold.workspaceCwd), MODE)
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'unreachable-load-failed.png') })
@@ -1351,6 +1356,7 @@ describe('web e2e: one-use QR browser login', () => {
await custom.waitFor()
expect(await nav.count()).toBe(1)
expect(await section.count()).toBe(0)
expect(await page.getByRole('region', { name: '配对申请', exact: true }).count()).toBe(0)
expect(await details.isChecked()).toBe(true)
expect(await extension.getByRole('status', { name: '附加选项中的邀请编号' }).textContent()).toBe(invitationId)
expect(await custom.getByRole('status', { name: '邀请编号' }).textContent()).toBe(invitationId)
+2 -2
View File
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
en: d4a2d669e11fc254
zh: adc1bb986ef5d03e
en: 653e1df0987ecd94
zh: b03cc980803a4160
+1 -1
View File
@@ -706,7 +706,7 @@ flowchart LR
| ctx key | Role | Owner | Implementations | Direct consumers | Companion plugins | Note |
| --- | --- | --- | --- | --- | --- | --- |
| `ctx.remoteConnection` | `service` | [`client-remote-connection`](../packages/client/remote-connection) | - | - | - | Owns one-use QR invitations, Remote browser credentials and the anonymous login document; its Client provides QR login and an independent Token-link shortcut. |
| `ctx.remoteConnection` | `service` | [`client-remote-connection`](../packages/client/remote-connection) | - | - | - | Owns QR invitations, approved pairing requests, Remote browser credentials and the anonymous login document; its Client provides approval controls and an independent Token-link shortcut. |
| `ctx.actionCards` | `service` | [`action-cards`](../packages/experimental/action-cards) | - | [`creation-recommendations`](../packages/experimental/creation-recommendations), [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | - | Owns card state, user actions and status notices; card kinds register their actions and handlers. |
| `ctx.pluginRecommendations` | `service` | [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | - | [`client-ui-plugin-recommendations`](../packages/experimental/client-ui-plugin-recommendations) | - | Reads the current catalog text of an official plugin card and enables the plugin through the profile plugin manager after a click. |
| `ctx.deepseekChatImport` | `service` | [`deepseek-chat-import`](../packages/experimental/deepseek-chat-import) | - | - | - | Serves the owner-only upload route that imports each conversation of a DeepSeek chat export as a Session, and the upload limits the browser checks first. |
+1 -1
View File
@@ -708,7 +708,7 @@ flowchart LR
| ctx 键 | 角色 | 所属包 | 实现 | 直接消费方 | 配套插件 | 说明 |
| --- | --- | --- | --- | --- | --- | --- |
| `ctx.remoteConnection` | `service` | [`client-remote-connection`](../packages/client/remote-connection) | - | - | - | 拥有一次性二维码邀请、Remote 浏览器凭据和匿名登录文档;Client 提供二维码登录及独立的 Token 链接复制入口。 |
| `ctx.remoteConnection` | `service` | [`client-remote-connection`](../packages/client/remote-connection) | - | - | - | 管理二维码邀请、获批的配对申请、Remote 浏览器凭据和匿名登录文档;Client 提供审批控件及独立的 Token 链接入口。 |
| `ctx.actionCards` | `service` | [`action-cards`](../packages/experimental/action-cards) | - | [`creation-recommendations`](../packages/experimental/creation-recommendations), [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | - | 负责卡片状态、用户操作和状态通知;各卡片种类注册自己的动作和处理器。 |
| `ctx.pluginRecommendations` | `service` | [`plugin-recommendations`](../packages/experimental/plugin-recommendations) | - | [`client-ui-plugin-recommendations`](../packages/experimental/client-ui-plugin-recommendations) | - | 读取官方插件卡片的当前目录文本,并在用户点击后通过配置插件管理器启用该插件。 |
| `ctx.deepseekChatImport` | `service` | [`deepseek-chat-import`](../packages/experimental/deepseek-chat-import) | - | - | - | 提供仅 owner 可用的上传路由,把 DeepSeek 会话导出的每个对话导入为一个会话,并提供浏览器先行检查的上传上限。 |
+1 -1
View File
@@ -589,7 +589,7 @@ export interface Config {
## `@deepseek-ai/dsh-client-remote-connection`
- `inject`: `connection` · `connection.authentication` · `credentials` · `webServer` · `webApp`
- `source`: [`packages/client/remote-connection/src/index.ts:28`](../packages/client/remote-connection/src/index.ts)
- `source`: [`packages/client/remote-connection/src/index.ts:33`](../packages/client/remote-connection/src/index.ts)
```ts config-catalog
/** Deployment timing and limits for remote browser login. */
+1 -1
View File
@@ -591,7 +591,7 @@ export interface Config {
## `@deepseek-ai/dsh-client-remote-connection`
- `inject`: `connection` · `connection.authentication` · `credentials` · `webServer` · `webApp`
- `source`: [`packages/client/remote-connection/src/index.ts:28`](../packages/client/remote-connection/src/index.ts)
- `source`: [`packages/client/remote-connection/src/index.ts:33`](../packages/client/remote-connection/src/index.ts)
```ts config-catalog
/** Deployment timing and limits for remote browser login. */
+2 -1
View File
@@ -550,6 +550,7 @@ flowchart TD
pkg_hmr --> pkg_cmdline
pkg_client_remote_connection --> pkg_credentials
pkg_client_remote_connection --> pkg_error
pkg_client_remote_connection --> pkg_host_webserver
pkg_authorization --> pkg_credentials
pkg_authorization --> pkg_error
pkg_credentials_local --> pkg_atomic_write
@@ -1817,7 +1818,7 @@ flowchart TD
| [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) |
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) |
| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) |
| [`client-remote-connection`](../packages/client/remote-connection) | `client` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error) |
| [`client-remote-connection`](../packages/client/remote-connection) | `client` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error), [`host-webserver`](../packages/host/webserver) |
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) |
+2 -1
View File
@@ -552,6 +552,7 @@ flowchart TD
pkg_hmr --> pkg_cmdline
pkg_client_remote_connection --> pkg_credentials
pkg_client_remote_connection --> pkg_error
pkg_client_remote_connection --> pkg_host_webserver
pkg_authorization --> pkg_credentials
pkg_authorization --> pkg_error
pkg_credentials_local --> pkg_atomic_write
@@ -1819,7 +1820,7 @@ flowchart TD
| [`api-terminal-controller`](../packages/api/terminal-controller) | `api` | [`subprocess`](../packages/subprocess/subprocess) |
| [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) |
| [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) |
| [`client-remote-connection`](../packages/client/remote-connection) | `client` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error) |
| [`client-remote-connection`](../packages/client/remote-connection) | `client` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error), [`host-webserver`](../packages/host/webserver) |
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`error`](../packages/util/error) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`typert-protocol`](../packages/typert/protocol) |
+2 -2
View File
@@ -18,8 +18,8 @@
en: 1f69a4c52a27e7e5
zh: e4431a252fb86f7c
/deepseek-ai-dsh-web-app/use-this-package/starting-the-web-gui:
en: 2c12e37538c57fe8
zh: 373b4e5ceae76d06
en: 532eb3f4c02ae3f0
zh: 1ce281f677ec29c7
/deepseek-ai-dsh-web-app/use-this-package/configuration:
en: 8a860bd7fe5743e4
zh: 7d5bbcf734160e86
+2
View File
@@ -42,6 +42,8 @@ dsh --profile web --no-open --port 8080
After startup you see a `dsh web:` line whose root URL carries a fresh process token. Unless `--no-open` or an SSH session suppresses it, the default browser opens that URL, receives a signed cookie, and redirects to the same directory without the token. You know it worked when the page loads and you can chat with the agent. Two failures to expect: if the frontend is not built, startup stops with a build hint (`pnpm run build` in a checkout); if the browser cannot be opened, a credential-free diagnostic prints to stderr while the server keeps running — open the printed startup URL yourself.
The sign-in page presents token entry and pairing in separate cards. Paste either a login link or its token; copy the link from Settings → Remote connection on a signed-in device. Continue becomes available only for a well-formed login link or token; activating it while unavailable shows a validation prompt. Editing dismisses the prompt until another submission attempt. Rejected tokens appear in a full-width error banner, matching the pairing failure banners. Pairing instructions are visible before requesting access. Another browser can request access from that page. Approve the matching code in **Settings → Remote connection** on a signed-in browser; the applicant then enters the application automatically. [Browser pairing](../../client/remote-connection/README.md) owns the approval rules and request limits.
**Settings → Models** displays **DeepSeek API**, using `DEEPSEEK_API_KEY`. The default is `deepseek-official` / `deepseek-flash` (DeepSeek-V4.1-Flash). The [DeepSeek plugin](../../llm/llm-deepseek/README.md#endpoint-and-wire-format) uses the Messages API.
Saved model selections override the composition default. The settings card accepts a Messages-compatible API address and a credential reference.
+2
View File
@@ -42,6 +42,8 @@ dsh --profile web --no-open --port 8080
启动后你会看到 `dsh web:` 行,其根 URL 携带新的进程 token。除非 `--no-open` 或 SSH 会话抑制,否则默认浏览器会打开该 URL、取得签名 cookie,再重定向到不含认证参数的同一目录。页面加载且你可以与 agent 对话,就说明成功了。两种可预期的失败:前端未构建时,启动会以构建提示停止(checkout 中运行 `pnpm run build`);浏览器无法打开时,stderr 会打印不含凭据的诊断,但服务器会继续运行——请自行打开已打印的启动 URL。
登录页将令牌输入与配对申请分成独立卡片。可粘贴登录链接或其中的令牌;登录链接可在已登录设备的设置 → 远程连接中复制。只有登录链接或令牌格式正确时“继续”才可用;不可用时激活按钮会显示校验提示。编辑输入内容会关闭提示,只有再次尝试提交时才重新显示。令牌被拒绝时显示占满内容宽度的错误横幅,与配对失败横幅一致。申请访问前即可看到配对操作说明。其他浏览器可以从此页申请访问。在已登录浏览器的**设置 → 远程连接**中核对显示码并批准后,申请浏览器会自动进入应用。[浏览器配对](../../client/remote-connection/README.zh.md)说明审批规则与申请限制。
**设置 → 模型**显示 **DeepSeek API**,使用 `DEEPSEEK_API_KEY`。默认模型为 `deepseek-official` / `deepseek-flash`(DeepSeek-V4.1-Flash)。[DeepSeek 插件](../../llm/llm-deepseek/README.zh.md#endpoint-and-wire-format)使用 Messages API。
已保存的模型选择覆盖组合默认值。设置卡接受兼容 Messages 的 API 地址与凭据引用。
@@ -12,20 +12,23 @@
en: 6f43444b88f0b1ac
zh: 46cf92c078350c5e
/deepseek-ai-dsh-client-remote-connection/table-of-contents:
en: ee070d32177b96d9
zh: f946b0eba6746ffd
en: cb4114e511d9a1bb
zh: e114ec11dac86de9
/deepseek-ai-dsh-client-remote-connection/use-this-package:
en: 8fdc12de7b7793a7
zh: f6f229e2555a8c8a
en: 291713708033cfaa
zh: 2177ab1c731e7e41
/deepseek-ai-dsh-client-remote-connection/authentication-and-failures:
en: e504f8415dea0fc3
zh: 0a11e6f2217cce29
en: 800ae2e8b5a319d1
zh: c53eac07dab5b9d0
/deepseek-ai-dsh-client-remote-connection/pairing-requests:
en: 46a6fd8dc2514ef2
zh: 0e35b1e5f23f2a73
/deepseek-ai-dsh-client-remote-connection/add-settings-options:
en: 012e1280c7169e42
zh: e74934c8611df09b
en: 09cb4d0c453e394c
zh: f6a438da3e471ffa
/deepseek-ai-dsh-client-remote-connection/replace-the-settings-panel:
en: f96e2dbaafbe11c8
zh: f83fda3f5a7e97ba
en: bd587e062413f32d
zh: 8f6249e76d682904
/deepseek-ai-dsh-client-remote-connection/further-exploration:
en: dc8b05a29d545c8e
zh: 81e6fb89db3c962e
+42 -5
View File
@@ -15,6 +15,7 @@ Settings shows shared sign-in guidance, then access-address and QR login cards.
- [Use this package](#use-this-package)
- [Authentication and failures](#authentication-and-failures)
- [Pairing requests](#pairing-requests)
- [Add settings options](#add-settings-options)
- [Replace the settings panel](#replace-the-settings-panel)
- [Further Exploration](#further-exploration)
@@ -27,7 +28,7 @@ The Web bundle mounts this plugin. Its Host half requires `connection`, `connect
QR login uses the advertised application URL, which supports HTTP and HTTPS, must name a non-loopback address reachable by the phone, and must pass Connection's trusted-host checks. Configure the listener, optional certificate or reverse proxy, `publicUrl`, and trusted hosts through the existing [Web application](../../bundle/web-app/README.md) configuration. This plugin never changes the listening interface or discovers a network address. A reverse proxy must preserve the external Host, remove its configured path prefix, and protect its upstream connection. A plain HTTP listener issuing a cookie for an HTTP public URL omits `Secure`; HTTPS listeners and HTTPS public URLs behind a TLS-terminating proxy retain `Secure`. An HTTPS proxy must enforce HTTPS for its public origin. The settings panel allows HTTP login and reminds the user that HTTP transmits login credentials without encryption.
The panel shows unmet address prerequisites in a shared notice above the cards. An unreachable or untrusted address keeps a copyable clean URL in the address card and hides QR login without showing a credential warning. Deployment-read failures remain retryable in the address card while QR login is unavailable. Reconnecting checks the address prerequisites again.
The panel shows unmet address prerequisites in a shared notice above the cards. An unreachable or untrusted address keeps a copyable clean URL in the address card and hides QR login without showing a credential warning. Pairing approvals remain available. Deployment-read failures remain retryable in the address card while QR login is unavailable. Reconnecting checks the address prerequisites again.
`cookieMaxAgeDays` defaults to 30 and fixes each Remote cookie's absolute lifetime. `ticketLifetimeMs` defaults to 120000. `pollIntervalMs` defaults to 1000 and controls the settings panel's status checks while its code is displayed. Only one invitation is outstanding per plugin instance: generating another replaces the previous one, and cancelling an old invitation does not cancel its replacement.
@@ -41,11 +42,47 @@ The owner-only `loginUrl()` method reads the same WebServer instance’s Token e
Remote owns the persistent `client-remote-connection/browser-session` credential record. Its signing key and v1 cookie format are independent of Token; a cookie binds the listener protocol and normalized Host, carries fixed issue and expiry times, and uses `HttpOnly`, `SameSite=Strict`, and `Path=/`. Validation never renews it. Corrupt records fail activation rather than replacing the key. Preserve the record across restarts to retain valid logins; replacing or deleting it invalidates old cookies on the next activation.
Remote uses one root login document for ordinary sign-in and QR exchange. A trusted but unauthenticated visit to the ordinary root receives HTTP 401; HEAD retains 401 without a body. The `login=qr` mode returns the same ordinary login document with HTTP 200 even when the browser already has a login cookie; it attempts QR exchange without replacing the page’s sign-in controls. The document exposes no Token value or private application injections; the ordinary login mode shows the Token form only when Token publishes an entry. The Token field accepts either a token or a full login link, and its placeholder uses the current page’s protocol, address, port, and application path with `xxx` as the example token and the theme’s caption color. Existing query parameters and fragments are omitted. Initial HTML uses a generic address template until the page initializes. Its hint directs users to copy a link from Settings → Remote connection on a signed-in device and paste it into this page. The page uses the application’s default font stack and grayscale text rendering. The Token field uses the theme’s blue focus border, with validation errors taking priority. Authenticated visits without QR mode render the application with their actual Peer and no second credential check. Source rejection remains 403; authentication failure without another successful provider remains 503.
Remote uses one root login document for ordinary sign-in and QR exchange. A trusted but unauthenticated visit to the ordinary root receives HTTP 401; HEAD retains 401 without a body. The `login=qr` mode returns the same ordinary login document with HTTP 200 even when the browser already has a login cookie; it attempts QR exchange while retaining the page’s sign-in controls. The document exposes no Token value or private application injections; the Token form appears whenever Token publishes an entry. The Token field accepts either a token or a full login link, and its placeholder uses the current page’s protocol, address, port, and application path with `xxx` as the example token and the theme’s caption color. Existing query parameters and fragments are omitted. Initial HTML uses a generic address template until the page initializes. Its hint directs users to copy a link from Settings → Remote connection on a signed-in device and paste it into this page. The page uses the application’s default font stack and grayscale text rendering. The Token field uses the theme’s blue focus border, with validation errors taking priority. Authenticated visits without QR mode render the application with their actual Peer and no second credential check. Source rejection remains 403; authentication failure without another successful provider remains 503.
## Pairing requests
The anonymous root page places Token entry and device pairing in separate cards below a shared heading. Its introduction asks users to choose one of the available sign-in methods. Both cards place a heading and description before their controls and use matching typography and spacing. Token errors appear below the field while the sign-in guidance stays visible. QR exchange feedback appears above both cards; a failed exchange leaves both sign-in methods available. Its deferred public `pairing/client.js` script defines `dsh-device-pairing`; the element owns the request controls, styles, and translations without loading authenticated Client modules. The Host generates this script from self-contained browser functions and public data shipped in its ordinary entry; plugin reload replaces the script with the current implementation. Removing the element aborts its work and discards its private ticket; browser back/forward-cache suspension preserves the ticket and resumes status checks.
The anonymous pairing card places the code, Request again, Cancel request, and waiting status in order, with the countdown beside the status. Request and status-check failures appear in full-width error banners; denial and expiry use warning banners. These banners have no icons; their border, spacing, and radius match the banners in Remote connection settings. The countdown stays outside these banners. Network and server failures show automatic reconnection status. HTTP 429 responses show an automatic retry notice; exhausted rate-limit retries ask the user to wait before requesting again. Exhausted recovery shows an error banner with Request again and no separate status-query action. The request action retains its primary foreground color while disabled. Confirmed cancellation restores Request to pair without a cancellation notice.
Settings shows pairing requests in a separate card after the access address and QR login cards, even when the advertised QR address is unavailable. The full-access warning banner appears only while the card displays requests. If a list read fails, the card hides the requests and warning and shows an error with **Retry**. A successful retry displays the latest list. A browser signed in through pairing has owner access and can approve requests from other devices. Pairing, QR, and link login keep independent state: creating or cancelling a pairing request does not replace a QR invitation or the reusable login link.
The public POST routes `pairing/request`, `pairing/status`, and `pairing/cancel` declare anonymous authentication; WebServer applies the Host, Origin, and Fetch Metadata checks before invoking their handlers. URLs resolve relative to the application directory for reverse-proxy mounts. The browser generates an ID and random secret before sending the first creation request. All three routes accept exactly these two JSON fields. Repeated creation with the same ID, secret, and origin returns the retained ticket without extending its expiry or changing its decision, including after cancellation. The Host generates a separate display code and retains the original connection IP. Only the applicant holds the secret; the display code cannot query, cancel, or collect the request. Settings uses `remoteConnection/pairingRequests` and `remoteConnection/decidePairing`; both require an active owner invocation, including when an API peer has method grants.
Approval rows display `sourceIp`, captured from the creating connection and normalized for IPv4/IPv6; missing addresses display Unknown. Forwarded headers are ignored. Behind a proxy this is the proxy's IP. `authority` remains the application's origin binding, never the displayed source; an IP does not identify a device or authorize access.
The first approval or denial wins. Cancellation can withdraw an uncollected approval. Approval lets the applicant collect a Remote cookie through the same private issuer used for QR redemption, independently of Token authentication. Retrying a lost response before request expiry returns the same cookie without extending its lifetime. Denial, cancellation, expiry, and plugin shutdown cannot create a login.
When an owner decision returns `approved`, `denied`, or `unavailable`, the card removes the request from the visible list before displaying the outcome notice. Earlier in-flight reads cannot restore the row, and the card immediately requests fresh data, including after a list read failure. An unknown decision outcome leaves the request in the list until a later read confirms its state. Changes from other devices and request expiry appear through the regular polling interval.
The applicant can cancel while creating a request or waiting for approval. If the creation response is unknown, the browser first repeats creation with its retained credentials to recover the same ticket, then confirms cancellation. An unknown cancellation retains those credentials; it cannot start another request.
The waiting page shows the remaining time. Creation, status reads, cancellation, and authorization checks have a complete-response timeout. Network failures, unreadable responses, HTTP 429, and server failures retry automatically with exponential delays starting at `pollIntervalMs`, capped by `retryMaxDelayMs`, for at most `maxRetries` additional attempts. A successful status read resets this budget. Other HTTP refusals stop immediately. Exhaustion stops automatic work and shows an error banner. **Request again** confirms that the previous request ended before creating new credentials and a new pairing code; an unconfirmed cancellation never creates a replacement. In-flight work is aborted and its late result cannot overwrite a replacement. After denial, cancellation, or confirmed expiry, the same action creates a fresh request.
At local or Host-reported expiry, the page aborts pending pairing work and checks browser authentication with a no-store `HEAD` request to the clean application URL. `200` opens the application; after `401`, the browser also confirms cancellation of the old request, whose Host expiry can be later than the local deadline. Only then can it finish expiry or create a replacement. Failed checks use the same bounded recovery. Exhaustion retains the credentials and reports an unknown sign-in outcome; **Request again** repeats this check before it can create another request. Only a confirmed signed-out browser can start again; cancelling a fetch does not undo a cookie already received.
Configure request limits under this plugin's `pairing` field:
| Field | Default | Meaning |
|---|---:|---|
| `pairing.requestTtlMs` | 300000 | Request lifetime, including approved delivery retries; must exceed the polling interval |
| `pairing.maxRequests` | 32 | Maximum retained pending and terminal requests |
| `pairing.requestIntervalMs` | 1000 | Minimum interval between creations across applicants |
| `pairing.pollIntervalMs` | 2000 | Minimum applicant polling interval, initial retry delay, and cadence for periodic Settings refreshes |
| `pairing.requestTimeoutMs` | 10000 | Timeout per HTTP attempt, including response-body reading |
| `pairing.maxRetries` | 3 | Additional attempts after transient failures |
| `pairing.retryMaxDelayMs` | 10000 | Maximum exponential retry delay; must be at least the polling interval |
Requests are process-local and remain in the bounded pool until expiry, including after a decision. Restarting or unloading the plugin clears them without revoking issued cookies. A full pool or creation rate limit asks the applicant to retry later; a failed poll retains the private ticket for recovery.
## Add settings options
Register in the root-scoped list `settings.remoteConnection.extensions` to add options after the main panel. Each plugin uses a unique `id`; entries render in ascending `order`, then registration order. Extensions appear alongside either the default panel or a replacement. `RemoteConnectionExtensionProps` provides the same shared state hooks, actions, and `close()` as [panel replacements](#replace-the-settings-panel). Each extension owns its rendering and localized copy.
Register in the root-scoped list `settings.remoteConnection.extensions` to add options after the main panel, including its default access-address, QR login, and pairing cards. Each plugin uses a unique `id`; entries render in ascending `order`, then registration order. Extensions appear alongside either the default panel or a replacement. `RemoteConnectionExtensionProps` provides the same shared state hooks, actions, and `close()` as [panel replacements](#replace-the-settings-panel). Each extension owns its rendering and localized copy.
```ts client
import type { Context } from '@deepseek-ai/cordis'
@@ -68,7 +105,7 @@ export function apply(ctx: Context): void {
## Replace the settings panel
The root-scoped, single `settings.remoteConnection.content` slot replaces the main panel while retaining its one settings navigation entry and additive extensions. Every occupant receives `RemoteConnectionContentProps` from this package's `/client` type exports: `useRemoteConnection(selector)`, `create()`, `cancel()`, `reload()`, `useLoginLink(selector)`, `copyLink()`, `reloadLink()`, `dismissCopyNotice(sequence)`, and the settings shell's `close()`. The plugin owns invitation and link state across replacements, so switching views preserves the current invitation, countdown, and copy feedback. Actions report their outcomes through the state hooks. A replacement owns its rendering and localized copy; it may register its own `locale` namespace.
The root-scoped, single `settings.remoteConnection.content` slot replaces the main panel, including the default access-address, QR login, and pairing cards, while retaining its one settings navigation entry and additive extensions. Every occupant receives `RemoteConnectionContentProps` from this package's `/client` type exports: `useRemoteConnection(selector)`, `create()`, `cancel()`, `reload()`, `useLoginLink(selector)`, `copyLink()`, `reloadLink()`, `dismissCopyNotice(sequence)`, and the settings shell's `close()`. Both slot prop types include `useApproval(selector)`, `decide(id, decision)`, and `dismiss()`; render approval controls only while `available` is true. The plugin owns invitation, link, and pairing approval state across replacements, so switching views preserves the current invitation, countdown, and copy feedback. Actions report their outcomes through the state hooks. A replacement owns its rendering and localized copy; it may register its own `locale` namespace.
Register a replacement component from your Client plugin with a lower priority than the default panel's `0`:
@@ -90,7 +127,7 @@ export function apply(ctx: Context): void {
}
```
`slots.inject` supports loading either contribution before the Remote connection plugin and re-registers it when the slot owner returns. Unloading an extension removes only that contribution, preserving the main panel, other extensions, and shared state. Unloading a replacement restores the default panel and its current state; unloading the Remote connection plugin removes both slots, stops polling, discards the link credential and copy notice immediately, and waits for outstanding reads, clipboard writes, and queued refreshes to settle. Only display `ticket.url` as a QR while `phase === 'pending'`: an uncertain operation may retain the ticket for recovery without permitting its display. Never persist or log either credential URL. Replacing this panel does not replace the anonymous login page or the Host invitation protocol.
`slots.inject` supports loading either contribution before the Remote connection plugin and re-registers it when the slot owner returns. Unloading an extension removes only that contribution, preserving the main panel, other extensions, and shared state. Unloading a replacement restores the default panel and its current state; unloading the Remote connection plugin removes both slots, stops polling, discards the link credential and copy notice immediately, and waits for outstanding reads, clipboard writes, and queued refreshes to settle. Only display `ticket.url` as a QR while `phase === 'pending'`: an uncertain operation may retain the ticket for recovery without permitting its display. Never persist or log either credential URL. Replacing this panel does not replace the anonymous login page or any Host login method.
## Further Exploration
+43 -5
View File
@@ -15,6 +15,7 @@ kind: "package-reference"
- [使用本包](#use-this-package)
- [认证与失败处理](#authentication-and-failures)
- [配对申请](#pairing-requests)
- [添加设置选项](#add-settings-options)
- [替换设置面板](#replace-the-settings-panel)
- [进一步探索](#further-exploration)
@@ -28,7 +29,7 @@ Web bundle 挂载此插件。Host 端依赖 `connection`、`connection.authentic
二维码登录使用公布的应用 URL,该地址支持 HTTP 和 HTTPS,必须指向手机可访问的非回环地址,并通过 Connection 的可信 Host 检查。通过现有 [Web 应用](../../bundle/web-app/README.zh.md) 配置设置监听器、可选证书或反向代理、`publicUrl` 和可信 Host。此插件不会更改监听接口或发现网络地址。反向代理必须保留外部 Host、移除配置的路径前缀,并保护上游连接。普通 HTTP 监听器为 HTTP 公布地址签发的 cookie 不带 `Secure`;HTTPS 监听器以及终止 TLS 的代理后的 HTTPS 公布地址仍使用 `Secure`。HTTPS 代理必须对外部源强制使用 HTTPS。设置面板允许 HTTP 登录,并提醒用户 HTTP 会明文传输登录凭据。
面板在卡片上方以共用提示说明尚未满足的地址前提。地址不可达或不受信任时,访问地址卡片保留可复制的干净 URL,不显示凭据告警,并隐藏二维码登录。二维码登录不可用时,部署信息的读取错误和重试操作保留在访问地址卡片中。重连后会重新检查地址前提。
面板在卡片上方以共用提示说明尚未满足的地址前提。地址不可达或不受信任时,访问地址卡片保留可复制的干净 URL,不显示凭据告警,并隐藏二维码登录。配对审批仍可使用。二维码登录不可用时,部署信息的读取错误和重试操作保留在访问地址卡片中。重连后会重新检查地址前提。
`cookieMaxAgeDays` 默认为 30,固定每份 Remote cookie 的绝对有效期。`ticketLifetimeMs` 默认为 120000。`pollIntervalMs` 默认为 1000,控制设置面板显示二维码时的状态检查间隔。每个插件实例同一时间只有一个待使用邀请:生成新邀请会替换旧邀请,取消旧邀请不会取消替代它的新邀请。
@@ -43,12 +44,49 @@ Web bundle 挂载此插件。Host 端依赖 `connection`、`connection.authentic
Remote 拥有持久的 `client-remote-connection/browser-session` 凭据记录。其签名密钥和 v1 cookie 格式独立于 Token;cookie 绑定监听协议与规范化 Host,携带固定签发及到期时间,并使用 `HttpOnly`、`SameSite=Strict` 和 `Path=/`。验证不续期。记录损坏会使插件激活失败,不会替换密钥。保留此记录可让有效登录跨重启继续使用;替换或删除记录会在下次激活时使旧 cookie 失效。
Remote 在根地址使用同一份登录文档处理普通登录和二维码兑换。来源可信但尚未登录的普通根地址访问返回 HTTP 401,HEAD 保留 401 且不返回正文。`login=qr` 模式以 HTTP 200 返回同一份普通登录文档,即使浏览器已有登录 cookie;它尝试二维码兑换,保留页面上的登录控件。文档不暴露 Token 值或私有应用注入;普通登录模式仅在 Token 发布入口时显示 Token 表单。Token 输入框支持令牌或完整登录链接,占位提示使用当前页面的协议、地址、端口和应用路径,使用 `xxx` 作为令牌示例,并采用主题的 caption 颜色,不带入现有查询参数或片段。页面初始化前,HTML 使用通用地址模板。说明引导用户在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此页面。页面沿用应用的默认字体栈和灰阶文字渲染。Token 输入框聚焦时使用主题蓝色细边框,校验错误时保留红色边框。已登录且未指定二维码模式的访问使用实际 Peer 渲染应用,不再次验证凭据。来源拒绝保持 403;认证故障且没有其它成功提供者时保持 503。
Remote 在根地址使用同一份登录文档处理普通登录和二维码兑换。来源可信但尚未登录的普通根地址访问返回 HTTP 401,HEAD 保留 401 且不返回正文。`login=qr` 模式以 HTTP 200 返回同一份普通登录文档,即使浏览器已有登录 cookie;它尝试二维码兑换,保留页面上的登录控件。文档不暴露 Token 值或私有应用注入;Token 发布入口时始终显示 Token 表单。Token 输入框支持令牌或完整登录链接,占位提示使用当前页面的协议、地址、端口和应用路径,使用 `xxx` 作为令牌示例,并采用主题的 caption 颜色,不带入现有查询参数或片段。页面初始化前,HTML 使用通用地址模板。说明引导用户在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此页面。页面沿用应用的默认字体栈和灰阶文字渲染。Token 输入框聚焦时使用主题蓝色细边框,校验错误时保留红色边框。已登录且未指定二维码模式的访问使用实际 Peer 渲染应用,不再次验证凭据。来源拒绝保持 403;认证故障且没有其它成功提供者时保持 503。
<a id="pairing-requests"></a>
## 配对申请
匿名根页面在共同标题下将 Token 输入和设备配对分为两张卡片。页面说明引导用户选择下方任一可用方式验证登录。两张卡片均按标题、说明、操作控件的顺序排列,并使用相同的字体与间距。令牌输入错误时,在输入框下显示错误信息,标题下的说明保持可见。二维码兑换提示位于两张卡片上方;兑换失败后,两种登录方式均可继续使用。公开的 `pairing/client.js` 脚本以 defer 方式加载,定义 `dsh-device-pairing`;元素自主管理申请控件、样式和词典,无需加载已认证 Client 模块。Host 使用随普通入口发布的自包含浏览器函数及公开数据生成此脚本;重新加载插件后,脚本随实现一同更新。移除元素会中止工作并丢弃私密票据;浏览器前进后退缓存的暂停则保留票据,并在恢复时查询状态。
匿名配对卡片依次显示配对码、重新申请、取消申请和等待状态,倒计时位于状态旁。申请和状态查询失败以占满内容宽度的错误横幅显示,拒绝和过期使用警告横幅。横幅不含图标,描边、间距和圆角与设置页远程连接中的横幅一致。倒计时位于横幅外。网络或服务端暂时失败时显示自动重连状态。HTTP 429 限流时提示稍后自动重试,次数耗尽后提示稍后重新申请。恢复次数耗尽后显示错误横幅和“重新申请”,不再提供独立的状态查询操作。申请操作禁用时保留主按钮的前景色。确认取消后恢复“申请配对”,不显示取消提示。
设置页在访问地址和二维码登录卡片之后,以独立卡片显示配对申请,即使公布的二维码地址不可用,审批仍可使用。只有卡片显示申请时,才展示完整访问权限警告。读取列表失败时,卡片隐藏申请和权限警告,显示错误提示和「重试」。重试成功后显示最新列表。通过配对登录的浏览器具有 owner 访问权限,也可以批准其他设备的申请。配对、二维码和链接登录分别管理状态:创建或取消配对申请不会替换二维码邀请或可重复使用的登录链接。
公开 POST 路由 `pairing/request`、`pairing/status` 和 `pairing/cancel` 声明匿名认证;WebServer 在调用处理函数前执行 Host、Origin 和 Fetch Metadata 检查。URL 相对于应用目录解析,以支持反向代理挂载。浏览器在首次创建前生成 ID 和随机 secret,三个路由的 JSON 请求体均仅含这两个字段。使用相同 ID、secret 和 origin 重复创建会返回保留的票据,不延长有效期,也不改变审批或取消结果。Host 生成独立的显示码,并保留首次创建连接的 IP。只有申请者持有 secret;显示码不能用于查询、取消或领取申请。设置页使用 `remoteConnection/pairingRequests` 和 `remoteConnection/decidePairing`;两者都要求当前 invocation 具有 owner 身份,即使 API peer 拥有方法调用权限也不例外。
审批行显示创建申请时从连接中取得的 `sourceIp`,并归一化 IPv4/IPv6 格式;地址缺失时显示“未知”。转发头不参与取值,经过代理时显示的是代理 IP。`authority` 仍用于绑定应用 origin,不作为来源地址显示;IP 不用于识别设备或授予访问权限。
第一次批准或拒绝决定生效。取消可以撤回尚未领取的批准。批准后,申请者通过二维码兑换所用的私有签发函数领取 Remote cookie,与 Token 认证相互独立。响应丢失时,在申请过期前重试可领取同一 cookie,不会延长有效期。拒绝、取消、过期和插件关闭均不能创建登录。
owner 的审批返回 `approved`、`denied` 或 `unavailable` 后,卡片先从可见列表中移除该申请,再显示结果提示。此前仍在途的读取结果不能恢复该行,卡片会立即重新读取列表,即使上次读取失败。审批结果不确定时,列表保留该申请,直到后续读取确认其状态。其他设备产生的变更和申请过期仍通过定期轮询更新。
申请者可以在创建申请或等待批准时取消。创建响应不确定时,浏览器先使用保留的凭据重复创建,取得同一份票据,再确认取消。取消结果不确定时保留凭据,不会创建另一份申请。
等待页面显示剩余时间。创建、状态读取、取消和登录检查均限制完整响应的等待时间。网络失败、无法读取响应、HTTP 429 和服务端失败会自动重试:以 `pollIntervalMs` 为初始延迟指数退避,最多等待 `retryMaxDelayMs`,追加尝试不超过 `maxRetries` 次。状态读取成功后重置次数,其他 HTTP 拒绝立即停止。次数耗尽后停止自动操作并显示错误横幅。**重新申请**先确认旧申请结束,再生成新凭据和配对码;取消结果不确定时绝不创建替代申请。进行中的操作会被中止,其迟到结果不能覆盖新申请。拒绝、取消或确认过期后,同一操作创建新申请。
本地计时到期或 Host 报告过期时,页面中止未完成的配对操作,并向干净的应用 URL 发送不使用缓存的 `HEAD` 请求,核对浏览器认证状态。`200` 会打开应用;收到 `401` 后还会确认取消旧申请,因为 Host 的有效期可能晚于本地倒计时。只有此后才能结束等待或创建替代申请。检查失败时按同样的次数限制自动恢复。次数耗尽后保留凭据并报告登录结果尚不确定;**重新申请**会先重新检查,再决定能否创建新申请。只有确认浏览器未登录后才允许重新开始;取消 fetch 不会撤销已收到的 cookie。
在此插件的 `pairing` 字段下配置申请限制:
| 字段 | 默认值 | 含义 |
|---|---:|---|
| `pairing.requestTtlMs` | 300000 | 申请有效期,包含批准后的领取重试;必须大于轮询间隔 |
| `pairing.maxRequests` | 32 | 保留的待处理与已结束申请总数上限 |
| `pairing.requestIntervalMs` | 1000 | 所有申请者共用的最短创建间隔 |
| `pairing.pollIntervalMs` | 2000 | 申请端最小轮询间隔、初始重试延迟与设置页定期刷新的间隔 |
| `pairing.requestTimeoutMs` | 10000 | 单次 HTTP 尝试的超时,包含响应体读取 |
| `pairing.maxRetries` | 3 | 暂时失败后的追加尝试次数 |
| `pairing.retryMaxDelayMs` | 10000 | 指数退避的最大延迟,不得小于轮询间隔 |
申请只保存在当前进程的有界请求池中,决定后仍保留至过期。重启或卸载插件会清空申请,但不会撤销已签发的 cookie。请求池已满或达到创建频率限制时,申请者需稍后重试;轮询失败会保留私密票据,以便恢复查询。
<a id="add-settings-options"></a>
## 添加设置选项
在根作用域的列表插槽 `settings.remoteConnection.extensions` 中注册,即可在主面板后添加选项。各插件使用唯一的 `id`;条目按 `order` 升序排列,相同值按注册顺序排列。扩展内容可与默认面板或替换面板同时显示。`RemoteConnectionExtensionProps` 提供与[面板替换组件](#replace-the-settings-panel)相同的共享状态 Hook、操作和 `close()`。各扩展组件负责自己的渲染和本地化文案。
在根作用域的列表插槽 `settings.remoteConnection.extensions` 中注册,即可在主面板(包括默认的访问地址、二维码登录和配对卡片)之后添加选项。各插件使用唯一的 `id`;条目按 `order` 升序排列,相同值按注册顺序排列。扩展内容可与默认面板或替换面板同时显示。`RemoteConnectionExtensionProps` 提供与[面板替换组件](#replace-the-settings-panel)相同的共享状态 Hook、操作和 `close()`。各扩展组件负责自己的渲染和本地化文案。
```ts client
import type { Context } from '@deepseek-ai/cordis'
@@ -72,7 +110,7 @@ export function apply(ctx: Context): void {
<a id="replace-the-settings-panel"></a>
## 替换设置面板
根作用域的单选插槽 `settings.remoteConnection.content` 支持替换主面板,同时保留唯一的设置导航项和追加的扩展内容。所有组件都获得本包 `/client` 类型入口导出的 `RemoteConnectionContentProps`:`useRemoteConnection(selector)`、`create()`、`cancel()`、`reload()`、`useLoginLink(selector)`、`copyLink()`、`reloadLink()`、`dismissCopyNotice(sequence)` 和设置外壳的 `close()`。插件在视图替换期间持有邀请和链接状态,因此切换视图会保留当前邀请、倒计时和复制反馈。操作结果通过状态 Hook 返回。替换组件负责自己的渲染和本地化文案,可以注册自己的 `locale` 命名空间。
根作用域的单选插槽 `settings.remoteConnection.content` 支持替换主面板,包括默认的访问地址、二维码登录和配对卡片,同时保留唯一的设置导航项和追加的扩展内容。所有组件都获得本包 `/client` 类型入口导出的 `RemoteConnectionContentProps`:`useRemoteConnection(selector)`、`create()`、`cancel()`、`reload()`、`useLoginLink(selector)`、`copyLink()`、`reloadLink()`、`dismissCopyNotice(sequence)` 和设置外壳的 `close()`。两类插槽 props 均提供 `useApproval(selector)`、`decide(id, decision)` 和 `dismiss()`;仅在 `available` 为 true 时渲染审批控件。插件在视图替换期间持有邀请、链接和配对审批状态,因此切换视图会保留当前邀请、倒计时和复制反馈。操作结果通过状态 Hook 返回。替换组件负责自己的渲染和本地化文案,可以注册自己的 `locale` 命名空间。
在 Client 插件中注册替换组件,优先级应低于默认面板的 `0`:
@@ -94,7 +132,7 @@ export function apply(ctx: Context): void {
}
```
`slots.inject` 支持先于远程连接插件加载任一种贡献,并在插槽所有者重新出现时恢复注册。卸载扩展组件仅移除该贡献,保留主面板、其他扩展和共享状态。卸载替换插件会恢复默认面板及其当前状态;卸载远程连接插件则移除两个插槽、停止轮询、立即丢弃链接凭据和复制提示,并等待进行中的读取、剪贴板写入和排队刷新完成。仅在 `phase === 'pending'` 时将 `ticket.url` 显示为二维码:结果不确定的操作可能保留票据用于恢复,但不允许展示。不得持久保存或记录任一凭据 URL。替换此面板不会替换匿名登录页面或 Host 邀请协议。
`slots.inject` 支持先于远程连接插件加载任一种贡献,并在插槽所有者重新出现时恢复注册。卸载扩展组件仅移除该贡献,保留主面板、其他扩展和共享状态。卸载替换插件会恢复默认面板及其当前状态;卸载远程连接插件则移除两个插槽、停止轮询、立即丢弃链接凭据和复制提示,并等待进行中的读取、剪贴板写入和排队刷新完成。仅在 `phase === 'pending'` 时将 `ticket.url` 显示为二维码:结果不确定的操作可能保留票据用于恢复,但不允许展示。不得持久保存或记录任一凭据 URL。替换此面板不会替换匿名登录页面或 Host 的任一登录方式。
<a id="further-exploration"></a>
## 进一步探索
@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-client-remote-connection",
"description": "Settings panel and single-use QR login for another browser",
"description": "QR login, private login links, and owner-approved browser pairing",
"version": "0.2.2-rc.5",
"publishConfig": {
"access": "public"
@@ -129,7 +129,7 @@
margin-inline-start: auto;
}
.qrActions > button,
.cardActions > button,
.linkRow > button,
.actions > button {
flex: none;
@@ -1,4 +1,4 @@
/** Access address and QR login for browser sign-in. */
/** Access address, QR login, and pairing approvals for browser sign-in. */
import { QRCodeSVG } from 'qrcode.react'
import { Button, IconWarningOutlineMedium, StateDot } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
@@ -10,12 +10,13 @@ import css from './RemoteConnectionSection.module.css'
export type RemoteConnectionSectionProps = RemoteConnectionContentProps & PropsLocale<'remoteConnection'>
/**
* Present address prerequisites, an access address, available QR login.
* Present address prerequisites, an access address, available QR login, and pairing cards.
* @param props - Section injection and standard slot props.
* @returns Remote connection settings content.
*/
export function RemoteConnectionSection(props: RemoteConnectionSectionProps) {
const { t, useRemoteConnection } = props
const { t, useRemoteConnection, useApproval } = props
const pairingAvailable = useApproval(state => state.available)
const available = useRemoteConnection(state => state.deployment?.availability === 'available')
const loading = useRemoteConnection(state => state.phase === 'loading' && state.deployment === null)
if (loading) return <section className={css.section} aria-label={t('title')}>
@@ -27,6 +28,7 @@ export function RemoteConnectionSection(props: RemoteConnectionSectionProps) {
<ConnectionNotice {...props} />
<AccessAddressCard {...props} />
{available && <QrLoginCard {...props} />}
{pairingAvailable && <PairingRequests {...props} />}
</section>
}
@@ -53,7 +55,7 @@ function QrLoginCard({ t, useRemoteConnection, create, cancel, reload }: Pick<Re
return <section className={css.card} aria-label={t('qrTitle')} aria-busy={busy || undefined}>
<header className={css.cardHeader}>
<h3 className={css.methodTitle}>{t('qrTitle')}</h3>
<div className={css.qrActions}>
<div className={css.cardActions}>
<Button variant="primary" size="sm" disabled={busy} onClick={create}>
{t(regenerate ? 'regenerate' : 'generate')}
</Button>
@@ -45,6 +45,13 @@ export async function apply(ctx: Context): Promise<void> {
const link = new LoginLinkController(scope.remote.remoteConnection, writeClipboard,
() => controller.store.getSnapshot().deployment?.url ?? null,
() => controller.store.getSnapshot().deployment?.availability === 'available')
const pairing = requestsResource(scope.remote.remoteConnection)
const approval = new PairingApproval(scope.remote.remoteConnection, id => pairing.confirmed(id))
const pairingFace = (): PairingInjected => ({
hooks: { approval: approval.state },
decide: (id, decision) => approval.decide(id, decision),
dismiss: () => { approval.dismiss() },
})
const invitationFace = controller.inject()
const linkFace = link.inject()
const approvalFace = pairingFace()
@@ -45,7 +45,7 @@ export class LoginLinkController {
* @param canCopyCredential - whether the current deployment permits copying a credential link.
*/
constructor(
private readonly remote: Pick<RemoteConnectionApi, 'loginUrl'>,
private readonly remote: Pick<TypertClientRemote['remoteConnection'], 'loginUrl'>,
private readonly write: (text: string) => Promise<boolean>,
private readonly accessAddress: () => string | null,
private readonly canCopyCredential: () => boolean,
@@ -21,14 +21,14 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
}
/**
* Additional options rendered after the active Remote connection panel.
* Entries share its invitation and login-link state, actions, and close().
* Entries share its invitation, login-link, and owner-gated pairing state, actions, and close().
* Replacing the panel does not replace these independently ordered entries.
*/
'settings.remoteConnection.extensions': {
kind: 'list'
scope: 'root'
owner: SettingsSectionOwnerProps
inject: RemoteConnectionFace & LoginLinkFace
inject: RemoteConnectionFace & LoginLinkFace & PairingInjected
}
}
}
@@ -36,5 +36,5 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
/** Settings close action and shared QR, login-link, and owner-gated pairing state/actions supplied to every panel. */
export type RemoteConnectionContentProps = PropsRuntime<'settings.remoteConnection.content'>
/** Shared login state, actions, and settings close action supplied to appended options. */
/** Shared login and owner-gated pairing state, actions, and settings close action supplied to appended options. */
export type RemoteConnectionExtensionProps = PropsRuntime<'settings.remoteConnection.extensions'>
@@ -184,6 +184,7 @@ export default class RemoteConnection extends TypertRemoteService {
if ('rejection' in admission && admission.rejection !== 401) return new Response('authentication unavailable', { status: admission.rejection, headers })
const html = renderAuthenticationPage({
tokenLoginEnabled: this.tokenLoginUrl(this.owner.webApp.getAdvertisedUrl()) !== undefined,
pairingEnabled: true,
})
return new Response(request.method === 'HEAD' ? null : html, { status: qrLogin ? 200 : 401, headers })
}
@@ -5,6 +5,8 @@ import { loginLocales } from './login-locales.ts'
export interface AuthenticationPageOptions {
/** Whether the default Token provider has published its login entry. */
readonly tokenLoginEnabled: boolean
/** Whether the Remote provider accepts device-pairing requests. */
readonly pairingEnabled?: boolean
}
const pageStyle = `
@@ -140,14 +142,18 @@ export function enterAuthenticationPage(
/**
* Render Remote's root login page, without a Token value or private boot data.
* @param options - public Token availability.
* @returns self-contained sign-in choices with independent QR exchange feedback.
* @param options - Token login and device-pairing availability.
* @returns sign-in cards with titles and descriptions above controls, below the shared heading and QR feedback.
*/
export function renderAuthenticationPage(options: AuthenticationPageOptions): string {
const t = loginLocales.en
const placeholder = t.tokenPlaceholder.replace('{url}', t.tokenPlaceholderFallbackUrl)
const content = `<h1 id="title">${t.authenticationTitle}</h1><p id="description" class="description">${options.tokenLoginEnabled ? t.authenticationDescription : t.authenticationUnavailable}</p><div id="qr-notice" class="notice" hidden><p id="status" role="status"></p><a id="open" href="./" hidden>${t.open}</a></div>${options.tokenLoginEnabled ? `<form id="token-form" action="./" method="get"><label id="token-label" for="token">${t.tokenLabel}</label><input id="token" type="password" name="token" placeholder="${placeholder}" required autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" aria-describedby="token-hint token-error"><p id="token-hint" class="hint">${t.tokenHint}</p><p id="token-error" class="error" role="alert"></p><button id="token-submit" type="submit">${t.tokenSubmit}</button></form>` : ''}`
return documentHtml(t.authenticationTitle, content, `(${enterAuthenticationPage.toString()})(${scriptJson(loginLocales)},(${enterBrowser.toString()}))`)
const tokenForm = options.tokenLoginEnabled ? `<form id="token-form" action="./" method="get" aria-labelledby="token-title"><h2 id="token-title"><label id="token-label" for="token">${t.tokenLabel}</label></h2><p id="token-hint" class="hint">${t.tokenHint}</p><input id="token" type="password" name="token" placeholder="${placeholder}" required autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" aria-describedby="token-hint token-error"><p id="token-error" class="error" role="alert"></p><button id="token-submit" type="submit">${t.tokenSubmit}</button></form>` : ''
const pairing = options.pairingEnabled
? `<dsh-device-pairing><noscript><p>${t.pairingScriptRequired}</p></noscript></dsh-device-pairing>` : ''
const methods = tokenForm || pairing ? `<div class="methods">${tokenForm}${pairing}</div>` : ''
const content = `<h1 id="title">${t.authenticationTitle}</h1><p id="description" class="description">${options.tokenLoginEnabled || options.pairingEnabled ? t.authenticationDescription : t.authenticationUnavailable}</p><div id="qr-notice" class="notice" hidden><p id="status" role="status"></p><a id="open" href="./" hidden>${t.open}</a></div>${methods}`
return documentHtml(t.authenticationTitle, content, `(${enterAuthenticationPage.toString()})(${scriptJson(loginLocales)},(${enterBrowser.toString()}))`, options.pairingEnabled)
}
/**
@@ -76,7 +76,24 @@ function extensionPlugin(id: string, order: number) {
}
}
async function bench(call: ConnectionHandle['rpc']['call'], beforeMount?: (ctx: Context) => Promise<void>) {
function PairingExtension({ useApproval, decide, dismiss }: RemoteConnectionExtensionProps) {
const approval = useApproval(state => state)
return createElement('section', { 'aria-label': 'Pairing extension' },
createElement('output', { 'aria-label': 'Approval status' }, approval.available ? approval.notice ?? 'ready' : 'unavailable'),
createElement('button', { disabled: !approval.available || approval.busy, onClick: () => { void decide('request-one' as PairingRequestId, 'allow') } }, 'Approve request'),
createElement('button', { onClick: dismiss }, 'Dismiss approval'))
}
const pairingExtensionPlugin = {
inject: ['slots'],
apply(ctx: Context) {
ctx.slots.inject('settings.remoteConnection.extensions', () => ctx.slots.register({
name: 'settings.remoteConnection.extensions', id: 'pairing-options',
}, PairingExtension))
},
}
async function bench(call: ConnectionHandle['rpc']['call'], beforeMount?: (ctx: Context) => Promise<void>, allowed = true) {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
await ctx.plugin(TypertRegistry).await()
@@ -126,19 +143,19 @@ describe('remote connection settings registration', () => {
await screen.findByRole('button', { name: '生成二维码' })
expect(await screen.findByRole('region', { name: '配对申请' })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.qrTitle })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.linkTitle })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.addressTitle })).toBeTruthy()
expect(slots.entries('settings.section')).toHaveLength(1)
const replacement = ctx.plugin(replacementPlugin)
await act(async () => { await replacement.await() })
expect(screen.queryByRole('region', { name: '配对申请' })).toBeNull()
expect(screen.queryByRole('region', { name: zh.linkTitle })).toBeNull()
expect(screen.queryByRole('region', { name: zh.addressTitle })).toBeNull()
expect(screen.queryByRole('button', { name: '生成二维码' })).toBeNull()
expect(screen.getByRole('region', { name: 'Custom connection' })).toBeTruthy()
expect(slots.entries('settings.section')).toHaveLength(1)
await act(async () => { await replacement.dispose() })
expect(await screen.findByRole('region', { name: '配对申请' })).toBeTruthy()
expect(screen.getByRole('button', { name: '生成二维码' })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.linkTitle })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.addressTitle })).toBeTruthy()
await act(async () => { await fiber.dispose() })
expect(slots.entries('settings.remoteConnection.content')).toEqual([])
expect(slots.entries('shell.overlay')).toEqual([])
@@ -236,6 +253,7 @@ describe('remote connection settings registration', () => {
it('appends ordered options without replacing the cards and keeps other entries and login state when one unloads', async () => {
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => {
if (endpoint === 'remoteConnection/pairingRequests') return { ok: true, value: { requests: [], pollIntervalMs: 60_000 } }
if (endpoint === 'remoteConnection/loginUrl') return { ok: true, value: 'https://host.example/?token=private' }
if (endpoint === 'remoteConnection/create') {
return { ok: true, value: { id: 'extension-invitation', url: 'https://host.example/?login=qr#private', lifetimeMs: 120_000 } }
@@ -254,8 +272,10 @@ describe('remote connection settings registration', () => {
const earlier = ctx.plugin(extensionPlugin('Earlier options', 10))
await act(async () => { await earlier.await() })
const earlierRegion = screen.getByRole('region', { name: 'Earlier options' })
expect(screen.getAllByRole('region').map(region => region.getAttribute('aria-label')))
.toEqual([zh.title, zh.addressTitle, zh.qrTitle, 'Earlier options', 'Later options'])
expect(screen.getAllByRole('region')).toEqual(
[zh.title, zh.addressTitle, zh.qrTitle, zh['pairing.title'], 'Earlier options', 'Later options']
.map(name => screen.getByRole('region', { name })),
)
expect(screen.getByRole('img', { name: zh.qr })).toBe(qr)
expect(earlierRegion.dataset).toMatchObject({ phase: 'pending', ticket: 'extension-invitation', link: 'ready' })
expect(laterRegion.dataset).toMatchObject({ phase: 'pending', ticket: 'extension-invitation', link: 'ready' })
@@ -438,8 +458,9 @@ describe('remote connection settings registration', () => {
})
const url = 'https://host.example/?token=private-login-token'
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
ok: true, value: endpoint === 'remoteConnection/loginUrl' ? url
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
: endpoint === 'remoteConnection/loginUrl' ? url
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
}))
const { slots } = await bench(call)
render(slots.renderSlot('root', {}))
@@ -517,7 +538,8 @@ describe('remote connection settings registration', () => {
const url = 'https://host.example/'
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => {
if (endpoint === 'remoteConnection/loginUrl') throw new Error('credential transport unavailable')
return { ok: true, value: { url, availability: 'available', ticket: 'none', pollIntervalMs: 1000 } }
return { ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
: { url, availability: 'available', ticket: 'none', pollIntervalMs: 1000 } }
})
const { slots, locale } = await bench(call)
locale.setLocale(language)
@@ -604,17 +626,66 @@ it('submits approval through the shared namespace and keeps its notice outside S
expect(face.hooks.approval.getSnapshot().available).toBe(false)
})
it('shares owner approval with appended options across panel replacement', async () => {
const decision = Promise.withResolvers<{ ok: true; value: 'approved' }>()
onTestFinished(() => { decision.resolve({ ok: true, value: 'approved' }) })
let approved = false
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => {
if (endpoint === 'remoteConnection/decidePairing') {
const result = await decision.promise
approved = true
return result
}
if (endpoint === 'remoteConnection/pairingRequests') return { ok: true, value: {
requests: approved ? [] : [{ id: 'request-one', code: 'ABCD2345', authority: 'https://host.example', sourceIp: '192.0.2.17', expiresInMs: 60000 }],
pollIntervalMs: 1000,
} }
return { ok: true, value: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 } }
})
const { ctx, slots, fiber } = await bench(call)
const extension = ctx.plugin(pairingExtensionPlugin)
await extension.await()
render(createElement(Fragment, null, slots.renderSlot('root', {})))
const approval = await screen.findByRole('button', { name: zh['pairing.approve'] })
const options = within(screen.getByRole('region', { name: 'Pairing extension' }))
expect(options.getByRole('status', { name: 'Approval status' }).textContent).toBe('ready')
fireEvent.click(options.getByRole('button', { name: 'Approve request' }))
expect(approval.hasAttribute('disabled')).toBe(true)
expect(options.getByRole('button', { name: 'Approve request' }).hasAttribute('disabled')).toBe(true)
await act(async () => { decision.resolve({ ok: true, value: 'approved' }) })
await screen.findByText(zh['pairing.approved'])
expect(options.getByRole('status', { name: 'Approval status' }).textContent).toBe('approved')
expect(screen.queryByText('ABCD 2345')).toBeNull()
expect(call).toHaveBeenCalledWith('/api', 'remoteConnection/decidePairing', { args: { id: 'request-one', decision: 'allow' } }, expect.any(AbortSignal))
const replacement = ctx.plugin(replacementPlugin)
await act(async () => { await replacement.await() })
expect(screen.queryByRole('region', { name: '配对申请' })).toBeNull()
expect(options.getByRole('status', { name: 'Approval status' }).textContent).toBe('approved')
fireEvent.click(options.getByRole('button', { name: 'Dismiss approval' }))
expect(screen.queryByText(zh['pairing.approved'])).toBeNull()
expect(approvalFace(slots).hooks.approval.getSnapshot().notice).toBeNull()
await act(async () => { await extension.dispose() })
expect(screen.queryByRole('region', { name: 'Pairing extension' })).toBeNull()
expect(screen.getByRole('region', { name: 'Custom connection' })).toBeTruthy()
await act(async () => { await fiber.dispose() })
})
it('preserves QR navigation while refusing pairing controls and reads without owner access', async () => {
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
ok: true, value: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
}))
const { slots, fiber } = await bench(call, undefined, false)
const { ctx, slots, fiber } = await bench(call, undefined, false)
await ctx.plugin(pairingExtensionPlugin).await()
render(createElement(Fragment, null, slots.renderSlot('root', {})))
await screen.findByRole('button', { name: '生成二维码' })
expect(slots.entries('settings.section')).toHaveLength(1)
expect(slots.entries('shell.overlay').map(entry => entry.options.id)).toEqual(['remote-connection-copy'])
expect(screen.queryByRole('region', { name: '配对申请' })).toBeNull()
const options = within(screen.getByRole('region', { name: 'Pairing extension' }))
expect(options.getByRole('status', { name: 'Approval status' }).textContent).toBe('unavailable')
expect(options.getByRole('button', { name: 'Approve request' }).hasAttribute('disabled')).toBe(true)
await approvalFace(slots).decide('request-one' as PairingRequestId, 'allow')
await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(2) })
expect(call.mock.calls.map(([, endpoint]) => endpoint)).toEqual(['remoteConnection/status', 'remoteConnection/loginUrl'])
@@ -2,6 +2,7 @@
/** Anonymous login-page effects before the authenticated application loads. */
import { afterEach, expect, it, vi } from 'vitest'
import { enterAuthenticationPage, renderAuthenticationPage } from '../src/login-page.ts'
import type { AuthenticationPageOptions } from '../src/login-page.ts'
import { loginLocales } from '../src/login-locales.ts'
const TOKEN = 'a'.repeat(43)
@@ -39,7 +40,7 @@ function page(path = `/?login=qr#${TOKEN}`, language = 'en-US') {
}
}
function authenticationPage(options = { tokenLoginEnabled: true }, language = 'en-US') {
function authenticationPage(options: AuthenticationPageOptions = { tokenLoginEnabled: true }, language = 'en-US') {
const html = new DOMParser().parseFromString(renderAuthenticationPage(options), 'text/html')
document.documentElement.innerHTML = html.documentElement.innerHTML
history.replaceState(null, '', '/mount/')
@@ -134,6 +135,8 @@ it('clears a Token from the address and clears submission feedback on edit', asy
await expect.poll(() => fixture.error.textContent).toBe(loginLocales.zh.tokenInvalid)
await expect.poll(() => fixture.submit.disabled).toBe(false)
expect(fixture.input.getAttribute('aria-invalid')).toBe('true')
expect(fixture.input.previousElementSibling?.textContent).toBe(loginLocales.zh.tokenHint)
expect(fixture.input.nextElementSibling).toBe(fixture.error)
fixture.input.dispatchEvent(new Event('input'))
expect(fixture.error.textContent).toBe('')
expect(fixture.input.hasAttribute('aria-invalid')).toBe(false)
@@ -393,3 +396,45 @@ it('escapes embedded localized text before serializing the anonymous script', ()
loginLocales.en.tokenPlaceholder.replace('{url}', loginLocales.en.tokenPlaceholderFallbackUrl),
)
})
it.each(['en-US', 'zh-CN'])('keeps device pairing available without the Token provider in %s', (language) => {
const fixture = authenticationPage({ tokenLoginEnabled: false, pairingEnabled: true }, language)
enterAuthenticationPage(loginLocales)
const t = language.startsWith('zh') ? loginLocales.zh : loginLocales.en
expect(document.getElementById('description')?.textContent).toBe(t.authenticationDescription)
expect(document.getElementById('token-form')).toBeNull()
expect(document.querySelectorAll('dsh-device-pairing')).toHaveLength(1)
const script = document.querySelector<HTMLScriptElement>('script[src]')!
expect(script.getAttribute('src')).toBe('./pairing/client.js')
expect(script.defer).toBe(true)
expect(document.documentElement.innerHTML).not.toContain('__DSH_BOOT__')
expect(document.documentElement.innerHTML).not.toContain('authPages')
expect(fixture.exchange).not.toHaveBeenCalled()
})
it('renders the Token form and pairing as separate sign-in actions in the same document', () => {
const fixture = authenticationPage({ tokenLoginEnabled: true, pairingEnabled: true })
enterAuthenticationPage(loginLocales)
expect(fixture.form.querySelector('dsh-device-pairing')).toBeNull()
expect(fixture.form.nextElementSibling?.tagName).toBe('DSH-DEVICE-PAIRING')
expect(document.querySelectorAll('script[src]')).toHaveLength(1)
expect(renderAuthenticationPage({ tokenLoginEnabled: true, pairingEnabled: true }))
.toContain(`<dsh-device-pairing><noscript><p>${loginLocales.en.pairingScriptRequired}</p></noscript></dsh-device-pairing>`)
})
it.each([
{ methods: 'Token and pairing', tokenLoginEnabled: true, pairingEnabled: true, count: 2 },
{ methods: 'Token only', tokenLoginEnabled: true, pairingEnabled: false, count: 1 },
{ methods: 'pairing only', tokenLoginEnabled: false, pairingEnabled: true, count: 1 },
])('renders $methods below the shared heading and QR feedback', ({ tokenLoginEnabled, pairingEnabled, count }) => {
authenticationPage({ tokenLoginEnabled, pairingEnabled })
const methods = document.querySelector('.methods')!
expect(methods.children).toHaveLength(count)
expect(document.getElementById('token-form')?.parentElement).toBe(tokenLoginEnabled ? methods : undefined)
expect(document.querySelector('dsh-device-pairing')?.parentElement).toBe(pairingEnabled ? methods : undefined)
expect(document.getElementById('title')?.parentElement).toBe(methods.parentElement)
expect(document.getElementById('description')?.parentElement).toBe(methods.parentElement)
expect(document.getElementById('qr-notice')?.parentElement).toBe(methods.parentElement)
})
@@ -147,6 +147,8 @@ it('serves QR mode from the root even to a browser already authenticated through
expect(page.headers['cache-control']).toBe('no-store')
expect(page.headers['referrer-policy']).toBe('no-referrer')
expect(page.headers['content-security-policy']).toContain("frame-ancestors 'none'")
expect(page.body).toContain('<dsh-device-pairing>')
expect(page.body).toContain('./pairing/client.js')
expect(page.body).toContain('<h1 id="title">Connect to this Host</h1>')
expect(page.body).toContain('id="token-form"')
expect(page.body).toContain('id="qr-notice"')
@@ -45,13 +45,26 @@ function panel(overrides: Partial<RemoteConnectionState> = {}, language: 'en' |
}
describe('Remote connection section', () => {
it.each(['en', 'zh'] as const)('introduces the access address before QR login in %s', (language) => {
const additionsCases: readonly { label: string; state: Partial<RemoteConnectionState> }[] = [
{ label: 'ready', state: {} },
{ label: 'loading', state: { phase: 'loading', deployment: null } },
{ label: 'unreachable', state: { deployment: { ...ready.deployment!, availability: 'unreachable-host' } } },
{ label: 'failed', state: { phase: 'error', deployment: null, error: 'loadFailed' } },
]
it.each(additionsCases)('keeps pairing approvals visible when QR state is $label', ({ state }) => {
const { useResource } = panel(state, 'en', {}, true)
expect(screen.getByRole('region', { name: 'Pairing requests' })).toBeTruthy()
expect(useResource).toHaveBeenCalledExactlyOnceWith('dsh-resource://device-pairing/requests?retry=0')
})
it.each(['en', 'zh'] as const)('introduces the access address before QR login and pairing approvals in %s', (language) => {
const copy = language === 'en' ? en : zh
panel({}, language)
panel({}, language, {}, true)
const section = screen.getByRole('region', { name: copy.title })
expect(within(section).getAllByRole('heading', { level: 3 }).map(heading => heading.textContent))
.toEqual([copy.addressTitle, copy.qrTitle])
expect(within(section).getAllByRole('region')).toHaveLength(2)
.toEqual([copy.addressTitle, copy.qrTitle, copy['pairing.title']])
expect(within(section).getAllByRole('region')).toHaveLength(3)
const description = within(section).getByText(copy.addressDescription)
for (const card of within(section).getAllByRole('region')) {
expect(within(card).queryByText(copy.addressDescription)).toBeNull()
@@ -98,10 +111,10 @@ describe('Remote connection section', () => {
it.each([
['en', 'unreachable-host'], ['en', 'untrusted-host'],
['zh', 'unreachable-host'], ['zh', 'untrusted-host'],
] as const)('shows %s guidance for %s before the address', (language, availability) => {
] as const)('shows %s guidance for %s before the address and keeps pairing available', (language, availability) => {
const copy = language === 'en' ? en : zh
const url = availability === 'unreachable-host' ? 'http://127.0.0.1:5432/' : 'https://untrusted.example/app/'
const { copyLink } = panel({ deployment: { ...ready.deployment!, url, availability } }, language, { copied: true })
const { copyLink } = panel({ deployment: { ...ready.deployment!, url, availability } }, language, { copied: true }, true)
const section = screen.getByRole('region', { name: copy.title })
const notice = within(section).getByText(copy[availability])
expect(notice.closest('[role="status"]')).not.toBeNull()
@@ -116,6 +129,7 @@ describe('Remote connection section', () => {
fireEvent.click(copyAddress)
expect(copyLink).toHaveBeenCalledOnce()
expect(within(section).queryByRole('region', { name: copy.qrTitle })).toBeNull()
expect(within(section).getByRole('region', { name: copy['pairing.title'] })).toBeTruthy()
expect(screen.queryByRole('img')).toBeNull()
expect(screen.queryByText(copy.addressDescription)).toBeNull()
expect(screen.queryByText(copy.warning)).toBeNull()
@@ -4459,7 +4459,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
kind: 'list',
scope: 'root',
summary: 'Additional options rendered after the active Remote connection panel.',
doc: 'Additional options rendered after the active Remote connection panel.\nEntries share its invitation and login-link state, actions, and close().\nReplacing the panel does not replace these independently ordered entries.',
doc: 'Additional options rendered after the active Remote connection panel.\nEntries share its invitation, login-link, and owner-gated pairing state, actions, and close().\nReplacing the panel does not replace these independently ordered entries.',
registerOptions: [
{
name: 'id',
@@ -4498,12 +4498,12 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
keyDomain: '',
hookContext: '',
slotInject: 'RemoteConnectionFace & LoginLinkFace',
slotInject: 'RemoteConnectionFace & LoginLinkFace & PairingInjected',
declaredBy: 'an entry in \'settings.section\' (client-remote-connection), so it exists while that entry is mounted',
occupants: [],
replaceRisk: 'none',
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.remoteConnection.extensions\', () => ctx.slots.register(\n { name: \'settings.remoteConnection.extensions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
source: 'packages/client/remote-connection/src/client/slots.ts:25',
source: 'packages/client/remote-connection/src/client/slots.ts:27',
},
{
key: 'settings.section',