mirror of
https://ghproxy.cflmy.top/https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-11-28 08:09:35 +08:00
feat(remote-connection): own browser authentication through providers
This commit is contained in:
1 parent
608960ebfc
commit
3059225fd9
106 files changed
+6527
-129
No files matched your search
@@ -137,6 +137,7 @@ External packages installed for runtime use or embedded in distributed Host or b
|
||||
| [`papaparse`](https://github.com/mholt/PapaParse) | MIT |
|
||||
| [`pdfjs-dist`](https://github.com/mozilla/pdf.js) | Apache-2.0 |
|
||||
| [`picomatch`](https://github.com/micromatch/picomatch) | MIT |
|
||||
| [`qrcode.react`](https://github.com/zpao/qrcode.react) | ISC |
|
||||
| [`react`](https://github.com/facebook/react) | MIT |
|
||||
| [`react-dom`](https://github.com/facebook/react) | MIT |
|
||||
| [`readable-stream`](https://github.com/nodejs/readable-stream) | MIT |
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
- main:
|
||||
- region "连接到此 Host":
|
||||
- heading "连接到此 Host" [level=1]
|
||||
- paragraph: 登录以继续
|
||||
- text: 登录令牌或链接
|
||||
- textbox "登录令牌或链接"
|
||||
- paragraph: 登录令牌位于此 Host 启动时输出的 URL 中
|
||||
- button "继续"
|
||||
@@ -0,0 +1,8 @@
|
||||
- main:
|
||||
- region "连接到此 Host":
|
||||
- heading "连接到此 Host" [level=1]
|
||||
- paragraph: 登录以继续
|
||||
- text: 登录令牌或链接
|
||||
- textbox "登录令牌或链接" [invalid]: {{invalid-token}}
|
||||
- alert: 此登录令牌无效或已过期,请粘贴新的令牌后重试
|
||||
- button "继续"
|
||||
@@ -0,0 +1,19 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成新二维码"
|
||||
- button "取消二维码"
|
||||
- img "一次性登录二维码"
|
||||
- paragraph:
|
||||
- text: 扫码后直接登录
|
||||
- timer: {{seconds}} 秒后过期
|
||||
- paragraph: 请勿分享登录二维码
|
||||
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "已复制"
|
||||
- paragraph: 请勿公开分享登录链接
|
||||
- paragraph: 持有此链接的人都可以直接登录,请仅发送给自己的设备,勿公开分享;重启服务后链接失效
|
||||
@@ -0,0 +1,10 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成新二维码"
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制登录链接"
|
||||
@@ -0,0 +1,12 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成新二维码"
|
||||
- status:
|
||||
- paragraph: 二维码已过期,请生成新二维码登录
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制登录链接"
|
||||
@@ -0,0 +1,12 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成新二维码"
|
||||
- status:
|
||||
- paragraph: 二维码已过期,请生成新二维码登录
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制登录链接"
|
||||
@@ -0,0 +1,18 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- 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 "复制登录链接"
|
||||
@@ -0,0 +1,21 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- 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 "已复制"
|
||||
- paragraph: 请勿公开分享登录链接
|
||||
- paragraph: 持有此链接的人都可以直接登录,请仅发送给自己的设备,勿公开分享;重启服务后链接失效
|
||||
- paragraph: HTTP 会明文传输登录凭据,请仅在可信网络中使用
|
||||
@@ -0,0 +1,10 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成登录二维码"
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制登录链接"
|
||||
@@ -0,0 +1,12 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成登录二维码"
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "已复制"
|
||||
- paragraph: 请勿公开分享登录链接
|
||||
- paragraph: 持有此链接的人都可以直接登录,请仅发送给自己的设备,勿公开分享;重启服务后链接失效
|
||||
@@ -0,0 +1,11 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成登录二维码"
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}
|
||||
- button "重试"
|
||||
- alert: 无法获取登录链接,请重试
|
||||
@@ -0,0 +1,12 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成登录二维码"
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "已复制"
|
||||
- paragraph: 请勿公开分享登录链接
|
||||
- paragraph: 持有此链接的人都可以直接登录,请仅发送给自己的设备,勿公开分享;重启服务后链接失效
|
||||
@@ -0,0 +1,12 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成登录二维码"
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "已复制"
|
||||
- paragraph: 请勿公开分享登录链接
|
||||
- paragraph: 持有此链接的人都可以直接登录,请仅发送给自己的设备,勿公开分享;重启服务后链接失效
|
||||
@@ -0,0 +1,10 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成登录二维码"
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制登录链接"
|
||||
@@ -0,0 +1,17 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成新二维码"
|
||||
- button "取消二维码"
|
||||
- img "一次性登录二维码"
|
||||
- paragraph:
|
||||
- text: 扫码后直接登录
|
||||
- timer: {{seconds}} 秒后过期
|
||||
- paragraph: 请勿分享登录二维码
|
||||
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制登录链接"
|
||||
@@ -0,0 +1,17 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成新二维码"
|
||||
- button "取消二维码"
|
||||
- img "一次性登录二维码"
|
||||
- paragraph:
|
||||
- text: 扫码后直接登录
|
||||
- timer: {{seconds}} 秒后过期
|
||||
- paragraph: 请勿分享登录二维码
|
||||
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制登录链接"
|
||||
@@ -0,0 +1,17 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成新二维码" [disabled]
|
||||
- button "取消二维码" [disabled]
|
||||
- status "正在生成登录二维码"
|
||||
- paragraph:
|
||||
- text: 扫码后直接登录
|
||||
- timer: {{seconds}} 秒后过期
|
||||
- paragraph: 请勿分享登录二维码
|
||||
- paragraph: 二维码使用或过期前,持有它的人都可以登录,请勿传播
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制登录链接"
|
||||
@@ -0,0 +1,9 @@
|
||||
- region "自定义远程连接":
|
||||
- heading "自定义远程连接" [level=2]
|
||||
- code: {{access-address}}
|
||||
- status: "邀请状态: pending"
|
||||
- status "邀请编号": {{invitation-id}}
|
||||
- button "生成新邀请"
|
||||
- button "取消邀请"
|
||||
- button "重新读取"
|
||||
- button "关闭设置"
|
||||
@@ -0,0 +1,11 @@
|
||||
- region "远程连接":
|
||||
- heading "远程连接" [level=2]
|
||||
- region "二维码登录":
|
||||
- heading "二维码登录" [level=3]
|
||||
- button "生成新二维码"
|
||||
- status: 二维码已使用,请在手机上确认是否已登录
|
||||
- region "链接登录":
|
||||
- heading "链接登录" [level=3]
|
||||
- paragraph: 复制登录链接,在另一台设备的浏览器中打开
|
||||
- code: {{access-address}}?token={{login-token}}
|
||||
- button "复制登录链接"
|
||||
@@ -0,0 +1,38 @@
|
||||
/** External panel using only its declared Slot props and shared React module. */
|
||||
window.__ModuleLoader__.load({
|
||||
id: '@fixture/remote-connection',
|
||||
factory(require) {
|
||||
const { createElement: h } = require('react')
|
||||
return {
|
||||
inject: ['slots', 'locale'],
|
||||
apply(ctx) {
|
||||
ctx.effect(() => ctx.locale.register('fixtureRemoteConnection', {
|
||||
zh: {
|
||||
title: '自定义远程连接', invitation: '邀请编号', phase: '邀请状态',
|
||||
create: '生成新邀请', cancel: '取消邀请', reload: '重新读取', close: '关闭设置',
|
||||
},
|
||||
en: {
|
||||
title: 'Custom remote connection', invitation: 'Invitation ID', phase: 'Invitation state',
|
||||
create: 'Create invitation', cancel: 'Cancel invitation', reload: 'Reload', close: 'Close settings',
|
||||
},
|
||||
}))
|
||||
ctx.slots.inject('settings.remoteConnection.content', () => ctx.slots.register({
|
||||
name: 'settings.remoteConnection.content', priority: -1, locale: 'fixtureRemoteConnection',
|
||||
}, ({ t, useRemoteConnection, create, cancel, reload, close }) => {
|
||||
const { deployment, phase, ticket } = useRemoteConnection(state => state)
|
||||
const busy = phase === 'creating' || phase === 'cancelling'
|
||||
return h('section', { 'aria-label': t('title') },
|
||||
h('h2', null, t('title')),
|
||||
deployment === null ? null : h('code', null, deployment.url),
|
||||
h('p', { role: 'status' }, `${t('phase')}: ${phase}`),
|
||||
h('output', { 'aria-label': t('invitation') }, ticket?.id ?? ''),
|
||||
h('button', { type: 'button', disabled: busy, onClick: create }, t('create')),
|
||||
h('button', { type: 'button', disabled: busy || ticket === null, onClick: cancel }, t('cancel')),
|
||||
h('button', { type: 'button', disabled: busy, onClick: reload }, t('reload')),
|
||||
h('button', { type: 'button', onClick: close }, t('close')),
|
||||
)
|
||||
}))
|
||||
},
|
||||
}
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,3 @@
|
||||
- insert:
|
||||
- id: fixture-remote-connection
|
||||
name: '@fixture/remote-connection'
|
||||
@@ -0,0 +1,2 @@
|
||||
/** Host companion for a replacement Remote connection settings panel. */
|
||||
export function apply() {}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"name": "@fixture/remote-connection",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"exports": { ".": "./index.js", "./client": "./client.js" },
|
||||
"dsh": {
|
||||
"bundle": { "patch": "./cordis.patch.yml" },
|
||||
"client": { "platform": "web" }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
/** Isolated built Web profile with an OS-allocated listener and disposable TLS material. */
|
||||
import { spawn, type ChildProcess } from 'node:child_process'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { materializeTlsFixture } from '../../../packages/host/webserver/tests/tls-fixture.ts'
|
||||
import { REPO_ROOT } from './support.ts'
|
||||
|
||||
/** One real CLI process, including its private persistence and certificate directory. */
|
||||
export interface RemoteConnectionFixture {
|
||||
/** Token provider's published startup URL, independent of Remote-issued credentials. */
|
||||
readonly authenticatedUrl: string
|
||||
/** Advertised clean root shared with the new mobile browser. */
|
||||
readonly url: string
|
||||
/** Private working directory; no user workspace or credentials are read. */
|
||||
readonly root: string
|
||||
/** Stop the CLI, await its exit, then remove all owned files. */
|
||||
close(): Promise<void>
|
||||
}
|
||||
|
||||
async function stop(child: ChildProcess, closed: Promise<void>): Promise<void> {
|
||||
if (child.exitCode !== null || child.signalCode !== null) return closed
|
||||
const escalation = setTimeout(() => { child.kill('SIGKILL') }, 10_000)
|
||||
child.kill('SIGTERM')
|
||||
try {
|
||||
await closed
|
||||
} finally {
|
||||
clearTimeout(escalation)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch the built `dsh web` profile; browsers map qr-login.test to its loopback listener.
|
||||
* The fixture certificate is self-signed and deliberately accepted only by test browser contexts.
|
||||
* @param secure - whether the actual listener uses TLS; false exercises HTTP login and cookies.
|
||||
* @param ticketLifetimeMs - invitation lifetime for expiry scenarios; omitted keeps the shipped default.
|
||||
* @returns the settled CLI and ownership-aware cleanup.
|
||||
*/
|
||||
export async function launchRemoteConnectionFixture(secure: boolean, ticketLifetimeMs?: number): Promise<RemoteConnectionFixture> {
|
||||
const bin = join(REPO_ROOT, 'apps/cli/lib/bin.js')
|
||||
if (!existsSync(bin)) throw new Error('Build the CLI and Web artifacts before running the remote-connection browser test.')
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-web-qr-'))
|
||||
let child: ChildProcess | undefined
|
||||
let closed: Promise<void> | undefined
|
||||
try {
|
||||
const workspace = join(root, 'workspace')
|
||||
await mkdir(workspace)
|
||||
const overlay = join(root, 'remote-connection.overlay.yml')
|
||||
await writeFile(overlay, [
|
||||
'- id: web-runtime',
|
||||
' inject: [webStartup, webServer]',
|
||||
' config:',
|
||||
" publicUrl: !!js ctx.webServer.getOrigin().replace('127.0.0.1', 'qr-login.test')",
|
||||
'- id: workspace-controller',
|
||||
' config:',
|
||||
` documentsDirectory: ${JSON.stringify(join(root, 'documents'))}`,
|
||||
'- id: ui-settings-general',
|
||||
' config:',
|
||||
" welcomeNoticeVersion: '2026-09-28.1'",
|
||||
...ticketLifetimeMs === undefined ? [] : [
|
||||
'- id: remote-connection',
|
||||
' config:',
|
||||
` ticketLifetimeMs: ${ticketLifetimeMs}`,
|
||||
],
|
||||
'- id: llm-deepseek',
|
||||
' disabled: true',
|
||||
'- id: llm-pi-ai',
|
||||
' disabled: true',
|
||||
'- id: session-title-llm',
|
||||
' disabled: true',
|
||||
'- id: agent-instructions',
|
||||
' disabled: true',
|
||||
'',
|
||||
].join('\n'))
|
||||
const tls = secure ? await materializeTlsFixture(root) : undefined
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
DSH_HOME: join(root, 'home'),
|
||||
DSH_AGENTS_HOME: join(root, 'agents'),
|
||||
DSH_TELEMETRY_DISABLED: '1',
|
||||
}
|
||||
delete env.NODE_OPTIONS
|
||||
delete env.DEEPSEEK_API_KEY
|
||||
delete env.DEEPSEEK_BASE_URL
|
||||
const processHandle = spawn(process.execPath, [
|
||||
bin, 'web',
|
||||
'--patch', join(REPO_ROOT, 'apps/web/tests/pin-browse-picker.overlay.yml'),
|
||||
'--patch', overlay,
|
||||
'--no-open', '--host', '127.0.0.1', '--port', '0',
|
||||
'--trusted-host', 'qr-login.test',
|
||||
...tls === undefined ? [] : ['--tls-cert', tls.certFile, '--tls-key', tls.keyFile],
|
||||
], { cwd: workspace, env, stdio: ['ignore', 'pipe', 'pipe'] })
|
||||
child = processHandle
|
||||
closed = new Promise<void>((resolve) => { processHandle.once('close', () => { resolve() }) })
|
||||
let output = ''
|
||||
const authenticatedUrl = await new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(() => { reject(new Error(`Web QR fixture did not start:\n${output}`)) }, 90_000)
|
||||
const settle = (value: string | Error): void => {
|
||||
clearTimeout(timer)
|
||||
if (value instanceof Error) reject(value)
|
||||
else resolve(value)
|
||||
}
|
||||
processHandle.stdout.setEncoding('utf8')
|
||||
processHandle.stderr.setEncoding('utf8')
|
||||
processHandle.stdout.on('data', (chunk: string) => {
|
||||
output += chunk
|
||||
const published = /dsh web: (https?:\/\/qr-login\.test:\d+\/[^\s]*)/.exec(output)?.[1]
|
||||
if (published !== undefined) settle(published)
|
||||
})
|
||||
processHandle.stderr.on('data', (chunk: string) => { output += chunk })
|
||||
processHandle.once('error', settle)
|
||||
processHandle.once('exit', (code, signal) => {
|
||||
settle(new Error(`Web QR fixture exited before readiness (${String(code)}, ${String(signal)}):\n${output}`))
|
||||
})
|
||||
})
|
||||
const url = new URL(authenticatedUrl)
|
||||
if (url.searchParams.getAll('token').length !== 1 || !url.searchParams.get('token')) {
|
||||
throw new Error('Web QR fixture did not receive the Token provider login URL.')
|
||||
}
|
||||
url.search = ''
|
||||
const whenClosed = closed
|
||||
let closing: Promise<void> | undefined
|
||||
return {
|
||||
authenticatedUrl, url: url.href, root,
|
||||
close() {
|
||||
closing ??= (async () => {
|
||||
await stop(processHandle, whenClosed)
|
||||
await rm(root, { recursive: true, force: true })
|
||||
})()
|
||||
return closing
|
||||
},
|
||||
}
|
||||
} catch (error) {
|
||||
if (child !== undefined && closed !== undefined) await stop(child, closed)
|
||||
await rm(root, { recursive: true, force: true })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
- id: web-runtime
|
||||
disabled: true
|
||||
- insert:
|
||||
- id: qr-test-web-runtime
|
||||
name: '@deepseek-ai/dsh-web-app'
|
||||
inject: [webServer]
|
||||
config:
|
||||
openBrowser: false
|
||||
printUrl: false
|
||||
surfaceContext: false
|
||||
publicUrl: !!js ctx.webServer.getOrigin().replace('127.0.0.1', 'qr-login.test')
|
||||
@@ -0,0 +1,701 @@
|
||||
/** Real settings-to-phone QR and link login; only test browsers accept the fixture's self-signed TLS. */
|
||||
import { mkdir } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { chromium, type Browser, type Locator, type Page } from 'playwright'
|
||||
import { afterAll, beforeAll, describe, expect, it, onTestFinished } from 'vitest'
|
||||
import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode } from './scaffold.ts'
|
||||
import { launchRemoteConnectionFixture, type RemoteConnectionFixture } from './remote-connection-fixture.ts'
|
||||
import { openSettings, ZH_BROWSER_LOCALE } from './support.ts'
|
||||
|
||||
const EXPECTED = fileURLToPath(new URL('./expected/remote-connection', import.meta.url))
|
||||
const MODE = webSnapshotMode()
|
||||
const MOBILE = { width: 390, height: 844 }
|
||||
const REPLACEMENT_FIXTURE = fileURLToPath(new URL('./fixtures/plugins/fixture-remote-connection', import.meta.url))
|
||||
const REPLACEMENT_OVERLAY = fileURLToPath(new URL('./remote-connection-replacement.overlay.yml', import.meta.url))
|
||||
|
||||
async function remoteSettings(page: Page): Promise<Locator> {
|
||||
await openSettings(page, 'zh')
|
||||
await page.getByRole('dialog', { name: '设置', exact: true })
|
||||
.getByRole('button', { name: '远程连接', exact: true }).click()
|
||||
const section = page.getByRole('region', { name: '远程连接', exact: true })
|
||||
await section.waitFor()
|
||||
const link = section.getByRole('region', { name: '链接登录', exact: true })
|
||||
await expect.poll(() => link.getByRole('button', { name: /^(复制登录链接|重试)$/ }).isEnabled()).toBe(true)
|
||||
return section
|
||||
}
|
||||
|
||||
async function createCode(page: Page, section: Locator): Promise<string> {
|
||||
const created = page.waitForResponse(response => new URL(response.url()).pathname === '/api/remoteConnection/create')
|
||||
await section.getByRole('button', { name: /^(生成登录二维码|生成新二维码)$/ }).click()
|
||||
const response = await created
|
||||
expect(response.status()).toBe(200)
|
||||
const envelope = await response.json() as { result: { ok: boolean; value: { url: string } } }
|
||||
expect(envelope.result.ok).toBe(true)
|
||||
const url = envelope.result.value.url
|
||||
const parsed = new URL(url)
|
||||
expect(parsed.pathname).toBe('/remote-login')
|
||||
expect(parsed.search).toBe('')
|
||||
expect(parsed.hash).toMatch(/^#[A-Za-z0-9_-]{43}$/)
|
||||
await section.getByRole('img', { name: '一次性登录二维码' }).waitFor()
|
||||
return url
|
||||
}
|
||||
|
||||
async function snapshot(page: Page, fixture: RemoteConnectionFixture, name: string): Promise<void> {
|
||||
const aria = await captureStableAria(page, 'section[aria-label="远程连接"]', fixture.root, {
|
||||
replacements: [[fixture.authenticatedUrl, '{{access-address}}?token={{login-token}}'], [fixture.url, '{{access-address}}']],
|
||||
})
|
||||
await compareOrRefreshGolden(join(EXPECTED, `${name}.expected.md`), aria.replace(/\d+ 秒后过期/gu, '{{seconds}} 秒后过期'), MODE)
|
||||
}
|
||||
|
||||
describe('web e2e: one-use QR browser login', () => {
|
||||
let browser: Browser
|
||||
let secure: RemoteConnectionFixture
|
||||
|
||||
beforeAll(async () => {
|
||||
if (MODE === 'refresh') await mkdir(EXPECTED, { recursive: true })
|
||||
secure = await launchRemoteConnectionFixture(true)
|
||||
browser = await chromium.launch({
|
||||
// Content growth must exercise the width consumed by a real scrollbar.
|
||||
ignoreDefaultArgs: ['--hide-scrollbars'],
|
||||
// Browser contexts otherwise inherit the OS proxy; bypass all destinations without contacting this unused address.
|
||||
proxy: { server: 'http://127.0.0.1:9', bypass: '*' },
|
||||
args: ['--host-resolver-rules=MAP qr-login.test 127.0.0.1'],
|
||||
})
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
try {
|
||||
await browser?.close()
|
||||
} finally {
|
||||
await secure?.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('shows the Remote-owned anonymous page, rejects an invalid Token in place, and signs in with the independent Token URL', async () => {
|
||||
const phone = await browser.newContext({
|
||||
ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE, viewport: MOBILE, colorScheme: 'light',
|
||||
})
|
||||
try {
|
||||
const page = await phone.newPage()
|
||||
const console = watchConsole(page)
|
||||
const response = await page.goto(secure.url)
|
||||
expect(response?.status()).toBe(401)
|
||||
expect(response?.headers()['content-type']).toContain('text/html')
|
||||
expect(response?.headers()['cache-control']).toBe('no-store')
|
||||
const startupToken = new URL(secure.authenticatedUrl).searchParams.get('token')!
|
||||
const body = await response!.text()
|
||||
expect(body).not.toContain(startupToken)
|
||||
expect(body).not.toContain('__DSH_BOOT__')
|
||||
await page.getByRole('heading', { name: '连接到此 Host', exact: true }).waitFor()
|
||||
const input = page.getByLabel('登录令牌或链接', { exact: true })
|
||||
const submit = page.getByRole('button', { name: '继续', exact: true })
|
||||
await input.waitFor()
|
||||
expect(await page.getByRole('button', { name: '账号菜单', exact: true }).count()).toBe(0)
|
||||
expect(await page.evaluate(async () => {
|
||||
const reply = await fetch('./', { method: 'HEAD', credentials: 'same-origin', cache: 'no-store', redirect: 'manual' })
|
||||
return { status: reply.status, body: await reply.text() }
|
||||
})).toEqual({ status: 401, body: '' })
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(MOBILE.width)
|
||||
await input.focus()
|
||||
expect(await input.evaluate(element => document.activeElement === element)).toBe(true)
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'anonymous-login.expected.md'),
|
||||
await captureStableAria(page, 'main', secure.root), MODE)
|
||||
const screenshots = process.env['DSH_REMOTE_CONNECTION_SCREENSHOTS']
|
||||
if (screenshots !== undefined) {
|
||||
await mkdir(screenshots, { recursive: true })
|
||||
await page.screenshot({ path: join(screenshots, 'anonymous-mobile-light.png') })
|
||||
}
|
||||
const lightBackground = await page.evaluate(() => getComputedStyle(document.documentElement).backgroundColor)
|
||||
await page.emulateMedia({ colorScheme: 'dark' })
|
||||
await expect.poll(() => page.evaluate(() => getComputedStyle(document.documentElement).backgroundColor)).not.toBe(lightBackground)
|
||||
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'anonymous-mobile-dark.png') })
|
||||
|
||||
const invalidToken = `${startupToken.startsWith('a') ? 'b' : 'a'}${startupToken.slice(1)}`
|
||||
const rejected = page.waitForResponse(reply => new URL(reply.url()).searchParams.get('token') === invalidToken)
|
||||
await input.fill(invalidToken)
|
||||
await submit.click()
|
||||
expect((await rejected).status()).toBe(401)
|
||||
await page.getByRole('alert').filter({ hasText: '此登录令牌无效或已过期,请粘贴新的令牌后重试' }).waitFor()
|
||||
expect(page.url()).toBe(secure.url)
|
||||
expect(await input.getAttribute('aria-invalid')).toBe('true')
|
||||
expect(await submit.isEnabled()).toBe(true)
|
||||
expect(await phone.cookies()).toEqual([])
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(MOBILE.width)
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'anonymous-rejected.expected.md'),
|
||||
await captureStableAria(page, 'main', secure.root, { replacements: [[invalidToken, '{{invalid-token}}']] }), MODE)
|
||||
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'anonymous-token-rejected-dark.png') })
|
||||
|
||||
await input.fill(secure.authenticatedUrl)
|
||||
await submit.click()
|
||||
await page.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
expect(page.url()).toBe(secure.url)
|
||||
expect((await phone.cookies()).filter(cookie => cookie.name.startsWith('dsh-auth-'))).toHaveLength(1)
|
||||
expect((await phone.cookies()).filter(cookie => cookie.name.startsWith('dsh-remote-'))).toEqual([])
|
||||
expect(await page.evaluate(async () => {
|
||||
const reply = await fetch('./', { method: 'HEAD', credentials: 'same-origin', cache: 'no-store', redirect: 'manual' })
|
||||
return { status: reply.status, body: await reply.text() }
|
||||
})).toEqual({ status: 200, body: '' })
|
||||
await page.reload()
|
||||
await page.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
expect(console.pageErrors).toEqual([])
|
||||
} finally {
|
||||
await phone.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('retries in the copy button, shows a fading tokenized link, and keeps credential warnings independent', async () => {
|
||||
const desktop = await browser.newContext({
|
||||
ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE, viewport: { width: 1200, height: 1000 },
|
||||
permissions: ['clipboard-read', 'clipboard-write'], colorScheme: 'light',
|
||||
})
|
||||
const phone = await browser.newContext({ ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE, viewport: MOBILE })
|
||||
try {
|
||||
const page = await desktop.newPage()
|
||||
const console = watchConsole(page)
|
||||
let rejectLinkRead = true
|
||||
await page.route('**/api/remoteConnection/loginUrl', (route) => {
|
||||
if (!rejectLinkRead) return route.continue()
|
||||
const request = route.request().postDataJSON() as { rpcId: string }
|
||||
return route.fulfill({ json: {
|
||||
type: 'server-response', rpcId: request.rpcId,
|
||||
result: { ok: false, error: { code: 'gateway/internal', message: 'Fixture unavailable', details: {} } },
|
||||
} })
|
||||
})
|
||||
await page.goto(secure.authenticatedUrl)
|
||||
const section = await remoteSettings(page)
|
||||
const qrSection = section.getByRole('region', { name: '二维码登录', exact: true })
|
||||
const linkSection = section.getByRole('region', { name: '链接登录', exact: true })
|
||||
expect(await qrSection.count()).toBe(1)
|
||||
expect(await linkSection.count()).toBe(1)
|
||||
for (const card of [qrSection, linkSection]) {
|
||||
expect(await card.getByRole('button').first().evaluate(element => getComputedStyle(element).fontSize)).toBe('12px')
|
||||
expect(await card.evaluate(element => Number.parseFloat(getComputedStyle(element).borderLeftWidth))).toBeGreaterThan(0)
|
||||
const cardBox = await card.boundingBox()
|
||||
const titleBox = await card.getByRole('heading', { level: 3 }).boundingBox()
|
||||
expect(cardBox).not.toBeNull()
|
||||
expect(titleBox).not.toBeNull()
|
||||
expect(titleBox!.x).toBeGreaterThan(cardBox!.x)
|
||||
expect(titleBox!.y).toBeGreaterThan(cardBox!.y)
|
||||
expect(titleBox!.x + titleBox!.width).toBeLessThan(cardBox!.x + cardBox!.width)
|
||||
}
|
||||
expect(await qrSection.locator('code').count()).toBe(0)
|
||||
expect(await linkSection.getByRole('button').count()).toBe(1)
|
||||
await linkSection.getByText('无法获取登录链接,请重试', { exact: true }).waitFor()
|
||||
await snapshot(page, secure, 'link-failed')
|
||||
rejectLinkRead = false
|
||||
await linkSection.getByRole('button', { name: '重试', exact: true }).click()
|
||||
await expect.poll(() => linkSection.getByRole('button', { name: '复制登录链接', exact: true }).isEnabled()).toBe(true)
|
||||
expect(await linkSection.getByRole('button').count()).toBe(1)
|
||||
const desktopLinkField = await linkSection.locator('code').locator('..').boundingBox()
|
||||
const desktopCopy = await linkSection.getByRole('button', { name: '复制登录链接', exact: true }).boundingBox()
|
||||
expect(desktopLinkField).not.toBeNull()
|
||||
expect(desktopCopy).not.toBeNull()
|
||||
expect(desktopLinkField!.height).toBe(desktopCopy!.height)
|
||||
expect(Math.abs(desktopLinkField!.y - desktopCopy!.y)).toBeLessThanOrEqual(1)
|
||||
expect(await section.getByText('请勿分享登录二维码', { exact: true }).count()).toBe(0)
|
||||
expect(await section.getByText('请勿公开分享登录链接', { exact: true }).count()).toBe(0)
|
||||
await snapshot(page, secure, 'link-ready')
|
||||
await linkSection.getByRole('button', { name: '复制登录链接', exact: true }).click()
|
||||
await page.getByText('链接已复制', { exact: true }).waitFor()
|
||||
const copiedUrl = await page.evaluate(() => navigator.clipboard.readText())
|
||||
expect(copiedUrl).toBe(secure.authenticatedUrl)
|
||||
const token = new URL(copiedUrl).searchParams.get('token')!
|
||||
expect(token).not.toBe('')
|
||||
expect(await linkSection.locator('code').textContent()).toBe(copiedUrl)
|
||||
expect(await linkSection.locator('code').evaluate(element => getComputedStyle(element).maskImage)).not.toBe('none')
|
||||
await linkSection.getByText('请勿公开分享登录链接', { exact: true }).waitFor()
|
||||
expect(await qrSection.getByText('请勿分享登录二维码', { exact: true }).count()).toBe(0)
|
||||
await snapshot(page, secure, 'link-copied')
|
||||
const screenshots = process.env['DSH_REMOTE_CONNECTION_SCREENSHOTS']
|
||||
if (screenshots !== undefined) {
|
||||
await mkdir(screenshots, { recursive: true })
|
||||
await page.getByText('链接已复制', { exact: true }).waitFor({ state: 'hidden' })
|
||||
await page.screenshot({ path: join(screenshots, 'link-desktop-light.png') })
|
||||
}
|
||||
|
||||
const phonePage = await phone.newPage()
|
||||
await phonePage.goto(copiedUrl)
|
||||
await phonePage.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
expect(phonePage.url()).toBe(secure.url)
|
||||
expect((await phone.cookies()).filter(cookie => cookie.name.startsWith('dsh-auth-'))).toHaveLength(1)
|
||||
await phonePage.reload()
|
||||
await phonePage.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
|
||||
await page.setViewportSize(MOBILE)
|
||||
await snapshot(page, secure, 'link-mobile-light')
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(MOBILE.width)
|
||||
const copyBox = await linkSection.getByRole('button', { name: '已复制', exact: true }).boundingBox()
|
||||
expect(copyBox).not.toBeNull()
|
||||
expect(copyBox!.x).toBeGreaterThanOrEqual(0)
|
||||
expect(copyBox!.x + copyBox!.width).toBeLessThanOrEqual(MOBILE.width)
|
||||
const mobileLinkField = await linkSection.locator('code').locator('..').boundingBox()
|
||||
expect(mobileLinkField).not.toBeNull()
|
||||
expect(mobileLinkField!.height).toBe(copyBox!.height)
|
||||
expect(mobileLinkField!.y + mobileLinkField!.height).toBeLessThan(copyBox!.y)
|
||||
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'link-mobile-light.png') })
|
||||
await page.emulateMedia({ colorScheme: 'dark' })
|
||||
await expect.poll(() => page.evaluate(() => getComputedStyle(document.documentElement).colorScheme)).toBe('dark')
|
||||
await snapshot(page, secure, 'link-mobile-dark')
|
||||
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'link-mobile-dark.png') })
|
||||
await page.setViewportSize({ width: 1200, height: 1000 })
|
||||
await page.emulateMedia({ colorScheme: 'light' })
|
||||
await createCode(page, section)
|
||||
await qrSection.getByText('请勿分享登录二维码', { exact: true }).waitFor()
|
||||
await linkSection.getByText('请勿公开分享登录链接', { exact: true }).waitFor()
|
||||
await snapshot(page, secure, 'both-active')
|
||||
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'both-desktop-light.png') })
|
||||
await linkSection.getByRole('button', { name: '已复制', exact: true }).click()
|
||||
await page.getByText('链接已复制', { exact: true }).waitFor()
|
||||
await page.getByRole('dialog', { name: '设置', exact: true }).getByRole('button', { name: '关闭', exact: true }).click()
|
||||
expect(await page.getByRole('dialog', { name: '设置', exact: true }).count()).toBe(0)
|
||||
expect(await page.getByText('链接已复制', { exact: true }).count()).toBe(1)
|
||||
expect(console.pageErrors).toEqual([])
|
||||
} finally {
|
||||
await Promise.all([desktop.close(), phone.close()])
|
||||
}
|
||||
})
|
||||
|
||||
it.each([true, false])('keeps QR and link rows horizontal when copying adds a scrollbar to a short panel (TLS: %s)', async (tls) => {
|
||||
const fixture = tls ? secure : await launchRemoteConnectionFixture(false)
|
||||
if (!tls) onTestFinished(() => fixture.close())
|
||||
const desktop = await browser.newContext({
|
||||
ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE, viewport: { width: 1200, height: 800 },
|
||||
permissions: ['clipboard-read', 'clipboard-write'], colorScheme: 'light',
|
||||
})
|
||||
try {
|
||||
const page = await desktop.newPage()
|
||||
await page.goto(fixture.authenticatedUrl)
|
||||
const section = await remoteSettings(page)
|
||||
await createCode(page, section)
|
||||
const qr = section.getByRole('region', { name: '二维码登录', exact: true })
|
||||
const link = section.getByRole('region', { name: '链接登录', exact: true })
|
||||
const copy = link.getByRole('button', { name: '复制登录链接', exact: true })
|
||||
const beforeSection = await section.boundingBox()
|
||||
const beforeQr = await qr.boundingBox()
|
||||
const beforeField = await link.locator('code').locator('..').boundingBox()
|
||||
const beforeCopy = await copy.boundingBox()
|
||||
const scrollport = page.getByRole('dialog', { name: '设置', exact: true }).locator('[data-slot="settings.section"]').locator('..')
|
||||
const beforeGutter = await scrollport.evaluate(element => element.getBoundingClientRect().width - element.clientWidth)
|
||||
const screenshots = process.env['DSH_REMOTE_CONNECTION_SCREENSHOTS']
|
||||
if (screenshots !== undefined) {
|
||||
await mkdir(screenshots, { recursive: true })
|
||||
await page.screenshot({ path: join(screenshots, 'copy-short-panel-before.png') })
|
||||
}
|
||||
await copy.click()
|
||||
await link.getByText('请勿公开分享登录链接', { exact: true }).waitFor()
|
||||
await page.getByText('链接已复制', { exact: true }).waitFor()
|
||||
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'copy-short-panel-after.png') })
|
||||
expect(beforeSection).not.toBeNull()
|
||||
expect(beforeQr).not.toBeNull()
|
||||
expect(beforeField).not.toBeNull()
|
||||
expect(beforeCopy).not.toBeNull()
|
||||
const gutterChange = await scrollport.evaluate(element => element.getBoundingClientRect().width - element.clientWidth) - beforeGutter
|
||||
expect((await section.boundingBox())!.width).toBe(beforeSection!.width - gutterChange)
|
||||
expect(await qr.boundingBox()).toEqual({ ...beforeQr!, width: beforeQr!.width - gutterChange })
|
||||
expect(await link.locator('code').locator('..').boundingBox()).toEqual({ ...beforeField!, width: beforeField!.width - gutterChange })
|
||||
expect(await link.getByRole('button', { name: '已复制', exact: true }).boundingBox()).toEqual({ ...beforeCopy!, x: beforeCopy!.x - gutterChange })
|
||||
expect(await qr.getByRole('img').count()).toBe(1)
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(1200)
|
||||
} finally {
|
||||
await desktop.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('signs in a separate phone browser once, preserves its login, and reports use without desktop approval', async () => {
|
||||
const desktop = await browser.newContext({ ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE })
|
||||
const phone = await browser.newContext({ ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE, viewport: MOBILE, colorScheme: 'light' })
|
||||
const stranger = await browser.newContext({ ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE, viewport: MOBILE })
|
||||
try {
|
||||
const desktopPage = await desktop.newPage()
|
||||
await desktopPage.goto(secure.authenticatedUrl)
|
||||
const desktopSection = await remoteSettings(desktopPage)
|
||||
const qrUrl = await createCode(desktopPage, desktopSection)
|
||||
expect(new URL(qrUrl).origin).toBe(new URL(secure.url).origin)
|
||||
const desktopCode = await desktopSection.getByRole('img', { name: '一次性登录二维码' }).boundingBox()
|
||||
const desktopAction = await desktopSection.getByRole('button', { name: '生成新二维码', exact: true }).boundingBox()
|
||||
const desktopTitle = await desktopSection.getByRole('heading', { name: '二维码登录', exact: true }).boundingBox()
|
||||
expect(desktopCode).not.toBeNull()
|
||||
expect(desktopAction).not.toBeNull()
|
||||
expect(desktopTitle).not.toBeNull()
|
||||
expect(desktopAction!.x).toBeGreaterThan(desktopTitle!.x + desktopTitle!.width)
|
||||
expect(desktopAction!.y + desktopAction!.height).toBeLessThan(desktopCode!.y)
|
||||
expect(Math.abs(desktopTitle!.y + desktopTitle!.height / 2 - desktopAction!.y - desktopAction!.height / 2)).toBeLessThanOrEqual(1)
|
||||
const desktopScan = await desktopSection.getByText('扫码后直接登录', { exact: true }).boundingBox()
|
||||
const desktopTimer = await desktopSection.getByRole('timer').boundingBox()
|
||||
const desktopWarning = await desktopSection.getByText('请勿分享登录二维码', { exact: true }).boundingBox()
|
||||
const desktopDetails = await desktopSection.getByRole('timer').locator('..').boundingBox()
|
||||
const desktopBanner = await desktopSection.getByText('请勿分享登录二维码', { exact: true }).locator('..').locator('..').boundingBox()
|
||||
expect(desktopScan).not.toBeNull()
|
||||
expect(desktopTimer).not.toBeNull()
|
||||
expect(desktopWarning).not.toBeNull()
|
||||
expect(desktopDetails).not.toBeNull()
|
||||
expect(desktopBanner).not.toBeNull()
|
||||
expect(desktopDetails!.x).toBe(desktopBanner!.x)
|
||||
expect(desktopDetails!.width).toBe(desktopBanner!.width)
|
||||
expect(Math.abs(desktopScan!.y - desktopTimer!.y)).toBeLessThanOrEqual(1)
|
||||
expect(desktopTimer!.y).toBeGreaterThan(desktopCode!.y + desktopCode!.height)
|
||||
expect(desktopWarning!.y).toBeGreaterThan(desktopTimer!.y + desktopTimer!.height)
|
||||
|
||||
const phonePage = await phone.newPage()
|
||||
const pageErrors: string[] = []
|
||||
phonePage.on('pageerror', (error) => { pageErrors.push(error.message) })
|
||||
const exchanged = phonePage.waitForResponse(response => new URL(response.url()).pathname === '/remote-login'
|
||||
&& response.request().method() === 'POST')
|
||||
await phonePage.goto(qrUrl)
|
||||
expect((await exchanged).status()).toBe(204)
|
||||
await phonePage.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
expect(phonePage.url()).toBe(secure.url)
|
||||
expect((await phone.cookies()).filter(cookie => cookie.name.startsWith('dsh-remote-'))).toEqual([
|
||||
expect.objectContaining({ httpOnly: true, secure: true, sameSite: 'Strict', domain: 'qr-login.test' }),
|
||||
])
|
||||
expect((await phone.cookies()).filter(cookie => cookie.name.startsWith('dsh-auth-'))).toEqual([])
|
||||
expect(await phonePage.evaluate(async () => (await fetch('./', {
|
||||
method: 'HEAD', credentials: 'same-origin', cache: 'no-store', redirect: 'manual',
|
||||
})).status)).toBe(200)
|
||||
await phonePage.reload()
|
||||
await phonePage.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
await desktopSection.getByText('二维码已使用,请在手机上确认是否已登录', { exact: true }).waitFor()
|
||||
expect(await desktopSection.getByRole('img').count()).toBe(0)
|
||||
await snapshot(desktopPage, secure, 'used')
|
||||
await desktopPage.close()
|
||||
|
||||
await phonePage.close()
|
||||
const returning = await phone.newPage()
|
||||
await returning.goto(secure.url)
|
||||
await returning.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
expect(returning.url()).toBe(secure.url)
|
||||
const mobileSection = await remoteSettings(returning)
|
||||
await mobileSection.getByRole('button', { name: '生成登录二维码', exact: true }).waitFor()
|
||||
await createCode(returning, mobileSection)
|
||||
await snapshot(returning, secure, 'mobile-light')
|
||||
expect(await returning.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(MOBILE.width)
|
||||
const box = await mobileSection.boundingBox()
|
||||
expect(box).not.toBeNull()
|
||||
expect(box!.x).toBeGreaterThanOrEqual(0)
|
||||
expect(box!.x + box!.width).toBeLessThanOrEqual(MOBILE.width)
|
||||
const qrBox = await mobileSection.getByRole('img', { name: '一次性登录二维码' }).boundingBox()
|
||||
expect(qrBox).not.toBeNull()
|
||||
expect(qrBox!.x).toBeGreaterThanOrEqual(0)
|
||||
expect(qrBox!.x + qrBox!.width).toBeLessThanOrEqual(MOBILE.width)
|
||||
const mobileAction = await mobileSection.getByRole('button', { name: '生成新二维码', exact: true }).boundingBox()
|
||||
const mobileTitle = await mobileSection.getByRole('heading', { name: '二维码登录', exact: true }).boundingBox()
|
||||
expect(mobileAction).not.toBeNull()
|
||||
expect(mobileTitle).not.toBeNull()
|
||||
expect(mobileAction!.y).toBeGreaterThan(mobileTitle!.y + mobileTitle!.height)
|
||||
expect(mobileAction!.x).toBe(mobileTitle!.x)
|
||||
expect(mobileAction!.width).toBe(mobileTitle!.width)
|
||||
expect(mobileAction!.y + mobileAction!.height).toBeLessThan(qrBox!.y)
|
||||
const mobileCancel = await mobileSection.getByRole('button', { name: '取消二维码', exact: true }).boundingBox()
|
||||
expect(mobileCancel).not.toBeNull()
|
||||
expect(mobileCancel!.y).toBeGreaterThan(mobileAction!.y + mobileAction!.height)
|
||||
expect(mobileCancel!.x).toBe(mobileAction!.x)
|
||||
expect(mobileCancel!.width).toBe(mobileAction!.width)
|
||||
const mobileScan = await mobileSection.getByText('扫码后直接登录', { exact: true }).boundingBox()
|
||||
const mobileTimer = await mobileSection.getByRole('timer').boundingBox()
|
||||
const mobileWarning = await mobileSection.getByText('请勿分享登录二维码', { exact: true }).boundingBox()
|
||||
const mobileDetails = await mobileSection.getByRole('timer').locator('..').boundingBox()
|
||||
const mobileBanner = await mobileSection.getByText('请勿分享登录二维码', { exact: true }).locator('..').locator('..').boundingBox()
|
||||
expect(mobileScan).not.toBeNull()
|
||||
expect(mobileTimer).not.toBeNull()
|
||||
expect(mobileWarning).not.toBeNull()
|
||||
expect(mobileDetails).not.toBeNull()
|
||||
expect(mobileBanner).not.toBeNull()
|
||||
expect(mobileDetails!.x).toBe(mobileBanner!.x)
|
||||
expect(mobileDetails!.width).toBe(mobileBanner!.width)
|
||||
expect(Math.abs(mobileScan!.y - mobileTimer!.y)).toBeLessThanOrEqual(1)
|
||||
expect(mobileTimer!.y).toBeGreaterThan(qrBox!.y + qrBox!.height)
|
||||
expect(mobileWarning!.y).toBeGreaterThan(mobileTimer!.y + mobileTimer!.height)
|
||||
const screenshots = process.env['DSH_REMOTE_CONNECTION_SCREENSHOTS']
|
||||
if (screenshots !== undefined) {
|
||||
await mkdir(screenshots, { recursive: true })
|
||||
await returning.screenshot({ path: join(screenshots, 'qr-mobile-light.png') })
|
||||
}
|
||||
await returning.emulateMedia({ colorScheme: 'dark' })
|
||||
await expect.poll(() => returning.evaluate(() => getComputedStyle(document.documentElement).colorScheme)).toBe('dark')
|
||||
await snapshot(returning, secure, 'mobile-dark')
|
||||
if (screenshots !== undefined) await returning.screenshot({ path: join(screenshots, 'qr-mobile-dark.png') })
|
||||
await mobileSection.getByRole('button', { name: '取消二维码', exact: true }).click()
|
||||
await mobileSection.getByRole('button', { name: '取消二维码', exact: true }).waitFor({ state: 'detached' })
|
||||
expect(await mobileSection.getByRole('status').count()).toBe(0)
|
||||
expect(await mobileSection.getByRole('img').count()).toBe(0)
|
||||
|
||||
const reusedPage = await stranger.newPage()
|
||||
const refused = reusedPage.waitForResponse(response => new URL(response.url()).pathname === '/remote-login'
|
||||
&& response.request().method() === 'POST')
|
||||
await reusedPage.goto(qrUrl)
|
||||
expect((await refused).status()).toBe(410)
|
||||
await expect.poll(() => new URL(reusedPage.url()).hash).toBe('')
|
||||
expect((await stranger.cookies()).filter(cookie => cookie.name.startsWith('dsh-remote-'))).toEqual([])
|
||||
expect(await reusedPage.getByRole('button', { name: '账号菜单', exact: true }).count()).toBe(0)
|
||||
expect(pageErrors).toEqual([])
|
||||
} finally {
|
||||
await Promise.all([desktop.close(), phone.close(), stranger.close()])
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps both cards in place while regenerating a QR with a local spinner', async () => {
|
||||
for (const viewport of [{ width: 1200, height: 1000 }, MOBILE]) {
|
||||
const desktop = await browser.newContext({ ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE, viewport })
|
||||
try {
|
||||
const page = await desktop.newPage()
|
||||
await page.goto(secure.authenticatedUrl)
|
||||
const section = await remoteSettings(page)
|
||||
await createCode(page, section)
|
||||
const qr = section.getByRole('region', { name: '二维码登录', exact: true })
|
||||
const link = section.getByRole('region', { name: '链接登录', exact: true })
|
||||
const qrBox = await qr.boundingBox()
|
||||
const linkBox = await link.boundingBox()
|
||||
const symbol = await qr.getByRole('img').boundingBox()
|
||||
const firstSvg = await qr.getByRole('img').innerHTML()
|
||||
expect(symbol).not.toBeNull()
|
||||
let release!: () => void
|
||||
const gate = new Promise<void>((resolve) => { release = resolve })
|
||||
await page.route('**/api/remoteConnection/create', async (route) => {
|
||||
await gate
|
||||
await route.continue()
|
||||
})
|
||||
const created = page.waitForResponse(response => new URL(response.url()).pathname === '/api/remoteConnection/create')
|
||||
try {
|
||||
await qr.getByRole('button', { name: '生成新二维码', exact: true }).click()
|
||||
const loading = qr.getByRole('status', { name: '正在生成登录二维码', exact: true })
|
||||
await loading.waitFor()
|
||||
expect(await qr.getByRole('img').count()).toBe(0)
|
||||
expect(await qr.getByRole('timer').isVisible()).toBe(true)
|
||||
expect(await qr.getByText('请勿分享登录二维码', { exact: true }).isVisible()).toBe(true)
|
||||
expect(await qr.boundingBox()).toEqual(qrBox)
|
||||
expect(await link.boundingBox()).toEqual(linkBox)
|
||||
expect(await link.getByRole('button', { name: '复制登录链接', exact: true }).isEnabled()).toBe(true)
|
||||
const spinner = await loading.boundingBox()
|
||||
expect(spinner).not.toBeNull()
|
||||
expect(Math.abs(spinner!.x + spinner!.width / 2 - symbol!.x - symbol!.width / 2)).toBeLessThanOrEqual(1)
|
||||
expect(Math.abs(spinner!.y + spinner!.height / 2 - symbol!.y - symbol!.height / 2)).toBeLessThanOrEqual(1)
|
||||
if (viewport.width !== MOBILE.width) await snapshot(page, secure, 'regenerating')
|
||||
const screenshots = process.env['DSH_REMOTE_CONNECTION_SCREENSHOTS']
|
||||
if (screenshots !== undefined) {
|
||||
await mkdir(screenshots, { recursive: true })
|
||||
await page.screenshot({ path: join(screenshots, viewport.width === MOBILE.width ? 'qr-generating-mobile.png' : 'qr-generating-desktop.png') })
|
||||
}
|
||||
} finally {
|
||||
release()
|
||||
await created
|
||||
}
|
||||
await qr.getByRole('img').waitFor()
|
||||
expect(await qr.getByRole('img').innerHTML()).not.toBe(firstSvg)
|
||||
expect(await qr.boundingBox()).toEqual(qrBox)
|
||||
expect(await link.boundingBox()).toEqual(linkBox)
|
||||
} finally {
|
||||
await desktop.close()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('places the expiry banner below the QR controls at full width and allows regeneration', async () => {
|
||||
const fixture = await launchRemoteConnectionFixture(false, 5000)
|
||||
onTestFinished(() => fixture.close())
|
||||
const desktop = await browser.newContext({
|
||||
locale: ZH_BROWSER_LOCALE, viewport: { width: 1200, height: 1000 }, colorScheme: 'light',
|
||||
})
|
||||
try {
|
||||
const page = await desktop.newPage()
|
||||
await page.goto(fixture.authenticatedUrl)
|
||||
const section = await remoteSettings(page)
|
||||
const first = await createCode(page, section)
|
||||
const qr = section.getByRole('region', { name: '二维码登录', exact: true })
|
||||
const notice = qr.getByRole('status')
|
||||
await notice.getByText('二维码已过期,请生成新二维码登录', { exact: true }).waitFor()
|
||||
expect(await notice.evaluate(element => Number.parseFloat(getComputedStyle(element).borderLeftWidth))).toBeGreaterThan(0)
|
||||
expect(await qr.getByRole('img').count()).toBe(0)
|
||||
expect(await qr.getByRole('timer').count()).toBe(0)
|
||||
expect(await qr.getByRole('button', { name: '生成新二维码', exact: true }).isEnabled()).toBe(true)
|
||||
const header = await qr.getByRole('heading', { name: '二维码登录', exact: true }).locator('..').boundingBox()
|
||||
const desktopNotice = await notice.boundingBox()
|
||||
expect(header).not.toBeNull()
|
||||
expect(desktopNotice).not.toBeNull()
|
||||
expect(desktopNotice!.y).toBeGreaterThan(header!.y + header!.height)
|
||||
expect(desktopNotice!.x).toBe(header!.x)
|
||||
expect(desktopNotice!.width).toBe(header!.width)
|
||||
await snapshot(page, fixture, 'expired')
|
||||
const screenshots = process.env['DSH_REMOTE_CONNECTION_SCREENSHOTS']
|
||||
if (screenshots !== undefined) {
|
||||
await mkdir(screenshots, { recursive: true })
|
||||
await page.screenshot({ path: join(screenshots, 'expired-desktop-light.png') })
|
||||
}
|
||||
await page.emulateMedia({ colorScheme: 'dark' })
|
||||
await expect.poll(() => page.evaluate(() => getComputedStyle(document.documentElement).colorScheme)).toBe('dark')
|
||||
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'expired-desktop-dark.png') })
|
||||
await page.setViewportSize(MOBILE)
|
||||
const mobileTitle = await qr.getByRole('heading', { name: '二维码登录', exact: true }).boundingBox()
|
||||
const mobileNotice = await notice.boundingBox()
|
||||
const mobileAction = await qr.getByRole('button', { name: '生成新二维码', exact: true }).boundingBox()
|
||||
expect(mobileTitle).not.toBeNull()
|
||||
expect(mobileNotice).not.toBeNull()
|
||||
expect(mobileAction).not.toBeNull()
|
||||
expect(mobileAction!.y).toBeGreaterThan(mobileTitle!.y + mobileTitle!.height)
|
||||
expect(mobileNotice!.y).toBeGreaterThan(mobileAction!.y + mobileAction!.height)
|
||||
expect(mobileAction!.x).toBe(mobileTitle!.x)
|
||||
expect(mobileAction!.width).toBe(mobileTitle!.width)
|
||||
expect(mobileNotice!.x).toBe(mobileAction!.x)
|
||||
expect(mobileNotice!.width).toBe(mobileAction!.width)
|
||||
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(MOBILE.width)
|
||||
await snapshot(page, fixture, 'expired-mobile-dark')
|
||||
if (screenshots !== undefined) await page.screenshot({ path: join(screenshots, 'expired-mobile-dark.png') })
|
||||
expect(await createCode(page, section)).not.toBe(first)
|
||||
expect(await qr.getByText('二维码已过期,请生成新二维码登录', { exact: true }).count()).toBe(0)
|
||||
} finally {
|
||||
await desktop.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('cancels an unused code without logging out an existing browser', async () => {
|
||||
const desktop = await browser.newContext({ ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE })
|
||||
const phone = await browser.newContext({ ignoreHTTPSErrors: true, locale: ZH_BROWSER_LOCALE })
|
||||
try {
|
||||
const page = await desktop.newPage()
|
||||
await page.goto(secure.authenticatedUrl)
|
||||
const section = await remoteSettings(page)
|
||||
const qrUrl = await createCode(page, section)
|
||||
await section.getByRole('button', { name: '取消二维码', exact: true }).click()
|
||||
await section.getByRole('button', { name: '取消二维码', exact: true }).waitFor({ state: 'detached' })
|
||||
expect(await section.getByRole('status').count()).toBe(0)
|
||||
expect(await section.getByRole('img').count()).toBe(0)
|
||||
await snapshot(page, secure, 'cancelled')
|
||||
const other = await phone.newPage()
|
||||
const refused = other.waitForResponse(response => new URL(response.url()).pathname === '/remote-login'
|
||||
&& response.request().method() === 'POST')
|
||||
await other.goto(qrUrl)
|
||||
expect((await refused).status()).toBe(410)
|
||||
expect((await phone.cookies()).filter(cookie => cookie.name.startsWith('dsh-remote-'))).toEqual([])
|
||||
await page.reload()
|
||||
await page.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
} finally {
|
||||
await Promise.all([desktop.close(), phone.close()])
|
||||
}
|
||||
})
|
||||
|
||||
it('replaces only the panel content while sharing the invitation and restores the default when unloaded', async () => {
|
||||
const scaffold = await launchWebScaffold({
|
||||
remoteAuthority: 'qr-login.test', extraOverlayPath: REPLACEMENT_OVERLAY,
|
||||
extraInstallAnchors: [join(REPLACEMENT_FIXTURE, 'package.json')],
|
||||
})
|
||||
onTestFinished(() => scaffold.close())
|
||||
const desktop = await browser.newContext({ locale: ZH_BROWSER_LOCALE })
|
||||
try {
|
||||
const page = await desktop.newPage()
|
||||
const console = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl)
|
||||
const section = await remoteSettings(page)
|
||||
const created = page.waitForResponse(response => new URL(response.url()).pathname === '/api/remoteConnection/create')
|
||||
await createCode(page, section)
|
||||
const initial = await (await created).json() as { result: { value: { id: string } } }
|
||||
const invitationId = initial.result.value.id
|
||||
const svg = section.getByRole('img', { name: '一次性登录二维码' })
|
||||
const initialSvg = await svg.innerHTML()
|
||||
const nav = page.getByRole('dialog', { name: '设置', exact: true })
|
||||
.getByRole('button', { name: '远程连接', exact: true })
|
||||
const custom = page.getByRole('region', { name: '自定义远程连接', exact: true })
|
||||
|
||||
const replacement = await scaffold.ctx.loader.create({ name: '@fixture/remote-connection' })
|
||||
await custom.waitFor()
|
||||
expect(await nav.count()).toBe(1)
|
||||
expect(await section.count()).toBe(0)
|
||||
expect(await custom.getByRole('status', { name: '邀请编号' }).textContent()).toBe(invitationId)
|
||||
await custom.getByText('邀请状态: pending', { exact: true }).waitFor()
|
||||
await compareOrRefreshGolden(join(EXPECTED, 'replacement.expected.md'),
|
||||
await captureStableAria(page, 'section[aria-label="自定义远程连接"]', scaffold.workspaceCwd, {
|
||||
replacements: [[`${scaffold.baseUrl}/`, '{{access-address}}'], [invitationId, '{{invitation-id}}']],
|
||||
}), MODE)
|
||||
|
||||
await custom.getByRole('button', { name: '重新读取', exact: true }).click()
|
||||
await custom.getByText('邀请状态: pending', { exact: true }).waitFor()
|
||||
expect(await custom.getByRole('status', { name: '邀请编号' }).textContent()).toBe(invitationId)
|
||||
scaffold.ctx.loader.remove(replacement)
|
||||
await svg.waitFor()
|
||||
expect(await nav.count()).toBe(1)
|
||||
expect(await custom.count()).toBe(0)
|
||||
expect(await svg.innerHTML()).toBe(initialSvg)
|
||||
|
||||
const nextReplacement = await scaffold.ctx.loader.create({ name: '@fixture/remote-connection' })
|
||||
await custom.waitFor()
|
||||
await custom.getByRole('button', { name: '取消邀请', exact: true }).click()
|
||||
await custom.getByText('邀请状态: cancelled', { exact: true }).waitFor()
|
||||
expect(await custom.getByRole('status', { name: '邀请编号' }).textContent()).toBe('')
|
||||
const recreated = page.waitForResponse(response => new URL(response.url()).pathname === '/api/remoteConnection/create')
|
||||
await custom.getByRole('button', { name: '生成新邀请', exact: true }).click()
|
||||
const response = await recreated
|
||||
expect(response.status()).toBe(200)
|
||||
const next = await response.json() as { result: { ok: boolean; value: { id: string } } }
|
||||
expect(next.result.ok).toBe(true)
|
||||
expect(next.result.value.id).not.toBe(invitationId)
|
||||
await expect.poll(() => custom.getByRole('status', { name: '邀请编号' }).textContent()).toBe(next.result.value.id)
|
||||
await custom.getByRole('button', { name: '关闭设置', exact: true }).click()
|
||||
expect(await page.getByRole('dialog', { name: '设置', exact: true }).count()).toBe(0)
|
||||
scaffold.ctx.loader.remove(nextReplacement)
|
||||
expect(console.pageErrors).toEqual([])
|
||||
} finally {
|
||||
await desktop.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('signs in over HTTP and preserves the phone login after the desktop closes without allowing code reuse', async () => {
|
||||
const fixture = await launchRemoteConnectionFixture(false)
|
||||
const desktop = await browser.newContext({ locale: ZH_BROWSER_LOCALE })
|
||||
const phone = await browser.newContext({ locale: ZH_BROWSER_LOCALE, viewport: MOBILE })
|
||||
const stranger = await browser.newContext({ locale: ZH_BROWSER_LOCALE, viewport: MOBILE })
|
||||
try {
|
||||
const desktopPage = await desktop.newPage()
|
||||
await desktopPage.goto(fixture.authenticatedUrl)
|
||||
const section = await remoteSettings(desktopPage)
|
||||
await section.getByRole('button', { name: '生成登录二维码', exact: true }).waitFor()
|
||||
await snapshot(desktopPage, fixture, 'http-ready')
|
||||
const qrUrl = await createCode(desktopPage, section)
|
||||
expect(new URL(qrUrl).protocol).toBe('http:')
|
||||
expect(new URL(qrUrl).origin).toBe(new URL(fixture.url).origin)
|
||||
await snapshot(desktopPage, fixture, 'http-active')
|
||||
expect(await desktopPage.evaluate(() => window.isSecureContext)).toBe(false)
|
||||
await section.getByRole('button', { name: '复制登录链接', exact: true }).click()
|
||||
await desktopPage.getByText('链接已复制', { exact: true }).waitFor()
|
||||
await section.getByText('请勿公开分享登录链接', { exact: true }).waitFor()
|
||||
expect(await section.getByText('HTTP 会明文传输登录凭据,请仅在可信网络中使用', { exact: true }).count()).toBe(2)
|
||||
expect(await section.getByRole('img', { name: '一次性登录二维码' }).count()).toBe(1)
|
||||
await snapshot(desktopPage, fixture, 'http-link-copied')
|
||||
|
||||
const phonePage = await phone.newPage()
|
||||
const exchanged = phonePage.waitForResponse(response => new URL(response.url()).pathname === '/remote-login'
|
||||
&& response.request().method() === 'POST')
|
||||
await phonePage.goto(qrUrl)
|
||||
expect((await exchanged).status()).toBe(204)
|
||||
await phonePage.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
expect(phonePage.url()).toBe(fixture.url)
|
||||
expect((await phone.cookies()).filter(cookie => cookie.name.startsWith('dsh-remote-'))).toEqual([
|
||||
expect.objectContaining({ httpOnly: true, secure: false, sameSite: 'Strict', domain: 'qr-login.test' }),
|
||||
])
|
||||
expect((await phone.cookies()).filter(cookie => cookie.name.startsWith('dsh-auth-'))).toEqual([])
|
||||
expect(await phonePage.evaluate(async () => (await fetch('./', {
|
||||
method: 'HEAD', credentials: 'same-origin', cache: 'no-store', redirect: 'manual',
|
||||
})).status)).toBe(200)
|
||||
await desktop.close()
|
||||
|
||||
await phonePage.close()
|
||||
const returning = await phone.newPage()
|
||||
await returning.goto(fixture.url)
|
||||
await returning.getByRole('button', { name: '账号菜单', exact: true, includeHidden: true }).waitFor({ state: 'attached' })
|
||||
expect(returning.url()).toBe(fixture.url)
|
||||
|
||||
const reusedPage = await stranger.newPage()
|
||||
const refused = reusedPage.waitForResponse(response => new URL(response.url()).pathname === '/remote-login'
|
||||
&& response.request().method() === 'POST')
|
||||
await reusedPage.goto(qrUrl)
|
||||
expect((await refused).status()).toBe(410)
|
||||
await expect.poll(() => new URL(reusedPage.url()).hash).toBe('')
|
||||
expect((await stranger.cookies()).filter(cookie => cookie.name.startsWith('dsh-remote-'))).toEqual([])
|
||||
expect(await reusedPage.getByRole('button', { name: '账号菜单', exact: true }).count()).toBe(0)
|
||||
} finally {
|
||||
try {
|
||||
await Promise.all([desktop.close(), phone.close(), stranger.close()])
|
||||
} finally {
|
||||
await fixture.close()
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
+20
-35
@@ -80,8 +80,9 @@ import {
|
||||
type SessionHeader,
|
||||
} from '@deepseek-ai/dsh-session'
|
||||
import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
// Empty type imports carry the webServer/agents/sessionPersistence Context merges.
|
||||
import type {} from '@deepseek-ai/dsh-host-webserver'
|
||||
import type { WebEntryUrl } from '@deepseek-ai/dsh-host-webserver'
|
||||
// Empty type imports carry the webApp/agents Context merges.
|
||||
import type {} from '@deepseek-ai/dsh-web-app'
|
||||
import type {} from '@deepseek-ai/dsh-agent'
|
||||
import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
|
||||
import { startPrefixProxy, type PrefixProxy } from './prefix-proxy.ts'
|
||||
@@ -653,11 +654,11 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
|
||||
},
|
||||
},
|
||||
// The bundle's web-runtime row resolves the same built dist under test
|
||||
// (apps/web IS @deepseek-ai/dsh-web-frontend). The scaffold captures the real
|
||||
// WebApp-published login URL; Playwright owns browser opening.
|
||||
// (apps/web IS @deepseek-ai/dsh-web-frontend). Collect Token entries through
|
||||
// WebApp's event without printing credentials; Playwright owns browser opening.
|
||||
// Preserve the composed surface-context choice because a patch replaces
|
||||
// the row's complete config.
|
||||
{ id: 'web-runtime', config: { surfaceContext, openBrowser: false, printUrl: true } },
|
||||
{ id: 'web-runtime', config: { surfaceContext, openBrowser: false, printUrl: false } },
|
||||
...publicHost === undefined && options.remoteAuthority === undefined
|
||||
? []
|
||||
: [{
|
||||
@@ -852,37 +853,21 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise<We
|
||||
resolution,
|
||||
})
|
||||
await ctx.plugin(Loader)
|
||||
// Scaffold boots already own process.cwd() exclusively within their test worker.
|
||||
// Capture only this listener's login line, and restore console on failed boot too.
|
||||
const startupLogin = Promise.withResolvers<URL>()
|
||||
let startupLoginUrl: URL
|
||||
const originalLog = console.log
|
||||
console.log = (...args: unknown[]) => {
|
||||
const line = args.length === 1 && typeof args[0] === 'string' ? args[0] : ''
|
||||
const match = /^dsh web: (http:\/\/127\.0\.0\.1:\d+\/\?token=[A-Za-z0-9_-]+)$/u.exec(line)
|
||||
if (match !== null) {
|
||||
const url = new URL(match[1]!)
|
||||
const boundPort = ctx.get('webServer')?.port
|
||||
if (boundPort !== undefined && url.port === String(boundPort)) {
|
||||
startupLogin.resolve(url)
|
||||
return
|
||||
}
|
||||
}
|
||||
originalLog(...args)
|
||||
}
|
||||
let startupTimer: ReturnType<typeof setTimeout> | undefined
|
||||
try {
|
||||
await mountRootInclude(ctx, rootConfig, readProfilePatches('dsh', profileContext))
|
||||
await ctx.loader.await()
|
||||
await auditStartupEntries(ctx, 'web e2e scaffold')
|
||||
startupTimer = setTimeout(() => {
|
||||
startupLogin.reject(new Error('web e2e scaffold: token plugin did not publish its login URL'))
|
||||
}, 10_000)
|
||||
startupLoginUrl = await startupLogin.promise
|
||||
} finally {
|
||||
clearTimeout(startupTimer)
|
||||
console.log = originalLog
|
||||
await mountRootInclude(ctx, rootConfig, readProfilePatches('dsh', profileContext))
|
||||
await ctx.loader.await()
|
||||
await auditStartupEntries(ctx, 'web e2e scaffold')
|
||||
const advertised = new URL(ctx.webApp.getAdvertisedUrl())
|
||||
const entries: WebEntryUrl[] = []
|
||||
ctx.emit(ctx.webServer, 'webserver/entry-url', advertised.href, entries)
|
||||
const tokenEntries = entries.filter((entry) => {
|
||||
const url = new URL(entry.url)
|
||||
return url.origin === advertised.origin && url.pathname === advertised.pathname
|
||||
&& url.searchParams.getAll('token').length === 1 && Boolean(url.searchParams.get('token'))
|
||||
})
|
||||
if (tokenEntries.length !== 1) {
|
||||
throw new Error('web e2e scaffold: expected one Token provider login URL for this application')
|
||||
}
|
||||
const startupLoginUrl = new URL(tokenEntries[0]!.url)
|
||||
if (options.developerTools !== undefined) {
|
||||
await ctx.settings.update('ui-settings', { enabled: options.developerTools })
|
||||
}
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
// this client-registered project must not also hold them (one program
|
||||
// cannot see both sides of the cordis Context merges).
|
||||
"exclude": [
|
||||
"tests/remote-connection.e2e.ts",
|
||||
"tests/remote-connection-fixture.ts",
|
||||
"tests/home-whale.e2e.ts",
|
||||
"tests/sidebar-drawer.e2e.ts",
|
||||
"tests/session-panel-layout.e2e.ts",
|
||||
|
||||
@@ -7,6 +7,8 @@ A service can be a core spine service, a swappable capability seam, a bundle/com
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
pkg_client_remote_connection["client-remote-connection"]
|
||||
svc_remoteConnection["ctx.remoteConnection<br/>Remote browser login"]
|
||||
pkg_action_cards["action-cards"]
|
||||
svc_actionCards["ctx.actionCards<br/>Optional action cards"]
|
||||
pkg_creation_recommendations["creation-recommendations"]
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
pkg_client_remote_connection["client-remote-connection"]
|
||||
svc_remoteConnection["ctx.remoteConnection<br/>Remote browser login"]
|
||||
pkg_action_cards["action-cards"]
|
||||
svc_actionCards["ctx.actionCards<br/>Optional action cards"]
|
||||
pkg_creation_recommendations["creation-recommendations"]
|
||||
|
||||
@@ -583,6 +583,27 @@ export interface Config {
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-product-analytics -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-remote-connection -->
|
||||
<a id="deepseek-aidsh-client-remote-connection"></a>
|
||||
|
||||
## `@deepseek-ai/dsh-client-remote-connection`
|
||||
|
||||
- `inject`: `connection` · `connection.authentication` · `credentials` · `webServer` · `webApp`
|
||||
- `source`: [`packages/client/remote-connection/src/index.ts:27`](../packages/client/remote-connection/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Deployment timing for QR login and its settings status. */
|
||||
export interface Config {
|
||||
/** Absolute lifetime in days for Remote browser credentials; default 30. */
|
||||
cookieMaxAgeDays: number
|
||||
/** Invitation lifetime in milliseconds; expiry never renews an existing browser session. */
|
||||
ticketLifetimeMs: number
|
||||
/** Interval in milliseconds between the settings panel's status reads. */
|
||||
pollIntervalMs: number
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-remote-connection -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-shortcuts -->
|
||||
<a id="deepseek-aidsh-client-shortcuts"></a>
|
||||
|
||||
|
||||
@@ -585,6 +585,27 @@ export interface Config {
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-product-analytics -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-remote-connection -->
|
||||
<a id="deepseek-aidsh-client-remote-connection"></a>
|
||||
|
||||
## `@deepseek-ai/dsh-client-remote-connection`
|
||||
|
||||
- `inject`: `connection` · `connection.authentication` · `credentials` · `webServer` · `webApp`
|
||||
- `source`: [`packages/client/remote-connection/src/index.ts:27`](../packages/client/remote-connection/src/index.ts)
|
||||
|
||||
```ts config-catalog
|
||||
/** Deployment timing for QR login and its settings status. */
|
||||
export interface Config {
|
||||
/** Absolute lifetime in days for Remote browser credentials; default 30. */
|
||||
cookieMaxAgeDays: number
|
||||
/** Invitation lifetime in milliseconds; expiry never renews an existing browser session. */
|
||||
ticketLifetimeMs: number
|
||||
/** Interval in milliseconds between the settings panel's status reads. */
|
||||
pollIntervalMs: number
|
||||
}
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-remote-connection -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-client-shortcuts -->
|
||||
<a id="deepseek-aidsh-client-shortcuts"></a>
|
||||
|
||||
|
||||
@@ -21,8 +21,8 @@
|
||||
en: 3221d1076554001f
|
||||
zh: 29f166be6a5c04d9
|
||||
/development-guide/contributor-reference/typescript-project-layout:
|
||||
en: 16d67911ecaa50d3
|
||||
zh: f5259b0fbf022db3
|
||||
en: 894d70bbd7e7dab3
|
||||
zh: 2d4a48d1b44a95de
|
||||
/development-guide/contributor-reference/environment-variables:
|
||||
en: 9a0b2f1a520cfc68
|
||||
zh: 62c9ec565909f605
|
||||
|
||||
+1
-1
@@ -106,7 +106,7 @@ PR artifact builders run `build:artifacts`; required Linux and Windows normal bu
|
||||
|
||||
Both tsdown passes match `vendor/*`, `packages/*/*`, and `apps/cli`; the Host pass also matches `apps/desktop-host`. They neither scan build artifacts to discover Client packages nor maintain a Host/Client package filter list. Package-local tsdown configs select entries for the current phase through `DSH_BUILD_FACE`: an ordinary Client plugin produces both its Node loader and browser bundle during the Client phase; `api-remotes` uses `hostPhase: true` to produce its Host entry early and only its browser bundle during the Client phase. Tsdown consumes only the JavaScript emitted to `lib/types` by the preceding tsc phase. Tsdown builds the matched workspace members concurrently, so `apps/desktop`, whose main bundle inlines workspace devDependencies from their `lib/` output, bundles in its own step after the Host pass ([Desktop README](../apps/desktop/README.md#bundled-workspace-dependencies)).
|
||||
|
||||
Typert analyzes Host types through `tsconfig.host.json` and generates Host reflection and Host-for-Client Remote declarations before package compilation. The source-only [`generate-typert.ts`](../scripts/generate-typert.ts) pass rejects workspace imports that require built output, including metadata dependencies that return to generated declarations. Host tsdown lowers source decorators without generating metadata again; Client tsdown also consumes the existing metadata. `pnpm run typecheck` generates metadata, compiles Host and Client packages in reference order, and checks each aggregate with `tsc -b` after its package compilation. It skips the native addon, bundles, Web, and the client build record. `lint`, `lint:fix`, and `doc-typecheck` prepare metadata and Host package declarations through `compile-referenced-projects.ts host-contracts`; generation failure stops dependent compilation. These declaration-only commands do not update runtime bundles: run `build:artifacts` before launching or testing built output.
|
||||
Typert analyzes Host types through `tsconfig.host.json` and generates Host reflection and Host-for-Client Remote declarations before package compilation. The source-only [`generate-typert.ts`](../scripts/generate-typert.ts) pass rejects workspace imports that require built output, including metadata dependencies that return to generated declarations. Host tsdown lowers source decorators without generating metadata again; Client tsdown also consumes the existing metadata. `pnpm run typecheck` generates metadata, compiles Host and Client packages in reference order, and checks each aggregate with `tsc -b` after its package compilation. It skips the native addon, bundles, Web, and the client build record. `lint`, `lint:fix`, and `doc-typecheck` prepare metadata and Host package declarations through `compile-referenced-projects.ts host-contracts`; generation failure stops dependent compilation. These declaration-only commands do not update runtime bundles: run `build:artifacts` before launching or testing built output. Documentation fences use `ts` for Host APIs and `ts client` for Client APIs; the checker compiles each face separately with its aggregate options and package references.
|
||||
|
||||
`pnpm run build` and `build:artifacts` embed the root package version, the seven-character source commit, and a dirty marker when Git reports local changes; they also inherit other caller-supplied `DSH_CLIENT_*` values. `pnpm run build:official` is the cross-platform local equivalent of the CI and release artifact build and omits the local dirty marker. Each successful `build` or `build:artifacts` writes a gitignored record that binds the exact public values to the Vite output and dynamic client bundles; release packing and built Web tests reject a missing record or artifacts changed by a later partial build. `pnpm run dev:web` runs `build:artifacts` first (`--skip-build` reuses an existing artifact tree instead), then samples the current version and Git state once and shares that environment across every watcher stage for the session; it does not validate the complete-build record because the watcher stages rewrite its recorded artifacts.
|
||||
|
||||
|
||||
@@ -110,7 +110,7 @@ PR 产物 builder 运行 `build:artifacts`;必需的 Linux 与 Windows 普通
|
||||
|
||||
两次 tsdown 都匹配 `vendor/*`、`packages/*/*` 与 `apps/cli`,Host 阶段另外匹配 `apps/desktop-host`;两者都不扫描构建产物来发现 Client 包,也不维护 Host/Client 包过滤表。包内 tsdown 配置根据 `DSH_BUILD_FACE` 决定当前阶段的入口:普通 Client 插件在 Client 阶段同时生成 Node loader 与 browser bundle;`api-remotes` 通过 `hostPhase: true` 提前生成 Host 入口,再在 Client 阶段只生成 browser bundle。tsdown 只消费 `lib/types` 中由前置 tsc 发射的 JavaScript。tsdown 并发构建匹配到的 workspace 成员;`apps/desktop` 的主进程 bundle 需要从工作区 devDependencies 的 `lib/` 产物内联这些包,因此在 Host 阶段之后单独一步打 bundle([Desktop README](../apps/desktop/README.zh.md#bundled-workspace-dependencies))。
|
||||
|
||||
Typert 通过 `tsconfig.host.json` 分析 Host 类型,在包编译之前生成 Host 反射和 Host-for-Client Remote 声明。仅源码的 [`generate-typert.ts`](../scripts/generate-typert.ts) 阶段拒绝依赖构建产物的工作区导入,包括经由依赖回到生成声明的元数据依赖。Host tsdown 转换源码装饰器,但不重复生成元数据;Client tsdown 同样使用已有元数据。`pnpm run typecheck` 生成元数据,按 reference 顺序编译 Host 与 Client 包,并在每个 aggregate 的包编译完成后以 `tsc -b` 检查它。该命令跳过 native addon、bundle、Web 和 client build record。`lint`、`lint:fix` 与 `doc-typecheck` 通过 `compile-referenced-projects.ts host-contracts` 准备元数据与 Host 包声明;生成失败时不启动依赖它的编译。这些仅生成声明的命令不更新运行时 bundle;启动或测试构建产物之前应运行 `build:artifacts`。
|
||||
Typert 通过 `tsconfig.host.json` 分析 Host 类型,在包编译之前生成 Host 反射和 Host-for-Client Remote 声明。仅源码的 [`generate-typert.ts`](../scripts/generate-typert.ts) 阶段拒绝依赖构建产物的工作区导入,包括经由依赖回到生成声明的元数据依赖。Host tsdown 转换源码装饰器,但不重复生成元数据;Client tsdown 同样使用已有元数据。`pnpm run typecheck` 生成元数据,按 reference 顺序编译 Host 与 Client 包,并在每个 aggregate 的包编译完成后以 `tsc -b` 检查它。该命令跳过 native addon、bundle、Web 和 client build record。`lint`、`lint:fix` 与 `doc-typecheck` 通过 `compile-referenced-projects.ts host-contracts` 准备元数据与 Host 包声明;生成失败时不启动依赖它的编译。这些仅生成声明的命令不更新运行时 bundle;启动或测试构建产物之前应运行 `build:artifacts`。 文档围栏用 `ts` 表示 Host API,用 `ts client` 表示 Client API;检查器使用各自的聚合选项与包引用分别编译两侧。
|
||||
|
||||
`pnpm run build` 与 `build:artifacts` 会内联根包版本、七位源码 commit,并在 Git 报告本地变化时内联 dirty 标记;调用方提供的其他 `DSH_CLIENT_*` 值也会被继承。`pnpm run build:official` 是与 CI 和 release 产物构建等价的跨平台本地命令,并省略本地 dirty 标记。每次 `build` 或 `build:artifacts` 成功后都会写入一份被 gitignore 的记录,把精确公开值与 Vite 输出及动态 client bundle 绑定;release 打包和 built Web 测试会拒绝缺少记录或被后续局部构建改动的产物。`pnpm run dev:web` 会先执行 `build:artifacts`(`--skip-build` 则复用现有产物树),再读取一次当前版本和 Git 状态,并在本次会话的所有 watcher stage 之间共享该环境;它不会校验完整构建记录,因为 watcher stage 会重写记录覆盖的产物。
|
||||
|
||||
|
||||
@@ -163,6 +163,7 @@ flowchart TD
|
||||
pkg_client_locale["client-locale"]
|
||||
pkg_client_modules["client-modules"]
|
||||
pkg_client_product_analytics["client-product-analytics"]
|
||||
pkg_client_remote_connection["client-remote-connection"]
|
||||
pkg_client_resources["client-resources"]
|
||||
pkg_client_script_realm["client-script-realm"]
|
||||
pkg_client_script_realm_iframe["client-script-realm-iframe"]
|
||||
|
||||
@@ -165,6 +165,7 @@ flowchart TD
|
||||
pkg_client_locale["client-locale"]
|
||||
pkg_client_modules["client-modules"]
|
||||
pkg_client_product_analytics["client-product-analytics"]
|
||||
pkg_client_remote_connection["client-remote-connection"]
|
||||
pkg_client_resources["client-resources"]
|
||||
pkg_client_script_realm["client-script-realm"]
|
||||
pkg_client_script_realm_iframe["client-script-realm-iframe"]
|
||||
|
||||
@@ -188,6 +188,42 @@ Types: [AuthenticationProvider](../../packages/client/connection/README.md#brows
|
||||
|
||||
Source: [`packages/client/connection/src/authentication.ts`](../../packages/client/connection/src/authentication.ts)
|
||||
|
||||
<a id="ctxremoteconnection--remoteconnection"></a>
|
||||
|
||||
### `ctx.remoteConnection` — `RemoteConnection`
|
||||
|
||||
One outstanding invitation, issued by an owner and consumed by a new browser.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Read prerequisites and the state of one invitation without disclosing its credential.
|
||||
* @param id - invitation to inspect, or null to inspect only deployment prerequisites.
|
||||
* @returns deployment availability and invitation state, with the polling interval.
|
||||
*/
|
||||
@Remote status(id: RemoteLoginId | null): RemoteConnectionStatus
|
||||
|
||||
/**
|
||||
* Authorize a new browser by generating a one-use login invitation; replaces any older invitation.
|
||||
* @returns the invitation credential and its fixed expiry.
|
||||
*/
|
||||
@Remote create(): RemoteLoginTicket
|
||||
|
||||
/**
|
||||
* Read the advertised URL carrying the process launch token; QR invitations are unchanged.
|
||||
* @returns owner-only login URL, reusable until the Host process restarts; never persist or log it.
|
||||
*/
|
||||
@Remote loginUrl(): string
|
||||
|
||||
/**
|
||||
* Cancel an unused invitation; this never revokes a browser session already issued.
|
||||
* @param id - invitation being cancelled; an older ID cannot cancel a replacement.
|
||||
* @returns the invitation's final state, including used when a redemption won the race.
|
||||
*/
|
||||
@Remote cancel(id: RemoteLoginId): RemoteLoginState
|
||||
```
|
||||
|
||||
Source: [`packages/client/remote-connection/src/index.ts`](../../packages/client/remote-connection/src/index.ts)
|
||||
|
||||
<a id="ctxwebapp--webapp"></a>
|
||||
|
||||
### `ctx.webApp` — `WebApp`
|
||||
|
||||
@@ -188,6 +188,42 @@ Types: [AuthenticationProvider](../../packages/client/connection/README.zh.md#br
|
||||
|
||||
Source: [`packages/client/connection/src/authentication.ts`](../../packages/client/connection/src/authentication.ts)
|
||||
|
||||
<a id="ctxremoteconnection--remoteconnection"></a>
|
||||
|
||||
### `ctx.remoteConnection` — `RemoteConnection`
|
||||
|
||||
One outstanding invitation, issued by an owner and consumed by a new browser.
|
||||
|
||||
```ts cordis-catalog
|
||||
/**
|
||||
* Read prerequisites and the state of one invitation without disclosing its credential.
|
||||
* @param id - invitation to inspect, or null to inspect only deployment prerequisites.
|
||||
* @returns deployment availability and invitation state, with the polling interval.
|
||||
*/
|
||||
@Remote status(id: RemoteLoginId | null): RemoteConnectionStatus
|
||||
|
||||
/**
|
||||
* Authorize a new browser by generating a one-use login invitation; replaces any older invitation.
|
||||
* @returns the invitation credential and its fixed expiry.
|
||||
*/
|
||||
@Remote create(): RemoteLoginTicket
|
||||
|
||||
/**
|
||||
* Read the advertised URL carrying the process launch token; QR invitations are unchanged.
|
||||
* @returns owner-only login URL, reusable until the Host process restarts; never persist or log it.
|
||||
*/
|
||||
@Remote loginUrl(): string
|
||||
|
||||
/**
|
||||
* Cancel an unused invitation; this never revokes a browser session already issued.
|
||||
* @param id - invitation being cancelled; an older ID cannot cancel a replacement.
|
||||
* @returns the invitation's final state, including used when a redemption won the race.
|
||||
*/
|
||||
@Remote cancel(id: RemoteLoginId): RemoteLoginState
|
||||
```
|
||||
|
||||
Source: [`packages/client/remote-connection/src/index.ts`](../../packages/client/remote-connection/src/index.ts)
|
||||
|
||||
<a id="ctxwebapp--webapp"></a>
|
||||
|
||||
### `ctx.webApp` — `WebApp`
|
||||
|
||||
@@ -351,6 +351,9 @@
|
||||
- id: ui-settings-general
|
||||
name: '@deepseek-ai/dsh-client-ui-settings-general'
|
||||
|
||||
- id: remote-connection
|
||||
name: '@deepseek-ai/dsh-client-remote-connection'
|
||||
|
||||
- id: ui-settings-models
|
||||
name: '@deepseek-ai/dsh-client-ui-settings-models'
|
||||
|
||||
|
||||
@@ -206,7 +206,8 @@
|
||||
"@deepseek-ai/dsh-workspace-changes": "workspace:*",
|
||||
"@deepseek-ai/schemastery": "workspace:~",
|
||||
"commander": "^15.0.0",
|
||||
"open": "^11.0.2"
|
||||
"open": "^11.0.2",
|
||||
"@deepseek-ai/dsh-client-remote-connection": "workspace:*"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/client/remote-connection/README.md
|
||||
/:
|
||||
en: 747fceec0b2fd3df
|
||||
zh: 1f806c1a71af1fba
|
||||
/deepseek-ai-dsh-client-remote-connection:
|
||||
en: 9bbd5b81d7f513ef
|
||||
zh: ba7d27a7b0f22dc9
|
||||
/deepseek-ai-dsh-client-remote-connection/summary:
|
||||
en: 639f29d44170cd2e
|
||||
zh: 91cb391d44fe3bf5
|
||||
/deepseek-ai-dsh-client-remote-connection/table-of-contents:
|
||||
en: a8ab0782b134a4da
|
||||
zh: b196ee5c0a5f157c
|
||||
/deepseek-ai-dsh-client-remote-connection/use-this-package:
|
||||
en: d2802227f1461f13
|
||||
zh: 4f6823bf57d429ea
|
||||
/deepseek-ai-dsh-client-remote-connection/authentication-and-failures:
|
||||
en: ca35b7a697425c27
|
||||
zh: 27304a45419b8b66
|
||||
/deepseek-ai-dsh-client-remote-connection/replace-the-settings-panel:
|
||||
en: df50aaf4c14e2907
|
||||
zh: 7dbacb9020d65470
|
||||
/deepseek-ai-dsh-client-remote-connection/further-exploration:
|
||||
en: dc8b05a29d545c8e
|
||||
zh: 81e6fb89db3c962e
|
||||
/deepseek-ai-dsh-client-remote-connection/model-experience:
|
||||
en: 2c60f5547f835f44
|
||||
zh: 47ade6e0a0b55b15
|
||||
/deepseek-ai-dsh-client-remote-connection/model-experience/kv-cache-effect:
|
||||
en: 4f912e6f343086de
|
||||
zh: e5435b3281ad1820
|
||||
/deepseek-ai-dsh-client-remote-connection/known-limitations-and-deferred-work:
|
||||
en: 4d3a1aa37bd7b9b5
|
||||
zh: 3de7b0d55b80afea
|
||||
/deepseek-ai-dsh-client-remote-connection/known-limitations-and-deferred-work/dev-note:
|
||||
en: b836f01bd0bceb4a
|
||||
zh: 25e979141fbe5501
|
||||
@@ -0,0 +1,96 @@
|
||||
---
|
||||
description: "Remote login through a single-use QR code or a private tokenized link."
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
# @deepseek-ai/dsh-client-remote-connection
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
The settings panel separates QR code login and link login. A signed-in owner can generate a one-use QR code or copy a tokenized URL to sign another browser into the same Host. QR redemption issues a Remote browser cookie; copied links continue to use the independent Token login. The QR code, countdown, and credential warning stack vertically; expiry appears as a warning banner. Credential warnings appear only after generation or successful copying. The login link displays its token and fades at the right edge. Clipboard outcomes use a shell toast that survives closing settings.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Use this package](#use-this-package)
|
||||
- [Authentication and failures](#authentication-and-failures)
|
||||
- [Replace the settings panel](#replace-the-settings-panel)
|
||||
- [Further Exploration](#further-exploration)
|
||||
- [Model Experience](#model-experience)
|
||||
- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
|
||||
|
||||
## 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. QR actions share the title row on wide cards and stack at full width below the title on narrow cards. Panel actions use the shared `Button`'s compact size, and the login-link field matches their height. The copy button reserves its label width across copying and copied states so the link field stays in place. The expiry banner sits below the QR header and spans the card's content width. The scan/countdown row and credential warning have the same width. 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 without a success message.
|
||||
|
||||
The advertised application URL 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.
|
||||
|
||||
`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.
|
||||
|
||||
## Authentication and failures
|
||||
|
||||
The QR contains an independently generated 256-bit credential in the URL fragment, never the process launch token. The public `remote-login` page removes the fragment and exchanges it with a same-origin POST. GET and HEAD do not redeem it. WebServer checks the request source before the anonymous route runs. Remote checks the advertised authority, consumes the credential once, and signs its own owner browser cookie. Redeemed, expired, cancelled, replaced, and pre-restart invitations cannot be exchanged again.
|
||||
|
||||
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. An interrupted exchange may already have issued the cookie; the page offers a clean application link to check the result and never retries the one-use credential automatically.
|
||||
|
||||
The owner-only `loginUrl()` method reads the 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. A changed URL clears the previous copy-success state and notice. A failed link read changes the copy button to Retry without blocking QR creation; a refused clipboard write reports failure and leaves copying retryable without showing a success warning. 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.
|
||||
|
||||
Remote also owns the root anonymous HTML. A trusted but unauthenticated GET receives the login document with HTTP 401; HEAD retains 401 without a body. The document exposes no Token value or private application injections. The Token form appears only when Token publishes an entry. Authenticated requests render the existing application with their actual Peer and no second credential check. Source rejection remains 403, and authentication failure without another successful provider remains 503.
|
||||
|
||||
## Replace the settings panel
|
||||
|
||||
The root-scoped, single `settings.remoteConnection.content` slot replaces the whole panel while retaining its one settings navigation entry. 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.
|
||||
|
||||
Register a replacement component from your Client plugin with a lower priority than the default panel's `0`:
|
||||
|
||||
```ts client
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type { FunctionComponent } from 'react'
|
||||
import type { RemoteConnectionContentProps } from '@deepseek-ai/dsh-client-remote-connection/client'
|
||||
|
||||
declare const CustomPanel: FunctionComponent<RemoteConnectionContentProps>
|
||||
|
||||
export const inject = ['slots']
|
||||
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.slots.inject('settings.remoteConnection.content', () => ctx.slots.register({
|
||||
name: 'settings.remoteConnection.content',
|
||||
priority: -1,
|
||||
}, CustomPanel))
|
||||
}
|
||||
```
|
||||
|
||||
`slots.inject` supports loading the replacement before the default plugin and re-registers it when the slot owner returns. Unloading the replacement restores the default panel and its current state; unloading the Remote connection plugin removes the content slot, 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.
|
||||
|
||||
## Further Exploration
|
||||
|
||||
- [Web server subsystem](../../../docs/subsystems/web-server.md) — browser services and settings contributions.
|
||||
- [Connection](../connection/README.md) — request-source policy, provider registration, and Peer ownership.
|
||||
|
||||
## Model Experience
|
||||
|
||||
None, as this package provides browser authentication and contributes no model input.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
None; this package neither assembles nor sends model requests.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- Before redemption, anyone with the QR can redeem it first. Expiry and single use limit exposure; they do not prevent credential forwarding or phishing. A previewer that executes JavaScript may consume the code.
|
||||
- Login belongs to the browser that completes the exchange. A scanner's embedded browser and an installed PWA may use different cookie stores. Clearing cookies, changing the Host authority, or cookie expiry requires signing in again.
|
||||
- The resulting browser has owner access. Remote cookies share one runtime Peer, with no per-device permission or revocation list. Cancelling a QR does not revoke an issued cookie. Cookie expiry rejects new requests and connections; it does not terminate an already-admitted WebSocket. Unloading Remote closes its shared Peer and connections, independently of Token connections.
|
||||
- The Host must remain running and reachable after the original browser closes. This plugin supplies neither tunnelling nor remote wake-up.
|
||||
|
||||
### Dev Note
|
||||
|
||||
<details>
|
||||
<summary>Working context for maintainers</summary>
|
||||
|
||||
None.
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,102 @@
|
||||
---
|
||||
description: "通过一次性二维码或带私密 token 的链接远程登录。"
|
||||
kind: "package-reference"
|
||||
---
|
||||
|
||||
# @deepseek-ai/dsh-client-remote-connection
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
## 概述
|
||||
|
||||
设置面板将二维码登录与链接登录分为两个区块。已登录的 owner 可以生成一次性二维码,或复制带 token 的 URL,让另一个浏览器登录同一 Host。二维码兑换签发 Remote 浏览器 cookie;复制链接继续使用独立的 Token 登录。二维码、倒计时和凭据告警纵向排列;二维码过期时显示告警 banner。凭据告警仅在生成二维码或成功复制链接后出现。登录链接直接显示 token,并在右侧渐隐。复制结果通过关闭设置后仍可见的外壳 toast 提示成功或失败。
|
||||
|
||||
## 目录
|
||||
|
||||
- [使用本包](#use-this-package)
|
||||
- [认证与失败处理](#authentication-and-failures)
|
||||
- [替换设置面板](#replace-the-settings-panel)
|
||||
- [进一步探索](#further-exploration)
|
||||
- [模型体验](#model-experience)
|
||||
- [已知限制与延期工作](#known-limitations-and-deferred-work)
|
||||
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
Web bundle 挂载此插件。Host 端依赖 `connection`、`connection.authentication`、`credentials`、`webServer` 和 `webApp`,Client 端通过 `settings.section` 提供面板。移除插件会移除页面、端点、待使用的邀请和 Remote Peer。已签发的 Remote cookie 需要该提供者处于活动状态;插件使用同一凭据记录重新加载后,有效 cookie 可以继续使用。设置面板支持产品提供的全部八种界面语言;匿名登录页支持英文和中文。两张卡片的标题均位于边框内。宽卡片中的二维码操作与标题同行,窄卡片中则在标题下方纵向排列并占满宽度。面板操作使用共享 `Button` 的紧凑尺寸,登录链接框与按钮等高。复制按钮为复制中和已复制等状态预留文案宽度,使链接框保持原位。过期 banner 位于二维码卡片标题栏下方,占满卡片内容宽度。扫码说明与倒计时所在行和凭据告警等宽。重新生成正在显示的二维码时,仅用加载状态替换二维码图像;倒计时、告警和链接操作保持原位。取消后直接收起二维码预览,不显示成功提示。
|
||||
|
||||
公布的应用 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 会明文传输登录凭据。
|
||||
|
||||
`cookieMaxAgeDays` 默认为 30,固定每份 Remote cookie 的绝对有效期。`ticketLifetimeMs` 默认为 120000。`pollIntervalMs` 默认为 1000,控制设置面板显示二维码时的状态检查间隔。每个插件实例同一时间只有一个待使用邀请:生成新邀请会替换旧邀请,取消旧邀请不会取消替代它的新邀请。
|
||||
|
||||
<a id="authentication-and-failures"></a>
|
||||
## 认证与失败处理
|
||||
|
||||
二维码在 URL fragment 中携带独立生成的 256 位凭据,始终不使用进程启动 token。公开的 `remote-login` 页面移除 fragment,并通过同源 POST 兑换凭据。GET 和 HEAD 不会兑换凭据。WebServer 在执行匿名路由前检查请求来源。Remote 检查公布地址的 authority,消费一次性凭据,再签发自己的 owner 浏览器 cookie。已兑换、过期、取消、被替换和重启前生成的邀请均不能再次兑换。
|
||||
|
||||
只有已认证的 owner 可以创建、查询或取消邀请。Host 保留凭据摘要,不保留可重复使用的明文。公开页面不包含已认证应用的初始化注入,也不会向第三方发送凭据。兑换中断时 cookie 可能已经签发;页面提供干净的应用链接以检查结果,不会自动重试一次性凭据。
|
||||
|
||||
仅供 owner 调用的 `loginUrl()` 读取通过 `webserver/entry-url` 发布的 Token 入口,返回公布的根地址,并在 `?token=…` 中携带其进程启动 token。未启用 Token 认证的 Host 无法提供此链接,二维码登录仍可使用。与二维码邀请不同,此链接可以重复使用,直到 Host 进程重启。复制链接不会创建、消费或替换二维码邀请。Client 仅在确认部署可用后预取 URL,在插件内存中保留,以右侧渐隐方式显示,并在重连时刷新。URL 变化后会清除旧的复制成功状态和提示。读取链接失败时,复制按钮原位变为重试,不阻塞二维码生成;剪贴板拒绝写入时报告失败,保留重试能力,不显示复制成功后的告警。链接读取结果和复制结果均不持久保存或写入日志。
|
||||
|
||||
Remote 拥有持久的 `client-remote-connection/browser-session` 凭据记录。其签名密钥和 v1 cookie 格式独立于 Token;cookie 绑定监听协议与规范化 Host,携带固定签发及到期时间,并使用 `HttpOnly`、`SameSite=Strict` 和 `Path=/`。验证不续期。记录损坏会使插件激活失败,不会替换密钥。保留此记录可让有效登录跨重启继续使用;替换或删除记录会在下次激活时使旧 cookie 失效。
|
||||
|
||||
Remote 也拥有根地址的匿名 HTML。来源可信但尚未登录的 GET 返回 HTTP 401 登录文档,HEAD 保留 401 且不返回正文。文档不暴露 Token 值或私有应用注入,仅在 Token 发布入口时显示 Token 表单。已认证请求使用实际 Peer 渲染原应用,不再次验证凭据。来源拒绝保持 403;认证故障且没有其它成功提供者时保持 503。
|
||||
|
||||
<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` 命名空间。
|
||||
|
||||
在 Client 插件中注册替换组件,优先级应低于默认面板的 `0`:
|
||||
|
||||
```ts client
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type { FunctionComponent } from 'react'
|
||||
import type { RemoteConnectionContentProps } from '@deepseek-ai/dsh-client-remote-connection/client'
|
||||
|
||||
declare const CustomPanel: FunctionComponent<RemoteConnectionContentProps>
|
||||
|
||||
export const inject = ['slots']
|
||||
|
||||
export function apply(ctx: Context): void {
|
||||
ctx.slots.inject('settings.remoteConnection.content', () => ctx.slots.register({
|
||||
name: 'settings.remoteConnection.content',
|
||||
priority: -1,
|
||||
}, CustomPanel))
|
||||
}
|
||||
```
|
||||
|
||||
`slots.inject` 支持先加载替换插件,并在插槽所有者重新出现时恢复注册。卸载替换插件会恢复默认面板及其当前状态;卸载远程连接插件则移除内容插槽、停止轮询、立即丢弃链接凭据和复制提示,并等待进行中的读取、剪贴板写入和排队刷新完成。仅在 `phase === 'pending'` 时将 `ticket.url` 显示为二维码:结果不确定的操作可能保留票据用于恢复,但不允许展示。不得持久保存或记录任一凭据 URL。替换此面板不会替换匿名登录页面或 Host 邀请协议。
|
||||
|
||||
<a id="further-exploration"></a>
|
||||
## 进一步探索
|
||||
|
||||
- [Web 服务器子系统](../../../docs/subsystems/web-server.zh.md) — 浏览器服务与设置贡献。
|
||||
- [Connection](../connection/README.zh.md) — 请求来源策略、提供者注册与 Peer 所有权。
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
无;此包提供浏览器认证,不贡献模型输入。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
无;此包不组装或发送模型请求。
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
## 已知限制与延期工作
|
||||
|
||||
- 兑换前,任何取得二维码的人都可能抢先兑换。过期和单次使用限制暴露范围,无法防止凭据转发或钓鱼。执行 JavaScript 的预览器可能消费二维码。
|
||||
- 登录状态属于完成兑换的浏览器。扫码器的内置浏览器和已安装的 PWA 可能使用不同 cookie 存储。清除 cookie、更改 Host authority 或 cookie 过期后需要重新登录。
|
||||
- 登录后的浏览器拥有 owner 权限。Remote cookie 共用一个运行时 Peer,没有按设备划分的权限或撤销列表。取消二维码不会撤销已签发的 cookie。cookie 过期会拒绝新请求与新连接,不会终止已经准入的 WebSocket。卸载 Remote 会关闭其共享 Peer 与连接,不影响 Token 连接。
|
||||
- 原浏览器关闭后,Host 仍须运行且可访问。此插件不提供隧道或远程唤醒。
|
||||
|
||||
### 开发备注
|
||||
|
||||
<details>
|
||||
<summary>维护者工作上下文</summary>
|
||||
|
||||
无。
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Remote-Verbindung",
|
||||
"description": "Melden Sie einen weiteren Browser mit einem kurzlebigen QR-Code zur einmaligen Verwendung an."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Remote connection",
|
||||
"description": "Sign another browser in with a short-lived, single-use QR code."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Conexión remota",
|
||||
"description": "Inicia sesión en otro navegador con un código QR temporal de un solo uso."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Connexion à distance",
|
||||
"description": "Connectez un autre navigateur avec un code QR temporaire à usage unique."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "リモート接続",
|
||||
"description": "短時間有効な使い捨て QR コードで別のブラウザーにログインします。"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Conexão remota",
|
||||
"description": "Entre em outro navegador com um código QR temporário de uso único."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Удалённое подключение",
|
||||
"description": "Войдите в другом браузере с помощью временного одноразового QR-кода."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "远程连接",
|
||||
"description": "通过短时、单次二维码登录另一个浏览器。"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-client-remote-connection",
|
||||
"description": "Settings panel and single-use QR login for another browser",
|
||||
"version": "0.2.2-rc.2",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
|
||||
"directory": "packages/client/remote-connection"
|
||||
},
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./lib/types/client/index.d.ts",
|
||||
"default": "./lib/client.js"
|
||||
},
|
||||
"./types": {
|
||||
"types": "./lib/types/types.d.ts"
|
||||
},
|
||||
"./typert": {
|
||||
"types": "./lib/typert.host.d.ts",
|
||||
"default": "./lib/typert.host.js"
|
||||
},
|
||||
"./remote": {
|
||||
"types": "./lib/typert.remote-client.d.ts",
|
||||
"default": "./lib/typert.remote-client.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json",
|
||||
"./locale/*.json": "./locale/*.json"
|
||||
},
|
||||
"dsh": {
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-api-remotes",
|
||||
"@deepseek-ai/dsh-client-locale",
|
||||
"@deepseek-ai/dsh-client-ui-settings-general"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"bundle": "tsdown",
|
||||
"watch": "tsdown --watch"
|
||||
},
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"locale/*.json",
|
||||
"lib/index.js",
|
||||
"lib/client.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"lib/**/*.js.map",
|
||||
"lib/typert.host.js",
|
||||
"lib/typert.host.d.ts",
|
||||
"lib/typert.remote-client.js",
|
||||
"lib/typert.remote-client.d.ts",
|
||||
"lib/typert.remote-client.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
|
||||
"@deepseek-ai/dsh-brand": "workspace:*",
|
||||
"@deepseek-ai/schemastery": "workspace:~",
|
||||
"zod": "4.6.6"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/dsh-credentials": "workspace:*",
|
||||
"@deepseek-ai/dsh-error": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-client-connection": "workspace:*",
|
||||
"@deepseek-ai/dsh-host-webserver": "workspace:*",
|
||||
"@deepseek-ai/dsh-web-app": "workspace:*",
|
||||
"@deepseek-ai/dsh-api-remotes": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-locale": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-store": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-renderer": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-layout": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-test-runtime": "workspace:*",
|
||||
"@deepseek-ai/dsh-remote-mock": "workspace:*",
|
||||
"@deepseek-ai/dsh-credentials": "workspace:*",
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"react": "^18.2.0",
|
||||
"qrcode.react": "^4.2.0",
|
||||
"@deepseek-ai/dsh-client-ui-settings": "workspace:*",
|
||||
"@deepseek-ai/dsh-api-gateway": "workspace:*",
|
||||
"@deepseek-ai/dsh-typert-registry": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-settings-general": "workspace:*",
|
||||
"@deepseek-ai/dsh-host-authentication-token": "workspace:*",
|
||||
"@deepseek-ai/dsh-host-frontend-static": "workspace:*",
|
||||
"@deepseek-ai/dsh-error": "workspace:*"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/** Clipboard feedback that survives closing the settings panel. */
|
||||
import { IconWarningOutlineMedium, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { LoginLinkFace } from './login-link-controller.ts'
|
||||
|
||||
/**
|
||||
* Present successful and failed clipboard writes outside the settings panel.
|
||||
* @param props - renderer-bound feedback, dismissal action, and localized copy.
|
||||
* @returns the latest clipboard toast, or nothing.
|
||||
*/
|
||||
export function LoginLinkToast({ useLoginLink, dismissCopyNotice, t }: PropsRuntime<'shell.overlay'> & InjectFace<LoginLinkFace> & PropsLocale<'remoteConnection'>) {
|
||||
const { notice, sequence } = useLoginLink(state => state)
|
||||
if (notice === null) return null
|
||||
return <Toast key={sequence} text={t(notice)} onDone={() => { dismissCopyNotice(sequence) }}
|
||||
{...notice === 'linkCopied' ? { tone: 'success' as const } : { icon: <IconWarningOutlineMedium /> }} />
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
.section {
|
||||
container-type: inline-size;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
width: 100%;
|
||||
max-width: 720px;
|
||||
min-width: 0;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cardHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.methodTitle {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
line-height: 22px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
line-height: 24px;
|
||||
}
|
||||
|
||||
.description,
|
||||
.qrDetails,
|
||||
.notice,
|
||||
.warning,
|
||||
.error {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.description,
|
||||
.qrDetails {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
min-width: 0;
|
||||
box-sizing: border-box;
|
||||
padding: 16px;
|
||||
border: 0.5px solid var(--dsw-alias-settings-card-stroke);
|
||||
border-radius: var(--dsw-radius-xl);
|
||||
background: var(--dsw-alias-settings-card-fill);
|
||||
}
|
||||
|
||||
.cardBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.symbol {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 240px;
|
||||
max-width: 100%;
|
||||
aspect-ratio: 1 / 1;
|
||||
margin-inline: auto;
|
||||
}
|
||||
|
||||
.qr {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
aspect-ratio: 1 / 1;
|
||||
border-radius: var(--dsw-radius-md);
|
||||
background: var(--dsw-static-neutral-00);
|
||||
}
|
||||
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.placeholder {
|
||||
/* Reserve the countdown and warning height while replacing the QR. */
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.qrActions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
max-width: 100%;
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
|
||||
.qrActions > button {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.linkRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.linkPreview {
|
||||
flex: 1;
|
||||
box-sizing: border-box;
|
||||
height: 28px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
padding: 3px 10px;
|
||||
border: 0.5px solid var(--dsw-alias-border-l2);
|
||||
border-radius: var(--dsw-radius-sm);
|
||||
}
|
||||
|
||||
.linkUrl {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
mask-image: linear-gradient(to right, var(--dsw-alias-label-primary) 55%, transparent 98%);
|
||||
}
|
||||
|
||||
.linkRow > button {
|
||||
flex: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.copyLabel {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
}
|
||||
|
||||
.copyLabel > span {
|
||||
grid-area: 1 / 1;
|
||||
}
|
||||
|
||||
.copyLabelSizer {
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.qrDetails {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
column-gap: 12px;
|
||||
row-gap: 4px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.countdown {
|
||||
flex: none;
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.caution {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 12px;
|
||||
border: 0.5px solid color-mix(in srgb, var(--dsw-alias-state-warn-primary) 40%, transparent);
|
||||
border-radius: var(--dsw-radius-lg);
|
||||
background: var(--dsw-alias-state-warn-tertiary);
|
||||
}
|
||||
|
||||
.cautionIcon {
|
||||
display: inline-flex;
|
||||
flex: none;
|
||||
margin-top: 2px;
|
||||
color: var(--dsw-alias-state-warn-primary);
|
||||
}
|
||||
|
||||
.cautionBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cautionTitle {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.error {
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--dsw-radius-md);
|
||||
background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 10%, transparent);
|
||||
}
|
||||
|
||||
.loading,
|
||||
.progress {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.loading {
|
||||
min-height: 160px;
|
||||
}
|
||||
|
||||
.progress {
|
||||
min-height: 32px;
|
||||
}
|
||||
|
||||
@container (max-width: 480px) {
|
||||
.cardHeader {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.qrActions {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
width: 100%;
|
||||
margin-inline-start: 0;
|
||||
}
|
||||
|
||||
.qrActions > button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.actions {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.actions > button {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.linkRow {
|
||||
align-items: stretch;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.linkPreview {
|
||||
flex: auto;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/** Separate QR and tokenized-link controls for signing another browser 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'
|
||||
import type { RemoteConnectionContentProps } from './slots.ts'
|
||||
import css from './RemoteConnectionSection.module.css'
|
||||
|
||||
/** Renderer-derived section data, localized copy, and actions. */
|
||||
export type RemoteConnectionSectionProps = RemoteConnectionContentProps & PropsLocale<'remoteConnection'>
|
||||
|
||||
/**
|
||||
* Present independent QR and tokenized-link cards with loading confined to the QR preview.
|
||||
* @param props - Section injection and standard slot props.
|
||||
* @returns Remote connection settings content.
|
||||
*/
|
||||
export function RemoteConnectionSection(props: RemoteConnectionSectionProps) {
|
||||
const { t, useRemoteConnection } = props
|
||||
const loading = useRemoteConnection(state => state.phase === 'loading' && state.deployment === null)
|
||||
if (loading) return <div className={css.loading} role="status" aria-label={t('loading')}><StateDot state="ongoing" size={20} /></div>
|
||||
return <section className={css.section} aria-label={t('title')}>
|
||||
<header className={css.header}>
|
||||
<h2 className={css.title}>{t('title')}</h2>
|
||||
</header>
|
||||
<QrLoginCard {...props} />
|
||||
<LinkLoginCard {...props} />
|
||||
</section>
|
||||
}
|
||||
|
||||
function QrLoginCard({ t, useRemoteConnection, create, cancel, reload }: Pick<RemoteConnectionSectionProps,
|
||||
't' | 'useRemoteConnection' | 'create' | 'cancel' | 'reload'>) {
|
||||
const { deployment, phase, ticket, error, remainingSeconds, retainDetails } = useRemoteConnection(state => state)
|
||||
const busy = phase === 'loading' || phase === 'creating' || phase === 'cancelling'
|
||||
const available = deployment?.availability === 'available'
|
||||
const http = deployment?.url.startsWith('http:') === true
|
||||
const visibleTicket = phase === 'pending' && ticket !== null ? ticket : null
|
||||
const showQrPreview = visibleTicket !== null || busy
|
||||
const showDetails = visibleTicket !== null || retainDetails
|
||||
const showQrBody = (phase !== 'ready' && phase !== 'cancelled') || !available
|
||||
return <section className={css.card} aria-label={t('qrTitle')} aria-busy={busy || undefined}>
|
||||
<header className={css.cardHeader}>
|
||||
<h3 className={css.methodTitle}>{t('qrTitle')}</h3>
|
||||
{(available || ticket !== null) && <div className={css.qrActions}>
|
||||
{available && <Button variant="primary" size="sm" disabled={busy} onClick={create}>
|
||||
{t(phase === 'ready' ? 'generate' : 'regenerate')}
|
||||
</Button>}
|
||||
{(ticket !== null || phase === 'creating') && <Button variant="outline" size="sm" disabled={busy} onClick={cancel}>{t('cancel')}</Button>}
|
||||
</div>}
|
||||
</header>
|
||||
{showQrBody && <div className={css.cardBody}>
|
||||
{showQrPreview && <div className={css.symbol}>
|
||||
{visibleTicket !== null && <QRCodeSVG className={css.qr} value={visibleTicket.url} size={240} marginSize={4} level="M" role="img" aria-label={t('qr')} title={t('qr')} />}
|
||||
{busy && <div className={css.progress} role="status" aria-label={t(phase)}><StateDot state="ongoing" size={20} /></div>}
|
||||
</div>}
|
||||
<div className={css.field}>
|
||||
{showQrPreview && <div className={showDetails ? css.field : `${css.field} ${css.placeholder}`} aria-hidden={!showDetails || undefined}>
|
||||
<p className={css.qrDetails}>
|
||||
<span>{t('scan')}</span>
|
||||
<span className={css.countdown} role="timer" aria-live="off">{t('expires', { seconds: String(remainingSeconds) })}</span>
|
||||
</p>
|
||||
<CredentialWarning t={t} http={http} method="qr" />
|
||||
</div>}
|
||||
{deployment !== null && deployment.availability !== 'available' && <p className={css.notice} role="status">{t(deployment.availability)}</p>}
|
||||
{phase === 'expired' && <div className={css.caution} role="status">
|
||||
<span className={css.cautionIcon} aria-hidden="true"><IconWarningOutlineMedium /></span>
|
||||
<div className={css.cautionBody}><p className={css.warning}>{t('expired')}</p></div>
|
||||
</div>}
|
||||
{(phase === 'used' || phase === 'replaced')
|
||||
&& <p className={css.notice} role="status">{t(phase)}</p>}
|
||||
{error !== null && <p className={css.error} role="alert">{t(error)}</p>}
|
||||
{(error === 'loadFailed' || error === 'statusFailed') && <div className={css.actions}>
|
||||
<Button variant="outline" size="sm" onClick={reload}>{t('retry')}</Button>
|
||||
</div>}
|
||||
</div>
|
||||
</div>}
|
||||
</section>
|
||||
}
|
||||
|
||||
function LinkLoginCard({ t, useRemoteConnection, useLoginLink, copyLink, reloadLink }: Pick<RemoteConnectionSectionProps,
|
||||
't' | 'useRemoteConnection' | 'useLoginLink' | 'copyLink' | 'reloadLink'>) {
|
||||
const deployment = useRemoteConnection(state => state.deployment)
|
||||
const link = useLoginLink(state => state)
|
||||
const available = deployment?.availability === 'available'
|
||||
const http = deployment?.url.startsWith('http:') === true
|
||||
const retryLink = link.phase === 'error'
|
||||
return <section className={css.card} aria-label={t('linkTitle')}>
|
||||
<header className={css.header}>
|
||||
<h3 className={css.methodTitle}>{t('linkTitle')}</h3>
|
||||
<p className={css.description}>{t('linkDescription')}</p>
|
||||
</header>
|
||||
{deployment !== null && <div className={css.linkRow}>
|
||||
<div className={css.linkPreview}>
|
||||
<code className={css.linkUrl}>{link.url ?? deployment.url}</code>
|
||||
</div>
|
||||
{available && <Button variant="outline" size="sm" disabled={link.phase === 'loading' || link.phase === 'copying'}
|
||||
onClick={retryLink ? reloadLink : copyLink}>
|
||||
<span className={css.copyLabel}>
|
||||
<span className={css.copyLabelSizer} aria-hidden="true">{t('copyLink')}</span>
|
||||
<span className={css.copyLabelSizer} aria-hidden="true">{t('copying')}</span>
|
||||
<span>{t(retryLink ? 'retry' : link.phase === 'copying' ? 'copying' : link.copied ? 'copied' : 'copyLink')}</span>
|
||||
</span>
|
||||
</Button>}
|
||||
</div>}
|
||||
{available && retryLink && <p className={css.error} role="alert">{t('linkFailed')}</p>}
|
||||
{link.copied && <CredentialWarning t={t} http={http} method="link" />}
|
||||
</section>
|
||||
}
|
||||
|
||||
function CredentialWarning({ t, http, method }: PropsLocale<'remoteConnection'> & { http: boolean; method: 'qr' | 'link' }) {
|
||||
return <div className={css.caution}>
|
||||
<span className={css.cautionIcon} aria-hidden="true"><IconWarningOutlineMedium /></span>
|
||||
<div className={css.cautionBody}>
|
||||
<p className={css.cautionTitle}>{t(method === 'qr' ? 'warningTitle' : 'linkWarningTitle')}</p>
|
||||
<p className={css.warning}>{t(method === 'qr' ? 'warning' : 'linkWarning')}</p>
|
||||
{http && <p className={css.warning}>{t('httpWarning')}</p>}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/** One settings navigation entry owning the replaceable Remote connection panel. */
|
||||
import type { PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {} from './slots.ts'
|
||||
|
||||
type Props = PropsRuntime<'settings.section'> & PropsRenderSlots<'settings.remoteConnection.content'>
|
||||
|
||||
/**
|
||||
* Render the selected panel while retaining the settings navigation identity.
|
||||
* @param props - Settings close action and the owned content renderer.
|
||||
* @returns The active Remote connection panel.
|
||||
*/
|
||||
export function RemoteConnectionSettings({ close, renderSlot }: Props) {
|
||||
return renderSlot('settings.remoteConnection.content', { close })
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/** Remote connection settings registration; invitation credentials stay in this plugin's memory. */
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import remoteConnectionRemote from '@deepseek-ai/dsh-client-remote-connection/remote'
|
||||
import type {} from '@deepseek-ai/dsh-api-remotes/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
import { writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { RemoteConnectionController } from './remote-connection-controller.ts'
|
||||
import { LoginLinkController } from './login-link-controller.ts'
|
||||
import { LoginLinkToast } from './LoginLinkToast.tsx'
|
||||
import { RemoteConnectionSection } from './RemoteConnectionSection.tsx'
|
||||
import { RemoteConnectionSettings } from './RemoteConnectionSettings.tsx'
|
||||
import { en, zh, ja, es, fr, de, ru, pt, type RemoteConnectionLocaleKey } from './locales.ts'
|
||||
|
||||
export type { RemoteConnectionContentProps } from './slots.ts'
|
||||
export type { RemoteConnectionState } from './remote-connection-controller.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** Remote connection settings copy. */
|
||||
remoteConnection: RemoteConnectionLocaleKey
|
||||
}
|
||||
}
|
||||
|
||||
/** Services consumed by the settings registration. */
|
||||
export const inject = ['slots', 'locale', 'remote']
|
||||
|
||||
/**
|
||||
* Register the section and own its polling until plugin disposal.
|
||||
* @param ctx - Browser context providing the settings slot and authenticated Remote.
|
||||
* @returns After the generated service and section are registered.
|
||||
*/
|
||||
export async function apply(ctx: Context): Promise<void> {
|
||||
await ctx.remote.$mount(remoteConnectionRemote)
|
||||
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)
|
||||
const link = new LoginLinkController(scope.remote.remoteConnection, writeClipboard)
|
||||
const invitationFace = controller.inject()
|
||||
const linkFace = link.inject()
|
||||
const face = { ...invitationFace, ...linkFace, hooks: { ...invitationFace.hooks, ...linkFace.hooks } }
|
||||
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()
|
||||
else void controller.load()
|
||||
})
|
||||
scope.slots.inject('settings.section', () => scope.slots.register({
|
||||
name: 'settings.section', id: 'remote-connection', order: 25,
|
||||
label: () => t('title'),
|
||||
children: {
|
||||
'settings.remoteConnection.content': { kind: 'single', scope: 'root', inject: face },
|
||||
},
|
||||
}, RemoteConnectionSettings))
|
||||
scope.slots.inject('settings.remoteConnection.content', () => scope.slots.register({
|
||||
name: 'settings.remoteConnection.content', locale: 'remoteConnection',
|
||||
}, RemoteConnectionSection))
|
||||
scope.slots.inject('shell.overlay', () => scope.slots.register({
|
||||
name: 'shell.overlay', id: 'remote-connection-copy', locale: 'remoteConnection', inject: () => linkFace,
|
||||
}, LoginLinkToast))
|
||||
void controller.load()
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
/** Copy for the Remote connection settings section. */
|
||||
|
||||
/** English dictionary and key authority. */
|
||||
export const en = {
|
||||
title: 'Remote connection',
|
||||
qrTitle: 'QR code login',
|
||||
linkTitle: 'Link login',
|
||||
linkDescription: 'Copy the login link and open it in the browser on your other device.',
|
||||
copyLink: 'Copy login link',
|
||||
copied: 'Copied',
|
||||
copying: 'Copying login link',
|
||||
linkWarningTitle: 'Keep this login link private',
|
||||
linkWarning: 'Anyone with this link can sign in. Send it only to your own devices; do not share it publicly. Restarting the server invalidates the link.',
|
||||
linkCopied: 'Link copied',
|
||||
copyFailed: 'Could not copy the login link. Check clipboard permissions and try again.',
|
||||
linkFailed: 'Could not load the login link. Try again.',
|
||||
generate: 'Create login QR code',
|
||||
regenerate: 'Create a new code',
|
||||
cancel: 'Cancel code',
|
||||
retry: 'Try again',
|
||||
qr: 'One-time login QR code',
|
||||
scan: 'Scan to sign in directly.',
|
||||
warningTitle: 'Keep this code private',
|
||||
warning: 'Anyone with this code can sign in until it is used or expires. Keep it private.',
|
||||
httpWarning: 'HTTP sends login credentials without encryption. Use only on a trusted network.',
|
||||
expires: 'Expires in {seconds}s',
|
||||
used: 'Code used. Check your phone to confirm sign-in.',
|
||||
expired: 'This code has expired. Create a new one to sign in.',
|
||||
replaced: 'Another code replaced this one. Create a new code to continue.',
|
||||
loading: 'Loading remote connection',
|
||||
creating: 'Creating login code',
|
||||
cancelling: 'Cancelling login code',
|
||||
'unreachable-host': 'Set an access address your phone can reach. A localhost or unspecified address cannot be used.',
|
||||
'untrusted-host': 'Add this access address to the Host’s trusted hosts before creating a code.',
|
||||
loadFailed: 'Could not load remote connection settings. Try again.',
|
||||
createFailed: 'Could not confirm code creation. A code may still be valid; creating a new one replaces it.',
|
||||
cancelFailed: 'Could not confirm cancellation. This code may still work; try cancelling again.',
|
||||
statusFailed: 'Could not confirm this code’s status. It may still work; retry or cancel it.',
|
||||
}
|
||||
|
||||
/** Typed keys for all panel content and accessible names. */
|
||||
export type RemoteConnectionLocaleKey = keyof typeof en
|
||||
|
||||
/** Simplified Chinese dictionary. */
|
||||
export const zh: Record<RemoteConnectionLocaleKey, string> = {
|
||||
title: '远程连接',
|
||||
qrTitle: '二维码登录',
|
||||
linkTitle: '链接登录',
|
||||
linkDescription: '复制登录链接,在另一台设备的浏览器中打开',
|
||||
copyLink: '复制登录链接',
|
||||
copied: '已复制',
|
||||
copying: '正在复制登录链接',
|
||||
linkWarningTitle: '请勿公开分享登录链接',
|
||||
linkWarning: '持有此链接的人都可以直接登录,请仅发送给自己的设备,勿公开分享;重启服务后链接失效',
|
||||
linkCopied: '链接已复制',
|
||||
copyFailed: '无法复制登录链接,请检查剪贴板权限后重试',
|
||||
linkFailed: '无法获取登录链接,请重试',
|
||||
generate: '生成登录二维码',
|
||||
regenerate: '生成新二维码',
|
||||
cancel: '取消二维码',
|
||||
retry: '重试',
|
||||
qr: '一次性登录二维码',
|
||||
scan: '扫码后直接登录',
|
||||
warningTitle: '请勿分享登录二维码',
|
||||
warning: '二维码使用或过期前,持有它的人都可以登录,请勿传播',
|
||||
httpWarning: 'HTTP 会明文传输登录凭据,请仅在可信网络中使用',
|
||||
expires: '{seconds} 秒后过期',
|
||||
used: '二维码已使用,请在手机上确认是否已登录',
|
||||
expired: '二维码已过期,请生成新二维码登录',
|
||||
replaced: '此二维码已被替换,请生成新二维码继续',
|
||||
loading: '正在加载远程连接',
|
||||
creating: '正在生成登录二维码',
|
||||
cancelling: '正在取消登录二维码',
|
||||
'unreachable-host': '请配置手机可访问的地址,不能使用 localhost 或未指定的监听地址',
|
||||
'untrusted-host': '请先将此访问地址加入 Host 的可信主机配置',
|
||||
loadFailed: '无法加载远程连接设置,请重试',
|
||||
createFailed: '无法确认二维码是否生成,可能仍有有效二维码;生成新二维码会将其替换',
|
||||
cancelFailed: '无法确认是否已取消,此二维码可能仍然有效,请重试取消',
|
||||
statusFailed: '无法确认二维码状态,它可能仍然有效,请重试或取消',
|
||||
}
|
||||
|
||||
/** Japanese dictionary. */
|
||||
export const ja: Record<RemoteConnectionLocaleKey, string> = {
|
||||
title: 'リモート接続',
|
||||
qrTitle: 'QRコードでログイン',
|
||||
linkTitle: 'リンクでログイン',
|
||||
linkDescription: 'ログインリンクをコピーし、別の端末のブラウザーで開いてください。',
|
||||
copyLink: 'ログインリンクをコピー',
|
||||
copied: 'コピー済み',
|
||||
copying: 'ログインリンクをコピー中',
|
||||
linkWarningTitle: 'ログインリンクを公開しないでください',
|
||||
linkWarning: 'このリンクを持つ人は誰でもログインできます。自分の端末にのみ送り、公開しないでください。サーバーを再起動するとリンクは無効になります。',
|
||||
linkCopied: 'リンクをコピーしました',
|
||||
copyFailed: 'ログインリンクをコピーできませんでした。クリップボードの権限を確認して再試行してください。',
|
||||
linkFailed: 'ログインリンクを読み込めませんでした。再試行してください。',
|
||||
generate: 'ログイン用QRコードを生成',
|
||||
regenerate: '新しいコードを生成',
|
||||
cancel: 'コードをキャンセル',
|
||||
retry: '再試行',
|
||||
qr: '使い捨てログイン用QRコード',
|
||||
scan: 'スキャンでログイン',
|
||||
warningTitle: 'このコードを共有しないでください',
|
||||
warning: '使用済みになるか有効期限が切れるまで、このコードを持つ人は誰でもログインできます。共有しないでください。',
|
||||
httpWarning: 'HTTPはログイン情報を暗号化せずに送信します。信頼できるネットワークでのみ使用してください。',
|
||||
expires: 'あと{seconds}秒で期限切れ',
|
||||
used: 'コードは使用済みです。スマートフォンでログインを確認してください。',
|
||||
expired: 'コードの有効期限が切れました。新しいコードを生成してください。',
|
||||
replaced: '別のコードに置き換えられました。新しいコードを生成してください。',
|
||||
loading: 'リモート接続を読み込み中',
|
||||
creating: 'ログイン用コードを生成中',
|
||||
cancelling: 'ログイン用コードをキャンセル中',
|
||||
'unreachable-host': 'スマートフォンからアクセスできるアドレスを設定してください。localhostや未指定のアドレスは使用できません。',
|
||||
'untrusted-host': 'コードを生成する前に、このアドレスをHostの信頼するホストに追加してください。',
|
||||
loadFailed: 'リモート接続設定を読み込めませんでした。再試行してください。',
|
||||
createFailed: 'コードの生成を確認できませんでした。有効なコードが残っている可能性があります。新しく生成すると置き換わります。',
|
||||
cancelFailed: 'キャンセルを確認できませんでした。このコードはまだ有効かもしれません。再度キャンセルしてください。',
|
||||
statusFailed: 'コードの状態を確認できませんでした。まだ有効かもしれません。再試行するかキャンセルしてください。',
|
||||
}
|
||||
|
||||
/** Spanish dictionary. */
|
||||
export const es: Record<RemoteConnectionLocaleKey, string> = {
|
||||
title: 'Conexión remota',
|
||||
qrTitle: 'Inicio de sesión con QR',
|
||||
linkTitle: 'Inicio de sesión con enlace',
|
||||
linkDescription: 'Copia el enlace y ábrelo en el navegador de tu otro dispositivo.',
|
||||
copyLink: 'Copiar enlace',
|
||||
copied: 'Copiado',
|
||||
copying: 'Copiando enlace',
|
||||
linkWarningTitle: 'Mantén este enlace privado',
|
||||
linkWarning: 'Cualquiera que tenga este enlace puede iniciar sesión. Envíalo solo a tus dispositivos y no lo publiques. Reiniciar el servidor invalida el enlace.',
|
||||
linkCopied: 'Enlace copiado',
|
||||
copyFailed: 'No se pudo copiar el enlace. Revisa los permisos del portapapeles y reinténtalo.',
|
||||
linkFailed: 'No se pudo cargar el enlace. Reinténtalo.',
|
||||
generate: 'Crear código QR de inicio de sesión',
|
||||
regenerate: 'Crear un código nuevo',
|
||||
cancel: 'Cancelar código',
|
||||
retry: 'Reintentar',
|
||||
qr: 'Código QR de inicio de sesión de un solo uso',
|
||||
scan: 'Escanea para entrar.',
|
||||
warningTitle: 'No compartas este código',
|
||||
warning: 'Cualquiera que tenga este código puede iniciar sesión hasta que se use o caduque. No lo compartas.',
|
||||
httpWarning: 'HTTP envía las credenciales sin cifrar. Úsalo solo en una red de confianza.',
|
||||
expires: 'Caduca en {seconds} s',
|
||||
used: 'Código utilizado. Comprueba en tu teléfono si has iniciado sesión.',
|
||||
expired: 'Este código ha caducado. Crea otro para iniciar sesión.',
|
||||
replaced: 'Otro código ha sustituido a este. Crea uno nuevo para continuar.',
|
||||
loading: 'Cargando conexión remota',
|
||||
creating: 'Creando código de inicio de sesión',
|
||||
cancelling: 'Cancelando código de inicio de sesión',
|
||||
'unreachable-host': 'Configura una dirección accesible desde el teléfono. No se puede usar localhost ni una dirección sin especificar.',
|
||||
'untrusted-host': 'Añade esta dirección a los hosts de confianza del Host antes de crear un código.',
|
||||
loadFailed: 'No se pudo cargar la configuración de conexión remota. Reinténtalo.',
|
||||
createFailed: 'No se pudo confirmar la creación. Puede que aún haya un código válido; al crear otro se sustituirá.',
|
||||
cancelFailed: 'No se pudo confirmar la cancelación. Este código puede seguir funcionando; vuelve a cancelarlo.',
|
||||
statusFailed: 'No se pudo confirmar el estado del código. Puede seguir funcionando; reinténtalo o cancélalo.',
|
||||
}
|
||||
|
||||
/** French dictionary. */
|
||||
export const fr: Record<RemoteConnectionLocaleKey, string> = {
|
||||
title: 'Connexion à distance',
|
||||
qrTitle: 'Connexion par code QR',
|
||||
linkTitle: 'Connexion par lien',
|
||||
linkDescription: 'Copiez le lien et ouvrez-le dans le navigateur de votre autre appareil.',
|
||||
copyLink: 'Copier le lien',
|
||||
copied: 'Copié',
|
||||
copying: 'Copie du lien',
|
||||
linkWarningTitle: 'Gardez ce lien confidentiel',
|
||||
linkWarning: 'Toute personne disposant de ce lien peut se connecter. Envoyez-le uniquement à vos appareils et ne le publiez pas. Redémarrer le serveur invalide le lien.',
|
||||
linkCopied: 'Lien copié',
|
||||
copyFailed: 'Impossible de copier le lien. Vérifiez les autorisations du presse-papiers et réessayez.',
|
||||
linkFailed: 'Impossible de charger le lien. Réessayez.',
|
||||
generate: 'Créer un code QR de connexion',
|
||||
regenerate: 'Créer un nouveau code',
|
||||
cancel: 'Annuler le code',
|
||||
retry: 'Réessayer',
|
||||
qr: 'Code QR de connexion à usage unique',
|
||||
scan: 'Scannez pour vous connecter.',
|
||||
warningTitle: 'Gardez ce code confidentiel',
|
||||
warning: 'Toute personne disposant de ce code peut se connecter tant qu’il n’a pas été utilisé ou n’a pas expiré. Ne le partagez pas.',
|
||||
httpWarning: 'HTTP transmet les identifiants sans chiffrement. Utilisez uniquement un réseau de confiance.',
|
||||
expires: 'Expire dans {seconds} s',
|
||||
used: 'Code utilisé. Vérifiez la connexion sur votre téléphone.',
|
||||
expired: 'Ce code a expiré. Créez-en un autre pour vous connecter.',
|
||||
replaced: 'Un autre code a remplacé celui-ci. Créez un nouveau code pour continuer.',
|
||||
loading: 'Chargement de la connexion à distance',
|
||||
creating: 'Création du code de connexion',
|
||||
cancelling: 'Annulation du code de connexion',
|
||||
'unreachable-host': 'Définissez une adresse accessible depuis votre téléphone. localhost et les adresses non spécifiées ne sont pas utilisables.',
|
||||
'untrusted-host': 'Ajoutez cette adresse aux hôtes de confiance du Host avant de créer un code.',
|
||||
loadFailed: 'Impossible de charger les paramètres de connexion à distance. Réessayez.',
|
||||
createFailed: 'La création du code n’a pas pu être confirmée. Un code peut encore être valide ; en créer un nouveau le remplacera.',
|
||||
cancelFailed: 'L’annulation n’a pas pu être confirmée. Ce code peut encore fonctionner ; réessayez de l’annuler.',
|
||||
statusFailed: 'L’état du code n’a pas pu être confirmé. Il peut encore fonctionner ; réessayez ou annulez-le.',
|
||||
}
|
||||
|
||||
/** German dictionary. */
|
||||
export const de: Record<RemoteConnectionLocaleKey, string> = {
|
||||
title: 'Fernverbindung',
|
||||
qrTitle: 'Anmeldung per QR-Code',
|
||||
linkTitle: 'Anmeldung per Link',
|
||||
linkDescription: 'Kopieren Sie den Link und öffnen Sie ihn im Browser Ihres anderen Geräts.',
|
||||
copyLink: 'Link kopieren',
|
||||
copied: 'Kopiert',
|
||||
copying: 'Anmeldelink wird kopiert',
|
||||
linkWarningTitle: 'Halten Sie diesen Link geheim',
|
||||
linkWarning: 'Jeder mit diesem Link kann sich anmelden. Senden Sie ihn nur an Ihre eigenen Geräte und veröffentlichen Sie ihn nicht. Ein Serverneustart macht den Link ungültig.',
|
||||
linkCopied: 'Link kopiert',
|
||||
copyFailed: 'Der Link konnte nicht kopiert werden. Prüfen Sie die Zwischenablageberechtigungen und versuchen Sie es erneut.',
|
||||
linkFailed: 'Der Anmeldelink konnte nicht geladen werden. Versuchen Sie es erneut.',
|
||||
generate: 'QR-Code zur Anmeldung erstellen',
|
||||
regenerate: 'Neuen Code erstellen',
|
||||
cancel: 'Code widerrufen',
|
||||
retry: 'Erneut versuchen',
|
||||
qr: 'Einmaliger QR-Code zur Anmeldung',
|
||||
scan: 'Zum Anmelden scannen.',
|
||||
warningTitle: 'Halten Sie diesen Code geheim',
|
||||
warning: 'Jeder mit diesem Code kann sich anmelden, bis er verwendet wird oder abläuft. Geben Sie ihn nicht weiter.',
|
||||
httpWarning: 'HTTP überträgt Anmeldedaten unverschlüsselt. Verwenden Sie es nur in einem vertrauenswürdigen Netzwerk.',
|
||||
expires: 'Läuft in {seconds} s ab',
|
||||
used: 'Code verwendet. Prüfen Sie die Anmeldung auf Ihrem Smartphone.',
|
||||
expired: 'Dieser Code ist abgelaufen. Erstellen Sie einen neuen Code zur Anmeldung.',
|
||||
replaced: 'Dieser Code wurde ersetzt. Erstellen Sie einen neuen Code, um fortzufahren.',
|
||||
loading: 'Fernverbindung wird geladen',
|
||||
creating: 'Anmeldecode wird erstellt',
|
||||
cancelling: 'Anmeldecode wird widerrufen',
|
||||
'unreachable-host': 'Legen Sie eine vom Smartphone erreichbare Adresse fest. localhost und nicht angegebene Adressen sind nicht verwendbar.',
|
||||
'untrusted-host': 'Fügen Sie diese Adresse vor dem Erstellen eines Codes den vertrauenswürdigen Hosts des Host hinzu.',
|
||||
loadFailed: 'Die Einstellungen für die Fernverbindung konnten nicht geladen werden. Versuchen Sie es erneut.',
|
||||
createFailed: 'Die Erstellung konnte nicht bestätigt werden. Ein Code könnte noch gültig sein; ein neuer Code ersetzt ihn.',
|
||||
cancelFailed: 'Der Widerruf konnte nicht bestätigt werden. Dieser Code könnte noch funktionieren; widerrufen Sie ihn erneut.',
|
||||
statusFailed: 'Der Status konnte nicht bestätigt werden. Der Code könnte noch funktionieren; versuchen Sie es erneut oder widerrufen Sie ihn.',
|
||||
}
|
||||
|
||||
/** Russian dictionary. */
|
||||
export const ru: Record<RemoteConnectionLocaleKey, string> = {
|
||||
title: 'Удалённое подключение',
|
||||
qrTitle: 'Вход по QR-коду',
|
||||
linkTitle: 'Вход по ссылке',
|
||||
linkDescription: 'Скопируйте ссылку и откройте её в браузере другого устройства.',
|
||||
copyLink: 'Копировать ссылку',
|
||||
copied: 'Скопировано',
|
||||
copying: 'Копирование ссылки',
|
||||
linkWarningTitle: 'Не публикуйте ссылку для входа',
|
||||
linkWarning: 'Любой обладатель ссылки может войти. Отправляйте её только на свои устройства и не публикуйте. Перезапуск сервера делает ссылку недействительной.',
|
||||
linkCopied: 'Ссылка скопирована',
|
||||
copyFailed: 'Не удалось скопировать ссылку. Проверьте разрешения буфера обмена и повторите попытку.',
|
||||
linkFailed: 'Не удалось загрузить ссылку. Повторите попытку.',
|
||||
generate: 'Создать QR-код для входа',
|
||||
regenerate: 'Создать новый код',
|
||||
cancel: 'Отменить код',
|
||||
retry: 'Повторить',
|
||||
qr: 'Одноразовый QR-код для входа',
|
||||
scan: 'Сканируйте для входа.',
|
||||
warningTitle: 'Не делитесь этим кодом',
|
||||
warning: 'Любой обладатель кода может войти, пока код не использован или не истёк. Не передавайте его другим.',
|
||||
httpWarning: 'HTTP передаёт учётные данные без шифрования. Используйте только доверенную сеть.',
|
||||
expires: 'Истекает через {seconds} с',
|
||||
used: 'Код использован. Проверьте на телефоне, выполнен ли вход.',
|
||||
expired: 'Срок действия кода истёк. Создайте новый код для входа.',
|
||||
replaced: 'Этот код заменён другим. Создайте новый код, чтобы продолжить.',
|
||||
loading: 'Загрузка удалённого подключения',
|
||||
creating: 'Создание кода для входа',
|
||||
cancelling: 'Отмена кода для входа',
|
||||
'unreachable-host': 'Укажите адрес, доступный с телефона. localhost и неопределённый адрес использовать нельзя.',
|
||||
'untrusted-host': 'Перед созданием кода добавьте этот адрес в доверенные хосты Host.',
|
||||
loadFailed: 'Не удалось загрузить настройки удалённого подключения. Повторите попытку.',
|
||||
createFailed: 'Не удалось подтвердить создание кода. Код может оставаться действительным; создание нового заменит его.',
|
||||
cancelFailed: 'Не удалось подтвердить отмену. Код может ещё работать; повторите отмену.',
|
||||
statusFailed: 'Не удалось подтвердить состояние кода. Он может ещё работать; повторите попытку или отмените его.',
|
||||
}
|
||||
|
||||
/** Portuguese dictionary. */
|
||||
export const pt: Record<RemoteConnectionLocaleKey, string> = {
|
||||
title: 'Conexão remota',
|
||||
qrTitle: 'Login por código QR',
|
||||
linkTitle: 'Login por link',
|
||||
linkDescription: 'Copie o link e abra-o no navegador do seu outro dispositivo.',
|
||||
copyLink: 'Copiar link',
|
||||
copied: 'Copiado',
|
||||
copying: 'Copiando link',
|
||||
linkWarningTitle: 'Mantenha este link privado',
|
||||
linkWarning: 'Qualquer pessoa com este link pode entrar. Envie-o apenas aos seus dispositivos e não o publique. Reiniciar o servidor invalida o link.',
|
||||
linkCopied: 'Link copiado',
|
||||
copyFailed: 'Não foi possível copiar o link. Verifique as permissões da área de transferência e tente novamente.',
|
||||
linkFailed: 'Não foi possível carregar o link. Tente novamente.',
|
||||
generate: 'Criar código QR de login',
|
||||
regenerate: 'Criar um novo código',
|
||||
cancel: 'Cancelar código',
|
||||
retry: 'Tentar novamente',
|
||||
qr: 'Código QR de login de uso único',
|
||||
scan: 'Escaneie para entrar.',
|
||||
warningTitle: 'Mantenha este código privado',
|
||||
warning: 'Qualquer pessoa com este código pode entrar até que ele seja usado ou expire. Não o compartilhe.',
|
||||
httpWarning: 'HTTP envia credenciais sem criptografia. Use apenas em uma rede confiável.',
|
||||
expires: 'Expira em {seconds} s',
|
||||
used: 'Código utilizado. Confira no celular se o login foi concluído.',
|
||||
expired: 'Este código expirou. Crie outro para entrar.',
|
||||
replaced: 'Outro código substituiu este. Crie um novo código para continuar.',
|
||||
loading: 'Carregando conexão remota',
|
||||
creating: 'Criando código de login',
|
||||
cancelling: 'Cancelando código de login',
|
||||
'unreachable-host': 'Defina um endereço acessível pelo celular. localhost ou um endereço não especificado não podem ser usados.',
|
||||
'untrusted-host': 'Adicione este endereço aos hosts confiáveis do Host antes de criar um código.',
|
||||
loadFailed: 'Não foi possível carregar as configurações de conexão remota. Tente novamente.',
|
||||
createFailed: 'Não foi possível confirmar a criação. Um código ainda pode ser válido; criar outro o substitui.',
|
||||
cancelFailed: 'Não foi possível confirmar o cancelamento. Este código ainda pode funcionar; tente cancelar novamente.',
|
||||
statusFailed: 'Não foi possível confirmar o estado do código. Ele ainda pode funcionar; tente novamente ou cancele.',
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/** In-memory login link and clipboard outcomes, independent of the QR invitation. */
|
||||
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type { RemoteConnectionApi } from './remote-connection-controller.ts'
|
||||
|
||||
/** Link readiness and clipboard feedback; credentials must never be persisted or logged. */
|
||||
export interface LoginLinkState {
|
||||
/** Tokenized address displayed by the settings panel and used for explicit clipboard writes. */
|
||||
url: string | null
|
||||
/** Loading failures remain retryable without affecting the QR invitation. */
|
||||
phase: 'loading' | 'ready' | 'copying' | 'error'
|
||||
/** Whether the current URL has been copied successfully. */
|
||||
copied: boolean
|
||||
/** Transient clipboard outcome presented by the shell overlay. */
|
||||
notice: 'linkCopied' | 'copyFailed' | null
|
||||
/** Identity of the latest notice; older toast completion cannot dismiss it. */
|
||||
sequence: number
|
||||
}
|
||||
|
||||
/** Link actions and private state bound by the slot renderer. */
|
||||
export interface LoginLinkFace {
|
||||
/** Copy the loaded credential without consuming or replacing a QR invitation. */
|
||||
copyLink: () => void
|
||||
/** Retry a failed login-link read. */
|
||||
reloadLink: () => void
|
||||
/** Retire the specified clipboard notice. */
|
||||
dismissCopyNotice: (sequence: number) => void
|
||||
/** Shared source for the settings panel and the longer-lived shell toast. */
|
||||
hooks: { loginLink: SnapshotStore<LoginLinkState> }
|
||||
}
|
||||
|
||||
/** Owns credential reads and clipboard writes; disposal drains them and discards late results. */
|
||||
export class LoginLinkController {
|
||||
/** In-memory credential and feedback, cleared when the plugin unloads. */
|
||||
readonly store = createSnapshotStore<LoginLinkState>({ url: null, phase: 'loading', copied: false, notice: null, sequence: 0 })
|
||||
private live = true
|
||||
private loading: Promise<void> | undefined
|
||||
private copying: Promise<void> | undefined
|
||||
private readonly pending = new Set<Promise<void>>()
|
||||
|
||||
/**
|
||||
* @param remote - owner-authenticated login-link reader.
|
||||
* @param write - clipboard writer returning true only after a successful write.
|
||||
*/
|
||||
constructor(private readonly remote: Pick<RemoteConnectionApi, 'loginUrl'>, private readonly write: (text: string) => Promise<boolean>) {}
|
||||
|
||||
/**
|
||||
* Bind stable actions and the shared feedback source.
|
||||
* @returns settings and shell-overlay injection values.
|
||||
*/
|
||||
inject(): LoginLinkFace {
|
||||
return {
|
||||
copyLink: () => { void this.copy() },
|
||||
reloadLink: () => { void this.load() },
|
||||
dismissCopyNotice: (sequence) => {
|
||||
if (this.store.getSnapshot().sequence === sequence) this.store.update((state) => { state.notice = null })
|
||||
},
|
||||
hooks: { loginLink: this.store },
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the login link before a copy gesture so HTTP clipboard fallback keeps user activation.
|
||||
* @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.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 }))
|
||||
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()))
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the cached URL directly from the user's gesture and report the actual result.
|
||||
* @returns after clipboard completion; a failure leaves the URL available for retry.
|
||||
*/
|
||||
copy(): Promise<void> {
|
||||
const { url, phase } = this.store.getSnapshot()
|
||||
if (!this.live || phase !== 'ready' || url === null) return Promise.resolve()
|
||||
this.store.update((state) => { state.phase = 'copying'; state.notice = null })
|
||||
this.copying = this.track(this.writeLink(url).finally(() => { this.copying = undefined }))
|
||||
return this.copying
|
||||
}
|
||||
|
||||
/**
|
||||
* Discard the credential, stop new work, and ignore late results.
|
||||
* @returns after all admitted reads, clipboard writes, and queued refreshes settle.
|
||||
*/
|
||||
async dispose(): Promise<void> {
|
||||
this.live = false
|
||||
this.store.update((state) => { state.url = null; state.notice = null; state.copied = false })
|
||||
await Promise.all(this.pending)
|
||||
}
|
||||
|
||||
private track(operation: Promise<void>): Promise<void> {
|
||||
this.pending.add(operation)
|
||||
void operation.finally(() => { this.pending.delete(operation) })
|
||||
return operation
|
||||
}
|
||||
|
||||
private async writeLink(url: string): Promise<void> {
|
||||
let copied: boolean
|
||||
try { copied = await this.write(url) } catch (_clipboardFailure) { copied = false }
|
||||
if (!this.active()) return
|
||||
this.store.update((state) => {
|
||||
state.phase = 'ready'
|
||||
state.copied ||= copied
|
||||
state.notice = copied ? 'linkCopied' : 'copyFailed'
|
||||
state.sequence += 1
|
||||
})
|
||||
}
|
||||
|
||||
private async read(previousUrl: string | null): Promise<void> {
|
||||
try {
|
||||
const result = await this.remote.loginUrl()
|
||||
if (!this.live) return
|
||||
this.store.update((state) => {
|
||||
state.url = result.ok ? result.value : null
|
||||
state.phase = result.ok ? 'ready' : 'error'
|
||||
if (state.url !== previousUrl) state.copied = false
|
||||
})
|
||||
} catch (_requestFailure) {
|
||||
if (this.live) this.store.update((state) => { state.phase = 'error'; state.copied = false })
|
||||
}
|
||||
}
|
||||
|
||||
private active(): boolean { return this.live }
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
/** Transient QR login state; secrets remain in memory until the invitation settles. */
|
||||
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import type {} from '@deepseek-ai/dsh-client-remote-connection/remote'
|
||||
import type { TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { RemoteConnectionStatus, RemoteLoginTicket } from '../types.ts'
|
||||
|
||||
/** Client methods are generated from the Host service. */
|
||||
export type RemoteConnectionApi = TypertClientRemote['remoteConnection']
|
||||
|
||||
/** Settings panel state, including uncertain outcomes that hide the QR. */
|
||||
export interface RemoteConnectionState {
|
||||
/** Advertised address and prerequisites; null until a deployment read succeeds. */
|
||||
deployment: RemoteConnectionStatus | null
|
||||
/** Current operation or invitation outcome; only pending permits displaying the QR credential. */
|
||||
phase: 'loading' | 'ready' | 'creating' | 'pending' | 'cancelling' | 'used' | 'expired' | 'cancelled' | 'replaced' | 'error'
|
||||
/** Secret invitation, retained during uncertain outcomes for status recovery; never persist or log its URL. */
|
||||
ticket: RemoteLoginTicket | null
|
||||
/** Failure owned by the panel; null after a successful read or new operation. */
|
||||
error: 'loadFailed' | 'createFailed' | 'cancelFailed' | 'statusFailed' | null
|
||||
/** Remaining invitation lifetime in whole seconds, measured against the browser's monotonic clock. */
|
||||
remainingSeconds: number
|
||||
/** Keep the scan line and warning visible during a QR operation; never permits displaying the retained credential. */
|
||||
retainDetails: boolean
|
||||
}
|
||||
|
||||
/** Registration-side data and actions for the settings section. */
|
||||
export interface RemoteConnectionFace {
|
||||
/** Start a new invitation; operation outcomes arrive through the state source. */
|
||||
create: () => void
|
||||
/** Cancel the retained invitation without revoking an already-issued browser session. */
|
||||
cancel: () => void
|
||||
/** Refresh deployment availability and any retained invitation's state. */
|
||||
reload: () => void
|
||||
/** Shared state source bound by the renderer to useRemoteConnection for every panel. */
|
||||
hooks: { remoteConnection: SnapshotStore<RemoteConnectionState> }
|
||||
}
|
||||
|
||||
/** Owns current invitation polling and ignores superseded replies. */
|
||||
export class RemoteConnectionController {
|
||||
/** Snapshot consumed by the settings section; credentials are discarded when it settles or unloads. */
|
||||
readonly store = createSnapshotStore<RemoteConnectionState>({
|
||||
deployment: null, phase: 'loading', ticket: null, error: null, remainingSeconds: 0, retainDetails: false,
|
||||
})
|
||||
private readonly pending = new Set<Promise<void>>()
|
||||
private timer: ReturnType<typeof setTimeout> | undefined
|
||||
private expiryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
private generation = 0
|
||||
private deadline = 0
|
||||
private live = true
|
||||
|
||||
/** @param remote - Generated owner-authenticated service methods. */
|
||||
constructor(private readonly remote: RemoteConnectionApi) {}
|
||||
|
||||
/**
|
||||
* Bind stable actions and the private snapshot to the slot renderer.
|
||||
* @returns The settings section's injection values.
|
||||
*/
|
||||
inject(): RemoteConnectionFace {
|
||||
return {
|
||||
create: () => { void this.create() },
|
||||
cancel: () => { void this.cancel() },
|
||||
reload: () => { void this.load() },
|
||||
hooks: { remoteConnection: this.store },
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh deployment availability and, when retained, the current invitation.
|
||||
* @returns After the read settles or immediately when another gesture owns the panel.
|
||||
*/
|
||||
load(): Promise<void> {
|
||||
if (!this.live || this.busy()) return Promise.resolve()
|
||||
const generation = this.begin()
|
||||
this.store.update((state) => { state.retainDetails = state.phase === 'pending'; state.phase = 'loading'; state.error = null })
|
||||
return this.track(this.read(generation))
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace the previous code; an uncertain response never restores its QR.
|
||||
* @returns After the creation result has been presented.
|
||||
*/
|
||||
create(): Promise<void> {
|
||||
const deployment = this.store.getSnapshot().deployment
|
||||
if (!this.live || this.busy() || deployment?.availability !== 'available') return Promise.resolve()
|
||||
const generation = this.begin()
|
||||
this.store.update((state) => { state.retainDetails = state.phase === 'pending'; state.phase = 'creating'; state.ticket = null; state.error = null })
|
||||
return this.track(this.runCreate(generation, deployment.pollIntervalMs))
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel the retained invitation without affecting an already-issued login.
|
||||
* @returns After cancellation settles; an unknown outcome remains visible.
|
||||
*/
|
||||
cancel(): Promise<void> {
|
||||
const ticket = this.store.getSnapshot().ticket
|
||||
if (!this.live || this.busy() || ticket === null) return Promise.resolve()
|
||||
const generation = this.begin()
|
||||
this.store.update((state) => { state.retainDetails = state.phase === 'pending'; state.phase = 'cancelling'; state.error = null })
|
||||
return this.track(this.runCancel(generation, ticket))
|
||||
}
|
||||
|
||||
/** Stop polling, discard the QR secret, and await owned requests. */
|
||||
async dispose(): Promise<void> {
|
||||
this.live = false
|
||||
this.begin()
|
||||
this.store.update((state) => { state.ticket = null; state.retainDetails = false })
|
||||
await Promise.all(this.pending)
|
||||
}
|
||||
|
||||
private busy(): boolean {
|
||||
return ['creating', 'cancelling'].includes(this.store.getSnapshot().phase)
|
||||
}
|
||||
|
||||
private begin(): number {
|
||||
clearTimeout(this.timer)
|
||||
clearTimeout(this.expiryTimer)
|
||||
this.timer = undefined
|
||||
this.expiryTimer = undefined
|
||||
return ++this.generation
|
||||
}
|
||||
|
||||
private current(generation: number): boolean { return this.live && generation === this.generation }
|
||||
|
||||
private track(operation: Promise<void>): Promise<void> {
|
||||
this.pending.add(operation)
|
||||
void operation.finally(() => { this.pending.delete(operation) })
|
||||
return operation
|
||||
}
|
||||
|
||||
private fail(generation: number, error: NonNullable<RemoteConnectionState['error']>): void {
|
||||
if (this.current(generation)) this.store.update((state) => { state.phase = 'error'; state.error = error; state.retainDetails = false })
|
||||
}
|
||||
|
||||
private async runCreate(generation: number, pollIntervalMs: number): Promise<void> {
|
||||
try {
|
||||
const result = await this.remote.create()
|
||||
if (!this.current(generation)) return
|
||||
if (!result.ok) { this.fail(generation, 'createFailed'); return }
|
||||
this.deadline = performance.now() + result.value.lifetimeMs
|
||||
this.store.update((state) => { state.ticket = result.value; state.phase = 'pending'; state.remainingSeconds = this.remainingSeconds(); state.retainDetails = false })
|
||||
this.schedule(generation, pollIntervalMs)
|
||||
} catch (_requestFailure) {
|
||||
this.fail(generation, 'createFailed')
|
||||
}
|
||||
}
|
||||
|
||||
private async runCancel(generation: number, ticket: RemoteLoginTicket): Promise<void> {
|
||||
try {
|
||||
const result = await this.remote.cancel(ticket.id)
|
||||
if (!this.current(generation)) return
|
||||
if (!result.ok) { this.fail(generation, 'cancelFailed'); return }
|
||||
this.store.update((state) => { state.ticket = null; state.phase = result.value === 'none' ? 'replaced' : result.value; state.retainDetails = false })
|
||||
} catch (_requestFailure) {
|
||||
this.fail(generation, 'cancelFailed')
|
||||
}
|
||||
}
|
||||
|
||||
private async read(generation: number): Promise<void> {
|
||||
const ticket = this.store.getSnapshot().ticket
|
||||
try {
|
||||
const result = await this.remote.status(ticket?.id ?? null)
|
||||
if (!this.current(generation)) return
|
||||
if (!result.ok) { this.fail(generation, ticket === null ? 'loadFailed' : 'statusFailed'); return }
|
||||
this.store.update((state) => {
|
||||
state.deployment = result.value
|
||||
state.remainingSeconds = this.remainingSeconds()
|
||||
state.error = null
|
||||
state.retainDetails = false
|
||||
state.phase = ticket === null ? 'ready' : result.value.ticket === 'none' ? 'replaced' : result.value.ticket
|
||||
if (state.phase !== 'pending' || result.value.availability !== 'available') state.ticket = null
|
||||
})
|
||||
const currentTicket = this.store.getSnapshot().ticket
|
||||
if (currentTicket === null) this.begin()
|
||||
else this.schedule(generation, result.value.pollIntervalMs)
|
||||
} catch (_requestFailure) {
|
||||
this.fail(generation, ticket === null ? 'loadFailed' : 'statusFailed')
|
||||
}
|
||||
}
|
||||
|
||||
private remainingSeconds(): number { return Math.max(0, Math.ceil((this.deadline - performance.now()) / 1000)) }
|
||||
|
||||
private schedule(generation: number, pollIntervalMs: number): void {
|
||||
const remaining = this.deadline - performance.now()
|
||||
if (remaining <= 0) {
|
||||
this.store.update((state) => { state.ticket = null; state.phase = 'expired'; state.remainingSeconds = 0; state.retainDetails = false })
|
||||
return
|
||||
}
|
||||
// The expiry deadline still hides the credential when a status request stalls.
|
||||
this.expiryTimer ??= setTimeout(() => {
|
||||
this.begin()
|
||||
this.store.update((state) => { state.ticket = null; state.phase = 'expired'; state.remainingSeconds = 0; state.retainDetails = false })
|
||||
}, remaining)
|
||||
this.timer = setTimeout(() => {
|
||||
this.timer = undefined
|
||||
void this.track(this.read(generation))
|
||||
}, Math.min(pollIntervalMs, remaining))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/** Replaceable settings content sharing the plugin-owned browser invitation. */
|
||||
import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { SettingsSectionOwnerProps } from '@deepseek-ai/dsh-client-ui-settings/client'
|
||||
import type { RemoteConnectionFace } from './remote-connection-controller.ts'
|
||||
import type { LoginLinkFace } from './login-link-controller.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface SlotMap {
|
||||
/**
|
||||
* Complete Remote connection panel with shared invitation state and actions.
|
||||
* Receives invitation and login-link selectors, their actions, and close().
|
||||
* Unloading a replacement restores the default panel with the current invitation.
|
||||
*/
|
||||
'settings.remoteConnection.content': {
|
||||
kind: 'single'
|
||||
scope: 'root'
|
||||
owner: SettingsSectionOwnerProps
|
||||
inject: RemoteConnectionFace & LoginLinkFace
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Settings close action, invitation selector, and create/cancel/reload actions supplied to every panel. */
|
||||
export type RemoteConnectionContentProps = PropsRuntime<'settings.remoteConnection.content'>
|
||||
@@ -0,0 +1,4 @@
|
||||
declare module '*.module.css' {
|
||||
const classes: Record<string, string>
|
||||
export default classes
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
/** Anonymous one-use credential exchange; application RPC remains authenticated. */
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||
import type { ConnectionTrustRequest } from '@deepseek-ai/dsh-client-connection'
|
||||
import { renderLoginPage } from './login-page.ts'
|
||||
|
||||
interface LoginRoute {
|
||||
readonly root: string
|
||||
readonly available: boolean
|
||||
readonly consume: (token: string) => boolean
|
||||
readonly issueCookie: (request: ConnectionTrustRequest) => string | undefined
|
||||
}
|
||||
|
||||
const HEADERS = {
|
||||
'cache-control': 'no-store',
|
||||
'referrer-policy': 'no-referrer',
|
||||
'x-content-type-options': 'nosniff',
|
||||
'content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve the public page or redeem its raw base64url credential over POST.
|
||||
* GET and HEAD never consume credentials. The POST is bound to the advertised
|
||||
* authority after WebServer's source checks; only a successful one-use
|
||||
* exchange receives a Remote browser cookie.
|
||||
* @param route - owning service's current availability and credential consumer.
|
||||
* @param request - incoming request with an at-most-43-byte credential body.
|
||||
* @param response - HTTP response owned through completion.
|
||||
*/
|
||||
export async function handleLogin(route: LoginRoute, request: IncomingMessage, response: ServerResponse): Promise<void> {
|
||||
const root = new URL(route.root)
|
||||
if (new URL(`${root.protocol}//${request.headers.host}`).host !== root.host) {
|
||||
response.writeHead(403, HEADERS)
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
if (request.method === 'GET' || request.method === 'HEAD') {
|
||||
response.writeHead(200, { ...HEADERS, 'content-type': 'text/html; charset=utf-8' })
|
||||
response.end(request.method === 'HEAD' ? undefined : renderLoginPage())
|
||||
return
|
||||
}
|
||||
if (request.method !== 'POST') {
|
||||
response.writeHead(405, { ...HEADERS, allow: 'GET, HEAD, POST' })
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
if (!route.available) {
|
||||
response.writeHead(403, HEADERS)
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
if (request.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase() !== 'text/plain') {
|
||||
response.writeHead(400, HEADERS)
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
const declaredLength = request.headers['content-length']
|
||||
if (declaredLength !== undefined && Number(declaredLength) > 43) {
|
||||
response.writeHead(413, { ...HEADERS, connection: 'close' })
|
||||
response.end()
|
||||
request.destroy()
|
||||
return
|
||||
}
|
||||
const chunks: Buffer[] = []
|
||||
let received = 0
|
||||
try {
|
||||
for await (const chunk of request) {
|
||||
const bytes = chunk as Buffer
|
||||
received += bytes.byteLength
|
||||
if (received > 43) {
|
||||
response.writeHead(413, { ...HEADERS, connection: 'close' })
|
||||
response.end()
|
||||
request.destroy()
|
||||
return
|
||||
}
|
||||
chunks.push(bytes)
|
||||
}
|
||||
} catch (_readFailure) {
|
||||
// A failed body read cannot consume an invitation or issue a browser credential.
|
||||
if (!response.destroyed && !response.headersSent) {
|
||||
response.writeHead(410, HEADERS)
|
||||
response.end()
|
||||
}
|
||||
return
|
||||
}
|
||||
const token = Buffer.concat(chunks).toString('utf8')
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) {
|
||||
response.writeHead(400, HEADERS)
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
if (!route.consume(token)) {
|
||||
response.writeHead(410, { ...HEADERS, 'content-type': 'application/json; charset=utf-8' })
|
||||
response.end(JSON.stringify({ code: 'invalid-or-expired' }))
|
||||
return
|
||||
}
|
||||
const cookie = route.issueCookie(request)
|
||||
if (cookie === undefined) {
|
||||
response.writeHead(403, HEADERS)
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
// An HTTPS public URL may terminate TLS at a proxy before the HTTP listener.
|
||||
const sessionCookie = root.protocol === 'https:' && !cookie.includes('; Secure') ? `${cookie}; Secure` : cookie
|
||||
response.writeHead(204, { ...HEADERS, 'set-cookie': sessionCookie })
|
||||
response.end()
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
/** Remote-owned QR authentication and an independent shortcut to Token login. */
|
||||
import { FiberState, Service, type Context } from '@deepseek-ai/cordis'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
import type {} from '@deepseek-ai/dsh-client-connection'
|
||||
import type {} from '@deepseek-ai/dsh-host-webserver'
|
||||
import type {} from '@deepseek-ai/dsh-web-app'
|
||||
import type {} from '@deepseek-ai/dsh-credentials'
|
||||
import type { PeerScope } from '@deepseek-ai/dsh-client-connection'
|
||||
import type { WebEntryUrl } from '@deepseek-ai/dsh-host-webserver'
|
||||
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { LoginTickets } from './login-tickets.ts'
|
||||
import { handleLogin } from './host-route.ts'
|
||||
import { RemoteBrowserAuth } from './remote-auth.ts'
|
||||
import { renderAuthenticationPage } from './login-page.ts'
|
||||
import type { RemoteConnectionStatus, RemoteLoginId, RemoteLoginState, RemoteLoginTicket } from './types.ts'
|
||||
|
||||
export type * from './types.ts'
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
/** Short-lived QR login invitations. */
|
||||
remoteConnection: RemoteConnection
|
||||
}
|
||||
}
|
||||
|
||||
/** Deployment timing for QR login and its settings status. */
|
||||
export interface Config {
|
||||
/** Absolute lifetime in days for Remote browser credentials; default 30. */
|
||||
cookieMaxAgeDays: number
|
||||
/** Invitation lifetime in milliseconds; expiry never renews an existing browser session. */
|
||||
ticketLifetimeMs: number
|
||||
/** Interval in milliseconds between the settings panel's status reads. */
|
||||
pollIntervalMs: number
|
||||
}
|
||||
|
||||
/** One outstanding invitation, issued by an owner and consumed by a new browser. */
|
||||
export default class RemoteConnection extends TypertRemoteService {
|
||||
static inject = ['connection', 'connection.authentication', 'credentials', 'webServer', 'webApp']
|
||||
static Config: z<Partial<Config>, Config> = z.object({
|
||||
cookieMaxAgeDays: z.natural().min(1).default(30),
|
||||
ticketLifetimeMs: z.natural().min(1).max(2_147_483_647).default(120_000),
|
||||
pollIntervalMs: z.natural().min(100).max(2_147_483_647).default(1000),
|
||||
})
|
||||
|
||||
private readonly tickets = new LoginTickets()
|
||||
private readonly owner: Context
|
||||
private readonly lifetime = new AbortController()
|
||||
private readonly pending = new Set<Promise<unknown>>()
|
||||
private readonly requests = new Set<import('node:http').IncomingMessage>()
|
||||
private disposed = false
|
||||
|
||||
/**
|
||||
* Register the anonymous exchange independently of the authenticated application page.
|
||||
* @param ctx - Host containing the existing browser authentication and advertised URL.
|
||||
* @param config - validated deployment timing.
|
||||
*/
|
||||
constructor(ctx: Context, private readonly config: Config) {
|
||||
super(ctx, 'remoteConnection')
|
||||
this.owner = ctx
|
||||
}
|
||||
|
||||
/** Prepare durable Remote credentials before publishing anonymous routes. */
|
||||
async [Service.init](): Promise<void> {
|
||||
const ctx = this.owner
|
||||
const auth = await RemoteBrowserAuth.create(ctx.credentials, this.config.cookieMaxAgeDays)
|
||||
if (this.stopped) return
|
||||
const peer = ctx.connection.createPeer({ principal: { kind: 'owner' } })
|
||||
ctx.effect(function* (this: RemoteConnection) {
|
||||
yield ctx.connection.authentication.register({
|
||||
authenticate: request => !this.stopped && auth.isAuthenticated(request, ctx.webServer.protocol === 'https:') ? peer : undefined,
|
||||
})
|
||||
yield ctx.webServer.register({
|
||||
kind: 'exact', path: '/remote-login', auth: 'anonymous',
|
||||
handler: async (request, response) => {
|
||||
this.requests.add(request)
|
||||
const task = handleLogin({
|
||||
root: ctx.webApp.getAdvertisedUrl(),
|
||||
available: !this.stopped && this.deployment().availability === 'available',
|
||||
consume: token => !this.stopped && this.tickets.consume(token),
|
||||
issueCookie: facts => auth.createSessionCookie(facts, ctx.webServer.protocol === 'https:'),
|
||||
}, request, response)
|
||||
this.pending.add(task)
|
||||
try { await task } finally { this.pending.delete(task); this.requests.delete(request) }
|
||||
},
|
||||
})
|
||||
yield ctx.webServer.register({
|
||||
kind: 'exact', path: '/', auth: 'anonymous',
|
||||
resource: async (request, admitted) => {
|
||||
const task = this.readRoot(request, admitted)
|
||||
this.pending.add(task)
|
||||
try { return await task } finally { this.pending.delete(task) }
|
||||
},
|
||||
})
|
||||
yield ctx.effect(() => async () => {
|
||||
this.disposed = true
|
||||
this.lifetime.abort()
|
||||
this.tickets.dispose()
|
||||
for (const request of this.requests) request.destroy()
|
||||
await Promise.allSettled([...this.pending])
|
||||
}, 'remote-connection: active requests')
|
||||
}.bind(this))
|
||||
}
|
||||
|
||||
private get stopped(): boolean {
|
||||
return this.disposed || this.owner.fiber.uid === null || this.owner.fiber.state === FiberState.UNLOADING
|
||||
}
|
||||
|
||||
private async readRoot(request: Request, admitted?: PeerScope): Promise<Response> {
|
||||
const signal = AbortSignal.any([request.signal, this.lifetime.signal])
|
||||
signal.throwIfAborted()
|
||||
const admission = admitted === undefined
|
||||
? this.owner.connection.authentication.authenticate({ headers: request.headers, method: request.method, url: request.url, signal })
|
||||
: { peer: admitted }
|
||||
if ('rejection' in admission) {
|
||||
const headers = {
|
||||
'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer',
|
||||
'x-content-type-options': 'nosniff',
|
||||
'content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'",
|
||||
}
|
||||
if (admission.rejection !== 401) return new Response('authentication unavailable', { status: admission.rejection, headers })
|
||||
const html = renderAuthenticationPage({ tokenLoginEnabled: this.tokenLoginUrl(this.owner.webApp.getAdvertisedUrl()) !== undefined })
|
||||
return new Response(request.method === 'HEAD' ? null : html, { status: 401, headers })
|
||||
}
|
||||
// The Web application owns index.html; the explicit Peer avoids a second authentication pass.
|
||||
return this.owner.webServer.readResource(new Request(new URL('index.html', request.url), { method: request.method, headers: request.headers, signal }), admission.peer)
|
||||
}
|
||||
|
||||
private tokenLoginUrl(baseUrl: string): string | undefined {
|
||||
const entries: WebEntryUrl[] = []
|
||||
this.owner.emit(this.owner.webServer, 'webserver/entry-url', baseUrl, entries)
|
||||
const root = new URL(baseUrl)
|
||||
const entry = entries.find((candidate) => {
|
||||
const url = new URL(candidate.url)
|
||||
return url.origin === root.origin && url.pathname === root.pathname
|
||||
&& url.searchParams.getAll('token').length === 1 && Boolean(url.searchParams.get('token'))
|
||||
})
|
||||
return entry?.url
|
||||
}
|
||||
|
||||
/**
|
||||
* Read prerequisites and the state of one invitation without disclosing its credential.
|
||||
* @param id - invitation to inspect, or null to inspect only deployment prerequisites.
|
||||
* @returns deployment availability and invitation state, with the polling interval.
|
||||
*/
|
||||
@Remote
|
||||
status(id: RemoteLoginId | null): RemoteConnectionStatus {
|
||||
this.requireOwner()
|
||||
return { ...this.deployment(), ticket: this.tickets.state(id), pollIntervalMs: this.config.pollIntervalMs }
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorize a new browser by generating a one-use login invitation; replaces any older invitation.
|
||||
* @returns the invitation credential and its fixed expiry.
|
||||
*/
|
||||
@Remote
|
||||
create(): RemoteLoginTicket {
|
||||
this.requireOwner()
|
||||
const deployment = this.availableDeployment()
|
||||
return this.tickets.create(deployment.url, this.config.ticketLifetimeMs)
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the advertised URL carrying the process launch token; QR invitations are unchanged.
|
||||
* @returns owner-only login URL, reusable until the Host process restarts; never persist or log it.
|
||||
*/
|
||||
@Remote
|
||||
loginUrl(): string {
|
||||
this.requireOwner()
|
||||
const url = this.tokenLoginUrl(this.availableDeployment().url)
|
||||
if (url === undefined) throw new RemoteError('remote-connection/token-unavailable', 'Token login is not enabled for this Host.', {})
|
||||
return url
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel an unused invitation; this never revokes a browser session already issued.
|
||||
* @param id - invitation being cancelled; an older ID cannot cancel a replacement.
|
||||
* @returns the invitation's final state, including used when a redemption won the race.
|
||||
*/
|
||||
@Remote
|
||||
cancel(id: RemoteLoginId): RemoteLoginState {
|
||||
this.requireOwner()
|
||||
this.tickets.cancel(id)
|
||||
return this.tickets.state(id)
|
||||
}
|
||||
|
||||
private requireOwner(): void {
|
||||
if (this.ctx.invocation?.peer.principal.kind !== 'owner') {
|
||||
throw new RemoteError('remote-connection/owner-required', 'Only an authenticated owner can manage login codes.', {})
|
||||
}
|
||||
if (this.stopped) throw new RemoteError('remote-connection/disposed', 'Remote login is no longer available.', {})
|
||||
}
|
||||
|
||||
private availableDeployment(): Pick<RemoteConnectionStatus, 'url' | 'availability'> {
|
||||
const deployment = this.deployment()
|
||||
if (deployment.availability !== 'available') {
|
||||
throw new RemoteError('remote-connection/unavailable', 'Configure a reachable, trusted URL before signing in remotely.', {
|
||||
reason: deployment.availability,
|
||||
})
|
||||
}
|
||||
return deployment
|
||||
}
|
||||
|
||||
private deployment(): Pick<RemoteConnectionStatus, 'url' | 'availability'> {
|
||||
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' || /^127\./.test(hostname)) {
|
||||
return { url, availability: 'unreachable-host' }
|
||||
}
|
||||
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' }
|
||||
}
|
||||
return { url, availability: 'available' }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** Copy for Remote's anonymous pages, before Client plugins load. */
|
||||
export const loginLocales = {
|
||||
en: {
|
||||
title: 'Connect this browser',
|
||||
pending: 'Signing in…',
|
||||
invalid: 'This QR code has expired or has already been used. Generate a new code on a signed-in device.',
|
||||
failed: 'Sign-in could not be confirmed. Open the app to check, or generate a new QR code on a signed-in device.',
|
||||
open: 'Open the app',
|
||||
scriptRequired: 'JavaScript is required to sign in with a QR code.',
|
||||
authenticationTitle: 'Connect to this Host',
|
||||
authenticationDescription: 'Sign in to continue.',
|
||||
authenticationUnavailable: 'No sign-in method is available. Contact the Host operator.',
|
||||
tokenLabel: 'Login token or link',
|
||||
tokenHint: 'Find the token in the URL printed when this Host started.',
|
||||
tokenInvalid: 'This login token is invalid or expired. Paste a current token and try again.',
|
||||
tokenFailed: 'Sign-in could not be confirmed. Try again or contact the Host operator.',
|
||||
tokenSubmit: 'Continue',
|
||||
tokenPending: 'Signing in…',
|
||||
},
|
||||
zh: {
|
||||
title: '连接此浏览器',
|
||||
pending: '正在登录…',
|
||||
invalid: '此二维码已过期或已使用,请在已登录的设备上生成新的二维码',
|
||||
failed: '无法确认登录结果,请打开应用检查,或在已登录的设备上生成新的二维码',
|
||||
open: '打开应用',
|
||||
scriptRequired: '扫码登录需要启用 JavaScript',
|
||||
authenticationTitle: '连接到此 Host',
|
||||
authenticationDescription: '登录以继续',
|
||||
authenticationUnavailable: '没有可用的登录方式,请联系 Host 管理者',
|
||||
tokenLabel: '登录令牌或链接',
|
||||
tokenHint: '登录令牌位于此 Host 启动时输出的 URL 中',
|
||||
tokenInvalid: '此登录令牌无效或已过期,请粘贴新的令牌后重试',
|
||||
tokenFailed: '无法确认登录结果,请重试或联系 Host 管理者',
|
||||
tokenSubmit: '继续',
|
||||
tokenPending: '正在登录…',
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/** Remote-owned anonymous login and QR exchange documents, without Client boot data. */
|
||||
import { loginLocales } from './login-locales.ts'
|
||||
|
||||
/** Public capabilities and rejection feedback shown by the anonymous login page. */
|
||||
export interface AuthenticationPageOptions {
|
||||
/** Whether the default Token provider has published its login entry. */
|
||||
readonly tokenLoginEnabled: boolean
|
||||
/** Whether this document follows a rejected Token submission. */
|
||||
readonly tokenRejected?: boolean
|
||||
}
|
||||
|
||||
const pageStyle = `
|
||||
:root{color-scheme:light dark;font-family:system-ui,sans-serif;background:light-dark(#fafafa,#171717);color:light-dark(#222,#eee)}
|
||||
body{margin:0;min-height:100dvh}
|
||||
.page{display:flex;align-items:center;justify-content:center;box-sizing:border-box;min-height:100dvh;padding:max(24px,env(safe-area-inset-top)) max(16px,env(safe-area-inset-right)) max(24px,env(safe-area-inset-bottom)) max(16px,env(safe-area-inset-left))}
|
||||
.card{display:flex;flex-direction:column;gap:12px;box-sizing:border-box;min-width:0;width:100%;max-width:360px;padding:24px;border:.5px solid color-mix(in srgb,currentColor 16%,transparent);border-radius:16px;background:light-dark(#fff,#232324)}
|
||||
h1{margin:0;font-size:20px;line-height:1.3;font-weight:500}
|
||||
p{margin:0;font-size:14px;line-height:1.5;overflow-wrap:anywhere}
|
||||
.description,.hint,label{color:color-mix(in srgb,currentColor 72%,transparent)}
|
||||
form{display:grid;grid-template-columns:minmax(0,1fr);grid-template-areas:'label' 'input' 'feedback' 'submit';gap:12px;min-width:0}
|
||||
label{grid-area:label;margin-bottom:-6px;font-size:13px;font-weight:500;line-height:1.5}
|
||||
input,button{box-sizing:border-box;min-width:0;min-height:44px;padding:8px 12px;font:inherit;font-size:14px;line-height:1.5;border-radius:8px}
|
||||
input{grid-area:input;width:100%;color:inherit;background:light-dark(#fafafa,#1b1b1c);border:.5px solid color-mix(in srgb,currentColor 16%,transparent)}
|
||||
input[aria-invalid='true']{border:1px solid light-dark(#ec1313,#f25a5a)}
|
||||
.hint,.error{grid-area:feedback;font-size:13px;line-height:1.5}
|
||||
.error{color:light-dark(#ec1313,#f25a5a)}
|
||||
.error:empty{display:none}
|
||||
form:has(.error:not(:empty)) .hint{visibility:hidden}
|
||||
button{grid-area:submit;cursor:pointer;font-weight:500;color:light-dark(#fff,#222);background:light-dark(#222,#eee);border:0}
|
||||
button:disabled{cursor:wait;opacity:.6}
|
||||
a{color:inherit;text-underline-offset:3px;padding:8px 0;font-size:14px;line-height:1.5}
|
||||
input:focus-visible,button:focus-visible,a:focus-visible{outline:2px solid currentColor;outline-offset:2px}
|
||||
@media(hover:hover){button:not(:disabled):hover{background:light-dark(#3c3c3d,#d4d4d4)}}
|
||||
@media(pointer:coarse){input{font-size:16px}}
|
||||
`
|
||||
|
||||
function scriptJson(value: typeof loginLocales): string {
|
||||
return JSON.stringify(value).replaceAll('<', '\\u003c')
|
||||
}
|
||||
|
||||
function documentHtml(title: string, content: string, script: string): string {
|
||||
return `<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="referrer" content="no-referrer"><meta name="robots" content="noindex"><title>${title}</title><style>${pageStyle}</style></head><body><main class="page"><section class="card" aria-labelledby="title">${content}</section></main><script>${script}</script></body></html>`
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit a Token through its own HTTP exchange without starting Client plugins.
|
||||
* Failed submissions remain on this page; page departure cancels an in-flight request.
|
||||
* @param locales - public copy embedded beside the entry.
|
||||
* @param tokenRejected - whether the Host already rejected a Token submission.
|
||||
*/
|
||||
export function enterAuthenticationPage(locales: typeof loginLocales, tokenRejected = false): void {
|
||||
const language = navigator.language.toLowerCase().startsWith('zh') ? 'zh' : 'en'
|
||||
const t = locales[language]
|
||||
document.documentElement.lang = language
|
||||
document.title = t.authenticationTitle
|
||||
const title = document.getElementById('title') as HTMLElement
|
||||
title.textContent = t.authenticationTitle
|
||||
const form = document.getElementById('token-form') as HTMLFormElement | null
|
||||
const description = document.getElementById('description') as HTMLElement
|
||||
description.textContent = form === null ? t.authenticationUnavailable : t.authenticationDescription
|
||||
const clean = new URL(location.href)
|
||||
clean.searchParams.delete('token')
|
||||
history.replaceState(null, '', clean)
|
||||
if (form === null) return
|
||||
const input = document.getElementById('token') as HTMLInputElement
|
||||
const error = document.getElementById('token-error') as HTMLElement
|
||||
const submit = document.getElementById('token-submit') as HTMLButtonElement
|
||||
const label = document.getElementById('token-label') as HTMLElement
|
||||
const hint = document.getElementById('token-hint') as HTMLElement
|
||||
label.textContent = t.tokenLabel
|
||||
hint.textContent = t.tokenHint
|
||||
submit.textContent = t.tokenSubmit
|
||||
if (tokenRejected) {
|
||||
error.textContent = t.tokenInvalid
|
||||
input.setAttribute('aria-invalid', 'true')
|
||||
}
|
||||
input.addEventListener('input', () => {
|
||||
input.removeAttribute('aria-invalid')
|
||||
error.textContent = ''
|
||||
})
|
||||
let pending: AbortController | undefined
|
||||
form.addEventListener('submit', (event) => {
|
||||
event.preventDefault()
|
||||
if (pending !== undefined) return
|
||||
let token = input.value.trim()
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) {
|
||||
try {
|
||||
const values = new URL(token).searchParams.getAll('token')
|
||||
token = values.length === 1 ? values.join('') : ''
|
||||
} catch (_invalidUrl) {
|
||||
// A pasted value that is neither a Token nor a URL cannot start an exchange.
|
||||
token = ''
|
||||
}
|
||||
}
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) {
|
||||
error.textContent = t.tokenInvalid
|
||||
input.setAttribute('aria-invalid', 'true')
|
||||
return
|
||||
}
|
||||
const target = new URL(form.action)
|
||||
target.searchParams.set('token', token)
|
||||
const lifetime = new AbortController()
|
||||
const abort = lifetime.abort.bind(lifetime, undefined)
|
||||
window.addEventListener('pagehide', abort, { once: true })
|
||||
pending = lifetime
|
||||
submit.disabled = true
|
||||
submit.textContent = t.tokenPending
|
||||
form.setAttribute('aria-busy', 'true')
|
||||
error.textContent = ''
|
||||
input.removeAttribute('aria-invalid')
|
||||
void fetch(target.href, {
|
||||
method: 'GET', credentials: 'same-origin', cache: 'no-store', redirect: 'follow', signal: lifetime.signal,
|
||||
}).then((response) => {
|
||||
if (lifetime.signal.aborted) return
|
||||
if (response.status === 200) location.replace('./')
|
||||
else {
|
||||
error.textContent = response.status === 401 ? t.tokenInvalid : t.tokenFailed
|
||||
if (response.status === 401) input.setAttribute('aria-invalid', 'true')
|
||||
}
|
||||
}).catch(() => {
|
||||
if (!lifetime.signal.aborted) error.textContent = t.tokenFailed
|
||||
}).finally(() => {
|
||||
window.removeEventListener('pagehide', abort)
|
||||
pending = undefined
|
||||
submit.disabled = false
|
||||
submit.textContent = t.tokenSubmit
|
||||
form.removeAttribute('aria-busy')
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Render Remote's public login page, without a Token value or private boot data.
|
||||
* @param options - public Token availability and optional rejection feedback.
|
||||
* @returns self-contained HTML with a native Token form and same-origin submission handling.
|
||||
*/
|
||||
export function renderAuthenticationPage(options: AuthenticationPageOptions): string {
|
||||
const t = loginLocales.en
|
||||
const content = `<h1 id="title">${t.authenticationTitle}</h1><p id="description" class="description">${options.tokenLoginEnabled ? t.authenticationDescription : t.authenticationUnavailable}</p>${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" required autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" aria-describedby="token-hint token-error"${options.tokenRejected ? ' aria-invalid="true"' : ''}><p id="token-hint" class="hint">${t.tokenHint}</p><p id="token-error" class="error" role="alert">${options.tokenRejected ? t.tokenInvalid : ''}</p><button id="token-submit" type="submit">${t.tokenSubmit}</button></form>` : ''}`
|
||||
return documentHtml(t.authenticationTitle, content, `(${enterAuthenticationPage.toString()})(${scriptJson(loginLocales)},${options.tokenRejected === true})`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Exchange the current page's QR fragment; all runtime dependencies must survive function serialization.
|
||||
* @param locales - Copy embedded beside the entry, before Client plugins load.
|
||||
*/
|
||||
export function enterBrowser(locales: typeof loginLocales): void {
|
||||
const language = navigator.language.toLowerCase().startsWith('zh') ? 'zh' : 'en'
|
||||
const t = locales[language]
|
||||
document.documentElement.lang = language
|
||||
document.title = t.title
|
||||
const title = document.getElementById('title') as HTMLElement
|
||||
const status = document.getElementById('status') as HTMLElement
|
||||
const open = document.getElementById('open') as HTMLElement
|
||||
title.textContent = t.title
|
||||
open.textContent = t.open
|
||||
const token = location.hash.slice(1)
|
||||
history.replaceState(null, '', location.pathname)
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) {
|
||||
status.textContent = t.invalid
|
||||
return
|
||||
}
|
||||
status.textContent = t.pending
|
||||
const lifetime = new AbortController()
|
||||
window.addEventListener('pagehide', () => { lifetime.abort() }, { once: true })
|
||||
void fetch(location.pathname, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
cache: 'no-store',
|
||||
redirect: 'error',
|
||||
headers: { 'content-type': 'text/plain' },
|
||||
body: token,
|
||||
signal: lifetime.signal,
|
||||
}).then((response) => {
|
||||
if (response.status === 204) location.replace('./')
|
||||
else status.textContent = response.status === 410 ? t.invalid : t.failed
|
||||
}).catch(() => {
|
||||
// A lost response may follow a successful single-use exchange; checking the app is safe.
|
||||
status.textContent = t.failed
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the public exchange page without authenticated application injections.
|
||||
* @returns HTML whose inline script removes the credential fragment before exchanging it with a same-origin POST.
|
||||
*/
|
||||
export function renderLoginPage(): string {
|
||||
const content = `<h1 id="title">${loginLocales.en.title}</h1><p id="status" role="status">${loginLocales.en.pending}</p><a id="open" href="./">${loginLocales.en.open}</a><noscript><p>${loginLocales.en.scriptRequired}</p></noscript>`
|
||||
return documentHtml(loginLocales.en.title, content, `(${enterBrowser.toString()})(${scriptJson(loginLocales)})`)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/** One service-owned, single-use browser login invitation. */
|
||||
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import type { RemoteLoginId, RemoteLoginState, RemoteLoginTicket } from './types.ts'
|
||||
|
||||
type Ticket = {
|
||||
readonly id: RemoteLoginId
|
||||
readonly expiresAt: number
|
||||
} & (
|
||||
| { readonly kind: 'pending'; readonly digest: Buffer }
|
||||
| { readonly kind: 'used' | 'expired' | 'cancelled' }
|
||||
)
|
||||
|
||||
/** One outstanding invitation; regeneration replaces it without retaining credentials. */
|
||||
export class LoginTickets {
|
||||
private ticket: Ticket | undefined
|
||||
|
||||
/**
|
||||
* Replace the outstanding invitation with a fresh random credential.
|
||||
* @param root - advertised application directory URL.
|
||||
* @param lifetimeMs - validated invitation lifetime.
|
||||
* @returns the only response carrying the plaintext credential.
|
||||
*/
|
||||
create(root: string, lifetimeMs: number): RemoteLoginTicket {
|
||||
const token = randomBytes(32).toString('base64url')
|
||||
const id = brandString<RemoteLoginId>(randomUUID())
|
||||
const expiresAt = Date.now() + lifetimeMs
|
||||
const url = new URL('remote-login', root.endsWith('/') ? root : `${root}/`)
|
||||
url.hash = token
|
||||
// Version 40 with medium error correction carries at most 2331 byte-mode bytes.
|
||||
if (Buffer.byteLength(url.href, 'utf8') > 2331) {
|
||||
throw new RemoteError('remote-connection/url-too-long', 'The application URL exceeds QR code capacity.', {})
|
||||
}
|
||||
this.ticket = { kind: 'pending', id, expiresAt, digest: digest(token) }
|
||||
return { id, url: url.href, lifetimeMs }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read an invitation without revealing its credential.
|
||||
* @param id - requested invitation, or null to read no invitation.
|
||||
* @returns current state; an identifier displaced by regeneration is replaced.
|
||||
*/
|
||||
state(id: RemoteLoginId | null): RemoteLoginState {
|
||||
if (id === null) return 'none'
|
||||
this.expire()
|
||||
return this.ticket?.id === id ? this.ticket.kind : 'replaced'
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate only the named invitation; stale cancellation cannot cancel a replacement.
|
||||
* @param id - invitation to cancel.
|
||||
*/
|
||||
cancel(id: RemoteLoginId): void {
|
||||
this.expire()
|
||||
const ticket = this.ticket
|
||||
if (ticket?.id === id && ticket.kind === 'pending') {
|
||||
this.ticket = { kind: 'cancelled', id, expiresAt: ticket.expiresAt }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomically validate and consume the credential before issuing a browser session.
|
||||
* @param token - credential supplied by the anonymous HTTP exchange.
|
||||
* @returns true for its sole successful exchange; all other attempts leave it unusable or unchanged.
|
||||
*/
|
||||
consume(token: string): boolean {
|
||||
this.expire()
|
||||
const ticket = this.ticket
|
||||
if (ticket?.kind !== 'pending' || !timingSafeEqual(ticket.digest, digest(token))) return false
|
||||
this.ticket = { kind: 'used', id: ticket.id, expiresAt: ticket.expiresAt }
|
||||
return true
|
||||
}
|
||||
|
||||
/** Remove the outstanding credential when its owning plugin unloads. */
|
||||
dispose(): void {
|
||||
this.ticket = undefined
|
||||
}
|
||||
|
||||
private expire(): void {
|
||||
const ticket = this.ticket
|
||||
if (ticket?.kind === 'pending' && Date.now() >= ticket.expiresAt) {
|
||||
this.ticket = { kind: 'expired', id: ticket.id, expiresAt: ticket.expiresAt }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function digest(token: string): Buffer {
|
||||
return createHash('sha256').update(token).digest()
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
/** Persistent Remote browser credentials, independent of Token authentication and runtime Peers. */
|
||||
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
|
||||
import { credentialKey } from '@deepseek-ai/dsh-credentials'
|
||||
import type { CredentialProvider, CredentialRecord } from '@deepseek-ai/dsh-credentials'
|
||||
import { HarnessError } from '@deepseek-ai/dsh-error'
|
||||
import type { ConnectionTrustRequest } from '@deepseek-ai/dsh-client-connection'
|
||||
|
||||
const RECORD_KEY = credentialKey('client-remote-connection', 'browser-session')
|
||||
const VERSION = 1
|
||||
const SECRET_BYTES = 32
|
||||
const DAY_MILLISECONDS = 86_400_000
|
||||
const MAX_DATE_MILLISECONDS = 8_640_000_000_000_000
|
||||
|
||||
type AuthenticationErrorCode =
|
||||
| 'REMOTE_AUTH_CREDENTIAL_CORRUPT'
|
||||
| 'REMOTE_AUTH_CREDENTIAL_UNAVAILABLE'
|
||||
| 'REMOTE_AUTH_CREDENTIAL_FAILED'
|
||||
| 'REMOTE_AUTH_INVALID_LIFETIME'
|
||||
|
||||
class RemoteAuthenticationError extends HarnessError {
|
||||
constructor(message: string, code: AuthenticationErrorCode, options?: ErrorOptions) {
|
||||
super(message, code, options)
|
||||
this.name = 'RemoteAuthenticationError'
|
||||
}
|
||||
}
|
||||
|
||||
interface CookiePayload {
|
||||
readonly version: typeof VERSION
|
||||
readonly authority: string
|
||||
readonly issuedAt: number
|
||||
readonly expiresAt: number
|
||||
}
|
||||
|
||||
function record(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function decode(value: string): Buffer | undefined {
|
||||
if (!/^[A-Za-z0-9_-]+$/u.test(value) || value.length % 4 === 1) return undefined
|
||||
const bytes = Buffer.from(value, 'base64url')
|
||||
return bytes.toString('base64url') === value ? bytes : undefined
|
||||
}
|
||||
|
||||
function readSecret(value: CredentialRecord | undefined): Buffer | undefined {
|
||||
if (value === undefined) return undefined
|
||||
if (value.kind !== 'grant' || !record(value.payload)
|
||||
|| value.payload.version !== VERSION || Object.keys(value.payload).length !== 2
|
||||
|| typeof value.payload.secret !== 'string') {
|
||||
throw new RemoteAuthenticationError(
|
||||
'Remote browser-session credentials have an unsupported format; restore the credential record before enabling Remote login.',
|
||||
'REMOTE_AUTH_CREDENTIAL_CORRUPT',
|
||||
)
|
||||
}
|
||||
const secret = decode(value.payload.secret)
|
||||
if (secret?.byteLength !== SECRET_BYTES) {
|
||||
throw new RemoteAuthenticationError(
|
||||
'Remote browser-session credentials contain an invalid signing key; restore the credential record before enabling Remote login.',
|
||||
'REMOTE_AUTH_CREDENTIAL_CORRUPT',
|
||||
)
|
||||
}
|
||||
return secret
|
||||
}
|
||||
|
||||
async function initializeSecret(credentials: CredentialProvider): Promise<Buffer> {
|
||||
const payload = { version: VERSION, secret: randomBytes(SECRET_BYTES).toString('base64url') }
|
||||
let stored: CredentialRecord | undefined
|
||||
try {
|
||||
stored = await credentials.modifyRecord(RECORD_KEY, (current) => {
|
||||
if (current !== undefined) {
|
||||
readSecret(current)
|
||||
return Promise.resolve(undefined)
|
||||
}
|
||||
return Promise.resolve({ kind: 'grant', payload })
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof HarnessError) throw error
|
||||
throw new RemoteAuthenticationError(
|
||||
'Remote browser-session credentials could not be loaded; check the credential provider before enabling Remote login.',
|
||||
'REMOTE_AUTH_CREDENTIAL_FAILED',
|
||||
{ cause: error },
|
||||
)
|
||||
}
|
||||
const secret = readSecret(stored)
|
||||
if (secret === undefined) {
|
||||
throw new RemoteAuthenticationError(
|
||||
'Remote browser-session credentials were not saved; configure a writable credential provider before enabling Remote login.',
|
||||
'REMOTE_AUTH_CREDENTIAL_UNAVAILABLE',
|
||||
)
|
||||
}
|
||||
return secret
|
||||
}
|
||||
|
||||
function header(headers: ConnectionTrustRequest['headers'], name: string): string | undefined {
|
||||
if (headers instanceof Headers) return headers.get(name) ?? undefined
|
||||
const value = headers[name]
|
||||
return typeof value === 'string' ? value : undefined
|
||||
}
|
||||
|
||||
function audience(request: ConnectionTrustRequest, secure: boolean): string | undefined {
|
||||
const host = header(request.headers, 'host')
|
||||
if (host === undefined || host.length === 0 || /[\s/\\?#@]/u.test(host)) return undefined
|
||||
try {
|
||||
return new URL(`${secure ? 'https:' : 'http:'}//${host}`).origin
|
||||
} catch (_invalidHost) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
function cookieName(authority: string): string {
|
||||
return `dsh-remote-${createHash('sha256').update(authority).digest('base64url')}`
|
||||
}
|
||||
|
||||
function cookieValue(value: string, name: string): string | undefined {
|
||||
let found: string | undefined
|
||||
for (const part of value.split(';')) {
|
||||
const at = part.indexOf('=')
|
||||
if (at === -1 || part.slice(0, at).trim() !== name) continue
|
||||
if (found !== undefined) return undefined
|
||||
found = part.slice(at + 1).trim()
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
function parsePayload(body: Buffer): CookiePayload | undefined {
|
||||
let value: unknown
|
||||
try { value = JSON.parse(body.toString('utf8')) } catch (_invalidJson) { return undefined }
|
||||
if (!record(value) || Object.keys(value).length !== 4 || value.version !== VERSION
|
||||
|| typeof value.authority !== 'string'
|
||||
|| typeof value.issuedAt !== 'number' || !Number.isSafeInteger(value.issuedAt) || value.issuedAt < 0
|
||||
|| typeof value.expiresAt !== 'number' || !Number.isSafeInteger(value.expiresAt)
|
||||
|| value.expiresAt > MAX_DATE_MILLISECONDS) return undefined
|
||||
return { version: VERSION, authority: value.authority, issuedAt: value.issuedAt, expiresAt: value.expiresAt }
|
||||
}
|
||||
|
||||
/** A durable signing key and fixed cookie lifetime for the Remote authentication provider. */
|
||||
export class RemoteBrowserAuth {
|
||||
private constructor(private readonly secret: Buffer, private readonly lifetimeMs: number) {}
|
||||
|
||||
/**
|
||||
* Load or atomically create Remote's signing key without changing an existing key.
|
||||
* @param credentials - persistent provider storing Remote's browser-session grant.
|
||||
* @param cookieMaxAgeDays - positive whole days for each credential's absolute lifetime.
|
||||
* @returns issuer and verifier whose credentials remain valid across plugin and process restarts until expiry.
|
||||
* @throws when the stored record is invalid, the provider fails, or the lifetime exceeds supported timestamps.
|
||||
*/
|
||||
static async create(credentials: CredentialProvider, cookieMaxAgeDays: number): Promise<RemoteBrowserAuth> {
|
||||
const lifetimeMs = cookieMaxAgeDays * DAY_MILLISECONDS
|
||||
if (!Number.isSafeInteger(lifetimeMs) || lifetimeMs <= 0
|
||||
|| !Number.isInteger(cookieMaxAgeDays) || Date.now() + lifetimeMs > MAX_DATE_MILLISECONDS) {
|
||||
throw new RemoteAuthenticationError(
|
||||
'Remote cookieMaxAgeDays must be positive whole days within the supported timestamp range.',
|
||||
'REMOTE_AUTH_INVALID_LIFETIME',
|
||||
)
|
||||
}
|
||||
return new RemoteBrowserAuth(await initializeSecret(credentials), lifetimeMs)
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a Remote browser credential after the caller validates its invitation or approval.
|
||||
* @param request - request whose Host selects the signed audience; source policy is checked by the caller's route.
|
||||
* @param secure - whether the receiving listener serves HTTPS; selects the audience and Secure attribute.
|
||||
* @returns Set-Cookie, or undefined when Host cannot identify an audience. This method does not authenticate the caller.
|
||||
*/
|
||||
createSessionCookie(request: ConnectionTrustRequest, secure: boolean): string | undefined {
|
||||
const authority = audience(request, secure)
|
||||
if (authority === undefined) return undefined
|
||||
const issuedAt = Date.now()
|
||||
const expiresAt = issuedAt + this.lifetimeMs
|
||||
const payload: CookiePayload = { version: VERSION, authority, issuedAt, expiresAt }
|
||||
const body = Buffer.from(JSON.stringify(payload)).toString('base64url')
|
||||
const signed = `v${VERSION}.${body}`
|
||||
const signature = createHmac('sha256', this.secret).update(signed).digest('base64url')
|
||||
const cookie = `${cookieName(authority)}=${signed}.${signature}; Max-Age=${String(this.lifetimeMs / 1000)}; Path=/; Expires=${new Date(expiresAt).toUTCString()}; HttpOnly; SameSite=Strict`
|
||||
return secure ? `${cookie}; Secure` : cookie
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify one Remote credential without changing its fixed expiry or allocating a Peer.
|
||||
* @param request - request carrying Host and Cookie; unrelated cookies are ignored.
|
||||
* @param secure - whether the receiving listener serves HTTPS; HTTP and HTTPS credentials are isolated.
|
||||
* @returns true only for one unambiguous, authentic, unexpired credential for this listener authority.
|
||||
*/
|
||||
isAuthenticated(request: ConnectionTrustRequest, secure: boolean): boolean {
|
||||
const authority = audience(request, secure)
|
||||
const cookies = header(request.headers, 'cookie')
|
||||
if (authority === undefined || cookies === undefined) return false
|
||||
const value = cookieValue(cookies, cookieName(authority))
|
||||
if (value === undefined) return false
|
||||
const parts = value.split('.')
|
||||
const [version, body, signature] = parts
|
||||
if (parts.length !== 3 || version !== `v${VERSION}` || body === undefined || signature === undefined) return false
|
||||
const supplied = decode(signature)
|
||||
const expected = createHmac('sha256', this.secret).update(`${version}.${body}`).digest()
|
||||
if (supplied?.byteLength !== expected.byteLength || !timingSafeEqual(supplied, expected)) return false
|
||||
const bytes = decode(body)
|
||||
if (bytes === undefined) return false
|
||||
const payload = parsePayload(bytes)
|
||||
if (payload === undefined || payload.authority !== authority) return false
|
||||
const now = Date.now()
|
||||
return payload.issuedAt <= now && payload.expiresAt > now && payload.expiresAt > payload.issuedAt
|
||||
&& payload.expiresAt - payload.issuedAt <= this.lifetimeMs
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/** Browser login invitations and deployment availability. */
|
||||
import type { Branded } from '@deepseek-ai/dsh-brand'
|
||||
|
||||
/** Identifier used to inspect or cancel an invitation; it cannot authorize login. */
|
||||
export type RemoteLoginId = Branded<'remote-login-id'>
|
||||
|
||||
/** Deployment prerequisite preventing QR login. */
|
||||
export type RemoteConnectionUnavailable = 'unreachable-host' | 'untrusted-host'
|
||||
|
||||
/** State of the invitation requested by the settings panel. */
|
||||
export type RemoteLoginState = 'none' | 'pending' | 'used' | 'expired' | 'cancelled' | 'replaced'
|
||||
|
||||
/** Settings projection; it never contains an invitation's secret. */
|
||||
export interface RemoteConnectionStatus {
|
||||
/** Clean advertised application URL. */
|
||||
readonly url: string
|
||||
/** Whether the advertised URL accepts remote browser requests. */
|
||||
readonly availability: 'available' | RemoteConnectionUnavailable
|
||||
/** State of the requested invitation, or none when no identifier was supplied. */
|
||||
readonly ticket: RemoteLoginState
|
||||
/** Interval between settings-panel status reads, in milliseconds. */
|
||||
readonly pollIntervalMs: number
|
||||
}
|
||||
|
||||
/** One short-lived bearer invitation, returned only when created. */
|
||||
export interface RemoteLoginTicket {
|
||||
/** Non-secret identifier for status reads and cancellation. */
|
||||
readonly id: RemoteLoginId
|
||||
/** Login page URL with the one-use credential in its fragment. */
|
||||
readonly url: string
|
||||
/** Lifetime in milliseconds, for browser countdowns independent of Host clock offset. */
|
||||
readonly lifetimeMs: number
|
||||
}
|
||||
|
||||
declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
interface RemoteErrorDetailsMap {
|
||||
'remote-connection/owner-required': Record<string, never>
|
||||
'remote-connection/disposed': Record<string, never>
|
||||
'remote-connection/unavailable': { readonly reason: RemoteConnectionUnavailable }
|
||||
/** The optional Token provider did not publish a login URL for this application. */
|
||||
'remote-connection/token-unavailable': Record<string, never>
|
||||
'remote-connection/url-too-long': Record<string, never>
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
// @vitest-environment jsdom
|
||||
/** Generated Remote methods and settings registrations leave with the plugin fiber. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { createElement, Fragment, useState } from 'react'
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { createSlotRenderer } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client'
|
||||
import { resolveSlotLabel, type PropsRenderSlots, type StandardSourceBinding } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
|
||||
import { apply as gatewayApply, inject as gatewayInject } from '@deepseek-ai/dsh-api-gateway/client'
|
||||
import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type { RemoteConnectionContentProps } from '@deepseek-ai/dsh-client-remote-connection/client'
|
||||
import { zh } from '../src/client/locales.ts'
|
||||
import { apply, inject } from '../src/client/index.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
function Root({ renderSlot, close }: PropsRenderSlots<'settings.section' | 'shell.overlay'> & Pick<RemoteConnectionContentProps, 'close'>) {
|
||||
const [visible, setVisible] = useState(true)
|
||||
return createElement(Fragment, null,
|
||||
createElement('button', { onClick: () => { setVisible(value => !value) } }, 'Toggle settings'),
|
||||
visible ? renderSlot('settings.section', { close }) : null,
|
||||
renderSlot('shell.overlay', {}))
|
||||
}
|
||||
|
||||
function Replacement({ useRemoteConnection, create, cancel, reload, close }: RemoteConnectionContentProps) {
|
||||
const { phase, ticket, remainingSeconds } = useRemoteConnection(state => state)
|
||||
return createElement('section', {
|
||||
'aria-label': 'Custom connection', 'data-phase': phase,
|
||||
'data-ticket': ticket?.id, 'data-seconds': remainingSeconds,
|
||||
},
|
||||
createElement('button', { onClick: create }, 'Create'),
|
||||
createElement('button', { onClick: cancel }, 'Cancel'),
|
||||
createElement('button', { onClick: reload }, 'Reload'),
|
||||
createElement('button', { onClick: close }, 'Close'))
|
||||
}
|
||||
|
||||
const replacementPlugin = {
|
||||
inject: ['slots'],
|
||||
apply(ctx: Context) {
|
||||
ctx.slots.inject('settings.remoteConnection.content', () => ctx.slots.register({
|
||||
name: 'settings.remoteConnection.content', priority: -1,
|
||||
}, Replacement))
|
||||
},
|
||||
}
|
||||
|
||||
async function bench(call: ConnectionHandle['rpc']['call'], beforeMount?: (ctx: Context) => Promise<void>) {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await ctx.plugin(TypertRegistry).await()
|
||||
ctx.provide('connection', {
|
||||
interactions: 'answer', isLoopback: true,
|
||||
openWebSocket: () => { throw new Error('This test uses in-process RPC') },
|
||||
generation: { getSnapshot: () => undefined, subscribe: () => () => {} },
|
||||
state: { getSnapshot: () => undefined, subscribe: () => () => {} },
|
||||
reconnect: () => {}, rpc: { call },
|
||||
registerGenerationSource: () => () => {},
|
||||
start: () => ({ stop: () => {} }),
|
||||
} satisfies ConnectionHandle)
|
||||
await ctx.plugin({ inject: [...gatewayInject], apply: gatewayApply }).await()
|
||||
await ctx.plugin(SlotRegistry).await()
|
||||
const slots = ctx.get('slots') as SlotRegistry
|
||||
slots.install(createSlotRenderer())
|
||||
const absentSession = createSnapshotStore<StandardSourceBinding>({ key: undefined, hooks: {}, keyedHooks: {}, props: {} })
|
||||
slots.installScope('session', {
|
||||
current: absentSession, bindingSource: () => absentSession, renderArea: () => null,
|
||||
})
|
||||
const close = vi.fn()
|
||||
const disposeRoot = slots.register({
|
||||
name: 'root', children: { 'settings.section': { kind: 'list', scope: 'root' }, 'shell.overlay': { kind: 'list', scope: 'root' } }, inject: () => ({ close }),
|
||||
}, Root)
|
||||
onTestFinished(disposeRoot)
|
||||
const locale = new LocaleRuntime(ctx)
|
||||
locale.setLocale('zh')
|
||||
ctx.provide('locale', locale)
|
||||
slots.installLocale(locale)
|
||||
await beforeMount?.(ctx)
|
||||
const fiber = ctx.plugin({ inject: [...inject], apply })
|
||||
await fiber.await()
|
||||
return { ctx, slots, locale, fiber, close }
|
||||
}
|
||||
|
||||
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 } }))
|
||||
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]!
|
||||
expect(entry.options.id).toBe('remote-connection')
|
||||
const face = slots.spec('settings.remoteConnection.content')?.inject
|
||||
expect(typeof face?.create).toBe('function')
|
||||
expect(typeof face?.cancel).toBe('function')
|
||||
expect(typeof face?.reload).toBe('function')
|
||||
expect(typeof face?.copyLink).toBe('function')
|
||||
expect(typeof face?.reloadLink).toBe('function')
|
||||
expect(face?.hooks).toBeDefined()
|
||||
for (const [language, title] of Object.entries({
|
||||
zh: '远程连接', en: 'Remote connection', ja: 'リモート接続', es: 'Conexión remota',
|
||||
fr: 'Connexion à distance', de: 'Fernverbindung', ru: 'Удалённое подключение', pt: 'Conexão remota',
|
||||
})) {
|
||||
if (language !== 'zh' && language !== 'en') {
|
||||
onTestFinished(locale.addLanguage({ id: language, label: language, fallback: 'en' }))
|
||||
}
|
||||
locale.setLocale(language)
|
||||
expect(resolveSlotLabel(entry.options.label)).toBe(title)
|
||||
}
|
||||
expect(ctx.get('remote.remoteConnection')).toBeDefined()
|
||||
expect(slots.entries('shell.overlay')).toHaveLength(1)
|
||||
await fiber.dispose()
|
||||
expect(slots.entries('settings.section')).toEqual([])
|
||||
expect(slots.entries('settings.remoteConnection.content')).toEqual([])
|
||||
expect(slots.spec('settings.remoteConnection.content')).toBeUndefined()
|
||||
expect(ctx.get('remote.remoteConnection')).toBeUndefined()
|
||||
expect(slots.entries('shell.overlay')).toEqual([])
|
||||
})
|
||||
|
||||
it.each(['status', 'loginUrl'] as const)('aborts an outstanding %s RPC and drains plugin teardown without its network response', async (pendingEndpoint) => {
|
||||
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 } })
|
||||
}
|
||||
if (signal !== undefined) requestSignals.push(signal)
|
||||
return new Promise<never>((_resolve, reject) => {
|
||||
signal?.addEventListener('abort', () => { reject(new Error('transport aborted')) }, { once: true })
|
||||
})
|
||||
})
|
||||
const { ctx, slots, fiber } = await bench(call)
|
||||
await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(pendingEndpoint === 'status' ? 1 : 2) })
|
||||
expect(requestSignals.every(signal => !signal.aborted)).toBe(true)
|
||||
await fiber.dispose()
|
||||
expect(requestSignals.every(signal => signal.aborted)).toBe(true)
|
||||
expect(ctx.get('remote.remoteConnection')).toBeUndefined()
|
||||
expect(slots.entries('settings.section')).toEqual([])
|
||||
expect(slots.entries('settings.remoteConnection.content')).toEqual([])
|
||||
})
|
||||
|
||||
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 call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => {
|
||||
if (endpoint === 'remoteConnection/loginUrl') return { ok: true, value: 'https://host.example/?token=private' }
|
||||
if (endpoint === 'remoteConnection/create') {
|
||||
return { ok: true, value: { id: 'invitation-a', url: 'https://host.example/remote-login#private', lifetimeMs: 120_000 } }
|
||||
}
|
||||
return { ok: true, value: status }
|
||||
})
|
||||
const { ctx, slots, close } = await bench(call)
|
||||
render(createElement(Fragment, null, slots.renderSlot('root', {})))
|
||||
fireEvent.click(await screen.findByRole('button', { name: '生成登录二维码' }))
|
||||
await screen.findByRole('img', { name: '一次性登录二维码' })
|
||||
|
||||
const replacement = ctx.plugin(replacementPlugin)
|
||||
await act(async () => { await replacement.await() })
|
||||
const custom = screen.getByRole('region', { name: 'Custom connection' })
|
||||
expect(screen.queryByRole('region', { name: '远程连接' })).toBeNull()
|
||||
expect(slots.entries('settings.section')).toHaveLength(1)
|
||||
expect(custom.dataset).toMatchObject({ phase: 'pending', ticket: 'invitation-a', seconds: '120' })
|
||||
clock.mockReturnValue(6000)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Reload' }))
|
||||
await vi.waitFor(() => { expect(custom.dataset.seconds).toBe('115') })
|
||||
expect(call).toHaveBeenLastCalledWith('/api', 'remoteConnection/status', { args: { id: 'invitation-a' } }, expect.any(AbortSignal))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
|
||||
expect(close).toHaveBeenCalledOnce()
|
||||
|
||||
await act(async () => { await replacement.dispose() })
|
||||
expect(screen.queryByRole('region', { name: 'Custom connection' })).toBeNull()
|
||||
expect(screen.getByRole('img', { name: '一次性登录二维码' })).toBeTruthy()
|
||||
expect(screen.getByRole('timer').textContent).toBe('115 秒后过期')
|
||||
expect(slots.entries('settings.section')).toHaveLength(1)
|
||||
expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/create')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('activates early replacement registrations with the owner and delegates creation and cancellation', async () => {
|
||||
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => {
|
||||
if (endpoint === 'remoteConnection/loginUrl') return { ok: true, value: 'https://host.example/?token=private' }
|
||||
if (endpoint === 'remoteConnection/create') {
|
||||
return { ok: true, value: { id: 'invitation-b', url: 'https://host.example/remote-login#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 } }
|
||||
})
|
||||
const { ctx, slots, fiber } = await bench(call, async (ctx) => {
|
||||
await ctx.plugin(replacementPlugin).await()
|
||||
expect(ctx.slots.entries('settings.remoteConnection.content')).toEqual([])
|
||||
})
|
||||
render(createElement(Fragment, null, slots.renderSlot('root', {})))
|
||||
const custom = await screen.findByRole('region', { name: 'Custom connection' })
|
||||
await vi.waitFor(() => { expect(custom.dataset.phase).toBe('ready') })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
|
||||
await vi.waitFor(() => { expect(custom.dataset).toMatchObject({ phase: 'pending', ticket: 'invitation-b' }) })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
await vi.waitFor(() => { expect(custom.dataset.phase).toBe('cancelled') })
|
||||
expect(custom.dataset.ticket).toBeUndefined()
|
||||
expect(call).toHaveBeenLastCalledWith('/api', 'remoteConnection/cancel', { args: { id: 'invitation-b' } }, expect.any(AbortSignal))
|
||||
expect(slots.entries('settings.section')).toHaveLength(1)
|
||||
await act(async () => { await fiber.dispose() })
|
||||
expect(screen.queryByRole('region')).toBeNull()
|
||||
expect(slots.entries('settings.remoteConnection.content')).toEqual([])
|
||||
await act(async () => { await ctx.plugin({ inject: [...inject], apply }).await() })
|
||||
const restored = screen.getByRole('region', { name: 'Custom connection' })
|
||||
await vi.waitFor(() => { expect(restored.dataset.phase).toBe('ready') })
|
||||
expect(restored.dataset.ticket).toBeUndefined()
|
||||
expect(slots.entries('settings.section')).toHaveLength(1)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Create' }))
|
||||
await vi.waitFor(() => { expect(restored.dataset).toMatchObject({ phase: 'pending', ticket: 'invitation-b' }) })
|
||||
})
|
||||
|
||||
it('keeps copy feedback in the shell after the settings panel closes and localizes failures', async () => {
|
||||
const write = vi.fn().mockResolvedValue(undefined)
|
||||
const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: write } })
|
||||
onTestFinished(() => {
|
||||
if (clipboardDescriptor === undefined) Reflect.deleteProperty(navigator, 'clipboard')
|
||||
else Object.defineProperty(navigator, 'clipboard', clipboardDescriptor)
|
||||
})
|
||||
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 },
|
||||
}))
|
||||
const { ctx, slots } = await bench(call)
|
||||
render(slots.renderSlot('root', {}))
|
||||
const copy = await screen.findByRole('button', { name: zh.copyLink })
|
||||
await vi.waitFor(() => { expect(copy).toHaveProperty('disabled', false) })
|
||||
fireEvent.click(copy)
|
||||
await screen.findByText(zh.linkCopied)
|
||||
expect(write).toHaveBeenCalledWith(url)
|
||||
expect(screen.getByText(zh.linkWarning)).toBeTruthy()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Toggle settings' }))
|
||||
expect(screen.queryByRole('region', { name: zh.title })).toBeNull()
|
||||
expect(screen.getByRole('alert').textContent).toBe(zh.linkCopied)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Toggle settings' }))
|
||||
write.mockRejectedValueOnce(new Error('clipboard permission'))
|
||||
fireEvent.click(await screen.findByRole('button', { name: zh.copied }))
|
||||
await screen.findByText(zh.copyFailed)
|
||||
expect(screen.getByText(zh.linkWarning)).toBeTruthy()
|
||||
expect(screen.getByText(url)).toBeTruthy()
|
||||
call.mockImplementation(async (_channel, endpoint) => ({
|
||||
ok: true, value: endpoint === 'remoteConnection/loginUrl' ? `${url}-new`
|
||||
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
|
||||
}))
|
||||
act(() => { ctx.emit('connection/reset') })
|
||||
await vi.waitFor(() => { expect(screen.getByRole('button', { name: zh.copyLink })).toHaveProperty('disabled', false) })
|
||||
expect(screen.queryByText(zh.linkWarning)).toBeNull()
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh.copyLink })) })
|
||||
expect(write).toHaveBeenLastCalledWith(`${url}-new`)
|
||||
expect(screen.getByRole('alert').textContent).toBe(zh.linkCopied)
|
||||
act(() => { vi.advanceTimersByTime(4000) })
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
expect(screen.getByText(zh.linkWarning)).toBeTruthy()
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('prefetches the login link only after deployment becomes available', async () => {
|
||||
let available = false
|
||||
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 ? 'available' : 'untrusted-host', ticket: 'none', pollIntervalMs: 1000 },
|
||||
}))
|
||||
const { ctx, slots } = await bench(call)
|
||||
await vi.waitFor(() => { expect(call).toHaveBeenCalledOnce() })
|
||||
act(() => { ctx.emit('connection/reset') })
|
||||
await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(2) })
|
||||
expect(call.mock.calls.every(([, endpoint]) => endpoint === 'remoteConnection/status')).toBe(true)
|
||||
available = true
|
||||
act(() => { ctx.emit('connection/reset') })
|
||||
await vi.waitFor(() => { expect(call.mock.calls.filter(([, endpoint]) => endpoint === 'remoteConnection/loginUrl')).toHaveLength(1) })
|
||||
const face = slots.spec('settings.remoteConnection.content')!.inject
|
||||
available = false
|
||||
act(() => { face.reload() })
|
||||
await vi.waitFor(() => { expect(face.hooks.remoteConnection.getSnapshot().deployment?.availability).toBe('untrusted-host') })
|
||||
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(1)
|
||||
})
|
||||
|
||||
it('keeps plugin disposal pending until a clipboard write settles', async () => {
|
||||
let finish!: () => void
|
||||
const pendingWrite = new Promise<void>((resolve) => { finish = resolve })
|
||||
const write = vi.fn(() => pendingWrite)
|
||||
const descriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard')
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: write } })
|
||||
onTestFinished(() => {
|
||||
if (descriptor === undefined) Reflect.deleteProperty(navigator, 'clipboard')
|
||||
else Object.defineProperty(navigator, 'clipboard', descriptor)
|
||||
})
|
||||
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)
|
||||
render(slots.renderSlot('root', {}))
|
||||
const copy = await screen.findByRole('button', { name: zh.copyLink })
|
||||
await vi.waitFor(() => { expect(copy).toHaveProperty('disabled', false) })
|
||||
try {
|
||||
fireEvent.click(copy)
|
||||
expect(write).toHaveBeenCalledOnce()
|
||||
let disposed = false
|
||||
const disposal = fiber.dispose().then(() => { disposed = true })
|
||||
await vi.waitFor(() => { expect(slots.entries('settings.section')).toEqual([]) })
|
||||
expect(disposed).toBe(false)
|
||||
finish()
|
||||
await act(async () => { await disposal })
|
||||
expect(disposed).toBe(true)
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
} finally {
|
||||
finish()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,267 @@
|
||||
/** Invitation state transitions and teardown under delayed Remote responses. */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
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 ticket: RemoteLoginTicket = { id: 'invitation-a' as RemoteLoginId, url: 'https://host.example/app/remote-login#token=private-a', lifetimeMs: 10_000 }
|
||||
const failure = { ok: false as const, error: new RemoteError('gateway/internal', 'unavailable', {}) }
|
||||
const controllers: RemoteConnectionController[] = []
|
||||
|
||||
beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(2000) })
|
||||
afterEach(async () => {
|
||||
await Promise.all(controllers.splice(0).map(controller => controller.dispose()))
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
function setup() {
|
||||
const remote = {
|
||||
status: vi.fn<RemoteConnectionApi['status']>().mockResolvedValue({ ok: true, value: deployment }),
|
||||
create: vi.fn<RemoteConnectionApi['create']>().mockResolvedValue({ ok: true, value: ticket }),
|
||||
cancel: vi.fn<RemoteConnectionApi['cancel']>().mockResolvedValue({ ok: true, value: 'cancelled' }),
|
||||
loginUrl: vi.fn<RemoteConnectionApi['loginUrl']>().mockResolvedValue({ ok: true, value: 'https://host.example/app/?token=private' }),
|
||||
}
|
||||
const controller = new RemoteConnectionController(remote)
|
||||
controllers.push(controller)
|
||||
return { remote, controller, state: () => controller.store.getSnapshot() }
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
const promise = new Promise<T>((settle) => { resolve = settle })
|
||||
return { promise, resolve }
|
||||
}
|
||||
|
||||
describe('Remote connection invitation state', () => {
|
||||
it('loads the clean address and only creates a code when the deployment is available', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.create()
|
||||
expect(remote.create).not.toHaveBeenCalled()
|
||||
remote.status.mockResolvedValueOnce({ ok: true, value: { ...deployment, availability: 'untrusted-host' } })
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
expect(state()).toMatchObject({ phase: 'ready', deployment: { availability: 'untrusted-host' } })
|
||||
expect(remote.create).not.toHaveBeenCalled()
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
expect(remote.status).toHaveBeenCalledWith(null)
|
||||
expect(state()).toMatchObject({ phase: 'pending', ticket })
|
||||
})
|
||||
|
||||
it('only issues one code per pending gesture, then forgets the secret after redemption', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
const pending = deferred<RemoteResult<RemoteLoginTicket>>()
|
||||
remote.create.mockReturnValueOnce(pending.promise)
|
||||
const creation = controller.create()
|
||||
expect(state()).toMatchObject({ phase: 'creating', ticket: null, retainDetails: false })
|
||||
await controller.create()
|
||||
await controller.cancel()
|
||||
await controller.load()
|
||||
expect(remote.create).toHaveBeenCalledTimes(1)
|
||||
expect(remote.cancel).not.toHaveBeenCalled()
|
||||
pending.resolve({ ok: true, value: ticket })
|
||||
await creation
|
||||
remote.status.mockResolvedValue({ ok: true, value: { ...deployment, ticket: 'used' } })
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(remote.status).toHaveBeenLastCalledWith(ticket.id)
|
||||
expect(state()).toMatchObject({ phase: 'used', ticket: null })
|
||||
await vi.advanceTimersByTimeAsync(12_000)
|
||||
expect(state().phase).toBe('used')
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('hides the previous code as soon as replacement starts, and never restores it after an unknown outcome', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
const pending = deferred<RemoteResult<RemoteLoginTicket>>()
|
||||
remote.create.mockReturnValueOnce(pending.promise)
|
||||
const replacement = controller.create()
|
||||
expect(state()).toMatchObject({ phase: 'creating', ticket: null, retainDetails: true, remainingSeconds: 10 })
|
||||
pending.resolve(failure)
|
||||
await replacement
|
||||
expect(state()).toMatchObject({ phase: 'error', ticket: null, error: 'createFailed', retainDetails: false })
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('keeps the countdown during replacement and resets it when the new code arrives', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
remote.status.mockResolvedValue({ ok: true, value: { ...deployment, ticket: 'pending' } })
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
const pending = deferred<RemoteResult<RemoteLoginTicket>>()
|
||||
remote.create.mockReturnValueOnce(pending.promise)
|
||||
const replacement = controller.create()
|
||||
expect(state()).toMatchObject({ phase: 'creating', ticket: null, retainDetails: true, remainingSeconds: 9 })
|
||||
const next = { ...ticket, id: 'invitation-b' as RemoteLoginId, url: 'https://host.example/app/remote-login#token=private-b', lifetimeMs: 20_000 }
|
||||
pending.resolve({ ok: true, value: next })
|
||||
await replacement
|
||||
expect(state()).toMatchObject({ phase: 'pending', ticket: next, retainDetails: false, remainingSeconds: 20 })
|
||||
})
|
||||
|
||||
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()
|
||||
await controller.create()
|
||||
const pending = deferred<RemoteResult<RemoteConnectionStatus>>()
|
||||
remote.status.mockReturnValueOnce(pending.promise)
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(state().phase).toBe('pending')
|
||||
await vi.advanceTimersByTimeAsync(9000)
|
||||
expect(state()).toMatchObject({ phase: 'expired', ticket: null })
|
||||
pending.resolve({ ok: true, value: { ...deployment, ticket: 'pending' } })
|
||||
await Promise.resolve()
|
||||
expect(state().phase).toBe('expired')
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('polls a live code and drops it if another owner replaces it', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
remote.status.mockResolvedValueOnce({ ok: true, value: { ...deployment, ticket: 'pending' } })
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(state()).toMatchObject({ phase: 'pending', remainingSeconds: 9 })
|
||||
remote.status.mockResolvedValueOnce({ ok: true, value: { ...deployment, ticket: 'none' } })
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(state()).toMatchObject({ phase: 'replaced', ticket: null })
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
|
||||
it('cancels its exact code and ignores an older in-flight status reply', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.cancel()
|
||||
expect(remote.cancel).not.toHaveBeenCalled()
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
const pending = deferred<RemoteResult<RemoteConnectionStatus>>()
|
||||
remote.status.mockReturnValueOnce(pending.promise)
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
await controller.cancel()
|
||||
expect(remote.cancel).toHaveBeenCalledWith(ticket.id)
|
||||
expect(state()).toMatchObject({ phase: 'cancelled', ticket: null })
|
||||
pending.resolve({ ok: true, value: { ...deployment, ticket: 'pending' } })
|
||||
await Promise.resolve()
|
||||
expect(state().phase).toBe('cancelled')
|
||||
})
|
||||
|
||||
it.each(['reply', 'rejection'] as const)('keeps cancellation uncertainty visible after a %s failure', async (kind) => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
if (kind === 'reply') remote.cancel.mockResolvedValueOnce(failure)
|
||||
else remote.cancel.mockRejectedValueOnce(new Error('network'))
|
||||
await controller.cancel()
|
||||
expect(state()).toMatchObject({ phase: 'error', error: 'cancelFailed', ticket })
|
||||
await controller.cancel()
|
||||
expect(state()).toMatchObject({ phase: 'cancelled', ticket: null })
|
||||
})
|
||||
|
||||
it.each(['reply', 'rejection'] as const)('reports deployment read failures from a %s and permits retry', async (kind) => {
|
||||
const { remote, controller, state } = setup()
|
||||
if (kind === 'reply') remote.status.mockResolvedValueOnce(failure)
|
||||
else remote.status.mockRejectedValueOnce(new Error('network'))
|
||||
await controller.load()
|
||||
expect(state()).toMatchObject({ phase: 'error', error: 'loadFailed' })
|
||||
await controller.load()
|
||||
expect(state()).toMatchObject({ phase: 'ready', error: null })
|
||||
})
|
||||
|
||||
it.each(['reply', 'rejection'] as const)('hides the QR on a status %s failure, and can recover its confirmed state', async (kind) => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
if (kind === 'reply') remote.status.mockResolvedValueOnce(failure)
|
||||
else remote.status.mockRejectedValueOnce(new Error('network'))
|
||||
await vi.advanceTimersByTimeAsync(1000)
|
||||
expect(state()).toMatchObject({ phase: 'error', error: 'statusFailed' })
|
||||
remote.status.mockResolvedValueOnce({ ok: true, value: { ...deployment, ticket: 'pending' } })
|
||||
await controller.load()
|
||||
expect(state()).toMatchObject({ phase: 'pending', error: null })
|
||||
})
|
||||
|
||||
it('reports thrown creation failures and uses a monotonic clock for the code lifetime', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
remote.create.mockRejectedValueOnce(new Error('network'))
|
||||
await controller.create()
|
||||
expect(state()).toMatchObject({ phase: 'error', error: 'createFailed' })
|
||||
remote.create.mockResolvedValueOnce({ ok: true, value: ticket })
|
||||
await controller.create()
|
||||
expect(state()).toMatchObject({ phase: 'pending', remainingSeconds: 10 })
|
||||
remote.status.mockResolvedValue({ ok: true, value: { ...deployment, ticket: 'pending' } })
|
||||
const clock = vi.spyOn(performance, 'now').mockReturnValue(performance.now() + 11_000)
|
||||
try { await controller.load() } finally { clock.mockRestore() }
|
||||
expect(state()).toMatchObject({ phase: 'expired', ticket: null, remainingSeconds: 0 })
|
||||
})
|
||||
|
||||
it('awaits disposal without publishing late credentials or starting further calls', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
const pending = deferred<RemoteResult<RemoteLoginTicket>>()
|
||||
remote.create.mockReturnValueOnce(pending.promise)
|
||||
const creation = controller.create()
|
||||
const disposal = controller.dispose()
|
||||
pending.resolve({ ok: true, value: ticket })
|
||||
await Promise.all([creation, disposal])
|
||||
expect(state().ticket).toBeNull()
|
||||
await controller.create()
|
||||
await controller.cancel()
|
||||
await controller.load()
|
||||
expect(remote.create).toHaveBeenCalledTimes(1)
|
||||
expect(remote.status).toHaveBeenCalledTimes(1)
|
||||
expect(vi.getTimerCount()).toBe(0)
|
||||
})
|
||||
it('runs the section actions against the same invitation owner', async () => {
|
||||
const { controller, state } = setup()
|
||||
const face = controller.inject()
|
||||
face.reload()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(state().phase).toBe('ready')
|
||||
face.create()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(state().phase).toBe('pending')
|
||||
face.cancel()
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
expect(state().phase).toBe('cancelled')
|
||||
})
|
||||
|
||||
it('does not publish a cancellation response after disposal', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
const pending = deferred<RemoteResult<RemoteLoginState>>()
|
||||
remote.cancel.mockReturnValueOnce(pending.promise)
|
||||
const cancellation = controller.cancel()
|
||||
const disposal = controller.dispose()
|
||||
pending.resolve({ ok: true, value: 'cancelled' })
|
||||
await Promise.all([cancellation, disposal])
|
||||
expect(state()).toMatchObject({ phase: 'cancelling', ticket: null })
|
||||
})
|
||||
|
||||
it('does not publish a rejected request after disposal', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
let reject!: (error: Error) => void
|
||||
remote.create.mockReturnValueOnce(new Promise((_resolve, fail) => { reject = fail }))
|
||||
const creation = controller.create()
|
||||
const disposal = controller.dispose()
|
||||
reject(new Error('closed transport'))
|
||||
await Promise.all([creation, disposal])
|
||||
expect(state()).toMatchObject({ phase: 'creating', ticket: null, error: null })
|
||||
})
|
||||
|
||||
it.each(['used', 'expired', 'replaced', 'none'] as const)('shows %s when cancellation finds that outcome already committed', async (outcome) => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
await controller.create()
|
||||
remote.cancel.mockResolvedValueOnce({ ok: true, value: outcome })
|
||||
await controller.cancel()
|
||||
expect(state()).toMatchObject({ phase: outcome === 'none' ? 'replaced' : outcome, ticket: null })
|
||||
})
|
||||
|
||||
})
|
||||
@@ -0,0 +1,152 @@
|
||||
/** Login-link credentials stay in memory and clipboard feedback follows the actual write. */
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { LoginLinkController } from '../src/client/login-link-controller.ts'
|
||||
import type { RemoteConnectionApi } from '../src/client/remote-connection-controller.ts'
|
||||
|
||||
const url = 'https://host.example/app/?token=private-login-token'
|
||||
|
||||
function setup() {
|
||||
const remote = { loginUrl: vi.fn<RemoteConnectionApi['loginUrl']>().mockResolvedValue({ ok: true, value: url }) }
|
||||
const write = vi.fn<(text: string) => Promise<boolean>>().mockResolvedValue(true)
|
||||
const controller = new LoginLinkController(remote, write)
|
||||
return { remote, write, controller, state: () => controller.store.getSnapshot() }
|
||||
}
|
||||
|
||||
it('prefetches the tokenized link and writes it during the copy gesture without a second request', async () => {
|
||||
const { remote, write, controller, state } = setup()
|
||||
await controller.copy()
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
await controller.load()
|
||||
expect(state()).toMatchObject({ phase: 'ready', url, copied: false, notice: null })
|
||||
const copying = controller.copy()
|
||||
expect(write).toHaveBeenCalledWith(url)
|
||||
await copying
|
||||
expect(state()).toMatchObject({ phase: 'ready', copied: true, notice: 'linkCopied', sequence: 1 })
|
||||
await controller.copy()
|
||||
expect(remote.loginUrl).toHaveBeenCalledOnce()
|
||||
expect(state().sequence).toBe(2)
|
||||
controller.inject().dismissCopyNotice(1)
|
||||
expect(state().notice).toBe('linkCopied')
|
||||
controller.inject().dismissCopyNotice(2)
|
||||
expect(state().notice).toBeNull()
|
||||
expect(state().copied).toBe(true)
|
||||
await controller.dispose()
|
||||
expect(state()).toMatchObject({ url: null, notice: null, copied: false })
|
||||
})
|
||||
|
||||
it('reports clipboard refusal and rejection without claiming that a link was copied', async () => {
|
||||
const { write, controller, state } = setup()
|
||||
await controller.load()
|
||||
write.mockResolvedValueOnce(false).mockRejectedValueOnce(new Error('clipboard denied'))
|
||||
await controller.copy()
|
||||
expect(state()).toMatchObject({ copied: false, notice: 'copyFailed', url })
|
||||
await controller.copy()
|
||||
expect(state()).toMatchObject({ copied: false, notice: 'copyFailed', sequence: 2 })
|
||||
await controller.copy()
|
||||
expect(state()).toMatchObject({ copied: true, notice: 'linkCopied', sequence: 3 })
|
||||
await controller.dispose()
|
||||
})
|
||||
|
||||
it('keeps failed link reads retryable and shares an outstanding read', async () => {
|
||||
const { remote, controller, write, state } = setup()
|
||||
remote.loginUrl.mockRejectedValueOnce(new Error('connection unavailable'))
|
||||
const first = controller.load()
|
||||
expect(controller.load()).toBe(first)
|
||||
await first
|
||||
expect(state()).toMatchObject({ phase: 'error', url: null, copied: false })
|
||||
await controller.copy()
|
||||
expect(write).not.toHaveBeenCalled()
|
||||
remote.loginUrl.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'unavailable', {}) })
|
||||
await controller.load()
|
||||
expect(state().phase).toBe('error')
|
||||
controller.inject().reloadLink()
|
||||
await vi.waitFor(() => { expect(state().phase).toBe('ready') })
|
||||
await controller.dispose()
|
||||
})
|
||||
|
||||
it('prevents overlapping clipboard writes and ignores completion after disposal', async () => {
|
||||
const { write, controller, state } = setup()
|
||||
await controller.load()
|
||||
let finish!: (copied: boolean) => void
|
||||
write.mockReturnValueOnce(new Promise((resolve) => { finish = resolve }))
|
||||
controller.inject().copyLink()
|
||||
await controller.copy()
|
||||
const reloading = controller.load()
|
||||
expect(write).toHaveBeenCalledOnce()
|
||||
expect(state()).toMatchObject({ phase: 'copying', copied: false })
|
||||
let disposed = false
|
||||
const disposal = controller.dispose().then(() => { disposed = true })
|
||||
await Promise.resolve()
|
||||
expect(disposed).toBe(false)
|
||||
finish(true)
|
||||
await Promise.all([reloading, disposal])
|
||||
expect(disposed).toBe(true)
|
||||
expect(state()).toMatchObject({ url: null, copied: false, notice: null })
|
||||
await controller.load()
|
||||
await controller.copy()
|
||||
expect(write).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('refreshes the cached token after an outstanding clipboard write completes', async () => {
|
||||
const { remote, write, controller, state } = setup()
|
||||
await controller.load()
|
||||
let finish!: (copied: boolean) => void
|
||||
write.mockReturnValueOnce(new Promise((resolve) => { finish = resolve }))
|
||||
const copying = controller.copy()
|
||||
const reloading = controller.load()
|
||||
expect(remote.loginUrl).toHaveBeenCalledOnce()
|
||||
remote.loginUrl.mockResolvedValueOnce({ ok: true, value: `${url}-new` })
|
||||
finish(true)
|
||||
await Promise.all([copying, reloading])
|
||||
expect(state()).toMatchObject({ phase: 'ready', url: `${url}-new`, copied: false, notice: null })
|
||||
await controller.copy()
|
||||
expect(write).toHaveBeenLastCalledWith(`${url}-new`)
|
||||
await controller.dispose()
|
||||
})
|
||||
|
||||
it.each(['response', 'failure'] as const)('discards a login-link %s arriving after disposal and refuses later refreshes', async (outcome) => {
|
||||
const { remote, controller, state } = setup()
|
||||
let finish!: (result: Awaited<ReturnType<RemoteConnectionApi['loginUrl']>>) => void
|
||||
let reject!: (error: Error) => void
|
||||
remote.loginUrl.mockReturnValueOnce(new Promise((resolve, rejectRequest) => { finish = resolve; reject = rejectRequest }))
|
||||
const loading = controller.load()
|
||||
let disposed = false
|
||||
const disposal = controller.dispose().then(() => { disposed = true })
|
||||
await Promise.resolve()
|
||||
expect(disposed).toBe(false)
|
||||
if (outcome === 'response') finish({ ok: true, value: url })
|
||||
else reject(new Error('transport closed'))
|
||||
await Promise.all([loading, disposal])
|
||||
expect(disposed).toBe(true)
|
||||
expect(state()).toMatchObject({ url: null, copied: false, notice: null })
|
||||
await controller.refresh()
|
||||
expect(remote.loginUrl).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('resets copy success for a changed URL and preserves it for the same URL', async () => {
|
||||
const { remote, controller, state } = setup()
|
||||
await controller.load()
|
||||
await controller.copy()
|
||||
remote.loginUrl.mockResolvedValue({ ok: true, value: `${url}-new` })
|
||||
await controller.refresh()
|
||||
expect(state()).toMatchObject({ url: `${url}-new`, copied: false, notice: null })
|
||||
await controller.copy()
|
||||
await controller.refresh()
|
||||
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 () => {
|
||||
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 })
|
||||
await controller.dispose()
|
||||
})
|
||||
@@ -0,0 +1,259 @@
|
||||
// @vitest-environment jsdom
|
||||
/** Anonymous login-page effects before the authenticated application loads. */
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { enterAuthenticationPage, enterBrowser, renderAuthenticationPage, renderLoginPage } from '../src/login-page.ts'
|
||||
import { loginLocales } from '../src/login-locales.ts'
|
||||
|
||||
const TOKEN = 'a'.repeat(43)
|
||||
const initialUrl = window.location.href
|
||||
|
||||
afterEach(() => {
|
||||
window.dispatchEvent(new Event('pagehide'))
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
history.replaceState(null, '', initialUrl)
|
||||
document.documentElement.innerHTML = '<head></head><body></body>'
|
||||
})
|
||||
|
||||
function page(path = `/remote-login#${TOKEN}`, language = 'en-US') {
|
||||
const html = new DOMParser().parseFromString(renderLoginPage(), 'text/html')
|
||||
document.documentElement.innerHTML = html.documentElement.innerHTML
|
||||
history.replaceState(null, '', path)
|
||||
const actualLocation = window.location
|
||||
const replace = vi.fn<Location['replace']>()
|
||||
vi.stubGlobal('location', {
|
||||
get hash() { return actualLocation.hash },
|
||||
get pathname() { return actualLocation.pathname },
|
||||
replace,
|
||||
} satisfies Pick<Location, 'hash' | 'pathname' | 'replace'>)
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue(language)
|
||||
const exchange = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 204 }))
|
||||
vi.stubGlobal('fetch', exchange)
|
||||
return {
|
||||
exchange, replace, actualLocation,
|
||||
status: document.getElementById('status') as HTMLElement,
|
||||
}
|
||||
}
|
||||
|
||||
function authenticationPage(options = { tokenLoginEnabled: true, tokenRejected: false }, language = 'en-US') {
|
||||
const html = new DOMParser().parseFromString(renderAuthenticationPage(options), 'text/html')
|
||||
document.documentElement.innerHTML = html.documentElement.innerHTML
|
||||
history.replaceState(null, '', '/mount/')
|
||||
const actualLocation = window.location
|
||||
const replace = vi.fn<Location['replace']>()
|
||||
vi.stubGlobal('location', {
|
||||
get href() { return actualLocation.href },
|
||||
replace,
|
||||
} satisfies Pick<Location, 'href' | 'replace'>)
|
||||
vi.spyOn(navigator, 'language', 'get').mockReturnValue(language)
|
||||
const exchange = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status: 200 }))
|
||||
vi.stubGlobal('fetch', exchange)
|
||||
return {
|
||||
exchange, replace, actualLocation,
|
||||
form: document.getElementById('token-form') as HTMLFormElement,
|
||||
input: document.getElementById('token') as HTMLInputElement,
|
||||
error: document.getElementById('token-error') as HTMLElement,
|
||||
submit: document.getElementById('token-submit') as HTMLButtonElement,
|
||||
}
|
||||
}
|
||||
|
||||
it.each(['en-US', 'zh-CN'])('shows the anonymous Token form without Client boot data in %s', (language) => {
|
||||
const fixture = authenticationPage(undefined, language)
|
||||
enterAuthenticationPage(loginLocales)
|
||||
const t = language.startsWith('zh') ? loginLocales.zh : loginLocales.en
|
||||
expect(document.title).toBe(t.authenticationTitle)
|
||||
expect(document.getElementById('description')?.textContent).toBe(t.authenticationDescription)
|
||||
expect(document.getElementById('token-label')?.textContent).toBe(t.tokenLabel)
|
||||
expect(document.getElementById('token-hint')?.textContent).toBe(t.tokenHint)
|
||||
expect(fixture.form.method).toBe('get')
|
||||
expect(fixture.form.action).toBe(new URL('/mount/', fixture.actualLocation.href).href)
|
||||
expect(fixture.input.type).toBe('password')
|
||||
expect(fixture.input.required).toBe(true)
|
||||
expect(fixture.input.getAttribute('aria-describedby')).toBe('token-hint token-error')
|
||||
expect(fixture.submit.textContent).toBe(t.tokenSubmit)
|
||||
expect(document.documentElement.innerHTML).not.toContain('__DSH_BOOT__')
|
||||
expect(document.documentElement.innerHTML).not.toContain('authPages')
|
||||
expect(fixture.exchange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('hides the Token form when its provider is unavailable', () => {
|
||||
const fixture = authenticationPage({ tokenLoginEnabled: false, tokenRejected: false }, 'zh-CN')
|
||||
enterAuthenticationPage(loginLocales)
|
||||
expect(document.getElementById('description')?.textContent).toBe(loginLocales.zh.authenticationUnavailable)
|
||||
expect(document.getElementById('token-form')).toBeNull()
|
||||
expect(fixture.exchange).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('removes a rejected Token from the address and keeps localized field feedback', () => {
|
||||
const fixture = authenticationPage({ tokenLoginEnabled: true, tokenRejected: true }, 'zh-CN')
|
||||
history.replaceState(null, '', `/mount/?token=${TOKEN}&keep=value`)
|
||||
enterAuthenticationPage(loginLocales, true)
|
||||
expect(fixture.actualLocation.href).not.toContain(TOKEN)
|
||||
expect(fixture.actualLocation.search).toBe('?keep=value')
|
||||
expect(fixture.error.textContent).toBe(loginLocales.zh.tokenInvalid)
|
||||
expect(fixture.input.getAttribute('aria-invalid')).toBe('true')
|
||||
fixture.input.value = TOKEN
|
||||
fixture.input.dispatchEvent(new Event('input'))
|
||||
expect(fixture.error.textContent).toBe('')
|
||||
expect(fixture.input.hasAttribute('aria-invalid')).toBe(false)
|
||||
})
|
||||
|
||||
it.each(['short', `https://elsewhere.example/?token=${TOKEN}&token=${TOKEN}`, `https://elsewhere.example/?other=${TOKEN}`])('rejects an invalid Token or link without sending it: %s', (value) => {
|
||||
const fixture = authenticationPage()
|
||||
enterAuthenticationPage(loginLocales)
|
||||
fixture.input.value = value
|
||||
expect(fixture.form.dispatchEvent(new Event('submit', { cancelable: true }))).toBe(false)
|
||||
expect(fixture.error.textContent).toBe(loginLocales.en.tokenInvalid)
|
||||
expect(fixture.input.getAttribute('aria-invalid')).toBe('true')
|
||||
expect(fixture.exchange).not.toHaveBeenCalled()
|
||||
expect(fixture.replace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([TOKEN, ` https://elsewhere.example/path?token=${TOKEN} `])('uses only the Token from the submitted value at the current application mount', async (value) => {
|
||||
const fixture = authenticationPage()
|
||||
const pending = Promise.withResolvers<Response>()
|
||||
fixture.exchange.mockReturnValue(pending.promise)
|
||||
enterAuthenticationPage(loginLocales)
|
||||
fixture.input.value = value
|
||||
fixture.form.dispatchEvent(new Event('submit', { cancelable: true }))
|
||||
const [target, init] = fixture.exchange.mock.calls[0]!
|
||||
expect(target).toBe(new URL(`/mount/?token=${TOKEN}`, fixture.actualLocation.href).href)
|
||||
expect(init).toMatchObject({ method: 'GET', credentials: 'same-origin', cache: 'no-store', redirect: 'follow' })
|
||||
expect(init?.signal).toBeInstanceOf(AbortSignal)
|
||||
expect(fixture.submit.disabled).toBe(true)
|
||||
expect(fixture.submit.textContent).toBe(loginLocales.en.tokenPending)
|
||||
expect(fixture.form.getAttribute('aria-busy')).toBe('true')
|
||||
fixture.form.dispatchEvent(new Event('submit', { cancelable: true }))
|
||||
expect(fixture.exchange).toHaveBeenCalledTimes(1)
|
||||
pending.resolve(new Response(null, { status: 200 }))
|
||||
await expect.poll(() => fixture.replace.mock.calls).toEqual([['./']])
|
||||
await expect.poll(() => fixture.submit.disabled).toBe(false)
|
||||
expect(fixture.actualLocation.href).not.toContain(TOKEN)
|
||||
})
|
||||
|
||||
it.each([401, 403, 503])('keeps HTTP %i on the anonymous page and allows another submission', async (status) => {
|
||||
const fixture = authenticationPage(undefined, 'zh-CN')
|
||||
fixture.exchange.mockResolvedValue(new Response(null, { status }))
|
||||
enterAuthenticationPage(loginLocales)
|
||||
fixture.input.value = TOKEN
|
||||
fixture.form.dispatchEvent(new Event('submit', { cancelable: true }))
|
||||
await expect.poll(() => fixture.error.textContent).toBe(status === 401 ? loginLocales.zh.tokenInvalid : loginLocales.zh.tokenFailed)
|
||||
await expect.poll(() => fixture.submit.disabled).toBe(false)
|
||||
expect(fixture.input.getAttribute('aria-invalid')).toBe(status === 401 ? 'true' : null)
|
||||
expect(fixture.replace).not.toHaveBeenCalled()
|
||||
fixture.exchange.mockResolvedValue(new Response(null, { status: 200 }))
|
||||
fixture.form.dispatchEvent(new Event('submit', { cancelable: true }))
|
||||
await expect.poll(() => fixture.replace.mock.calls).toEqual([['./']])
|
||||
})
|
||||
|
||||
it('reports a failed Token request without automatically replaying it', async () => {
|
||||
const fixture = authenticationPage()
|
||||
fixture.exchange.mockRejectedValue(new TypeError('connection closed'))
|
||||
enterAuthenticationPage(loginLocales)
|
||||
fixture.input.value = TOKEN
|
||||
fixture.form.dispatchEvent(new Event('submit', { cancelable: true }))
|
||||
await expect.poll(() => fixture.error.textContent).toBe(loginLocales.en.tokenFailed)
|
||||
expect(fixture.exchange).toHaveBeenCalledTimes(1)
|
||||
expect(fixture.replace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('aborts each in-flight Token request when the page leaves, including after a previous failure', async () => {
|
||||
const fixture = authenticationPage()
|
||||
fixture.exchange.mockResolvedValueOnce(new Response(null, { status: 401 }))
|
||||
enterAuthenticationPage(loginLocales)
|
||||
fixture.input.value = TOKEN
|
||||
fixture.form.dispatchEvent(new Event('submit', { cancelable: true }))
|
||||
await expect.poll(() => fixture.submit.disabled).toBe(false)
|
||||
let signal: AbortSignal | undefined
|
||||
fixture.exchange.mockImplementation((_target, init) => new Promise<Response>((_resolve, reject) => {
|
||||
signal = init?.signal ?? undefined
|
||||
signal?.addEventListener('abort', () => { reject(new DOMException('page hidden', 'AbortError')) }, { once: true })
|
||||
}))
|
||||
fixture.form.dispatchEvent(new Event('submit', { cancelable: true }))
|
||||
expect(signal?.aborted).toBe(false)
|
||||
window.dispatchEvent(new Event('pagehide'))
|
||||
expect(signal?.aborted).toBe(true)
|
||||
await expect.poll(() => fixture.submit.disabled).toBe(false)
|
||||
expect(fixture.error.textContent).toBe('')
|
||||
expect(fixture.replace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['', '#short', `#${'a'.repeat(42)}!`])('removes an invalid fragment without sending a login request: %s', (fragment) => {
|
||||
const fixture = page(`/remote-login${fragment}`)
|
||||
enterBrowser(loginLocales)
|
||||
expect(fixture.actualLocation.hash).toBe('')
|
||||
expect(fixture.status.textContent).toBe(loginLocales.en.invalid)
|
||||
expect(fixture.exchange).not.toHaveBeenCalled()
|
||||
expect(fixture.replace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clears the credential before POST and keeps the mount prefix when opening the authenticated app', async () => {
|
||||
const fixture = page(`/mount/remote-login#${TOKEN}`, 'ZH-cn')
|
||||
const pending = Promise.withResolvers<Response>()
|
||||
fixture.exchange.mockImplementation((input, init) => {
|
||||
expect(fixture.actualLocation.href).not.toContain(TOKEN)
|
||||
expect(input).toBe('/mount/remote-login')
|
||||
expect(init).toMatchObject({
|
||||
method: 'POST', credentials: 'same-origin', cache: 'no-store', redirect: 'error',
|
||||
headers: { 'content-type': 'text/plain' }, body: TOKEN,
|
||||
})
|
||||
expect(init?.signal).toBeInstanceOf(AbortSignal)
|
||||
return pending.promise
|
||||
})
|
||||
enterBrowser(loginLocales)
|
||||
expect(document.documentElement.lang).toBe('zh')
|
||||
expect(document.title).toBe(loginLocales.zh.title)
|
||||
expect(document.getElementById('title')?.textContent).toBe(loginLocales.zh.title)
|
||||
expect(document.getElementById('open')?.textContent).toBe(loginLocales.zh.open)
|
||||
expect(fixture.status.textContent).toBe(loginLocales.zh.pending)
|
||||
expect(fixture.replace).not.toHaveBeenCalled()
|
||||
pending.resolve(new Response(null, { status: 204 }))
|
||||
await expect.poll(() => fixture.replace.mock.calls).toEqual([['./']])
|
||||
expect(new URL(fixture.replace.mock.calls[0]![0], fixture.actualLocation.href).pathname).toBe('/mount/')
|
||||
})
|
||||
|
||||
it.each([410, 403, 500])('reports HTTP %i without claiming login or redirecting', async (status) => {
|
||||
const fixture = page(undefined, 'fr-FR')
|
||||
fixture.exchange.mockResolvedValue(new Response(null, { status }))
|
||||
enterBrowser(loginLocales)
|
||||
await expect.poll(() => fixture.status.textContent).toBe(status === 410 ? loginLocales.en.invalid : loginLocales.en.failed)
|
||||
expect(document.documentElement.lang).toBe('en')
|
||||
expect(fixture.replace).not.toHaveBeenCalled()
|
||||
expect(fixture.actualLocation.hash).toBe('')
|
||||
expect(document.getElementById('open')?.getAttribute('href')).toBe('./')
|
||||
})
|
||||
|
||||
it('reports a lost response as an unknown outcome and keeps the app recovery link', async () => {
|
||||
const fixture = page()
|
||||
fixture.exchange.mockRejectedValue(new TypeError('connection closed'))
|
||||
enterBrowser(loginLocales)
|
||||
await expect.poll(() => fixture.status.textContent).toBe(loginLocales.en.failed)
|
||||
expect(fixture.replace).not.toHaveBeenCalled()
|
||||
expect(document.getElementById('open')?.getAttribute('href')).toBe('./')
|
||||
expect(fixture.actualLocation.href).not.toContain(TOKEN)
|
||||
})
|
||||
|
||||
it('aborts the owned exchange when the browser leaves the page', async () => {
|
||||
const fixture = page()
|
||||
let signal: AbortSignal | undefined
|
||||
fixture.exchange.mockImplementation((_input, init) => new Promise<Response>((_resolve, reject) => {
|
||||
signal = init?.signal ?? undefined
|
||||
signal?.addEventListener('abort', () => { reject(new DOMException('page hidden', 'AbortError')) }, { once: true })
|
||||
}))
|
||||
enterBrowser(loginLocales)
|
||||
expect(signal?.aborted).toBe(false)
|
||||
window.dispatchEvent(new Event('pagehide'))
|
||||
expect(signal?.aborted).toBe(true)
|
||||
await expect.poll(() => fixture.status.textContent).toBe(loginLocales.en.failed)
|
||||
expect(fixture.replace).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('escapes embedded localized text before serializing the anonymous script', () => {
|
||||
const copy = { ...loginLocales, en: { ...loginLocales.en, failed: '</script><img src=x>' } }
|
||||
vi.spyOn(JSON, 'stringify').mockImplementationOnce(() => JSON.stringify(copy))
|
||||
const html = renderLoginPage()
|
||||
expect(html).not.toContain('</script><img src=x>')
|
||||
expect(html).toContain('\\u003c/script>\\u003cimg src=x>')
|
||||
expect(html).toContain('name="referrer" content="no-referrer"')
|
||||
expect(html).toContain(`<noscript><p>${loginLocales.en.scriptRequired}</p></noscript>`)
|
||||
})
|
||||
@@ -0,0 +1,323 @@
|
||||
/** QR login credentials, owner-only management, and anonymous exchange. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import type { WebResourceRoute, WebRoute, WebServer } from '@deepseek-ai/dsh-host-webserver'
|
||||
import type { Principal, RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import * as Token from '@deepseek-ai/dsh-host-authentication-token'
|
||||
import { IncomingMessage, type ServerResponse } from 'node:http'
|
||||
import { Socket } from 'node:net'
|
||||
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import * as Connection from '@deepseek-ai/dsh-client-connection'
|
||||
import { MemoryCredentials } from '../../../credentials/credentials/tests/memory.ts'
|
||||
import RemoteConnection from '../src/index.ts'
|
||||
import { LoginTickets } from '../src/login-tickets.ts'
|
||||
import { RemoteBrowserAuth } from '../src/remote-auth.ts'
|
||||
import type { RemoteLoginTicket } from '../src/types.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-typert-protocol' {
|
||||
interface PrincipalMap {
|
||||
/** Non-owner exercising direct QR invitation calls. */
|
||||
'qr-test-guest': { readonly kind: 'qr-test-guest' }
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
function credential(ticket: RemoteLoginTicket): string {
|
||||
return new URL(ticket.url).hash.slice(1)
|
||||
}
|
||||
|
||||
function caller(ctx: Context, principal: Principal = { kind: 'owner' }): RemoteConnection {
|
||||
const peer = ctx.connection.createPeer({ principal })
|
||||
const invocation: RemoteInvocation = {
|
||||
request: { namespace: 'remoteConnection', method: 'create', args: {} },
|
||||
service: 'remoteConnection', peer, signal: peer.signal,
|
||||
uplink: () => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true as const, value: undefined }) }) }),
|
||||
}
|
||||
return ctx.extend({ invocation }).remoteConnection
|
||||
}
|
||||
|
||||
async function mount(url = 'https://login.example/ui/', protocol: 'http:' | 'https:' = 'https:') {
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
const routes: (WebRoute | WebResourceRoute)[] = []
|
||||
await ctx.plugin(MemoryCredentials)
|
||||
ctx.provide('webServer', {
|
||||
host: '127.0.0.1', protocol,
|
||||
register(route: WebRoute | WebResourceRoute) {
|
||||
routes.push(route)
|
||||
return () => { routes.splice(routes.indexOf(route), 1) }
|
||||
},
|
||||
} as WebServer)
|
||||
ctx.provide('webApp', { getAdvertisedUrl: () => url })
|
||||
await ctx.plugin(Connection, { trustedHosts: ['login.example', 'other.example'] })
|
||||
await ctx.plugin(Token, { cookieMaxAgeDays: 30 })
|
||||
const fiber = ctx.plugin(RemoteConnection, RemoteConnection.Config({ ticketLifetimeMs: 120_000, pollIntervalMs: 1000 }))
|
||||
await fiber
|
||||
const registered = routes.find((entry): entry is WebRoute => entry.path === '/remote-login' && 'handler' in entry)!
|
||||
const route: WebRoute = {
|
||||
...registered,
|
||||
async handler(request, response) {
|
||||
const facts = {
|
||||
headers: request.headers, method: request.method,
|
||||
url: new URL(request.url ?? '/', 'http://fixture.invalid'), transport: 'http' as const, socket: request.socket,
|
||||
}
|
||||
const policy = typeof registered.auth === 'function' ? registered.auth(facts) : registered.auth ?? 'required'
|
||||
const admission = ctx.bail('webserver/authorize', facts, policy)
|
||||
if (admission?.kind === 'deny') {
|
||||
response.writeHead(admission.status)
|
||||
response.end()
|
||||
return
|
||||
}
|
||||
await registered.handler(request, response, admission?.peer)
|
||||
},
|
||||
}
|
||||
return { ctx, routes, fiber, route, registered, service: caller(ctx) }
|
||||
}
|
||||
|
||||
function streamingRequest(method: string, headers: Record<string, string> = {}): IncomingMessage {
|
||||
const socket = new Socket()
|
||||
const request = Object.assign(new IncomingMessage(socket), {
|
||||
method, url: '/remote-login', headers: { host: 'login.example', origin: 'https://login.example', 'content-type': 'text/plain', ...headers },
|
||||
})
|
||||
onTestFinished(() => { request.destroy(); socket.destroy() })
|
||||
return request
|
||||
}
|
||||
|
||||
function request(method: string, body = '', headers: Record<string, string> = {}): IncomingMessage {
|
||||
const result = streamingRequest(method, headers)
|
||||
if (body !== '') result.push(Buffer.from(body))
|
||||
result.push(null)
|
||||
return result
|
||||
}
|
||||
|
||||
function response() {
|
||||
const state = { status: 0, headers: {} as Readonly<Record<string, string>>, body: undefined as string | undefined }
|
||||
const value = {
|
||||
writeHead(status: number, headers: Readonly<Record<string, string>> = {}) {
|
||||
state.status = status
|
||||
state.headers = headers
|
||||
return this
|
||||
},
|
||||
end(body?: string) { state.body = body; return this },
|
||||
} as ServerResponse
|
||||
return { value, state }
|
||||
}
|
||||
|
||||
async function exchange(route: WebRoute, token: string, headers?: Record<string, string>) {
|
||||
const res = response()
|
||||
await route.handler(request('POST', token, headers), res.value)
|
||||
return res.state
|
||||
}
|
||||
|
||||
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 })
|
||||
const ticket = service.create()
|
||||
expect(ticket.lifetimeMs).toBe(120_000)
|
||||
expect(ticket.url).toMatch(/^https:\/\/login\.example\/ui\/remote-login#[A-Za-z0-9_-]{43}$/)
|
||||
expect(ticket.url).not.toContain('token=')
|
||||
expect(service.status(ticket.id).ticket).toBe('pending')
|
||||
const result = await exchange(route, credential(ticket))
|
||||
expect(result.status).toBe(204)
|
||||
expect(result.headers['set-cookie']).toContain('HttpOnly; SameSite=Strict; Secure')
|
||||
expect(result.headers['set-cookie']).toContain('Max-Age=2592000')
|
||||
const cookie = result.headers['set-cookie']!.split(';', 1)[0]!
|
||||
const admitted = ctx.connection.admit({ headers: { host: 'login.example', cookie } })
|
||||
if ('rejection' in admitted) throw new Error('Remote Cookie was rejected')
|
||||
expect(admitted.peer).not.toBe(ctx.connection.browserPeer)
|
||||
expect(admitted.peer.principal).toEqual({ kind: 'owner' })
|
||||
expect(ctx.connection.admit({ headers: { host: 'other.example', cookie } })).toEqual({ rejection: 401 })
|
||||
expect(service.status(ticket.id).ticket).toBe('used')
|
||||
expect(service.cancel(ticket.id)).toBe('used')
|
||||
expect(service.status(ticket.id).ticket).toBe('used')
|
||||
expect((await exchange(route, credential(ticket))).status).toBe(410)
|
||||
expect(ctx.connection.admit({ headers: { host: 'login.example', cookie } })).toEqual(admitted)
|
||||
})
|
||||
|
||||
it('never consumes a ticket on page reads or malformed and cross-origin requests', async () => {
|
||||
const { route, service } = await mount()
|
||||
const ticket = service.create()
|
||||
for (const method of ['GET', 'HEAD']) {
|
||||
const res = response()
|
||||
await route.handler(request(method), res.value)
|
||||
expect(res.state.status).toBe(200)
|
||||
expect(res.state.headers['cache-control']).toBe('no-store')
|
||||
expect(res.state.headers['referrer-policy']).toBe('no-referrer')
|
||||
expect(res.state.headers['content-security-policy']).toContain("frame-ancestors 'none'")
|
||||
expect(res.state.headers['set-cookie']).toBeUndefined()
|
||||
if (method === 'HEAD') expect(res.state.body).toBeUndefined()
|
||||
else expect(res.state.body).toContain('<html')
|
||||
}
|
||||
const put = response()
|
||||
await route.handler(request('PUT'), put.value)
|
||||
expect(put.state.status).toBe(405)
|
||||
for (const headers of [
|
||||
{ host: 'evil.example' },
|
||||
{ host: 'other.example', origin: 'https://other.example' },
|
||||
{ origin: 'https://evil.example' },
|
||||
{ 'sec-fetch-site': 'cross-site' },
|
||||
]) {
|
||||
expect((await exchange(route, credential(ticket), headers)).status).toBe(403)
|
||||
}
|
||||
expect((await exchange(route, credential(ticket), { 'content-type': 'application/json' })).status).toBe(400)
|
||||
for (const invalid of ['', 'short', 'é'.repeat(20)]) expect((await exchange(route, invalid)).status).toBe(400)
|
||||
expect((await exchange(route, 'x'.repeat(43))).status).toBe(410)
|
||||
expect(service.status(ticket.id).ticket).toBe('pending')
|
||||
expect((await exchange(route, credential(ticket), { host: 'login.example:443' })).status).toBe(204)
|
||||
})
|
||||
|
||||
it('returns the process-token login URL without consuming or replacing the QR invitation', async () => {
|
||||
const { service } = await mount()
|
||||
const ticket = service.create()
|
||||
const link = service.loginUrl()
|
||||
expect(new URL(link).origin + new URL(link).pathname).toBe('https://login.example/ui/')
|
||||
expect(new URL(link).searchParams.get('token')).toMatch(/^[A-Za-z0-9_-]{43}$/)
|
||||
expect(service.loginUrl()).toBe(link)
|
||||
expect(service.status(ticket.id)).toMatchObject({ ticket: 'pending', url: 'https://login.example/ui/' })
|
||||
expect(JSON.stringify(service.status(ticket.id))).not.toContain(new URL(link).searchParams.get('token'))
|
||||
})
|
||||
|
||||
it('bounds declared and streamed credential bodies without consuming a ticket', async () => {
|
||||
const { route, service } = await mount()
|
||||
const ticket = service.create()
|
||||
expect((await exchange(route, credential(ticket), { 'content-length': '44' })).status).toBe(413)
|
||||
expect((await exchange(route, 'x'.repeat(44))).status).toBe(413)
|
||||
expect(service.status(ticket.id).ticket).toBe('pending')
|
||||
})
|
||||
|
||||
it('allows exactly one of two overlapping exchanges', async () => {
|
||||
const { route, service } = await mount()
|
||||
const ticket = service.create()
|
||||
const streams = [streamingRequest('POST'), streamingRequest('POST')]
|
||||
const responses = [response(), response()]
|
||||
const pending = streams.map((stream, index) => Promise.resolve(route.handler(stream, responses[index]!.value)))
|
||||
for (const stream of streams) { stream.push(Buffer.from(credential(ticket))); stream.push(null) }
|
||||
await Promise.all(pending)
|
||||
expect(responses.map(res => res.state.status).sort()).toEqual([204, 410])
|
||||
expect(responses.filter(res => res.state.headers['set-cookie'] !== undefined)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('does not expose a session when the Remote credential signer refuses issuance', async () => {
|
||||
const { route, service } = await mount()
|
||||
const ticket = service.create()
|
||||
const issuance = vi.spyOn(RemoteBrowserAuth.prototype, 'createSessionCookie').mockReturnValue(undefined)
|
||||
const result = await exchange(route, credential(ticket))
|
||||
expect(result.status).toBe(403)
|
||||
expect(result.headers['set-cookie']).toBeUndefined()
|
||||
expect(service.status(ticket.id).ticket).toBe('used')
|
||||
issuance.mockRestore()
|
||||
expect((await exchange(route, credential(ticket))).status).toBe(410)
|
||||
})
|
||||
|
||||
it('rejects expired, cancelled and replaced invitations and preserves the replacement on stale cancellation', async () => {
|
||||
const now = vi.spyOn(Date, 'now').mockReturnValue(1000)
|
||||
const { route, service } = await mount()
|
||||
const expired = service.create()
|
||||
now.mockReturnValue(1000 + expired.lifetimeMs)
|
||||
expect((await exchange(route, credential(expired))).status).toBe(410)
|
||||
expect(service.status(expired.id).ticket).toBe('expired')
|
||||
expect(service.cancel(expired.id)).toBe('expired')
|
||||
const cancelled = service.create()
|
||||
expect(service.cancel(cancelled.id)).toBe('cancelled')
|
||||
expect(service.status(cancelled.id).ticket).toBe('cancelled')
|
||||
expect((await exchange(route, credential(cancelled))).status).toBe(410)
|
||||
const old = service.create()
|
||||
const replacement = service.create()
|
||||
expect(service.status(old.id).ticket).toBe('replaced')
|
||||
expect(service.cancel(old.id)).toBe('replaced')
|
||||
expect(service.status(replacement.id).ticket).toBe('pending')
|
||||
expect((await exchange(route, credential(old))).status).toBe(410)
|
||||
expect((await exchange(route, credential(replacement))).status).toBe(204)
|
||||
})
|
||||
|
||||
it('requires an owner even when a caller bypasses the generated Remote gateway', async () => {
|
||||
const { ctx, service } = await mount()
|
||||
const ticket = service.create()
|
||||
for (const denied of [ctx.remoteConnection, caller(ctx, { kind: 'qr-test-guest' })]) {
|
||||
expect(() => denied.status(null)).toThrow(expect.objectContaining({ code: 'remote-connection/owner-required' }))
|
||||
expect(() => denied.create()).toThrow(expect.objectContaining({ code: 'remote-connection/owner-required' }))
|
||||
expect(() => denied.loginUrl()).toThrow(expect.objectContaining({ code: 'remote-connection/owner-required' }))
|
||||
expect(() => denied.cancel(ticket.id)).toThrow(expect.objectContaining({ code: 'remote-connection/owner-required' }))
|
||||
}
|
||||
expect(service.status(ticket.id).ticket).toBe('pending')
|
||||
})
|
||||
|
||||
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'],
|
||||
] 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.create()).toThrow(expect.objectContaining({ code: 'remote-connection/unavailable', details: { reason: availability } }))
|
||||
expect(() => service.loginUrl()).toThrow(expect.objectContaining({ code: 'remote-connection/unavailable', details: { reason: availability } }))
|
||||
})
|
||||
|
||||
it('marks QR cookies Secure behind an HTTPS proxy while preserving the upstream cookie audience', async () => {
|
||||
const { ctx, route, service } = await mount('https://login.example/ui/', 'http:')
|
||||
const result = await exchange(route, credential(service.create()))
|
||||
expect(result.status).toBe(204)
|
||||
expect(result.headers['set-cookie']).toContain('; Secure')
|
||||
const cookie = result.headers['set-cookie']!.split(';', 1)[0]!
|
||||
const admitted = ctx.connection.admit({ headers: { host: 'login.example', cookie } })
|
||||
if ('rejection' in admitted) throw new Error('Remote proxy Cookie was rejected')
|
||||
expect(admitted.peer).not.toBe(ctx.connection.browserPeer)
|
||||
})
|
||||
|
||||
it('signs in over HTTP with a non-Secure Remote cookie and rejects replay', async () => {
|
||||
const { ctx, route, service } = await mount('http://login.example/ui/', 'http:')
|
||||
expect(service.status(null).availability).toBe('available')
|
||||
const ticket = service.create()
|
||||
expect(ticket.url).toMatch(/^http:\/\/login\.example\/ui\/remote-login#[A-Za-z0-9_-]{43}$/)
|
||||
expect((await exchange(route, credential(ticket), { origin: 'http://evil.example' })).status).toBe(403)
|
||||
expect(service.status(ticket.id).ticket).toBe('pending')
|
||||
const headers = { host: 'login.example:80', origin: 'http://login.example' }
|
||||
const result = await exchange(route, credential(ticket), headers)
|
||||
expect(result.status).toBe(204)
|
||||
expect(result.headers['set-cookie']).toContain('HttpOnly; SameSite=Strict')
|
||||
expect(result.headers['set-cookie']).not.toContain('; Secure')
|
||||
const cookie = result.headers['set-cookie']!.split(';', 1)[0]!
|
||||
const admitted = ctx.connection.admit({ headers: { ...headers, cookie } })
|
||||
if ('rejection' in admitted) throw new Error('Remote HTTP Cookie was rejected')
|
||||
expect(admitted.peer).not.toBe(ctx.connection.browserPeer)
|
||||
const replay = await exchange(route, credential(ticket), headers)
|
||||
expect(replay.status).toBe(410)
|
||||
expect(replay.headers['set-cookie']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('refuses anonymous exchanges while the advertised deployment is unreachable', async () => {
|
||||
const { route } = await mount('http://localhost/', 'http:')
|
||||
expect((await exchange(route, 'a'.repeat(43), { host: 'localhost', origin: 'http://localhost' })).status).toBe(403)
|
||||
})
|
||||
|
||||
it('removes the route and invalidates pending requests when the plugin unloads', async () => {
|
||||
const { route, registered, routes, fiber, service } = await mount()
|
||||
const ticket = service.create()
|
||||
const stream = streamingRequest('POST')
|
||||
const res = response()
|
||||
const pending = route.handler(stream, res.value)
|
||||
const disposing = fiber.dispose()
|
||||
stream.push(Buffer.from(credential(ticket)))
|
||||
stream.push(null)
|
||||
await Promise.all([disposing, pending])
|
||||
expect(res.state.status).toBe(410)
|
||||
expect(res.state.headers['set-cookie']).toBeUndefined()
|
||||
expect(routes).not.toContain(registered)
|
||||
expect(() => service.create()).toThrow(expect.objectContaining({ code: 'remote-connection/disposed' }))
|
||||
expect(() => service.loginUrl()).toThrow(expect.objectContaining({ code: 'remote-connection/disposed' }))
|
||||
})
|
||||
|
||||
it('rejects QR URLs above the byte-mode capacity without replacing an outstanding invitation', () => {
|
||||
const tickets = new LoginTickets()
|
||||
const ticket = tickets.create('https://login.example', 120_000)
|
||||
expect(() => tickets.create(`https://login.example/${'a'.repeat(2331)}/`, 120_000)).toThrow(expect.objectContaining({ code: 'remote-connection/url-too-long' }))
|
||||
expect(tickets.state(ticket.id)).toBe('pending')
|
||||
tickets.dispose()
|
||||
expect(tickets.consume(credential(ticket))).toBe(false)
|
||||
})
|
||||
@@ -0,0 +1,276 @@
|
||||
/** Remote browser credentials retain their own durable key and fixed authority-scoped expiry. */
|
||||
|
||||
import { createHmac, randomBytes } from 'node:crypto'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { CredentialProvider, credentialKey } from '@deepseek-ai/dsh-credentials'
|
||||
import type { CredentialKey, CredentialRecord } from '@deepseek-ai/dsh-credentials'
|
||||
import { HarnessError } from '@deepseek-ai/dsh-error'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { RemoteBrowserAuth } from '../src/remote-auth.ts'
|
||||
|
||||
const DAY = 86_400_000
|
||||
const RECORD_KEY = credentialKey('client-remote-connection', 'browser-session')
|
||||
|
||||
class RecordCredentials extends CredentialProvider {
|
||||
record: CredentialRecord | undefined
|
||||
readonly keys: CredentialKey[] = []
|
||||
writes = 0
|
||||
private tail = Promise.resolve()
|
||||
|
||||
constructor(record?: CredentialRecord) {
|
||||
const ctx = new Context()
|
||||
super(ctx)
|
||||
this.record = record
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
}
|
||||
|
||||
override resolve(): never { throw new Error('Reference resolution is outside this fixture') }
|
||||
override describe(): never { throw new Error('Reference description is outside this fixture') }
|
||||
override set(): never { throw new Error('Reference writes are outside this fixture') }
|
||||
override unset(): never { throw new Error('Reference removal is outside this fixture') }
|
||||
override describeRecord(): never { throw new Error('Record description is outside this fixture') }
|
||||
override listRecords(): never { throw new Error('Record enumeration is outside this fixture') }
|
||||
override readRecord(): Promise<CredentialRecord | undefined> { return Promise.resolve(this.record) }
|
||||
override deleteRecord(): Promise<void> { this.record = undefined; return Promise.resolve() }
|
||||
|
||||
override modifyRecord(
|
||||
key: CredentialKey,
|
||||
mutate: (current: CredentialRecord | undefined) => Promise<CredentialRecord | undefined>,
|
||||
): Promise<CredentialRecord | undefined> {
|
||||
this.keys.push(key)
|
||||
const write = this.tail.then(async () => {
|
||||
const next = await mutate(this.record)
|
||||
if (next !== undefined) { this.record = next; this.writes++ }
|
||||
return this.record
|
||||
})
|
||||
this.tail = write.then(() => undefined, () => undefined)
|
||||
return write
|
||||
}
|
||||
}
|
||||
|
||||
function secretRecord(): CredentialRecord {
|
||||
return { kind: 'grant', payload: { version: 1, secret: randomBytes(32).toString('base64url') } }
|
||||
}
|
||||
|
||||
function issue(auth: RemoteBrowserAuth, host = 'remote.example', secure = false): { setCookie: string; pair: string; name: string } {
|
||||
const setCookie = auth.createSessionCookie({ headers: { host } }, secure)
|
||||
if (setCookie === undefined) throw new Error('Expected the test request to identify an audience')
|
||||
const pair = setCookie.split(';', 1)[0]!
|
||||
return { setCookie, pair, name: pair.slice(0, pair.indexOf('=')) }
|
||||
}
|
||||
|
||||
function signedBody(store: RecordCredentials, name: string, body: string): string {
|
||||
const record = store.record
|
||||
if (record?.kind !== 'grant' || typeof record.payload !== 'object' || record.payload === null) {
|
||||
throw new Error('Expected the test credential store to hold a grant')
|
||||
}
|
||||
const secret: unknown = Reflect.get(record.payload, 'secret')
|
||||
if (typeof secret !== 'string') throw new Error('Expected the test grant to hold a signing key')
|
||||
const signed = `v1.${body}`
|
||||
const signature = createHmac('sha256', Buffer.from(secret, 'base64url')).update(signed).digest('base64url')
|
||||
return `${name}=${signed}.${signature}`
|
||||
}
|
||||
|
||||
function signedPayload(store: RecordCredentials, name: string, value: unknown): string {
|
||||
return signedBody(store, name, Buffer.from(JSON.stringify(value)).toString('base64url'))
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('Remote browser credentials', () => {
|
||||
it('reuses the durable Remote key across instances without storing a runtime Peer', async () => {
|
||||
const store = new RecordCredentials()
|
||||
const first = await RemoteBrowserAuth.create(store, 30)
|
||||
const { pair, setCookie } = issue(first)
|
||||
expect(setCookie).toContain('; Max-Age=2592000; Path=/; Expires=')
|
||||
expect(setCookie).toMatch(/; HttpOnly; SameSite=Strict$/u)
|
||||
expect(pair).toMatch(/^dsh-remote-[A-Za-z0-9_-]+=v1\./u)
|
||||
expect(store.record).toMatchObject({ kind: 'grant', payload: { version: 1 } })
|
||||
const saved = structuredClone(store.record)
|
||||
const restarted = await RemoteBrowserAuth.create(store, 30)
|
||||
expect(restarted.isAuthenticated({ headers: { host: 'remote.example', cookie: pair } }, false)).toBe(true)
|
||||
expect(store.record).toEqual(saved)
|
||||
expect(store.keys).toEqual([RECORD_KEY, RECORD_KEY])
|
||||
expect(store.writes).toBe(1)
|
||||
})
|
||||
|
||||
it('uses the atomically committed key when two initializations overlap', async () => {
|
||||
const store = new RecordCredentials()
|
||||
const [first, second] = await Promise.all([
|
||||
RemoteBrowserAuth.create(store, 30),
|
||||
RemoteBrowserAuth.create(store, 30),
|
||||
])
|
||||
expect(store.writes).toBe(1)
|
||||
const cookie = issue(first).pair
|
||||
expect(second.isAuthenticated({ headers: { host: 'remote.example', cookie } }, false)).toBe(true)
|
||||
|
||||
const committed = secretRecord()
|
||||
const competing = new RecordCredentials()
|
||||
vi.spyOn(competing, 'modifyRecord').mockImplementationOnce(async (_key, mutate) => {
|
||||
await mutate(undefined)
|
||||
return committed
|
||||
})
|
||||
const winner = await RemoteBrowserAuth.create(new RecordCredentials(committed), 30)
|
||||
const loser = await RemoteBrowserAuth.create(competing, 30)
|
||||
expect(winner.isAuthenticated({ headers: { host: 'remote.example', cookie: issue(loser).pair } }, false)).toBe(true)
|
||||
})
|
||||
|
||||
it('retains the absolute expiry after verification and process restart', async () => {
|
||||
vi.useFakeTimers()
|
||||
const now = Date.UTC(2026, 10, 12)
|
||||
vi.setSystemTime(now)
|
||||
const store = new RecordCredentials()
|
||||
const first = await RemoteBrowserAuth.create(store, 1)
|
||||
const { pair, setCookie } = issue(first)
|
||||
expect(setCookie).toContain(`Expires=${new Date(now + DAY).toUTCString()}`)
|
||||
const body = pair.split('.')[1]!
|
||||
expect(JSON.parse(Buffer.from(body, 'base64url').toString('utf8'))).toEqual({
|
||||
version: 1, authority: 'http://remote.example', issuedAt: now, expiresAt: now + DAY,
|
||||
})
|
||||
vi.setSystemTime(now + DAY / 2)
|
||||
const restarted = await RemoteBrowserAuth.create(store, 1)
|
||||
const request = { headers: { host: 'remote.example', cookie: pair } }
|
||||
expect(restarted.isAuthenticated(request, false)).toBe(true)
|
||||
vi.setSystemTime(now + DAY - 1)
|
||||
expect(restarted.isAuthenticated(request, false)).toBe(true)
|
||||
vi.setSystemTime(now + DAY)
|
||||
expect(restarted.isAuthenticated(request, false)).toBe(false)
|
||||
})
|
||||
|
||||
it('binds both cookie name and signed audience to the listener scheme and normalized Host', async () => {
|
||||
const auth = await RemoteBrowserAuth.create(new RecordCredentials(), 30)
|
||||
const http = issue(auth, 'Remote.Example:80')
|
||||
const https = issue(auth, 'Remote.Example:443', true)
|
||||
expect(auth.isAuthenticated({ headers: { host: 'remote.example', cookie: http.pair } }, false)).toBe(true)
|
||||
expect(auth.isAuthenticated({ headers: new Headers({ host: 'REMOTE.EXAMPLE:443', cookie: https.pair }) }, true)).toBe(true)
|
||||
expect(https.setCookie).toMatch(/; Secure$/u)
|
||||
expect(https.name).not.toBe(http.name)
|
||||
for (const host of ['other.example', 'remote.example:8080']) {
|
||||
expect(auth.isAuthenticated({ headers: { host, cookie: http.pair } }, false)).toBe(false)
|
||||
}
|
||||
expect(auth.isAuthenticated({ headers: { host: 'remote.example', cookie: http.pair } }, true)).toBe(false)
|
||||
expect(auth.isAuthenticated({ headers: { host: 'remote.example', cookie: http.pair.replace(http.name, https.name) } }, true)).toBe(false)
|
||||
const ipv6 = issue(auth, '[::1]:3080')
|
||||
expect(auth.isAuthenticated({ headers: { host: '[0:0:0:0:0:0:0:1]:3080', cookie: ipv6.pair } }, false)).toBe(true)
|
||||
})
|
||||
|
||||
it('rejects ambiguous Cookie entries while ignoring unrelated cookies', async () => {
|
||||
const auth = await RemoteBrowserAuth.create(new RecordCredentials(), 30)
|
||||
const { pair, name } = issue(auth)
|
||||
const request = (cookie: string) => ({ headers: { host: 'remote.example', cookie } })
|
||||
expect(auth.isAuthenticated(request(`unrelated=value; ${pair}; ignored`), false)).toBe(true)
|
||||
for (const cookie of [`${pair}; ${pair}`, `${name}=; ${pair}`, `${pair}; ${name}=invalid`, 'unrelated=value']) {
|
||||
expect(auth.isAuthenticated(request(cookie), false)).toBe(false)
|
||||
}
|
||||
expect(auth.isAuthenticated({ headers: { host: 'remote.example', cookie: [pair] } }, false)).toBe(false)
|
||||
expect(auth.isAuthenticated({ headers: { host: 'remote.example' } }, false)).toBe(false)
|
||||
expect(auth.isAuthenticated({ headers: new Headers({ host: 'remote.example' }) }, false)).toBe(false)
|
||||
})
|
||||
|
||||
it('refuses missing, malformed, and non-authority Host fields', async () => {
|
||||
const auth = await RemoteBrowserAuth.create(new RecordCredentials(), 30)
|
||||
const { pair } = issue(auth)
|
||||
for (const host of ['', 'remote.example/path', 'remote.example?x', 'remote.example#x', 'user@remote.example', ' remote.example', 'remote.example\\path', '[::1']) {
|
||||
expect(auth.createSessionCookie({ headers: { host } }, false)).toBeUndefined()
|
||||
expect(auth.isAuthenticated({ headers: { host, cookie: pair } }, false)).toBe(false)
|
||||
}
|
||||
expect(auth.createSessionCookie({ headers: {} }, false)).toBeUndefined()
|
||||
expect(auth.createSessionCookie({ headers: { host: ['remote.example'] } }, false)).toBeUndefined()
|
||||
expect(auth.isAuthenticated({ headers: { cookie: pair } }, false)).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects tampering, malformed encodings, and unsupported cookie versions', async () => {
|
||||
const store = new RecordCredentials()
|
||||
const auth = await RemoteBrowserAuth.create(store, 30)
|
||||
const { pair, name } = issue(auth)
|
||||
for (const cookie of [
|
||||
`${pair}!`, pair.replace('=v1.', '=v2.'), `${pair}.extra`, `${name}=v1`, `${name}=v1.e30`,
|
||||
`${name}=v1.e30.AA`, `${name}=v1.e30.`, `${pair}=`,
|
||||
pair.replace('=v1.', '=v1.x'), signedBody(store, name, 'a'), signedBody(store, name, 'e30='),
|
||||
signedBody(store, name, 'e31'),
|
||||
signedBody(store, name, Buffer.from('not JSON').toString('base64url')),
|
||||
]) {
|
||||
expect(auth.isAuthenticated({ headers: { host: 'remote.example', cookie } }, false)).toBe(false)
|
||||
}
|
||||
const other = await RemoteBrowserAuth.create(new RecordCredentials(), 30)
|
||||
expect(other.isAuthenticated({ headers: { host: 'remote.example', cookie: pair } }, false)).toBe(false)
|
||||
})
|
||||
|
||||
it('validates signed JSON fields and time bounds before accepting credentials', async () => {
|
||||
vi.useFakeTimers()
|
||||
const now = Date.UTC(2026, 10, 12)
|
||||
vi.setSystemTime(now)
|
||||
const store = new RecordCredentials()
|
||||
const auth = await RemoteBrowserAuth.create(store, 1)
|
||||
const { name } = issue(auth)
|
||||
const valid = { version: 1, authority: 'http://remote.example', issuedAt: now, expiresAt: now + DAY }
|
||||
for (const payload of [
|
||||
null, [], true, 1, 'credential', {}, { ...valid, extra: true }, { ...valid, version: 2 },
|
||||
{ ...valid, authority: 1 }, { ...valid, authority: 'http://other.example' },
|
||||
{ ...valid, issuedAt: 'now' }, { ...valid, issuedAt: -1 }, { ...valid, issuedAt: now + 1 },
|
||||
{ ...valid, issuedAt: now + 0.5 }, { ...valid, issuedAt: Number.MAX_SAFE_INTEGER + 1 },
|
||||
{ ...valid, expiresAt: 'later' }, { ...valid, expiresAt: null }, { ...valid, expiresAt: now },
|
||||
{ ...valid, expiresAt: now - 1 }, { ...valid, expiresAt: now + DAY + 1 },
|
||||
{ ...valid, expiresAt: now + 0.5 }, { ...valid, expiresAt: 8_640_000_000_000_001 },
|
||||
]) {
|
||||
const cookie = signedPayload(store, name, payload)
|
||||
expect(auth.isAuthenticated({ headers: { host: 'remote.example', cookie } }, false)).toBe(false)
|
||||
}
|
||||
const shortened = await RemoteBrowserAuth.create(store, 1)
|
||||
const longer = await RemoteBrowserAuth.create(store, 2)
|
||||
expect(shortened.isAuthenticated({ headers: { host: 'remote.example', cookie: issue(longer).pair } }, false)).toBe(false)
|
||||
})
|
||||
|
||||
it.each<CredentialRecord>([
|
||||
{ kind: 'api-key', key: 'unrelated' },
|
||||
{ kind: 'grant', payload: null },
|
||||
{ kind: 'grant', payload: [] },
|
||||
{ kind: 'grant', payload: {} },
|
||||
{ kind: 'grant', payload: { version: 2, secret: randomBytes(32).toString('base64url') } },
|
||||
{ kind: 'grant', payload: { version: 1, secret: randomBytes(32).toString('base64url'), extra: true } },
|
||||
{ kind: 'grant', payload: { version: 1, secret: 1 } },
|
||||
{ kind: 'grant', payload: { version: 1, secret: '' } },
|
||||
{ kind: 'grant', payload: { version: 1, secret: 'x' } },
|
||||
{ kind: 'grant', payload: { version: 1, secret: 'AA' } },
|
||||
{ kind: 'grant', payload: { version: 1, secret: `${randomBytes(32).toString('base64url')}=` } },
|
||||
])('refuses a corrupt stored record without replacing it: %j', async (record) => {
|
||||
const store = new RecordCredentials(record)
|
||||
await expect(RemoteBrowserAuth.create(store, 30)).rejects.toMatchObject({
|
||||
name: 'RemoteAuthenticationError', code: 'REMOTE_AUTH_CREDENTIAL_CORRUPT',
|
||||
})
|
||||
expect(store.record).toEqual(record)
|
||||
expect(store.writes).toBe(0)
|
||||
})
|
||||
|
||||
it('reports unavailable storage and preserves structured provider failures', async () => {
|
||||
const unavailable = new RecordCredentials()
|
||||
vi.spyOn(unavailable, 'modifyRecord').mockResolvedValueOnce(undefined)
|
||||
await expect(RemoteBrowserAuth.create(unavailable, 30)).rejects.toMatchObject({
|
||||
name: 'RemoteAuthenticationError', code: 'REMOTE_AUTH_CREDENTIAL_UNAVAILABLE',
|
||||
})
|
||||
const failed = new RecordCredentials()
|
||||
const cause = new Error('storage unavailable')
|
||||
vi.spyOn(failed, 'modifyRecord').mockRejectedValueOnce(cause)
|
||||
await expect(RemoteBrowserAuth.create(failed, 30)).rejects.toMatchObject({
|
||||
name: 'RemoteAuthenticationError', code: 'REMOTE_AUTH_CREDENTIAL_FAILED', cause,
|
||||
})
|
||||
const structured = new RecordCredentials()
|
||||
const error = new HarnessError('storage refused the write', 'CREDENTIAL_PERMISSION_DENIED')
|
||||
vi.spyOn(structured, 'modifyRecord').mockRejectedValueOnce(error)
|
||||
await expect(RemoteBrowserAuth.create(structured, 30)).rejects.toBe(error)
|
||||
})
|
||||
|
||||
it.each([0, -1, 0.5, Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER])(
|
||||
'refuses unsupported lifetimes before touching persistent credentials: %s',
|
||||
async (days) => {
|
||||
const store = new RecordCredentials()
|
||||
await expect(RemoteBrowserAuth.create(store, days)).rejects.toMatchObject({
|
||||
name: 'RemoteAuthenticationError', code: 'REMOTE_AUTH_INVALID_LIFETIME',
|
||||
})
|
||||
expect(store.keys).toEqual([])
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,340 @@
|
||||
/** Remote's public root page and independent credentials over real HTTP admission. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import * as Connection from '@deepseek-ai/dsh-client-connection'
|
||||
import * as FrontendStatic from '@deepseek-ai/dsh-host-frontend-static'
|
||||
import * as Token from '@deepseek-ai/dsh-host-authentication-token'
|
||||
import WebServer from '@deepseek-ai/dsh-host-webserver'
|
||||
import type { CredentialKey, CredentialRecord } from '@deepseek-ai/dsh-credentials'
|
||||
import type { PeerScope, RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol'
|
||||
import { request as httpRequest } from 'node:http'
|
||||
import type { IncomingHttpHeaders, ServerResponse } from 'node:http'
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { afterEach, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { MemoryCredentials } from '../../../credentials/credentials/tests/memory.ts'
|
||||
import RemoteConnection from '../src/index.ts'
|
||||
|
||||
afterEach(() => { vi.restoreAllMocks() })
|
||||
|
||||
interface Reply {
|
||||
readonly status: number | undefined
|
||||
readonly headers: IncomingHttpHeaders
|
||||
readonly body: string
|
||||
}
|
||||
|
||||
function owner(ctx: Context): RemoteConnection {
|
||||
const peer = ctx.connection.createPeer({ principal: { kind: 'owner' } })
|
||||
const invocation: RemoteInvocation = {
|
||||
request: { namespace: 'remoteConnection', method: 'create', args: {} },
|
||||
service: 'remoteConnection', peer, signal: peer.signal,
|
||||
uplink: () => ({ [Symbol.asyncIterator]: () => ({ next: async () => ({ done: true as const, value: undefined }) }) }),
|
||||
}
|
||||
return ctx.extend({ invocation }).remoteConnection
|
||||
}
|
||||
|
||||
function cookie(reply: Reply): string {
|
||||
const value = reply.headers['set-cookie']?.[0]?.split(';', 1)[0]
|
||||
if (value === undefined) throw new Error('login did not issue a Cookie')
|
||||
return value
|
||||
}
|
||||
|
||||
async function mounted(withToken = false, releaseHeldRead?: () => void) {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-remote-root-'))
|
||||
const ctx = new Context()
|
||||
onTestFinished(async () => {
|
||||
releaseHeldRead?.()
|
||||
await ctx.fiber.dispose()
|
||||
await rm(root, { recursive: true, force: true })
|
||||
})
|
||||
const index = join(root, 'index.html')
|
||||
await writeFile(index, '<!doctype html><html><head></head><body>PRIVATE_APPLICATION</body></html>')
|
||||
await ctx.plugin(MemoryCredentials)
|
||||
await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 })
|
||||
const origin = ctx.webServer.getOrigin()
|
||||
const authority = `remote.example:${String(ctx.webServer.port)}`
|
||||
const publicUrl = `http://${authority}/`
|
||||
ctx.provide('webApp', { getAdvertisedUrl: () => publicUrl })
|
||||
await ctx.plugin(Connection, { trustedHosts: ['remote.example'] })
|
||||
const renderedPeers: PeerScope[] = []
|
||||
ctx.on('webserver/index-inject', (rows, peer) => {
|
||||
renderedPeers.push(peer)
|
||||
rows.push({ kind: 'script', placement: 'head', text: 'window.PRIVATE_BOOT_DATA = true' })
|
||||
})
|
||||
await ctx.plugin(FrontendStatic, { distIndex: index })
|
||||
const token = withToken ? ctx.plugin(Token, { cookieMaxAgeDays: 30 }) : undefined
|
||||
await token?.await()
|
||||
const config = RemoteConnection.Config({ ticketLifetimeMs: 120_000, pollIntervalMs: 1000 })
|
||||
const remote = ctx.plugin(RemoteConnection, config)
|
||||
await remote.await()
|
||||
const service = owner(ctx)
|
||||
const send = (path: string, method = 'GET', headers: Record<string, string> = {}, body?: string): Promise<Reply> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const request = httpRequest(new URL(path, origin), {
|
||||
method,
|
||||
headers: { host: authority, ...headers },
|
||||
}, (response) => {
|
||||
const chunks: Buffer[] = []
|
||||
response.on('data', (chunk: Buffer) => { chunks.push(chunk) })
|
||||
response.once('error', reject)
|
||||
response.once('end', () => {
|
||||
resolve({ status: response.statusCode, headers: response.headers, body: Buffer.concat(chunks).toString('utf8') })
|
||||
})
|
||||
})
|
||||
request.once('error', reject)
|
||||
request.end(body)
|
||||
})
|
||||
const redeem = async () => {
|
||||
const ticket = service.create()
|
||||
return send('/remote-login', 'POST', { 'content-type': 'text/plain', origin: publicUrl.slice(0, -1) }, new URL(ticket.url).hash.slice(1))
|
||||
}
|
||||
return { ctx, config, origin, authority, publicUrl, remote, token, service, send, redeem, renderedPeers }
|
||||
}
|
||||
|
||||
it('offers an anonymous root page without Token and renders the admitted Remote Peer after QR login', async () => {
|
||||
const { ctx, authority, send, redeem, service, renderedPeers } = await mounted()
|
||||
const authenticate = vi.spyOn(ctx.connection.authentication, 'authenticate')
|
||||
const anonymous = await send('/')
|
||||
expect(anonymous.status).toBe(401)
|
||||
expect(anonymous.headers['content-type']).toContain('text/html')
|
||||
expect(anonymous.headers['cache-control']).toBe('no-store')
|
||||
expect(anonymous.body).toContain('<html')
|
||||
expect(anonymous.body).not.toContain('name="token"')
|
||||
expect(anonymous.body).not.toContain('PRIVATE_APPLICATION')
|
||||
expect(anonymous.body).not.toContain('PRIVATE_BOOT_DATA')
|
||||
expect(authenticate).toHaveBeenCalledTimes(1)
|
||||
expect(renderedPeers).toHaveLength(0)
|
||||
expect(() => service.loginUrl()).toThrow(expect.objectContaining({ code: 'remote-connection/token-unavailable' }))
|
||||
expect((await send('/', 'HEAD')).status).toBe(401)
|
||||
expect((await send('/index.html')).status).toBe(401)
|
||||
|
||||
const exchanged = await redeem()
|
||||
expect(exchanged.status).toBe(204)
|
||||
const remoteCookie = cookie(exchanged)
|
||||
const admission = ctx.connection.admit({ headers: { host: authority, cookie: remoteCookie } })
|
||||
if ('rejection' in admission) throw new Error('Remote Cookie was rejected')
|
||||
expect(admission.peer).not.toBe(ctx.connection.browserPeer)
|
||||
authenticate.mockClear()
|
||||
const page = await send('/', 'GET', { cookie: remoteCookie })
|
||||
expect(page.status).toBe(200)
|
||||
expect(page.body).toContain('PRIVATE_APPLICATION')
|
||||
expect(page.body).toContain('PRIVATE_BOOT_DATA')
|
||||
expect(renderedPeers.at(-1)).toBe(admission.peer)
|
||||
expect(authenticate).toHaveBeenCalledTimes(1)
|
||||
authenticate.mockClear()
|
||||
const head = await send('/', 'HEAD', { cookie: remoteCookie })
|
||||
expect(head.status).toBe(200)
|
||||
expect(head.body).toBe('')
|
||||
expect(authenticate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps source refusals outside the root page and invitation exchange', async () => {
|
||||
const { ctx, publicUrl, send, service, renderedPeers } = await mounted()
|
||||
const ticket = service.create()
|
||||
const authenticate = vi.spyOn(ctx.connection.authentication, 'authenticate')
|
||||
const secret = new URL(ticket.url).hash.slice(1)
|
||||
for (const headers of [
|
||||
{ host: 'untrusted.example' },
|
||||
{ origin: 'http://untrusted.example' },
|
||||
{ 'sec-fetch-site': 'cross-site' },
|
||||
]) {
|
||||
const page = await send('/', 'GET', headers)
|
||||
expect(page.status).toBe(403)
|
||||
expect(page.body).not.toContain('<html')
|
||||
expect((await send('/remote-login', 'POST', { 'content-type': 'text/plain', ...headers }, secret)).status).toBe(403)
|
||||
expect(service.status(ticket.id).ticket).toBe('pending')
|
||||
}
|
||||
expect(authenticate).not.toHaveBeenCalled()
|
||||
expect(renderedPeers).toHaveLength(0)
|
||||
const exchanged = await send('/remote-login', 'POST', { 'content-type': 'text/plain', origin: publicUrl.slice(0, -1) }, secret)
|
||||
expect(exchanged.status).toBe(204)
|
||||
})
|
||||
|
||||
it('keeps copied Token links and Remote credentials independent across provider unloads', async () => {
|
||||
const { ctx, authority, config, remote, token, service, send, redeem } = await mounted(true)
|
||||
const ticket = service.create()
|
||||
const link = new URL(service.loginUrl())
|
||||
const tokenSecret = link.searchParams.get('token')!
|
||||
expect(tokenSecret).toMatch(/^[A-Za-z0-9_-]{43}$/)
|
||||
expect(service.status(ticket.id).ticket).toBe('pending')
|
||||
const anonymous = await send('/')
|
||||
expect(anonymous.status).toBe(401)
|
||||
expect(anonymous.body).toContain('name="token"')
|
||||
expect(anonymous.body).not.toContain(tokenSecret)
|
||||
const tokenExchange = await send(link.pathname + link.search)
|
||||
expect(tokenExchange.status).toBe(303)
|
||||
const tokenCookie = cookie(tokenExchange)
|
||||
const tokenAdmission = ctx.connection.admit({ headers: { host: authority, cookie: tokenCookie } })
|
||||
if ('rejection' in tokenAdmission) throw new Error('Token Cookie was rejected')
|
||||
const remoteExchange = await redeem()
|
||||
expect(remoteExchange.status).toBe(204)
|
||||
const remoteCookie = cookie(remoteExchange)
|
||||
expect(remoteCookie.split('=', 1)[0]).not.toBe(tokenCookie.split('=', 1)[0])
|
||||
const remoteAdmission = ctx.connection.admit({ headers: { host: authority, cookie: remoteCookie } })
|
||||
if ('rejection' in remoteAdmission) throw new Error('Remote Cookie was rejected')
|
||||
expect(remoteAdmission.peer).not.toBe(tokenAdmission.peer)
|
||||
await remote.dispose()
|
||||
expect(remoteAdmission.peer.signal.aborted).toBe(true)
|
||||
expect(tokenAdmission.peer.signal.aborted).toBe(false)
|
||||
expect(ctx.connection.admit({ headers: { host: authority, cookie: remoteCookie } })).toEqual({ rejection: 401 })
|
||||
expect((await send('/', 'GET', { cookie: tokenCookie })).status).toBe(200)
|
||||
|
||||
const resumed = ctx.plugin(RemoteConnection, config)
|
||||
await resumed.await()
|
||||
const restored = ctx.connection.admit({ headers: { host: authority, cookie: remoteCookie } })
|
||||
if ('rejection' in restored) throw new Error('Remote Cookie did not survive provider reload')
|
||||
expect(restored.peer).not.toBe(remoteAdmission.peer)
|
||||
expect((await send('/', 'GET', { cookie: remoteCookie })).status).toBe(200)
|
||||
await token?.dispose()
|
||||
expect(tokenAdmission.peer.signal.aborted).toBe(true)
|
||||
expect(restored.peer.signal.aborted).toBe(false)
|
||||
expect(ctx.connection.admit({ headers: { host: authority, cookie: tokenCookie } })).toEqual({ rejection: 401 })
|
||||
expect((await send('/', 'GET', { cookie: remoteCookie })).status).toBe(200)
|
||||
const otherTicket = owner(ctx).create()
|
||||
expect((await send('/remote-login', 'POST', { 'content-type': 'text/plain' }, new URL(otherTicket.url).hash.slice(1))).status).toBe(204)
|
||||
})
|
||||
|
||||
it('trusts an explicitly admitted in-process Peer without authenticating it again', async () => {
|
||||
const { ctx, origin, renderedPeers } = await mounted()
|
||||
const peer = ctx.connection.createPeer({ principal: { kind: 'owner' } })
|
||||
const authenticate = vi.spyOn(ctx.connection.authentication, 'authenticate')
|
||||
const page = await ctx.webServer.readResource(new Request(new URL('/', origin)), peer)
|
||||
expect(page.status).toBe(200)
|
||||
expect(await page.text()).toContain('PRIVATE_APPLICATION')
|
||||
expect(renderedPeers.at(-1)).toBe(peer)
|
||||
expect(authenticate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('waits for its admitted root read before completing Remote disposal', async () => {
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const { ctx, authority, remote, send, redeem, renderedPeers } = await mounted(false, () => { release.resolve(undefined) })
|
||||
const anonymous = await send('/')
|
||||
expect(anonymous.status).toBe(401)
|
||||
expect(anonymous.body).not.toContain('PRIVATE_APPLICATION')
|
||||
expect(anonymous.body).not.toContain('PRIVATE_BOOT_DATA')
|
||||
const remoteCookie = cookie(await redeem())
|
||||
const admission = ctx.connection.admit({ headers: { host: authority, cookie: remoteCookie } })
|
||||
if ('rejection' in admission) throw new Error('Remote Cookie was rejected')
|
||||
const reached = Promise.withResolvers<{ readonly request: Request; readonly peer: PeerScope | undefined }>()
|
||||
const read = ctx.webServer.readResource.bind(ctx.webServer)
|
||||
const readResource = vi.spyOn(ctx.webServer, 'readResource').mockImplementationOnce(async (request, peer) => {
|
||||
const response = await read(request, peer)
|
||||
reached.resolve({ request, peer })
|
||||
await release.promise
|
||||
return response
|
||||
})
|
||||
const authenticate = vi.spyOn(ctx.connection.authentication, 'authenticate')
|
||||
const pending = send('/', 'GET', { cookie: remoteCookie })
|
||||
let disposing: Promise<void> | undefined
|
||||
try {
|
||||
const held = await reached.promise
|
||||
expect(new URL(held.request.url).pathname).toBe('/index.html')
|
||||
expect(held.peer).toBe(admission.peer)
|
||||
expect(renderedPeers.at(-1)).toBe(admission.peer)
|
||||
expect(authenticate).toHaveBeenCalledTimes(1)
|
||||
expect(readResource).toHaveBeenCalledOnce()
|
||||
let disposed = false
|
||||
disposing = remote.dispose().then(() => { disposed = true })
|
||||
await vi.waitFor(() => { expect(held.request.signal.aborted).toBe(true) })
|
||||
expect(disposed).toBe(false)
|
||||
release.resolve(undefined)
|
||||
await disposing
|
||||
const page = await pending
|
||||
expect(page.status).toBe(200)
|
||||
expect(page.body).toContain('PRIVATE_APPLICATION')
|
||||
expect(authenticate).toHaveBeenCalledTimes(1)
|
||||
expect(admission.peer.signal.aborted).toBe(true)
|
||||
expect(ctx.connection.admit({ headers: { host: authority, cookie: remoteCookie } })).toEqual({ rejection: 401 })
|
||||
const after = await send('/', 'GET', { cookie: remoteCookie })
|
||||
expect(after.status).toBe(401)
|
||||
expect(after.body).not.toContain('PRIVATE_APPLICATION')
|
||||
expect(after.body).not.toContain('PRIVATE_BOOT_DATA')
|
||||
} finally {
|
||||
release.resolve(undefined)
|
||||
await Promise.allSettled([pending, ...disposing === undefined ? [] : [disposing]])
|
||||
}
|
||||
})
|
||||
|
||||
it('does not publish routes or a Peer after disposal interrupts credential initialization', async () => {
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
const ctx = new Context()
|
||||
onTestFinished(async () => {
|
||||
release.resolve(undefined)
|
||||
await ctx.fiber.dispose()
|
||||
})
|
||||
class PausedCredentials extends MemoryCredentials {
|
||||
override async modifyRecord(
|
||||
key: CredentialKey,
|
||||
mutate: (current: CredentialRecord | undefined) => Promise<CredentialRecord | undefined>,
|
||||
): Promise<CredentialRecord | undefined> {
|
||||
entered.resolve(undefined)
|
||||
await release.promise
|
||||
return super.modifyRecord(key, mutate)
|
||||
}
|
||||
}
|
||||
await ctx.plugin(PausedCredentials)
|
||||
await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 })
|
||||
ctx.provide('webApp', { getAdvertisedUrl: () => 'http://remote.example/' })
|
||||
await ctx.plugin(Connection, { trustedHosts: ['remote.example'] })
|
||||
const registerRoute = vi.spyOn(ctx.webServer, 'register')
|
||||
const registerProvider = vi.spyOn(ctx.connection.authentication, 'register')
|
||||
const createPeer = vi.spyOn(ctx.connection, 'createPeer')
|
||||
const remote = ctx.plugin(RemoteConnection, RemoteConnection.Config({}))
|
||||
const initializing = Promise.allSettled([remote.await()])
|
||||
await entered.promise
|
||||
const disposing = remote.dispose()
|
||||
release.resolve(undefined)
|
||||
await disposing
|
||||
expect((await initializing).map(result => result.status)).toEqual(['fulfilled'])
|
||||
expect(registerRoute).not.toHaveBeenCalled()
|
||||
expect(registerProvider).not.toHaveBeenCalled()
|
||||
expect(createPeer).not.toHaveBeenCalled()
|
||||
expect(ctx.connection.admit({ headers: { host: 'remote.example' } })).toEqual({ rejection: 401 })
|
||||
})
|
||||
|
||||
it('does not write a second response when an applicant disconnects during its credential body', async () => {
|
||||
const { ctx, origin, authority, publicUrl, service, send } = await mounted()
|
||||
const entered = Promise.withResolvers<{ readonly response: ServerResponse; readonly writes: () => number }>()
|
||||
const handled = Promise.withResolvers<undefined>()
|
||||
ctx.on('webserver/request', async (request, response, next) => {
|
||||
if (request.url !== '/remote-login') { await next(); return }
|
||||
const writes = vi.spyOn(response, 'writeHead')
|
||||
entered.resolve({ response, writes: () => writes.mock.calls.length })
|
||||
try { await next() } finally { handled.resolve(undefined) }
|
||||
})
|
||||
const ticket = service.create()
|
||||
const secret = new URL(ticket.url).hash.slice(1)
|
||||
const errors: Error[] = []
|
||||
const request = httpRequest(new URL('/remote-login', origin), {
|
||||
method: 'POST', headers: { host: authority, origin: publicUrl.slice(0, -1), 'content-type': 'text/plain' },
|
||||
})
|
||||
request.on('error', error => errors.push(error))
|
||||
const closed = new Promise<void>((resolve) => { request.once('close', resolve) })
|
||||
request.write(secret.slice(0, -1))
|
||||
try {
|
||||
const accepted = await entered.promise
|
||||
request.destroy()
|
||||
await Promise.all([closed, handled.promise])
|
||||
expect(accepted.response.destroyed).toBe(true)
|
||||
expect(accepted.writes()).toBe(0)
|
||||
expect(errors.every(error => Reflect.get(error, 'code') === 'ECONNRESET')).toBe(true)
|
||||
expect(service.status(ticket.id).ticket).toBe('pending')
|
||||
const completed = await send('/remote-login', 'POST', { 'content-type': 'text/plain' }, secret)
|
||||
expect(completed.status).toBe(204)
|
||||
} finally {
|
||||
request.destroy()
|
||||
await closed
|
||||
}
|
||||
})
|
||||
|
||||
it('reports provider faults as unavailable without rendering a login page or private data', async () => {
|
||||
const { ctx, send, renderedPeers } = await mounted()
|
||||
ctx.connection.authentication.register({ authenticate() { throw new Error('unavailable fixture provider') } })
|
||||
const page = await send('/')
|
||||
expect(page.status).toBe(503)
|
||||
expect(page.body).not.toContain('<html')
|
||||
expect(page.body).not.toContain('PRIVATE_APPLICATION')
|
||||
expect(page.body).not.toContain('PRIVATE_BOOT_DATA')
|
||||
expect(renderedPeers).toHaveLength(0)
|
||||
})
|
||||
@@ -0,0 +1,238 @@
|
||||
// @vitest-environment jsdom
|
||||
/** What the Remote connection panel exposes during each login-code outcome. */
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
|
||||
import { RemoteConnectionSection, type RemoteConnectionSectionProps } from '../src/client/RemoteConnectionSection.tsx'
|
||||
import type { RemoteConnectionState } from '../src/client/remote-connection-controller.ts'
|
||||
import type { LoginLinkState } from '../src/client/login-link-controller.ts'
|
||||
import type { RemoteLoginId } from '../src/types.ts'
|
||||
import { en, zh } from '../src/client/locales.ts'
|
||||
import type {} from '../src/client/index.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const ready: RemoteConnectionState = {
|
||||
deployment: { url: 'https://host.example/app/', availability: 'available', 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/remote-login#token=private', lifetimeMs: 120_000 }
|
||||
|
||||
function panel(overrides: Partial<RemoteConnectionState> = {}, language: 'en' | 'zh' = 'en', linkOverrides: Partial<LoginLinkState> = {}) {
|
||||
const state = createSnapshotStore({ ...ready, ...overrides })
|
||||
const linkState = createSnapshotStore<LoginLinkState>({ url: 'https://host.example/app/?token=private-login-token', phase: 'ready', copied: false, notice: null, sequence: 0, ...linkOverrides })
|
||||
const actions = { create: vi.fn(), cancel: vi.fn(), reload: vi.fn(), copyLink: vi.fn(), reloadLink: vi.fn(), dismissCopyNotice: vi.fn() }
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
const locale = new LocaleRuntime(ctx)
|
||||
locale.register('remoteConnection', { en, zh })
|
||||
locale.setLocale(language)
|
||||
const t = locale.bind('remoteConnection')
|
||||
const props = {
|
||||
...actions, t, useRemoteConnection: bindSnapshotSelector(state), useLoginLink: bindSnapshotSelector(linkState),
|
||||
} as RemoteConnectionSectionProps
|
||||
render(<RemoteConnectionSection {...props} />)
|
||||
return { ...actions, state, linkState }
|
||||
}
|
||||
|
||||
describe('Remote connection section', () => {
|
||||
it('separates QR and link login and shows no credential warnings before either action', () => {
|
||||
const { create, copyLink } = panel()
|
||||
expect(screen.getByRole('region', { name: en.title })).toBeTruthy()
|
||||
expect(screen.queryByText(en.warningTitle)).toBeNull()
|
||||
expect(screen.queryByText(en.linkWarningTitle)).toBeNull()
|
||||
expect(screen.queryByText(en.httpWarning)).toBeNull()
|
||||
expect(screen.queryByRole('img')).toBeNull()
|
||||
const qr = screen.getByRole('region', { name: en.qrTitle })
|
||||
const link = screen.getByRole('region', { name: en.linkTitle })
|
||||
expect(within(qr).queryByRole('button', { name: en.copyLink })).toBeNull()
|
||||
expect(within(link).queryByRole('button', { name: en.generate })).toBeNull()
|
||||
expect(within(qr).queryByText('https://host.example/app/')).toBeNull()
|
||||
expect(within(qr).queryByRole('code')).toBeNull()
|
||||
expect(within(link).getByText('https://host.example/app/?token=private-login-token')).toBeTruthy()
|
||||
fireEvent.click(within(qr).getByRole('button', { name: en.generate }))
|
||||
fireEvent.click(within(link).getByRole('button', { name: en.copyLink }))
|
||||
expect(create).toHaveBeenCalledOnce()
|
||||
expect(copyLink).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('renders a scannable SVG and countdown without printing or linking the secret URL', () => {
|
||||
const { create, cancel } = panel({ phase: 'pending', ticket })
|
||||
const qr = screen.getByRole('img', { name: en.qr })
|
||||
expect(qr.tagName.toLowerCase()).toBe('svg')
|
||||
expect(qr.querySelector('path')).not.toBeNull()
|
||||
expect(screen.getByRole('timer').textContent).toBe('Expires in 120s')
|
||||
expect(screen.getByText(en.warning)).toBeTruthy()
|
||||
expect(screen.queryByText(en.linkWarning)).toBeNull()
|
||||
expect(screen.getByText(en.scan)).toBeTruthy()
|
||||
expect(document.body.textContent).not.toContain(ticket.url)
|
||||
expect(document.querySelector('a[href*="token="]')).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: en.regenerate }))
|
||||
fireEvent.click(screen.getByRole('button', { name: en.cancel }))
|
||||
expect(create).toHaveBeenCalledOnce()
|
||||
expect(cancel).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each(['unreachable-host', 'untrusted-host'] as const)('explains the %s prerequisite and offers no code', (availability) => {
|
||||
panel({ deployment: { ...ready.deployment!, availability } })
|
||||
expect(screen.getByRole('status').textContent).toBe(en[availability])
|
||||
expect(screen.queryByRole('button')).toBeNull()
|
||||
expect(screen.queryByRole('img')).toBeNull()
|
||||
expect(screen.queryByText(en.warning)).toBeNull()
|
||||
})
|
||||
|
||||
it.each(['en', 'zh'] as const)('allows HTTP code creation with a plaintext reminder in %s', (language) => {
|
||||
const copy = language === 'en' ? en : zh
|
||||
const { create } = panel({ deployment: { ...ready.deployment!, url: 'http://host.example/app/' } }, language)
|
||||
expect(screen.queryByText(copy.httpWarning)).toBeNull()
|
||||
expect(screen.queryByText(copy.warning)).toBeNull()
|
||||
const generate = screen.getByRole('button', { name: copy.generate })
|
||||
expect(generate).toHaveProperty('disabled', false)
|
||||
fireEvent.click(generate)
|
||||
expect(create).toHaveBeenCalledOnce()
|
||||
cleanup()
|
||||
panel({ deployment: { ...ready.deployment!, url: 'http://host.example/app/' }, phase: 'pending', ticket }, language)
|
||||
expect(screen.getByText(copy.httpWarning)).toBeTruthy()
|
||||
expect(screen.getByText(copy.warning)).toBeTruthy()
|
||||
})
|
||||
|
||||
it.each(['loading', 'creating', 'cancelling'] as const)('hides the QR and prevents duplicate gestures while %s', (phase) => {
|
||||
panel({ phase, ticket })
|
||||
expect(screen.getByRole('status', { name: en[phase] })).toBeTruthy()
|
||||
expect(screen.queryByRole('img')).toBeNull()
|
||||
expect(screen.getByRole('button', { name: en.regenerate })).toHaveProperty('disabled', true)
|
||||
expect(screen.getByRole('button', { name: en.cancel })).toHaveProperty('disabled', true)
|
||||
})
|
||||
|
||||
it('keeps the link card and its focus while the QR is generated or refreshed', () => {
|
||||
const { state, copyLink } = panel({ phase: 'pending', ticket }, 'en', { copied: true })
|
||||
const qr = screen.getByRole('region', { name: en.qrTitle })
|
||||
const link = screen.getByRole('region', { name: en.linkTitle })
|
||||
const copy = within(link).getByRole('button', { name: en.copied })
|
||||
copy.focus()
|
||||
for (const phase of ['creating', 'loading'] as const) {
|
||||
act(() => { state.update((value) => { value.phase = phase; value.ticket = null }) })
|
||||
expect(screen.getByRole('region', { name: en.qrTitle })).toBe(qr)
|
||||
expect(within(qr).getByRole('status', { name: en[phase] })).toBeTruthy()
|
||||
expect(within(qr).queryByRole('img')).toBeNull()
|
||||
expect(within(qr).queryByRole('timer')).toBeNull()
|
||||
expect(screen.getByRole('region', { name: en.linkTitle })).toBe(link)
|
||||
expect(within(link).getByRole('button', { name: en.copied })).toBe(copy)
|
||||
expect(copy).toHaveProperty('disabled', false)
|
||||
expect(document.activeElement).toBe(copy)
|
||||
expect(within(link).getByText(en.linkWarning)).toBeTruthy()
|
||||
}
|
||||
fireEvent.click(copy)
|
||||
expect(copyLink).toHaveBeenCalledOnce()
|
||||
act(() => { state.update((value) => { value.phase = 'pending'; value.ticket = ticket; value.remainingSeconds = 90 }) })
|
||||
expect(within(qr).getByRole('img', { name: en.qr })).toBeTruthy()
|
||||
expect(within(qr).getByRole('timer').textContent).toBe('Expires in 90s')
|
||||
})
|
||||
|
||||
it('retains the scan line, countdown, and warning while only the QR is replaced', () => {
|
||||
const { state } = panel({ phase: 'pending', ticket })
|
||||
const qr = screen.getByRole('region', { name: en.qrTitle })
|
||||
const scan = within(qr).getByText(en.scan)
|
||||
const timer = within(qr).getByRole('timer')
|
||||
const warning = within(qr).getByText(en.warning)
|
||||
act(() => { state.update((value) => { value.phase = 'creating'; value.ticket = null; value.retainDetails = true }) })
|
||||
expect(within(qr).queryByRole('img')).toBeNull()
|
||||
expect(within(qr).getByRole('status', { name: en.creating })).toBeTruthy()
|
||||
expect(within(qr).getByText(en.scan)).toBe(scan)
|
||||
expect(within(qr).getByRole('timer')).toBe(timer)
|
||||
expect(within(qr).getByText(en.warning)).toBe(warning)
|
||||
expect(timer.textContent).toBe('Expires in 120s')
|
||||
expect(document.body.textContent).not.toContain(ticket.url)
|
||||
act(() => { state.update((value) => { value.phase = 'pending'; value.ticket = ticket; value.remainingSeconds = 90; value.retainDetails = false }) })
|
||||
expect(within(qr).getByRole('img', { name: en.qr })).toBeTruthy()
|
||||
expect(within(qr).getByRole('timer')).toBe(timer)
|
||||
expect(timer.textContent).toBe('Expires in 90s')
|
||||
expect(within(qr).getByText(en.warning)).toBe(warning)
|
||||
})
|
||||
|
||||
it.each(['used', 'expired', 'replaced'] as const)('shows %s as a settled outcome with no QR', (phase) => {
|
||||
panel({ phase })
|
||||
expect(screen.getByRole('status').textContent).toBe(en[phase])
|
||||
expect(screen.queryByRole('img')).toBeNull()
|
||||
expect(screen.getByRole('button', { name: en.regenerate })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('closes the QR preview after cancellation without a success message', () => {
|
||||
panel({ phase: 'cancelled' })
|
||||
const qr = screen.getByRole('region', { name: en.qrTitle })
|
||||
expect(within(qr).queryByRole('img')).toBeNull()
|
||||
expect(within(qr).queryByRole('timer')).toBeNull()
|
||||
expect(within(qr).queryByRole('status')).toBeNull()
|
||||
expect(within(qr).queryByText(en.warning)).toBeNull()
|
||||
expect(within(qr).queryByRole('button', { name: en.cancel })).toBeNull()
|
||||
expect(within(qr).getByRole('button', { name: en.regenerate })).toHaveProperty('disabled', false)
|
||||
})
|
||||
|
||||
it('keeps an uncertain code hidden and offers status recovery and cancellation', () => {
|
||||
const { reload, cancel } = panel({ phase: 'error', error: 'statusFailed', ticket })
|
||||
expect(screen.getByRole('alert').textContent).toBe(en.statusFailed)
|
||||
expect(screen.queryByRole('img')).toBeNull()
|
||||
fireEvent.click(screen.getByRole('button', { name: en.retry }))
|
||||
fireEvent.click(screen.getByRole('button', { name: en.cancel }))
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
expect(cancel).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('allows retry when deployment loading failed and shows a centered pending state while reading', () => {
|
||||
const { reload } = panel({ phase: 'error', deployment: null, error: 'loadFailed' })
|
||||
expect(screen.getByRole('alert').textContent).toBe(en.loadFailed)
|
||||
fireEvent.click(screen.getByRole('button', { name: en.retry }))
|
||||
expect(reload).toHaveBeenCalledOnce()
|
||||
cleanup()
|
||||
panel({ phase: 'loading', deployment: null })
|
||||
expect(screen.getByRole('status', { name: en.loading })).toBeTruthy()
|
||||
expect(screen.queryByRole('button')).toBeNull()
|
||||
})
|
||||
|
||||
it('localizes the panel and its countdown', () => {
|
||||
panel({ phase: 'pending', ticket, remainingSeconds: 0 }, 'zh')
|
||||
expect(screen.getByRole('region', { name: zh.title })).toBeTruthy()
|
||||
expect(screen.getByRole('img', { name: zh.qr })).toBeTruthy()
|
||||
expect(screen.getByRole('timer').textContent).toBe('0 秒后过期')
|
||||
expect(screen.getByText(zh.warningTitle)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('shows link feedback and its warning only after copying succeeds, independently of QR login', () => {
|
||||
const { linkState } = panel()
|
||||
expect(screen.queryByText(en.linkWarning)).toBeNull()
|
||||
act(() => { linkState.update((state) => { state.phase = 'copying' }) })
|
||||
expect(screen.getByRole('button', { name: en.copying })).toHaveProperty('disabled', true)
|
||||
expect(screen.queryByText(en.linkWarning)).toBeNull()
|
||||
act(() => { linkState.update((state) => { state.phase = 'ready'; state.copied = true }) })
|
||||
expect(screen.getByRole('button', { name: en.copied })).toHaveProperty('disabled', false)
|
||||
expect(screen.getByText(en.linkWarning)).toBeTruthy()
|
||||
expect(screen.queryByText(en.warning)).toBeNull()
|
||||
expect(screen.getByText('https://host.example/app/?token=private-login-token')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('reuses the copy button to retry a failed link read while QR creation remains available', () => {
|
||||
const { reloadLink, copyLink, linkState } = panel({}, 'en', { phase: 'error', url: null })
|
||||
const link = screen.getByRole('region', { name: en.linkTitle })
|
||||
expect(within(link).getByRole('alert').textContent).toBe(en.linkFailed)
|
||||
expect(within(link).getAllByRole('button')).toHaveLength(1)
|
||||
const action = within(link).getByRole('button', { name: en.retry })
|
||||
expect(action).toHaveProperty('disabled', false)
|
||||
fireEvent.click(action)
|
||||
expect(reloadLink).toHaveBeenCalledOnce()
|
||||
expect(screen.getByRole('button', { name: en.generate })).toHaveProperty('disabled', false)
|
||||
expect(screen.queryByText(en.linkWarning)).toBeNull()
|
||||
act(() => { linkState.update((state) => { state.phase = 'loading' }) })
|
||||
expect(within(link).getByRole('button', { name: en.copyLink })).toBe(action)
|
||||
expect(action).toHaveProperty('disabled', true)
|
||||
act(() => { linkState.update((state) => { state.phase = 'ready'; state.url = 'https://host.example/app/?token=retry-token' }) })
|
||||
expect(within(link).getByRole('button', { name: en.copyLink })).toBe(action)
|
||||
expect(within(link).getAllByRole('button')).toHaveLength(1)
|
||||
expect(within(link).queryByRole('alert')).toBeNull()
|
||||
expect(action).toHaveProperty('disabled', false)
|
||||
fireEvent.click(action)
|
||||
expect(copyLink).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.client.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo"
|
||||
},
|
||||
"include": [
|
||||
"src/client",
|
||||
"src/login-page.ts",
|
||||
"src/login-locales.ts",
|
||||
"src/types.ts",
|
||||
"src/css-modules.d.ts"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../../util/brand"
|
||||
},
|
||||
{
|
||||
"path": "../../typert/protocol"
|
||||
},
|
||||
{
|
||||
"path": "../store"
|
||||
},
|
||||
{
|
||||
"path": "../ui-primitives"
|
||||
},
|
||||
{
|
||||
"path": "../ui-slots"
|
||||
},
|
||||
{
|
||||
"path": "../ui-renderer"
|
||||
},
|
||||
{
|
||||
"path": "../ui-layout"
|
||||
},
|
||||
{
|
||||
"path": "../ui-settings/tsconfig.client.json"
|
||||
},
|
||||
{
|
||||
"path": "../locale/tsconfig.client.json"
|
||||
},
|
||||
{
|
||||
"path": "../../api/remotes/tsconfig.client.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo"
|
||||
},
|
||||
"include": [
|
||||
"src/*.ts"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../../../vendor/schemastery"
|
||||
},
|
||||
{
|
||||
"path": "../../util/brand"
|
||||
},
|
||||
{
|
||||
"path": "../../typert/protocol"
|
||||
},
|
||||
{
|
||||
"path": "../connection/tsconfig.host.json"
|
||||
},
|
||||
{
|
||||
"path": "../../host/webserver"
|
||||
},
|
||||
{
|
||||
"path": "../../bundle/web-app"
|
||||
},
|
||||
{
|
||||
"path": "../../credentials/credentials"
|
||||
},
|
||||
{
|
||||
"path": "../../util/error"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.host.json"
|
||||
},
|
||||
{
|
||||
"path": "./tsconfig.client.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { clientBundle } from '../tsdown.client.ts'
|
||||
|
||||
export default clientBundle(import.meta.dirname, ['lib/types/index.js'])
|
||||
@@ -656,3 +656,9 @@ export const IconSaveOutlineRegular = productIcon('save-outline', 'regular')
|
||||
|
||||
/** Medium floppy-disk save action. */
|
||||
export const IconSaveOutlineMedium = productIcon('save-outline', 'medium')
|
||||
|
||||
/** Regular remote connection phone artwork; both weights preserve its filled contours. */
|
||||
export const IconRemoteConnectionOutlineRegular = productIcon('remote-connection-outline', 'regular')
|
||||
|
||||
/** Medium remote connection phone artwork; both weights preserve its filled contours. */
|
||||
export const IconRemoteConnectionOutlineMedium = productIcon('remote-connection-outline', 'medium')
|
||||
@@ -40,6 +40,7 @@ describe('product icon set', () => {
|
||||
expect(medium.sort()).toEqual(regular.sort())
|
||||
expect(iconNames).toEqual(expect.arrayContaining([
|
||||
'IconMicrophoneOutlineRegular',
|
||||
'IconRemoteConnectionOutlineRegular',
|
||||
'IconPlanOutlineRegular', 'IconCompactOutlineRegular', 'IconShieldOutlineRegular', 'IconDeliverDocRegular',
|
||||
'IconWarningTriangleOutlineRegular', 'IconCompareSplitOutlineRegular', 'IconCloseCircleFillRegular',
|
||||
'IconEyeOutlineRegular', 'IconEyeOffOutlineRegular',
|
||||
|
||||
@@ -19,7 +19,7 @@ import clsx from 'clsx'
|
||||
import {
|
||||
ConnectionIndicator, Tooltip, useModalLayer,
|
||||
IconAgentPresetOutlineMedium, IconArchiveOutlineMedium, IconCloseOutlineRegular, IconDataOutlineMedium,
|
||||
IconPersonalizationOutlineMedium, IconSettingsOutlineMedium, IconUserOutlineMedium,
|
||||
IconPersonalizationOutlineMedium, IconRemoteConnectionOutlineMedium, IconSettingsOutlineMedium, IconUserOutlineMedium,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { ConnectionIndicatorState } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SettingsRootComponentProps, SettingsSectionRow } from './shell-contract.ts'
|
||||
@@ -38,6 +38,7 @@ function navIcon(id: string) {
|
||||
if (id === 'agent-presets') return <IconAgentPresetOutlineMedium size={16} />
|
||||
if (id === 'plugins') return <IconPersonalizationOutlineMedium size={16} />
|
||||
if (id === 'archived-sessions') return <IconArchiveOutlineMedium size={16} />
|
||||
if (id === 'remote-connection') return <IconRemoteConnectionOutlineMedium size={16} />
|
||||
return <IconSettingsOutlineMedium size={16} />
|
||||
}
|
||||
|
||||
|
||||
@@ -399,19 +399,21 @@ describe('SettingsPanel navigation', () => {
|
||||
{ id: 'agent-presets', order: 20, label: 'Agent presets' },
|
||||
{ id: 'plugins', order: 30, label: 'Plugins' },
|
||||
{ id: 'archived-sessions', order: 40, label: 'Archived sessions' },
|
||||
{ id: 'contributed', order: 50, label: 'Contributed' },
|
||||
{ id: 'remote-connection', order: 50, label: 'Remote connection' },
|
||||
{ id: 'contributed', order: 60, label: 'Contributed' },
|
||||
],
|
||||
})
|
||||
openPanel()
|
||||
// Each product glyph names its sprite symbol id in data-icon.
|
||||
const glyphs = ['General', 'Models', 'Agent presets', 'Plugins', 'Archived sessions', 'Contributed']
|
||||
const glyphs = ['General', 'Models', 'Agent presets', 'Plugins', 'Archived sessions', 'Remote connection', 'Contributed']
|
||||
.map(name => screen.getByRole('button', { name }).querySelector('svg')?.getAttribute('data-icon'))
|
||||
|
||||
expect(glyphs.every(glyph => glyph !== undefined && glyph !== '')).toBe(true)
|
||||
// The four ids the shell names get their own glyph; every other section —
|
||||
// The five ids the shell names get their own glyph; every other section —
|
||||
// including one this package never heard of — shares the gear.
|
||||
expect(new Set(glyphs.slice(0, 5)).size).toBe(5)
|
||||
expect(glyphs[5]).toBe(glyphs[0])
|
||||
expect(new Set(glyphs.slice(0, 6)).size).toBe(6)
|
||||
expect(glyphs[5]).toBe('dsw-icon-remote-connection-outline-medium')
|
||||
expect(glyphs[6]).toBe(glyphs[0])
|
||||
})
|
||||
|
||||
it('switches the rendered section on nav click', () => {
|
||||
|
||||
@@ -44,7 +44,7 @@ const CHILD_NAMES = Object.keys(CHILD_SPECS) as Array<keyof typeof CHILD_SPECS>
|
||||
* ui-settings-models, ui-plugin-manager, and ui-agent-preset. A plugin
|
||||
* adding a section changes this list.
|
||||
*/
|
||||
const PRODUCT_SECTIONS: readonly string[] = ['general', 'models', 'plugins', 'agent-presets']
|
||||
const PRODUCT_SECTIONS: readonly string[] = ['general', 'models', 'plugins', 'agent-presets', 'remote-connection']
|
||||
/** Onboarding steps the web-app roster registers, in coordinator order; both come from ui-settings-models. */
|
||||
const PRODUCT_ONBOARDING: readonly { id: string; order: number }[] = [
|
||||
{ id: 'welcome-notice', order: -100 },
|
||||
|
||||
@@ -33,17 +33,19 @@ describe('icon sprite', () => {
|
||||
expect(sprite()).toBeNull()
|
||||
})
|
||||
|
||||
it('swaps in the active theme replacement and restores the default when the theme leaves', async () => {
|
||||
it.each([SEARCH, 'dsw-icon-remote-connection-outline-medium'] as const)('replaces %s independently and restores its default when the theme leaves', async (id) => {
|
||||
const { theme, fiber, symbol } = await mount()
|
||||
const dispose = theme.register({ id: 'skin', colorScheme: 'dark', tokens: {}, icons: { [SEARCH]: TWO_TONE } })
|
||||
const gear = symbol('dsw-icon-settings-outline-medium')
|
||||
const dispose = theme.register({ id: 'skin', colorScheme: 'dark', tokens: {}, icons: { [id]: TWO_TONE } })
|
||||
theme.setTheme('skin')
|
||||
const replaced = symbol(SEARCH)!
|
||||
const replaced = symbol(id)!
|
||||
expect(replaced.getAttribute('viewBox')).toBe('0 0 16 16')
|
||||
expect(replaced.hasAttribute('width') || replaced.hasAttribute('class')).toBe(false)
|
||||
expect(replaced.querySelector('circle')?.getAttribute('fill')).toBe('var(--dsw-alias-link)')
|
||||
expect(symbol('dsw-icon-settings-outline-medium')).toBe(gear)
|
||||
const untouched = symbol('dsw-icon-plus-outline-regular')
|
||||
theme.setTheme('light')
|
||||
expect(symbol(SEARCH)?.querySelector('circle')).toBeNull()
|
||||
expect(symbol(id)?.querySelector('circle')).toBeNull()
|
||||
expect(symbol('dsw-icon-plus-outline-regular')).toBe(untouched)
|
||||
dispose()
|
||||
await fiber.dispose()
|
||||
|
||||
@@ -4420,6 +4420,40 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.onboarding\', () => ctx.slots.register(\n { name: \'settings.onboarding\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/ui-settings/src/client/contract/slots.ts:100',
|
||||
},
|
||||
{
|
||||
key: 'settings.remoteConnection.content',
|
||||
kind: 'single',
|
||||
scope: 'root',
|
||||
summary: 'Complete Remote connection panel with shared invitation state and actions.',
|
||||
doc: 'Complete Remote connection panel with shared invitation state and actions.\nReceives invitation and login-link selectors, their actions, and close().\nUnloading a replacement restores the default panel with the current invitation.',
|
||||
registerOptions: [],
|
||||
ownerProps: [
|
||||
'/**\n * Owner share of a settings section entry. The shell owns modal visibility\n * and navigation; a section\'s data arrives through its own inject faces and\n * stores. `close` is the one shell affordance a section receives, for flows\n * that leave settings altogether (starting a session from a section) — the\n * onboarding coordinator\'s `openSection`/`complete` precedent, inverted.\n */\nexport interface SettingsSectionOwnerProps {\n /** Close the settings panel (the shell owns the open state). */\n close: () => void\n}',
|
||||
],
|
||||
ownerPropsReferences: [],
|
||||
standardProps: [
|
||||
'useRemoteAccess: (action: RemoteEndpoint) => boolean',
|
||||
'useResource: UseResource',
|
||||
'useContextMenu: UseContextMenu',
|
||||
'useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>',
|
||||
'usePanelInfo: UsePanelInfo',
|
||||
'useSessionStatus: UseSessionStatus',
|
||||
'useSessions: UseSessions',
|
||||
'useSessionRetainInfo: UseSessionRetainInfo',
|
||||
'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean',
|
||||
'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean',
|
||||
],
|
||||
keyDomain: '',
|
||||
hookContext: '',
|
||||
slotInject: 'RemoteConnectionFace & LoginLinkFace',
|
||||
declaredBy: 'an entry in \'settings.section\' (client-remote-connection), so it exists while that entry is mounted',
|
||||
occupants: [
|
||||
'client-remote-connection RemoteConnectionSection',
|
||||
],
|
||||
replaceRisk: 'shadows-shipped-ui',
|
||||
example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.remoteConnection.content\', () => ctx.slots.register(\n { name: \'settings.remoteConnection.content\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}',
|
||||
source: 'packages/client/remote-connection/src/client/slots.ts:14',
|
||||
},
|
||||
{
|
||||
key: 'settings.section',
|
||||
kind: 'list',
|
||||
@@ -4467,6 +4501,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
slotInject: '',
|
||||
declaredBy: 'factory \'settings.section.view\' (client-ui-settings-general), so it exists while that definition is registered',
|
||||
occupants: [
|
||||
'client-remote-connection RemoteConnectionSettings id \'remote-connection\'',
|
||||
'client-ui-agent-preset AgentPresetSection id \'agent-presets\'',
|
||||
'client-ui-plugin-manager PluginsSettingsLink',
|
||||
'client-ui-settings-account AccountSection id \'account\'',
|
||||
@@ -4671,6 +4706,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
|
||||
slotInject: '',
|
||||
declaredBy: 'an entry in \'root\' (client-ui-layout), so it exists while that entry is mounted',
|
||||
occupants: [
|
||||
'client-remote-connection LoginLinkToast id \'remote-connection-copy\'',
|
||||
'client-ui-agent-team TeamDisableConfirmation id \'agent-team.disable\'',
|
||||
'client-ui-chat QuotaNoticeHost id \'chat.quota-notice\'',
|
||||
'client-ui-connector-account ConnectorAccountToastEntry id \'connector-account.notice\'',
|
||||
|
||||
@@ -3181,6 +3181,37 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'remoteConnection',
|
||||
summary: 'One outstanding invitation, issued by an owner and consumed by a new browser.',
|
||||
description: 'One outstanding invitation, issued by an owner and consumed by a new browser.',
|
||||
methods: [
|
||||
{
|
||||
signature: '@Remote status(id: RemoteLoginId | null): RemoteConnectionStatus',
|
||||
description: 'Read prerequisites and the state of one invitation without disclosing its credential.',
|
||||
parameters: [{ name: 'id', description: 'invitation to inspect, or null to inspect only deployment prerequisites.' }],
|
||||
returns: 'deployment availability and invitation state, with the polling interval.',
|
||||
},
|
||||
{
|
||||
signature: '@Remote create(): RemoteLoginTicket',
|
||||
description: 'Authorize a new browser by generating a one-use login invitation; replaces any older invitation.',
|
||||
parameters: [],
|
||||
returns: 'the invitation credential and its fixed expiry.',
|
||||
},
|
||||
{
|
||||
signature: '@Remote loginUrl(): string',
|
||||
description: 'Read the advertised URL carrying the process launch token; QR invitations are unchanged.',
|
||||
parameters: [],
|
||||
returns: 'owner-only login URL, reusable until the Host process restarts; never persist or log it.',
|
||||
},
|
||||
{
|
||||
signature: '@Remote cancel(id: RemoteLoginId): RemoteLoginState',
|
||||
description: 'Cancel an unused invitation; this never revokes a browser session already issued.',
|
||||
parameters: [{ name: 'id', description: 'invitation being cancelled; an older ID cannot cancel a replacement.' }],
|
||||
returns: 'the invitation\'s final state, including used when a redemption won the race.',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'sandbox',
|
||||
summary: 'Abstract process-sandbox service.',
|
||||
@@ -9363,6 +9394,14 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'RemoteAccessRole',
|
||||
declaration: 'export interface RemoteAccessRole<K extends RemoteAccessResourceKind> {\n readonly name: string;\n readonly resource: K;\n readonly actions: readonly RemoteAccessAction[];\n}',
|
||||
},
|
||||
{
|
||||
name: 'RemoteConnectionStatus',
|
||||
declaration: 'export interface RemoteConnectionStatus {\n readonly url: string;\n readonly availability: \'available\' | RemoteConnectionUnavailable;\n readonly ticket: RemoteLoginState;\n readonly pollIntervalMs: number;\n}',
|
||||
},
|
||||
{
|
||||
name: 'RemoteConnectionUnavailable',
|
||||
declaration: 'export type RemoteConnectionUnavailable = \'unreachable-host\' | \'untrusted-host\';',
|
||||
},
|
||||
{
|
||||
name: 'RemoteError',
|
||||
declaration: 'export class RemoteError<Code extends RemoteErrorCode = RemoteErrorCode> extends HarnessError {\n readonly isDSHRemoteError: true;\n constructor(override readonly code: Code, message: string, readonly details: RemoteErrorDetailsMap[Code], options?: ErrorOptions);\n}',
|
||||
@@ -9383,6 +9422,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [
|
||||
name: 'RemoteEventHostInfo',
|
||||
declaration: 'export interface RemoteEventHostInfo {\n readonly home: string;\n}',
|
||||
},
|
||||
{
|
||||
name: 'RemoteLoginId',
|
||||
declaration: 'export type RemoteLoginId = Branded<\'remote-login-id\'>;',
|
||||
},
|
||||
{
|
||||
name: 'RemoteLoginState',
|
||||
declaration: 'export type RemoteLoginState = \'none\' | \'pending\' | \'used\' | \'expired\' | \'cancelled\' | \'replaced\';',
|
||||
},
|
||||
{
|
||||
name: 'RemoteLoginTicket',
|
||||
declaration: 'export interface RemoteLoginTicket {\n readonly id: RemoteLoginId;\n readonly url: string;\n readonly lifetimeMs: number;\n}',
|
||||
},
|
||||
{
|
||||
name: 'RemoteStream',
|
||||
declaration: 'export type RemoteStream<Out, In = never> = AsyncIterable<Out> & {\n readonly [STREAM_UPLINK]?: In;\n};',
|
||||
|
||||
@@ -72,6 +72,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo
|
||||
| `@deepseek-ai/dsh-client-locale` | no | Locale plugin: Host-backed preference, extensible language catalog, browser fallback, and typed built-in dictionaries |
|
||||
| `@deepseek-ai/dsh-client-modules` | no | Client module system, dual-face: node half composes the __DSH_BOOT__ entry graph (incremental dsh.client scan, bundle route, index tap, webPlugins service); browser half is the lazy-CJS module table the vendored cordis Loader consumes as its internal seam |
|
||||
| `@deepseek-ai/dsh-client-product-analytics` | yes | Desktop product event collection and authenticated Host reporting |
|
||||
| `@deepseek-ai/dsh-client-remote-connection` | yes | Settings panel and single-use QR login for another browser |
|
||||
| `@deepseek-ai/dsh-client-resources` | no | Unified client resource model: protocol-registered providers turn URL addresses into live values, consumed through the useResource global standard hook |
|
||||
| `@deepseek-ai/dsh-client-script-realm` | no | Direct-reference script environments and Cordis-owned provider registration |
|
||||
| `@deepseek-ai/dsh-client-script-realm-iframe` | no | Optional iframe ScriptRealm provider |
|
||||
|
||||
@@ -17,6 +17,8 @@ export const remoteDefaultResponses: RemoteTable = {
|
||||
'workspace/initializeDefault': ok(undefined),
|
||||
// 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 }),
|
||||
// ui-model-selection `ModelDirectoryResolver` constructor.
|
||||
'session/modelCatalog': ok({
|
||||
default: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
|
||||
|
||||
Generated
+100
@@ -3185,6 +3185,9 @@ importers:
|
||||
'@deepseek-ai/dsh-client-product-analytics':
|
||||
specifier: workspace:*
|
||||
version: link:../../client/product-analytics
|
||||
'@deepseek-ai/dsh-client-remote-connection':
|
||||
specifier: workspace:*
|
||||
version: link:../../client/remote-connection
|
||||
'@deepseek-ai/dsh-client-resources':
|
||||
specifier: workspace:*
|
||||
version: link:../../client/resources
|
||||
@@ -3900,6 +3903,91 @@ importers:
|
||||
specifier: workspace:*
|
||||
version: link:../../settings/settings
|
||||
|
||||
packages/client/remote-connection:
|
||||
dependencies:
|
||||
'@deepseek-ai/dsh-brand':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/brand
|
||||
'@deepseek-ai/dsh-typert-protocol':
|
||||
specifier: workspace:*
|
||||
version: link:../../typert/protocol
|
||||
'@deepseek-ai/schemastery':
|
||||
specifier: link:../../../vendor/schemastery
|
||||
version: link:../../../vendor/schemastery
|
||||
zod:
|
||||
specifier: 4.6.6
|
||||
version: 4.6.6
|
||||
devDependencies:
|
||||
'@deepseek-ai/dsh-error':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/error
|
||||
'@deepseek-ai/dsh-credentials':
|
||||
specifier: workspace:*
|
||||
version: link:../../credentials/credentials
|
||||
'@deepseek-ai/cordis':
|
||||
specifier: workspace:~
|
||||
version: link:../../../vendor/cordis
|
||||
'@deepseek-ai/dsh-api-gateway':
|
||||
specifier: workspace:*
|
||||
version: link:../../api/gateway
|
||||
'@deepseek-ai/dsh-api-remotes':
|
||||
specifier: workspace:*
|
||||
version: link:../../api/remotes
|
||||
'@deepseek-ai/dsh-client-connection':
|
||||
specifier: workspace:*
|
||||
version: link:../connection
|
||||
'@deepseek-ai/dsh-client-locale':
|
||||
specifier: workspace:*
|
||||
version: link:../locale
|
||||
'@deepseek-ai/dsh-client-store':
|
||||
specifier: workspace:*
|
||||
version: link:../store
|
||||
'@deepseek-ai/dsh-client-test-runtime':
|
||||
specifier: workspace:*
|
||||
version: link:../../test-support/client-runtime
|
||||
'@deepseek-ai/dsh-client-ui-layout':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-layout
|
||||
'@deepseek-ai/dsh-client-ui-primitives':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-primitives
|
||||
'@deepseek-ai/dsh-client-ui-renderer':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-renderer
|
||||
'@deepseek-ai/dsh-client-ui-settings':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-settings
|
||||
'@deepseek-ai/dsh-client-ui-settings-general':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-settings-general
|
||||
'@deepseek-ai/dsh-client-ui-slots':
|
||||
specifier: workspace:*
|
||||
version: link:../ui-slots
|
||||
'@deepseek-ai/dsh-host-authentication-token':
|
||||
specifier: workspace:*
|
||||
version: link:../../host/authentication-token
|
||||
'@deepseek-ai/dsh-host-frontend-static':
|
||||
specifier: workspace:*
|
||||
version: link:../../host/frontend-static
|
||||
'@deepseek-ai/dsh-host-webserver':
|
||||
specifier: workspace:*
|
||||
version: link:../../host/webserver
|
||||
'@deepseek-ai/dsh-remote-mock':
|
||||
specifier: workspace:*
|
||||
version: link:../../test-support/remote-mock
|
||||
'@deepseek-ai/dsh-typert-registry':
|
||||
specifier: workspace:*
|
||||
version: link:../../typert/registry
|
||||
'@deepseek-ai/dsh-web-app':
|
||||
specifier: workspace:*
|
||||
version: link:../../bundle/web-app
|
||||
qrcode.react:
|
||||
specifier: ^4.2.0
|
||||
version: 4.2.0(react@18.3.1)
|
||||
react:
|
||||
specifier: ^18.2.0
|
||||
version: 18.3.1
|
||||
|
||||
packages/client/resources:
|
||||
devDependencies:
|
||||
'@deepseek-ai/cordis':
|
||||
@@ -21076,6 +21164,13 @@ importers:
|
||||
|
||||
packages:
|
||||
|
||||
qrcode.react@4.2.0:
|
||||
peerDependencies:
|
||||
react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
|
||||
resolution:
|
||||
integrity: sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==
|
||||
|
||||
|
||||
'@agentclientprotocol/sdk@1.4.0':
|
||||
resolution: {integrity: sha512-/eufudw+aFY1LKLolT6yFE6UMmYRl7fMJ/DEONSIyR6wI3slHWITBsANRGqXEY8FRzqUxwh7QEaGiZHcJPVThg==}
|
||||
peerDependencies:
|
||||
@@ -28875,6 +28970,11 @@ packages:
|
||||
|
||||
snapshots:
|
||||
|
||||
qrcode.react@4.2.0(react@18.3.1):
|
||||
dependencies:
|
||||
react: 18.3.1
|
||||
|
||||
|
||||
'@agentclientprotocol/sdk@1.4.0(zod@4.6.6)':
|
||||
dependencies:
|
||||
zod: 4.6.6
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/** Markdown compiler-face routing and invalid-example diagnostics through real TypeScript projects. */
|
||||
import { mkdtempSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { expect, it } from 'vitest'
|
||||
import { compileBlocks, extractBlocks } from './doc-typecheck.ts'
|
||||
import { removeFixtureSafely } from './test-fixture-cleanup.ts'
|
||||
|
||||
it('checks Client examples against their JSX project and rejects invalid props without mixing Host types', () => {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-doc-faces-'))
|
||||
try {
|
||||
for (const face of ['host', 'client'] as const) {
|
||||
const extension = face === 'client' ? 'tsx' : 'ts'
|
||||
mkdirSync(join(root, face))
|
||||
writeFileSync(join(root, face, `index.${extension}`), face === 'client'
|
||||
? 'export interface Props { ready: boolean }\n'
|
||||
: 'export interface Props { count: number }\n')
|
||||
writeFileSync(join(root, face, 'tsconfig.json'), JSON.stringify({
|
||||
compilerOptions: { composite: true, outDir: './lib', types: [], jsx: 'preserve' },
|
||||
include: [`index.${extension}`],
|
||||
}))
|
||||
writeFileSync(join(root, `tsconfig.${face}.json`), JSON.stringify({
|
||||
compilerOptions: {
|
||||
composite: true,
|
||||
noEmit: true,
|
||||
strict: true,
|
||||
types: [],
|
||||
...(face === 'client' ? { jsx: 'preserve' } : {}),
|
||||
paths: { 'fixture-api': [`./${face}/index.${extension}`] },
|
||||
},
|
||||
references: [{ path: `./${face}` }],
|
||||
}))
|
||||
}
|
||||
const file = join(root, 'README.md')
|
||||
const markdown = [
|
||||
'# Example', '',
|
||||
'```ts',
|
||||
"import type { Props } from 'fixture-api'",
|
||||
'export const props: Props = { count: 1 }',
|
||||
'```',
|
||||
'```ts client',
|
||||
"import type { Props } from 'fixture-api'",
|
||||
'export const props: Props = { ready: true }',
|
||||
'```',
|
||||
'',
|
||||
].join('\n')
|
||||
writeFileSync(file, markdown)
|
||||
expect(compileBlocks(extractBlocks(file, root), false, root)).toBeUndefined()
|
||||
writeFileSync(file, markdown.replace('ready: true', "ready: 'wrong'"))
|
||||
expect(compileBlocks(extractBlocks(file, root), false, root))
|
||||
.toContain("README.md (block at line 7, +2:31): error TS2322: Type 'string' is not assignable to type 'boolean'.")
|
||||
expect(readdirSync(root).filter(name => name.startsWith('.doc-typecheck-'))).toEqual([])
|
||||
} finally {
|
||||
removeFixtureSafely(root)
|
||||
}
|
||||
})
|
||||
+107
-75
@@ -2,8 +2,9 @@
|
||||
* Typecheck Markdown `ts` fences against the workspace API. `ignore-check` fences are reported as
|
||||
* opt-outs; generated catalog fragments and source-equivalence blocks are skipped here because their
|
||||
* owning gates verify them. Frozen upgrade guides retain their release-specific examples.
|
||||
* Byte-identical `.zh.md` copies reuse their unsuffixed sibling's check. A
|
||||
* build-coordinated mode consumes existing declarations without emit.
|
||||
* Byte-identical `.zh.md` copies reuse their unsuffixed sibling's check.
|
||||
* Client fences compile separately from Host fences; a build-coordinated mode consumes existing
|
||||
* declarations without emit.
|
||||
*/
|
||||
|
||||
import { execFileSync } from 'node:child_process'
|
||||
@@ -22,7 +23,7 @@ const root = resolve(import.meta.dirname, '..')
|
||||
* counted in the opt-out ratio; the catalog and type-equivalence variants are
|
||||
* excluded from that ratio because their owning gates verify them.
|
||||
*/
|
||||
type BlockKind = 'check' | 'ignore' | 'type-equiv' | 'cordis-catalog' | 'persistence-catalog' | 'config-catalog'
|
||||
type BlockKind = 'check' | 'client' | 'ignore' | 'type-equiv' | 'cordis-catalog' | 'persistence-catalog' | 'config-catalog'
|
||||
|
||||
/** One extracted code block. */
|
||||
interface Block {
|
||||
@@ -36,6 +37,7 @@ interface Block {
|
||||
/** The info-string → kind table this gate tracks. */
|
||||
const KIND_BY_INFO: Record<string, BlockKind> = {
|
||||
'ts': 'check',
|
||||
'ts client': 'client',
|
||||
'ts ignore-check': 'ignore',
|
||||
'ts type-equiv': 'type-equiv',
|
||||
'ts public-api': 'type-equiv',
|
||||
@@ -44,9 +46,14 @@ const KIND_BY_INFO: Record<string, BlockKind> = {
|
||||
'ts config-catalog': 'config-catalog',
|
||||
}
|
||||
|
||||
/** Extract every recognized TypeScript fence from one Markdown file. */
|
||||
function extractBlocks(absPath: string): Block[] {
|
||||
const file = relative(root, absPath)
|
||||
/**
|
||||
* Extract every recognized TypeScript fence from one Markdown file.
|
||||
* @param absPath - Markdown file to parse.
|
||||
* @param repositoryRoot - Root used for diagnostic paths.
|
||||
* @returns Recognized fences with their compiler kind and Markdown location.
|
||||
*/
|
||||
export function extractBlocks(absPath: string, repositoryRoot = root): Block[] {
|
||||
const file = relative(repositoryRoot, absPath)
|
||||
return markdownFences(readFileSync(absPath, 'utf8')).flatMap((fence) => {
|
||||
const kind = KIND_BY_INFO[fence.info]
|
||||
return kind === undefined ? [] : [{ file, line: fence.line, kind, code: fence.code }]
|
||||
@@ -62,19 +69,17 @@ const configHost: ts.ParseConfigFileHost = {
|
||||
}
|
||||
|
||||
/**
|
||||
* Load host-aggregate settings and redirect workspace aliases to declarations
|
||||
* from the coordinated build. Doc fragments speak the host vocabulary; the host
|
||||
* aggregate (never the root solution — it has no compilerOptions) carries the
|
||||
* workspace paths via tsconfig.base.json.
|
||||
* Load the selected compiler face and redirect workspace aliases to declarations
|
||||
* from the coordinated build. Host and Client context augmentations remain in separate programs.
|
||||
*/
|
||||
function builtTypeCompilerOptions(): ts.CompilerOptions {
|
||||
const configPath = join(root, 'tsconfig.host.json')
|
||||
function builtTypeCompilerOptions(face: 'host' | 'client'): ts.CompilerOptions {
|
||||
const configPath = join(root, `tsconfig.${face}.json`)
|
||||
const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, configHost)
|
||||
if (!parsed) throw new Error(`doc-typecheck: cannot parse ${configPath}`)
|
||||
if (parsed.errors.length > 0) {
|
||||
throw new Error(parsed.errors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
|
||||
}
|
||||
if (parsed.options.paths === undefined) throw new Error('doc-typecheck: host tsconfig has no workspace paths')
|
||||
if (parsed.options.paths === undefined) throw new Error('doc-typecheck: selected tsconfig has no workspace paths')
|
||||
const paths = Object.fromEntries(Object.entries(parsed.options.paths).map(([specifier, candidates]) => [
|
||||
specifier,
|
||||
candidates.map(builtDeclarationPath),
|
||||
@@ -96,8 +101,8 @@ function builtTypeCompilerOptions(): ts.CompilerOptions {
|
||||
}
|
||||
|
||||
/** Compile Markdown blocks as virtual files against declarations from the coordinated build. */
|
||||
function compileBlocksAgainstBuiltTypes(blocks: Block[]): readonly ts.Diagnostic[] {
|
||||
const options = builtTypeCompilerOptions()
|
||||
function compileBlocksAgainstBuiltTypes(blocks: Block[], face: 'host' | 'client'): readonly ts.Diagnostic[] {
|
||||
const options = builtTypeCompilerOptions(face)
|
||||
const sources = new Map<string, string>()
|
||||
for (const [index, block] of blocks.entries()) {
|
||||
const fileName = resolve(root, '.doc-typecheck', `block-${index}.ts`)
|
||||
@@ -137,12 +142,11 @@ function formatDiagnostics(diagnostics: readonly ts.Diagnostic[], blocks: Block[
|
||||
}
|
||||
|
||||
/**
|
||||
* Reuse the Host aggregate references from a temp project one directory below
|
||||
* root. Generated Client API examples opt out because their declarations do
|
||||
* not exist until source-only Typert generation has run.
|
||||
* Reuse the selected aggregate's package references from a temp project one directory below root.
|
||||
* Public commands prepare generated Remote declarations before this project compiles.
|
||||
*/
|
||||
function workspaceReferences(): { path: string }[] {
|
||||
const file = join(root, 'tsconfig.host.json')
|
||||
function workspaceReferences(face: 'host' | 'client', repositoryRoot: string): { path: string }[] {
|
||||
const file = join(repositoryRoot, `tsconfig.${face}.json`)
|
||||
// Parse with TypeScript's own JSONC reader: a regex comment stripper corrupts the `/*/` path
|
||||
// candidate in the workspace wildcard.
|
||||
const result = ts.readConfigFile(file, path => readFileSync(path, 'utf8'))
|
||||
@@ -157,31 +161,37 @@ function workspaceReferences(): { path: string }[] {
|
||||
}
|
||||
|
||||
/** The standalone temp project used when no coordinated build owns declaration freshness. */
|
||||
function tempTsconfig(): string {
|
||||
function tempTsconfig(face: 'host' | 'client', repositoryRoot: string): string {
|
||||
return JSON.stringify({
|
||||
extends: '../tsconfig.host.json',
|
||||
extends: `../tsconfig.${face}.json`,
|
||||
compilerOptions: {
|
||||
noUnusedLocals: false,
|
||||
noUnusedParameters: false,
|
||||
tsBuildInfoFile: './tsconfig.tsbuildinfo',
|
||||
},
|
||||
include: ['block-*.ts'],
|
||||
references: workspaceReferences(),
|
||||
references: workspaceReferences(face, repositoryRoot),
|
||||
})
|
||||
}
|
||||
|
||||
/** Compile blocks through project references for the standalone command. */
|
||||
function compileBlocksStandalone(blocks: Block[]): string | undefined {
|
||||
const tmp = mkdtempSync(join(root, '.doc-typecheck-'))
|
||||
/**
|
||||
* Compile blocks through one compiler face's package references without a coordinated build.
|
||||
* @param blocks - Markdown blocks checked together in the selected program.
|
||||
* @param face - Aggregate owning the blocks' Host or Client APIs.
|
||||
* @param repositoryRoot - Repository containing the face-specific aggregate configs.
|
||||
* @returns Remapped compiler diagnostics, or undefined when every block compiles.
|
||||
*/
|
||||
function compileBlocksStandalone(blocks: Block[], face: 'host' | 'client', repositoryRoot = root): string | undefined {
|
||||
const tmp = mkdtempSync(join(repositoryRoot, '.doc-typecheck-'))
|
||||
try {
|
||||
writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig())
|
||||
writeFileSync(join(tmp, 'tsconfig.json'), tempTsconfig(face, repositoryRoot))
|
||||
for (const [index, block] of blocks.entries()) {
|
||||
writeFileSync(join(tmp, `block-${index}.ts`), block.code.endsWith('\n') ? block.code : `${block.code}\n`)
|
||||
}
|
||||
try {
|
||||
// Invoke tsc's JS entry through Node instead of a platform-specific shell shim.
|
||||
execFileSync(process.execPath, ['node_modules/typescript/bin/tsc', '-b', join(tmp, 'tsconfig.json')], {
|
||||
cwd: root,
|
||||
execFileSync(process.execPath, [join(root, 'node_modules/typescript/bin/tsc'), '-b', join(tmp, 'tsconfig.json')], {
|
||||
cwd: repositoryRoot,
|
||||
stdio: 'pipe',
|
||||
})
|
||||
return undefined
|
||||
@@ -203,53 +213,75 @@ function remapBlockPaths(output: string, blocks: Block[]): string {
|
||||
})
|
||||
}
|
||||
|
||||
const markdownGlobs = ['README.md', '.agents/notes/**/*.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
|
||||
/**
|
||||
* Check compilable fences in separate Host and Client programs.
|
||||
* @param blocks - Extracted fences, including independently checked or ignored kinds.
|
||||
* @param useBuiltTypes - Whether a coordinated build already owns declaration freshness.
|
||||
* @param repositoryRoot - Standalone repository root; built mode uses this workspace's declarations.
|
||||
* @returns Remapped compiler diagnostics, or undefined when both programs compile.
|
||||
*/
|
||||
export function compileBlocks(blocks: Block[], useBuiltTypes: boolean, repositoryRoot = root): string | undefined {
|
||||
for (const face of ['host', 'client'] as const) {
|
||||
const selected = blocks.filter(block => block.kind === (face === 'host' ? 'check' : 'client'))
|
||||
if (selected.length === 0) continue
|
||||
const error = useBuiltTypes
|
||||
? (() => {
|
||||
const diagnostics = compileBlocksAgainstBuiltTypes(selected, face)
|
||||
return diagnostics.length === 0 ? undefined : formatDiagnostics(diagnostics, selected)
|
||||
})()
|
||||
: compileBlocksStandalone(selected, face, repositoryRoot)
|
||||
if (error !== undefined) return error
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
const files: string[] = []
|
||||
const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string }
|
||||
for (const pattern of markdownGlobs) {
|
||||
for (const match of globSync(pattern, { cwd: root })) {
|
||||
const file = match.replaceAll('\\', '/')
|
||||
if (!isArchivedAgentNotePath(file) && !isFrozenUpgradeGuidePath(file, version)) files.push(resolve(root, file))
|
||||
/** Check the repository's eligible Markdown fences and report their compilation status. */
|
||||
function main(): void {
|
||||
const markdownGlobs = ['README.md', '.agents/notes/**/*.md', 'docs/**/*.md', 'packages/*/*.md', 'packages/*/*/*.md']
|
||||
|
||||
const { version } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { version: string }
|
||||
const files: string[] = []
|
||||
for (const pattern of markdownGlobs) {
|
||||
for (const match of globSync(pattern, { cwd: root })) {
|
||||
const file = match.replaceAll('\\', '/')
|
||||
if (!isArchivedAgentNotePath(file) && !isFrozenUpgradeGuidePath(file, version)) files.push(resolve(root, file))
|
||||
}
|
||||
}
|
||||
files.sort()
|
||||
|
||||
const extracted = files.flatMap(file => extractBlocks(file))
|
||||
const { primary: all, derivatives } = partitionPairedMarkdownDerivatives(
|
||||
extracted,
|
||||
block => block.file,
|
||||
block => `${block.kind}\0${block.code}`,
|
||||
)
|
||||
const checked = all.filter(b => b.kind === 'check' || b.kind === 'client')
|
||||
const ignored = all.filter(b => b.kind === 'ignore')
|
||||
// Only compile-eligible fences belong in the opt-out ratio; every other skipped
|
||||
// kind has an independent verifier named in the BlockKind rules above.
|
||||
const ratioDenominator = checked.length + ignored.length
|
||||
|
||||
if (checked.length === 0) {
|
||||
console.log('doc-typecheck: no ts code blocks to check.')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const useBuiltTypes = process.env.DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT === '1'
|
||||
const compilationError = compileBlocks(all, useBuiltTypes)
|
||||
if (compilationError !== undefined) {
|
||||
console.error('doc-typecheck: documentation code blocks failed to compile.\n')
|
||||
console.error(compilationError)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const ratio = ignored.length / ratioDenominator
|
||||
const skipped = all.length - ratioDenominator
|
||||
console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out), ${skipped} type-equiv/catalog (checked elsewhere), ${derivatives.length} paired derivative(s).`)
|
||||
// Guard against the escape hatch becoming the norm.
|
||||
if (ratioDenominator >= 4 && ratio > 0.5) {
|
||||
console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
files.sort()
|
||||
|
||||
const extracted = files.flatMap(extractBlocks)
|
||||
const { primary: all, derivatives } = partitionPairedMarkdownDerivatives(
|
||||
extracted,
|
||||
block => block.file,
|
||||
block => `${block.kind}\0${block.code}`,
|
||||
)
|
||||
const checked = all.filter(b => b.kind === 'check')
|
||||
const ignored = all.filter(b => b.kind === 'ignore')
|
||||
// Only compile-eligible fences belong in the opt-out ratio; every other skipped
|
||||
// kind has an independent verifier named in the BlockKind rules above.
|
||||
const ratioDenominator = checked.length + ignored.length
|
||||
|
||||
if (checked.length === 0) {
|
||||
console.log('doc-typecheck: no ts code blocks to check.')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const useBuiltTypes = process.env.DSH_DOC_TYPECHECK_USE_BUILD_OUTPUT === '1'
|
||||
const compilationError = useBuiltTypes
|
||||
? (() => {
|
||||
const diagnostics = compileBlocksAgainstBuiltTypes(checked)
|
||||
return diagnostics.length === 0 ? undefined : formatDiagnostics(diagnostics, checked)
|
||||
})()
|
||||
: compileBlocksStandalone(checked)
|
||||
if (compilationError !== undefined) {
|
||||
console.error('doc-typecheck: documentation code blocks failed to compile.\n')
|
||||
console.error(compilationError)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const ratio = ignored.length / ratioDenominator
|
||||
const skipped = all.length - ratioDenominator
|
||||
console.log(`doc-typecheck: ${checked.length} block(s) compiled, ${ignored.length} ignored (${(ratio * 100).toFixed(0)}% opt-out), ${skipped} type-equiv/catalog (checked elsewhere), ${derivatives.length} paired derivative(s).`)
|
||||
// Guard against the escape hatch becoming the norm.
|
||||
if (ratioDenominator >= 4 && ratio > 0.5) {
|
||||
console.error(`doc-typecheck: too many blocks opt out of checking (${ignored.length}/${ratioDenominator}). Make them compile or delete them.`)
|
||||
process.exit(1)
|
||||
}
|
||||
if (import.meta.main) main()
|
||||
@@ -59,6 +59,7 @@ export const SERVICE_PAGE: Record<string, string> = {
|
||||
productTelemetry: 'product-telemetry.md',
|
||||
productAnalytics: 'product-telemetry.md',
|
||||
connection: 'web-server.md',
|
||||
remoteConnection: 'web-server.md',
|
||||
'connection.authentication': 'web-server.md',
|
||||
pluginManager: 'boot.md',
|
||||
actionCards: 'boot.md',
|
||||
@@ -326,6 +327,10 @@ export const EVENT_WALK_EXEMPTIONS: Record<string, string> = {
|
||||
* appear on more than one page.
|
||||
*/
|
||||
export const LINK_MAP: Readonly<Record<string, string>> = {
|
||||
RemoteConnectionStatus: 'web-server.md',
|
||||
RemoteLoginId: 'web-server.md',
|
||||
RemoteLoginTicket: 'web-server.md',
|
||||
RemoteLoginState: 'web-server.md',
|
||||
AuthenticationProvider: '../../packages/client/connection/README.md#browser-authentication-and-request-trust',
|
||||
PeerId: 'typert.md',
|
||||
Principal: 'typert.md',
|
||||
|
||||
@@ -107,6 +107,13 @@ const GROUP_ORDER = [
|
||||
]
|
||||
|
||||
const SERVICE_ROLES: ServiceRole[] = [
|
||||
{
|
||||
key: 'remoteConnection',
|
||||
pkg: 'client-remote-connection',
|
||||
title: 'Remote browser login',
|
||||
mode: 'service',
|
||||
note: 'Owns one-use QR invitations, Remote browser credentials and the anonymous login document; its Client provides QR login and an independent Token-link shortcut.',
|
||||
},
|
||||
{
|
||||
key: 'actionCards',
|
||||
pkg: 'action-cards',
|
||||
|
||||
@@ -87,6 +87,8 @@ const PEER_REQUIRED_HOST_EXPORTS = {
|
||||
'@deepseek-ai/dsh-user-questions': ['UserQuestionError'],
|
||||
// The tool registry and every subclass rely on `instanceof` against one HarnessError class.
|
||||
'@deepseek-ai/dsh-error': ['HarnessError'],
|
||||
// The Remote plugin uses the injected credential service; its key helper follows that peer.
|
||||
'@deepseek-ai/dsh-credentials': ['credentialKey'],
|
||||
// `instanceof` checks need the translator's own class instance.
|
||||
'@deepseek-ai/dsh-experimental-translator': ['TranslationError'],
|
||||
// Stateless; a safe classification would turn the forge panel's forge and worktree peers into dependencies.
|
||||
|
||||
@@ -147,6 +147,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
|
||||
'packages/client/ui-session': { kind: 'none', reason: 'Browser-side Session adapter; registers nothing model-facing.' },
|
||||
'packages/client/ui-session-status': { kind: 'none', reason: 'Owner reading records and the Client Session status table add no tools, prompts, or Session events.' },
|
||||
'packages/client/connection': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
|
||||
'packages/client/remote-connection': { kind: 'none', reason: 'Browser authentication and settings UI; contributes no model input.' },
|
||||
'packages/client/file-upload': { kind: 'none', reason: 'Browser-side request-body transport; registers nothing model-facing.' },
|
||||
'packages/api/remotes': { kind: 'none', reason: 'The Remote BFF selects business methods and forwarded events; selected services own any model-visible effect.' },
|
||||
'packages/api/remote-access': { kind: 'none', reason: 'Remote access decisions for Client callers; registers nothing model-facing.' },
|
||||
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user