diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index f2b2097573..54d04615b7 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -845,6 +845,29 @@ async function bootEmptyPreview(origin: string, browser: Browser): Promise 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 } + }).__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 diff --git a/packages/client/remote-connection/src/base64.ts b/packages/client/remote-connection/src/base64.ts new file mode 100644 index 0000000000..304c7cfc2e --- /dev/null +++ b/packages/client/remote-connection/src/base64.ts @@ -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 +} diff --git a/packages/client/remote-connection/src/login-tickets.ts b/packages/client/remote-connection/src/login-tickets.ts index b2d7b9d29d..bdcdd17bde 100644 --- a/packages/client/remote-connection/src/login-tickets.ts +++ b/packages/client/remote-connection/src/login-tickets.ts @@ -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(randomUUID()) const expiresAt = Date.now() + lifetimeMs const url = new URL('remote-login', root.endsWith('/') ? root : `${root}/`) diff --git a/packages/client/remote-connection/src/remote-auth.ts b/packages/client/remote-connection/src/remote-auth.ts index e09a1562ff..1e046ccc6b 100644 --- a/packages/client/remote-connection/src/remote-auth.ts +++ b/packages/client/remote-connection/src/remote-auth.ts @@ -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 { 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 { - 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 }