forked from cflmy/deepseek-harness
fix(remote-connection): restore login url for loopback (#8920)
* fix(remote-connection): show loopback login links Keep Token links available to the signed-in owner when the Host uses a loopback address. Explain the requirements for signing in from another device. * fix(remote-connection): hide entry on desktop
This commit is contained in:
1 parent
cc8dd8ea2d
commit
7b27ce4235
27 files changed
+332
-137
No files matched your search
@@ -5,7 +5,6 @@
|
||||
- button "模型"
|
||||
- button "插件管理"
|
||||
- button "Agent 预设"
|
||||
- button "远程连接"
|
||||
- button "打开配置文件"
|
||||
- button "关闭"
|
||||
- text: 权限 选择新会话的默认权限模式
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
- button "Models"
|
||||
- button "Plugins"
|
||||
- button "Agent presets"
|
||||
- button "Remote connection"
|
||||
- button "Open configuration file"
|
||||
- button "Close"
|
||||
- text: Permission Choose the default permission mode for new sessions
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
- dialog "设置":
|
||||
- text: 设置
|
||||
- navigation:
|
||||
- button "通用设置"
|
||||
- button "模型"
|
||||
- button "插件管理"
|
||||
- button "Agent 预设"
|
||||
- button "打开配置文件"
|
||||
- button "关闭"
|
||||
- heading "模型" [level=2]
|
||||
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
|
||||
- list:
|
||||
- listitem:
|
||||
- text: DeepSeek API deepseek-official API 密钥
|
||||
- button "认证说明": "?"
|
||||
- textbox "API 密钥":
|
||||
- /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY)
|
||||
- paragraph: 未检测到环境变量。请填写 API 密钥,或设置环境变量 DEEPSEEK_API_KEY。
|
||||
- group: 自定义设置
|
||||
- button "取消"
|
||||
- button "保存"
|
||||
- button "添加模型提供商"
|
||||
@@ -1,11 +1,17 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- status:
|
||||
- paragraph: 当前地址不能用于其他设备登录,请配置其他设备可访问的地址,例如能连通的局域网地址或已配置的公网、VPN 地址
|
||||
- paragraph: 当前地址无法用于跨设备登录。请用另一台设备能访问的地址重新启动服务。
|
||||
- list:
|
||||
- listitem: 两台设备在同一局域网时,可用局域网 IP。
|
||||
- listitem: 通过 VPN 或公网访问时,可用已开通访问的 VPN 地址或公网 IP。
|
||||
- region "访问地址":
|
||||
- heading "访问地址" [level=3]
|
||||
- code: {{access-address}}
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制链接"
|
||||
- paragraph: 请勿公开分享登录链接
|
||||
- paragraph: 此链接包含登录凭据,能访问此地址的人可凭链接登录,请仅发送给自己的设备,勿公开分享;重启服务后链接失效
|
||||
- paragraph: HTTP 会明文传输登录凭据,请仅在可信网络中使用
|
||||
- region "配对申请":
|
||||
- heading "配对申请" [level=3]
|
||||
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
|
||||
@@ -1,11 +1,17 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- status:
|
||||
- paragraph: 当前地址不能用于其他设备登录,请配置其他设备可访问的地址,例如能连通的局域网地址或已配置的公网、VPN 地址
|
||||
- paragraph: 当前地址无法用于跨设备登录。请用另一台设备能访问的地址重新启动服务。
|
||||
- list:
|
||||
- listitem: 两台设备在同一局域网时,可用局域网 IP。
|
||||
- listitem: 通过 VPN 或公网访问时,可用已开通访问的 VPN 地址或公网 IP。
|
||||
- region "访问地址":
|
||||
- heading "访问地址" [level=3]
|
||||
- code: {{access-address}}
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制链接"
|
||||
- paragraph: 请勿公开分享登录链接
|
||||
- paragraph: 此链接包含登录凭据,能访问此地址的人可凭链接登录,请仅发送给自己的设备,勿公开分享;重启服务后链接失效
|
||||
- paragraph: HTTP 会明文传输登录凭据,请仅在可信网络中使用
|
||||
- region "配对申请":
|
||||
- heading "配对申请" [level=3]
|
||||
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
|
||||
@@ -90,15 +90,16 @@ describe.skipIf(MODE === 'record').each([false, true])('web e2e: native credenti
|
||||
const settings = page.getByRole('dialog', { name: '设置', exact: true })
|
||||
await settings.getByRole('button', { name: '模型', exact: true }).click()
|
||||
await settings.getByLabel('API 密钥', { exact: true }).waitFor()
|
||||
expect(await settings.getByRole('button', { name: '远程连接', exact: true }).count()).toBe(desktop ? 0 : 1)
|
||||
expect(await page.getByRole('dialog', { name: '添加一个 API Key 开始使用' }).count()).toBe(0)
|
||||
expect(await welcome.count()).toBe(0)
|
||||
expect(await readFile(credentialPath, 'utf8')).toBe(credentials)
|
||||
const aria = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
|
||||
await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'models.expected.md'), aria, MODE)
|
||||
await compareOrRefreshGolden(join(SNAPSHOT_DIR, desktop ? 'models-desktop.expected.md' : 'models.expected.md'), aria, MODE)
|
||||
await page.keyboard.press('Escape')
|
||||
}
|
||||
expect(tripwire.warnings).toEqual([])
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
await assertFixtureInventory(SNAPSHOT_DIR, ['models.expected.md', 'signed-out-menu.expected.md'])
|
||||
await assertFixtureInventory(SNAPSHOT_DIR, ['models-desktop.expected.md', 'models.expected.md', 'signed-out-menu.expected.md'])
|
||||
})
|
||||
})
|
||||
@@ -859,14 +859,14 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise<void>
|
||||
}),
|
||||
})
|
||||
const body = await response.json() as {
|
||||
result: { ok: true; value: { url: string; availability: string; ticket: string; pollIntervalMs: number } }
|
||||
result: { ok: true; value: { url: string; availability: string; loginUrlAllowed: boolean; ticket: string; pollIntervalMs: number } }
|
||||
| { ok: false; error: { message: string } }
|
||||
}
|
||||
if (!body.result.ok) throw new Error(`empty remoteConnection/status failed: ${body.result.error.message}`)
|
||||
return body.result.value
|
||||
})
|
||||
expect(remoteStatus).toEqual({
|
||||
url: 'http://127.0.0.1:3080', availability: 'unreachable-host', ticket: 'none', pollIntervalMs: 1000,
|
||||
url: 'http://127.0.0.1:3080', availability: 'unreachable-host', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000,
|
||||
})
|
||||
const pairingScript = await page.evaluate(async () => {
|
||||
const transport = (globalThis as typeof globalThis & {
|
||||
|
||||
@@ -422,13 +422,18 @@ describe('web e2e: one-use QR browser login', () => {
|
||||
it.each([
|
||||
{
|
||||
name: 'unreachable', hostname: '127.0.0.1', options: {},
|
||||
warning: '当前地址不能用于其他设备登录,请配置其他设备可访问的地址,例如能连通的局域网地址或已配置的公网、VPN 地址',
|
||||
warning: '当前地址无法用于跨设备登录。请用另一台设备能访问的地址重新启动服务。',
|
||||
steps: [
|
||||
'两台设备在同一局域网时,可用局域网 IP。',
|
||||
'通过 VPN 或公网访问时,可用已开通访问的 VPN 地址或公网 IP。',
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'untrusted', hostname: 'untrusted-remote.test', options: { extraOverlayPath: UNTRUSTED_OVERLAY },
|
||||
warning: '请先将此访问地址加入 Host 的可信主机配置,才能使用下方的登录方式',
|
||||
steps: [],
|
||||
},
|
||||
])('explains unavailable address prerequisites before sign-in methods for $name', async ({ name, hostname, options, warning }) => {
|
||||
])('explains unavailable address prerequisites before sign-in methods for $name', async ({ name, hostname, options, warning, steps }) => {
|
||||
const scaffold = await launchWebScaffold(options)
|
||||
onTestFinished(() => scaffold.close())
|
||||
// The shared QR browser's proxy setup rejects the scaffold's loopback URL.
|
||||
@@ -436,6 +441,8 @@ describe('web e2e: one-use QR browser login', () => {
|
||||
onTestFinished(() => localBrowser.close())
|
||||
const plainUrl = scaffold.ctx.webApp.getAdvertisedUrl()
|
||||
expect(new URL(plainUrl).hostname).toBe(hostname)
|
||||
const loopback = name === 'unreachable'
|
||||
const expectedAddress = loopback ? scaffold.authenticatedUrl : plainUrl
|
||||
for (const [viewport, colorScheme, suffix] of [
|
||||
[{ width: 1200, height: 1000 }, 'light', 'desktop'],
|
||||
[MOBILE, 'dark', 'mobile-dark'],
|
||||
@@ -452,9 +459,10 @@ describe('web e2e: one-use QR browser login', () => {
|
||||
.getByRole('button', { name: '远程连接', exact: true }).click()
|
||||
const section = page.getByRole('region', { name: '远程连接', exact: true })
|
||||
const address = section.getByRole('region', { name: '访问地址', exact: true })
|
||||
await expect.poll(() => address.locator('code').textContent()).toBe(plainUrl)
|
||||
await expect.poll(async () => await address.locator('code').textContent() === expectedAddress).toBe(true)
|
||||
const notice = section.getByRole('status').filter({ hasText: warning })
|
||||
await notice.getByText(warning, { exact: true }).waitFor()
|
||||
expect(await notice.getByRole('listitem').allTextContents()).toEqual(steps)
|
||||
const pairing = section.getByRole('region', { name: '配对申请', exact: true })
|
||||
await waitForPairingList(pairing)
|
||||
expect(await section.getByRole('region').count()).toBe(2)
|
||||
@@ -467,11 +475,12 @@ describe('web e2e: one-use QR browser login', () => {
|
||||
expect(await address.getByRole('button').count()).toBe(1)
|
||||
await copy.click()
|
||||
await page.getByText('链接已复制', { exact: true }).waitFor()
|
||||
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(plainUrl)
|
||||
const copiedAddress = await page.evaluate(() => navigator.clipboard.readText())
|
||||
expect(copiedAddress === expectedAddress).toBe(true)
|
||||
expect(await copy.isEnabled()).toBe(true)
|
||||
expect(await section.getByText('请勿公开分享登录链接', { exact: true }).count()).toBe(0)
|
||||
expect(await section.getByText('请勿公开分享登录链接', { exact: true }).count()).toBe(loopback ? 1 : 0)
|
||||
expect(await section.getByText('请勿分享登录二维码', { exact: true }).count()).toBe(0)
|
||||
expect(new URL((await address.locator('code').textContent())!).searchParams.has('token')).toBe(false)
|
||||
expect(Boolean(new URL(copiedAddress).searchParams.get('token'))).toBe(loopback)
|
||||
const titleBox = await section.getByRole('heading', { level: 2 }).boundingBox()
|
||||
const noticeBox = await notice.boundingBox()
|
||||
const addressBox = await address.boundingBox()
|
||||
@@ -486,14 +495,24 @@ describe('web e2e: one-use QR browser login', () => {
|
||||
expect(noticeBox!.x + noticeBox!.width).toBeLessThanOrEqual(viewport.width)
|
||||
await compareOrRefreshGolden(join(EXPECTED, `${name}-${suffix}.expected.md`),
|
||||
await captureStableAria(page, 'section[aria-label="远程连接"]', scaffold.workspaceCwd, {
|
||||
replacements: [[plainUrl, '{{access-address}}']],
|
||||
replacements: [[scaffold.authenticatedUrl, '{{access-address}}?token={{login-token}}'], [plainUrl, '{{access-address}}']],
|
||||
}), MODE)
|
||||
const screenshots = process.env['DSH_REMOTE_CONNECTION_SCREENSHOTS']
|
||||
if (screenshots !== undefined) {
|
||||
await mkdir(screenshots, { recursive: true })
|
||||
await page.screenshot({ path: join(screenshots, `${name}-${suffix}.png`) })
|
||||
await page.screenshot({ path: join(screenshots, `${name}-${suffix}.png`), mask: loopback ? [address.locator('code')] : [] })
|
||||
}
|
||||
if (name === 'unreachable' && suffix === 'desktop') {
|
||||
if (loopback && suffix === 'desktop') {
|
||||
const guest = await localBrowser.newPage({ locale: ZH_BROWSER_LOCALE })
|
||||
try {
|
||||
await guest.goto(copiedAddress)
|
||||
await guest.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
expect(guest.url() === new URL(plainUrl).href).toBe(true)
|
||||
expect((await guest.context().cookies()).some(cookie => cookie.name.startsWith('dsh-auth-'))).toBe(true)
|
||||
} finally {
|
||||
await guest.close()
|
||||
}
|
||||
|
||||
await page.route('**/api/remoteConnection/status', route => route.abort('failed'))
|
||||
await page.reload()
|
||||
await openSettings(page, 'zh')
|
||||
@@ -512,7 +531,7 @@ describe('web e2e: one-use QR browser login', () => {
|
||||
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'unreachable-load-failed.png') })
|
||||
await page.unroute('**/api/remoteConnection/status')
|
||||
await retry.click()
|
||||
await expect.poll(() => address.locator('code').textContent()).toBe(plainUrl)
|
||||
await expect.poll(async () => await address.locator('code').textContent() === expectedAddress).toBe(true)
|
||||
await notice.getByText(warning, { exact: true }).waitFor()
|
||||
expect(await address.getByRole('alert').count()).toBe(0)
|
||||
}
|
||||
|
||||
@@ -15,11 +15,11 @@
|
||||
en: cb4114e511d9a1bb
|
||||
zh: e114ec11dac86de9
|
||||
/deepseek-ai-dsh-client-remote-connection/use-this-package:
|
||||
en: 291713708033cfaa
|
||||
zh: 2177ab1c731e7e41
|
||||
en: 1b041c2f19e60428
|
||||
zh: ed7603fc16dedd51
|
||||
/deepseek-ai-dsh-client-remote-connection/authentication-and-failures:
|
||||
en: 800ae2e8b5a319d1
|
||||
zh: c53eac07dab5b9d0
|
||||
en: f7536575431d8e1e
|
||||
zh: d39b1907e78abaa6
|
||||
/deepseek-ai-dsh-client-remote-connection/pairing-requests:
|
||||
en: 46a6fd8dc2514ef2
|
||||
zh: 0e35b1e5f23f2a73
|
||||
|
||||
@@ -24,11 +24,11 @@ Settings shows shared sign-in guidance, then access-address and QR login cards.
|
||||
|
||||
## Use this package
|
||||
|
||||
The Web bundle mounts this plugin. Its Host half requires `connection`, `connection.authentication`, `credentials`, `webServer`, and `webApp`; its Client half contributes the panel through `settings.section`. Removing the plugin removes its page, endpoints, outstanding invitation, and Remote Peer. Already-issued Remote cookies require this provider to be active; valid cookies can be used again after the plugin reloads with the same credential record. The settings panel supports all eight shipped UI languages; the anonymous login page supports English and Chinese. Both cards enclose their titles. The section heading and introductory text match the Models settings typography and spacing. QR actions share the title row on wide cards and stack at full width below the title on narrow cards. The panel uses standard small buttons. The URL field matches the copy button’s 28px height and centers the address text vertically. On narrow cards, the copy button spans the card’s content width below the URL field. The copy button keeps its label and disables only during a clipboard write. The expiry banner sits below the QR header and spans the card's content width. The countdown is centered below the QR code, with an additional 16px bottom margin before the credential warning. Regenerating a visible code replaces only the QR image with a spinner; the countdown, warning, and link controls stay in place. Cancelling closes the preview and restores **Create QR code** without a success message.
|
||||
The Web bundle mounts this plugin. Its Host half requires `connection`, `connection.authentication`, `credentials`, `webServer`, and `webApp`; its Client half contributes the panel to browser settings through `settings.section`. The Desktop window omits this section. Removing the plugin removes its page, endpoints, outstanding invitation, and Remote Peer. Already-issued Remote cookies require this provider to be active; valid cookies can be used again after the plugin reloads with the same credential record. The settings panel supports all eight shipped UI languages; the anonymous login page supports English and Chinese. Both cards enclose their titles. The section heading and introductory text match the Models settings typography and spacing. QR actions share the title row on wide cards and stack at full width below the title on narrow cards. The panel uses standard small buttons. The URL field matches the copy button’s 28px height and centers the address text vertically. On narrow cards, the copy button spans the card’s content width below the URL field. The copy button keeps its label and disables only during a clipboard write. The expiry banner sits below the QR header and spans the card's content width. The countdown is centered below the QR code, with an additional 16px bottom margin before the credential warning. Regenerating a visible code replaces only the QR image with a spinner; the countdown, warning, and link controls stay in place. Cancelling closes the preview and restores **Create QR code** without a success message.
|
||||
|
||||
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. Pairing approvals remain available. 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. For a trusted loopback address such as `127.0.0.1`, the access-address card shows the Token login link when the provider supplies one. The owner can copy it to sign in with another browser on the same computer. QR login stays hidden because other devices cannot reach this address. Wildcard and untrusted addresses show only the clean URL. 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.
|
||||
|
||||
@@ -38,7 +38,7 @@ The QR uses the advertised application root with `?login=qr` and an independentl
|
||||
|
||||
Only an authenticated owner can create, inspect, or cancel invitations. The Host retains a digest of the credential, not its reusable plaintext. The public page has no authenticated application injections and sends no credential to third parties. Failed QR exchanges keep the ordinary login page and its configured Token form available, with a localized banner explaining the failure. An interrupted exchange may already have issued the cookie; the banner offers a clean application link to check an unconfirmed result and never retries the one-use credential automatically.
|
||||
|
||||
The owner-only `loginUrl()` method reads the same WebServer instance’s Token entry published through `webserver/entry-url` and returns the advertised root with its process launch token in `?token=…`. A Host without Token authentication cannot provide this link; QR login remains available. Unlike the QR invitation, this link remains reusable until the Host process restarts. Copying it never creates, consumes, or replaces a QR invitation. The Client prefetches the URL only after deployment availability is confirmed, retains it in plugin memory, displays it with a fading right edge, and refreshes it on reconnection. Starting a credential read clears earlier copy notices. The credential warning resets when the URL changes or the user leaves Remote connection settings, including by closing the panel. A clipboard write that finishes after leaving still reports its outcome through the shell toast, but cannot restore the warning for a later visit. While the credential URL is loading or unavailable, copying uses the displayed clean address without a link-read error or Retry button; QR creation remains independent. Only a successful copy of the current credential URL enables its warning; copying the clean address does not. A refused clipboard write reports failure and leaves copying retryable. Neither link reads nor copy outcomes are persisted or logged.
|
||||
The owner-only `loginUrl()` method reads the same WebServer instance’s Token entry published through `webserver/entry-url` and returns the advertised root with its process launch token in `?token=…`. A Host without Token authentication cannot provide this link; QR login remains available. Unlike the QR invitation, this link remains reusable until the Host process restarts. Copying it never creates, consumes, or replaces a QR invitation. The Client prefetches the URL only after the Host allows Token login links for the advertised address, retains it in plugin memory, displays it with a fading right edge, and refreshes it on reconnection. Starting a credential read clears earlier copy notices. The credential warning resets when the URL changes or the user leaves Remote connection settings, including by closing the panel. A clipboard write that finishes after leaving still reports its outcome through the shell toast, but cannot restore the warning for a later visit. While the credential URL is loading or unavailable, copying uses the displayed clean address without a link-read error or Retry button; QR creation remains independent. Only a successful copy of the current credential URL enables its warning; copying the clean address does not. A refused clipboard write reports failure and leaves copying retryable. Neither link reads nor copy outcomes are persisted or logged.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -25,11 +25,11 @@ kind: "package-reference"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
Web bundle 挂载此插件。Host 端依赖 `connection`、`connection.authentication`、`credentials`、`webServer` 和 `webApp`,Client 端通过 `settings.section` 提供面板。移除插件会移除页面、端点、待使用的邀请和 Remote Peer。已签发的 Remote cookie 需要该提供者处于活动状态;插件使用同一凭据记录重新加载后,有效 cookie 可以继续使用。设置面板支持产品提供的全部八种界面语言;匿名登录页支持英文和中文。两张卡片的标题均位于边框内。页面标题和说明文字采用与模型设置页一致的字体和间距。宽卡片中的二维码操作与标题同行,窄卡片中则在标题下方纵向排列并占满宽度。面板使用标准小号按钮。链接框与复制按钮同为 28px 高,地址文字垂直居中。窄卡片中的复制按钮位于链接框下方,占满卡片内容宽度。复制按钮保持固定文案,仅在写入剪贴板时禁用。过期 banner 位于二维码卡片标题栏下方,占满卡片内容宽度。倒计时居中位于二维码下方,并在凭据告警上方增加 16px 下边距。重新生成正在显示的二维码时,仅用加载状态替换二维码图像;倒计时、告警和链接操作保持原位。取消后直接收起二维码预览,按钮恢复为**生成二维码**,不显示成功提示。
|
||||
Web bundle 挂载此插件。Host 端依赖 `connection`、`connection.authentication`、`credentials`、`webServer` 和 `webApp`,Client 端通过 `settings.section` 在浏览器设置中提供面板。Desktop 窗口隐藏此入口。移除插件会移除页面、端点、待使用的邀请和 Remote Peer。已签发的 Remote cookie 需要该提供者处于活动状态;插件使用同一凭据记录重新加载后,有效 cookie 可以继续使用。设置面板支持产品提供的全部八种界面语言;匿名登录页支持英文和中文。两张卡片的标题均位于边框内。页面标题和说明文字采用与模型设置页一致的字体和间距。宽卡片中的二维码操作与标题同行,窄卡片中则在标题下方纵向排列并占满宽度。面板使用标准小号按钮。链接框与复制按钮同为 28px 高,地址文字垂直居中。窄卡片中的复制按钮位于链接框下方,占满卡片内容宽度。复制按钮保持固定文案,仅在写入剪贴板时禁用。过期 banner 位于二维码卡片标题栏下方,占满卡片内容宽度。倒计时居中位于二维码下方,并在凭据告警上方增加 16px 下边距。重新生成正在显示的二维码时,仅用加载状态替换二维码图像;倒计时、告警和链接操作保持原位。取消后直接收起二维码预览,按钮恢复为**生成二维码**,不显示成功提示。
|
||||
|
||||
二维码登录使用公布的应用 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,不显示凭据告警,并隐藏二维码登录。配对审批仍可使用。二维码登录不可用时,部署信息的读取错误和重试操作保留在访问地址卡片中。重连后会重新检查地址前提。
|
||||
面板在卡片上方以共用提示说明尚未满足的地址前提。使用 `127.0.0.1` 等受信任的回环地址时,如果 Token 提供者发布了登录链接,访问地址卡片会显示该链接。owner 可以复制链接,在同一台电脑的另一个浏览器中登录。其他设备无法访问这个回环地址,因此面板会隐藏二维码登录。通配地址和不受信任的地址只显示不带凭据的 URL。配对审批仍可使用。二维码登录不可用时,部署信息的读取错误和重试操作保留在访问地址卡片中。重连后会重新检查地址前提。
|
||||
|
||||
`cookieMaxAgeDays` 默认为 30,固定每份 Remote cookie 的绝对有效期。`ticketLifetimeMs` 默认为 120000。`pollIntervalMs` 默认为 1000,控制设置面板显示二维码时的状态检查间隔。每个插件实例同一时间只有一个待使用邀请:生成新邀请会替换旧邀请,取消旧邀请不会取消替代它的新邀请。
|
||||
|
||||
@@ -40,7 +40,7 @@ Web bundle 挂载此插件。Host 端依赖 `connection`、`connection.authentic
|
||||
|
||||
只有已认证的 owner 可以创建、查询或取消邀请。Host 保留凭据摘要,不保留可重复使用的明文。公开页面不包含已认证应用的初始化注入,也不会向第三方发送凭据。二维码兑换失败时保留普通登录页及已配置的 Token 表单,并用本地化 banner 说明失败原因。兑换中断时 cookie 可能已经签发;banner 提供干净的应用链接以检查未知结果,不会自动重试一次性凭据。
|
||||
|
||||
仅供 owner 调用的 `loginUrl()` 读取同一 WebServer 实例通过 `webserver/entry-url` 发布的 Token 入口,返回公布的根地址,并在 `?token=…` 中携带其进程启动 token。未启用 Token 认证的 Host 无法提供此链接,二维码登录仍可使用。与二维码邀请不同,此链接可以重复使用,直到 Host 进程重启。复制链接不会创建、消费或替换二维码邀请。Client 仅在确认部署可用后预取 URL,在插件内存中保留,以右侧渐隐方式显示,并在重连时刷新。开始读取凭据时会清除先前的复制反馈。凭据 URL 变化或用户离开远程连接设置页(包括关闭设置面板)时,会重置凭据告警。离开后才完成的剪贴板写入仍通过全局 toast 报告结果,但不会在下次进入时恢复告警。凭据 URL 正在加载或不可用时,复制使用显示的干净地址,不显示链接读取错误或重试按钮;二维码生成仍独立可用。只有成功复制当前凭据 URL 后才显示其凭据告警,复制干净地址不会触发该告警。剪贴板拒绝写入时报告失败,并保留再次复制的能力。链接读取结果和复制结果均不持久保存或写入日志。
|
||||
仅供 owner 调用的 `loginUrl()` 读取同一 WebServer 实例通过 `webserver/entry-url` 发布的 Token 入口,返回公布的根地址,并在 `?token=…` 中携带其进程启动 token。未启用 Token 认证的 Host 无法提供此链接,二维码登录仍可使用。与二维码邀请不同,此链接可以重复使用,直到 Host 进程重启。复制链接不会创建、消费或替换二维码邀请。Client 仅在 Host 允许为公布的地址读取 Token 登录链接后才预取 URL,在插件内存中保留,以右侧渐隐方式显示,并在重连时刷新。开始读取凭据时会清除先前的复制反馈。凭据 URL 变化或用户离开远程连接设置页(包括关闭设置面板)时,会重置凭据告警。离开后才完成的剪贴板写入仍通过全局 toast 报告结果,但不会在下次进入时恢复告警。凭据 URL 正在加载或不可用时,复制使用显示的干净地址,不显示链接读取错误或重试按钮;二维码生成仍独立可用。只有成功复制当前凭据 URL 后才显示其凭据告警,复制干净地址不会触发该告警。剪贴板拒绝写入时报告失败,并保留再次复制的能力。链接读取结果和复制结果均不持久保存或写入日志。
|
||||
|
||||
Remote 拥有持久的 `client-remote-connection/browser-session` 凭据记录。其签名密钥和 v1 cookie 格式独立于 Token;cookie 绑定监听协议与规范化 Host,携带固定签发及到期时间,并使用 `HttpOnly`、`SameSite=Strict` 和 `Path=/`。验证不续期。记录损坏会使插件激活失败,不会替换密钥。保留此记录可让有效登录跨重启继续使用;替换或删除记录会在下次激活时使旧 cookie 失效。
|
||||
|
||||
|
||||
@@ -211,6 +211,11 @@
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.warningList {
|
||||
padding-inline-start: 1.5em;
|
||||
list-style-type: decimal;
|
||||
}
|
||||
|
||||
.cautionTitle {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
|
||||
@@ -36,9 +36,15 @@ function ConnectionNotice({ t, useRemoteConnection }: Pick<RemoteConnectionSecti
|
||||
const deployment = useRemoteConnection(state => state.deployment)
|
||||
if (deployment === null) return null
|
||||
if (deployment.availability === 'available') return <p className={css.intro}>{t('addressDescription')}</p>
|
||||
const [message, ...steps] = t(deployment.availability).split('\n')
|
||||
return <div className={css.caution} role="status">
|
||||
<span className={css.cautionIcon} aria-hidden="true"><IconWarningOutlineMedium /></span>
|
||||
<div className={css.cautionBody}><p className={css.warning}>{t(deployment.availability)}</p></div>
|
||||
<div className={css.cautionBody}>
|
||||
<p className={css.warning}>{message}</p>
|
||||
{steps.length > 0 && <ol className={`${css.warning} ${css.warningList}`}>
|
||||
{steps.map(step => <li key={step}>{step}</li>)}
|
||||
</ol>}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -94,25 +100,25 @@ function AccessAddressCard({ t, useRemoteConnection, useLoginLink, copyLink, rel
|
||||
const deployment = useRemoteConnection(state => state.deployment)
|
||||
const error = useRemoteConnection(state => state.error)
|
||||
const link = useLoginLink(state => state)
|
||||
const available = deployment?.availability === 'available'
|
||||
const credentialUrl = deployment?.loginUrlAllowed ? link.url : null
|
||||
const http = deployment?.url.startsWith('http:') === true
|
||||
return <section className={css.card} aria-label={t('addressTitle')}>
|
||||
<header className={css.header}>
|
||||
<h3 className={css.methodTitle}>{t('addressTitle')}</h3>
|
||||
</header>
|
||||
{!available && error !== null && <>
|
||||
{deployment?.availability !== 'available' && error !== null && <>
|
||||
<p className={css.error} role="alert">{t(error)}</p>
|
||||
<div className={css.actions}><Button variant="outline" size="sm" onClick={reload}>{t('retry')}</Button></div>
|
||||
</>}
|
||||
{deployment !== null && <div className={css.linkRow}>
|
||||
<div className={css.linkPreview}>
|
||||
<code className={css.linkUrl}>{(available ? link.url : null) ?? deployment.url}</code>
|
||||
<code className={css.linkUrl}>{credentialUrl ?? deployment.url}</code>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" disabled={link.phase === 'copying'} onClick={copyLink}>
|
||||
{t('copyLink')}
|
||||
</Button>
|
||||
</div>}
|
||||
{available && link.url !== null && link.copied && <CredentialWarning t={t} http={http} method="link" />}
|
||||
{credentialUrl !== null && link.copied && <CredentialWarning t={t} http={http} method="link" />}
|
||||
</section>
|
||||
}
|
||||
|
||||
|
||||
@@ -32,19 +32,21 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
export const inject = ['slots', 'locale', 'remote', 'remoteAccess', 'resources']
|
||||
|
||||
/**
|
||||
* Register the section and own its polling until plugin disposal.
|
||||
* Mount the Remote and register the browser settings section and polling.
|
||||
* @param ctx - Browser context providing the settings slot and authenticated Remote.
|
||||
* @returns After the generated service and section are registered.
|
||||
* @returns After the generated service and any browser settings registrations are ready.
|
||||
*/
|
||||
export async function apply(ctx: Context): Promise<void> {
|
||||
await ctx.remote.$mount(remoteConnectionRemote)
|
||||
if ('dshDesktop' in globalThis) return
|
||||
ctx.effect(() => ctx.locale.register('remoteConnection', { en, zh, ja, es, fr, de, ru, pt }), 'remote-connection: dictionaries')
|
||||
const t = ctx.locale.bind('remoteConnection')
|
||||
ctx.inject(['remote.remoteConnection'], (scope) => {
|
||||
const controller = new RemoteConnectionController(scope.remote.remoteConnection)
|
||||
let loginAddress: string | null = null
|
||||
const link = new LoginLinkController(scope.remote.remoteConnection, writeClipboard,
|
||||
() => controller.store.getSnapshot().deployment?.url ?? null,
|
||||
() => controller.store.getSnapshot().deployment?.availability === 'available')
|
||||
() => loginAddress !== null)
|
||||
const pairing = requestsResource(scope.remote.remoteConnection)
|
||||
const approval = new PairingApproval(scope.remote.remoteConnection, id => pairing.confirmed(id))
|
||||
const pairingFace = (): PairingInjected => ({
|
||||
@@ -61,17 +63,15 @@ export async function apply(ctx: Context): Promise<void> {
|
||||
}
|
||||
scope.effect(() => () => controller.dispose(), 'remote-connection: invitation lifetime')
|
||||
scope.effect(() => () => link.dispose(), 'remote-connection: login link')
|
||||
let linkAvailable = false
|
||||
scope.effect(() => controller.store.subscribe(() => {
|
||||
const available = controller.store.getSnapshot().deployment?.availability === 'available'
|
||||
if (available === linkAvailable) return
|
||||
linkAvailable = available
|
||||
if (available) void link.refresh()
|
||||
}), 'remote-connection: link availability')
|
||||
scope.on('connection/reset', () => {
|
||||
if (linkAvailable) void link.refresh()
|
||||
void controller.load()
|
||||
})
|
||||
const deployment = controller.store.getSnapshot().deployment
|
||||
const address = deployment?.loginUrlAllowed ? deployment.url : null
|
||||
if (address === loginAddress) return
|
||||
loginAddress = address
|
||||
link.invalidate()
|
||||
if (address !== null) void link.load()
|
||||
}), 'remote-connection: login address')
|
||||
scope.on('connection/reset', () => { void controller.reconnect() })
|
||||
scope.slots.inject('settings.section', () => scope.slots.register({
|
||||
name: 'settings.section', id: 'remote-connection', order: 25,
|
||||
label: () => t('title'),
|
||||
|
||||
@@ -28,6 +28,7 @@ export const en = {
|
||||
loading: 'Loading remote connection',
|
||||
creating: 'Creating login code',
|
||||
cancelling: 'Cancelling login code',
|
||||
/** Additional lines in this notice appear as numbered steps. */
|
||||
'unreachable-host': 'This address cannot be used to sign in from another device; configure a reachable address, such as a LAN address or an already configured public or VPN address.',
|
||||
'untrusted-host': 'Allow this address in the Host’s trusted hosts before using either login method.',
|
||||
loadFailed: 'Could not load remote connection settings. Try again.',
|
||||
@@ -66,7 +67,11 @@ export const zh: Record<RemoteConnectionLocaleKey, string> = {
|
||||
loading: '正在加载远程连接',
|
||||
creating: '正在生成登录二维码',
|
||||
cancelling: '正在取消登录二维码',
|
||||
'unreachable-host': '当前地址不能用于其他设备登录,请配置其他设备可访问的地址,例如能连通的局域网地址或已配置的公网、VPN 地址',
|
||||
'unreachable-host': [
|
||||
'当前地址无法用于跨设备登录。请用另一台设备能访问的地址重新启动服务。',
|
||||
'两台设备在同一局域网时,可用局域网 IP。',
|
||||
'通过 VPN 或公网访问时,可用已开通访问的 VPN 地址或公网 IP。',
|
||||
].join('\n'),
|
||||
'untrusted-host': '请先将此访问地址加入 Host 的可信主机配置,才能使用下方的登录方式',
|
||||
loadFailed: '无法加载远程连接设置,请重试',
|
||||
createFailed: '无法确认二维码是否生成,可能仍有有效二维码;生成新二维码会将其替换',
|
||||
|
||||
@@ -35,6 +35,7 @@ export class LoginLinkController {
|
||||
private live = true
|
||||
private loading: Promise<void> | undefined
|
||||
private copying: Promise<void> | undefined
|
||||
private readGeneration = 0
|
||||
private warningGeneration = 0
|
||||
private readonly pending = new Set<Promise<void>>()
|
||||
|
||||
@@ -71,23 +72,29 @@ export class LoginLinkController {
|
||||
* @returns after the read settles; duplicate reads share it, and a refresh waits for a clipboard write.
|
||||
*/
|
||||
load(): Promise<void> {
|
||||
if (!this.live) return Promise.resolve()
|
||||
if (!this.live || !this.canCopyCredential()) return Promise.resolve()
|
||||
if (this.copying !== undefined) return this.track(this.copying.then(() => this.load()))
|
||||
if (this.loading !== undefined) return this.loading
|
||||
const previousUrl = this.store.getSnapshot().url
|
||||
this.store.update((state) => { state.phase = 'loading'; state.url = null; state.notice = null })
|
||||
this.loading = this.track(this.read(previousUrl).finally(() => { this.loading = undefined }))
|
||||
const generation = this.readGeneration
|
||||
this.loading = this.track(this.read(previousUrl, generation).finally(() => {
|
||||
if (this.readGeneration === generation) this.loading = undefined
|
||||
}))
|
||||
return this.loading
|
||||
}
|
||||
|
||||
/**
|
||||
* Read again after an in-flight operation so a connection reset cannot reuse its old result.
|
||||
* @returns after the fresh read settles, or after disposal prevents the read.
|
||||
*/
|
||||
refresh(): Promise<void> {
|
||||
if (!this.live) return Promise.resolve()
|
||||
const operation = this.loading ?? this.copying
|
||||
return operation === undefined ? this.load() : this.track(operation.then(() => this.load()))
|
||||
/** Discard the previous deployment's credential and its outstanding read when the login address changes. */
|
||||
invalidate(): void {
|
||||
this.readGeneration += 1
|
||||
this.warningGeneration += 1
|
||||
this.loading = undefined
|
||||
this.store.update((state) => {
|
||||
state.url = null
|
||||
state.copied = false
|
||||
state.notice = null
|
||||
state.phase = this.copying === undefined ? 'ready' : 'copying'
|
||||
})
|
||||
}
|
||||
|
||||
/** Clear the page's credential warning without discarding clipboard outcomes or the cached URL. */
|
||||
@@ -142,17 +149,17 @@ export class LoginLinkController {
|
||||
})
|
||||
}
|
||||
|
||||
private async read(previousUrl: string | null): Promise<void> {
|
||||
private async read(previousUrl: string | null, generation: number): Promise<void> {
|
||||
try {
|
||||
const result = await this.remote.loginUrl()
|
||||
if (!this.live) return
|
||||
if (!this.live || this.readGeneration !== generation) return
|
||||
this.store.update((state) => {
|
||||
state.url = result.ok ? result.value : null
|
||||
state.phase = this.copying !== undefined ? 'copying' : result.ok ? 'ready' : 'error'
|
||||
if (state.url !== previousUrl) state.copied = false
|
||||
})
|
||||
} catch (_requestFailure) {
|
||||
if (this.live) this.store.update((state) => {
|
||||
if (this.live && this.readGeneration === generation) this.store.update((state) => {
|
||||
state.phase = this.copying !== undefined ? 'copying' : 'error'
|
||||
state.copied = false
|
||||
})
|
||||
|
||||
@@ -64,6 +64,16 @@ export class RemoteConnectionController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Withdraw the old connection's login address until the Host confirms its deployment again.
|
||||
* @returns after any outstanding QR gesture settles and the status read completes.
|
||||
*/
|
||||
async reconnect(): Promise<void> {
|
||||
this.store.update((state) => { state.deployment = null })
|
||||
if (this.busy()) await Promise.all(this.pending)
|
||||
await this.load()
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh deployment availability and, when retained, the current invitation.
|
||||
* @returns After the read settles or immediately when another gesture owns the panel.
|
||||
|
||||
@@ -222,8 +222,7 @@ export default class RemoteConnection extends TypertRemoteService {
|
||||
@Remote
|
||||
create(): RemoteLoginTicket {
|
||||
this.requireOwner()
|
||||
const deployment = this.availableDeployment()
|
||||
return this.tickets.create(deployment.url, this.config.ticketLifetimeMs)
|
||||
return this.tickets.create(this.loginBaseUrl('qr'), this.config.ticketLifetimeMs)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -233,7 +232,7 @@ export default class RemoteConnection extends TypertRemoteService {
|
||||
@Remote
|
||||
loginUrl(): string {
|
||||
this.requireOwner()
|
||||
const url = this.tokenLoginUrl(this.availableDeployment().url)
|
||||
const url = this.tokenLoginUrl(this.loginBaseUrl('token'))
|
||||
if (url === undefined) throw new RemoteError('remote-connection/token-unavailable', 'Token login is not enabled for this Host.', {})
|
||||
return url
|
||||
}
|
||||
@@ -283,30 +282,30 @@ export default class RemoteConnection extends TypertRemoteService {
|
||||
if (this.stopped) throw new RemoteError('remote-connection/disposed', 'Remote login is no longer available.', {})
|
||||
}
|
||||
|
||||
private availableDeployment(): Pick<RemoteConnectionStatus, 'url' | 'availability'> {
|
||||
private loginBaseUrl(method: 'qr' | 'token'): string {
|
||||
const deployment = this.deployment()
|
||||
if (deployment.availability !== 'available') {
|
||||
if (deployment.availability !== 'available' && (method === 'qr' || !deployment.loginUrlAllowed)) {
|
||||
throw new RemoteError('remote-connection/unavailable', 'Configure a reachable, trusted URL before signing in remotely.', {
|
||||
reason: deployment.availability,
|
||||
})
|
||||
}
|
||||
return deployment
|
||||
return deployment.url
|
||||
}
|
||||
|
||||
private deployment(): Pick<RemoteConnectionStatus, 'url' | 'availability'> {
|
||||
private deployment(): Pick<RemoteConnectionStatus, 'url' | 'availability' | 'loginUrlAllowed'> {
|
||||
const url = this.ctx.webApp.getAdvertisedUrl()
|
||||
const root = new URL(url)
|
||||
const hostname = root.hostname
|
||||
if (hostname === 'localhost' || hostname.endsWith('.localhost') || hostname === '[::1]'
|
||||
|| hostname === '[::]' || hostname === '0.0.0.0' || (hostname.startsWith('127.') && isIPv4(hostname))) {
|
||||
return { url, availability: 'unreachable-host' }
|
||||
if (hostname.endsWith('.localhost') || hostname === '[::]' || hostname === '0.0.0.0') {
|
||||
return { url, availability: 'unreachable-host', loginUrlAllowed: false }
|
||||
}
|
||||
const admission = this.owner.bail(this.owner.webServer, 'webserver/authorize', {
|
||||
headers: { host: root.host, origin: root.origin }, method: 'GET', url: root, transport: 'http',
|
||||
}, 'anonymous')
|
||||
if (admission?.kind === 'deny') {
|
||||
return { url, availability: 'untrusted-host' }
|
||||
const loginUrlAllowed = admission?.kind === 'allow'
|
||||
if (hostname === 'localhost' || hostname === '[::1]' || (hostname.startsWith('127.') && isIPv4(hostname))) {
|
||||
return { url, availability: 'unreachable-host', loginUrlAllowed }
|
||||
}
|
||||
return { url, availability: 'available' }
|
||||
return { url, availability: loginUrlAllowed ? 'available' : 'untrusted-host', loginUrlAllowed }
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,10 @@ export type RemoteLoginState = 'none' | 'pending' | 'used' | 'expired' | 'cancel
|
||||
export interface RemoteConnectionStatus {
|
||||
/** Clean advertised application URL. */
|
||||
readonly url: string
|
||||
/** Whether the advertised URL accepts remote browser requests. */
|
||||
/** Whether the advertised URL is reachable and trusted for QR login. */
|
||||
readonly availability: 'available' | RemoteConnectionUnavailable
|
||||
/** Whether the owner may request a login link from the Host's optional Token provider for this address. */
|
||||
readonly loginUrlAllowed: boolean
|
||||
/** State of the requested invitation, or none when no identifier was supplied. */
|
||||
readonly ticket: RemoteLoginState
|
||||
/** Interval between settings-panel status reads, in milliseconds. */
|
||||
|
||||
@@ -132,8 +132,19 @@ async function bench(call: ConnectionHandle['rpc']['call'], beforeMount?: (ctx:
|
||||
}
|
||||
|
||||
describe('remote connection settings registration', () => {
|
||||
it('keeps the Remote mounted without registering settings or polling in Desktop', async () => {
|
||||
vi.stubGlobal('dshDesktop', { protocolVersion: 1 })
|
||||
onTestFinished(() => { vi.unstubAllGlobals() })
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>()
|
||||
const { ctx, slots } = await bench(call)
|
||||
expect(slots.entries('settings.section')).toHaveLength(0)
|
||||
expect(slots.entries('shell.overlay')).toHaveLength(0)
|
||||
expect(call).not.toHaveBeenCalled()
|
||||
expect(ctx.get('remote.remoteConnection')).toBeDefined()
|
||||
})
|
||||
|
||||
it('keeps one navigation entry and replaces QR, link login, and pairing approvals together', async () => {
|
||||
const status = { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 }
|
||||
const status = { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 }
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
|
||||
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 1000 }
|
||||
: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private' : status,
|
||||
@@ -163,7 +174,7 @@ describe('remote connection settings registration', () => {
|
||||
|
||||
it('registers localized content and removes the section and generated namespace when unloaded', async () => {
|
||||
const status = 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 } }))
|
||||
? 'https://host.example/?token=private' : { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 } }))
|
||||
const { ctx, slots, locale, fiber } = await bench(status)
|
||||
await vi.waitFor(() => { expect(status).toHaveBeenCalledWith('/api', 'remoteConnection/status', { args: { id: null } }, expect.any(AbortSignal)) })
|
||||
const entry = slots.entries('settings.section')[0]!
|
||||
@@ -210,7 +221,7 @@ describe('remote connection settings registration', () => {
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => {
|
||||
if (endpoint === 'remoteConnection/status') await response.promise
|
||||
return { ok: true, value: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
|
||||
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 } }
|
||||
: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 } }
|
||||
})
|
||||
let ctx: Context | undefined
|
||||
try {
|
||||
@@ -234,7 +245,7 @@ describe('remote connection settings registration', () => {
|
||||
const requestSignals: AbortSignal[] = []
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation((_channel, endpoint, _data, signal) => {
|
||||
if (pendingEndpoint === 'loginUrl' && endpoint === 'remoteConnection/status') {
|
||||
return Promise.resolve({ ok: true, value: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 } })
|
||||
return Promise.resolve({ ok: true, value: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 } })
|
||||
}
|
||||
if (signal !== undefined) requestSignals.push(signal)
|
||||
return new Promise<never>((_resolve, reject) => {
|
||||
@@ -259,7 +270,7 @@ describe('remote connection settings registration', () => {
|
||||
return { ok: true, value: { id: 'extension-invitation', url: 'https://host.example/?login=qr#private', lifetimeMs: 120_000 } }
|
||||
}
|
||||
if (endpoint === 'remoteConnection/cancel') return { ok: true, value: 'cancelled' }
|
||||
return { ok: true, value: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 60_000 } }
|
||||
return { ok: true, value: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 60_000 } }
|
||||
})
|
||||
const { ctx, slots, close } = await bench(call)
|
||||
render(slots.renderSlot('root', {}))
|
||||
@@ -304,7 +315,7 @@ describe('remote connection settings registration', () => {
|
||||
it('shares an existing invitation with replacement content and restores its remaining lifetime on unload', async () => {
|
||||
const clock = vi.spyOn(performance, 'now').mockReturnValue(1000)
|
||||
onTestFinished(() => { clock.mockRestore() })
|
||||
const status = { url: 'https://host.example/', availability: 'available', ticket: 'pending', pollIntervalMs: 60_000 }
|
||||
const status = { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'pending', pollIntervalMs: 60_000 }
|
||||
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' }
|
||||
@@ -354,7 +365,7 @@ describe('remote connection settings registration', () => {
|
||||
return { ok: true, value: { id: 'invitation-b', url: 'https://host.example/?login=qr#private', lifetimeMs: 120_000 } }
|
||||
}
|
||||
if (endpoint === 'remoteConnection/cancel') return { ok: true, value: 'cancelled' }
|
||||
return { ok: true, value: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 60_000 } }
|
||||
return { ok: true, value: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 60_000 } }
|
||||
})
|
||||
const { ctx, slots, fiber } = await bench(call, async (ctx) => {
|
||||
await ctx.plugin(replacementPlugin).await()
|
||||
@@ -401,7 +412,7 @@ describe('remote connection settings registration', () => {
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
|
||||
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
|
||||
: endpoint === 'remoteConnection/loginUrl' ? url
|
||||
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
|
||||
: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 },
|
||||
}))
|
||||
const { ctx, slots } = await bench(call)
|
||||
render(slots.renderSlot('root', {}))
|
||||
@@ -427,7 +438,7 @@ describe('remote connection settings registration', () => {
|
||||
call.mockImplementation(async (_channel, endpoint) => ({
|
||||
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
|
||||
: endpoint === 'remoteConnection/loginUrl' ? `${url}-new`
|
||||
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
|
||||
: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 },
|
||||
}))
|
||||
act(() => { ctx.emit('connection/reset') })
|
||||
await screen.findByText(`${url}-new`)
|
||||
@@ -460,7 +471,7 @@ describe('remote connection settings registration', () => {
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
|
||||
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
|
||||
: endpoint === 'remoteConnection/loginUrl' ? url
|
||||
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
|
||||
: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 },
|
||||
}))
|
||||
const { slots } = await bench(call)
|
||||
render(slots.renderSlot('root', {}))
|
||||
@@ -481,7 +492,7 @@ describe('remote connection settings registration', () => {
|
||||
expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('refreshes deployment on every reconnect and prefetches the login link once available', async () => {
|
||||
it('shows and copies a loopback login link, then drops it when the Host stops permitting it', async () => {
|
||||
const write = vi.fn<(text: string) => Promise<void>>().mockResolvedValue(undefined)
|
||||
const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: write } })
|
||||
@@ -489,11 +500,13 @@ describe('remote connection settings registration', () => {
|
||||
if (clipboardDescriptor === undefined) Reflect.deleteProperty(navigator, 'clipboard')
|
||||
else Object.defineProperty(navigator, 'clipboard', clipboardDescriptor)
|
||||
})
|
||||
let available = false
|
||||
let loginUrlAllowed = false
|
||||
const url = 'http://127.0.0.1:5432/'
|
||||
const link = `${url}?token=private`
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
|
||||
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
|
||||
: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
|
||||
: { url: 'https://host.example/', availability: available ? 'available' : 'untrusted-host', ticket: 'none', pollIntervalMs: 1000 },
|
||||
: endpoint === 'remoteConnection/loginUrl' ? link
|
||||
: { url, availability: loginUrlAllowed ? 'unreachable-host' : 'untrusted-host', loginUrlAllowed, ticket: 'none', pollIntervalMs: 1000 },
|
||||
}))
|
||||
const { ctx, slots } = await bench(call)
|
||||
await vi.waitFor(() => { expect(call).toHaveBeenCalledOnce() })
|
||||
@@ -503,29 +516,64 @@ describe('remote connection settings registration', () => {
|
||||
const face = slots.spec('settings.remoteConnection.content')!.inject
|
||||
await vi.waitFor(() => { expect(face.hooks.remoteConnection.getSnapshot().deployment?.availability).toBe('untrusted-host') })
|
||||
face.copyLink()
|
||||
await vi.waitFor(() => { expect(write).toHaveBeenCalledExactlyOnceWith('https://host.example/') })
|
||||
await vi.waitFor(() => { expect(write).toHaveBeenCalledExactlyOnceWith(url) })
|
||||
await vi.waitFor(() => { expect(face.hooks.loginLink.getSnapshot().notice).toBe('linkCopied') })
|
||||
expect(face.hooks.loginLink.getSnapshot().copied).toBe(false)
|
||||
available = true
|
||||
loginUrlAllowed = true
|
||||
act(() => { ctx.emit('connection/reset') })
|
||||
await vi.waitFor(() => { expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(1) })
|
||||
await vi.waitFor(() => { expect(face.hooks.loginLink.getSnapshot().url).toBe('https://host.example/?token=private') })
|
||||
available = false
|
||||
await vi.waitFor(() => { expect(face.hooks.loginLink.getSnapshot().url).toBe(link) })
|
||||
render(slots.renderSlot('root', {}))
|
||||
const address = within(screen.getByRole('region', { name: zh.addressTitle }))
|
||||
expect(address.getByText(link)).toBeTruthy()
|
||||
expect(screen.queryByRole('region', { name: zh.qrTitle })).toBeNull()
|
||||
fireEvent.click(address.getByRole('button', { name: zh.copyLink }))
|
||||
await screen.findByText(zh.linkWarning)
|
||||
expect(write).toHaveBeenLastCalledWith(link)
|
||||
loginUrlAllowed = false
|
||||
act(() => { ctx.emit('connection/reset') })
|
||||
await vi.waitFor(() => { expect(face.hooks.remoteConnection.getSnapshot().deployment?.availability).toBe('untrusted-host') })
|
||||
expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/status')).toHaveLength(4)
|
||||
await vi.waitFor(() => { expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(2) })
|
||||
act(() => { ctx.emit('connection/reset') })
|
||||
await vi.waitFor(() => { expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/status')).toHaveLength(5) })
|
||||
expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(2)
|
||||
expect(face.hooks.loginLink.getSnapshot().url).toBe('https://host.example/?token=private')
|
||||
await vi.waitFor(() => { expect(face.hooks.remoteConnection.getSnapshot().deployment?.loginUrlAllowed).toBe(false) })
|
||||
expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/status')).toHaveLength(5)
|
||||
expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(1)
|
||||
expect(face.hooks.loginLink.getSnapshot().url).toBeNull()
|
||||
expect(screen.queryByText(link)).toBeNull()
|
||||
expect(screen.queryByText(zh.linkWarning)).toBeNull()
|
||||
face.reloadLink()
|
||||
expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(1)
|
||||
face.copyLink()
|
||||
await vi.waitFor(() => { expect(write).toHaveBeenCalledTimes(2) })
|
||||
await vi.waitFor(() => { expect(write).toHaveBeenCalledTimes(3) })
|
||||
await vi.waitFor(() => { expect(face.hooks.loginLink.getSnapshot().notice).toBe('linkCopied') })
|
||||
expect(write).toHaveBeenLastCalledWith('https://host.example/')
|
||||
expect(write).toHaveBeenLastCalledWith(url)
|
||||
expect(face.hooks.loginLink.getSnapshot().copied).toBe(false)
|
||||
})
|
||||
|
||||
it('requests a new link when the advertised address changes between eligible addresses', async () => {
|
||||
const previous = 'https://host.example/'
|
||||
const local = 'http://127.0.0.1/'
|
||||
let address = previous
|
||||
const nextRead = Promise.withResolvers<string>()
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => {
|
||||
if (endpoint === 'remoteConnection/loginUrl') {
|
||||
return { ok: true, value: address === local ? await nextRead.promise : `${previous}?token=previous` }
|
||||
}
|
||||
return { ok: true, value: { url: address, availability: address === local ? 'unreachable-host' : 'available',
|
||||
loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 } }
|
||||
})
|
||||
const { slots } = await bench(call)
|
||||
onTestFinished(() => { nextRead.resolve(`${local}?token=local`) })
|
||||
const face = slots.spec('settings.remoteConnection.content')!.inject
|
||||
await vi.waitFor(() => { expect(face.hooks.loginLink.getSnapshot().url).toBe(`${previous}?token=previous`) })
|
||||
address = local
|
||||
face.reload()
|
||||
await vi.waitFor(() => { expect(face.hooks.remoteConnection.getSnapshot().deployment?.url).toBe(local) })
|
||||
expect(face.hooks.loginLink.getSnapshot().url).toBeNull()
|
||||
nextRead.resolve(`${local}?token=local`)
|
||||
await vi.waitFor(() => { expect(face.hooks.loginLink.getSnapshot().url).toBe(`${local}?token=local`) })
|
||||
})
|
||||
|
||||
it.each(['en', 'zh'] as const)('copies the clean address after a credential read fails and reports clipboard outcomes in %s', async (language) => {
|
||||
const copy = language === 'en' ? en : zh
|
||||
const write = vi.fn<(text: string) => Promise<void>>().mockRejectedValueOnce(new Error('clipboard permission')).mockResolvedValue(undefined)
|
||||
@@ -539,7 +587,7 @@ describe('remote connection settings registration', () => {
|
||||
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: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
|
||||
: { url, availability: 'available', ticket: 'none', pollIntervalMs: 1000 } }
|
||||
: { url, availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 } }
|
||||
})
|
||||
const { slots, locale } = await bench(call)
|
||||
locale.setLocale(language)
|
||||
@@ -579,7 +627,7 @@ describe('remote connection settings registration', () => {
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
|
||||
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
|
||||
: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
|
||||
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
|
||||
: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 },
|
||||
}))
|
||||
const { slots, fiber } = await bench(call)
|
||||
render(slots.renderSlot('root', {}))
|
||||
@@ -612,7 +660,7 @@ it('submits approval through the shared namespace and keeps its notice outside S
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
|
||||
ok: true, value: endpoint === 'remoteConnection/decidePairing' ? 'approved'
|
||||
: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
|
||||
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
|
||||
: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 },
|
||||
}))
|
||||
const { slots, fiber } = await bench(call)
|
||||
const face = approvalFace(slots)
|
||||
@@ -641,7 +689,7 @@ it('shares owner approval with appended options across panel replacement', async
|
||||
pollIntervalMs: 1000,
|
||||
} }
|
||||
return { ok: true, value: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
|
||||
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 } }
|
||||
: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 } }
|
||||
})
|
||||
const { ctx, slots, fiber } = await bench(call)
|
||||
const extension = ctx.plugin(pairingExtensionPlugin)
|
||||
@@ -674,7 +722,7 @@ it('shares owner approval with appended options across panel replacement', async
|
||||
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 },
|
||||
: { url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 },
|
||||
}))
|
||||
const { ctx, slots, fiber } = await bench(call, undefined, false)
|
||||
await ctx.plugin(pairingExtensionPlugin).await()
|
||||
@@ -696,7 +744,7 @@ it('aborts a pending pairing read and decision when the shared plugin unloads',
|
||||
const signals: AbortSignal[] = []
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint, _args, signal) => {
|
||||
if (endpoint === 'remoteConnection/status') return { ok: true, value: {
|
||||
url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000,
|
||||
url: 'https://host.example/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000,
|
||||
} }
|
||||
if (endpoint === 'remoteConnection/loginUrl') return { ok: true, value: 'https://host.example/?token=private' }
|
||||
if (signal === undefined) throw new Error('Missing lifetime signal')
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { RemoteConnectionStatus, RemoteLoginId, RemoteLoginTicket, RemoteLoginState } from '../src/types.ts'
|
||||
import { RemoteConnectionController, type RemoteConnectionApi } from '../src/client/remote-connection-controller.ts'
|
||||
|
||||
const deployment: RemoteConnectionStatus = { url: 'https://host.example/app/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 }
|
||||
const deployment: RemoteConnectionStatus = { url: 'https://host.example/app/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 }
|
||||
const ticket: RemoteLoginTicket = { id: 'invitation-a' as RemoteLoginId, url: 'https://host.example/app/?login=qr#token=private-a', lifetimeMs: 10_000 }
|
||||
const failure = { ok: false as const, error: new RemoteError('gateway/internal', 'unavailable', {}) }
|
||||
const controllers: RemoteConnectionController[] = []
|
||||
@@ -103,6 +103,22 @@ describe('Remote connection invitation state', () => {
|
||||
expect(state()).toMatchObject({ phase: 'pending', ticket: next, retainDetails: false, remainingSeconds: 20 })
|
||||
})
|
||||
|
||||
it('rechecks the login address after reconnecting during an outstanding QR creation', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
const creating = deferred<RemoteResult<RemoteLoginTicket>>()
|
||||
remote.create.mockReturnValueOnce(creating.promise)
|
||||
const creation = controller.create()
|
||||
const reconnect = controller.reconnect()
|
||||
expect(state().deployment).toBeNull()
|
||||
expect(remote.status).toHaveBeenCalledOnce()
|
||||
const loopback = { ...deployment, url: 'http://127.0.0.1/', availability: 'unreachable-host' as const }
|
||||
remote.status.mockResolvedValueOnce({ ok: true, value: loopback })
|
||||
creating.resolve({ ok: true, value: ticket })
|
||||
await Promise.all([creation, reconnect])
|
||||
expect(state()).toMatchObject({ deployment: loopback, ticket: null })
|
||||
})
|
||||
|
||||
it('expires the code even while a status request is stalled, and ignores its late answer', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
|
||||
@@ -96,11 +96,11 @@ it('copies the clean address directly before any credential has loaded', async (
|
||||
await controller.dispose()
|
||||
})
|
||||
|
||||
it.each(['rejection', 'refusal'] as const)('copies the clean address after credential-read %s', async (outcome) => {
|
||||
const address = 'https://host.example/app/'
|
||||
it.each(['rejection', 'missing Token provider'] as const)('copies the clean loopback address after credential-read %s', async (outcome) => {
|
||||
const address = 'http://127.0.0.1:5432/'
|
||||
const { remote, write, controller, state } = setup(() => address)
|
||||
if (outcome === 'rejection') remote.loginUrl.mockRejectedValueOnce(new Error('connection unavailable'))
|
||||
else remote.loginUrl.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'unavailable', {}) })
|
||||
else remote.loginUrl.mockResolvedValueOnce({ ok: false, error: new RemoteError('remote-connection/token-unavailable', 'Token login is disabled', {}) })
|
||||
await controller.load()
|
||||
expect(state()).toMatchObject({ phase: 'error', url: null, copied: false })
|
||||
const copying = controller.copy()
|
||||
@@ -173,6 +173,23 @@ it('does not attribute a plain-address copy to a credential that loads afterward
|
||||
expect(state()).toMatchObject({ phase: 'ready', url, copied: false, notice: 'linkCopied' })
|
||||
})
|
||||
|
||||
it('withdraws the old link before a pending clipboard write finishes on another deployment', async () => {
|
||||
const { remote, write, controller, state } = setup()
|
||||
await controller.load()
|
||||
const writing = Promise.withResolvers<boolean>()
|
||||
write.mockReturnValueOnce(writing.promise)
|
||||
const copying = controller.copy()
|
||||
controller.invalidate()
|
||||
expect(state()).toMatchObject({ url: null, copied: false, phase: 'copying' })
|
||||
const next = 'http://127.0.0.1/?token=local'
|
||||
remote.loginUrl.mockResolvedValueOnce({ ok: true, value: next })
|
||||
const loading = controller.load()
|
||||
writing.resolve(true)
|
||||
await Promise.all([copying, loading])
|
||||
expect(state()).toMatchObject({ url: next, copied: false })
|
||||
await controller.dispose()
|
||||
})
|
||||
|
||||
it('shares a copy reentered while its busy state is published', async () => {
|
||||
const { write, controller, state } = setup()
|
||||
await controller.load()
|
||||
@@ -251,7 +268,7 @@ it.each(['response', 'failure'] as const)('discards a login-link %s arriving aft
|
||||
await Promise.all([loading, disposal])
|
||||
expect(disposed).toBe(true)
|
||||
expect(state()).toMatchObject({ url: null, copied: false, notice: null })
|
||||
await controller.refresh()
|
||||
await controller.load()
|
||||
expect(remote.loginUrl).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
@@ -260,24 +277,26 @@ it('resets copy success for a changed URL and preserves it for the same URL', as
|
||||
await controller.load()
|
||||
await controller.copy()
|
||||
remote.loginUrl.mockResolvedValue({ ok: true, value: `${url}-new` })
|
||||
await controller.refresh()
|
||||
await controller.load()
|
||||
expect(state()).toMatchObject({ url: `${url}-new`, copied: false, notice: null })
|
||||
await controller.copy()
|
||||
await controller.refresh()
|
||||
await controller.load()
|
||||
expect(state()).toMatchObject({ url: `${url}-new`, copied: true, notice: null })
|
||||
await controller.dispose()
|
||||
})
|
||||
|
||||
it('reads the current connection after a reset overlaps an earlier read', async () => {
|
||||
it.each(['success', 'failure'] as const)('ignores a late credential %s after the deployment changes', async (outcome) => {
|
||||
const { remote, controller, state } = setup()
|
||||
let finish!: (result: Awaited<ReturnType<RemoteConnectionApi['loginUrl']>>) => void
|
||||
remote.loginUrl.mockReturnValueOnce(new Promise((resolve) => { finish = resolve }))
|
||||
const loading = controller.load()
|
||||
const refresh = controller.refresh()
|
||||
remote.loginUrl.mockResolvedValueOnce({ ok: true, value: `${url}-new` })
|
||||
finish({ ok: true, value: url })
|
||||
await Promise.all([loading, refresh])
|
||||
expect(remote.loginUrl).toHaveBeenCalledTimes(2)
|
||||
expect(state()).toMatchObject({ url: `${url}-new`, copied: false, notice: null })
|
||||
const previous = Promise.withResolvers<Awaited<ReturnType<RemoteConnectionApi['loginUrl']>>>()
|
||||
remote.loginUrl.mockReturnValueOnce(previous.promise)
|
||||
const oldRead = controller.load()
|
||||
controller.invalidate()
|
||||
const local = 'http://127.0.0.1/?token=local'
|
||||
remote.loginUrl.mockResolvedValueOnce({ ok: true, value: local })
|
||||
await controller.load()
|
||||
if (outcome === 'success') previous.resolve({ ok: true, value: url })
|
||||
else previous.reject(new Error('previous connection closed'))
|
||||
await oldRead
|
||||
expect(state()).toMatchObject({ url: local, phase: 'ready', copied: false })
|
||||
await controller.dispose()
|
||||
})
|
||||
@@ -107,7 +107,9 @@ async function exchange(route: WebRoute, token: string, headers?: Record<string,
|
||||
|
||||
it('issues a prefix-preserving one-use invitation and a Remote-owned browser cookie', async () => {
|
||||
const { ctx, route, service } = await mount()
|
||||
expect(service.status(null)).toEqual({ url: 'https://login.example/ui/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 })
|
||||
expect(service.status(null)).toEqual({
|
||||
url: 'https://login.example/ui/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000,
|
||||
})
|
||||
const ticket = service.create()
|
||||
expect(ticket.lifetimeMs).toBe(120_000)
|
||||
expect(ticket.url).toMatch(/^https:\/\/login\.example\/ui\/\?login=qr#[A-Za-z0-9_-]{43}$/)
|
||||
@@ -312,20 +314,41 @@ it('requires an owner even when a caller bypasses the generated Remote gateway',
|
||||
expect(service.status(ticket.id).ticket).toBe('pending')
|
||||
})
|
||||
|
||||
it.each(['http://127.0.0.1:4312/ui/', 'https://127.0.0.2/', 'https://localhost/', 'http://[::1]/'])(
|
||||
'offers the owner a local Token link at %s and keeps QR login unavailable', async (url) => {
|
||||
const { service } = await mount(url)
|
||||
expect(service.status(null)).toMatchObject({ url, availability: 'unreachable-host', loginUrlAllowed: true })
|
||||
const link = new URL(service.loginUrl())
|
||||
expect(link.searchParams.get('token')).toMatch(/^[A-Za-z0-9_-]{43}$/u)
|
||||
link.searchParams.delete('token')
|
||||
expect(link.href).toBe(url)
|
||||
expect(() => service.create()).toThrow(expect.objectContaining({ code: 'remote-connection/unavailable' }))
|
||||
},
|
||||
)
|
||||
|
||||
it('requires source admission before returning a loopback Token link', async () => {
|
||||
const { ctx, service } = await mount('http://127.0.0.1/')
|
||||
ctx.on('webserver/authorize', () => ({ kind: 'deny', status: 403 }), { prepend: true })
|
||||
expect(service.status(null).loginUrlAllowed).toBe(false)
|
||||
expect(() => service.loginUrl()).toThrow(expect.objectContaining({ code: 'remote-connection/unavailable' }))
|
||||
})
|
||||
|
||||
it('reports a missing Token provider for an admitted loopback address', async () => {
|
||||
const { service } = await mount('http://127.0.0.1/', 'http:', false)
|
||||
expect(service.status(null).loginUrlAllowed).toBe(true)
|
||||
expect(() => service.loginUrl()).toThrow(expect.objectContaining({ code: 'remote-connection/token-unavailable' }))
|
||||
})
|
||||
|
||||
it.each([
|
||||
['http://localhost/', 'unreachable-host'],
|
||||
['http://unknown.example/', 'untrusted-host'],
|
||||
['https://localhost/', 'unreachable-host'],
|
||||
['https://app.localhost/', 'unreachable-host'],
|
||||
['https://127.0.0.2/', 'unreachable-host'],
|
||||
['https://[::1]/', 'unreachable-host'],
|
||||
['https://[::]/', 'unreachable-host'],
|
||||
['https://0.0.0.0/', 'unreachable-host'],
|
||||
['https://unknown.example/', 'untrusted-host'],
|
||||
['https://127.unknown.example/', 'untrusted-host'],
|
||||
] as const)('reports the unmet prerequisite for %s', async (url, availability) => {
|
||||
const { service } = await mount(url)
|
||||
expect(service.status(null).availability).toBe(availability)
|
||||
expect(service.status(null)).toMatchObject({ availability, loginUrlAllowed: false })
|
||||
expect(() => service.create()).toThrow(expect.objectContaining({ code: 'remote-connection/unavailable', details: { reason: availability } }))
|
||||
expect(() => service.loginUrl()).toThrow(expect.objectContaining({ code: 'remote-connection/unavailable', details: { reason: availability } }))
|
||||
})
|
||||
|
||||
@@ -20,7 +20,7 @@ export default createTypertRemoteInfo({
|
||||
parameters: [{ name: 'id', source: 'json', codec: nullableId, strictCodec: nullableId }],
|
||||
result: codec(() => z.object({
|
||||
url: z.string(), availability: z.enum(['available', 'unreachable-host', 'untrusted-host']),
|
||||
ticket: invitationState(), pollIntervalMs: z.number(),
|
||||
loginUrlAllowed: z.boolean(), ticket: invitationState(), pollIntervalMs: z.number(),
|
||||
})),
|
||||
},
|
||||
'remoteConnection/create': {
|
||||
|
||||
@@ -17,7 +17,7 @@ import { PairingApproval } from '../src/client/pairing-approval.ts'
|
||||
afterEach(cleanup)
|
||||
|
||||
const ready: RemoteConnectionState = {
|
||||
deployment: { url: 'https://host.example/app/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
|
||||
deployment: { url: 'https://host.example/app/', availability: 'available', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 },
|
||||
phase: 'ready', ticket: null, error: null, remainingSeconds: 120, retainDetails: false,
|
||||
}
|
||||
const ticket = { id: 'code-a' as RemoteLoginId, url: 'https://host.example/app/?login=qr#token=private', lifetimeMs: 120_000 }
|
||||
@@ -114,12 +114,14 @@ describe('Remote connection section', () => {
|
||||
] 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 }, true)
|
||||
const deployment = { ...ready.deployment!, url, availability, loginUrlAllowed: false }
|
||||
const { copyLink } = panel({ deployment }, language, { copied: true }, true)
|
||||
const section = screen.getByRole('region', { name: copy.title })
|
||||
const notice = within(section).getByText(copy[availability])
|
||||
const message = copy[availability].split('\n')[0]!
|
||||
const notice = within(section).getByText(message)
|
||||
expect(notice.closest('[role="status"]')).not.toBeNull()
|
||||
for (const card of within(section).getAllByRole('region')) {
|
||||
expect(within(card).queryByText(copy[availability])).toBeNull()
|
||||
expect(within(card).queryByText(message)).toBeNull()
|
||||
expect(notice.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
||||
}
|
||||
const address = within(section).getByRole('region', { name: copy.addressTitle })
|
||||
@@ -249,7 +251,7 @@ describe('Remote connection section', () => {
|
||||
{ language: 'en', cached: true }, { language: 'zh', cached: true },
|
||||
] as const)('keeps a failed address read recoverable in $language (cached address: $cached)', ({ language, cached }) => {
|
||||
const copy = language === 'en' ? en : zh
|
||||
const deployment = cached ? { ...ready.deployment!, availability: 'untrusted-host' as const } : null
|
||||
const deployment = cached ? { ...ready.deployment!, availability: 'untrusted-host' as const, loginUrlAllowed: false } : null
|
||||
const { reload } = panel({ phase: 'error', deployment, error: 'loadFailed' }, language)
|
||||
const address = screen.getByRole('region', { name: copy.addressTitle })
|
||||
expect(within(address).getByRole('alert').textContent).toBe(copy.loadFailed)
|
||||
|
||||
@@ -9428,7 +9428,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
},
|
||||
{
|
||||
name: 'RemoteConnectionStatus',
|
||||
declaration: 'export interface RemoteConnectionStatus {\n readonly url: string;\n readonly availability: \'available\' | RemoteConnectionUnavailable;\n readonly ticket: RemoteLoginState;\n readonly pollIntervalMs: number;\n}',
|
||||
declaration: 'export interface RemoteConnectionStatus {\n readonly url: string;\n readonly availability: \'available\' | RemoteConnectionUnavailable;\n readonly loginUrlAllowed: boolean;\n readonly ticket: RemoteLoginState;\n readonly pollIntervalMs: number;\n}',
|
||||
},
|
||||
{
|
||||
name: 'RemoteConnectionUnavailable',
|
||||
|
||||
@@ -18,7 +18,8 @@ export const remoteDefaultResponses: RemoteTable = {
|
||||
// ui-settings `mirror.ensure()` at apply and again on `connection/reset`.
|
||||
'settings/describe': ok({ writable: true, hasDocument: false, namespaces: [] }),
|
||||
// remote-connection reads the advertised address when its settings section registers.
|
||||
'remoteConnection/status': ok({ url: 'http://localhost:3000/', availability: 'unreachable-host', ticket: 'none', pollIntervalMs: 1000 }),
|
||||
'remoteConnection/status': ok({ url: 'http://localhost:3000/', availability: 'unreachable-host', loginUrlAllowed: true, ticket: 'none', pollIntervalMs: 1000 }),
|
||||
'remoteConnection/loginUrl': { ok: false, error: { code: 'remote-connection/token-unavailable', message: 'Token login is not enabled for this Host.', details: {} } },
|
||||
// ui-model-selection `ModelDirectoryResolver` constructor.
|
||||
'session/modelCatalog': ok({
|
||||
default: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
|
||||
|
||||
Reference in new issue
Block a user