fix(remote-connection): support Preview credential encoding

This commit is contained in:
EricMoin committed 2026-11-19 21:24:42 +08:00
1 parent 3059225fd9
commit 1d6bec2575
4 files changed
+52 -11

No files matched your search

+23
View File
@@ -845,6 +845,29 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise<void>
return body.result.value.items.length
})
expect(sessionCount).toBe(0)
const remoteStatus = 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('/api/remoteConnection/status', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
type: 'client-request', rpcId: 'empty-preview-remote-status', method: 'remoteConnection/status',
payload: { args: { id: null } },
}),
})
const body = await response.json() as {
result: { ok: true; value: { url: string; availability: string; ticket: string; pollIntervalMs: number } }
| { ok: false; error: { message: string } }
}
if (!body.result.ok) throw new Error(`empty remoteConnection/status failed: ${body.result.error.message}`)
return body.result.value
})
expect(remoteStatus).toEqual({
url: 'http://127.0.0.1:3080', availability: 'unreachable-host', ticket: 'none', pollIntervalMs: 1000,
})
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
@@ -0,0 +1,22 @@
/** Canonical URL-safe credentials for Node and Preview's Buffer implementation. */
/**
* Encode bytes without padding, using Buffer encodings supported by Preview.
* @param bytes - credential or signed payload bytes.
* @returns canonical URL-safe base64 text.
*/
export function encodeBase64Url(bytes: Uint8Array): string {
return Buffer.from(bytes).toString('base64').replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '')
}
/**
* Decode only canonical, nonempty URL-safe base64 text.
* @param value - untrusted credential or signed payload text.
* @returns decoded bytes, or undefined for invalid alphabet, padding, or trailing bits.
*/
export function decodeBase64Url(value: string): Buffer | undefined {
if (!/^[A-Za-z0-9_-]+$/u.test(value) || value.length % 4 === 1) return undefined
const padding = '='.repeat((4 - value.length % 4) % 4)
const bytes = Buffer.from(value.replaceAll('-', '+').replaceAll('_', '/') + padding, 'base64')
return encodeBase64Url(bytes) === value ? bytes : undefined
}
@@ -3,6 +3,7 @@ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypt
import { brandString } from '@deepseek-ai/dsh-brand'
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import type { RemoteLoginId, RemoteLoginState, RemoteLoginTicket } from './types.ts'
import { encodeBase64Url } from './base64.ts'
type Ticket = {
readonly id: RemoteLoginId
@@ -23,7 +24,7 @@ export class LoginTickets {
* @returns the only response carrying the plaintext credential.
*/
create(root: string, lifetimeMs: number): RemoteLoginTicket {
const token = randomBytes(32).toString('base64url')
const token = encodeBase64Url(randomBytes(32))
const id = brandString<RemoteLoginId>(randomUUID())
const expiresAt = Date.now() + lifetimeMs
const url = new URL('remote-login', root.endsWith('/') ? root : `${root}/`)
@@ -5,6 +5,7 @@ import { credentialKey } from '@deepseek-ai/dsh-credentials'
import type { CredentialProvider, CredentialRecord } from '@deepseek-ai/dsh-credentials'
import { HarnessError } from '@deepseek-ai/dsh-error'
import type { ConnectionTrustRequest } from '@deepseek-ai/dsh-client-connection'
import { decodeBase64Url as decode, encodeBase64Url as encode } from './base64.ts'
const RECORD_KEY = credentialKey('client-remote-connection', 'browser-session')
const VERSION = 1
@@ -36,12 +37,6 @@ function record(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function decode(value: string): Buffer | undefined {
if (!/^[A-Za-z0-9_-]+$/u.test(value) || value.length % 4 === 1) return undefined
const bytes = Buffer.from(value, 'base64url')
return bytes.toString('base64url') === value ? bytes : undefined
}
function readSecret(value: CredentialRecord | undefined): Buffer | undefined {
if (value === undefined) return undefined
if (value.kind !== 'grant' || !record(value.payload)
@@ -63,7 +58,7 @@ function readSecret(value: CredentialRecord | undefined): Buffer | undefined {
}
async function initializeSecret(credentials: CredentialProvider): Promise<Buffer> {
const payload = { version: VERSION, secret: randomBytes(SECRET_BYTES).toString('base64url') }
const payload = { version: VERSION, secret: encode(randomBytes(SECRET_BYTES)) }
let stored: CredentialRecord | undefined
try {
stored = await credentials.modifyRecord(RECORD_KEY, (current) => {
@@ -108,7 +103,7 @@ function audience(request: ConnectionTrustRequest, secure: boolean): string | un
}
function cookieName(authority: string): string {
return `dsh-remote-${createHash('sha256').update(authority).digest('base64url')}`
return `dsh-remote-${encode(createHash('sha256').update(authority).digest())}`
}
function cookieValue(value: string, name: string): string | undefined {
@@ -168,9 +163,9 @@ export class RemoteBrowserAuth {
const issuedAt = Date.now()
const expiresAt = issuedAt + this.lifetimeMs
const payload: CookiePayload = { version: VERSION, authority, issuedAt, expiresAt }
const body = Buffer.from(JSON.stringify(payload)).toString('base64url')
const body = encode(Buffer.from(JSON.stringify(payload)))
const signed = `v${VERSION}.${body}`
const signature = createHmac('sha256', this.secret).update(signed).digest('base64url')
const signature = encode(createHmac('sha256', this.secret).update(signed).digest())
const cookie = `${cookieName(authority)}=${signed}.${signature}; Max-Age=${String(this.lifetimeMs / 1000)}; Path=/; Expires=${new Date(expiresAt).toUTCString()}; HttpOnly; SameSite=Strict`
return secure ? `${cookie}; Secure` : cookie
}