feat(remote-connection): pair browsers through the shared root login page

This commit is contained in:
EricMoin committed 2026-11-19 21:25:58 +08:00
1 parent 971cda8344
commit 5313ad4bfa
71 files changed
+5120 -59

No files matched your search

+563
View File
@@ -0,0 +1,563 @@
/** An anonymous browser enters the shipped application only after settings approval. */
import { fileURLToPath } from 'node:url'
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { chromium, type Locator, type Page } from 'playwright'
import { expect, it, onTestFinished } from 'vitest'
import {
captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode,
} from './scaffold.ts'
import { launchRemoteConnectionFixture } from './remote-connection-fixture.ts'
import { openSettings, ZH_BROWSER_LOCALE } from './support.ts'
const spoofedSourceIp = '198.51.100.42'
const spoofedSourceHeaders = {
forwarded: `for=${spoofedSourceIp}`,
'x-forwarded-for': spoofedSourceIp,
'x-real-ip': spoofedSourceIp,
}
async function expectObservedSource(requests: Locator, authority: string): Promise<void> {
const content = await requests.innerText()
expect(content).toContain('来源 IP')
expect(content).toContain('127.0.0.1')
expect(content).not.toContain(authority)
expect(content).not.toContain(spoofedSourceIp)
}
async function readPairingCodes(page: Page, baseUrl: string): Promise<{ status: number; codes: (string | undefined)[] | undefined }> {
const response = await page.request.post(new URL('api/remoteConnection/pairingRequests', baseUrl).href, {
data: { type: 'client-request', rpcId: 'pairing-list-observation', method: 'remoteConnection/pairingRequests', payload: { args: {} } },
})
try {
const list: unknown = await response.json()
const result: unknown = typeof list === 'object' && list !== null ? Reflect.get(list, 'result') : undefined
const value: unknown = typeof result === 'object' && result !== null ? Reflect.get(result, 'value') : undefined
const rows: unknown = typeof value === 'object' && value !== null ? Reflect.get(value, 'requests') : undefined
const codes = Array.isArray(rows) ? rows.map((row: unknown) => {
const code: unknown = typeof row === 'object' && row !== null ? Reflect.get(row, 'code') : undefined
return typeof code === 'string' ? code : undefined
}) : undefined
return { status: response.status(), codes }
} finally { await response.dispose() }
}
async function decideWithDelayedList(page: Page, requests: Locator, code: string, decision: 'allow' | 'deny'): Promise<string> {
const releaseStaleRead = Promise.withResolvers<undefined>()
const releaseFreshReads = Promise.withResolvers<undefined>()
let readCount = 0
let staleRead: { method: string; request: unknown; response: unknown } | undefined
let staleReadSettled = false
let freshReadStarted = false
const routeErrors: unknown[] = []
await page.route('**/api/remoteConnection/pairingRequests', async (route) => {
const stale = readCount++ === 0
let handlingStarted = false
try {
if (stale) {
const response = await route.fetch()
staleRead = {
method: route.request().method(), request: route.request().postDataJSON(), response: await response.json(),
}
await releaseStaleRead.promise
handlingStarted = true
if (route.request().failure()?.errorText === 'net::ERR_ABORTED') await route.abort('aborted')
else await route.fulfill({ response })
} else {
freshReadStarted = true
await releaseFreshReads.promise
handlingStarted = true
if (route.request().failure()?.errorText === 'net::ERR_ABORTED') await route.abort('aborted')
else await route.continue()
}
} catch (error) {
if (route.request().failure()?.errorText !== 'net::ERR_ABORTED') routeErrors.push(error)
if (!handlingStarted) {
try { await route.abort('failed') } catch (abortError) { routeErrors.push(abortError) }
}
} finally {
if (stale) staleReadSettled = true
}
})
try {
await expect.poll(() => staleRead !== undefined || routeErrors.length > 0, { timeout: 15_000 }).toBe(true)
expect(routeErrors).toEqual([])
expect(staleRead?.method).toBe('POST')
expect(staleRead?.request).toMatchObject({ payload: { args: {} } })
expect(staleRead?.response).toMatchObject({ result: {
ok: true, value: { requests: [{ code: code.replace(' ', '') }] },
} })
await requests.getByRole('button', { name: decision === 'allow' ? '批准' : '拒绝', exact: true }).click()
const notice = page.getByRole('alert').filter({ hasText: decision === 'allow' ? '已批准申请' : '已拒绝申请' })
await notice.waitFor()
expect(await requests.getByText(code, { exact: true }).count()).toBe(0)
const snapshot = (await Promise.all([requests.ariaSnapshot(), notice.ariaSnapshot()])).join('\n')
releaseStaleRead.resolve(undefined)
await expect.poll(() => staleReadSettled, { timeout: 15_000 }).toBe(true)
await expect.poll(() => freshReadStarted, { timeout: 15_000 }).toBe(true)
expect(await requests.getByText(code, { exact: true }).count()).toBe(0)
return snapshot
} finally {
releaseStaleRead.resolve(undefined)
releaseFreshReads.resolve(undefined)
await page.unrouteAll({ behavior: 'wait' })
expect(routeErrors).toEqual([])
}
}
it('lets a paired mobile browser approve another device and keeps denied or cancelled applicants signed out behind a public mount', async () => {
const scaffold = await launchWebScaffold({
publicMount: { prefix: '/tools/dsh/' },
extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const owner = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 1440, height: 1000 } })
await owner.goto(scaffold.authenticatedUrl)
await owner.waitForFunction(() => '__DSH_BOOT__' in window)
expect((await owner.context().cookies()).some(cookie => cookie.name.startsWith('dsh-auth-') && cookie.httpOnly)).toBe(true)
await openSettings(owner, 'zh')
const navigation = owner.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true })
await expect.poll(() => navigation.count()).toBe(1)
await navigation.click()
const approvals = owner.getByRole('region', { name: '远程连接', exact: true })
.getByRole('region', { name: '配对申请', exact: true })
await approvals.waitFor()
const applicant = await browser.newPage({
locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 },
extraHTTPHeaders: spoofedSourceHeaders,
})
const errors: string[] = []
applicant.on('pageerror', error => errors.push(error.message))
const anonymousScript = applicant.waitForResponse(response => response.url() === new URL('pairing/client.js', scaffold.baseUrl).href)
expect((await applicant.goto(scaffold.baseUrl))?.status()).toBe(401)
expect((await anonymousScript).status()).toBe(200)
expect(await applicant.evaluate(() => customElements.get('dsh-device-pairing') !== undefined)).toBe(true)
expect(await applicant.evaluate(() => '__ModuleLoader__' in window)).toBe(false)
await applicant.locator('#auth-pair-request').click()
await applicant.locator('#auth-pair-code').waitFor()
const previousCode = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(previousCode, { exact: true }).waitFor()
const countdown = applicant.locator('#auth-pair-countdown')
const initialCountdown = await countdown.innerText()
expect(initialCountdown).toMatch(/\d+:\d{2}/u)
await expect.poll(() => countdown.innerText()).not.toBe(initialCountdown)
const [replacementResponse] = await Promise.all([
applicant.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request')),
applicant.getByRole('button', { name: '重新申请', exact: true }).click(),
])
await expect.poll(() => applicant.locator('#auth-pair-code').innerText()).not.toBe(previousCode)
await applicant.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
const code = await applicant.locator('#auth-pair-code').innerText()
expect(code).toMatch(/^[A-Z2-9]{4} [A-Z2-9]{4}$/u)
await approvals.getByText(previousCode, { exact: true }).waitFor({ state: 'detached' })
await approvals.getByText(code, { exact: true }).waitFor()
expect(await replacementResponse.request().allHeaders()).toMatchObject(spoofedSourceHeaders)
const ticket: unknown = await replacementResponse.json()
expect(ticket).toMatchObject({ code: code.replace(' ', ''), sourceIp: '127.0.0.1', authority: new URL(scaffold.baseUrl).origin })
await expectObservedSource(approvals, new URL(scaffold.baseUrl).host)
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await applicant.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
const screenshotDirectory = process.env.DSH_PAIRING_SCREENSHOT_DIR
if (screenshotDirectory !== undefined) {
await applicant.emulateMedia({ colorScheme: 'light' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).backgroundColor)).toBe('rgb(250, 250, 250)')
await applicant.screenshot({ path: join(screenshotDirectory, 'auth-request-light.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: 'dark' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).backgroundColor)).toBe('rgb(23, 23, 23)')
await applicant.screenshot({ path: join(screenshotDirectory, 'auth-request-dark.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: null })
}
const mode = webSnapshotMode()
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/request.expected.md', import.meta.url)),
(await captureStableAria(applicant, 'main', scaffold.workspaceCwd, {
replacements: [[code, '{{pairing-code}}'], [new URL(scaffold.baseUrl).host, '{{authority}}']],
})).replace(/\d+:\d{2}/gu, '{{remaining}}'), mode,
)
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/approval.expected.md', import.meta.url)),
(await approvals.ariaSnapshot()).replaceAll(code, '{{pairing-code}}'), mode,
)
const approvedDecision = await decideWithDelayedList(owner, approvals, code, 'allow')
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(scaffold.baseUrl)
expect((await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect((await applicant.reload())?.status()).toBe(200)
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
await openSettings(applicant, 'zh')
await applicant.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true }).click()
const mobileSection = applicant.getByRole('region', { name: '远程连接', exact: true })
const mobileApprovals = mobileSection.getByRole('region', { name: '配对申请', exact: true })
await mobileApprovals.getByText('暂无待审批的申请', { exact: true }).waitFor()
expect(await mobileSection.getByRole('img', { name: '一次性登录二维码', exact: true }).count()).toBe(0)
const third = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
third.on('pageerror', error => errors.push(error.message))
expect((await third.goto(scaffold.baseUrl))?.status()).toBe(401)
await third.getByRole('button', { name: '申请配对', exact: true }).click()
await third.locator('#auth-pair-code').waitFor()
const thirdCode = await third.locator('#auth-pair-code').innerText()
await mobileApprovals.getByText(thirdCode, { exact: true }).waitFor()
await expectObservedSource(mobileApprovals, new URL(scaffold.baseUrl).host)
expect(await third.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await third.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
expect(await third.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
if (screenshotDirectory !== undefined) {
await applicant.emulateMedia({ colorScheme: 'light' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).colorScheme)).toBe('light')
await applicant.screenshot({ path: join(screenshotDirectory, 'pairing-light.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: 'dark' })
await expect.poll(() => applicant.evaluate(() => getComputedStyle(document.documentElement).colorScheme)).toBe('dark')
await applicant.screenshot({ path: join(screenshotDirectory, 'pairing-dark.png'), fullPage: true })
await applicant.emulateMedia({ colorScheme: null })
}
await mobileApprovals.getByRole('button', { name: '批准', exact: true }).click()
await third.waitForFunction(() => '__DSH_BOOT__' in window)
expect(third.url()).toBe(scaffold.baseUrl)
expect((await third.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect((await third.reload())?.status()).toBe(200)
await third.waitForFunction(() => '__DSH_BOOT__' in window)
await mobileApprovals.getByText(thirdCode, { exact: true }).waitFor({ state: 'detached' })
expect(await third.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
expect(errors).toEqual([])
const denied = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
expect((await denied.goto(scaffold.baseUrl))?.status()).toBe(401)
await denied.locator('#auth-pair-request').click()
await denied.locator('#auth-pair-code').waitFor()
const deniedCode = await denied.locator('#auth-pair-code').innerText()
await approvals.getByText(deniedCode, { exact: true }).waitFor()
const deniedDecision = await decideWithDelayedList(owner, approvals, deniedCode, 'deny')
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/decision.expected.md', import.meta.url)),
[approvedDecision, deniedDecision].join('\n'), mode,
)
await denied.locator('#auth-pair-panel[data-state="denied"]').waitFor()
expect(await denied.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await denied.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
await denied.getByRole('button', { name: '重新申请', exact: true }).click()
await denied.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
const cancelledCode = await denied.locator('#auth-pair-code').innerText()
await approvals.getByText(cancelledCode, { exact: true }).waitFor()
await denied.locator('#auth-pair-cancel').click()
await denied.getByRole('button', { name: '申请配对', exact: true }).waitFor()
expect(await denied.locator('#auth-pair-panel').isHidden()).toBe(true)
await approvals.getByText(cancelledCode, { exact: true }).waitFor({ state: 'detached' })
expect((await denied.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect((await denied.reload())?.status()).toBe(401)
for (const decision of ['allow', 'deny'] as const) {
const unconfirmed = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
unconfirmed.on('pageerror', error => errors.push(error.message))
expect((await unconfirmed.goto(scaffold.baseUrl))?.status()).toBe(401)
const creation = unconfirmed.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request') && response.status() === 200)
await unconfirmed.getByRole('button', { name: '申请配对', exact: true }).click()
await unconfirmed.locator('#auth-pair-code').waitFor()
const unconfirmedCode = await unconfirmed.locator('#auth-pair-code').innerText()
const created = await creation
const ticket: unknown = await created.json()
const submitted: unknown = created.request().postDataJSON()
if (typeof ticket !== 'object' || ticket === null || typeof submitted !== 'object' || submitted === null) {
throw new Error('Pairing creation did not exchange credential records')
}
expect(Reflect.get(ticket, 'id') === Reflect.get(submitted, 'id') && Reflect.get(ticket, 'secret') === Reflect.get(submitted, 'secret')).toBe(true)
expect(Reflect.get(ticket, 'code')).toBe(unconfirmedCode.replace(' ', ''))
const observed = await readPairingCodes(owner, scaffold.baseUrl)
expect(observed.status).toBe(200)
expect(observed.codes).toContain(unconfirmedCode.replace(' ', ''))
try { await approvals.getByText(unconfirmedCode, { exact: true }).waitFor() }
catch (error) {
const current = await readPairingCodes(owner, scaffold.baseUrl)
console.info('pairing approval list before dropped decision', { decision, code: unconfirmedCode, ...current, content: await approvals.innerText(), errors })
throw error
}
expect((await unconfirmed.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
const decisionDropped = Promise.withResolvers<undefined>()
const routeErrors: unknown[] = []
let committedResponse: unknown
await owner.route('**/api/remoteConnection/decidePairing', async (route) => {
try {
const response = await route.fetch()
committedResponse = await response.json()
expect(response.status()).toBe(200)
} catch (error) {
routeErrors.push(error)
} finally {
try { await route.abort('failed') } catch (error) { routeErrors.push(error) }
decisionDropped.resolve(undefined)
}
})
try {
await approvals.getByRole('button', { name: decision === 'allow' ? '批准' : '拒绝', exact: true }).click()
await decisionDropped.promise
expect(routeErrors).toEqual([])
expect(committedResponse).toMatchObject({ result: { ok: true, value: decision === 'allow' ? 'approved' : 'denied' } })
await owner.getByRole('alert').filter({ hasText: '无法确认审批结果,请刷新列表后再试' }).waitFor()
expect(await owner.getByRole('alert').filter({ hasText: '已批准申请' }).count()).toBe(0)
expect(await owner.getByRole('alert').filter({ hasText: '已拒绝申请' }).count()).toBe(0)
if (decision === 'allow') {
await unconfirmed.waitForFunction(() => '__DSH_BOOT__' in window)
expect(unconfirmed.url()).toBe(scaffold.baseUrl)
expect((await unconfirmed.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect((await unconfirmed.reload())?.status()).toBe(200)
await unconfirmed.waitForFunction(() => '__DSH_BOOT__' in window)
} else {
await unconfirmed.locator('#auth-pair-panel[data-state="denied"]').waitFor()
expect(await unconfirmed.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await unconfirmed.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect((await unconfirmed.reload())?.status()).toBe(401)
}
await approvals.getByText(unconfirmedCode, { exact: true }).waitFor({ state: 'detached' })
} finally {
await owner.unrouteAll({ behavior: 'wait' })
expect(routeErrors).toEqual([])
}
}
expect(errors).toEqual([])
} finally {
await browser.close()
}
})
it('keeps one Remote connection panel, its QR invitation, and login link while another browser requests approval', async () => {
const fixture = await launchRemoteConnectionFixture(false)
onTestFinished(() => fixture.close())
const browser = await chromium.launch({
proxy: { server: 'http://127.0.0.1:9', bypass: '*' },
args: ['--host-resolver-rules=MAP qr-login.test 127.0.0.1'],
})
try {
const owner = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 1440, height: 1000 } })
await owner.goto(fixture.authenticatedUrl)
await openSettings(owner, 'zh')
const navigation = owner.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true })
await expect.poll(() => navigation.count()).toBe(1)
await navigation.click()
const section = owner.getByRole('region', { name: '远程连接', exact: true })
const loginLink = section.getByRole('region', { name: '链接登录', exact: true }).locator('code')
await expect.poll(() => loginLink.innerText()).toBe(fixture.authenticatedUrl)
const approvals = section.getByRole('region', { name: '配对申请', exact: true })
await approvals.getByText('暂无待审批的申请', { exact: true }).waitFor()
const created = owner.waitForResponse(response => new URL(response.url()).pathname === '/api/remoteConnection/create')
await section.getByRole('button', { name: '生成二维码', exact: true }).click()
const invitation = await (await created).json() as { result: { ok: boolean; value: { url: string } } }
expect(invitation.result.ok).toBe(true)
const qr = section.getByRole('img', { name: '一次性登录二维码', exact: true })
await qr.waitFor()
const qrMarkup = await qr.innerHTML()
const applicant = await browser.newPage({
locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 }, extraHTTPHeaders: spoofedSourceHeaders,
})
expect((await applicant.goto(fixture.url))?.status()).toBe(401)
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
const previousCode = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(previousCode, { exact: true }).waitFor()
const countdown = applicant.locator('#auth-pair-countdown')
const initialCountdown = await countdown.innerText()
await expect.poll(() => countdown.innerText()).not.toBe(initialCountdown)
const [replacementResponse] = await Promise.all([
applicant.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request')),
applicant.getByRole('button', { name: '重新申请', exact: true }).click(),
])
await applicant.locator('#auth-pair-panel[data-state="waiting"]').waitFor()
await expect.poll(() => applicant.locator('#auth-pair-code').innerText()).not.toBe(previousCode)
const code = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(previousCode, { exact: true }).waitFor({ state: 'detached' })
await approvals.getByText(code, { exact: true }).waitFor()
expect(await replacementResponse.request().allHeaders()).toMatchObject(spoofedSourceHeaders)
const ticket: unknown = await replacementResponse.json()
expect(ticket).toMatchObject({ code: code.replace(' ', ''), sourceIp: '127.0.0.1', authority: new URL(fixture.url).origin })
await expectObservedSource(approvals, new URL(fixture.url).host)
expect(await qr.innerHTML()).toBe(qrMarkup)
expect(await section.getByRole('button', { name: '重新生成', exact: true }).isEnabled()).toBe(true)
expect(await section.getByRole('button', { name: '取消', exact: true }).isEnabled()).toBe(true)
expect(await navigation.count()).toBe(1)
expect(await approvals.getByRole('button').allTextContents()).toEqual(['批准', '拒绝'])
for (const width of [1440, 390]) {
await owner.setViewportSize({ width, height: 1000 })
await approvals.scrollIntoViewIfNeeded()
const codeBounds = (await approvals.locator('code').boundingBox())!
const sourceIp = (await approvals.getByText('127.0.0.1', { exact: true }).boundingBox())!
const approve = (await approvals.getByRole('button', { name: '批准', exact: true }).boundingBox())!
const deny = (await approvals.getByRole('button', { name: '拒绝', exact: true }).boundingBox())!
if (width === 1440) {
expect(approve.x).toBeGreaterThan(codeBounds.x + codeBounds.width)
expect(deny.x).toBeGreaterThan(approve.x + approve.width)
expect(approve.y).toBe(deny.y)
const informationCenter = (codeBounds.y + sourceIp.y + sourceIp.height) / 2
expect(Math.abs(informationCenter - approve.y - approve.height / 2)).toBeLessThanOrEqual(1)
} else {
expect(approve.y).toBeGreaterThanOrEqual(sourceIp.y + sourceIp.height)
expect(deny.y).toBeGreaterThanOrEqual(approve.y + approve.height)
expect(approve.x).toBe(deny.x)
expect(approve.width).toBe(deny.width)
}
}
await owner.setViewportSize({ width: 1440, height: 1000 })
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/coexistence.expected.md', import.meta.url)),
(await captureStableAria(owner, 'section[aria-label="远程连接"]', fixture.root, {
replacements: [[fixture.authenticatedUrl, '{{access-address}}?token={{login-token}}'], [fixture.url, '{{access-address}}'], [code, '{{pairing-code}}']],
})).replace(/\d+ 秒后过期/gu, '{{seconds}} 秒后过期'), webSnapshotMode(),
)
await approvals.getByRole('button', { name: '批准', exact: true }).click()
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(fixture.url)
expect((await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
expect(await qr.innerHTML()).toBe(qrMarkup)
expect(await loginLink.innerText()).toBe(fixture.authenticatedUrl)
const scanning = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
const exchanged = scanning.waitForResponse(response => new URL(response.url()).pathname === '/' && new URL(response.url()).searchParams.get('login') === 'qr'
&& response.request().method() === 'POST')
await scanning.goto(invitation.result.value.url)
expect((await exchanged).status()).toBe(204)
await scanning.waitForFunction(() => '__DSH_BOOT__' in window)
expect(scanning.url()).toBe(fixture.url)
expect((await scanning.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)).toBe(true)
await section.getByText('二维码已使用,请在手机上确认是否已登录', { exact: true }).waitFor()
expect(await navigation.count()).toBe(1)
} finally { await browser.close() }
})
it('shows expiry and lets the applicant start a new request without signing in', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-pairing-expiry-'))
onTestFinished(() => rm(root, { recursive: true, force: true }))
const overlay = join(root, 'pairing.yml')
await writeFile(overlay, '- id: remote-connection\n config:\n pairing:\n requestTtlMs: 3000\n pollIntervalMs: 500\n')
const scaffold = await launchWebScaffold({
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const applicant = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
expect((await applicant.goto(scaffold.baseUrl))?.status()).toBe(401)
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
const expiredCode = await applicant.locator('#auth-pair-code').innerText()
await applicant.locator('#auth-pair-panel[data-state="expired"]').waitFor()
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await applicant.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
await applicant.getByRole('button', { name: '重新申请', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
expect(await applicant.locator('#auth-pair-code').innerText()).not.toBe(expiredCode)
await applicant.locator('#auth-pair-cancel').click()
await applicant.getByRole('button', { name: '申请配对', exact: true }).waitFor()
expect(await applicant.locator('#auth-pair-panel').isHidden()).toBe(true)
} finally { await browser.close() }
})
it('keeps Token and pairing usable on the same page after a QR exchange fails', async () => {
const fixture = await launchRemoteConnectionFixture(false)
onTestFinished(() => fixture.close())
const browser = await chromium.launch({
proxy: { server: 'http://127.0.0.1:9', bypass: '*' },
args: ['--host-resolver-rules=MAP qr-login.test 127.0.0.1'],
})
try {
const applicant = await browser.newPage({ locale: ZH_BROWSER_LOCALE, viewport: { width: 390, height: 844 } })
const errors: string[] = []
applicant.on('pageerror', error => errors.push(error.message))
const target = new URL(fixture.url)
target.searchParams.set('login', 'qr')
target.hash = 'a'.repeat(43)
const exchanged = applicant.waitForResponse(response => response.request().method() === 'POST'
&& new URL(response.url()).pathname === '/' && new URL(response.url()).searchParams.get('login') === 'qr')
expect((await applicant.goto(target.href))?.status()).toBe(200)
expect((await exchanged).status()).toBe(410)
const failure = applicant.getByRole('alert').filter({ hasText: '二维码' })
await failure.waitFor()
expect(new URL(applicant.url()).hash).toBe('')
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
const token = applicant.getByLabel('登录令牌或链接', { exact: true })
expect(await token.isEnabled()).toBe(true)
expect(await applicant.locator('#token-submit').isEnabled()).toBe(true)
expect(await applicant.getByRole('button', { name: '申请配对', exact: true }).isEnabled()).toBe(true)
const screenshotDirectory = process.env.DSH_PAIRING_SCREENSHOT_DIR
if (screenshotDirectory !== undefined) await mkdir(screenshotDirectory, { recursive: true })
for (const scene of [
{ name: 'mobile-light', width: 390, height: 844, colorScheme: 'light' },
{ name: 'mobile-dark', width: 390, height: 844, colorScheme: 'dark' },
{ name: 'desktop-light', width: 1440, height: 1000, colorScheme: 'light' },
] as const) {
await applicant.setViewportSize({ width: scene.width, height: scene.height })
await applicant.emulateMedia({ colorScheme: scene.colorScheme })
const layout = await applicant.evaluate(() => {
const form = document.querySelector<HTMLElement>('#token-form')!
const pairing = document.querySelector<HTMLElement>('dsh-device-pairing')!
const notice = document.querySelector<HTMLElement>('#qr-notice')!
const title = document.querySelector<HTMLElement>('#title')!
const formBox = form.getBoundingClientRect()
const pairBox = pairing.getBoundingClientRect()
return {
sameContainer: form.parentElement === pairing.parentElement,
feedbackOutside: notice.parentElement === form.parentElement?.parentElement,
headingAbove: title.getBoundingClientRect().bottom <= notice.getBoundingClientRect().top,
feedbackAbove: notice.getBoundingClientRect().bottom <= formBox.top,
gap: pairBox.top - formBox.bottom,
xDifference: pairBox.x - formBox.x,
widthDifference: pairBox.width - formBox.width,
borders: [form, pairing].map(card => Number.parseFloat(getComputedStyle(card).borderTopWidth)),
parentBorder: Number.parseFloat(getComputedStyle(form.parentElement!).borderTopWidth),
overflows: document.documentElement.scrollWidth > innerWidth,
}
})
expect(layout).toMatchObject({
sameContainer: true, feedbackOutside: true, headingAbove: true, feedbackAbove: true, overflows: false,
})
expect(Math.abs(layout.gap - 24)).toBeLessThanOrEqual(1)
expect(Math.abs(layout.xDifference)).toBeLessThanOrEqual(1)
expect(Math.abs(layout.widthDifference)).toBeLessThanOrEqual(1)
expect(layout.borders.every(border => border > 0)).toBe(true)
expect(layout.parentBorder).toBe(0)
if (screenshotDirectory !== undefined) {
await applicant.screenshot({
path: join(screenshotDirectory, `qr-rejected-options-${scene.name}.png`), fullPage: true,
})
}
}
await applicant.setViewportSize({ width: 390, height: 844 })
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
await applicant.locator('#auth-pair-code').waitFor()
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
if (screenshotDirectory !== undefined) {
for (const colorScheme of ['light', 'dark'] as const) {
await applicant.emulateMedia({ colorScheme })
await applicant.screenshot({
path: join(screenshotDirectory, `pairing-waiting-mobile-${colorScheme}.png`), fullPage: true,
})
}
}
expect(await token.isEnabled()).toBe(true)
const launchToken = new URL(fixture.authenticatedUrl).searchParams.get('token')
if (launchToken === null) throw new Error('Token entry did not publish a startup credential')
await token.fill(launchToken)
await applicant.locator('#token-submit').click()
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(fixture.url)
expect((await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-auth-') && cookie.httpOnly)).toBe(true)
expect(errors).toEqual([])
} finally {
await browser.close()
}
})
@@ -0,0 +1,10 @@
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- note:
- paragraph: 批准后,该浏览器将获得此应用的完整访问权限,也可以批准其他设备
- text: 配对码
- code: {{pairing-code}}
- paragraph: 来源 IP 127.0.0.1
- button "批准"
- button "拒绝"
@@ -0,0 +1,28 @@
- 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 "复制链接"
- region "配对申请":
- heading "配对申请" [level=3]
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- note:
- paragraph: 批准后,该浏览器将获得此应用的完整访问权限,也可以批准其他设备
- text: 配对码
- code: {{pairing-code}}
- paragraph: 来源 IP 127.0.0.1
- button "批准"
- button "拒绝"
@@ -0,0 +1,14 @@
- main:
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 登录以继续
- text: 登录令牌或链接
- textbox "登录令牌或链接"
- paragraph: 登录令牌位于此 Host 启动时输出的 URL 中
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- code: {{pairing-code}}
- button "重新申请" [disabled]
- status: 正在确认登录状态…
@@ -0,0 +1,10 @@
- region "配对申请":
- heading "配对申请" [level=3]
- status: 暂无待审批的申请
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 已批准申请
- region "配对申请":
- heading "配对申请" [level=3]
- status: 暂无待审批的申请
- paragraph: 在另一台设备上打开此应用并申请配对,核对两端配对码后再批准
- alert: 已拒绝申请
@@ -0,0 +1,14 @@
- main:
- region "Connect to this Host":
- heading "Connect to this Host" [level=1]
- paragraph: Sign in to continue.
- text: Login token or link
- textbox "Login token or link"
- paragraph: Find the token in the URL printed when this Host started.
- button "Continue"
- region "Pair this device":
- heading "Pair this device" [level=2]
- paragraph: After requesting, open Settings → Remote connection on another signed-in device. Match the pairing code and approve to sign in here automatically.
- code: {{pairing-code}}
- button "Request again"
- alert: Could not complete pairing. Check your connection, then request again.
@@ -0,0 +1,14 @@
- main:
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 登录以继续
- text: 登录令牌或链接
- textbox "登录令牌或链接"
- paragraph: 登录令牌位于此 Host 启动时输出的 URL 中
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- code: {{pairing-code}}
- button "重新申请"
- alert: 无法完成配对,请检查网络后重新申请
@@ -0,0 +1,16 @@
- main:
- region "连接到此 Host":
- heading "连接到此 Host" [level=1]
- paragraph: 登录以继续
- text: 登录令牌或链接
- textbox "登录令牌或链接"
- paragraph: 登录令牌位于此 Host 启动时输出的 URL 中
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- code: {{pairing-code}}
- button "重新申请"
- button "取消申请"
- status: 正在等待批准…
- timer: 剩余时间:{{remaining}}
@@ -7,3 +7,7 @@
- /placeholder: {{application-url}}?token=xxx
- paragraph: 在已登录设备的「设置 → 远程连接」中复制链接,粘贴到此处
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- button "申请配对"
@@ -8,3 +8,7 @@
- text: {{invalid-token}}
- alert: 此登录令牌无效或已过期,请粘贴新的令牌后重试
- button "继续"
- region "配对此设备":
- heading "配对此设备" [level=2]
- paragraph: 申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。
- button "申请配对"
+103
View File
@@ -0,0 +1,103 @@
/** A delayed pairing result cannot undo the browser session already delivered by HTTP. */
import { fileURLToPath } from 'node:url'
import { chromium } from 'playwright'
import { expect, it, onTestFinished } from 'vitest'
import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode } from './scaffold.ts'
import { openSettings, ZH_BROWSER_LOCALE } from './support.ts'
it('recognizes a delivered browser session when the pairing result crosses the local deadline', async () => {
const scaffold = await launchWebScaffold({
publicMount: { prefix: '/tools/dsh/' },
extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const owner = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
await owner.goto(scaffold.authenticatedUrl)
await owner.waitForFunction(() => '__DSH_BOOT__' in window)
await openSettings(owner, 'zh')
await owner.getByRole('dialog', { name: '设置', exact: true })
.getByRole('button', { name: '远程连接', exact: true }).click()
const approvals = owner.getByRole('region', { name: '远程连接', exact: true })
.getByRole('region', { name: '配对申请', exact: true })
await approvals.waitFor()
const applicant = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
const errors: string[] = []
let creations = 0
applicant.on('pageerror', error => errors.push(error.message))
applicant.on('request', (request) => {
if (new URL(request.url()).pathname.endsWith('/pairing/request')) creations++
})
await applicant.clock.install()
await applicant.addInitScript(() => {
const nativeFetch = globalThis.fetch.bind(globalThis)
const release = new Promise<void>((resolve) => {
globalThis.addEventListener('release-pairing-completion', () => { resolve() }, { once: true })
})
const releaseCheck = new Promise<void>((resolve) => {
globalThis.addEventListener('release-session-check', () => { resolve() }, { once: true })
})
globalThis.fetch = async (...args) => {
const response = await nativeFetch(...args)
if (args[1]?.method === 'HEAD' && response.url === new URL('.', document.baseURI).href) {
document.documentElement.dataset.sessionCheckStatus = String(response.status)
await releaseCheck
}
if (!new URL(response.url).pathname.endsWith('/pairing/status')) return response
const nativeJson = response.json.bind(response)
response.json = async () => {
const value: unknown = await nativeJson()
if (typeof value === 'object' && value !== null && Reflect.get(value, 'status') === 'completed') {
document.documentElement.dataset.completionHeld = 'true'
await release
document.documentElement.dataset.completionReleased = 'true'
}
return value
}
return response
}
})
expect((await applicant.goto(scaffold.baseUrl))?.status()).toBe(401)
const created = applicant.waitForResponse(response => new URL(response.url()).pathname.endsWith('/pairing/request'))
await applicant.getByRole('button', { name: '申请配对', exact: true }).click()
const ticket = await (await created).json() as { expiresInMs: number }
await applicant.locator('#auth-pair-code').waitFor()
const code = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(code, { exact: true }).waitFor()
await approvals.getByRole('button', { name: '批准', exact: true }).click()
await expect.poll(() => applicant.evaluate(() => document.documentElement.dataset.completionHeld), { timeout: 15_000 }).toBe('true')
const delivered = (await applicant.context().cookies()).some(cookie => cookie.name.startsWith('dsh-remote-') && cookie.httpOnly)
const protectedResponse = await applicant.request.get(scaffold.baseUrl)
const protectedStatus = protectedResponse.status()
await protectedResponse.dispose()
expect(delivered).toBe(true)
expect(protectedStatus).toBe(200)
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
await applicant.clock.fastForward(ticket.expiresInMs)
await expect.poll(() => applicant.evaluate(() => document.documentElement.dataset.sessionCheckStatus)).toBe('200')
await applicant.locator('#auth-pair-panel[data-state="checking"]').waitFor()
await compareOrRefreshGolden(
fileURLToPath(new URL('./expected/device-pairing/completion-checking.expected.md', import.meta.url)),
await captureStableAria(applicant, 'main', scaffold.workspaceCwd, {
replacements: [[code, '{{pairing-code}}']],
}), webSnapshotMode(),
)
await applicant.evaluate(() => { globalThis.dispatchEvent(new Event('release-pairing-completion')) })
await expect.poll(() => applicant.evaluate(() => document.documentElement.dataset.completionReleased)).toBe('true')
expect(await applicant.locator('#auth-pair-panel').getAttribute('data-state')).toBe('checking')
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect(creations).toBe(1)
await applicant.evaluate(() => { globalThis.dispatchEvent(new Event('release-session-check')) })
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(applicant.url()).toBe(scaffold.baseUrl)
expect(creations).toBe(1)
expect(errors).toEqual([])
} finally {
await browser.close()
}
})
+102
View File
@@ -0,0 +1,102 @@
/** Real anonymous pages recover transport failures and replace requests without inheriting old approval. */
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium } from 'playwright'
import { expect, it, onTestFinished } from 'vitest'
import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, webSnapshotMode } from './scaffold.ts'
import { openSettings, ZH_BROWSER_LOCALE } from './support.ts'
it.each(['zh', 'en'])('recovers and replaces a request from the same browser and IP after repeated failures in %s', async (language) => {
const root = await mkdtemp(join(tmpdir(), 'dsh-pairing-recovery-'))
onTestFinished(() => rm(root, { recursive: true, force: true }))
const overlay = join(root, 'pairing.yml')
await writeFile(overlay, '- id: remote-connection\n config:\n pairing:\n requestIntervalMs: 1\n pollIntervalMs: 100\n requestTimeoutMs: 1000\n maxRetries: 2\n retryMaxDelayMs: 400\n')
const scaffold = await launchWebScaffold({
publicMount: { prefix: '/tools/dsh/' },
extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay],
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
try {
const owner = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
await owner.goto(scaffold.authenticatedUrl)
await owner.waitForFunction(() => '__DSH_BOOT__' in window)
await openSettings(owner, 'zh')
await owner.getByRole('dialog', { name: '设置', exact: true }).getByRole('button', { name: '远程连接', exact: true }).click()
const approvals = owner.getByRole('region', { name: '配对申请', exact: true })
const applicant = await browser.newPage({ locale: language === 'zh' ? ZH_BROWSER_LOCALE : 'en-US', viewport: { width: 390, height: 844 } })
const errors: string[] = []
applicant.on('pageerror', error => errors.push(error.message))
const oldRead = Promise.withResolvers<undefined>()
const releaseOldRead = Promise.withResolvers<undefined>()
const oldReadSettled = Promise.withResolvers<undefined>()
let held = false
await applicant.route('**/pairing/status', async (route) => {
if (held) { await route.continue(); return }
held = true
const response = await route.fetch()
oldRead.resolve(undefined)
try {
await releaseOldRead.promise
if (route.request().failure()?.errorText === 'net::ERR_ABORTED') await route.abort('aborted')
else await route.fulfill({ response })
} finally { oldReadSettled.resolve(undefined) }
})
try {
expect((await applicant.goto(scaffold.baseUrl))?.status()).toBe(401)
await applicant.locator('#auth-pair-request').click()
await applicant.locator('#auth-pair-code').waitFor()
const original = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(original, { exact: true }).waitFor()
await oldRead.promise
await applicant.locator('#auth-pair-request').click()
await expect.poll(() => applicant.locator('#auth-pair-code').innerText()).not.toBe(original)
const replacement = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(replacement, { exact: true }).waitFor()
await expect.poll(() => approvals.getByText(original, { exact: true }).count()).toBe(0)
releaseOldRead.resolve(undefined)
await oldReadSettled.promise
await applicant.unrouteAll({ behavior: 'wait' })
expect(await applicant.evaluate(() => '__DSH_BOOT__' in window)).toBe(false)
expect((await applicant.context().cookies()).filter(cookie => /^dsh-(?:auth|remote)-/u.test(cookie.name))).toEqual([])
expect(await approvals.innerText()).toContain('127.0.0.1')
await applicant.context().setOffline(true)
await applicant.locator('#auth-pair-panel[data-state="error"]').waitFor()
expect(await applicant.locator('#auth-pair-retry').count()).toBe(0)
expect(await applicant.locator('#auth-pair-request').isEnabled()).toBe(true)
await compareOrRefreshGolden(
fileURLToPath(new URL(`./expected/device-pairing/recovery-error.${language}.expected.md`, import.meta.url)),
await captureStableAria(applicant, 'main', scaffold.workspaceCwd, { replacements: [[replacement, '{{pairing-code}}']] }),
webSnapshotMode(),
)
const screenshots = process.env.DSH_PAIRING_SCREENSHOT_DIR
if (screenshots !== undefined) {
await mkdir(screenshots, { recursive: true })
for (const theme of ['light', 'dark'] as const) {
await applicant.emulateMedia({ colorScheme: theme })
await applicant.screenshot({ path: join(screenshots, `recovery-${language}-${theme}.png`), fullPage: true })
}
}
expect(await applicant.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true)
await applicant.context().setOffline(false)
await applicant.locator('#auth-pair-request').click()
await expect.poll(() => applicant.locator('#auth-pair-code').innerText()).not.toBe(replacement)
const fresh = await applicant.locator('#auth-pair-code').innerText()
await approvals.getByText(fresh, { exact: true }).waitFor()
await expect.poll(() => approvals.getByText(replacement, { exact: true }).count()).toBe(0)
const approved = owner.waitForResponse(response => new URL(response.url()).pathname.endsWith('/remoteConnection/decidePairing'))
await approvals.getByRole('button', { name: '批准', exact: true }).click()
await approved
await applicant.waitForFunction(() => '__DSH_BOOT__' in window)
expect(errors).toEqual([])
} finally {
releaseOldRead.resolve(undefined)
await applicant.unrouteAll({ behavior: 'wait' })
}
} finally {
await browser.close()
}
})
+44
View File
@@ -868,6 +868,16 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise<void>
expect(remoteStatus).toEqual({
url: 'http://127.0.0.1:3080', availability: 'unreachable-host', ticket: 'none', pollIntervalMs: 1000,
})
const pairingScript = await page.evaluate(async () => {
const transport = (globalThis as typeof globalThis & {
__DSH_TRANSPORT__?: { fetch(input: string, init: RequestInit): Promise<Response> }
}).__DSH_TRANSPORT__
if (transport === undefined) throw new Error('empty preview transport is absent after boot')
const response = await transport.fetch('/pairing/client.js', { method: 'GET' })
if (!response.ok) throw new Error(`preview pairing script returned ${String(response.status)}`)
return response.text()
})
await exercisePairingScript(browser, origin, pairingScript)
expect(pageErrors.map(error => error.message)).toEqual([])
// One accepted static-host 404: the open-in-app availability read has no
// host routes — the controller publishes an empty list and the header
@@ -886,3 +896,37 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise<void>
await page.close()
}
}
/**
* Execute the script generated inside the packed Worker in an independent browser document.
* Its pairing responses are page-local fixtures; no Worker globals or Client loader reach the document.
* @param browser - browser running the preview acceptance.
* @param origin - unique static fixture origin.
* @param script - JavaScript returned by the packed plugin's public route.
*/
async function exercisePairingScript(browser: Browser, origin: string, script: string): Promise<void> {
const page = await newEnglishPage(browser)
const errors: Error[] = []
page.on('pageerror', (error) => { errors.push(error) })
try {
await page.route(`${origin}/pairing-script-check`, route => route.fulfill({
contentType: 'text/html', body: '<!doctype html><html><body><dsh-device-pairing></dsh-device-pairing></body></html>',
}))
await page.route(`${origin}/pairing/request`, route => route.fulfill({ json: {
...(route.request().postDataJSON() as { id: string; secret: string }), code: 'ABCD2345',
authority: origin, sourceIp: null, expiresInMs: 30000, pollIntervalMs: 1000,
} }))
await page.route(`${origin}/pairing/status`, route => route.fulfill({ json: { status: 'pending' } }))
await page.route(`${origin}/pairing/cancel`, route => route.fulfill({ json: { status: 'cancelled' } }))
await page.goto(`${origin}/pairing-script-check`)
await page.addScriptTag({ content: script })
expect(await page.evaluate(() => '__ModuleLoader__' in window)).toBe(false)
await page.locator('#auth-pair-request').click()
await expect.poll(() => page.locator('#auth-pair-code').textContent()).toBe('ABCD 2345')
await page.locator('#auth-pair-cancel').click()
await expect.poll(() => page.locator('#auth-pair-panel').getAttribute('data-state')).toBe('cancelled')
expect(errors.map(error => error.message)).toEqual([])
} finally {
await page.close()
}
}
@@ -51,6 +51,7 @@ export async function launchRemoteConnectionFixture(secure: boolean, ticketLifet
'- id: web-runtime',
' inject: [webStartup, webServer]',
' config:',
' openBrowser: false',
" publicUrl: !!js ctx.webServer.getOrigin().replace('127.0.0.1', 'qr-login.test')",
'- id: workspace-controller',
' config:',
+1
View File
@@ -1247,6 +1247,7 @@ describe('web e2e: one-use QR browser login', () => {
expect(await custom.getByRole('status', { name: '邀请编号' }).textContent()).toBe(invitationId)
scaffold.ctx.loader.remove(replacement)
await svg.waitFor()
await section.getByRole('region', { name: '配对申请', exact: true }).waitFor()
expect(await nav.count()).toBe(1)
expect(await custom.count()).toBe(0)
expect(await svg.innerHTML()).toBe(initialSvg)
+3
View File
@@ -23,6 +23,9 @@
// this client-registered project must not also hold them (one program
// cannot see both sides of the cordis Context merges).
"exclude": [
"tests/device-pairing.e2e.ts",
"tests/pairing-completion.e2e.ts",
"tests/pairing-recovery.e2e.ts",
"tests/remote-connection.e2e.ts",
"tests/remote-connection-fixture.ts",
"tests/home-whale.e2e.ts",
+18 -1
View File
@@ -592,7 +592,7 @@ export interface Config {
- `source`: [`packages/client/remote-connection/src/index.ts:28`](../packages/client/remote-connection/src/index.ts)
```ts config-catalog
/** Deployment timing for QR login and its settings status. */
/** Deployment timing and limits for remote browser login. */
export interface Config {
/** Absolute lifetime in days for Remote browser credentials; default 30. */
cookieMaxAgeDays: number
@@ -600,6 +600,23 @@ export interface Config {
ticketLifetimeMs: number
/** Interval in milliseconds between the settings panel's status reads. */
pollIntervalMs: number
/** Limits for anonymous requests and approval delivery. */
pairing: {
/** Lifetime in milliseconds, including retries of approved delivery. Default: 300000. */
requestTtlMs: number
/** Maximum retained requests, including terminal requests until expiry. Default: 32. */
maxRequests: number
/** Minimum interval between anonymous creations across this process. Default: 1000. */
requestIntervalMs: number
/** Minimum applicant polling interval and periodic approval-list refresh interval. Default: 2000. */
pollIntervalMs: number
/** Complete anonymous HTTP request timeout in milliseconds. Default: 10000. */
requestTimeoutMs: number
/** Additional attempts after network, timeout, rate-limit, or server failures. Default: 3. */
maxRetries: number
/** Maximum exponential retry delay in milliseconds; at least pollIntervalMs. Default: 10000. */
retryMaxDelayMs: number
}
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-remote-connection -->
+18 -1
View File
@@ -594,7 +594,7 @@ export interface Config {
- `source`: [`packages/client/remote-connection/src/index.ts:28`](../packages/client/remote-connection/src/index.ts)
```ts config-catalog
/** Deployment timing for QR login and its settings status. */
/** Deployment timing and limits for remote browser login. */
export interface Config {
/** Absolute lifetime in days for Remote browser credentials; default 30. */
cookieMaxAgeDays: number
@@ -602,6 +602,23 @@ export interface Config {
ticketLifetimeMs: number
/** Interval in milliseconds between the settings panel's status reads. */
pollIntervalMs: number
/** Limits for anonymous requests and approval delivery. */
pairing: {
/** Lifetime in milliseconds, including retries of approved delivery. Default: 300000. */
requestTtlMs: number
/** Maximum retained requests, including terminal requests until expiry. Default: 32. */
maxRequests: number
/** Minimum interval between anonymous creations across this process. Default: 1000. */
requestIntervalMs: number
/** Minimum applicant polling interval and periodic approval-list refresh interval. Default: 2000. */
pollIntervalMs: number
/** Complete anonymous HTTP request timeout in milliseconds. Default: 10000. */
requestTimeoutMs: number
/** Additional attempts after network, timeout, rate-limit, or server failures. Default: 3. */
maxRetries: number
/** Maximum exponential retry delay in milliseconds; at least pollIntervalMs. Default: 10000. */
retryMaxDelayMs: number
}
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-client-remote-connection -->
+17 -1
View File
@@ -192,7 +192,7 @@ Source: [`packages/client/connection/src/authentication.ts`](../../packages/clie
### `ctx.remoteConnection` — `RemoteConnection`
One outstanding invitation, issued by an owner and consumed by a new browser.
Owner-authorized browser login through QR codes, private links, or pairing requests.
```ts cordis-catalog
/**
@@ -220,6 +220,22 @@ One outstanding invitation, issued by an owner and consumed by a new browser.
* @returns the invitation's final state, including used when a redemption won the race.
*/
@Remote cancel(id: RemoteLoginId): RemoteLoginState
/**
* Read pending requests without the credentials used to collect their sessions.
* @param signal - current Remote call's cancellation.
* @returns pending codes and the deployment's refresh interval.
*/
@Remote pairingRequests(signal: AbortSignal): PairingRequestsValue
/**
* Approve or deny one displayed code; the first decision is retained across retries.
* @param id - request selected after comparing its code with the applicant's screen.
* @param decision - allow or deny full owner access for the requesting browser.
* @param signal - current Remote call's cancellation before the decision commits.
* @returns committed decision, or unavailable after cancellation, expiry, or collection.
*/
@Remote decidePairing(id: PairingRequestId, decision: PairingDecision, signal: AbortSignal): PairingDecisionResult
```
Source: [`packages/client/remote-connection/src/index.ts`](../../packages/client/remote-connection/src/index.ts)
+17 -1
View File
@@ -192,7 +192,7 @@ Source: [`packages/client/connection/src/authentication.ts`](../../packages/clie
### `ctx.remoteConnection` — `RemoteConnection`
One outstanding invitation, issued by an owner and consumed by a new browser.
Owner-authorized browser login through QR codes, private links, or pairing requests.
```ts cordis-catalog
/**
@@ -220,6 +220,22 @@ One outstanding invitation, issued by an owner and consumed by a new browser.
* @returns the invitation's final state, including used when a redemption won the race.
*/
@Remote cancel(id: RemoteLoginId): RemoteLoginState
/**
* Read pending requests without the credentials used to collect their sessions.
* @param signal - current Remote call's cancellation.
* @returns pending codes and the deployment's refresh interval.
*/
@Remote pairingRequests(signal: AbortSignal): PairingRequestsValue
/**
* Approve or deny one displayed code; the first decision is retained across retries.
* @param id - request selected after comparing its code with the applicant's screen.
* @param decision - allow or deny full owner access for the requesting browser.
* @param signal - current Remote call's cancellation before the decision commits.
* @returns committed decision, or unavailable after cancellation, expiry, or collection.
*/
@Remote decidePairing(id: PairingRequestId, decision: PairingDecision, signal: AbortSignal): PairingDecisionResult
```
Source: [`packages/client/remote-connection/src/index.ts`](../../packages/client/remote-connection/src/index.ts)
@@ -3,8 +3,8 @@
# 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
en: da9b40b15dbf1306
zh: 67fcfed98a961f88
/deepseek-ai-dsh-client-remote-connection:
en: 9bbd5b81d7f513ef
zh: ba7d27a7b0f22dc9
+2 -2
View File
@@ -1,5 +1,5 @@
---
description: "Remote login through a single-use QR code or a private tokenized link."
description: "QR login, private login links, and owner-approved browser pairing."
kind: "package-reference"
---
@@ -25,7 +25,7 @@ Settings shows shared sign-in guidance, then access-address and QR login cards.
The Web bundle mounts this plugin. Its Host half requires `connection`, `connection.authentication`, `credentials`, `webServer`, and `webApp`; its Client half contributes the panel through `settings.section`. Removing the plugin removes its page, endpoints, outstanding invitation, and Remote Peer. Already-issued Remote cookies require this provider to be active; valid cookies can be used again after the plugin reloads with the same credential record. The settings panel supports all eight shipped UI languages; the anonymous login page supports English and Chinese. Both cards enclose their titles. The section heading and introductory text match the Models settings typography and spacing. QR actions share the title row on wide cards and stack at full width below the title on narrow cards. The panel uses standard small buttons. The URL field matches the copy button’s 28px height and centers the address text vertically. On narrow cards, the copy button spans the card’s content width below the URL field. The copy button keeps its label and disables only during a clipboard write. The expiry banner sits below the QR header and spans the card's content width. The countdown is centered below the QR code, with an additional 16px bottom margin before the credential warning. Regenerating a visible code replaces only the QR image with a spinner; the countdown, warning, and link controls stay in place. Cancelling closes the preview and restores **Create QR code** without a success message.
The 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.
QR login uses the advertised application URL, which supports HTTP and HTTPS, must name a non-loopback address reachable by the phone, and must pass Connection's trusted-host checks. Configure the listener, optional certificate or reverse proxy, `publicUrl`, and trusted hosts through the existing [Web application](../../bundle/web-app/README.md) configuration. This plugin never changes the listening interface or discovers a network address. A reverse proxy must preserve the external Host, remove its configured path prefix, and protect its upstream connection. A plain HTTP listener issuing a cookie for an HTTP public URL omits `Secure`; HTTPS listeners and HTTPS public URLs behind a TLS-terminating proxy retain `Secure`. An HTTPS proxy must enforce HTTPS for its public origin. The settings panel allows HTTP login and reminds the user that HTTP transmits login credentials without encryption.
The panel shows unmet address prerequisites in a shared notice above the cards. An unreachable or untrusted address keeps a copyable clean URL in the address card and hides QR login without showing a credential warning. Deployment-read failures remain retryable in the address card while QR login is unavailable. Reconnecting checks the address prerequisites again.
@@ -1,5 +1,5 @@
---
description: "通过一次性二维码或带私密 token 的链接远程登录。"
description: "二维码登录、私密登录链接和 owner 审批的浏览器配对。"
kind: "package-reference"
---
@@ -26,7 +26,7 @@ kind: "package-reference"
Web bundle 挂载此插件。Host 端依赖 `connection`、`connection.authentication`、`credentials`、`webServer` 和 `webApp`,Client 端通过 `settings.section` 提供面板。移除插件会移除页面、端点、待使用的邀请和 Remote Peer。已签发的 Remote cookie 需要该提供者处于活动状态;插件使用同一凭据记录重新加载后,有效 cookie 可以继续使用。设置面板支持产品提供的全部八种界面语言;匿名登录页支持英文和中文。两张卡片的标题均位于边框内。页面标题和说明文字采用与模型设置页一致的字体和间距。宽卡片中的二维码操作与标题同行,窄卡片中则在标题下方纵向排列并占满宽度。面板使用标准小号按钮。链接框与复制按钮同为 28px 高,地址文字垂直居中。窄卡片中的复制按钮位于链接框下方,占满卡片内容宽度。复制按钮保持固定文案,仅在写入剪贴板时禁用。过期 banner 位于二维码卡片标题栏下方,占满卡片内容宽度。倒计时居中位于二维码下方,并在凭据告警上方增加 16px 下边距。重新生成正在显示的二维码时,仅用加载状态替换二维码图像;倒计时、告警和链接操作保持原位。取消后直接收起二维码预览,按钮恢复为**生成二维码**,不显示成功提示。
公布的应用 URL 支持 HTTP 和 HTTPS,必须指向手机可访问的非回环地址,并通过 Connection 的可信 Host 检查。通过现有 [Web 应用](../../bundle/web-app/README.zh.md) 配置设置监听器、可选证书或反向代理、`publicUrl` 和可信 Host。此插件不会更改监听接口或发现网络地址。反向代理必须保留外部 Host、移除配置的路径前缀,并保护上游连接。普通 HTTP 监听器为 HTTP 公布地址签发的 cookie 不带 `Secure`;HTTPS 监听器以及终止 TLS 的代理后的 HTTPS 公布地址仍使用 `Secure`。HTTPS 代理必须对外部源强制使用 HTTPS。设置面板允许 HTTP 登录,并提醒用户 HTTP 会明文传输登录凭据。
二维码登录使用公布的应用 URL,该地址支持 HTTP 和 HTTPS,必须指向手机可访问的非回环地址,并通过 Connection 的可信 Host 检查。通过现有 [Web 应用](../../bundle/web-app/README.zh.md) 配置设置监听器、可选证书或反向代理、`publicUrl` 和可信 Host。此插件不会更改监听接口或发现网络地址。反向代理必须保留外部 Host、移除配置的路径前缀,并保护上游连接。普通 HTTP 监听器为 HTTP 公布地址签发的 cookie 不带 `Secure`;HTTPS 监听器以及终止 TLS 的代理后的 HTTPS 公布地址仍使用 `Secure`。HTTPS 代理必须对外部源强制使用 HTTPS。设置面板允许 HTTP 登录,并提醒用户 HTTP 会明文传输登录凭据。
面板在卡片上方以共用提示说明尚未满足的地址前提。地址不可达或不受信任时,访问地址卡片保留可复制的干净 URL,不显示凭据告警,并隐藏二维码登录。二维码登录不可用时,部署信息的读取错误和重试操作保留在访问地址卡片中。重连后会重新检查地址前提。
@@ -43,7 +43,9 @@
"inject": [
"@deepseek-ai/dsh-api-remotes",
"@deepseek-ai/dsh-client-locale",
"@deepseek-ai/dsh-client-ui-settings-general"
"@deepseek-ai/dsh-client-ui-settings-general",
"@deepseek-ai/dsh-api-remote-access",
"@deepseek-ai/dsh-client-resources"
]
}
},
@@ -75,7 +77,8 @@
"peerDependencies": {
"@deepseek-ai/cordis": "workspace:~",
"@deepseek-ai/dsh-credentials": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*"
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/dsh-host-webserver": "workspace:*"
},
"devDependencies": {
"@deepseek-ai/dsh-client-connection": "workspace:*",
@@ -100,6 +103,8 @@
"@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-api-remote-access": "workspace:*",
"@deepseek-ai/dsh-client-resources": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*"
}
}
@@ -0,0 +1,28 @@
/** Public pairing script served before the authenticated application loads. */
import type { Context } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-host-webserver'
import { renderPairingScript } from './anonymous/index.ts'
import type { PairingRecovery } from './anonymous/pairing.ts'
/**
* Register the generated script in the Remote plugin's lifetime.
* @param ctx - plugin scope containing the HTTP listener.
* @param recovery - validated public timing and recovery limits.
*/
export function registerAnonymousPairing(ctx: Context, recovery: PairingRecovery): void {
const script = renderPairingScript(recovery)
ctx.effect(() => ctx.webServer.register({
kind: 'exact', path: '/pairing/client.js', auth: 'anonymous',
handler(request, response) {
if (request.method !== 'GET' && request.method !== 'HEAD') {
response.writeHead(405, { allow: 'GET, HEAD' })
response.end()
return
}
response.writeHead(200, {
'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
})
response.end(request.method === 'HEAD' ? undefined : script)
},
}))
}
@@ -0,0 +1,55 @@
/** Native element whose request state belongs to its connected document lifetime. */
import type { mountPairing, PairingRecovery } from './pairing.ts'
import type { pairingLocales, pairingMethodLabels } from './locales.ts'
interface PairingElement extends HTMLElement {
connectedCallback(): void
disconnectedCallback(): void
}
/**
* Define the anonymous element from explicitly supplied browser code and public data.
* Serialized into the public script; no runtime dependency may escape its parameters.
* @param mount - instance-owned pairing interaction.
* @param locales - public dictionaries selected by browser language.
* @param labels - public request labels selected by browser language.
* @param css - plugin-owned anonymous-page styles.
* @param recovery - validated public timing and recovery limits.
* @returns the registered element constructor.
*/
export function definePairingElement(
mount: typeof mountPairing, locales: typeof pairingLocales, labels: typeof pairingMethodLabels, css: string, recovery: PairingRecovery,
): new () => PairingElement {
const styles = Object.fromEntries(['pairing', 'panel', 'title', 'hint', 'message', 'countdown', 'code', 'feedback', 'button', 'primary']
.map(name => [name, `dsh-device-pairing-${name}`]))
return ((Element: new () => PairingElement) => {
customElements.define('dsh-device-pairing', Element)
return Element
})(class extends HTMLElement {
private dispose: (() => void) | undefined
/** Mount once per connection; reconnection starts without a retained credential. */
connectedCallback(): void {
if (this.dispose !== undefined) return
const view = this.ownerDocument.defaultView
if (view === null) return
const language = view.navigator.language.toLowerCase()
const t = language.startsWith('zh') ? locales.zh : locales.en
const label = labels[language.replace(/-.*/, '')] ?? labels.en
this.dispose = mount(this, styles, t, label, {
request: view.fetch.bind(view), navigate(url) { view.location.href = url },
}, recovery)
const style = this.ownerDocument.createElement('style')
style.textContent = css
this.prepend(style)
}
/** Release listeners, timers and requests when the method leaves the document. */
disconnectedCallback(): void {
this.dispose?.()
this.dispose = undefined
this.replaceChildren()
}
})
}
@@ -0,0 +1,17 @@
/** Generate the public classic script without an independently built browser artifact. */
import { definePairingElement } from './element.ts'
import { mountPairing } from './pairing.ts'
import type { PairingRecovery } from './pairing.ts'
import { pairingLocales, pairingMethodLabels } from './locales.ts'
import { pairingStyles } from './styles.ts'
/**
* Serialize the self-contained browser entry and its public dictionaries and styles.
* @param recovery - validated public timing and recovery limits.
* @returns executable classic JavaScript with no authenticated Client dependencies.
*/
export function renderPairingScript(recovery: PairingRecovery): string {
const data = [pairingLocales, pairingMethodLabels, pairingStyles, recovery]
.map(value => JSON.stringify(value).replaceAll('<', '\\u003c')).join(',')
return `(${definePairingElement.toString()})(${mountPairing.toString()},${data});`
}
@@ -0,0 +1,53 @@
/** Anonymous pairing copy available before the application locale service. */
const en = {
pairTitle: 'Pair this device',
pairHint: 'After requesting, open Settings → Remote connection on another signed-in device. Match the pairing code and approve to sign in here automatically.',
pairCreating: 'Requesting approval…',
pairWaiting: 'Waiting for approval…',
pairCancelling: 'Cancelling this request…',
pairReplacing: 'Cancelling the previous request before requesting again…',
pairChecking: 'Checking sign-in status…',
pairRecovering: 'Reconnecting automatically…',
pairCheckError: 'Could not confirm sign-in. Check your connection, then request again.',
pairCode: 'Pairing code',
pairRemaining: 'Expires in {time}',
pairDenied: 'The request was denied. You can request again.',
pairExpired: 'The request expired. Request again.',
pairError: 'Could not complete pairing. Check your connection, then request again.',
pairCreateError: 'Could not request pairing. Check your connection, then request again.',
pairCancel: 'Cancel request',
pairAgain: 'Request again',
} as const
/** Stable keys shared by the anonymous pairing translations. */
export type PairingLocaleKey = keyof typeof en
const zh: Record<PairingLocaleKey, string> = {
pairTitle: '配对此设备',
pairHint: '申请后,在另一台已登录设备的“设置 → 远程连接”核对配对码并批准,此设备将自动登录。',
pairCreating: '正在申请配对…',
pairWaiting: '正在等待批准…',
pairCancelling: '正在取消申请…',
pairReplacing: '正在取消原申请,随后重新申请…',
pairChecking: '正在确认登录状态…',
pairRecovering: '正在自动重新连接…',
pairCheckError: '无法确认登录状态,请检查网络后重新申请',
pairCode: '配对码',
pairRemaining: '剩余时间:{time}',
pairDenied: '申请已被拒绝,可以重新申请',
pairExpired: '申请已过期,请重新申请',
pairError: '无法完成配对,请检查网络后重新申请',
pairCreateError: '无法申请配对,请检查网络后重新申请',
pairCancel: '取消申请',
pairAgain: '重新申请',
}
/** Public dictionaries embedded in the anonymous script before application startup. */
export const pairingLocales = { en, zh }
/** Labels for the anonymous method and its initial request action. */
export const pairingMethodLabels: Readonly<Record<string, string> & { en: string }> = {
en: 'Request to pair', zh: '申请配对', de: 'Kopplung anfordern', es: 'Solicitar vinculación',
fr: 'Demander l’association', ja: 'ペアリングを申請', pt: 'Solicitar pareamento', ru: 'Запросить сопряжение',
}
@@ -0,0 +1,333 @@
/** Request approval and collect the browser cookie before authenticated application startup. */
import type { PairingCredential, PairingRequestId, PairingTicket } from '../pairing-types.ts'
import type { PairingLocaleKey } from './locales.ts'
/** Browser operations owned by the anonymous document. */
export interface PairingBrowser {
/** Fetch an application-relative pairing endpoint. */
request: typeof fetch
/** Navigate after the requesting browser has received its login cookie. */
navigate: (url: string) => void
}
/** Public, Host-configured bounds for anonymous recovery. */
export interface PairingRecovery {
readonly requestTtlMs: number
readonly pollIntervalMs: number
/** Bounds the complete response, including reading its body. */
readonly requestTimeoutMs: number
/** Additional attempts after a transient failure. */
readonly maxRetries: number
/** Caps exponential delays starting at pollIntervalMs. */
readonly retryMaxDelayMs: number
}
type Styles = Readonly<Record<string, string | undefined>>
type State = 'creating' | 'waiting' | 'cancelling' | 'replacing' | 'checking' | 'denied' | 'expired' | 'cancelled' | 'error'
type Operation = 'request' | 'status' | 'cancel' | 'replace' | 'check'
type Reply = { readonly status: number; readonly value: unknown }
/**
* Mount the anonymous controls with bounded, cancellable recovery and no authenticated Client modules.
* Serialized into the public script: runtime dependencies stay inside this function or its parameters.
* Native Promise chains keep Preview's async-lowering helpers out of the serialized function.
* Creation retries reuse credentials generated before sending; replacement confirms the old request ended.
* Unknown outcomes retain credentials. Expiry requires checking browser authorization before starting again.
* @param method - the device-pairing method rendered by the anonymous page.
* @param styles - anonymous pairing CSS classes.
* @param t - localized interaction copy.
* @param requestLabel - localized initial request action.
* @param browser - fetch and navigation for this document.
* @param recovery - validated Host timing and retry limits.
* @returns disposer aborting requests, timers and document listeners.
*/
export function mountPairing(
method: HTMLElement, styles: Styles, t: Readonly<Record<PairingLocaleKey, string>>, requestLabel: string,
browser: PairingBrowser, recovery: PairingRecovery,
): () => void {
const doc = method.ownerDocument
const view = doc.defaultView
if (view === null) return () => {}
const base = new URL('.', doc.baseURI)
const {
ticketOf, newCredential, button, current, show, stop, terminal, exchange, pause, read,
fail, navigate, tick, execute, startRequest, cancelRequest, suspend, resume,
} = {
ticketOf(this: void, value: unknown, held: PairingCredential): PairingTicket | undefined {
if (typeof value !== 'object' || value === null) return undefined
const id: unknown = Reflect.get(value, 'id')
const secret: unknown = Reflect.get(value, 'secret')
const code: unknown = Reflect.get(value, 'code')
const authority: unknown = Reflect.get(value, 'authority')
const sourceIp: unknown = Reflect.get(value, 'sourceIp')
const expiresInMs: unknown = Reflect.get(value, 'expiresInMs')
const pollIntervalMs: unknown = Reflect.get(value, 'pollIntervalMs')
if (id !== held.id || secret !== held.secret
|| typeof code !== 'string' || !/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{8}$/u.test(code)
|| typeof authority !== 'string' || authority.length === 0
|| (sourceIp !== null && typeof sourceIp !== 'string')
|| typeof expiresInMs !== 'number' || !Number.isSafeInteger(expiresInMs) || expiresInMs <= 0
|| typeof pollIntervalMs !== 'number' || !Number.isSafeInteger(pollIntervalMs) || pollIntervalMs <= 0) return undefined
return { ...held, code, authority, sourceIp, expiresInMs, pollIntervalMs }
},
newCredential(this: void): PairingCredential {
// getRandomValues also works on the supported plain-HTTP login page.
const bytes = view.crypto.getRandomValues(new Uint8Array(16))
const uuid = new DataView(bytes.buffer)
uuid.setUint8(6, (uuid.getUint8(6) & 15) | 64)
uuid.setUint8(8, (uuid.getUint8(8) & 63) | 128)
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
const id = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` as PairingRequestId
const secret = view.btoa(String.fromCharCode(...view.crypto.getRandomValues(new Uint8Array(32))))
.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')
return { id, secret }
},
button(this: void, id: string, text: string): HTMLButtonElement {
const element = doc.createElement('button')
element.id = id
element.type = 'button'
element.className = styles.button ?? ''
element.textContent = text
return element
},
current(this: void, version: number): boolean { return active && version === generation },
show(this: void, state: State, text: string = messages[state]): void {
const elapsed = credential !== undefined && performance.now() >= deadline
panel.hidden = state === 'cancelled'
panel.dataset.state = state
message.textContent = text
message.setAttribute('role', state === 'error' ? 'alert' : 'status')
code.hidden = ticket === undefined
code.textContent = ticket === undefined ? '' : `${ticket.code.slice(0, 4)} ${ticket.code.slice(4)}`
remaining.hidden = ticket === undefined || elapsed || state === 'error'
cancel.hidden = credential === undefined || elapsed || state === 'error' || state === 'checking'
cancel.disabled = busy && state !== 'creating'
start.textContent = state === 'creating' ? t.pairCreating : state === 'cancelled' ? requestLabel : t.pairAgain
start.disabled = busy
},
stop(this: void): void {
generation++
clearTimeout(timer)
clearTimeout(countdown)
controller.abort()
controller = new AbortController()
busy = false
},
terminal(this: void, state: 'denied' | 'expired' | 'cancelled'): void {
stop()
credential = undefined
ticket = undefined
show(state)
},
exchange(this: void, operation: 'request' | 'status' | 'cancel' | 'check', held: PairingCredential, signal: AbortSignal): Promise<Reply | undefined> {
const attempt = new AbortController()
return new Promise((resolve) => {
let settled = false
const { finish, abort } = {
finish(this: void, reply?: Reply): void {
if (settled) return
settled = true
clearTimeout(timeout)
signal.removeEventListener('abort', abort)
resolve(reply)
},
abort(this: void): void { attempt.abort(); finish() },
}
const timeout = setTimeout(abort, recovery.requestTimeoutMs)
signal.addEventListener('abort', abort, { once: true })
Promise.resolve().then(() => browser.request(operation === 'check' ? base : new URL(`pairing/${operation}`, base), {
method: operation === 'check' ? 'HEAD' : 'POST', credentials: 'same-origin', cache: 'no-store',
redirect: 'error', signal: attempt.signal,
...(operation === 'check' ? {} : { headers: { 'content-type': 'application/json' }, body: JSON.stringify(held) }),
})).then((response) => {
if (operation === 'check' || response.status !== 200) {
finish({ status: response.status, value: undefined })
attempt.abort()
return
}
return response.json().then((value: unknown) => { finish({ status: response.status, value }) })
}).catch(() => { finish() })
})
},
pause(this: void, delay: number, signal: AbortSignal): Promise<void> {
return new Promise((resolve) => {
const { finish } = {
finish(this: void): void { clearTimeout(wait); signal.removeEventListener('abort', finish); resolve() },
}
const wait = setTimeout(finish, delay)
signal.addEventListener('abort', finish, { once: true })
})
},
read(this: void, operation: 'request' | 'status' | 'cancel' | 'check', held: PairingCredential, state: State, signal: AbortSignal, failures = 0): Promise<Reply | undefined> {
return exchange(operation, held, signal).then((reply) => {
if (signal.aborted) return undefined
if (reply !== undefined && reply.status !== 429 && reply.status < 500) return reply
if (failures === recovery.maxRetries) return undefined
show(state, t.pairRecovering)
return pause(Math.min(recovery.retryMaxDelayMs, recovery.pollIntervalMs * 2 ** failures), signal)
.then(() => signal.aborted ? undefined : read(operation, held, state, signal, failures + 1))
})
},
fail(this: void, text: string): void { stop(); show('error', text) },
navigate(this: void): void {
stop()
credential = undefined
ticket = undefined
browser.navigate(base.href)
},
tick(this: void, held: PairingCredential): void {
const milliseconds = deadline - performance.now()
if (milliseconds <= 0) {
void execute(operation === 'replace' || operation === 'cancel' ? operation : 'check', held)
return
}
const seconds = Math.ceil(milliseconds / 1000)
remaining.textContent = t.pairRemaining.replace('{time}', `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`)
countdown = setTimeout(() => { tick(held) }, Math.min(1000, milliseconds))
},
execute(this: void, next: Operation, held: PairingCredential): Promise<void> {
stop()
operation = next
const version = generation
const signal = controller.signal
const expiring = next === 'check' || performance.now() >= deadline
busy = expiring || next !== 'status'
const state: State = expiring ? 'checking' : next === 'request' ? 'creating' : next === 'replace' ? 'replacing' : next === 'cancel' ? 'cancelling' : 'waiting'
show(state)
const admission = expiring ? read('check', held, state, signal).then((reply) => {
if (!current(version)) return
if (reply?.status === 200) { navigate(); return }
if (reply?.status !== 401) fail(t.pairCheckError)
// A 401 alone cannot retire a Host request that outlives the browser's deadline.
}) : Promise.resolve()
return admission.then(() => {
if (!current(version)) return
if (!expiring) tick(held)
const creation = ticket === undefined ? read('request', held, state, signal).then((reply) => {
if (!current(version)) return undefined
const received = reply?.status === 200 ? ticketOf(reply.value, held) : undefined
if (received === undefined) { fail(t.pairCreateError); return undefined }
ticket = received
deadline = Math.min(deadline, performance.now() + received.expiresInMs)
clearTimeout(countdown)
if (!expiring) {
if (performance.now() >= deadline) { void execute(next === 'request' ? 'check' : next, held); return undefined }
tick(held)
}
return received
}) : Promise.resolve(ticket)
return creation.then((received) => {
if (!current(version) || received === undefined) return
if (next === 'request' && !expiring) {
busy = false
show('waiting')
timer = setTimeout(() => { void execute('status', held) }, received.pollIntervalMs)
return
}
return read(next === 'status' && !expiring ? 'status' : 'cancel', held, state, signal).then((reply) => {
if (!current(version)) return
const status: unknown = typeof reply?.value === 'object' && reply.value !== null ? Reflect.get(reply.value, 'status') : undefined
if (reply?.status === 200 && status === 'completed') { navigate(); return }
if (reply?.status === 200 && status === 'expired' && !expiring) {
deadline = performance.now()
void execute(next === 'replace' || next === 'cancel' ? next : 'check', held)
return
}
if (reply?.status === 200 && (status === 'denied' || status === 'cancelled' || status === 'expired')) {
terminal(expiring ? next === 'cancel' ? 'cancelled' : 'expired' : status)
if (next === 'replace') startRequest()
return
}
if (next === 'status' && reply?.status === 200 && status === 'pending') {
show('waiting')
timer = setTimeout(() => { void execute('status', held) }, received.pollIntervalMs)
} else fail(t.pairError)
})
})
})
},
startRequest(this: void): void {
if (!active || busy) return
if (credential === undefined) {
credential = newCredential()
deadline = performance.now() + recovery.requestTtlMs
void execute('request', credential)
} else void execute('replace', credential)
},
cancelRequest(this: void): void {
if (active && credential !== undefined && (!busy || operation === 'request')) void execute('cancel', credential)
},
suspend(this: void): void { active = false; stop() },
resume(this: void): void {
if (active) return
active = true
if (credential !== undefined) void execute(ticket === undefined ? 'request' : 'status', credential)
},
}
const section = doc.createElement('section')
section.className = styles.pairing ?? ''
section.setAttribute('aria-labelledby', 'auth-pair-title')
const title = doc.createElement('h2')
title.id = 'auth-pair-title'
title.className = styles.title ?? ''
title.textContent = t.pairTitle
const start = button('auth-pair-request', requestLabel)
start.className = `${styles.button ?? ''} ${styles.primary ?? ''}`.trim()
const panel = doc.createElement('div')
panel.id = 'auth-pair-panel'
panel.className = styles.panel ?? ''
panel.hidden = true
const hint = doc.createElement('p')
hint.className = styles.hint ?? ''
hint.textContent = t.pairHint
const message = doc.createElement('p')
message.className = styles.message ?? ''
message.setAttribute('role', 'status')
const code = doc.createElement('code')
code.id = 'auth-pair-code'
code.className = styles.code ?? ''
code.setAttribute('aria-label', t.pairCode)
code.hidden = true
const remaining = doc.createElement('p')
remaining.id = 'auth-pair-countdown'
remaining.className = styles.countdown ?? ''
remaining.setAttribute('role', 'timer')
remaining.setAttribute('aria-live', 'off')
remaining.hidden = true
const feedback = doc.createElement('div')
feedback.className = styles.feedback ?? ''
const cancel = button('auth-pair-cancel', t.pairCancel)
cancel.hidden = true
feedback.append(message, remaining)
panel.append(feedback)
section.append(title, hint, code, start, cancel, panel)
method.replaceChildren(section)
let credential: PairingCredential | undefined
let ticket: PairingTicket | undefined
let controller = new AbortController()
let timer: ReturnType<typeof setTimeout> | undefined
let countdown: ReturnType<typeof setTimeout> | undefined
let deadline = 0
let busy = false
let active = true
let generation = 0
let operation: Operation = 'request'
const messages = {
creating: t.pairCreating, waiting: t.pairWaiting, cancelling: t.pairCancelling, replacing: t.pairReplacing,
checking: t.pairChecking, denied: t.pairDenied, expired: t.pairExpired, cancelled: '', error: t.pairError,
}
start.addEventListener('click', startRequest)
cancel.addEventListener('click', cancelRequest)
view.addEventListener('pagehide', suspend)
view.addEventListener('pageshow', resume)
return () => {
suspend()
credential = undefined
ticket = undefined
start.removeEventListener('click', startRequest)
cancel.removeEventListener('click', cancelRequest)
view.removeEventListener('pagehide', suspend)
view.removeEventListener('pageshow', resume)
}
}
@@ -0,0 +1,135 @@
/** Plugin-owned styles embedded in the anonymous script, with the same lifetime as its element. */
export const pairingStyles = `
dsh-device-pairing {
display: block;
min-width: 0;
}
.dsh-device-pairing-pairing {
display: flex;
flex-direction: column;
gap: 12px;
min-width: 0;
font-size: 13px;
line-height: 1.5;
}
.dsh-device-pairing-panel {
display: flex;
flex-direction: column;
gap: 12px;
}
.dsh-device-pairing-panel[hidden] {
display: none;
}
.dsh-device-pairing-title {
margin: 0;
font-size: 14px;
font-weight: 500;
}
.dsh-device-pairing-hint,
.dsh-device-pairing-message,
.dsh-device-pairing-countdown {
margin: 0;
color: var(--dsw-alias-label-secondary, color-mix(in srgb, currentColor 72%, transparent));
}
.dsh-device-pairing-countdown {
flex: none;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.dsh-device-pairing-message {
min-width: 0;
overflow-wrap: anywhere;
}
.dsh-device-pairing-message[role='alert'],
.dsh-device-pairing-panel[data-state='denied'] .dsh-device-pairing-message,
.dsh-device-pairing-panel[data-state='expired'] .dsh-device-pairing-message {
grid-column: 1 / -1;
padding: 12px;
border: 0.5px solid color-mix(in srgb, var(--dsh-pairing-banner-color) 40%, transparent);
border-radius: var(--dsw-radius-lg, 12px);
color: var(--dsw-alias-label-primary, light-dark(#222, #eee));
line-height: 20px;
}
.dsh-device-pairing-message[role='alert'] {
--dsh-pairing-banner-color: var(--dsw-alias-state-error-primary, light-dark(#ec1313, #f25a5a));
background: color-mix(in srgb, var(--dsh-pairing-banner-color) 10%, transparent);
}
.dsh-device-pairing-panel[data-state='denied'] .dsh-device-pairing-message,
.dsh-device-pairing-panel[data-state='expired'] .dsh-device-pairing-message {
--dsh-pairing-banner-color: var(--dsw-alias-state-warn-primary, light-dark(#bd720b, #e7a53c));
background: var(--dsw-alias-state-warn-tertiary, color-mix(in srgb, var(--dsh-pairing-banner-color) 10%, transparent));
}
.dsh-device-pairing-code {
padding: 8px 0;
text-align: center;
font-family: var(--ds-font-family-code, ui-monospace, SFMono-Regular, monospace);
font-size: 24px;
font-weight: 500;
letter-spacing: 3px;
overflow-wrap: anywhere;
color: var(--dsw-alias-label-primary, light-dark(#222, #eee));
}
.dsh-device-pairing-feedback {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 8px;
}
.dsh-device-pairing-countdown {
grid-column: 2;
}
.dsh-device-pairing-button {
box-sizing: border-box;
min-height: 44px;
padding: 8px 12px;
font: inherit;
font-weight: 500;
border: 0.5px solid var(--dsw-alias-border-l2, color-mix(in srgb, currentColor 16%, transparent));
border-radius: var(--dsw-radius-sm, 8px);
color: var(--dsw-alias-label-primary, light-dark(#222, #eee));
background: var(--dsw-alias-bg-layer-1, light-dark(#fff, #232324));
cursor: pointer;
}
.dsh-device-pairing-button:disabled {
cursor: default;
color: var(--dsw-alias-label-tertiary, color-mix(in srgb, currentColor 48%, transparent));
}
.dsh-device-pairing-button:focus-visible {
outline-style: solid;
outline-offset: 2px;
}
.dsh-device-pairing-primary {
font-size: 14px;
line-height: 1.5;
color: var(--dsw-alias-label-primary-foreground, light-dark(#fff, #222));
background: var(--dsw-alias-button-primary-fill, light-dark(#222, #eee));
border: 0;
}
@media (hover: hover) {
.dsh-device-pairing-button:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover, light-dark(#f5f5f5, #303031));
}
.dsh-device-pairing-primary:hover:not(:disabled) {
background: var(--dsw-alias-button-primary-hover, light-dark(#3c3c3d, #d4d4d4));
}
}
`
@@ -0,0 +1,92 @@
.section {
font-size: 13px;
line-height: 20px;
}
.status {
display: flex;
min-width: 0;
}
.sourceIp,
.error {
margin: 0;
}
.label,
.sourceIp {
color: var(--dsw-alias-label-secondary);
}
.error {
color: var(--dsw-alias-state-error-primary);
}
.request {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
padding: 12px;
border: 0.5px solid var(--dsw-alias-border-l2);
border-radius: var(--dsw-radius-md);
}
.details {
display: flex;
flex: 1;
flex-direction: column;
gap: 8px;
min-width: 0;
}
.identity {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
min-width: 0;
}
.code {
font-family: var(--ds-font-family-code);
font-size: 16px;
line-height: 24px;
letter-spacing: 2px;
font-variant-numeric: tabular-nums;
}
.sourceIp {
display: flex;
flex-wrap: wrap;
gap: 4px 8px;
overflow-wrap: anywhere;
}
.notice {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
}
.actions {
flex: none;
}
.empty {
display: flex;
justify-content: center;
padding: 16px;
}
@container (max-width: 480px) {
.request {
flex-direction: column;
align-items: stretch;
}
.actions > button {
min-height: 40px;
}
}
@@ -0,0 +1,84 @@
/** Approval controls and persistent outcome notices, independent of Cordis contexts. */
import { useId, useState } from 'react'
import { Button, IconWarningOutlineMedium, StateDot, Tag, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
import type { ObservableSnapshot } from '@deepseek-ai/dsh-client-store'
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-resources/client'
import type { RemoteConnectionContentProps } from './slots.ts'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
import type { PairingDecision, PairingRequestId } from '../types.ts'
import type { ApprovalState } from './pairing-approval.ts'
import type {} from './pairing-resource.ts'
import css from './PairingRequests.module.css'
import card from './RemoteConnectionSection.module.css'
/** Owner operations and mutation state bound by the client plugin. */
export interface PairingInjected {
readonly hooks: { readonly approval: ObservableSnapshot<ApprovalState> }
/** @param id - selected request. @param decision - allow or deny. @returns after the operation settles. */
decide: (id: PairingRequestId, decision: PairingDecision) => Promise<void>
/** Dismiss the latest approval outcome. */
dismiss: () => void
}
type Face = InjectFace<PairingInjected> & PropsLocale<'remoteConnection'>
/**
* Render pending request codes and connection source IP addresses within Remote connection settings.
* @param props - standard resource hook, owner actions, mutation state and localized copy.
* @returns the approval card with an empty status or pending requests and their permission warning.
*/
export function PairingRequests({ useResource, useApproval, decide, t }: Pick<RemoteConnectionContentProps, 'useResource'> & Face) {
const title = useId()
const [retry, setRetry] = useState(0)
const requests = useResource<'device-pairing'>(`dsh-resource://device-pairing/requests?retry=${String(retry)}`)
const busy = useApproval(value => value.busy)
const empty = requests.status === 'live' && requests.value?.requests.length === 0
const hasRequests = requests.value !== undefined && requests.value.requests.length > 0
return <section className={`${card.card} ${css.section}`} aria-labelledby={title}>
<header className={card.cardHeader}>
<h3 className={card.methodTitle} id={title}>{t('pairing.title')}</h3>
{empty && <span className={css.status} role="status"><Tag tone="neutral">{t('pairing.empty')}</Tag></span>}
</header>
<p className={card.description}>{t('pairing.description')}</p>
{hasRequests && <div className={card.caution} role="note">
<span className={card.cautionIcon} aria-hidden="true"><IconWarningOutlineMedium /></span>
<p className={card.warning}>{t('pairing.permission')}</p>
</div>}
{requests.status === 'loading' && <div className={css.empty} role="status" aria-label={t('pairing.loading')}><StateDot state="ongoing" /></div>}
{(requests.status === 'failed' || requests.status === 'none') && <div className={css.notice}>
<p className={css.error} role="alert">{t('pairing.readFailed')}</p>
<Button variant="outline" onClick={() => { setRetry(value => value + 1) }}>{t('pairing.retry')}</Button>
</div>}
{requests.value?.requests.map(request => <div className={css.request} key={request.id}>
<div className={css.details}>
<div className={css.identity}>
<span className={css.label}>{t('pairing.code')}</span>
<code className={css.code}>{request.code.slice(0, 4)} {request.code.slice(4)}</code>
</div>
<p className={css.sourceIp}>
<span>{t('pairing.sourceIp')}</span>
<span>{request.sourceIp ?? t('pairing.sourceIpUnknown')}</span>
</p>
</div>
<div className={`${card.cardActions} ${css.actions}`}>
<Button variant="primary" size="sm" disabled={busy || requests.status !== 'live'}
onClick={() => { void decide(request.id, 'allow') }}>{t('pairing.approve')}</Button>
<Button variant="outline" size="sm" disabled={busy || requests.status !== 'live'}
onClick={() => { void decide(request.id, 'deny') }}>{t('pairing.deny')}</Button>
</div>
</div>)}
</section>
}
/**
* Announce the decision even when the owner has closed Settings.
* @param props - mutation state, notice dismissal and localized copy.
* @returns the current toast, or nothing.
*/
export function PairingToast({ useApproval, dismiss, t }: PropsRuntime<'shell.overlay'> & Face) {
const state = useApproval(value => value)
if (state.notice === null) return null
return <Toast key={state.sequence} text={t(`pairing.${state.notice}`)} onDone={dismiss}
{...state.notice === 'approved' || state.notice === 'denied' ? { tone: 'success' as const } : {}} />
}
@@ -120,7 +120,7 @@
visibility: hidden;
}
.qrActions {
.cardActions {
display: flex;
justify-content: flex-end;
flex-wrap: wrap;
@@ -246,14 +246,14 @@
gap: 8px;
}
.qrActions {
.cardActions {
flex-direction: column;
align-items: stretch;
width: 100%;
margin-inline-start: 0;
}
.qrActions > button {
.cardActions > button {
width: 100%;
}
@@ -3,6 +3,7 @@ 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 { PairingRequests } from './PairingRequests.tsx'
import css from './RemoteConnectionSection.module.css'
/** Renderer-derived section data, localized copy, and actions. */
@@ -17,7 +18,10 @@ export function RemoteConnectionSection(props: RemoteConnectionSectionProps) {
const { t, useRemoteConnection } = props
const available = useRemoteConnection(state => state.deployment?.availability === 'available')
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>
if (loading) return <section className={css.section} aria-label={t('title')}>
{pairingAvailable && <PairingRequests {...props} />}
<div className={css.loading} role="status" aria-label={t('loading')}><StateDot state="ongoing" size={20} /></div>
</section>
return <section className={css.section} aria-label={t('title')}>
<h2 className={css.title}>{t('title')}</h2>
<ConnectionNotice {...props} />
@@ -2,6 +2,7 @@
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-api-remote-access/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'
@@ -12,6 +13,9 @@ import { LoginLinkController } from './login-link-controller.ts'
import { LoginLinkToast } from './LoginLinkToast.tsx'
import { RemoteConnectionSection } from './RemoteConnectionSection.tsx'
import { RemoteConnectionSettings } from './RemoteConnectionSettings.tsx'
import { PairingApproval } from './pairing-approval.ts'
import { requestsResource } from './pairing-resource.ts'
import { PairingToast, type PairingInjected } from './PairingRequests.tsx'
import { en, zh, ja, es, fr, de, ru, pt, type RemoteConnectionLocaleKey } from './locales.ts'
export type { RemoteConnectionContentProps, RemoteConnectionExtensionProps } from './slots.ts'
@@ -25,7 +29,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
}
/** Services consumed by the settings registration. */
export const inject = ['slots', 'locale', 'remote']
export const inject = ['slots', 'locale', 'remote', 'remoteAccess', 'resources']
/**
* Register the section and own its polling until plugin disposal.
@@ -43,7 +47,11 @@ export async function apply(ctx: Context): Promise<void> {
() => controller.store.getSnapshot().deployment?.availability === 'available')
const invitationFace = controller.inject()
const linkFace = link.inject()
const face = { ...invitationFace, ...linkFace, hooks: { ...invitationFace.hooks, ...linkFace.hooks } }
const approvalFace = pairingFace()
const face = {
...invitationFace, ...linkFace, ...approvalFace,
hooks: { ...invitationFace.hooks, ...linkFace.hooks, ...approvalFace.hooks },
}
scope.effect(() => () => controller.dispose(), 'remote-connection: invitation lifetime')
scope.effect(() => () => link.dispose(), 'remote-connection: login link')
let linkAvailable = false
@@ -72,6 +80,14 @@ export async function apply(ctx: Context): Promise<void> {
scope.slots.inject('shell.overlay', () => scope.slots.register({
name: 'shell.overlay', id: 'remote-connection-copy', locale: 'remoteConnection', inject: () => linkFace,
}, LoginLinkToast))
scope.remoteAccess.whenAccess('remoteConnection/pairingRequests', function* () {
approval.activate()
yield () => { approval.dispose() }
yield scope.resources.register(pairing.provider)
yield scope.slots.inject('shell.overlay', () => scope.slots.register({
name: 'shell.overlay', id: 'remote-connection-pairing-notice', locale: 'remoteConnection', inject: pairingFace,
}, PairingToast))
})
void controller.load()
})
}
@@ -1,7 +1,9 @@
/** Copy for the Remote connection settings section. */
import * as pairing from './pairing-locales.ts'
/** English dictionary and key authority. */
export const en = {
...pairing.en,
title: 'Remote connection',
qrTitle: 'QR code login',
addressTitle: 'Access address',
@@ -39,6 +41,7 @@ export type RemoteConnectionLocaleKey = keyof typeof en
/** Simplified Chinese dictionary. */
export const zh: Record<RemoteConnectionLocaleKey, string> = {
...pairing.zh,
title: '远程连接',
qrTitle: '二维码登录',
addressTitle: '访问地址',
@@ -73,6 +76,7 @@ export const zh: Record<RemoteConnectionLocaleKey, string> = {
/** Japanese dictionary. */
export const ja: Record<RemoteConnectionLocaleKey, string> = {
...pairing.ja,
title: 'リモート接続',
qrTitle: 'QRコードでログイン',
addressTitle: 'アクセスアドレス',
@@ -107,6 +111,7 @@ export const ja: Record<RemoteConnectionLocaleKey, string> = {
/** Spanish dictionary. */
export const es: Record<RemoteConnectionLocaleKey, string> = {
...pairing.es,
title: 'Conexión remota',
qrTitle: 'Inicio de sesión con QR',
addressTitle: 'Dirección de acceso',
@@ -141,6 +146,7 @@ export const es: Record<RemoteConnectionLocaleKey, string> = {
/** French dictionary. */
export const fr: Record<RemoteConnectionLocaleKey, string> = {
...pairing.fr,
title: 'Connexion à distance',
qrTitle: 'Connexion par code QR',
addressTitle: 'Adresse d’accès',
@@ -175,6 +181,7 @@ export const fr: Record<RemoteConnectionLocaleKey, string> = {
/** German dictionary. */
export const de: Record<RemoteConnectionLocaleKey, string> = {
...pairing.de,
title: 'Fernverbindung',
qrTitle: 'Anmeldung per QR-Code',
addressTitle: 'Zugriffsadresse',
@@ -209,6 +216,7 @@ export const de: Record<RemoteConnectionLocaleKey, string> = {
/** Russian dictionary. */
export const ru: Record<RemoteConnectionLocaleKey, string> = {
...pairing.ru,
title: 'Удалённое подключение',
qrTitle: 'Вход по QR-коду',
addressTitle: 'Адрес доступа',
@@ -243,6 +251,7 @@ export const ru: Record<RemoteConnectionLocaleKey, string> = {
/** Portuguese dictionary. */
export const pt: Record<RemoteConnectionLocaleKey, string> = {
...pairing.pt,
title: 'Conexão remota',
qrTitle: 'Login por código QR',
addressTitle: 'Endereço de acesso',
@@ -1,6 +1,6 @@
/** 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'
import type { TypertClientRemote } from '@deepseek-ai/dsh-typert-protocol'
/** Link readiness and clipboard feedback; credentials must never be persisted or logged. */
export interface LoginLinkState {
@@ -0,0 +1,72 @@
/** Owner decisions and their shell-wide notices survive a settings view closing. */
import type { Context } from '@deepseek-ai/cordis'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import type {} from '@deepseek-ai/dsh-client-remote-connection/remote'
import type { PairingDecision, PairingDecisionResult, PairingRequestId } from '../types.ts'
/** Mutation state shared by approval controls and the persistent notice. */
export interface ApprovalState {
readonly available: boolean
readonly busy: boolean
readonly notice: 'approved' | 'denied' | 'unavailable' | 'failed' | null
readonly sequence: number
}
/** Serializes owner decisions and ignores results after access is withdrawn. */
export class PairingApproval {
/** Framework-observed operation state; it contains no applicant credentials. */
readonly state = createSnapshotStore<ApprovalState>({ available: false, busy: false, notice: null, sequence: 0 })
private controller: AbortController | undefined
/**
* @param remote - generated owner-only pairing mutations.
* @param confirmed - removes a confirmed request from active resources before resolving; never rejects.
*/
constructor(
private readonly remote: Pick<Context['remote']['remoteConnection'], 'decidePairing'>,
private readonly confirmed: (id: PairingRequestId) => Promise<void>,
) {}
/** Activate approval controls for the current owner-access grant. */
activate(): void {
this.controller = new AbortController()
this.state.set({ ...this.state.getSnapshot(), available: true })
}
/**
* Submit the owner decision and update active lists before announcing its confirmed outcome.
* An unknown outcome retains the request for reconciliation.
* @param id - selected request.
* @param decision - allow or deny after comparing the displayed code.
* @returns after the decision settles or access is withdrawn.
*/
async decide(id: PairingRequestId, decision: PairingDecision): Promise<void> {
const controller = this.controller
if (controller === undefined || this.state.getSnapshot().busy) return
const aborted = (): boolean => controller.signal.aborted
this.state.set({ ...this.state.getSnapshot(), busy: true, notice: null })
let notice: ApprovalState['notice'] = 'failed'
let result: RemoteResult<PairingDecisionResult> | undefined
try {
result = await this.remote.decidePairing(id, decision, controller.signal)
} catch (_requestFailure) {
// The shell notice reports an unknown decision outcome; polling retains the actual row state.
}
if (result?.ok) notice = result.value
if (aborted()) return
if (notice !== 'failed') await this.confirmed(id)
if (aborted()) return
this.state.set({ available: true, busy: false, notice, sequence: this.state.getSnapshot().sequence + 1 })
}
/** Dismiss only the notice currently displayed by the shell. */
dismiss(): void { this.state.set({ ...this.state.getSnapshot(), notice: null }) }
/** Abort the current operation and discard state when owner access ends. */
dispose(): void {
this.controller?.abort()
this.controller = undefined
this.state.set({ available: false, busy: false, notice: null, sequence: this.state.getSnapshot().sequence })
}
}
@@ -0,0 +1,93 @@
/** Copy for Remote connection settings and owner approval. */
export const en = {
'pairing.title': 'Pairing requests',
'pairing.description': 'Open this app on the other device and request pairing. Compare the codes before approving.',
'pairing.permission': 'Approval gives that browser full access to this app, including approving other devices.',
'pairing.empty': 'No requests awaiting approval.',
'pairing.code': 'Pairing code',
'pairing.sourceIp': 'Source IP',
'pairing.sourceIpUnknown': 'Unknown',
'pairing.approve': 'Approve',
'pairing.deny': 'Deny',
'pairing.retry': 'Retry',
'pairing.loading': 'Loading pairing requests',
'pairing.readFailed': 'Could not load requests. Retry to refresh the list.',
'pairing.approved': 'Request approved',
'pairing.denied': 'Request denied',
'pairing.unavailable': 'This request is no longer awaiting approval',
'pairing.failed': 'Could not confirm your decision. Refresh the list before trying again.',
} as const
/** Keys shared by the pairing dictionaries. */
export type PairingLocaleKey = keyof typeof en
/** Chinese pairing copy. */
export const zh: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': '来源 IP', 'pairing.sourceIpUnknown': '未知',
'pairing.title': '配对申请',
'pairing.description': '在另一台设备上打开此应用并申请配对,核对两端配对码后再批准',
'pairing.permission': '批准后,该浏览器将获得此应用的完整访问权限,也可以批准其他设备',
'pairing.empty': '暂无待审批的申请', 'pairing.code': '配对码', 'pairing.approve': '批准', 'pairing.deny': '拒绝', 'pairing.retry': '重试', 'pairing.loading': '正在加载配对申请',
'pairing.readFailed': '无法加载申请,请重试以刷新列表', 'pairing.approved': '已批准申请', 'pairing.denied': '已拒绝申请',
'pairing.unavailable': '此申请已不在待审批状态', 'pairing.failed': '无法确认审批结果,请刷新列表后再试',
}
/** Japanese pairing copy. */
export const ja: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': '接続元 IP', 'pairing.sourceIpUnknown': '不明',
'pairing.title': 'ペアリング申請', 'pairing.description': '別のデバイスでこのアプリを開き、ペアリングを申請してください。承認する前に両方のコードを照合してください。',
'pairing.permission': '承認すると、そのブラウザーはこのアプリへのフルアクセス権を得て、他のデバイスも承認できます。',
'pairing.empty': '承認待ちの申請はありません。', 'pairing.code': 'ペアリングコード', 'pairing.approve': '承認', 'pairing.deny': '拒否', 'pairing.retry': '再試行', 'pairing.loading': 'ペアリング申請を読み込み中',
'pairing.readFailed': '申請を読み込めませんでした。再試行して一覧を更新してください。', 'pairing.approved': '申請を承認しました', 'pairing.denied': '申請を拒否しました',
'pairing.unavailable': 'この申請は承認待ちではありません', 'pairing.failed': '審査結果を確認できませんでした。一覧を更新してから再試行してください。',
}
/** Spanish pairing copy. */
export const es: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'IP de origen', 'pairing.sourceIpUnknown': 'Desconocida',
'pairing.title': 'Solicitudes de vinculación', 'pairing.description': 'Abra esta aplicación en el otro dispositivo y solicite la vinculación. Compare los códigos antes de aprobar.',
'pairing.permission': 'La aprobación concede a ese navegador acceso completo a esta aplicación, incluida la capacidad de aprobar otros dispositivos.',
'pairing.empty': 'No hay solicitudes pendientes de aprobación.', 'pairing.code': 'Código de vinculación', 'pairing.approve': 'Aprobar', 'pairing.deny': 'Rechazar', 'pairing.retry': 'Reintentar', 'pairing.loading': 'Cargando solicitudes de vinculación',
'pairing.readFailed': 'No se pudieron cargar las solicitudes. Reintente para actualizar la lista.', 'pairing.approved': 'Solicitud aprobada', 'pairing.denied': 'Solicitud rechazada',
'pairing.unavailable': 'Esta solicitud ya no está pendiente de aprobación', 'pairing.failed': 'No se pudo confirmar su decisión. Actualice la lista antes de reintentar.',
}
/** French pairing copy. */
export const fr: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'IP source', 'pairing.sourceIpUnknown': 'Inconnue',
'pairing.title': 'Demandes d’association', 'pairing.description': 'Ouvrez cette application sur l’autre appareil et demandez une association. Comparez les codes avant d’approuver.',
'pairing.permission': 'L’approbation donne à ce navigateur un accès complet à cette application, y compris la possibilité d’approuver d’autres appareils.',
'pairing.empty': 'Aucune demande en attente d’approbation.', 'pairing.code': 'Code d’association', 'pairing.approve': 'Approuver', 'pairing.deny': 'Refuser', 'pairing.retry': 'Réessayer', 'pairing.loading': 'Chargement des demandes d’association',
'pairing.readFailed': 'Impossible de charger les demandes. Réessayez pour actualiser la liste.', 'pairing.approved': 'Demande approuvée', 'pairing.denied': 'Demande refusée',
'pairing.unavailable': 'Cette demande n’est plus en attente d’approbation', 'pairing.failed': 'Impossible de confirmer votre décision. Actualisez la liste avant de réessayer.',
}
/** German pairing copy. */
export const de: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'Quell-IP', 'pairing.sourceIpUnknown': 'Unbekannt',
'pairing.title': 'Kopplungsanfragen', 'pairing.description': 'Öffnen Sie diese App auf dem anderen Gerät und fordern Sie eine Kopplung an. Vergleichen Sie die Codes vor der Genehmigung.',
'pairing.permission': 'Die Genehmigung gewährt diesem Browser vollständigen Zugriff auf diese App, einschließlich der Genehmigung weiterer Geräte.',
'pairing.empty': 'Keine Anfragen warten auf Genehmigung.', 'pairing.code': 'Kopplungscode', 'pairing.approve': 'Genehmigen', 'pairing.deny': 'Ablehnen', 'pairing.retry': 'Erneut versuchen', 'pairing.loading': 'Kopplungsanfragen werden geladen',
'pairing.readFailed': 'Anfragen konnten nicht geladen werden. Versuchen Sie es erneut, um die Liste zu aktualisieren.', 'pairing.approved': 'Anfrage genehmigt', 'pairing.denied': 'Anfrage abgelehnt',
'pairing.unavailable': 'Diese Anfrage wartet nicht mehr auf Genehmigung', 'pairing.failed': 'Ihre Entscheidung konnte nicht bestätigt werden. Aktualisieren Sie die Liste, bevor Sie es erneut versuchen.',
}
/** Russian pairing copy. */
export const ru: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'IP-адрес источника', 'pairing.sourceIpUnknown': 'Неизвестен',
'pairing.title': 'Запросы на сопряжение', 'pairing.description': 'Откройте приложение на другом устройстве и запросите сопряжение. Перед одобрением сравните коды.',
'pairing.permission': 'Одобрение предоставляет этому браузеру полный доступ к приложению, включая возможность одобрять другие устройства.',
'pairing.empty': 'Нет запросов, ожидающих одобрения.', 'pairing.code': 'Код сопряжения', 'pairing.approve': 'Одобрить', 'pairing.deny': 'Отклонить', 'pairing.retry': 'Повторить', 'pairing.loading': 'Загрузка запросов на сопряжение',
'pairing.readFailed': 'Не удалось загрузить запросы. Повторите попытку, чтобы обновить список.', 'pairing.approved': 'Запрос одобрен', 'pairing.denied': 'Запрос отклонён',
'pairing.unavailable': 'Этот запрос больше не ожидает одобрения', 'pairing.failed': 'Не удалось подтвердить решение. Обновите список перед повторной попыткой.',
}
/** Portuguese pairing copy. */
export const pt: Record<PairingLocaleKey, string> = {
'pairing.sourceIp': 'IP de origem', 'pairing.sourceIpUnknown': 'Desconhecido',
'pairing.title': 'Pedidos de emparelhamento', 'pairing.description': 'Abra esta aplicação no outro dispositivo e solicite o emparelhamento. Compare os códigos antes de aprovar.',
'pairing.permission': 'A aprovação dá a esse navegador acesso completo a esta aplicação, incluindo a possibilidade de aprovar outros dispositivos.',
'pairing.empty': 'Nenhum pedido aguarda aprovação.', 'pairing.code': 'Código de emparelhamento', 'pairing.approve': 'Aprovar', 'pairing.deny': 'Recusar', 'pairing.retry': 'Tentar novamente', 'pairing.loading': 'A carregar pedidos de emparelhamento',
'pairing.readFailed': 'Não foi possível carregar os pedidos. Tente novamente para atualizar a lista.', 'pairing.approved': 'Pedido aprovado', 'pairing.denied': 'Pedido recusado',
'pairing.unavailable': 'Este pedido já não aguarda aprovação', 'pairing.failed': 'Não foi possível confirmar a decisão. Atualize a lista antes de tentar novamente.',
}
@@ -0,0 +1,126 @@
/** Mounted-only polling for the owner's pending pairing requests. */
import type { Context } from '@deepseek-ai/cordis'
import type { ResourceProvider } from '@deepseek-ai/dsh-client-resources/client'
import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'
import type { RemoteFailure, RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import type { PairingRequestId, PairingRequestsValue } from '../types.ts'
import type {} from '@deepseek-ai/dsh-client-remote-connection/remote'
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface ResourceProtocolMap {
/** Pairing requests whose displayed codes require owner approval. */
'device-pairing': PairingRequestsValue
}
}
declare module '@deepseek-ai/dsh-typert-protocol' {
interface RemoteErrorDetailsMap {
/** The approval-list read failed before a response was received. */
'pairing/read-failed': {}
}
}
/**
* Poll held request lists and publish confirmed decisions before their next read.
* Failed reads retain their last list and wait for a confirmation or a newly opened retry.
* A confirmation removes its request but preserves an earlier read failure until a fresh read succeeds.
* @param remote - generated pairing Remote methods.
* @returns the provider and a callback that waits for loaded lists to consume the removal or close.
* Unopened and not-yet-loaded lists acknowledge immediately.
*/
export function requestsResource(remote: Pick<Context['remote']['remoteConnection'], 'pairingRequests'>): {
provider: ResourceProvider<'device-pairing'>
confirmed(id: PairingRequestId): Promise<void>
} {
const active = new Set<(id: PairingRequestId) => Promise<void>>()
const provider: ResourceProvider<'device-pairing'> = {
protocol: 'device-pairing',
async *open(_address, { signal }) {
const aborted = (): boolean => signal.aborted
if (aborted()) return
let current: PairingRequestsValue | undefined
let failure: RemoteFailure | undefined
let request: AbortController | undefined
let timer: ReturnType<typeof setTimeout> | undefined
let wake = Promise.withResolvers<undefined>()
const pending = new Set<PairingRequestId>()
const acknowledgements = new Set<() => void>()
const acknowledge = (callbacks: readonly (() => void)[]): void => {
for (const callback of callbacks) {
acknowledgements.delete(callback)
callback()
}
}
const confirmed = (id: PairingRequestId): Promise<void> => new Promise<void>((resolve) => {
pending.add(id)
acknowledgements.add(resolve)
request?.abort()
clearTimeout(timer)
wake.resolve(undefined)
})
const close = (): void => {
active.delete(confirmed)
signal.removeEventListener('abort', close)
request?.abort()
clearTimeout(timer)
acknowledge([...acknowledgements])
wake.resolve(undefined)
}
const read = async (readSignal: AbortSignal): Promise<RemoteResult<PairingRequestsValue>> => {
try {
return await remote.pairingRequests(readSignal)
} catch (error) {
return {
ok: false,
error: remoteErrorOf(error) ?? new RemoteError('pairing/read-failed', 'Could not read pairing requests.', {}),
}
}
}
active.add(confirmed)
signal.addEventListener('abort', close, { once: true })
try {
while (!aborted()) {
if (pending.size > 0) {
if (current !== undefined) {
current = { ...current, requests: current.requests.filter(row => !pending.has(row.id)) }
pending.clear()
const consumed = [...acknowledgements]
yield { ok: true, value: current }
if (aborted()) return
if (failure !== undefined) yield { ok: false, error: failure }
acknowledge(consumed)
continue
}
pending.clear()
acknowledge([...acknowledgements])
}
wake = Promise.withResolvers<undefined>()
request = new AbortController()
const result = await Promise.race([read(request.signal), wake.promise.then(() => undefined)])
request = undefined
if (aborted()) return
// A confirmed decision supersedes any read already in flight, even if its transport ignores abort.
if (pending.size > 0 || result === undefined) continue
if (result.ok) {
current = result.value
failure = undefined
} else failure = result.error
const consumed = [...acknowledgements]
yield result
acknowledge(consumed)
if (pending.size > 0) continue
if (aborted()) return
if (result.ok) timer = setTimeout(() => { wake.resolve(undefined) }, result.value.pollIntervalMs)
await wake.promise
clearTimeout(timer)
}
} finally {
close()
}
},
}
return {
provider,
async confirmed(id) { await Promise.all([...active].map(notify => notify(id))) },
}
}
@@ -49,7 +49,7 @@ export class RemoteConnectionController {
private live = true
/** @param remote - Generated owner-authenticated service methods. */
constructor(private readonly remote: RemoteConnectionApi) {}
constructor(private readonly remote: Pick<RemoteConnectionApi, 'status' | 'create' | 'cancel'>) {}
/**
* Bind stable actions and the private snapshot to the slot renderer.
@@ -3,19 +3,21 @@ 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'
import type { PairingInjected } from './PairingRequests.tsx'
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotMap {
/**
* Complete Remote connection panel with shared invitation state and actions.
* Complete Remote connection panel with QR, login-link, and pairing approval state.
* Receives invitation and login-link selectors, their actions, and close().
* Unloading a replacement restores the default panel with the current invitation.
* useApproval(selector) exposes owner-access availability and decision outcomes; decide() and dismiss() manage them.
* Replacing this panel hides all default sections; unloading restores their current state.
*/
'settings.remoteConnection.content': {
kind: 'single'
scope: 'root'
owner: SettingsSectionOwnerProps
inject: RemoteConnectionFace & LoginLinkFace
inject: RemoteConnectionFace & LoginLinkFace & PairingInjected
}
/**
* Additional options rendered after the active Remote connection panel.
@@ -31,7 +33,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
}
}
/** Settings close action, invitation selector, and create/cancel/reload actions supplied to every panel. */
/** Settings close action and shared QR, login-link, and owner-gated pairing state/actions supplied to every panel. */
export type RemoteConnectionContentProps = PropsRuntime<'settings.remoteConnection.content'>
/** Shared login state, actions, and settings close action supplied to appended options. */
+76 -9
View File
@@ -8,23 +8,28 @@ 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 { HarnessError } from '@deepseek-ai/dsh-error'
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
import { LoginTickets } from './login-tickets.ts'
import { handleLogin, isQrLogin } from './host-route.ts'
import { RemoteBrowserAuth } from './remote-auth.ts'
import { renderAuthenticationPage } from './login-page.ts'
import { PairingRequests } from './pairing-requests.ts'
import { registerPairingRoutes } from './pairing-routes.ts'
import { registerAnonymousPairing } from './anonymous-assets.ts'
import type { RemoteConnectionStatus, RemoteLoginId, RemoteLoginState, RemoteLoginTicket } from './types.ts'
import type { PairingDecision, PairingDecisionResult, PairingRequestId, PairingRequestsValue } from './pairing-types.ts'
export type * from './types.ts'
declare module '@deepseek-ai/cordis' {
interface Context {
/** Short-lived QR login invitations. */
/** QR invitations, private login links, and owner-approved browser pairing. */
remoteConnection: RemoteConnection
}
}
/** Deployment timing for QR login and its settings status. */
/** Deployment timing and limits for remote browser login. */
export interface Config {
/** Absolute lifetime in days for Remote browser credentials; default 30. */
cookieMaxAgeDays: number
@@ -32,18 +37,45 @@ export interface Config {
ticketLifetimeMs: number
/** Interval in milliseconds between the settings panel's status reads. */
pollIntervalMs: number
/** Limits for anonymous requests and approval delivery. */
pairing: {
/** Lifetime in milliseconds, including retries of approved delivery. Default: 300000. */
requestTtlMs: number
/** Maximum retained requests, including terminal requests until expiry. Default: 32. */
maxRequests: number
/** Minimum interval between anonymous creations across this process. Default: 1000. */
requestIntervalMs: number
/** Minimum applicant polling interval and periodic approval-list refresh interval. Default: 2000. */
pollIntervalMs: number
/** Complete anonymous HTTP request timeout in milliseconds. Default: 10000. */
requestTimeoutMs: number
/** Additional attempts after network, timeout, rate-limit, or server failures. Default: 3. */
maxRetries: number
/** Maximum exponential retry delay in milliseconds; at least pollIntervalMs. Default: 10000. */
retryMaxDelayMs: number
}
}
/** One outstanding invitation, issued by an owner and consumed by a new browser. */
/** Owner-authorized browser login through QR codes, private links, or pairing requests. */
export default class RemoteConnection extends TypertRemoteService {
static inject = ['connection', 'connection.authentication', 'credentials', 'webServer', 'webApp']
static Config: z<Partial<Config>, Config> = z.object({
static Config: z<Partial<Omit<Config, 'pairing'>> & { pairing?: Partial<Config['pairing']> }, 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),
pairing: z.object({
requestTtlMs: z.natural().min(1).max(2_147_483_647).default(300_000),
maxRequests: z.natural().min(1).default(32),
requestIntervalMs: z.natural().min(1).default(1_000),
pollIntervalMs: z.natural().min(1).max(2_147_483_647).default(2_000),
requestTimeoutMs: z.natural().min(1).max(2_147_483_647).default(10_000),
maxRetries: z.natural().default(3),
retryMaxDelayMs: z.natural().min(1).max(2_147_483_647).default(10_000),
}),
})
private readonly tickets = new LoginTickets()
private readonly pairing: PairingRequests
private readonly owner: Context
private readonly lifetime = new AbortController()
private readonly pending = new Set<Promise<unknown>>()
@@ -51,12 +83,19 @@ export default class RemoteConnection extends TypertRemoteService {
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.
* Register anonymous login routes independently of the authenticated application page.
* @param ctx - Host containing browser authentication, anonymous pages, and the advertised URL.
* @param config - validated deployment limits; pairing lifetime must exceed its polling interval.
*/
constructor(ctx: Context, private readonly config: Config) {
super(ctx, 'remoteConnection')
if (config.pairing.requestTtlMs <= config.pairing.pollIntervalMs) {
throw new HarnessError('remote-connection: pairing.requestTtlMs must exceed pairing.pollIntervalMs', 'REMOTE_PAIRING_INVALID_CONFIG')
}
if (config.pairing.retryMaxDelayMs < config.pairing.pollIntervalMs) {
throw new HarnessError('remote-connection: pairing.retryMaxDelayMs must be at least pairing.pollIntervalMs', 'REMOTE_PAIRING_INVALID_CONFIG')
}
this.pairing = new PairingRequests(config.pairing)
this.owner = ctx
}
@@ -105,6 +144,8 @@ export default class RemoteConnection extends TypertRemoteService {
response.off('close', onClose)
}
})
registerAnonymousPairing(ctx, this.config.pairing)
yield registerPairingRoutes(ctx, this.pairing, this.lifetime, request => auth.createSessionCookie(request, ctx.webServer.protocol === 'https:'))
yield ctx.webServer.register({
kind: 'exact', path: '/', auth: 'anonymous',
resource: async (request, admitted) => {
@@ -138,7 +179,7 @@ export default class RemoteConnection extends TypertRemoteService {
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'",
'content-security-policy': "default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; form-action 'self'; base-uri 'self'; frame-ancestors 'none'",
}
if ('rejection' in admission && admission.rejection !== 401) return new Response('authentication unavailable', { status: admission.rejection, headers })
const html = renderAuthenticationPage({
@@ -208,9 +249,35 @@ export default class RemoteConnection extends TypertRemoteService {
return this.tickets.state(id)
}
/**
* Read pending requests without the credentials used to collect their sessions.
* @param signal - current Remote call's cancellation.
* @returns pending codes and the deployment's refresh interval.
*/
@Remote
pairingRequests(signal: AbortSignal): PairingRequestsValue {
signal.throwIfAborted()
this.requireOwner()
return { requests: this.pairing.list(), pollIntervalMs: this.config.pairing.pollIntervalMs }
}
/**
* Approve or deny one displayed code; the first decision is retained across retries.
* @param id - request selected after comparing its code with the applicant's screen.
* @param decision - allow or deny full owner access for the requesting browser.
* @param signal - current Remote call's cancellation before the decision commits.
* @returns committed decision, or unavailable after cancellation, expiry, or collection.
*/
@Remote
decidePairing(id: PairingRequestId, decision: PairingDecision, signal: AbortSignal): PairingDecisionResult {
signal.throwIfAborted()
this.requireOwner()
return this.pairing.decide(id, decision)
}
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.', {})
throw new RemoteError('remote-connection/owner-required', 'Only an authenticated owner can authorize browser access.', {})
}
if (this.stopped) throw new RemoteError('remote-connection/disposed', 'Remote login is no longer available.', {})
}
@@ -11,6 +11,7 @@ export const loginLocales = {
authenticationTitle: 'Connect to this Host',
authenticationDescription: 'Sign in to continue.',
authenticationUnavailable: 'No sign-in method is available. Contact the Host operator.',
pairingScriptRequired: 'JavaScript is required to request device pairing.',
tokenLabel: 'Login token or link',
tokenPlaceholder: '{url}?token=xxx',
tokenPlaceholderFallbackUrl: 'http://<ip>:<port>/',
@@ -31,6 +32,7 @@ export const loginLocales = {
authenticationTitle: '连接到此 Host',
authenticationDescription: '登录以继续',
authenticationUnavailable: '没有可用的登录方式,请联系 Host 管理者',
pairingScriptRequired: '申请设备配对需要启用 JavaScript',
tokenLabel: '登录令牌或链接',
tokenPlaceholder: '{url}?token=xxx',
tokenPlaceholderFallbackUrl: 'http://<ip>:<port>/',
@@ -11,7 +11,9 @@ const pageStyle = `
:root{color-scheme:light dark;font-family:var(--dsw-font-family,-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB','Microsoft YaHei','Helvetica Neue',Helvetica,Arial,sans-serif);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;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)}
.card{display:flex;flex-direction:column;gap:12px;box-sizing:border-box;min-width:0;width:100%;max-width:360px}
.methods{display:grid;gap:24px}
.card:not(:has(.methods)),.methods>*{box-sizing:border-box;min-width:0;padding:24px;border:.5px solid color-mix(in srgb,currentColor 16%,transparent);border-radius:var(--dsw-radius-lg,12px);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)}
@@ -42,9 +44,9 @@ function scriptJson(value: typeof loginLocales): string {
return JSON.stringify(value).replaceAll('<', '\\u003c')
}
function documentHtml(title: string, content: string, script: string): string {
function documentHtml(title: string, content: string, script: string, pairingEnabled = false): 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>`
<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>${pairingEnabled ? '<script defer src="./pairing/client.js"></script>' : ''}</body></html>`
}
/**
@@ -65,7 +67,8 @@ export function enterAuthenticationPage(
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
description.textContent = form === null && document.querySelector('dsh-device-pairing') === null
? t.authenticationUnavailable : t.authenticationDescription
const clean = new URL(location.href)
clean.searchParams.delete('token')
history.replaceState(null, '', clean)
@@ -0,0 +1,145 @@
/** Bounded, process-local requests and repeatable delivery of an approved browser Cookie. */
import { randomBytes, timingSafeEqual } from 'node:crypto'
import type { PairingCredential, PairingDecision, PairingDecisionResult, PairingRequestId, PairingTicket, PendingPairingRequest } from './pairing-types.ts'
/** Deployment limits resolved by the plugin configuration before allocation. */
export interface PairingLimits {
readonly requestTtlMs: number
readonly maxRequests: number
readonly requestIntervalMs: number
readonly pollIntervalMs: number
}
type RequestOutcome =
| { readonly status: 'pending' | 'denied' | 'cancelled' }
| { readonly status: 'approved' }
| { readonly status: 'completed'; readonly cookie: string }
interface PairingRecord {
readonly id: PairingRequestId
readonly code: string
readonly secret: string
readonly authority: string
readonly sourceIp: string | null
readonly expiresAt: number
nextPollAt: number
outcome: RequestOutcome
}
/** State result consumed by the HTTP response owner. */
export type PairingPoll =
| { readonly status: 'pending' | 'denied' | 'cancelled' | 'expired' | 'slow-down' | 'unavailable' }
| { readonly status: 'completed'; readonly cookie: string }
/** Owns one plugin activation's private request tickets and decisions. */
export class PairingRequests {
private readonly records = new Map<PairingRequestId, PairingRecord>()
private nextCreationAt = 0
/** @param limits - complete, validated request lifetime, capacity, and cadence. */
constructor(private readonly limits: PairingLimits) {}
/**
* Allocate one ticket; repeating its identity returns the retained ticket without renewing it.
* Repeated creation cannot change an existing approval, denial, cancellation, or Cookie.
* @param authority - normalized origin accepted by WebServer admission.
* @param sourceIp - normalized IP observed on the creating connection, or null when unavailable.
* @param credential - browser-generated identity and secret retained before the first HTTP request.
* @returns ticket, or undefined on a credential conflict, creation rate limit, or full pool.
*/
create(authority: string, sourceIp: string | null, credential: PairingCredential): PairingTicket | undefined {
this.prune()
const existing = this.records.get(credential.id)
if (existing !== undefined) {
if (existing.authority !== authority || !matches(credential.secret, existing.secret)) return undefined
return { ...this.publicValue(existing), secret: existing.secret, pollIntervalMs: this.limits.pollIntervalMs }
}
const now = Date.now()
if (now < this.nextCreationAt || this.records.size >= this.limits.maxRequests) return undefined
const alphabet = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'
let code: string
do {
code = Array.from(randomBytes(8), byte => alphabet[byte & 31]).join('')
} while (Array.from(this.records.values()).some(record => record.code === code))
const record: PairingRecord = {
...credential, code, authority, sourceIp,
expiresAt: now + this.limits.requestTtlMs,
nextPollAt: now + this.limits.pollIntervalMs,
outcome: { status: 'pending' },
}
this.records.set(record.id, record)
this.nextCreationAt = now + this.limits.requestIntervalMs
return { ...this.publicValue(record), secret: record.secret, pollIntervalMs: this.limits.pollIntervalMs }
}
/**
* Read only pending, unexpired requests without their private credentials.
* @returns rows the owner can approve or deny.
*/
list(): PendingPairingRequest[] {
this.prune()
return Array.from(this.records.values()).filter(record => record.outcome.status === 'pending')
.map(record => this.publicValue(record))
}
/**
* Keep the first decision when owner devices race or retry after a lost response.
* @param id - request selected after comparing the displayed code.
* @param decision - allow or deny access as the owner.
* @returns committed decision or unavailable for an expired, cancelled, or collected request.
*/
decide(id: PairingRequestId, decision: PairingDecision): PairingDecisionResult {
this.prune()
const record = this.records.get(id)
if (record === undefined) return 'unavailable'
if (record.outcome.status === 'pending') record.outcome = { status: decision === 'allow' ? 'approved' : 'denied' }
return record.outcome.status === 'approved' || record.outcome.status === 'denied' ? record.outcome.status : 'unavailable'
}
/**
* Read or cancel one ticket; only approval can sign a Cookie, once per ticket.
* A failed signer leaves the approval intact. A lost delivery can be retried with
* the same secret until expiry, receiving the same Cookie without extending it.
* @param id - applicant's request identity.
* @param secret - private ticket credential, never the display code.
* @param authority - origin of this request, which must match ticket creation.
* @param cancel - withdraw before approved delivery completes.
* @param issueCookie - Remote credential issuer for the current request.
* @returns request state and, only after approval, its retained Cookie.
*/
poll(id: PairingRequestId, secret: string, authority: string, cancel: boolean, issueCookie: () => string | undefined): PairingPoll {
this.prune()
const record = this.records.get(id)
if (record === undefined || record.authority !== authority || !matches(secret, record.secret)) return { status: 'expired' }
if (cancel && record.outcome.status !== 'completed' && record.outcome.status !== 'denied') record.outcome = { status: 'cancelled' }
if (!cancel && Date.now() < record.nextPollAt) return { status: 'slow-down' }
record.nextPollAt = Date.now() + this.limits.pollIntervalMs
if (record.outcome.status === 'approved') {
const cookie = issueCookie()
if (cookie === undefined) return { status: 'unavailable' }
record.outcome = { status: 'completed', cookie }
}
return record.outcome
}
/** Remove every private ticket and retained Cookie when the plugin unloads. */
clear(): void { this.records.clear() }
private prune(): void {
for (const [id, record] of this.records) if (record.expiresAt <= Date.now()) this.records.delete(id)
}
private publicValue(record: PairingRecord): PendingPairingRequest {
return {
id: record.id, code: record.code, authority: record.authority, sourceIp: record.sourceIp,
expiresInMs: record.expiresAt - Date.now(),
}
}
}
function matches(actual: string, expected: string): boolean {
const bytes = Buffer.from(actual)
const target = Buffer.from(expected)
return bytes.length === target.length && timingSafeEqual(bytes, target)
}
@@ -0,0 +1,164 @@
/** Anonymous pairing routes admitted by the WebServer's source policy. */
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { Context } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-client-connection'
import type { ConnectionTrustRequest } from '@deepseek-ai/dsh-client-connection'
import { normalizeBindAddress } from '@deepseek-ai/dsh-host-webserver'
import { z } from 'zod'
import type { PairingRequestId } from './pairing-types.ts'
import type { PairingRequests } from './pairing-requests.ts'
const MAX_BODY_BYTES = 1024
const ticketInput = z.object({ id: z.uuid(), secret: z.string().regex(/^[A-Za-z0-9_-]{43}$/u) }).strict()
type Operation = 'request' | 'status' | 'cancel'
type BodyResult = { readonly status: 'body'; readonly text: string } | { readonly status: 'invalid' | 'too-large' | 'unavailable' }
/**
* Register public POST routes and join in-flight bodies during plugin disposal.
* Bodies above 1KiB receive 413 and close the connection without waiting for the remaining bytes.
* @param ctx - plugin scope carrying the HTTP listener.
* @param requests - this activation's private request pool.
* @param lifetime - plugin lifetime, aborted before retained requests are cleared.
* @param issueCookie - Remote-owned credential issuer, available after initialization.
* @returns disposer that stops and drains requests before withdrawing the routes.
*/
export function registerPairingRoutes(
ctx: Context, requests: PairingRequests, lifetime: AbortController,
issueCookie: (request: ConnectionTrustRequest) => string | undefined,
): () => Promise<void> {
const pending = new Set<Promise<void>>()
return ctx.effect(function* () {
for (const operation of ['request', 'status', 'cancel'] as const) {
yield ctx.webServer.register({
kind: 'exact', path: `/pairing/${operation}`, auth: 'anonymous',
async handler(request, response) {
const task = handleRequest(ctx, requests, lifetime.signal, issueCookie, operation, request, response)
pending.add(task)
try { await task } finally { pending.delete(task) }
},
})
}
yield async () => {
lifetime.abort()
requests.clear()
await Promise.allSettled([...pending])
}
})
}
async function handleRequest(
ctx: Context, requests: PairingRequests, lifetime: AbortSignal,
issueCookie: (request: ConnectionTrustRequest) => string | undefined,
operation: Operation, request: IncomingMessage, response: ServerResponse,
): Promise<void> {
if (lifetime.aborted) {
send(response, 503, { status: 'unavailable' })
return
}
if (request.method !== 'POST') {
send(response, 405, { status: 'invalid' }, { allow: 'POST' })
return
}
const host = request.headers.host as string
// WebServer admission validated the Host; forwarded headers do not select the scheme.
const authority = new URL(`${ctx.webServer.protocol}//${host}`).origin
if (request.headers['content-type']?.split(';', 1)[0]?.trim().toLowerCase() !== 'application/json') {
send(response, 400, { status: 'invalid' })
return
}
const disconnected = new AbortController()
const remoteAddress = request.socket.remoteAddress
const onClose = (): void => { disconnected.abort() }
response.on('close', onClose)
try {
const body = await readBody(request, AbortSignal.any([lifetime, disconnected.signal]))
if (response.destroyed) return
// oxlint-disable-next-line typescript/no-unnecessary-condition -- disposal can abort while the body is awaited
if (lifetime.aborted || body.status === 'unavailable') {
send(response, 503, { status: 'unavailable' })
return
}
if (body.status === 'too-large') {
send(response, 413, { status: 'invalid' }, { connection: 'close' })
request.destroy()
return
}
if (body.status !== 'body') {
send(response, 400, { status: 'invalid' })
return
}
let value: unknown
try { value = JSON.parse(body.text) } catch (_invalidJson) {
// A malformed wire body creates no request and cannot change an existing one.
send(response, 400, { status: 'invalid' })
return
}
const input = ticketInput.safeParse(value)
if (!input.success) {
send(response, 400, { status: 'invalid' })
return
}
if (operation === 'request') {
const ticket = requests.create(authority, remoteAddress === undefined ? null : normalizeBindAddress(remoteAddress), {
id: input.data.id as PairingRequestId, secret: input.data.secret,
})
if (ticket === undefined) send(response, 429, { status: 'busy' })
else send(response, 200, ticket)
return
}
const result = requests.poll(input.data.id as PairingRequestId, input.data.secret, authority,
operation === 'cancel', () => {
const cookie = issueCookie(request)
return cookie !== undefined && new URL(ctx.webApp.getAdvertisedUrl()).protocol === 'https:' && !cookie.includes('; Secure')
? `${cookie}; Secure` : cookie
})
if (result.status === 'completed') {
send(response, 200, { status: 'completed' }, { 'set-cookie': result.cookie })
return
}
send(response, result.status === 'slow-down' ? 429 : result.status === 'unavailable' ? 503 : 200, result)
} catch (error) {
ctx.logger.warn('Pairing login could not complete; the applicant can retry the same request', error)
send(response, 503, { status: 'unavailable' })
} finally {
response.off('close', onClose)
}
}
function send(response: ServerResponse, status: number, body: object, headers: Record<string, string> = {}): void {
response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...headers })
response.end(JSON.stringify(body))
}
function readBody(request: IncomingMessage, signal: AbortSignal): Promise<BodyResult> {
return new Promise((resolve) => {
const chunks: Buffer[] = []
let size = 0
const finish = (result: BodyResult): void => {
request.off('data', onData)
request.off('end', onEnd)
signal.removeEventListener('abort', onAbort)
if (result.status === 'too-large') request.pause()
else request.resume()
resolve(result)
}
const onData = (chunk: Buffer): void => {
size += chunk.byteLength
if (size > MAX_BODY_BYTES) finish({ status: 'too-large' })
else chunks.push(chunk)
}
const onEnd = (): void => { finish({ status: 'body', text: Buffer.concat(chunks, size).toString('utf8') }) }
const onError = (): void => { finish({ status: 'invalid' }) }
const onAbort = (): void => { finish({ status: 'unavailable' }) }
const onClose = (): void => { request.off('error', onError) }
request.on('data', onData)
request.once('end', onEnd)
// A disconnected request may emit its error after the response has closed and settled the body.
request.once('error', onError)
request.once('close', onClose)
signal.addEventListener('abort', onAbort, { once: true })
const declaredLength = request.headers['content-length']
if (declaredLength !== undefined && Number(declaredLength) > MAX_BODY_BYTES) finish({ status: 'too-large' })
})
}
@@ -0,0 +1,44 @@
/** Public pairing-request data; display codes never authenticate an applicant. */
import type { Branded } from '@deepseek-ai/dsh-brand'
/** Opaque identity of one process-local pairing request. */
export type PairingRequestId = Branded<'PairingRequestId'>
/** Browser-generated identity retained across creation retries and cancellation. */
export interface PairingCredential {
readonly id: PairingRequestId
/** Random credential, never the human-readable pairing code. */
readonly secret: string
}
/** Request awaiting the owner's comparison of the displayed code. */
export interface PendingPairingRequest {
readonly id: PairingRequestId
readonly code: string
/** Listener-protocol origin to which the applicant's ticket is bound. */
readonly authority: string
/** IP observed on the creating HTTP connection; null when unavailable. Forwarded headers are ignored. */
readonly sourceIp: string | null
readonly expiresInMs: number
}
/** Private ticket returned only to the requesting browser. */
export interface PairingTicket extends PendingPairingRequest, PairingCredential {
readonly pollIntervalMs: number
}
/** Owner's decision after comparing the two displayed codes. */
export type PairingDecision = 'allow' | 'deny'
/** First committed decision, or a request no longer available for approval. */
export type PairingDecisionResult = 'approved' | 'denied' | 'unavailable'
/** Pending approval rows and the minimum refresh interval. */
export interface PairingRequestsValue {
readonly requests: readonly PendingPairingRequest[]
readonly pollIntervalMs: number
}
/** Anonymous response; the approved Cookie is carried only in Set-Cookie. */
export type PairingStatus = 'pending' | 'denied' | 'cancelled' | 'expired' | 'slow-down' | 'completed' | 'unavailable'
@@ -1,6 +1,8 @@
/** Browser login invitations and deployment availability. */
import type { Branded } from '@deepseek-ai/dsh-brand'
export type * from './pairing-types.ts'
/** Identifier used to inspect or cancel an invitation; it cannot authorize login. */
export type RemoteLoginId = Branded<'remote-login-id'>
@@ -0,0 +1,144 @@
// @vitest-environment jsdom
/** Public custom elements own their work across connection and document suspension. */
import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest'
import { definePairingElement } from '../src/anonymous/element.ts'
import { mountPairing } from '../src/anonymous/pairing.ts'
import { pairingLocales, pairingMethodLabels } from '../src/anonymous/locales.ts'
import { pairingStyles } from '../src/anonymous/styles.ts'
const recovery = { requestTtlMs: 10000, pollIntervalMs: 1000, requestTimeoutMs: 5000, maxRetries: 2, retryMaxDelayMs: 2000 }
const DevicePairingElement = definePairingElement(mountPairing, pairingLocales, pairingMethodLabels, pairingStyles, recovery)
type PairingElement = InstanceType<typeof DevicePairingElement>
const ticket = {
id: 'c647d366-084c-4b7e-9c10-592dd355a4fb', secret: 'a'.repeat(43), code: 'ABCD2345',
authority: 'https://host.example', sourceIp: '192.0.2.17', expiresInMs: 10000, pollIntervalMs: 1000,
}
const request = vi.fn<typeof fetch>()
beforeEach(() => {
vi.useFakeTimers()
vi.stubGlobal('fetch', request)
request.mockReset().mockImplementation(async (_input, init) => {
if (typeof init?.body !== 'string') throw new Error('Missing creation credentials')
const held = JSON.parse(init.body) as { id: string; secret: string }
return new Response(JSON.stringify({ ...ticket, ...held }))
})
document.head.innerHTML = '<base href="https://host.example/tools/dsh/">'
})
afterEach(() => {
document.body.replaceChildren()
document.head.replaceChildren()
vi.unstubAllGlobals()
vi.restoreAllMocks()
vi.useRealTimers()
})
function mount(): PairingElement {
const element = document.createElement('dsh-device-pairing')
if (!(element instanceof DevicePairingElement)) throw new Error('Pairing element is not defined')
document.body.append(element)
return element
}
async function create(element: PairingElement): Promise<void> {
element.querySelector<HTMLButtonElement>('#auth-pair-request')!.click()
await vi.advanceTimersByTimeAsync(0)
}
it('defines and mounts independently of authenticated Client modules, with instance-owned styles', () => {
const element = mount()
expect(element.querySelector('h2')?.textContent).toBe('Pair this device')
expect(element.querySelectorAll('style')).toHaveLength(1)
expect(element.querySelector('button')?.classList.contains('dsh-device-pairing-button')).toBe(true)
expect(element.querySelector('button')?.classList.contains('dsh-device-pairing-primary')).toBe(true)
expect(element.querySelector('button')?.textContent).toBe('Request to pair')
expect(element.querySelector('p')?.textContent).toContain('Settings → Remote connection')
expect(element.querySelector('p')?.closest('[hidden]')).toBeNull()
expect(request).not.toHaveBeenCalled()
element.connectedCallback()
expect(element.querySelectorAll('section')).toHaveLength(1)
element.remove()
expect(element.childNodes).toHaveLength(0)
expect(vi.getTimerCount()).toBe(0)
})
it.each([
['zh-CN', '配对此设备', '申请配对'],
['de-DE', 'Pair this device', 'Kopplung anfordern'],
['unknown', 'Pair this device', 'Request to pair'],
])('selects public copy for browser language %s without the application locale service', (language, title, label) => {
vi.spyOn(window.navigator, 'language', 'get').mockReturnValue(language)
const element = mount()
expect(element.querySelector('h2')?.textContent).toBe(title)
expect(element.querySelector('button')?.textContent).toBe(label)
})
it('aborts an unfinished creation on removal and reconnects without accepting its late ticket', async () => {
const pending = Promise.withResolvers<Response>()
request.mockReturnValueOnce(pending.promise)
const element = mount()
await create(element)
const signal = request.mock.calls[0]?.[1]?.signal
element.remove()
expect(signal?.aborted).toBe(true)
document.body.append(element)
pending.resolve(new Response(JSON.stringify(ticket)))
await vi.advanceTimersByTimeAsync(0)
expect(element.querySelector<HTMLElement>('#auth-pair-panel')?.hidden).toBe(true)
expect(element.textContent).not.toContain('ABCD 2345')
expect(vi.getTimerCount()).toBe(0)
await create(element)
expect(request).toHaveBeenCalledTimes(2)
expect(element.querySelector('#auth-pair-code')?.textContent).toBe('ABCD 2345')
element.remove()
expect(vi.getTimerCount()).toBe(0)
window.dispatchEvent(new Event('pageshow'))
expect(request).toHaveBeenCalledTimes(2)
})
it('retains the private ticket across BFCache suspension and resumes its status read', async () => {
const element = mount()
await create(element)
window.dispatchEvent(new Event('pagehide'))
expect(element.isConnected).toBe(true)
expect(element.querySelector('#auth-pair-code')?.textContent).toBe('ABCD 2345')
expect(vi.getTimerCount()).toBe(0)
request.mockResolvedValueOnce(new Response('{"status":"pending"}'))
window.dispatchEvent(new Event('pageshow'))
await vi.advanceTimersByTimeAsync(0)
expect(request).toHaveBeenCalledTimes(2)
expect(request.mock.calls[1]?.[0]).toEqual(new URL('https://host.example/tools/dsh/pairing/status'))
expect(request.mock.calls[1]?.[1]?.body).toBe(request.mock.calls[0]?.[1]?.body)
expect(element.querySelector('#auth-pair-panel')?.getAttribute('data-state')).toBe('waiting')
})
it('waits for a browsing context before mounting an adopted element', () => {
const doc = document.implementation.createHTMLDocument('Detached document')
const element = document.createElement('dsh-device-pairing')
doc.adoptNode(element)
doc.body.append(element)
expect(element.childNodes).toHaveLength(0)
expect(request).not.toHaveBeenCalled()
document.adoptNode(element)
document.body.append(element)
expect(element.querySelector('#auth-pair-request')).not.toBeNull()
})
it('navigates to the clean application URL after collecting approval and stops polling', async () => {
const original = window.location.href
onTestFinished(() => { window.history.replaceState(null, '', original) })
const base = new URL('.', original)
document.head.replaceChildren()
window.history.replaceState(null, '', `${base.href}#waiting`)
const element = mount()
await create(element)
request.mockResolvedValueOnce(new Response('{"status":"completed"}'))
await vi.advanceTimersByTimeAsync(1000)
expect(window.location.href).toBe(base.href)
expect(request).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(10000)
expect(request).toHaveBeenCalledTimes(2)
expect(vi.getTimerCount()).toBe(0)
})
@@ -0,0 +1,66 @@
// @vitest-environment jsdom
/** The generated HTTP script runs without its Host module's lexical scope. */
import { spawnSync } from 'node:child_process'
import { resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { afterEach, expect, it, vi } from 'vitest'
import { renderPairingScript } from '../src/anonymous/index.ts'
import { renderAuthenticationPage } from '../src/login-page.ts'
const recovery = { requestTtlMs: 10000, pollIntervalMs: 1000, requestTimeoutMs: 5000, maxRetries: 2, retryMaxDelayMs: 2000 }
afterEach(() => {
document.body.replaceChildren()
document.head.replaceChildren()
vi.unstubAllGlobals()
vi.restoreAllMocks()
vi.useRealTimers()
})
it('mounts, requests, and cancels pairing from the source-launched classic script', async ({ task }) => {
// The dsh source launcher applies tsx name preservation that Vitest's transform does not.
const entry = pathToFileURL(resolve(import.meta.dirname, '../src/anonymous/index.ts')).href
const generated = spawnSync(process.execPath, ['--import', 'tsx/esm', '--input-type=module', '--eval',
`import { renderPairingScript } from ${JSON.stringify(entry)}; process.stdout.write(renderPairingScript(${JSON.stringify(recovery)}))`,
], { encoding: 'utf8', timeout: task.timeout })
expect(generated.error).toBeUndefined()
expect(generated.signal).toBeNull()
expect(generated.status, generated.stderr).toBe(0)
vi.useFakeTimers()
const ticket = {
id: 'c647d366-084c-4b7e-9c10-592dd355a4fb', secret: 'a'.repeat(43), code: 'ABCD2345',
authority: 'https://host.example', sourceIp: null, expiresInMs: 10000, pollIntervalMs: 1000,
}
const request = vi.fn<typeof fetch>()
.mockImplementationOnce(async (_input, init) => {
if (typeof init?.body !== 'string') throw new Error('Missing creation credentials')
const held = JSON.parse(init.body) as { id: string; secret: string }
return new Response(JSON.stringify({ ...ticket, ...held }))
})
.mockResolvedValueOnce(new Response('{"status":"cancelled"}'))
vi.stubGlobal('fetch', request)
const html = new DOMParser().parseFromString(renderAuthenticationPage({ tokenLoginEnabled: true, pairingEnabled: true }), 'text/html')
document.documentElement.innerHTML = html.documentElement.innerHTML
document.head.insertAdjacentHTML('afterbegin', '<base href="https://host.example/tools/dsh/">')
window.eval(generated.stdout)
const element = document.querySelector('dsh-device-pairing')!
expect(element.querySelector('style')?.textContent).toContain('.dsh-device-pairing-code')
expect(document.querySelector('#token-form')).not.toBeNull()
expect(document.querySelector('script[src]')?.getAttribute('src')).toBe('./pairing/client.js')
expect('__ModuleLoader__' in window).toBe(false)
element.querySelector<HTMLButtonElement>('#auth-pair-request')!.click()
await vi.advanceTimersByTimeAsync(0)
expect(element.querySelector('#auth-pair-code')?.textContent).toBe('ABCD 2345')
element.querySelector<HTMLButtonElement>('#auth-pair-cancel')!.click()
await vi.advanceTimersByTimeAsync(0)
expect(request.mock.calls[1]?.[1]?.body).toBe(request.mock.calls[0]?.[1]?.body)
expect(element.querySelector('#auth-pair-panel')?.getAttribute('data-state')).toBe('cancelled')
expect(vi.getTimerCount()).toBe(0)
})
it('escapes public data that could otherwise close an embedded script', () => {
vi.spyOn(JSON, 'stringify').mockReturnValueOnce('{"title":"</script><img src=x>"}')
const script = renderPairingScript(recovery)
expect(script).not.toContain('</script')
expect(script).toContain('\\u003c/script>\\u003cimg src=x>')
})
@@ -0,0 +1,579 @@
// @vitest-environment jsdom
/** Anonymous recovery keeps one Host request through transport failures and replaces it only after cancellation. */
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import type { PairingCredential, PairingTicket } from '../src/pairing-types.ts'
import { PairingRequests } from '../src/pairing-requests.ts'
import { mountPairing, type PairingRecovery } from '../src/anonymous/pairing.ts'
import { pairingLocales, pairingMethodLabels } from '../src/anonymous/locales.ts'
const recovery: PairingRecovery = {
requestTtlMs: 30_000, pollIntervalMs: 1000, requestTimeoutMs: 500, maxRetries: 2, retryMaxDelayMs: 2000,
}
let dispose: (() => void) | undefined
beforeEach(() => {
vi.useFakeTimers()
document.head.innerHTML = '<base href="https://host.example/tools/dsh/">'
document.body.innerHTML = '<div id="pairing-method"></div>'
})
afterEach(() => {
dispose?.()
dispose = undefined
vi.useRealTimers()
vi.restoreAllMocks()
document.head.replaceChildren()
document.body.replaceChildren()
})
function payload(init: RequestInit | undefined): PairingCredential {
if (typeof init?.body !== 'string') throw new Error('Missing private request credential')
return JSON.parse(init.body) as PairingCredential
}
function url(input: Parameters<typeof fetch>[0] | undefined): string {
if (input === undefined) throw new Error('Missing request URL')
return input instanceof Request ? input.url : input.toString()
}
function fixture(language = 'zh', overrides: Partial<PairingRecovery> = {}) {
const policy = { ...recovery, ...overrides }
const pool = new PairingRequests({ ...policy, maxRequests: 32, requestIntervalMs: 1 })
let last: PairingTicket | undefined
let loggedIn = false
const issue = vi.fn(() => 'cookie')
const request = vi.fn<typeof fetch>().mockImplementation(async (input, init) => {
if (init?.method === 'HEAD') return new Response(null, { status: loggedIn ? 200 : 401 })
const held = payload(init)
if (url(input).endsWith('/request')) {
const ticket = pool.create('https://host.example', '192.0.2.17', held)
if (ticket === undefined) return new Response('{"status":"busy"}', { status: 429 })
last = ticket
return new Response(JSON.stringify(ticket))
}
const result = pool.poll(held.id, held.secret, 'https://host.example', url(input).endsWith('/cancel'), issue)
if (result.status === 'completed') loggedIn = true
return new Response(JSON.stringify(result), { status: result.status === 'slow-down' ? 429 : 200 })
})
const navigate = vi.fn<(value: string) => void>()
const method = document.querySelector<HTMLElement>('#pairing-method')!
dispose = mountPairing(method, {}, language === 'zh' ? pairingLocales.zh : pairingLocales.en,
pairingMethodLabels[language] ?? pairingMethodLabels.en, { request, navigate }, policy)
return {
request, navigate, pool, issue,
ticket() { if (last === undefined) throw new Error('No ticket received'); return last },
approve() { if (last === undefined) throw new Error('No ticket received'); pool.decide(last.id, 'allow') },
}
}
function button(id: string): HTMLButtonElement {
const result = document.getElementById(`auth-pair-${id}`)
if (!(result instanceof HTMLButtonElement)) throw new Error(`Missing ${id} button`)
return result
}
function state(): string | undefined { return document.getElementById('auth-pair-panel')?.dataset.state }
async function create(): Promise<void> { button('request').click(); await vi.advanceTimersByTimeAsync(0) }
it('keeps credentials out of the DOM, polls the mounted application, and signs in automatically', async () => {
const f = fixture()
await create()
const ticket = f.ticket()
expect(ticket.id).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u)
expect(ticket.secret).toMatch(/^[A-Za-z0-9_-]{43}$/u)
expect(document.body.innerHTML).not.toContain(ticket.secret)
expect(document.getElementById('auth-pair-retry')).toBeNull()
expect(button('request').textContent).toBe('重新申请')
expect(button('request').disabled).toBe(false)
expect(url(f.request.mock.calls[0]?.[0])).toBe('https://host.example/tools/dsh/pairing/request')
f.approve()
await vi.advanceTimersByTimeAsync(1000)
expect(f.request.mock.calls[1]?.[1]).toMatchObject({
method: 'POST', credentials: 'same-origin', cache: 'no-store', body: JSON.stringify({ id: ticket.id, secret: ticket.secret }),
})
expect(f.issue).toHaveBeenCalledOnce()
expect(f.navigate).toHaveBeenCalledExactlyOnceWith('https://host.example/tools/dsh/')
expect(vi.getTimerCount()).toBe(0)
})
it('retries a lost creation response with the same credentials without duplicating the Host request', async () => {
const f = fixture()
const normal = f.request.getMockImplementation()!
f.request.mockImplementationOnce(async (...args) => { await normal(...args); throw new Error('response lost') })
await create()
const original = f.ticket()
expect(f.pool.list()).toHaveLength(1)
expect(state()).toBe('creating')
expect(document.querySelector('[role="alert"]')).toBeNull()
await vi.advanceTimersByTimeAsync(1000)
expect(f.request.mock.calls[1]?.[1]?.body).toBe(f.request.mock.calls[0]?.[1]?.body)
expect(f.ticket().id).toBe(original.id)
expect(f.ticket().expiresInMs).toBe(29_000)
expect(f.pool.list()).toHaveLength(1)
expect(state()).toBe('waiting')
})
it.each(['zh', 'en'])('automatically backs off status failures and exposes only Request again after exhaustion in %s', async (language) => {
const f = fixture(language)
await create()
const original = f.ticket()
f.request.mockRejectedValueOnce(new Error('offline'))
.mockResolvedValueOnce(new Response('{"status":"unavailable"}', { status: 503 }))
.mockRejectedValueOnce(new Error('offline'))
await vi.advanceTimersByTimeAsync(1000)
expect(f.request).toHaveBeenCalledTimes(2)
expect(document.querySelector('[role="alert"]')).toBeNull()
await vi.advanceTimersByTimeAsync(999)
expect(f.request).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(1)
expect(f.request).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(1999)
expect(f.request).toHaveBeenCalledTimes(3)
await vi.advanceTimersByTimeAsync(1)
expect(state()).toBe('error')
expect(document.querySelector('[role="alert"]')?.textContent).toBe(language === 'zh' ? pairingLocales.zh.pairError : pairingLocales.en.pairError)
expect(button('request').disabled).toBe(false)
expect(document.getElementById('auth-pair-retry')).toBeNull()
expect(vi.getTimerCount()).toBe(0)
await create()
expect(f.pool.decide(original.id, 'allow')).toBe('unavailable')
expect(f.ticket().id).not.toBe(original.id)
expect(f.pool.list().map(row => row.id)).toEqual([f.ticket().id])
expect(state()).toBe('waiting')
})
it.each(['headers', 'body'] as const)('times out stalled response %s and ignores its late completion after a successful retry', async (part) => {
const f = fixture()
await create()
const heldResponse = Promise.withResolvers<Response>()
const heldBody = Promise.withResolvers<unknown>()
const response = new Response('{"status":"completed"}')
if (part === 'body') vi.spyOn(response, 'json').mockReturnValue(heldBody.promise)
f.request.mockReturnValueOnce(part === 'headers' ? heldResponse.promise : Promise.resolve(response))
await vi.advanceTimersByTimeAsync(1000)
const signal = f.request.mock.calls[1]?.[1]?.signal
await vi.advanceTimersByTimeAsync(499)
expect(signal?.aborted).toBe(false)
await vi.advanceTimersByTimeAsync(1)
expect(signal?.aborted).toBe(true)
f.approve()
await vi.advanceTimersByTimeAsync(1000)
expect(f.navigate).toHaveBeenCalledOnce()
heldResponse.resolve(response)
heldBody.resolve({ status: 'completed' })
await vi.advanceTimersByTimeAsync(0)
expect(f.navigate).toHaveBeenCalledOnce()
expect(f.issue).toHaveBeenCalledOnce()
expect(vi.getTimerCount()).toBe(0)
})
it('can replace while the old status request is in flight without accepting its late result', async () => {
const f = fixture()
await create()
const original = f.ticket()
const old = Promise.withResolvers<Response>()
f.request.mockReturnValueOnce(old.promise)
await vi.advanceTimersByTimeAsync(1000)
const oldSignal = f.request.mock.calls[1]?.[1]?.signal
expect(button('request').disabled).toBe(false)
await create()
const replacement = f.ticket()
expect(oldSignal?.aborted).toBe(true)
expect(replacement.id).not.toBe(original.id)
expect(f.pool.decide(original.id, 'allow')).toBe('unavailable')
expect(f.pool.list().map(row => row.id)).toEqual([replacement.id])
old.resolve(new Response('{"status":"completed"}'))
await vi.advanceTimersByTimeAsync(0)
expect(f.navigate).not.toHaveBeenCalled()
f.approve()
await vi.advanceTimersByTimeAsync(1000)
expect(f.navigate).toHaveBeenCalledOnce()
})
it('recovers a creation identity before cancelling it and starting a different request', async () => {
const f = fixture()
const normal = f.request.getMockImplementation()!
const old = Promise.withResolvers<Response>()
let original: Response | undefined
f.request.mockImplementationOnce(async (...args) => { original = await normal(...args); return old.promise })
await create()
const first = f.ticket()
const oldSignal = f.request.mock.calls[0]?.[1]?.signal
button('cancel').click()
await vi.advanceTimersByTimeAsync(0)
expect(oldSignal?.aborted).toBe(true)
expect(f.request.mock.calls[1]?.[1]?.body).toBe(f.request.mock.calls[0]?.[1]?.body)
expect(f.pool.list()).toEqual([])
expect(state()).toBe('cancelled')
await vi.advanceTimersByTimeAsync(1)
await create()
expect(f.ticket().id).not.toBe(first.id)
old.resolve(original!)
await vi.advanceTimersByTimeAsync(0)
expect(f.pool.list().map(row => row.id)).toEqual([f.ticket().id])
expect(f.navigate).not.toHaveBeenCalled()
expect(state()).toBe('waiting')
})
it('does not create a replacement when cancellation remains unknown after retries', async () => {
const f = fixture()
await create()
const first = f.ticket()
f.request.mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce(new Error('offline'))
await create()
await vi.advanceTimersByTimeAsync(3000)
expect(state()).toBe('error')
expect(f.request.mock.calls.filter(([input]) => url(input).endsWith('/request'))).toHaveLength(1)
expect(f.pool.list().map(row => row.id)).toEqual([first.id])
await create()
expect(f.pool.decide(first.id, 'allow')).toBe('unavailable')
expect(f.ticket().id).not.toBe(first.id)
expect(f.pool.list()).toHaveLength(1)
})
it('collects a completed old request instead of creating another when cancellation races delivery', async () => {
const f = fixture()
await create()
f.approve()
const normal = f.request.getMockImplementation()!
const body = Promise.withResolvers<unknown>()
f.request.mockImplementationOnce(async (...args) => {
const response = await normal(...args)
vi.spyOn(response, 'json').mockReturnValue(body.promise)
return response
})
await vi.advanceTimersByTimeAsync(1000)
await create()
expect(f.navigate).toHaveBeenCalledOnce()
expect(f.issue).toHaveBeenCalledOnce()
expect(f.request.mock.calls.filter(([input]) => url(input).endsWith('/request'))).toHaveLength(1)
body.resolve({ status: 'completed' })
await vi.advanceTimersByTimeAsync(0)
expect(f.navigate).toHaveBeenCalledOnce()
})
it.each([200, 401])('automatically checks browser authorization at expiry and handles HTTP %s', async (status) => {
const f = fixture('zh', { requestTtlMs: 2000 })
await create()
f.request.mockResolvedValueOnce(new Response('{"status":"pending"}'))
.mockResolvedValueOnce(new Response(null, { status }))
await vi.advanceTimersByTimeAsync(2000)
expect(f.request.mock.calls[2]?.[1]).toMatchObject({ method: 'HEAD', credentials: 'same-origin', cache: 'no-store', redirect: 'error' })
expect(f.navigate).toHaveBeenCalledTimes(status === 200 ? 1 : 0)
if (status === 401) expect(state()).toBe('expired')
expect(vi.getTimerCount()).toBe(0)
})
it('retries a hung authorization check automatically and preserves the ticket when the retry budget is exhausted', async () => {
const f = fixture('zh', { requestTtlMs: 2000 })
await create()
const held = Promise.withResolvers<Response>()
f.request.mockResolvedValueOnce(new Response('{"status":"pending"}')).mockReturnValueOnce(held.promise)
.mockResolvedValueOnce(new Response(null, { status: 503 })).mockRejectedValueOnce(new Error('offline'))
await vi.advanceTimersByTimeAsync(5500)
expect(state()).toBe('error')
expect(document.querySelector('[role="alert"]')?.textContent).toBe(pairingLocales.zh.pairCheckError)
expect(button('request').disabled).toBe(false)
expect(f.request.mock.calls.filter(([input]) => url(input).endsWith('/request'))).toHaveLength(1)
await create()
expect(f.request.mock.calls.at(-3)?.[1]?.method).toBe('HEAD')
expect(state()).toBe('waiting')
expect(f.request.mock.calls.filter(([input]) => url(input).endsWith('/request'))).toHaveLength(2)
held.resolve(new Response(null, { status: 200 }))
await vi.advanceTimersByTimeAsync(0)
expect(f.navigate).not.toHaveBeenCalled()
})
it('checks a delivered Cookie when a completed response body crosses the local deadline', async () => {
const f = fixture('zh', { requestTtlMs: 2000, requestTimeoutMs: 5000 })
await create()
f.approve()
const normal = f.request.getMockImplementation()!
const body = Promise.withResolvers<unknown>()
f.request.mockImplementationOnce(async (...args) => {
const response = await normal(...args)
vi.spyOn(response, 'json').mockReturnValue(body.promise)
return response
})
await vi.advanceTimersByTimeAsync(2000)
expect(f.navigate).toHaveBeenCalledOnce()
body.resolve({ status: 'completed' })
await vi.advanceTimersByTimeAsync(0)
expect(f.navigate).toHaveBeenCalledOnce()
expect(f.issue).toHaveBeenCalledOnce()
})
it('checks authorization after Host-reported expiry rather than creating a request immediately', async () => {
const f = fixture()
await create()
f.request.mockResolvedValueOnce(new Response('{"status":"expired"}'))
await vi.advanceTimersByTimeAsync(1000)
expect(f.request.mock.calls[2]?.[1]?.method).toBe('HEAD')
expect(state()).toBe('expired')
expect(f.request).toHaveBeenCalledTimes(4)
})
it.each(['denied', 'cancelled'])('ends waiting on %s and permits a new approval flow', async (status) => {
const f = fixture()
await create()
f.request.mockResolvedValueOnce(new Response(JSON.stringify({ status })))
await vi.advanceTimersByTimeAsync(1000)
expect(state()).toBe(status)
expect(vi.getTimerCount()).toBe(0)
await create()
expect(state()).toBe('waiting')
})
it.each([
['request', '{"status":"forbidden"}'], ['request', 'Forbidden'],
['status', 'Forbidden'], ['cancel', 'Forbidden'],
] as const)('does not retry a permanent %s refusal with body %s', async (operation, body) => {
const f = fixture()
if (operation !== 'request') await create()
const before = f.request.mock.calls.length
const response = new Response(body, { status: 403 })
const json = vi.spyOn(response, 'json')
f.request.mockResolvedValueOnce(response)
if (operation === 'status') await vi.advanceTimersByTimeAsync(1000)
else if (operation === 'cancel') { button('cancel').click(); await vi.advanceTimersByTimeAsync(0) }
else await create()
expect(state()).toBe('error')
expect(f.request).toHaveBeenCalledTimes(before + 1)
expect(f.request.mock.calls[before]?.[1]?.signal?.aborted).toBe(true)
expect(json).not.toHaveBeenCalled()
expect(f.navigate).not.toHaveBeenCalled()
expect(f.issue).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
})
it.each(['request', 'status', 'cancel'] as const)('does not accept invalid JSON from a successful %s response', async (operation) => {
const f = fixture()
if (operation !== 'request') await create()
const before = f.request.mock.calls.length
f.request.mockImplementation(async () => new Response('not JSON'))
if (operation === 'status') await vi.advanceTimersByTimeAsync(1000)
else if (operation === 'cancel') { button('cancel').click(); await vi.advanceTimersByTimeAsync(0) }
else await create()
await vi.advanceTimersByTimeAsync(3000)
expect(state()).toBe('error')
expect(f.request).toHaveBeenCalledTimes(before + 3)
expect(f.navigate).not.toHaveBeenCalled()
expect(f.issue).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
})
it('caps retry delays and restarts the budget after a successful pending response', async () => {
const f = fixture('zh', { maxRetries: 4, retryMaxDelayMs: 1500 })
await create()
f.request.mockRejectedValueOnce(new Error('offline')).mockRejectedValueOnce(new Error('offline'))
.mockRejectedValueOnce(new Error('offline')).mockResolvedValueOnce(new Response('{"status":"pending"}'))
await vi.advanceTimersByTimeAsync(5000)
expect(f.request).toHaveBeenCalledTimes(5)
f.request.mockRejectedValueOnce(new Error('offline'))
await vi.advanceTimersByTimeAsync(1000)
expect(f.request).toHaveBeenCalledTimes(6)
f.approve()
await vi.advanceTimersByTimeAsync(1000)
expect(f.navigate).toHaveBeenCalledOnce()
})
it.each(['delay', 'request'] as const)('cancels all work on disposal during a retry %s', async (phase) => {
const f = fixture()
const held = Promise.withResolvers<Response>()
if (phase === 'request') f.request.mockReturnValueOnce(held.promise)
else f.request.mockRejectedValueOnce(new Error('offline'))
await create()
const signal = f.request.mock.calls[0]?.[1]?.signal
dispose?.()
dispose = undefined
if (phase === 'request') expect(signal?.aborted).toBe(true)
expect(vi.getTimerCount()).toBe(0)
held.resolve(new Response('{}'))
await vi.advanceTimersByTimeAsync(60_000)
expect(f.request).toHaveBeenCalledOnce()
expect(f.navigate).not.toHaveBeenCalled()
})
it('resumes an interrupted creation with its original identity after BFCache suspension', async () => {
const f = fixture()
const normal = f.request.getMockImplementation()!
const held = Promise.withResolvers<Response>()
let original: Response | undefined
f.request.mockImplementationOnce(async (...args) => { original = await normal(...args); return held.promise })
await create()
window.dispatchEvent(new Event('pagehide'))
expect(vi.getTimerCount()).toBe(0)
window.dispatchEvent(new Event('pageshow'))
await vi.advanceTimersByTimeAsync(0)
expect(f.request.mock.calls[1]?.[1]?.body).toBe(f.request.mock.calls[0]?.[1]?.body)
expect(f.pool.list()).toHaveLength(1)
held.resolve(original!)
await vi.advanceTimersByTimeAsync(0)
expect(state()).toBe('waiting')
})
it.each([
['id', 'wrong'], ['secret', 'wrong'], ['code', 'bad'], ['authority', ''], ['sourceIp', 1],
['expiresInMs', 0], ['expiresInMs', 0.5], ['pollIntervalMs', 0], ['pollIntervalMs', 1.5],
] as const)('rejects a malformed creation field %s=%s without polling', async (field, value) => {
const f = fixture()
const normal = f.request.getMockImplementation()!
f.request.mockImplementationOnce(async (...args) => {
const response = await normal(...args)
return new Response(JSON.stringify({ ...await response.json(), [field]: value }))
})
await create()
expect(state()).toBe('error')
expect(vi.getTimerCount()).toBe(0)
expect(f.navigate).not.toHaveBeenCalled()
})
it('waits for an attached browsing context before mounting', () => {
const detached = document.implementation.createHTMLDocument('Detached')
const method = detached.createElement('div')
const release = mountPairing(method, {}, pairingLocales.en, pairingMethodLabels.en,
{ request: vi.fn<typeof fetch>(), navigate: vi.fn() }, recovery)
release()
expect(method.childNodes).toHaveLength(0)
})
it.each([null, 'invalid'])('rejects a non-object creation response: %s', async (value) => {
const f = fixture()
f.request.mockResolvedValueOnce(new Response(JSON.stringify(value)))
await create()
expect(state()).toBe('error')
expect(f.request).toHaveBeenCalledOnce()
expect(vi.getTimerCount()).toBe(0)
})
it('cancels a Host request that outlives the local countdown because creation arrived later', async () => {
const f = fixture('zh', { requestTtlMs: 2000 })
const normal = f.request.getMockImplementation()!
const received = Promise.withResolvers<undefined>()
f.request.mockImplementationOnce(async (...args) => { await received.promise; return normal(...args) })
await create()
await vi.advanceTimersByTimeAsync(100)
received.resolve(undefined)
await vi.advanceTimersByTimeAsync(0)
const first = f.ticket()
await vi.advanceTimersByTimeAsync(1900)
expect(state()).toBe('expired')
expect(f.pool.decide(first.id, 'allow')).toBe('unavailable')
expect(f.pool.list()).toEqual([])
expect(url(f.request.mock.calls.at(-1)?.[0])).toMatch(/\/pairing\/cancel$/u)
await create()
expect(f.pool.list().map(row => row.id)).toEqual([f.ticket().id])
})
it.each(['replace', 'cancel'] as const)('settles an interrupted %s at the deadline before another request can start', async (action) => {
const f = fixture('zh', { requestTtlMs: 2000, requestTimeoutMs: 5000 })
await create()
const old = Promise.withResolvers<Response>()
f.request.mockResolvedValueOnce(new Response('{"status":"pending"}'))
await vi.advanceTimersByTimeAsync(1000)
f.request.mockReturnValueOnce(old.promise)
if (action === 'replace') await create()
else { button('cancel').click(); await vi.advanceTimersByTimeAsync(0) }
await vi.advanceTimersByTimeAsync(1000)
expect(state()).toBe(action === 'replace' ? 'waiting' : 'cancelled')
expect(f.request.mock.calls.filter(([input]) => url(input).endsWith('/request'))).toHaveLength(action === 'replace' ? 2 : 1)
old.resolve(new Response('{"status":"completed"}'))
await vi.advanceTimersByTimeAsync(0)
expect(f.navigate).not.toHaveBeenCalled()
})
it.each(['request', 'cancel'] as const)('checks expiry when decoding a %s creation response consumes its remaining lifetime', async (action) => {
const f = fixture('zh', { requestTtlMs: 2000 })
const normal = f.request.getMockImplementation()!
const pending = Promise.withResolvers<Response>()
if (action === 'cancel') {
f.request.mockReturnValueOnce(pending.promise)
await create()
}
f.request.mockImplementationOnce(async (...args) => {
const response = await normal(...args)
const json = response.json.bind(response)
vi.spyOn(response, 'json').mockImplementation(async () => {
const value: unknown = await json()
vi.spyOn(performance, 'now').mockReturnValue(2001)
return value
})
return response
})
if (action === 'request') await create()
else { button('cancel').click(); await vi.advanceTimersByTimeAsync(0) }
expect(state()).toBe(action === 'request' ? 'expired' : 'cancelled')
expect(f.pool.list()).toEqual([])
expect(f.navigate).not.toHaveBeenCalled()
pending.resolve(new Response('{}'))
await vi.advanceTimersByTimeAsync(0)
})
it('ignores a disposed authorization check and does not restart it on pageshow', async () => {
const f = fixture('zh', { requestTtlMs: 2000 })
await create()
const old = Promise.withResolvers<Response>()
f.request.mockResolvedValueOnce(new Response('{"status":"pending"}')).mockReturnValueOnce(old.promise)
await vi.advanceTimersByTimeAsync(2000)
expect(state()).toBe('checking')
dispose?.()
dispose = undefined
old.resolve(new Response(null, { status: 200 }))
window.dispatchEvent(new Event('pageshow'))
await vi.advanceTimersByTimeAsync(0)
expect(f.navigate).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
})
it('does not duplicate a pending action when queued clicks arrive after controls become disabled', async () => {
const f = fixture()
const old = Promise.withResolvers<Response>()
f.request.mockReturnValueOnce(old.promise)
await create()
button('request').dispatchEvent(new Event('click'))
expect(f.request).toHaveBeenCalledOnce()
button('cancel').click()
button('cancel').dispatchEvent(new Event('click'))
await vi.advanceTimersByTimeAsync(0)
expect(state()).toBe('cancelled')
expect(f.pool.list()).toEqual([])
old.resolve(new Response('{}'))
await vi.advanceTimersByTimeAsync(0)
})
it('resumes without issuing requests when no applicant exists and ignores duplicate pageshow', async () => {
const f = fixture()
window.dispatchEvent(new Event('pageshow'))
window.dispatchEvent(new Event('pagehide'))
button('request').click()
button('cancel').dispatchEvent(new Event('click'))
window.dispatchEvent(new Event('pageshow'))
window.dispatchEvent(new Event('pageshow'))
expect(f.request).not.toHaveBeenCalled()
await create()
window.dispatchEvent(new Event('pagehide'))
window.dispatchEvent(new Event('pageshow'))
await vi.advanceTimersByTimeAsync(1000)
expect(f.request.mock.calls.filter(([input]) => url(input).endsWith('/request'))).toHaveLength(1)
expect(state()).toBe('waiting')
})
it.each(['replace', 'cancel'] as const)('checks authorization when a %s response reports Host expiry', async (action) => {
const f = fixture()
await create()
f.request.mockResolvedValueOnce(new Response('{"status":"expired"}'))
if (action === 'replace') await create()
else { button('cancel').click(); await vi.advanceTimersByTimeAsync(0) }
expect(f.request.mock.calls[2]?.[1]?.method).toBe('HEAD')
if (action === 'replace') await vi.advanceTimersByTimeAsync(1000)
expect(state()).toBe(action === 'replace' ? 'waiting' : 'cancelled')
})
it('recovers and cancels an unknown creation after its local deadline before enabling another applicant', async () => {
const f = fixture('zh', { requestTtlMs: 2000 })
const old = Promise.withResolvers<Response>()
f.request.mockReturnValueOnce(old.promise).mockReturnValueOnce(old.promise)
await create()
await vi.advanceTimersByTimeAsync(2000)
expect(state()).toBe('expired')
expect(f.pool.list()).toEqual([])
expect(url(f.request.mock.calls.at(-1)?.[0])).toMatch(/\/pairing\/cancel$/u)
old.resolve(new Response('{}'))
await vi.advanceTimersByTimeAsync(0)
expect(f.navigate).not.toHaveBeenCalled()
})
@@ -5,17 +5,22 @@ import { createElement, Fragment, useState } from 'react'
import { act, cleanup, fireEvent, render, screen, within } 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 { createSlotRenderer, StaticRemoteAccess } 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 { apply as resourcesApply, inject as resourcesInject } from '@deepseek-ai/dsh-client-resources/client'
import type { PairingRequestId } from '../src/types.ts'
import type { PairingInjected } from '../src/client/PairingRequests.tsx'
import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'
import type { RemoteConnectionContentProps, RemoteConnectionExtensionProps } from '@deepseek-ai/dsh-client-remote-connection/client'
import { en, zh } from '../src/client/locales.ts'
import { apply, inject } from '../src/client/index.ts'
vi.mock('@deepseek-ai/dsh-client-remote-connection/remote', async () => import('./remote-fixture.ts'))
afterEach(cleanup)
function Root({ renderSlot, close }: PropsRenderSlots<'settings.section' | 'shell.overlay'> & Pick<RemoteConnectionContentProps, 'close'>) {
@@ -86,6 +91,8 @@ async function bench(call: ConnectionHandle['rpc']['call'], beforeMount?: (ctx:
} satisfies ConnectionHandle)
await ctx.plugin({ inject: [...gatewayInject], apply: gatewayApply }).await()
await ctx.plugin(SlotRegistry).await()
await ctx.plugin({ inject: [...resourcesInject], apply: resourcesApply }).await()
new StaticRemoteAccess(ctx, () => allowed)
const slots = ctx.get('slots') as SlotRegistry
slots.install(createSlotRenderer())
const absentSession = createSnapshotStore<StandardSourceBinding>({ key: undefined, hooks: {}, keyedHooks: {}, props: {} })
@@ -108,6 +115,37 @@ async function bench(call: ConnectionHandle['rpc']['call'], beforeMount?: (ctx:
}
describe('remote connection settings registration', () => {
it('keeps one navigation entry and replaces QR, link login, and pairing approvals together', async () => {
const status = { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 }
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 1000 }
: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private' : status,
}))
const { ctx, slots, fiber } = await bench(call)
render(createElement(Fragment, null, slots.renderSlot('root', {})))
await screen.findByRole('button', { name: '生成二维码' })
await screen.findByText('暂无待审批的申请')
expect(screen.getByRole('region', { name: '配对申请' })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.qrTitle })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.linkTitle })).toBeTruthy()
expect(slots.entries('settings.section')).toHaveLength(1)
const replacement = ctx.plugin(replacementPlugin)
await act(async () => { await replacement.await() })
expect(screen.queryByRole('region', { name: '配对申请' })).toBeNull()
expect(screen.queryByRole('region', { name: zh.linkTitle })).toBeNull()
expect(screen.queryByRole('button', { name: '生成二维码' })).toBeNull()
expect(screen.getByRole('region', { name: 'Custom connection' })).toBeTruthy()
expect(slots.entries('settings.section')).toHaveLength(1)
await act(async () => { await replacement.dispose() })
await screen.findByText('暂无待审批的申请')
expect(screen.getByRole('region', { name: '配对申请' })).toBeTruthy()
expect(screen.getByRole('button', { name: '生成二维码' })).toBeTruthy()
expect(screen.getByRole('region', { name: zh.linkTitle })).toBeTruthy()
await act(async () => { await fiber.dispose() })
expect(slots.entries('settings.remoteConnection.content')).toEqual([])
expect(slots.entries('shell.overlay')).toEqual([])
})
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 } }))
@@ -121,6 +159,7 @@ describe('remote connection settings registration', () => {
expect(typeof face?.reload).toBe('function')
expect(typeof face?.copyLink).toBe('function')
expect(typeof face?.reloadLink).toBe('function')
expect(typeof face?.decide).toBe('function')
expect(face?.hooks).toBeDefined()
expect(slots.spec('settings.remoteConnection.extensions')?.inject).toBe(face)
for (const [language, title] of Object.entries({
@@ -134,7 +173,7 @@ describe('remote connection settings registration', () => {
expect(resolveSlotLabel(entry.options.label)).toBe(title)
}
expect(ctx.get('remote.remoteConnection')).toBeDefined()
expect(slots.entries('shell.overlay')).toHaveLength(1)
expect(slots.entries('shell.overlay')).toHaveLength(2)
await fiber.dispose()
expect(slots.entries('settings.section')).toEqual([])
expect(slots.entries('settings.remoteConnection.content')).toEqual([])
@@ -249,6 +288,7 @@ describe('remote connection settings registration', () => {
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/pairingRequests') return { ok: true, value: { requests: [], pollIntervalMs: 60_000 } }
if (endpoint === 'remoteConnection/loginUrl') return { ok: true, value: 'https://host.example/?token=private' }
if (endpoint === 'remoteConnection/create') {
return { ok: true, value: { id: 'invitation-a', url: 'https://host.example/?login=qr#private', lifetimeMs: 120_000 } }
@@ -290,6 +330,7 @@ describe('remote connection settings registration', () => {
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/pairingRequests') return { ok: true, value: { requests: [], pollIntervalMs: 60_000 } }
if (endpoint === 'remoteConnection/loginUrl') return { ok: true, value: 'https://host.example/?token=private' }
if (endpoint === 'remoteConnection/create') {
return { ok: true, value: { id: 'invitation-b', url: 'https://host.example/?login=qr#private', lifetimeMs: 120_000 } }
@@ -340,8 +381,9 @@ describe('remote connection settings registration', () => {
})
const url = 'https://host.example/?token=private-login-token'
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
ok: true, value: endpoint === 'remoteConnection/loginUrl' ? url
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
: endpoint === 'remoteConnection/loginUrl' ? url
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
}))
const { ctx, slots } = await bench(call)
render(slots.renderSlot('root', {}))
@@ -365,8 +407,9 @@ describe('remote connection settings registration', () => {
await screen.findByText(zh.linkWarning)
expect(screen.getByRole('alert').textContent).toBe(zh.linkCopied)
call.mockImplementation(async (_channel, endpoint) => ({
ok: true, value: endpoint === 'remoteConnection/loginUrl' ? `${url}-new`
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
: endpoint === 'remoteConnection/loginUrl' ? `${url}-new`
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
}))
act(() => { ctx.emit('connection/reset') })
await screen.findByText(`${url}-new`)
@@ -429,8 +472,9 @@ describe('remote connection settings registration', () => {
})
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 },
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
: { url: 'https://host.example/', availability: available ? 'available' : 'untrusted-host', ticket: 'none', pollIntervalMs: 1000 },
}))
const { ctx, slots } = await bench(call)
await vi.waitFor(() => { expect(call).toHaveBeenCalledOnce() })
@@ -513,8 +557,9 @@ describe('remote connection settings registration', () => {
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 },
ok: true, value: endpoint === 'remoteConnection/pairingRequests' ? { requests: [], pollIntervalMs: 60_000 }
: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
}))
const { slots, fiber } = await bench(call)
render(slots.renderSlot('root', {}))
@@ -536,3 +581,72 @@ describe('remote connection settings registration', () => {
}
})
})
function approvalFace(slots: SlotRegistry): PairingInjected {
const face = slots.spec('settings.remoteConnection.content')?.inject
if (face === undefined) throw new Error('Missing connection settings injection')
return face
}
it('submits approval through the shared namespace and keeps its notice outside Settings', async () => {
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
ok: true, value: endpoint === 'remoteConnection/decidePairing' ? 'approved'
: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
}))
const { slots, fiber } = await bench(call)
const face = approvalFace(slots)
await face.decide('request-one' as PairingRequestId, 'allow')
expect(call).toHaveBeenCalledWith('/api', 'remoteConnection/decidePairing', { args: { id: 'request-one', decision: 'allow' } }, expect.any(AbortSignal))
expect(face.hooks.approval.getSnapshot().notice).toBe('approved')
expect(slots.entries('shell.overlay')).toHaveLength(2)
face.dismiss()
expect(face.hooks.approval.getSnapshot().notice).toBeNull()
await fiber.dispose()
expect(face.hooks.approval.getSnapshot().available).toBe(false)
})
it('preserves QR navigation while refusing pairing controls and reads without owner access', async () => {
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint) => ({
ok: true, value: endpoint === 'remoteConnection/loginUrl' ? 'https://host.example/?token=private'
: { url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000 },
}))
const { slots, fiber } = await bench(call, undefined, false)
render(createElement(Fragment, null, slots.renderSlot('root', {})))
await screen.findByRole('button', { name: '生成二维码' })
expect(slots.entries('settings.section')).toHaveLength(1)
expect(slots.entries('shell.overlay').map(entry => entry.options.id)).toEqual(['remote-connection-copy'])
expect(screen.queryByRole('region', { name: '配对申请' })).toBeNull()
await approvalFace(slots).decide('request-one' as PairingRequestId, 'allow')
await vi.waitFor(() => { expect(call).toHaveBeenCalledTimes(2) })
expect(call.mock.calls.map(([, endpoint]) => endpoint)).toEqual(['remoteConnection/status', 'remoteConnection/loginUrl'])
await act(async () => { await fiber.dispose() })
})
it('aborts a pending pairing read and decision when the shared plugin unloads', async () => {
const signals: AbortSignal[] = []
const call = vi.fn<ConnectionHandle['rpc']['call']>().mockImplementation(async (_channel, endpoint, _args, signal) => {
if (endpoint === 'remoteConnection/status') return { ok: true, value: {
url: 'https://host.example/', availability: 'available', ticket: 'none', pollIntervalMs: 1000,
} }
if (endpoint === 'remoteConnection/loginUrl') return { ok: true, value: 'https://host.example/?token=private' }
if (signal === undefined) throw new Error('Missing lifetime signal')
signals.push(signal)
return new Promise<never>((_resolve, reject) => {
signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
})
})
const { ctx, slots, fiber } = await bench(call)
const pin = new AbortController()
onTestFinished(() => { pin.abort() })
ctx.resources.pin('dsh-resource://device-pairing/requests', pin.signal)
const face = approvalFace(slots)
const decision = face.decide('request-one' as PairingRequestId, 'deny')
await vi.waitFor(() => { expect(signals).toHaveLength(2) })
await fiber.dispose()
await decision
expect(signals.every(signal => signal.aborted)).toBe(true)
expect(slots.entries('settings.section')).toEqual([])
expect(slots.entries('shell.overlay')).toEqual([])
expect(face.hooks.approval.getSnapshot()).toMatchObject({ available: false, busy: false, notice: null })
})
@@ -0,0 +1,109 @@
/** Decision outcomes stay ordered and stop publishing when owner access ends. */
import { expect, it, vi } from 'vitest'
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import type { PairingDecisionResult, PairingRequestId } from '../src/types.ts'
import { PairingApproval } from '../src/client/pairing-approval.ts'
const id = 'request-one' as PairingRequestId
it.each([
{ decision: 'allow', value: 'approved' },
{ decision: 'allow', value: 'denied' },
{ decision: 'allow', value: 'unavailable' },
{ decision: 'deny', value: 'approved' },
{ decision: 'deny', value: 'denied' },
{ decision: 'deny', value: 'unavailable' },
] as const)('announces the committed $value after $decision and list publication', async ({ decision, value }) => {
const decide = vi.fn(async () => ({ ok: true as const, value }))
const published = Promise.withResolvers<undefined>()
const confirmed = vi.fn(() => published.promise)
const approval = new PairingApproval({ decidePairing: decide }, confirmed)
approval.activate()
try {
const operation = approval.decide(id, decision)
await vi.waitFor(() => { expect(confirmed).toHaveBeenCalledExactlyOnceWith(id) })
expect(approval.state.getSnapshot()).toMatchObject({ busy: true, notice: null, sequence: 0 })
await approval.decide(id, decision === 'allow' ? 'deny' : 'allow')
expect(decide).toHaveBeenCalledOnce()
published.resolve(undefined)
await operation
expect(decide).toHaveBeenCalledWith(id, decision, expect.any(AbortSignal))
expect(approval.state.getSnapshot()).toEqual({ available: true, busy: false, notice: value, sequence: 1 })
approval.dismiss()
expect(approval.state.getSnapshot().notice).toBeNull()
} finally { published.resolve(undefined); approval.dispose() }
})
it.each(['refused', 'disconnected'] as const)('reports an unknown outcome after a %s operation', async (failure) => {
const decide = vi.fn<() => Promise<RemoteResult<PairingDecisionResult>>>()
if (failure === 'refused') decide.mockResolvedValue({ ok: false, error: new RemoteError('remote-connection/owner-required', 'Owner required.', {}) })
else decide.mockRejectedValue(new Error('disconnected'))
const confirmed = vi.fn(async () => {})
const approval = new PairingApproval({ decidePairing: decide }, confirmed)
approval.activate()
try {
await approval.decide(id, 'deny')
expect(approval.state.getSnapshot()).toMatchObject({ busy: false, notice: 'failed' })
expect(confirmed).not.toHaveBeenCalled()
} finally { approval.dispose() }
})
it('submits one decision at a time and ignores a result after access is revoked', async () => {
const pending = Promise.withResolvers<RemoteResult<PairingDecisionResult>>()
const decide = vi.fn(() => pending.promise)
const confirmed = vi.fn(async () => {})
const approval = new PairingApproval({ decidePairing: decide }, confirmed)
approval.activate()
const operation = approval.decide(id, 'allow')
expect(approval.state.getSnapshot().busy).toBe(true)
await approval.decide(id, 'deny')
expect(decide).toHaveBeenCalledOnce()
approval.dispose()
pending.resolve({ ok: true, value: 'approved' })
await operation
expect(approval.state.getSnapshot()).toEqual({ available: false, busy: false, notice: null, sequence: 0 })
expect(confirmed).not.toHaveBeenCalled()
await approval.decide(id, 'allow')
expect(decide).toHaveBeenCalledOnce()
})
it('does not announce a decision after access ends during list publication', async () => {
const published = Promise.withResolvers<undefined>()
const confirmed = vi.fn(() => published.promise)
const approval = new PairingApproval({ decidePairing: async () => ({ ok: true, value: 'denied' }) }, confirmed)
approval.activate()
const operation = approval.decide(id, 'deny')
await vi.waitFor(() => { expect(confirmed).toHaveBeenCalledOnce() })
approval.dispose()
published.resolve(undefined)
await operation
expect(approval.state.getSnapshot()).toEqual({ available: false, busy: false, notice: null, sequence: 0 })
})
it.each(['response', 'rejection'] as const)('ignores an old %s after owner access is restored and a new decision completes', async (outcome) => {
const previous = Promise.withResolvers<RemoteResult<PairingDecisionResult>>()
const nextId = 'request-two' as PairingRequestId
const decide = vi.fn<() => Promise<RemoteResult<PairingDecisionResult>>>()
.mockReturnValueOnce(previous.promise).mockResolvedValueOnce({ ok: true, value: 'denied' })
const confirmed = vi.fn(async () => {})
const approval = new PairingApproval({ decidePairing: decide }, confirmed)
approval.activate()
const oldOperation = approval.decide(id, 'allow')
approval.dispose()
approval.activate()
try {
await approval.decide(nextId, 'deny')
const current = approval.state.getSnapshot()
expect(current).toMatchObject({ busy: false, notice: 'denied', sequence: 1 })
if (outcome === 'response') previous.resolve({ ok: true, value: 'approved' })
else previous.reject(new Error('old connection closed'))
await oldOperation
expect(approval.state.getSnapshot()).toBe(current)
expect(confirmed).toHaveBeenCalledExactlyOnceWith(nextId)
} finally {
previous.resolve({ ok: true, value: 'unavailable' })
approval.dispose()
await oldOperation
}
})
@@ -0,0 +1,196 @@
/** Private ticket ownership, approval decisions, expiry, and retryable Cookie delivery. */
import { randomBytes, randomUUID } from 'node:crypto'
import { afterEach, expect, it, vi } from 'vitest'
import { PairingRequests } from '../src/pairing-requests.ts'
import type { PairingLimits } from '../src/pairing-requests.ts'
import type { PairingRequestId } from '../src/types.ts'
const AUTHORITY = 'https://example.test'
const SOURCE_IP = '192.0.2.24'
const limits: PairingLimits = { requestTtlMs: 10_000, maxRequests: 2, requestIntervalMs: 100, pollIntervalMs: 200 }
function credential() { return { id: randomUUID() as PairingRequestId, secret: randomBytes(32).toString('base64url') } }
function setup(overrides: Partial<PairingLimits> = {}) {
vi.useFakeTimers()
const requests = new PairingRequests({ ...limits, ...overrides })
const ticket = requests.create(AUTHORITY, SOURCE_IP, credential())!
const issue = vi.fn((): string | undefined => 'signed-cookie')
const poll = (secret = ticket.secret, authority = AUTHORITY, cancel = false) => requests.poll(ticket.id, secret, authority, cancel, issue)
return { requests, ticket, issue, poll }
}
afterEach(() => vi.useRealTimers())
it('retains each applicant connection IP independently of the shared application origin', () => {
const { requests, ticket } = setup()
vi.advanceTimersByTime(limits.requestIntervalMs)
const second = requests.create(AUTHORITY, '2001:db8::24', credential())!
expect(ticket.sourceIp).toBe(SOURCE_IP)
expect(second.sourceIp).toBe('2001:db8::24')
expect(requests.list().map(({ id, authority, sourceIp }) => ({ id, authority, sourceIp }))).toEqual([
{ id: ticket.id, authority: AUTHORITY, sourceIp: SOURCE_IP },
{ id: second.id, authority: AUTHORITY, sourceIp: '2001:db8::24' },
])
})
it('requires the private ticket and owner approval, then retries the same Cookie', () => {
const { requests, ticket, issue, poll } = setup()
expect(ticket.code).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{8}$/u)
expect(ticket.secret).toHaveLength(43)
expect(requests.list()).toEqual([{ id: ticket.id, code: ticket.code, authority: AUTHORITY, sourceIp: SOURCE_IP, expiresInMs: 10_000 }])
vi.advanceTimersByTime(200)
expect(poll(ticket.code)).toEqual({ status: 'expired' })
expect(poll('A'.repeat(43))).toEqual({ status: 'expired' })
expect(poll(ticket.secret, 'https://other.test')).toEqual({ status: 'expired' })
expect(requests.poll('absent' as PairingRequestId, ticket.secret, AUTHORITY, false, issue)).toEqual({ status: 'expired' })
expect(poll()).toEqual({ status: 'pending' })
expect(issue).not.toHaveBeenCalled()
expect(requests.decide(ticket.id, 'allow')).toBe('approved')
expect(requests.list()).toEqual([])
vi.advanceTimersByTime(200)
expect(poll()).toEqual({ status: 'completed', cookie: 'signed-cookie' })
expect(requests.decide(ticket.id, 'deny')).toBe('unavailable')
vi.advanceTimersByTime(200)
expect(poll()).toEqual({ status: 'completed', cookie: 'signed-cookie' })
expect(poll(ticket.secret, AUTHORITY, true)).toEqual({ status: 'completed', cookie: 'signed-cookie' })
expect(issue).toHaveBeenCalledTimes(1)
})
it.each(['allow', 'deny'] as const)('retains the first decision when owner devices disagree: %s', (first) => {
const { requests, ticket, poll, issue } = setup()
const result = first === 'allow' ? 'approved' : 'denied'
expect(requests.decide(ticket.id, first)).toBe(result)
expect(requests.decide(ticket.id, first === 'allow' ? 'deny' : 'allow')).toBe(result)
vi.advanceTimersByTime(200)
expect(poll().status).toBe(first === 'allow' ? 'completed' : 'denied')
expect(issue).toHaveBeenCalledTimes(first === 'allow' ? 1 : 0)
})
it('withdraws an uncollected approval and preserves denial on cancellation', () => {
const { requests, ticket, poll, issue } = setup()
requests.decide(ticket.id, 'allow')
expect(poll(ticket.secret, AUTHORITY, true)).toEqual({ status: 'cancelled' })
expect(requests.decide(ticket.id, 'allow')).toBe('unavailable')
vi.advanceTimersByTime(200)
expect(poll()).toEqual({ status: 'cancelled' })
const denied = requests.create(AUTHORITY, SOURCE_IP, credential())!
requests.decide(denied.id, 'deny')
expect(requests.poll(denied.id, denied.secret, AUTHORITY, true, issue)).toEqual({ status: 'denied' })
expect(issue).not.toHaveBeenCalled()
})
it.each(['allow', 'deny'] as const)('does not revive a cancelled request when an owner later chooses %s', (decision) => {
const { requests, ticket, poll, issue } = setup()
expect(poll(ticket.secret, AUTHORITY, true)).toEqual({ status: 'cancelled' })
expect(requests.decide(ticket.id, decision)).toBe('unavailable')
expect(requests.list()).toEqual([])
vi.advanceTimersByTime(limits.pollIntervalMs)
expect(poll()).toEqual({ status: 'cancelled' })
expect(issue).not.toHaveBeenCalled()
})
it.each(['allow', 'deny'] as const)('rejects a first %s decision at the exact request deadline', (decision) => {
const { requests, ticket, poll, issue } = setup()
vi.advanceTimersByTime(limits.requestTtlMs - 1)
expect(requests.list()).toEqual([{ id: ticket.id, code: ticket.code, authority: AUTHORITY, sourceIp: SOURCE_IP, expiresInMs: 1 }])
vi.advanceTimersByTime(1)
expect(requests.decide(ticket.id, decision)).toBe('unavailable')
expect(poll()).toEqual({ status: 'expired' })
expect(requests.list()).toEqual([])
expect(issue).not.toHaveBeenCalled()
})
it('expires an approval exactly at its deadline and reclaims capacity', () => {
const { requests, ticket, poll, issue } = setup({ maxRequests: 1 })
requests.decide(ticket.id, 'allow')
vi.advanceTimersByTime(10_000)
expect(poll()).toEqual({ status: 'expired' })
expect(requests.decide(ticket.id, 'allow')).toBe('unavailable')
expect(requests.list()).toEqual([])
expect(requests.create(AUTHORITY, SOURCE_IP, credential())).toBeDefined()
expect(issue).not.toHaveBeenCalled()
})
it('bounds global creation, per-ticket polling, and retention of terminal requests', () => {
const { requests, ticket, poll } = setup()
expect(requests.create(AUTHORITY, SOURCE_IP, credential())).toBeUndefined()
expect(poll()).toEqual({ status: 'slow-down' })
vi.advanceTimersByTime(100)
const second = requests.create(AUTHORITY, SOURCE_IP, credential())!
expect(second.code).not.toBe(ticket.code)
expect(second.secret).not.toBe(ticket.secret)
requests.decide(ticket.id, 'deny')
vi.advanceTimersByTime(100)
expect(requests.create(AUTHORITY, SOURCE_IP, credential())).toBeUndefined()
})
it('keeps approval retryable when Cookie signing is refused or fails', () => {
const { requests, ticket, issue, poll } = setup()
requests.decide(ticket.id, 'allow')
vi.advanceTimersByTime(200)
issue.mockReturnValueOnce(undefined)
expect(poll()).toEqual({ status: 'unavailable' })
vi.advanceTimersByTime(200)
issue.mockImplementationOnce(() => { throw new Error('signer unavailable') })
expect(poll).toThrow('signer unavailable')
vi.advanceTimersByTime(200)
expect(poll()).toEqual({ status: 'completed', cookie: 'signed-cookie' })
})
it.each(['cancel', 'deny'] as const)('handles %s after Cookie signing fails without changing the first owner decision', (next) => {
const { requests, ticket, issue, poll } = setup()
expect(requests.decide(ticket.id, 'allow')).toBe('approved')
vi.advanceTimersByTime(limits.pollIntervalMs)
issue.mockReturnValueOnce(undefined)
expect(poll()).toEqual({ status: 'unavailable' })
expect(requests.list()).toEqual([])
if (next === 'cancel') {
expect(poll(ticket.secret, AUTHORITY, true)).toEqual({ status: 'cancelled' })
expect(requests.decide(ticket.id, 'allow')).toBe('unavailable')
vi.advanceTimersByTime(limits.pollIntervalMs)
expect(poll()).toEqual({ status: 'cancelled' })
expect(issue).toHaveBeenCalledOnce()
} else {
expect(requests.decide(ticket.id, 'deny')).toBe('approved')
vi.advanceTimersByTime(limits.pollIntervalMs)
expect(poll()).toEqual({ status: 'completed', cookie: 'signed-cookie' })
expect(issue).toHaveBeenCalledTimes(2)
}
})
it('forgets tickets and retained Cookies on unload', () => {
const { requests, ticket, poll } = setup()
requests.decide(ticket.id, 'allow')
requests.clear()
expect(requests.list()).toEqual([])
expect(poll()).toEqual({ status: 'expired' })
})
it('replays creation before rate and capacity checks without extending expiry or replacing the source IP', () => {
const { requests, ticket } = setup({ maxRequests: 1 })
expect(requests.create(AUTHORITY, '198.51.100.42', ticket)).toEqual(ticket)
vi.advanceTimersByTime(100)
expect(requests.create(AUTHORITY, SOURCE_IP, ticket)).toEqual({ ...ticket, expiresInMs: 9900 })
expect(requests.create('https://other.test', SOURCE_IP, ticket)).toBeUndefined()
expect(requests.create(AUTHORITY, SOURCE_IP, { ...ticket, secret: 'b'.repeat(43) })).toBeUndefined()
expect(requests.list()).toHaveLength(1)
})
it('does not revive a cancelled creation when its older HTTP request arrives after a replacement from the same IP', () => {
const { requests, ticket, poll, issue } = setup()
expect(poll(ticket.secret, AUTHORITY, true).status).toBe('cancelled')
vi.advanceTimersByTime(limits.requestIntervalMs)
const replacement = requests.create(AUTHORITY, SOURCE_IP, credential())!
expect(replacement.id).not.toBe(ticket.id)
expect(replacement.secret).not.toBe(ticket.secret)
expect(requests.create(AUTHORITY, SOURCE_IP, ticket)).toMatchObject({ id: ticket.id, code: ticket.code })
expect(requests.decide(ticket.id, 'allow')).toBe('unavailable')
expect(requests.list().map(row => row.id)).toEqual([replacement.id])
vi.advanceTimersByTime(limits.pollIntervalMs)
expect(poll().status).toBe('cancelled')
expect(requests.poll(replacement.id, ticket.secret, AUTHORITY, false, issue).status).toBe('expired')
expect(requests.poll(replacement.id, replacement.secret, AUTHORITY, false, issue).status).toBe('pending')
expect(issue).not.toHaveBeenCalled()
})
@@ -0,0 +1,286 @@
/** Pending-list polling is held by a view and never survives its resource release. */
import { afterEach, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import { ResourceRegistry } from '@deepseek-ai/dsh-client-resources/src/client/resources.ts'
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import type { PairingRequestId, PairingRequestsValue } from '../src/types.ts'
import { requestsResource } from '../src/client/pairing-resource.ts'
afterEach(() => { vi.useRealTimers() })
const value: PairingRequestsValue = { requests: [], pollIntervalMs: 1000 }
const firstId = 'request-one' as PairingRequestId
const secondId = 'request-two' as PairingRequestId
const listed: PairingRequestsValue = {
requests: [firstId, secondId].map((id, index) => ({
id, code: index === 0 ? 'ABCD2345' : 'WXYZ6789', authority: 'https://host.example', sourceIp: '192.0.2.17', expiresInMs: 60_000,
})),
pollIntervalMs: 1000,
}
const remaining: PairingRequestsValue = { ...listed, requests: listed.requests.slice(1) }
const address = 'dsh-resource://device-pairing/requests'
it('polls with the server interval and releases the timer on abort', async () => {
vi.useFakeTimers()
const requests = vi.fn(async () => ({ ok: true as const, value }))
const controller = new AbortController()
const stream = requestsResource({ pairingRequests: requests }).provider.open('dsh-resource://device-pairing/requests', { signal: controller.signal })[Symbol.asyncIterator]()
try {
expect(await stream.next()).toEqual({ done: false, value: { ok: true, value } })
const next = stream.next()
await vi.advanceTimersByTimeAsync(999)
expect(requests).toHaveBeenCalledOnce()
await vi.advanceTimersByTimeAsync(1)
expect(await next).toMatchObject({ done: false })
expect(requests).toHaveBeenCalledTimes(2)
const released = stream.next()
await vi.advanceTimersByTimeAsync(0)
controller.abort()
expect(await released).toEqual({ done: true, value: undefined })
expect(vi.getTimerCount()).toBe(0)
} finally { controller.abort(); await stream.return?.() }
})
it.each(['refused', 'disconnected', 'typed-error'] as const)('yields a %s read as a resource failure', async (failure) => {
const requests = vi.fn<() => Promise<RemoteResult<PairingRequestsValue>>>()
const ownerRequired = new RemoteError('remote-connection/owner-required', 'Owner required.', {})
if (failure === 'refused') requests.mockResolvedValue({ ok: false, error: ownerRequired })
else if (failure === 'typed-error') requests.mockRejectedValue(ownerRequired)
else requests.mockRejectedValue(new Error('disconnected'))
const controller = new AbortController()
const stream = requestsResource({ pairingRequests: requests }).provider.open('dsh-resource://device-pairing/requests', { signal: controller.signal })[Symbol.asyncIterator]()
try {
expect(await stream.next()).toMatchObject({ done: false, value: {
ok: false, error: { code: failure === 'disconnected' ? 'pairing/read-failed' : 'remote-connection/owner-required' },
} })
controller.abort()
expect(await stream.next()).toEqual({ done: true, value: undefined })
} finally { controller.abort(); await stream.return?.() }
})
it.each(['response', 'rejection'] as const)('ignores an in-flight %s after release and never reads an already aborted resource', async (outcome) => {
const pending = Promise.withResolvers<RemoteResult<PairingRequestsValue>>()
const requests = vi.fn(() => pending.promise)
const controller = new AbortController()
const { provider } = requestsResource({ pairingRequests: requests })
const stream = provider.open('dsh-resource://device-pairing/requests', { signal: controller.signal })[Symbol.asyncIterator]()
const next = stream.next()
controller.abort()
if (outcome === 'response') pending.resolve({ ok: true, value })
else pending.reject(new Error('transport aborted'))
expect(await next).toEqual({ done: true, value: undefined })
const stopped = provider.open('dsh-resource://device-pairing/requests', { signal: controller.signal })[Symbol.asyncIterator]()
expect(await stopped.next()).toEqual({ done: true, value: undefined })
expect(requests).toHaveBeenCalledOnce()
})
it('publishes a confirmed removal before its next poll and keeps other rows when the fresh read fails', async () => {
vi.useFakeTimers()
const refresh = Promise.withResolvers<RemoteResult<PairingRequestsValue>>()
const recovery = Promise.withResolvers<RemoteResult<PairingRequestsValue>>()
const requests = vi.fn<() => Promise<RemoteResult<PairingRequestsValue>>>()
.mockResolvedValueOnce({ ok: true, value: listed }).mockReturnValueOnce(refresh.promise)
.mockReturnValueOnce(recovery.promise)
const ctx = new Context()
const resources = new ResourceRegistry(ctx)
const owner = requestsResource({ pairingRequests: requests })
const release = resources.register(owner.provider)
const source = resources.source(address)
const ready = Promise.withResolvers<undefined>()
const failed = Promise.withResolvers<undefined>()
const unsubscribe = source.subscribe(() => {
if (source.getSnapshot().status === 'live') ready.resolve(undefined)
if (source.getSnapshot().status === 'failed') failed.resolve(undefined)
})
try {
await ready.promise
expect(source.getSnapshot().value).toEqual(listed)
await owner.confirmed(firstId)
expect(source.getSnapshot()).toMatchObject({ status: 'live', value: remaining })
expect(requests).toHaveBeenCalledTimes(2)
refresh.reject(new Error('disconnected'))
await failed.promise
expect(source.getSnapshot()).toMatchObject({
status: 'failed', value: remaining, failure: { code: 'pairing/read-failed' },
})
expect(vi.getTimerCount()).toBe(0)
await owner.confirmed(secondId)
expect(source.getSnapshot()).toMatchObject({
status: 'failed', value, failure: { code: 'pairing/read-failed' },
})
expect(requests).toHaveBeenCalledTimes(3)
const recovered = Promise.withResolvers<undefined>()
const stopWatching = source.subscribe(() => {
if (source.getSnapshot().status === 'live') recovered.resolve(undefined)
})
try {
recovery.resolve({ ok: true, value })
await recovered.promise
expect(source.getSnapshot()).toMatchObject({ status: 'live', value, failure: undefined })
} finally { stopWatching() }
} finally {
unsubscribe()
release()
await ctx.fiber.dispose()
}
})
it('acknowledges immediately while the initial list is unresolved and replaces the old read', async () => {
const first = Promise.withResolvers<RemoteResult<PairingRequestsValue>>()
const fresh = Promise.withResolvers<RemoteResult<PairingRequestsValue>>()
const requests = vi.fn<(signal: AbortSignal) => Promise<RemoteResult<PairingRequestsValue>>>()
.mockReturnValueOnce(first.promise).mockReturnValueOnce(fresh.promise)
const owner = requestsResource({ pairingRequests: requests })
const controller = new AbortController()
const stream = owner.provider.open(address, { signal: controller.signal })[Symbol.asyncIterator]()
try {
const initial = stream.next()
await owner.confirmed(firstId)
expect(requests.mock.calls[0]?.[0].aborted).toBe(true)
expect(requests).toHaveBeenCalledTimes(2)
first.resolve({ ok: true, value: listed })
fresh.resolve({ ok: true, value: remaining })
expect(await initial).toEqual({ done: false, value: { ok: true, value: remaining } })
} finally { controller.abort(); await stream.return?.() }
})
it('keeps a failed list idle until a manual retry opens a fresh resource', async () => {
vi.useFakeTimers()
const requests = vi.fn<() => Promise<RemoteResult<PairingRequestsValue>>>()
.mockRejectedValueOnce(new Error('disconnected')).mockResolvedValueOnce({ ok: true, value: listed })
const { provider } = requestsResource({ pairingRequests: requests })
const controller = new AbortController()
const stream = provider.open(`${address}?retry=0`, { signal: controller.signal })[Symbol.asyncIterator]()
const retryController = new AbortController()
const retry = provider.open(`${address}?retry=1`, { signal: retryController.signal })[Symbol.asyncIterator]()
try {
expect(await stream.next()).toMatchObject({ done: false, value: { ok: false } })
const closed = stream.next()
await vi.advanceTimersByTimeAsync(5000)
expect(requests).toHaveBeenCalledOnce()
controller.abort()
expect(await closed).toEqual({ done: true, value: undefined })
expect(await retry.next()).toEqual({ done: false, value: { ok: true, value: listed } })
expect(requests).toHaveBeenCalledTimes(2)
} finally {
controller.abort()
retryController.abort()
await stream.return?.()
await retry.return?.()
}
})
it.each(['response', 'rejection'] as const)('discards a late %s from the read started before confirmation', async (outcome) => {
vi.useFakeTimers()
const stale = Promise.withResolvers<RemoteResult<PairingRequestsValue>>()
const fresh = Promise.withResolvers<RemoteResult<PairingRequestsValue>>()
const requests = vi.fn<(signal: AbortSignal) => Promise<RemoteResult<PairingRequestsValue>>>()
.mockResolvedValueOnce({ ok: true, value: listed }).mockReturnValueOnce(stale.promise).mockReturnValueOnce(fresh.promise)
const owner = requestsResource({ pairingRequests: requests })
const controller = new AbortController()
const stream = owner.provider.open(address, { signal: controller.signal })[Symbol.asyncIterator]()
try {
await stream.next()
const waiting = stream.next()
await vi.advanceTimersByTimeAsync(1000)
expect(requests).toHaveBeenCalledTimes(2)
const confirmed = owner.confirmed(firstId)
expect(requests.mock.calls[1]?.[0].aborted).toBe(true)
expect(await waiting).toEqual({ done: false, value: { ok: true, value: remaining } })
const refreshed = stream.next()
await confirmed
expect(requests).toHaveBeenCalledTimes(3)
let delivered = false
void refreshed.then(() => { delivered = true })
if (outcome === 'response') stale.resolve({ ok: true, value: listed })
else stale.reject(new Error('old read failed'))
await vi.advanceTimersByTimeAsync(0)
expect(delivered).toBe(false)
fresh.resolve({ ok: true, value: remaining })
expect(await refreshed).toEqual({ done: false, value: { ok: true, value: remaining } })
} finally { controller.abort(); await stream.return?.() }
})
it.each(['abort', 'return'] as const)('waits for removal consumption and releases its confirmation on %s', async (method) => {
vi.useFakeTimers()
const requests = vi.fn(async () => ({ ok: true as const, value: listed }))
const owner = requestsResource({ pairingRequests: requests })
await owner.confirmed(firstId)
expect(requests).not.toHaveBeenCalled()
const controller = new AbortController()
const stream = owner.provider.open(address, { signal: controller.signal })[Symbol.asyncIterator]()
try {
expect(await stream.next()).toEqual({ done: false, value: { ok: true, value: listed } })
let acknowledged = false
const confirmed = owner.confirmed(firstId).then(() => { acknowledged = true })
expect(await stream.next()).toEqual({ done: false, value: { ok: true, value: remaining } })
expect(acknowledged).toBe(false)
if (method === 'abort') controller.abort()
else await stream.return?.()
await confirmed
expect(acknowledged).toBe(true)
expect(vi.getTimerCount()).toBe(0)
await owner.confirmed(secondId)
expect(requests).toHaveBeenCalledOnce()
expect(await stream.next()).toEqual({ done: true, value: undefined })
} finally { controller.abort(); await stream.return?.() }
})
it('releases confirmation when aborted while restoring a read failure after removal', async () => {
vi.useFakeTimers()
const error = new RemoteError('pairing/read-failed', 'Could not read pairing requests.', {})
const requests = vi.fn<() => Promise<RemoteResult<PairingRequestsValue>>>()
.mockResolvedValueOnce({ ok: true, value: listed }).mockResolvedValueOnce({ ok: false, error })
const owner = requestsResource({ pairingRequests: requests })
const controller = new AbortController()
const stream = owner.provider.open(address, { signal: controller.signal })[Symbol.asyncIterator]()
try {
await stream.next()
const failure = stream.next()
await vi.advanceTimersByTimeAsync(1000)
expect(await failure).toEqual({ done: false, value: { ok: false, error } })
let acknowledged = false
const confirmed = owner.confirmed(firstId).then(() => { acknowledged = true })
expect(await stream.next()).toEqual({ done: false, value: { ok: true, value: remaining } })
expect(await stream.next()).toEqual({ done: false, value: { ok: false, error } })
expect(acknowledged).toBe(false)
controller.abort()
await confirmed
expect(await stream.next()).toEqual({ done: true, value: undefined })
expect(requests).toHaveBeenCalledTimes(2)
expect(vi.getTimerCount()).toBe(0)
} finally { controller.abort(); await stream.return?.() }
})
it('releases a waiting confirmation and abandons an unresolved fresh read when the last subscriber leaves', async () => {
const pending = Promise.withResolvers<RemoteResult<PairingRequestsValue>>()
const requests = vi.fn<(signal: AbortSignal) => Promise<RemoteResult<PairingRequestsValue>>>()
.mockResolvedValueOnce({ ok: true, value: listed }).mockReturnValueOnce(pending.promise)
const ctx = new Context()
const resources = new ResourceRegistry(ctx)
const owner = requestsResource({ pairingRequests: requests })
const release = resources.register(owner.provider)
const source = resources.source(address)
const ready = Promise.withResolvers<undefined>()
const unsubscribe = source.subscribe(() => {
if (source.getSnapshot().status === 'live') ready.resolve(undefined)
})
try {
await ready.promise
await owner.confirmed(firstId)
expect(requests).toHaveBeenCalledTimes(2)
const confirmed = owner.confirmed(secondId)
unsubscribe()
await confirmed
expect(requests.mock.calls[1]?.[0].aborted).toBe(true)
expect(source.getSnapshot()).toMatchObject({ status: 'loading', value: undefined })
pending.resolve({ ok: true, value: listed })
await owner.confirmed(firstId)
expect(requests).toHaveBeenCalledTimes(2)
} finally {
unsubscribe()
release()
await ctx.fiber.dispose()
}
})
@@ -0,0 +1,151 @@
// @vitest-environment jsdom
/** Owner decisions remain visible outside Settings; read failures preserve the last request list. */
import { afterEach, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import type { ComponentProps } from 'react'
import { allowAllAccess, bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
import type { ResourceSnapshot } from '@deepseek-ai/dsh-client-resources/client'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import type { PairingDecisionResult, PairingRequestId, PairingRequestsValue } from '../src/types.ts'
import { PairingApproval } from '../src/client/pairing-approval.ts'
import { PairingRequests, PairingToast } from '../src/client/PairingRequests.tsx'
import { en, zh, ja, es, fr, de, ru, pt } from '../src/client/locales.ts'
afterEach(cleanup)
function fixture(sourceIp: string | null = '192.0.2.17') {
const decide = vi.fn<() => Promise<RemoteResult<PairingDecisionResult>>>().mockResolvedValue({ ok: true, value: 'approved' })
const approval = new PairingApproval({ decidePairing: decide }, async () => {})
approval.activate()
const value: PairingRequestsValue = {
requests: [{ id: 'request-one' as PairingRequestId, code: 'ABCD2345', authority: 'https://host.example', sourceIp, expiresInMs: 60000 }],
pollIntervalMs: 1000,
}
const snapshot: ResourceSnapshot<PairingRequestsValue> = { status: 'live', failure: undefined, value }
const useResource = vi.fn(() => snapshot)
const props = {
useResource, useApproval: bindSnapshotSelector(approval.state),
decide: (id: PairingRequestId, decision: 'allow' | 'deny') => approval.decide(id, decision),
dismiss: () => { approval.dismiss() }, t: makeTranslate(en),
} as ComponentProps<typeof PairingRequests>
const unusedHook = (): never => { throw new Error('Pairing toast does not read global state') }
const toastProps = {
...props, ...allowAllAccess, useContextMenu: contextMenuHook(),
usePanelInfo: unusedHook, useWorkspaces: unusedHook, useSessions: unusedHook,
useSessionStatus: unusedHook, useSessionRetainInfo: unusedHook,
} satisfies ComponentProps<typeof PairingToast>
return { decide, approval, snapshot, value, useResource, props, toastProps }
}
it('shows the code and source IP, then announces the decision after Settings closes during submission', async () => {
const { props, toastProps, decide, approval } = fixture()
const pending = Promise.withResolvers<RemoteResult<PairingDecisionResult>>()
decide.mockReturnValueOnce(pending.promise)
try {
const section = render(<PairingRequests {...props} />)
render(<PairingToast {...toastProps} />)
expect(screen.queryByRole('heading', { level: 2 })).toBeNull()
expect(screen.getByRole('heading', { level: 3, name: en['pairing.title'] })).toBeTruthy()
expect(screen.getByRole('region', { name: en['pairing.title'] })).toBeTruthy()
expect(screen.getByRole('note').textContent).toBe(en['pairing.permission'])
expect(screen.queryByText(en['pairing.empty'])).toBeNull()
expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual([en['pairing.approve'], en['pairing.deny']])
expect(screen.getByText('ABCD 2345')).toBeTruthy()
expect(screen.getByText(en['pairing.sourceIp'])).toBeTruthy()
expect(screen.getByText('192.0.2.17')).toBeTruthy()
expect(screen.queryByText('https://host.example')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: en['pairing.approve'] }))
section.unmount()
await act(async () => { pending.resolve({ ok: true, value: 'approved' }) })
await screen.findByText(en['pairing.approved'])
expect(decide).toHaveBeenCalledWith('request-one', 'allow', expect.any(AbortSignal))
expect(screen.getByText(en['pairing.approved'])).toBeTruthy()
} finally { pending.resolve({ ok: true, value: 'unavailable' }); approval.dispose() }
})
it.each(Object.entries({ en, zh, ja, es, fr, de, ru, pt }))('labels the source IP in %s and renders unknown or the full IPv6 address', (_language, dictionary) => {
const { props, approval, snapshot, value, useResource } = fixture(null)
const ipv6 = '2001:0db8:1234:5678:90ab:cdef:1234:5678'
try {
const view = render(<PairingRequests {...props} t={makeTranslate(dictionary)} />)
expect(screen.getByText(dictionary['pairing.sourceIp'])).toBeTruthy()
expect(screen.getByText(dictionary['pairing.sourceIpUnknown'])).toBeTruthy()
expect(screen.queryByText('https://host.example')).toBeNull()
useResource.mockReturnValue({
...snapshot, value: { ...value, requests: value.requests.map(row => ({ ...row, sourceIp: ipv6 })) },
})
view.rerender(<PairingRequests {...props} t={makeTranslate(dictionary)} />)
expect(screen.getByText(ipv6, { exact: true })).toBeTruthy()
expect(screen.queryByText(dictionary['pairing.sourceIpUnknown'])).toBeNull()
expect(screen.queryByText('https://host.example')).toBeNull()
} finally { approval.dispose() }
})
it('keeps a failed operation row visible and serializes decisions', async () => {
const { props, toastProps, decide, approval } = fixture()
const pending = Promise.withResolvers<RemoteResult<PairingDecisionResult>>()
decide.mockReturnValueOnce(pending.promise)
try {
render(<><PairingRequests {...props} /><PairingToast {...toastProps} /></>)
fireEvent.click(screen.getByRole('button', { name: en['pairing.deny'] }))
expect(screen.getByRole('button', { name: en['pairing.approve'] }).hasAttribute('disabled')).toBe(true)
await act(async () => {
pending.reject(new Error('response lost'))
await pending.promise.catch(() => undefined)
})
await screen.findByText(en['pairing.failed'])
expect(screen.getByText('ABCD 2345')).toBeTruthy()
expect(screen.getByRole('button', { name: en['pairing.approve'] }).hasAttribute('disabled')).toBe(false)
} finally { approval.dispose() }
})
it('retains loaded requests during a read failure and disables decisions until refresh', () => {
const { props, approval, snapshot, useResource } = fixture()
useResource.mockReturnValue({ ...snapshot, status: 'failed' })
try {
render(<PairingRequests {...props} />)
expect(screen.getByRole('alert').textContent).toBe(en['pairing.readFailed'])
expect(screen.getByText('ABCD 2345')).toBeTruthy()
expect(screen.getByRole('note').textContent).toBe(en['pairing.permission'])
expect(screen.getByRole('button', { name: en['pairing.deny'] }).hasAttribute('disabled')).toBe(true)
fireEvent.click(screen.getByRole('button', { name: en['pairing.retry'] }))
expect(useResource).toHaveBeenLastCalledWith('dsh-resource://device-pairing/requests?retry=1')
} finally { approval.dispose() }
})
it('shows a loading indicator, then a read-only empty status in the card header without a permission warning', async () => {
const { props, approval, snapshot, useResource } = fixture()
useResource.mockReturnValue({ status: 'loading', value: undefined, failure: undefined })
try {
const view = render(<PairingRequests {...props} />)
expect(screen.getByRole('status', { name: en['pairing.loading'] })).toBeTruthy()
expect(screen.queryByText(en['pairing.permission'])).toBeNull()
useResource.mockReturnValue({ ...snapshot, value: { requests: [], pollIntervalMs: 1000 } })
view.rerender(<PairingRequests {...props} t={makeTranslate(zh)} />)
expect(screen.getByRole('heading', { level: 3, name: zh['pairing.title'] })).toBeTruthy()
await waitFor(() => { expect(screen.getByText(zh['pairing.empty'])).toBeTruthy() })
const status = screen.getByRole('status')
expect(status.textContent).toBe(zh['pairing.empty'])
expect(screen.getByRole('heading', { level: 3, name: zh['pairing.title'] }).closest('header')?.contains(status)).toBe(true)
expect(status.querySelector('button')).toBeNull()
expect(screen.queryByRole('note')).toBeNull()
expect(screen.queryByRole('button', { name: zh['pairing.approve'] })).toBeNull()
useResource.mockReturnValue({ ...snapshot, status: 'failed', value: { requests: [], pollIntervalMs: 1000 } })
view.rerender(<PairingRequests {...props} t={makeTranslate(zh)} />)
expect(screen.getByRole('alert').textContent).toBe(zh['pairing.readFailed'])
expect(screen.queryByText(zh['pairing.empty'])).toBeNull()
} finally { approval.dispose() }
})
it('removes the permission warning when the last pending request leaves the list', () => {
const { props, approval, snapshot, useResource } = fixture()
try {
const view = render(<PairingRequests {...props} />)
expect(screen.getByRole('note').textContent).toBe(en['pairing.permission'])
useResource.mockReturnValue({ ...snapshot, value: { requests: [], pollIntervalMs: 1000 } })
view.rerender(<PairingRequests {...props} />)
expect(screen.queryByRole('note')).toBeNull()
expect(screen.queryByText('ABCD 2345')).toBeNull()
expect(screen.getByRole('status').textContent).toBe(en['pairing.empty'])
} finally { approval.dispose() }
})
@@ -0,0 +1,735 @@
/** Anonymous HTTP requests, owner-only approval, and independent Remote browser authentication. */
import { randomBytes, randomUUID } from 'node:crypto'
import { request as httpRequest, type IncomingMessage, type ServerResponse } from 'node:http'
import { request as httpsRequest } from 'node:https'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Context } from '@deepseek-ai/cordis'
import type { CredentialKey, CredentialRecord } from '@deepseek-ai/dsh-credentials'
import * as Connection from '@deepseek-ai/dsh-client-connection'
import * as Token from '@deepseek-ai/dsh-host-authentication-token'
import WebServer, { type WebEntryUrl, type WebResourceRoute, type WebRoute } from '@deepseek-ai/dsh-host-webserver'
import type { Principal, RemoteInvocation } from '@deepseek-ai/dsh-typert-protocol'
import { afterEach, expect, it, vi } from 'vitest'
import { MemoryCredentials } from '../../../credentials/credentials/tests/memory.ts'
import { materializeTlsFixture } from '../../../host/webserver/tests/tls-fixture.ts'
import RemoteConnection from '../src/index.ts'
import type { Config } from '../src/index.ts'
import type { PairingTicket } from '../src/types.ts'
import { renderPairingScript } from '../src/anonymous/index.ts'
import { RemoteBrowserAuth } from '../src/remote-auth.ts'
import { PairingRequests } from '../src/pairing-requests.ts'
declare module '@deepseek-ai/dsh-typert-protocol' {
interface PrincipalMap {
/** Non-owner used to check approval independently of Gateway grants. */
'pairing-test-guest': { readonly kind: 'pairing-test-guest' }
}
}
const config: Config = {
cookieMaxAgeDays: 30, ticketLifetimeMs: 120_000, pollIntervalMs: 1000,
pairing: {
requestTtlMs: 10_000, maxRequests: 2, requestIntervalMs: 100, pollIntervalMs: 200,
requestTimeoutMs: 1000, maxRetries: 3, retryMaxDelayMs: 1000,
},
}
const cleanups: (() => Promise<void>)[] = []
afterEach(async () => {
await Promise.all(cleanups.splice(0).map(cleanup => cleanup()))
vi.useRealTimers()
vi.restoreAllMocks()
})
async function mounted(
protocol: 'http:' | 'https:' = 'http:',
storage = new Map<CredentialKey, CredentialRecord>(),
withToken = false,
advertisedUrl = `${protocol}//localhost/`,
) {
const ctx = new Context()
const root = protocol === 'https:' ? await mkdtemp(join(tmpdir(), 'dsh-pairing-tls-')) : undefined
cleanups.push(async () => {
await ctx.fiber.dispose()
if (root !== undefined) await rm(root, { recursive: true, force: true })
})
class SharedCredentials extends MemoryCredentials {
override readRecord(key: CredentialKey): Promise<CredentialRecord | undefined> { return Promise.resolve(storage.get(key)) }
override async modifyRecord(
key: CredentialKey,
mutate: (current: CredentialRecord | undefined) => Promise<CredentialRecord | undefined>,
): Promise<CredentialRecord | undefined> {
const current = storage.get(key)
const next = await mutate(current)
if (next !== undefined) storage.set(key, next)
return next ?? current
}
}
await ctx.plugin(SharedCredentials)
const tls = root === undefined ? undefined : await materializeTlsFixture(root)
await ctx.plugin(WebServer, {
host: '127.0.0.1', port: 0,
...tls === undefined ? {} : { tls: { certFile: tls.certFile, keyFile: tls.keyFile } },
})
ctx.provide('webApp', { getAdvertisedUrl: () => advertisedUrl })
await ctx.plugin(Connection, { trustedHosts: ['pair.test', 'other.test', '192.0.2.40'] })
const token = withToken ? ctx.plugin(Token, { cookieMaxAgeDays: 30 }) : undefined
await token?.await()
const routes: (WebRoute | WebResourceRoute)[] = []
const register = ctx.webServer.register.bind(ctx.webServer)
vi.spyOn(ctx.webServer, 'register').mockImplementation((route) => {
const dispose = register(route)
routes.push(route)
return () => { routes.splice(routes.indexOf(route), 1); dispose() }
})
const fiber = ctx.plugin(RemoteConnection, config)
await fiber.await()
const service = ctx.remoteConnection
const url = ctx.webServer.getOrigin()
const headers = { host: 'pair.test', origin: `${protocol}//pair.test`, 'content-type': 'application/json' }
const transport = protocol === 'https:' ? httpsRequest : httpRequest
const open = (path: string, method: string, additional: Record<string, string> = {}) => {
const result = Promise.withResolvers<Response>()
const request = transport(`${url}${path}`, {
method, headers: { ...headers, ...additional }, ...tls === undefined ? {} : { ca: tls.ca, servername: 'localhost' },
}, (response) => {
const chunks: Buffer[] = []
response.on('data', (chunk: Buffer) => chunks.push(chunk))
response.once('error', result.reject)
response.once('end', () => {
const responseHeaders = new Headers()
for (const [key, value] of Object.entries(response.headers)) {
if (typeof value === 'string') responseHeaders.set(key, value)
else for (const item of value ?? []) responseHeaders.append(key, item)
}
const body = method === 'HEAD' || response.statusCode === 204 ? null : Buffer.concat(chunks)
result.resolve(new Response(body, { status: response.statusCode!, headers: responseHeaders }))
})
})
request.once('error', result.reject)
const closed = new Promise<void>((resolve) => { request.once('close', resolve) })
const settled = result.promise.then(() => undefined, () => undefined)
cleanups.push(async () => { request.destroy(); await Promise.all([closed, settled]) })
return { request, response: result.promise }
}
const send = (path: string, method = 'GET', additional: Record<string, string> = {}, body?: string) => {
const pending = open(path, method, additional)
pending.request.end(body)
return pending.response
}
const openExchange = (operation: string, method: string, additional: Record<string, string> = {}) => open(`/pairing/${operation}`, method, additional)
const exchange = (operation: string, method: string, body?: string, additional: Record<string, string> = {}) =>
send(`/pairing/${operation}`, method, additional, body)
const post = (operation: 'request' | 'status' | 'cancel', body?: object, additional: Record<string, string> = {}) =>
exchange(operation, 'POST', JSON.stringify(body ?? (operation === 'request' ? { id: randomUUID(), secret: randomBytes(32).toString('base64url') } : undefined)), additional)
const caller = (principal: Principal = { kind: 'owner' }) => {
const peer = ctx.connection.createPeer({ principal })
const invocation: RemoteInvocation = {
service: 'remoteConnection', request: { namespace: 'remoteConnection', method: 'pairingRequests', args: {} }, signal: peer.signal, peer,
uplink: <In>(): AsyncIterable<In> => ({
[Symbol.asyncIterator]: () => ({ next: () => Promise.resolve({ done: true, value: undefined }) }),
}),
}
return { service: ctx.extend({ invocation }).remoteConnection, signal: peer.signal }
}
const create = async () => {
const response = await post('request')
expect(response.status).toBe(200)
return await response.json() as PairingTicket
}
const onceRequest = (callback: (request: IncomingMessage, response: ServerResponse) => void, before = false) => {
const dispose = ctx.on('webserver/request', async (request, response, next) => {
dispose()
if (before) callback(request, response)
const task = next()
if (!before) callback(request, response)
await task
})
cleanups.push(() => { dispose(); return Promise.resolve() })
}
const holdPost = async (operation: 'request' | 'status' | 'cancel', ticket: Pick<PairingTicket, 'id' | 'secret'>) => {
const received = Promise.withResolvers<undefined>()
onceRequest(() => { received.resolve(undefined) })
const body = JSON.stringify({ id: ticket.id, secret: ticket.secret })
const pending = openExchange(operation, 'POST')
pending.request.write(body.slice(0, -1))
await received.promise
return { response: pending.response, finish: () => { pending.request.end(body.slice(-1)) } }
}
return { ctx, service, fiber, token, routes, post, exchange, send, holdPost, create, caller, url, headers, onceRequest }
}
it.each(['http:', 'https:'] as const)('delivers a valid Remote Cookie without Token only to the approved applicant over %s', async (protocol) => {
const fixture = await mounted(protocol)
vi.useFakeTimers({ toFake: ['Date'] })
const { ctx, create, post, caller } = fixture
const ticket = await create()
const owner = caller()
expect(owner.service.status(null).availability).toBe('unreachable-host')
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([{
id: ticket.id, code: ticket.code, authority: `${protocol}//pair.test`, sourceIp: '127.0.0.1', expiresInMs: 10_000,
}])
expect(owner.service.decidePairing(ticket.id, 'allow', owner.signal)).toBe('approved')
vi.setSystemTime(Date.now() + 200)
const stolen = await post('status', { id: ticket.id, secret: 'A'.repeat(43) })
expect(await stolen.json()).toEqual({ status: 'expired' })
expect(stolen.headers.get('set-cookie')).toBeNull()
const response = await post('status', { id: ticket.id, secret: ticket.secret })
expect(response.status).toBe(200)
expect(await response.json()).toEqual({ status: 'completed' })
const cookie = response.headers.get('set-cookie')!
expect(cookie).toContain('HttpOnly')
expect(cookie.includes('; Secure')).toBe(protocol === 'https:')
expect(response.headers.get('cache-control')).toBe('no-store')
const admitted = ctx.connection.admit({ headers: { host: 'pair.test', cookie: cookie.split(';', 1)[0]! } })
if ('rejection' in admitted) throw new Error('Remote pairing Cookie was rejected')
expect(admitted.peer).not.toBe(ctx.connection.browserPeer)
expect(admitted.peer.principal).toEqual({ kind: 'owner' })
vi.setSystemTime(Date.now() + 200)
const retry = await post('status', { id: ticket.id, secret: ticket.secret })
expect(retry.headers.get('set-cookie')).toBe(cookie)
expect(await retry.json()).toEqual({ status: 'completed' })
})
it('keeps anonymous polls pending until approval and validates their authority', async () => {
const { create, post, caller } = await mounted()
vi.useFakeTimers({ toFake: ['Date'] })
const ticket = await create()
const body = { id: ticket.id, secret: ticket.secret }
expect((await post('status', body)).status).toBe(429)
vi.setSystemTime(Date.now() + 200)
const pending = await post('status', body)
expect(await pending.json()).toEqual({ status: 'pending' })
expect(pending.headers.get('set-cookie')).toBeNull()
const wrongHost = await post('status', body, { host: 'other.test', origin: 'http://other.test' })
expect(await wrongHost.json()).toEqual({ status: 'expired' })
const owner = caller()
owner.service.decidePairing(ticket.id, 'deny', owner.signal)
vi.setSystemTime(Date.now() + 200)
const denied = await post('status', body)
expect(await denied.json()).toEqual({ status: 'denied' })
expect(denied.headers.get('set-cookie')).toBeNull()
})
it('shares Remote authentication with QR behind an advertised HTTPS proxy while retaining the listener authority', async () => {
const { ctx, create, caller, post, send } = await mounted('http:', new Map(), false, 'https://pair.test/')
vi.useFakeTimers({ toFake: ['Date'] })
const ticket = await create()
expect(ticket.authority).toBe('http://pair.test')
const owner = caller()
owner.service.decidePairing(ticket.id, 'allow', owner.signal)
vi.setSystemTime(Date.now() + config.pairing.pollIntervalMs)
const response = await post('status', { id: ticket.id, secret: ticket.secret }, { 'x-forwarded-proto': 'https' })
expect(await response.json()).toEqual({ status: 'completed' })
const cookie = response.headers.get('set-cookie')!
expect(cookie).toContain('; Secure')
const paired = ctx.connection.admit({ headers: { host: 'pair.test', cookie: cookie.split(';', 1)[0]! } })
if ('rejection' in paired) throw new Error('Remote pairing Cookie was rejected at the listener authority')
const qr = owner.service.create()
const exchanged = await send('/?login=qr', 'POST', { 'content-type': 'text/plain' }, new URL(qr.url).hash.slice(1))
expect(exchanged.status).toBe(204)
const qrCookie = exchanged.headers.get('set-cookie')!.split(';', 1)[0]!
expect(ctx.connection.admit({ headers: { host: 'pair.test', cookie: qrCookie } })).toEqual({ peer: paired.peer })
expect(() => owner.service.loginUrl()).toThrow(expect.objectContaining({ code: 'remote-connection/token-unavailable' }))
})
it.each(['allow', 'deny'] as const)('delivers the first owner decision %s when opposite decisions precede an in-flight poll body', async (first) => {
const { ctx, create, caller, holdPost } = await mounted()
vi.useFakeTimers({ toFake: ['Date'] })
const ticket = await create()
const owner = caller()
const other = caller()
vi.setSystemTime(Date.now() + config.pairing.pollIntervalMs)
const pending = await holdPost('status', ticket)
const decision = first === 'allow' ? 'approved' : 'denied'
expect(owner.service.decidePairing(ticket.id, first, owner.signal)).toBe(decision)
expect(other.service.decidePairing(ticket.id, first === 'allow' ? 'deny' : 'allow', other.signal)).toBe(decision)
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
pending.finish()
const response = await pending.response
expect(await response.json()).toEqual({ status: first === 'allow' ? 'completed' : 'denied' })
const cookie = response.headers.get('set-cookie')
if (first === 'allow') {
expect(cookie).not.toBeNull()
expect(ctx.connection.admit({ headers: { host: 'pair.test', cookie: cookie!.split(';', 1)[0]! } })).toHaveProperty('peer')
} else {
expect(cookie).toBeNull()
expect(ctx.connection.admit({ headers: { host: 'pair.test' } })).toEqual({ rejection: 401 })
}
})
it.each(['allow', 'deny'] as const)('finishes an in-flight cancellation after the owner chooses %s without issuing a Cookie', async (decision) => {
const { ctx, create, caller, holdPost, post } = await mounted()
vi.useFakeTimers({ toFake: ['Date'] })
const ticket = await create()
const owner = caller()
const pending = await holdPost('cancel', ticket)
expect(owner.service.decidePairing(ticket.id, decision, owner.signal)).toBe(decision === 'allow' ? 'approved' : 'denied')
pending.finish()
const response = await pending.response
const status = decision === 'allow' ? 'cancelled' : 'denied'
expect(await response.json()).toEqual({ status })
expect(response.headers.get('set-cookie')).toBeNull()
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
vi.setSystemTime(Date.now() + config.pairing.pollIntervalMs)
const after = await post('status', { id: ticket.id, secret: ticket.secret })
expect(await after.json()).toEqual({ status })
expect(after.headers.get('set-cookie')).toBeNull()
expect(ctx.connection.admit({ headers: { host: 'pair.test' } })).toEqual({ rejection: 401 })
})
it('withdraws approval while the applicant collection body is still incomplete', async () => {
const { create, caller, holdPost, post } = await mounted()
vi.useFakeTimers({ toFake: ['Date'] })
const ticket = await create()
const owner = caller()
expect(owner.service.decidePairing(ticket.id, 'allow', owner.signal)).toBe('approved')
vi.setSystemTime(Date.now() + config.pairing.pollIntervalMs)
const pending = await holdPost('status', ticket)
const cancelled = await post('cancel', { id: ticket.id, secret: ticket.secret })
expect(await cancelled.json()).toEqual({ status: 'cancelled' })
expect(cancelled.headers.get('set-cookie')).toBeNull()
vi.setSystemTime(Date.now() + config.pairing.pollIntervalMs)
pending.finish()
const response = await pending.response
expect(await response.json()).toEqual({ status: 'cancelled' })
expect(response.headers.get('set-cookie')).toBeNull()
expect(owner.service.decidePairing(ticket.id, 'allow', owner.signal)).toBe('unavailable')
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
})
it('expires approval at the exact deadline while a collection body is still incomplete', async () => {
const { create, caller, holdPost } = await mounted()
vi.useFakeTimers({ toFake: ['Date'] })
const createdAt = Date.now()
const ticket = await create()
const owner = caller()
expect(owner.service.decidePairing(ticket.id, 'allow', owner.signal)).toBe('approved')
vi.setSystemTime(createdAt + config.pairing.requestTtlMs - 1)
const pending = await holdPost('status', ticket)
vi.setSystemTime(createdAt + config.pairing.requestTtlMs)
pending.finish()
const response = await pending.response
expect(await response.json()).toEqual({ status: 'expired' })
expect(response.headers.get('set-cookie')).toBeNull()
expect(owner.service.decidePairing(ticket.id, 'allow', owner.signal)).toBe('unavailable')
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
})
it('keeps an issued Cookie valid after cancellation, a later denial, and the ticket deadline', async () => {
const { ctx, create, caller, post } = await mounted()
vi.useFakeTimers({ toFake: ['Date'] })
const createdAt = Date.now()
const ticket = await create()
const body = { id: ticket.id, secret: ticket.secret }
const owner = caller()
owner.service.decidePairing(ticket.id, 'allow', owner.signal)
vi.setSystemTime(createdAt + config.pairing.pollIntervalMs)
const delivered = await post('status', body)
expect(await delivered.json()).toEqual({ status: 'completed' })
const cookie = delivered.headers.get('set-cookie')!
const cancelled = await post('cancel', body)
expect(await cancelled.json()).toEqual({ status: 'completed' })
expect(cancelled.headers.get('set-cookie')).toBe(cookie)
expect(owner.service.decidePairing(ticket.id, 'deny', owner.signal)).toBe('unavailable')
vi.setSystemTime(createdAt + config.pairing.requestTtlMs)
const expired = await post('status', body)
expect(await expired.json()).toEqual({ status: 'expired' })
expect(expired.headers.get('set-cookie')).toBeNull()
expect(ctx.connection.admit({ headers: { host: 'pair.test', cookie: cookie.split(';', 1)[0]! } })).toHaveProperty('peer')
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
})
it.each(['plugin reload', 'new Host activation'] as const)('forgets approved tickets but preserves issued Cookies after %s', async (mode) => {
const storage = new Map<CredentialKey, CredentialRecord>()
const original = await mounted('http:', storage)
vi.useFakeTimers({ toFake: ['Date'] })
const ticket = await original.create()
const owner = original.caller()
owner.service.decidePairing(ticket.id, 'allow', owner.signal)
vi.setSystemTime(Date.now() + config.pairing.pollIntervalMs)
const delivered = await original.post('status', { id: ticket.id, secret: ticket.secret })
expect(await delivered.json()).toEqual({ status: 'completed' })
const cookie = delivered.headers.get('set-cookie')!
const uncollected = await original.create()
expect(owner.service.decidePairing(uncollected.id, 'allow', owner.signal)).toBe('approved')
let current = original
if (mode === 'plugin reload') {
await original.fiber.dispose()
await original.ctx.plugin(RemoteConnection, config).await()
} else {
await original.ctx.fiber.dispose()
current = await mounted('http:', storage)
}
const resumed = current.caller()
expect(resumed.service.pairingRequests(resumed.signal).requests).toEqual([])
for (const previous of [ticket, uncollected]) {
expect(resumed.service.decidePairing(previous.id, 'allow', resumed.signal)).toBe('unavailable')
const response = await current.post('status', { id: previous.id, secret: previous.secret })
expect(await response.json()).toEqual({ status: 'expired' })
expect(response.headers.get('set-cookie')).toBeNull()
}
expect(current.ctx.connection.admit({ headers: { host: 'pair.test', cookie: cookie.split(';', 1)[0]! } })).toHaveProperty('peer')
})
it.each([
['PAIR.test:80', 'http://pair.test', 'http://pair.test'],
['[::1]:80', 'http://[::1]', 'http://[::1]'],
['pair.test:9090', 'http://pair.test:9090', 'http://pair.test:9090'],
])('normalizes accepted Host %s using the listener protocol', async (host, origin, authority) => {
const { post } = await mounted()
const response = await post('request', undefined, { host, origin })
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ authority })
})
it('records the HTTP peer instead of the destination Host or forwarded addresses', async () => {
const { post, caller } = await mounted()
const response = await post('request', undefined, {
host: '192.0.2.40', origin: 'http://192.0.2.40',
'x-forwarded-for': '198.51.100.77', 'x-real-ip': '198.51.100.78', forwarded: 'for=198.51.100.79',
})
expect(response.status).toBe(200)
expect(await response.json()).toMatchObject({ authority: 'http://192.0.2.40', sourceIp: '127.0.0.1' })
const owner = caller()
expect(owner.service.pairingRequests(owner.signal).requests).toMatchObject([{
authority: 'http://192.0.2.40', sourceIp: '127.0.0.1',
}])
})
it.each([
['192.0.2.24', '192.0.2.24'],
['::ffff:192.0.2.24', '192.0.2.24'],
['2001:db8:abcd:1234::24', '2001:db8:abcd:1234::24'],
[undefined, null],
])('records the socket IP %s in the ticket and approval list', async (remoteAddress, sourceIp) => {
const { onceRequest, create, caller } = await mounted()
onceRequest((request) => {
Object.defineProperty(request.socket, 'remoteAddress', { configurable: true, value: remoteAddress })
}, true)
const ticket = await create()
expect(ticket.sourceIp).toBe(sourceIp)
const owner = caller()
expect(owner.service.pairingRequests(owner.signal).requests).toMatchObject([{ id: ticket.id, sourceIp }])
})
it('captures the connection IP before awaiting the request body', async () => {
const { onceRequest, create } = await mounted()
onceRequest((request) => {
Object.defineProperty(request.socket, 'remoteAddress', { configurable: true, value: undefined })
})
expect((await create()).sourceIp).toBe('127.0.0.1')
})
it('checks request trust and method before anonymous allocation', async () => {
const { post, exchange, caller } = await mounted()
const allocate = vi.spyOn(PairingRequests.prototype, 'create')
const poll = vi.spyOn(PairingRequests.prototype, 'poll')
const issue = vi.spyOn(RemoteBrowserAuth.prototype, 'createSessionCookie')
for (const operation of ['request', 'status', 'cancel'] as const) {
for (const headers of [{ host: 'untrusted.test' }, { origin: 'http://foreign.test' }, { 'sec-fetch-site': 'cross-site' }]) {
const rejected = await post(operation, undefined, headers)
expect(rejected.status).toBe(403)
expect(await rejected.text()).toBe('forbidden')
}
}
expect(allocate).not.toHaveBeenCalled()
expect(poll).not.toHaveBeenCalled()
expect(issue).not.toHaveBeenCalled()
const get = await exchange('request', 'GET')
expect(get.status).toBe(405)
expect(get.headers.get('allow')).toBe('POST')
const owner = caller()
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
})
it('keeps paired Remote credentials independent from Token through provider unload and reload', async () => {
const { ctx, fiber, token, create, post, caller, send } = await mounted('http:', new Map(), true)
ctx.effect(() => ctx.webServer.register({
kind: 'exact', path: '/private',
handler(_request, response, peer) { response.end(peer?.id) },
}))
const entries: WebEntryUrl[] = []
ctx.emit(ctx.webServer, 'webserver/entry-url', 'http://pair.test/', entries)
const entry = entries.find(candidate => new URL(candidate.url).searchParams.has('token'))
if (entry === undefined) throw new Error('Token entry URL was not published')
const tokenResponse = await send(new URL(entry.url).pathname + new URL(entry.url).search)
expect(tokenResponse.status).toBe(303)
const tokenCookie = tokenResponse.headers.get('set-cookie')!.split(';', 1)[0]!
const tokenAdmission = ctx.connection.admit({ headers: { host: 'pair.test', cookie: tokenCookie } })
if ('rejection' in tokenAdmission) throw new Error('Token Cookie was rejected')
vi.useFakeTimers({ toFake: ['Date'] })
const ticket = await create()
const owner = caller()
expect(owner.service.decidePairing(ticket.id, 'allow', owner.signal)).toBe('approved')
vi.setSystemTime(Date.now() + config.pairing.pollIntervalMs)
const paired = await post('status', { id: ticket.id, secret: ticket.secret })
expect(await paired.json()).toEqual({ status: 'completed' })
const remoteCookie = paired.headers.get('set-cookie')!.split(';', 1)[0]!
expect(remoteCookie.split('=', 1)[0]).not.toBe(tokenCookie.split('=', 1)[0])
const remoteAdmission = ctx.connection.admit({ headers: { host: 'pair.test', cookie: remoteCookie } })
if ('rejection' in remoteAdmission) throw new Error('Remote pairing Cookie was rejected')
expect(remoteAdmission.peer).not.toBe(tokenAdmission.peer)
expect(await (await send('/private', 'GET', { cookie: remoteCookie })).text()).toBe(remoteAdmission.peer.id)
await fiber.dispose()
expect(remoteAdmission.peer.signal.aborted).toBe(true)
expect(tokenAdmission.peer.signal.aborted).toBe(false)
expect((await send('/private', 'GET', { cookie: remoteCookie })).status).toBe(401)
expect(await (await send('/private', 'GET', { cookie: tokenCookie })).text()).toBe(tokenAdmission.peer.id)
await ctx.plugin(RemoteConnection, config)
const restored = ctx.connection.admit({ headers: { host: 'pair.test', cookie: remoteCookie } })
if ('rejection' in restored) throw new Error('Remote pairing Cookie did not survive reload')
expect(restored.peer).not.toBe(remoteAdmission.peer)
expect(await (await send('/private', 'GET', { cookie: remoteCookie })).text()).toBe(restored.peer.id)
await token?.dispose()
expect(tokenAdmission.peer.signal.aborted).toBe(true)
expect(restored.peer.signal.aborted).toBe(false)
expect((await send('/private', 'GET', { cookie: tokenCookie })).status).toBe(401)
expect((await send('/private', 'GET', { cookie: remoteCookie })).status).toBe(200)
})
it('refuses malformed, oversized, and extra credential fields without changing requests', async () => {
const { create, post, exchange, caller } = await mounted()
const ticket = await create()
const body = { id: ticket.id, secret: ticket.secret }
expect((await post('status', body, { 'content-type': 'text/plain' })).status).toBe(400)
expect((await post('status', body, { 'content-type': 'application/jsonp' })).status).toBe(400)
expect((await post('status', { ...body, secret: ticket.code })).status).toBe(400)
expect((await post('status', { ...body, approved: true })).status).toBe(400)
expect((await post('status', { ...body, id: 'not-a-uuid' })).status).toBe(400)
expect((await post('request', {})).status).toBe(400)
expect((await post('request', { sourceIp: '198.51.100.80' })).status).toBe(400)
const malformed = await exchange('status', 'POST', '{')
expect(malformed.status).toBe(400)
const oversized = await exchange('status', 'POST', 'x'.repeat(1025))
expect(oversized.status).toBe(413)
const owner = caller()
expect(owner.service.pairingRequests(owner.signal).requests).toHaveLength(1)
expect(owner.service.pairingRequests(owner.signal).requests[0]?.sourceIp).toBe('127.0.0.1')
})
it('bounds requests and expires cancelled tickets without granting a session', async () => {
const { create, post, caller } = await mounted()
vi.useFakeTimers({ toFake: ['Date'] })
const ticket = await create()
expect((await post('request')).status).toBe(429)
const cancelled = await post('cancel', { id: ticket.id, secret: ticket.secret })
expect(await cancelled.json()).toEqual({ status: 'cancelled' })
expect(cancelled.headers.get('set-cookie')).toBeNull()
const owner = caller()
expect(owner.service.decidePairing(ticket.id, 'allow', owner.signal)).toBe('unavailable')
vi.setSystemTime(Date.now() + 10_000)
const expired = await post('status', { id: ticket.id, secret: ticket.secret })
expect(await expired.json()).toEqual({ status: 'expired' })
})
it.each(['declared', 'chunked'] as const)('closes an oversized %s request without waiting for its body to finish', async (mode) => {
const { url, headers, onceRequest, caller } = await mounted()
const serverClosed = new Promise<void>((resolve) => {
onceRequest((incoming) => { incoming.socket.once('close', () => { resolve() }) })
})
const request = httpRequest(`${url}/pairing/request`, {
method: 'POST', headers: {
...headers, connection: 'keep-alive',
...(mode === 'declared' ? { 'content-length': '1025' } : { 'transfer-encoding': 'chunked' }),
},
})
cleanups.push(() => { request.destroy(); return Promise.resolve() })
const clientClosed = new Promise<void>((resolve) => { request.once('close', () => { resolve() }) })
const result = new Promise<{ response: IncomingMessage; body: string }>((resolve, reject) => {
request.once('error', reject)
request.once('response', (response) => {
const chunks: Buffer[] = []
response.on('data', (chunk: Buffer) => { chunks.push(chunk) })
response.once('error', reject)
response.once('end', () => { resolve({ response, body: Buffer.concat(chunks).toString('utf8') }) })
})
})
request.flushHeaders()
if (mode === 'chunked') request.write('x'.repeat(1025))
const { response, body } = await result
expect(response.statusCode).toBe(413)
expect(response.headers.connection).toBe('close')
expect(response.headers['set-cookie']).toBeUndefined()
expect(JSON.parse(body)).toEqual({ status: 'invalid' })
expect(request.writableEnded).toBe(false)
await Promise.all([serverClosed, clientClosed])
const owner = caller()
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
})
it('enforces owner approval even when called outside Gateway dispatch', async () => {
const { create, caller, service } = await mounted()
const ticket = await create()
const guest = caller({ kind: 'pairing-test-guest' })
expect(() => guest.service.pairingRequests(guest.signal)).toThrow(expect.objectContaining({ code: 'remote-connection/owner-required' }))
expect(() => guest.service.decidePairing(ticket.id, 'allow', guest.signal)).toThrow(expect.objectContaining({ code: 'remote-connection/owner-required' }))
expect(() => service.pairingRequests(guest.signal)).toThrow(expect.objectContaining({ code: 'remote-connection/owner-required' }))
const owner = caller()
const cancelled = AbortSignal.abort(new Error('cancelled'))
expect(() => owner.service.decidePairing(ticket.id, 'allow', cancelled)).toThrow('cancelled')
expect(owner.service.pairingRequests(owner.signal).requests).toHaveLength(1)
})
it('embeds pairing directly in the anonymous Remote page and removes its contributions on unload', async () => {
const { fiber, routes, caller, send } = await mounted()
const response = await send('/')
expect(response.status).toBe(401)
const html = await response.text()
expect(html).toContain('<dsh-device-pairing>')
expect(html).toContain('<script defer src="./pairing/client.js"></script>')
expect(response.headers.get('content-security-policy')).toContain("script-src 'self'")
expect(html).not.toContain('name="token"')
const head = await send('/', 'HEAD')
expect(head.status).toBe(401)
expect(await head.text()).toBe('')
const owner = caller()
await fiber.dispose()
expect(routes.some(route => route.path.startsWith('/pairing/'))).toBe(false)
expect(routes.some(route => route.path === '/')).toBe(false)
expect((await send('/')).status).toBe(404)
expect(() => owner.service.pairingRequests(owner.signal)).toThrow(expect.objectContaining({ code: 'remote-connection/disposed' }))
})
it('serves its public browser asset without a cookie and removes the route on unload', async () => {
const { send, fiber } = await mounted()
const asset = '/pairing/client.js'
const response = await send(asset)
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toBe('text/javascript; charset=utf-8')
expect(response.headers.get('cache-control')).toBe('no-store')
expect(response.headers.get('x-content-type-options')).toBe('nosniff')
expect(response.headers.get('set-cookie')).toBeNull()
expect(await response.text()).toBe(renderPairingScript(config.pairing))
const head = await send(asset, 'HEAD')
expect(head.status).toBe(200)
expect(await head.text()).toBe('')
const post = await send(asset, 'POST')
expect(post.status).toBe(405)
expect(post.headers.get('allow')).toBe('GET, HEAD')
await fiber.dispose()
expect((await send(asset)).status).toBe(404)
})
it('joins an unfinished request body on unload without allocating a ticket', async () => {
const { fiber, url, headers, onceRequest, caller } = await mounted()
const received = new Promise<void>((resolve) => { onceRequest(() => { resolve() }) })
const request = httpRequest(`${url}/pairing/request`, { method: 'POST', headers })
const outcome = new Promise<number | undefined>((resolve, reject) => {
request.once('response', (response) => { response.resume(); response.once('end', () =>{ resolve(response.statusCode) }) })
request.once('error', reject)
})
request.flushHeaders()
request.write('{')
await received
const owner = caller()
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
await fiber.dispose()
request.end()
expect(await outcome).toBe(503)
})
it('contains an applicant disconnect while its body is incomplete', async () => {
const { url, headers, onceRequest, caller } = await mounted()
const received = new Promise<void>((resolve) => { onceRequest((incoming) => { incoming.once('close', resolve) }) })
const request = httpRequest(`${url}/pairing/request`, { method: 'POST', headers })
const connected = new Promise<void>((resolve) => { onceRequest(() => { resolve() }) })
const closed = new Promise<void>((resolve) => { request.once('error', () => {}); request.once('close', resolve) })
request.write('{')
await connected
request.destroy()
await Promise.all([received, closed])
const owner = caller()
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
})
it('refuses a body that fails while being read', async () => {
const { onceRequest, post, caller } = await mounted()
onceRequest((request) => { request.emit('error', new Error('body transport failure')) })
const response = await post('request')
expect(response.status).toBe(400)
expect(await response.json()).toEqual({ status: 'invalid' })
const owner = caller()
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([])
})
it('keeps an approval retryable when Remote refuses or fails to sign', async () => {
const { ctx, create, post, caller } = await mounted()
vi.useFakeTimers({ toFake: ['Date'] })
const ticket = await create()
const owner = caller()
owner.service.decidePairing(ticket.id, 'allow', owner.signal)
const issuer = vi.spyOn(RemoteBrowserAuth.prototype, 'createSessionCookie')
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
try {
vi.setSystemTime(Date.now() + 200)
issuer.mockReturnValueOnce(undefined)
const unavailable = await post('status', { id: ticket.id, secret: ticket.secret })
expect(unavailable.status).toBe(503)
expect(unavailable.headers.get('set-cookie')).toBeNull()
vi.setSystemTime(Date.now() + 200)
issuer.mockImplementationOnce(() => { throw new Error('signing unavailable') })
const failed = await post('status', { id: ticket.id, secret: ticket.secret })
expect(failed.status).toBe(503)
expect(failed.headers.get('set-cookie')).toBeNull()
vi.setSystemTime(Date.now() + 200)
const retry = await post('status', { id: ticket.id, secret: ticket.secret })
expect(await retry.json()).toEqual({ status: 'completed' })
expect(retry.headers.get('set-cookie')).toContain('HttpOnly')
} finally { issuer.mockRestore(); warn.mockRestore() }
})
it('refuses a retained HTTP callback after its plugin has unloaded', async () => {
const { ctx, fiber, routes, post } = await mounted()
const callback = routes.find(route => route.path === '/pairing/request')!
await fiber.dispose()
ctx.effect(() => ctx.webServer.register(callback))
const response = await post('request')
expect(response.status).toBe(503)
expect(await response.json()).toEqual({ status: 'unavailable' })
})
it('rejects a lifetime too short to allow its first poll', async () => {
const ctx = new Context()
cleanups.push(() => ctx.fiber.dispose())
expect(() => new RemoteConnection(ctx, { ...config, pairing: { ...config.pairing, requestTtlMs: config.pairing.pollIntervalMs } }))
.toThrow('pairing.requestTtlMs must exceed pairing.pollIntervalMs')
})
it.each(['request', 'status'] as const)('keeps a delayed old %s separate from a replacement on the same connection IP', async (operation) => {
const { create, post, caller, holdPost } = await mounted()
vi.useFakeTimers({ toFake: ['Date'] })
const owner = caller()
const identity = { id: randomUUID() as PairingTicket['id'], secret: randomBytes(32).toString('base64url') }
const first = operation === 'status' ? await create() : identity
const delayed = await holdPost(operation, first)
if (operation === 'request') expect((await post('request', first)).status).toBe(200)
expect(await (await post('cancel', { id: first.id, secret: first.secret })).json()).toEqual({ status: 'cancelled' })
vi.setSystemTime(Date.now() + config.pairing.requestIntervalMs)
const replacement = await create()
expect(replacement.id).not.toBe(first.id)
expect(owner.service.pairingRequests(owner.signal).requests.map(row => row.id)).toEqual([replacement.id])
expect(owner.service.decidePairing(first.id, 'allow', owner.signal)).toBe('unavailable')
vi.setSystemTime(Date.now() + config.pairing.pollIntervalMs)
delayed.finish()
const oldResponse = await delayed.response
expect(oldResponse.headers.has('set-cookie')).toBe(false)
expect(await oldResponse.json()).toMatchObject(operation === 'request' ? { id: first.id } : { status: 'cancelled' })
expect(owner.service.pairingRequests(owner.signal).requests).toEqual([expect.objectContaining({ id: replacement.id, sourceIp: '127.0.0.1' })])
const freshStatus = await post('status', { id: replacement.id, secret: replacement.secret })
expect(await freshStatus.json()).toEqual({ status: 'pending' })
expect(freshStatus.headers.has('set-cookie')).toBe(false)
expect(owner.service.decidePairing(replacement.id, 'allow', owner.signal)).toBe('approved')
vi.setSystemTime(Date.now() + config.pairing.pollIntervalMs)
expect((await post('status', { id: replacement.id, secret: replacement.secret })).headers.has('set-cookie')).toBe(true)
})
it('rejects a retry delay cap below the applicant polling interval', () => {
const ctx = new Context()
expect(() => new RemoteConnection(ctx, { ...config, pairing: { ...config.pairing, retryMaxDelayMs: 1 } }))
.toThrow('pairing.retryMaxDelayMs must be at least pairing.pollIntervalMs')
})
@@ -0,0 +1,53 @@
/** Source-only lifecycle fixture; the Web replay exercises the actual generated pairing contribution. */
import { z } from 'zod'
import { createTypertRemoteInfo } from '@deepseek-ai/dsh-typert-protocol/remote-info'
import type { TypertRemoteCodecSpec } from '@deepseek-ai/dsh-typert-protocol'
function codec(create: () => z.ZodType): TypertRemoteCodecSpec {
return { mode: 'strict', typeSymbol: '@pairing-test#value', create }
}
const id = codec(() => z.string())
const decision = codec(() => z.enum(['allow', 'deny']))
const nullableId = codec(() => z.string().nullable())
const invitationState = (): z.ZodType => z.enum(['pending', 'used', 'expired', 'cancelled', 'replaced', 'none'])
export default createTypertRemoteInfo({
package: '@deepseek-ai/dsh-client-remote-connection',
methods: {
'remoteConnection/status': {
service: 'remoteConnection', invocation: { kind: 'direct' },
parameters: [{ name: 'id', source: 'json', codec: nullableId, strictCodec: nullableId }],
result: codec(() => z.object({
url: z.string(), availability: z.enum(['available', 'unreachable-host', 'untrusted-host']),
ticket: invitationState(), pollIntervalMs: z.number(),
})),
},
'remoteConnection/create': {
service: 'remoteConnection', invocation: { kind: 'direct' }, parameters: [],
result: codec(() => z.object({ id: z.string(), url: z.string(), lifetimeMs: z.number() })),
},
'remoteConnection/loginUrl': {
service: 'remoteConnection', invocation: { kind: 'direct' }, parameters: [],
result: codec(() => z.string()),
},
'remoteConnection/cancel': {
service: 'remoteConnection', invocation: { kind: 'direct' },
parameters: [{ name: 'id', source: 'json', codec: id, strictCodec: id }], result: codec(invitationState),
},
'remoteConnection/decidePairing': {
service: 'remoteConnection', invocation: { kind: 'direct' }, cancellation: { parameter: 'signal' },
parameters: [
{ name: 'id', source: 'json', codec: id, strictCodec: id },
{ name: 'decision', source: 'json', codec: decision, strictCodec: decision },
],
result: codec(() => z.enum(['approved', 'denied', 'unavailable'])),
},
'remoteConnection/pairingRequests': {
service: 'remoteConnection', invocation: { kind: 'direct' }, cancellation: { parameter: 'signal' }, parameters: [],
result: codec(() => z.object({ requests: z.array(z.object({
id: z.string(), code: z.string(), authority: z.string(), sourceIp: z.string().nullable(), expiresInMs: z.number(),
})), pollIntervalMs: z.number() })),
},
},
}, z)
@@ -168,6 +168,20 @@ it('serves QR mode from the root even to a browser already authenticated through
expect(service.status(ticket.id).ticket).toBe('used')
})
it('keeps Token sign-in and pairing available after a QR invitation is rejected', async () => {
const { send, renderedPeers } = await mounted(true)
const rejected = await send('/?login=qr', 'POST', { 'content-type': 'text/plain' }, 'a'.repeat(43))
expect(rejected.status).toBe(410)
expect(rejected.headers['set-cookie']).toBeUndefined()
const page = await send('/?login=qr')
expect(page.status).toBe(200)
expect(page.body).toContain('id="token-form"')
expect(page.body).toContain('<dsh-device-pairing>')
expect(page.body).toContain('./pairing/client.js')
expect(page.body).not.toContain('PRIVATE_APPLICATION')
expect(renderedPeers).toHaveLength(0)
})
it('keeps source refusals outside the root page and invitation exchange', async () => {
const { ctx, publicUrl, send, service, renderedPeers } = await mounted()
const ticket = service.create()
@@ -12,6 +12,7 @@ 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'
import { PairingApproval } from '../src/client/pairing-approval.ts'
afterEach(cleanup)
@@ -21,7 +22,7 @@ const ready: RemoteConnectionState = {
}
const ticket = { id: 'code-a' as RemoteLoginId, url: 'https://host.example/app/?login=qr#token=private', lifetimeMs: 120_000 }
function panel(overrides: Partial<RemoteConnectionState> = {}, language: 'en' | 'zh' = 'en', linkOverrides: Partial<LoginLinkState> = {}) {
function panel(overrides: Partial<RemoteConnectionState> = {}, language: 'en' | 'zh' = 'en', linkOverrides: Partial<LoginLinkState> = {}, pairingAvailable = false) {
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() }
@@ -31,11 +32,16 @@ function panel(overrides: Partial<RemoteConnectionState> = {}, language: 'en' |
locale.register('remoteConnection', { en, zh })
locale.setLocale(language)
const t = locale.bind('remoteConnection')
const approval = new PairingApproval({ decidePairing: vi.fn() }, async () => {})
if (pairingAvailable) approval.activate()
onTestFinished(() => { approval.dispose() })
const useResource = vi.fn(() => ({ status: 'live', value: { requests: [], pollIntervalMs: 1000 }, failure: undefined }))
const props = {
...actions, t, useRemoteConnection: bindSnapshotSelector(state), useLoginLink: bindSnapshotSelector(linkState),
useApproval: bindSnapshotSelector(approval.state), useResource, decide: vi.fn(), dismiss: vi.fn(),
} as RemoteConnectionSectionProps
render(<RemoteConnectionSection {...props} />)
return { ...actions, state, linkState }
return { ...actions, state, linkState, useResource }
}
describe('Remote connection section', () => {
@@ -7,10 +7,12 @@
},
"include": [
"src/client",
"src/anonymous",
"src/login-page.ts",
"src/login-locales.ts",
"src/types.ts",
"src/css-modules.d.ts"
"src/css-modules.d.ts",
"src/pairing-types.ts"
],
"references": [
{
@@ -45,6 +47,12 @@
},
{
"path": "../../api/remotes/tsconfig.client.json"
},
{
"path": "../../api/remote-access/tsconfig.client.json"
},
{
"path": "../resources"
}
]
}
@@ -6,7 +6,8 @@
"tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo"
},
"include": [
"src/*.ts"
"src/*.ts",
"src/anonymous"
],
"references": [
{
@@ -35,6 +36,9 @@
},
{
"path": "../../util/error"
},
{
"path": "../../api/remote-access/tsconfig.host.json"
}
]
}
@@ -4424,8 +4424,8 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
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.',
summary: 'Complete Remote connection panel with QR, login-link, and pairing approval state.',
doc: 'Complete Remote connection panel with QR, login-link, and pairing approval state.\nReceives invitation and login-link selectors, their actions, and close().\nuseApproval(selector) exposes owner-access availability and decision outcomes; decide() and dismiss() manage them.\nReplacing this panel hides all default sections; unloading restores their current state.',
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 /** Leave the page: close the settings panel, or on the Plugins page return to the view the page was opened from. */\n close: () => void\n}',
@@ -4445,14 +4445,14 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
],
keyDomain: '',
hookContext: '',
slotInject: 'RemoteConnectionFace & LoginLinkFace',
slotInject: 'RemoteConnectionFace & LoginLinkFace & PairingInjected',
declaredBy: 'an entry in \'settings.section\' (client-remote-connection), so it exists while that entry is mounted',
occupants: [
'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',
source: 'packages/client/remote-connection/src/client/slots.ts:16',
},
{
key: 'settings.remoteConnection.extensions',
@@ -4758,6 +4758,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [
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-remote-connection PairingToast id \'remote-connection-pairing-notice\'',
'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\'',
@@ -3183,8 +3183,8 @@ 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.',
summary: 'Owner-authorized browser login through QR codes, private links, or pairing requests.',
description: 'Owner-authorized browser login through QR codes, private links, or pairing requests.',
methods: [
{
signature: '@Remote status(id: RemoteLoginId | null): RemoteConnectionStatus',
@@ -3210,6 +3210,18 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
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.',
},
{
signature: '@Remote pairingRequests(signal: AbortSignal): PairingRequestsValue',
description: 'Read pending requests without the credentials used to collect their sessions.',
parameters: [{ name: 'signal', description: 'current Remote call\'s cancellation.' }],
returns: 'pending codes and the deployment\'s refresh interval.',
},
{
signature: '@Remote decidePairing(id: PairingRequestId, decision: PairingDecision, signal: AbortSignal): PairingDecisionResult',
description: 'Approve or deny one displayed code; the first decision is retained across retries.',
parameters: [{ name: 'id', description: 'request selected after comparing its code with the applicant\'s screen.' }, { name: 'decision', description: 'allow or deny full owner access for the requesting browser.' }, { name: 'signal', description: 'current Remote call\'s cancellation before the decision commits.' }],
returns: 'committed decision, or unavailable after cancellation, expiry, or collection.',
},
],
},
{
@@ -8914,6 +8926,22 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'PaidTranslationSpec',
declaration: 'export interface PaidTranslationSpec extends TranslationSpecFields {\n readonly provider: PaidTranslationProvider;\n readonly sessionId: SessionId;\n}',
},
{
name: 'PairingDecision',
declaration: 'export type PairingDecision = \'allow\' | \'deny\';',
},
{
name: 'PairingDecisionResult',
declaration: 'export type PairingDecisionResult = \'approved\' | \'denied\' | \'unavailable\';',
},
{
name: 'PairingRequestId',
declaration: 'export type PairingRequestId = Branded<\'PairingRequestId\'>;',
},
{
name: 'PairingRequestsValue',
declaration: 'export interface PairingRequestsValue {\n readonly requests: readonly PendingPairingRequest[];\n readonly pollIntervalMs: number;\n}',
},
{
name: 'PaneOpenArgs',
declaration: 'export interface PaneOpenArgs {\n id: string;\n title?: string;\n focus?: true;\n closeOnEscape?: true;\n holdToasts?: true;\n rows?: number;\n columns?: number;\n}',
@@ -8942,6 +8970,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'PendingModule',
declaration: 'export interface PendingModule {\n url: string;\n reason: \'host-module\' | \'unmanaged-plugin\' | \'module-comparison\';\n}',
},
{
name: 'PendingPairingRequest',
declaration: 'export interface PendingPairingRequest {\n readonly id: PairingRequestId;\n readonly code: string;\n readonly authority: string;\n readonly sourceIp: string | null;\n readonly expiresInMs: number;\n}',
},
{
name: 'PendingRemoteEventInfo',
declaration: 'export interface PendingRemoteEventInfo {\n readonly event: string;\n readonly agentId: RemoteEventAgentId;\n}',
@@ -72,7 +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-remote-connection` | yes | QR login, private login links, and owner-approved browser pairing |
| `@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 |
+6
View File
@@ -3924,6 +3924,12 @@ importers:
'@deepseek-ai/dsh-credentials':
specifier: workspace:*
version: link:../../credentials/credentials
'@deepseek-ai/dsh-client-resources':
specifier: workspace:*
version: link:../resources
'@deepseek-ai/dsh-api-remote-access':
specifier: workspace:*
version: link:../../api/remote-access
'@deepseek-ai/cordis':
specifier: workspace:~
version: link:../../../vendor/cordis
+4
View File
@@ -1005,6 +1005,10 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
WebAuthRequest: 'web-server.md',
WebAuthenticationRule: 'web-server.md',
WebFallback: 'web-server.md',
PairingRequestId: 'web-server.md',
PairingDecision: 'web-server.md',
PairingDecisionResult: 'web-server.md',
PairingRequestsValue: 'web-server.md',
WebRoute: 'web-server.md',
WebResourceRoute: 'web-server.md',
IndexInjection: 'web-server.md',
+1 -1
View File
@@ -112,7 +112,7 @@ const SERVICE_ROLES: ServiceRole[] = [
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.',
note: 'Owns QR invitations, approved pairing requests, Remote browser credentials and the anonymous login document; its Client provides approval controls and an independent Token-link shortcut.',
},
{
key: 'actionCards',
+2
View File
@@ -94,6 +94,8 @@ const PEER_REQUIRED_HOST_EXPORTS = {
// Stateless; a safe classification would turn the forge panel's forge and worktree peers into dependencies.
'@deepseek-ai/dsh-experimental-forge': ['changeRequestKey'],
'@deepseek-ai/dsh-experimental-worktree': ['generatedWorktreeName', 'CREATED_RECORD', 'createdWorktreeSchema'],
// Stateless; the injected WebServer remains a peer.
'@deepseek-ai/dsh-host-webserver': ['normalizeBindAddress'],
// The forge panel matches ctx.fs failures with `instanceof FsError`.
'@deepseek-ai/dsh-fs': ['FsError'],
'@deepseek-ai/dsh-scope': ['carrierKeyOf', 'createScope', 'scopeOf', 'scopeParentOf', 'scopeTarget'],
+3
View File
@@ -8,6 +8,9 @@
"rewriteRelativeImportExtensions": false
},
"include": [
"apps/web/tests/device-pairing.e2e.ts",
"apps/web/tests/pairing-completion.e2e.ts",
"apps/web/tests/pairing-recovery.e2e.ts",
"snapshots/session/headless.snapshot.ts",
"apps/web/tests/remote-connection.e2e.ts",
"apps/web/tests/remote-connection-fixture.ts",