diff --git a/prototype/channel-browser/src/lib.rs b/prototype/channel-browser/src/lib.rs index 312e616b9..c69ca85d0 100644 --- a/prototype/channel-browser/src/lib.rs +++ b/prototype/channel-browser/src/lib.rs @@ -445,6 +445,9 @@ pub fn channel_wire_limits() -> Result { "rooms": MAX_ROOMS, "profilePage": PROFILE_PAGE_SIZE, "eventBytes": wire::CHANNEL_MESSAGE_BYTES, + "inputFrameBytes": piik_channel_core::input::INPUT_FRAME_BYTES, + "inputCommandBytes": piik_channel_core::input::INPUT_COMMAND_BYTES, + "inputTextBytes": piik_channel_core::input::INPUT_TEXT_BYTES, "identityImageBytes": wire::IDENTITY_IMAGE_URL_BYTES, })) } diff --git a/prototype/channel-core/src/input.rs b/prototype/channel-core/src/input.rs index 8238978a9..f412732a4 100644 --- a/prototype/channel-core/src/input.rs +++ b/prototype/channel-core/src/input.rs @@ -5,6 +5,10 @@ use serde::{Deserialize, Serialize}; use serde_json::Value; use uuid::Uuid; +pub const INPUT_FRAME_BYTES: usize = 8192; +pub const INPUT_COMMAND_BYTES: usize = 4096; +pub const INPUT_TEXT_BYTES: usize = 2048; + #[derive(Clone, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct InputRegistration { @@ -144,7 +148,7 @@ pub fn route( || serde_json::to_vec(frame) .map_err(|_| "invalid_input_frame")? .len() - > crate::conversation::CONTROL_FRAME_BYTES + > INPUT_FRAME_BYTES { return Err("invalid_input_frame"); } diff --git a/prototype/channel-native/src/input/cipher.rs b/prototype/channel-native/src/input/cipher.rs index 74bd91ad0..58eac5f55 100644 --- a/prototype/channel-native/src/input/cipher.rs +++ b/prototype/channel-native/src/input/cipher.rs @@ -5,6 +5,7 @@ use aes_gcm::{ }; use anyhow::{anyhow, ensure, Result}; use base64::{engine::general_purpose::STANDARD, Engine}; +use piik_channel_core::input::INPUT_COMMAND_BYTES; use uuid::Uuid; pub(super) struct Cipher { @@ -25,7 +26,7 @@ impl Cipher { pub fn open(&mut self, data: &str, flow: Uuid) -> Result> { ensure!(data.len() <= 6144, "input_packet_too_large"); let bytes = STANDARD.decode(data)?; - ensure!((36..=4132).contains(&bytes.len()), "invalid_input_packet"); + ensure!((36..=36 + INPUT_COMMAND_BYTES).contains(&bytes.len()), "invalid_input_packet"); let sequence = u64::from_be_bytes(bytes[..8].try_into()?); ensure!(sequence > self.received, "stale_input_packet"); let plain = self diff --git a/prototype/channel-native/src/input/mod.rs b/prototype/channel-native/src/input/mod.rs index 6582b1547..756ca17a1 100644 --- a/prototype/channel-native/src/input/mod.rs +++ b/prototype/channel-native/src/input/mod.rs @@ -1464,7 +1464,7 @@ impl InputEvent { Some(Action::Held(Held::Button(button), down)) } Self::Wheel { delta } if (-1200..=1200).contains(&delta) => Some(Action::Wheel(delta)), - Self::Text { text } if text.len() <= 2048 && !text.contains('\0') => { + Self::Text { text } if text.len() <= piik_channel_core::input::INPUT_TEXT_BYTES && !text.contains('\0') => { Some(Action::Text(text)) } _ => None, diff --git a/prototype/channel-native/src/peer.rs b/prototype/channel-native/src/peer.rs index 1cb59f71f..99d972db9 100644 --- a/prototype/channel-native/src/peer.rs +++ b/prototype/channel-native/src/peer.rs @@ -2521,7 +2521,7 @@ impl Driver { } } Lane::Input => { - if !ready.open() || message.len() > 8192 { + if !ready.open() || message.len() > piik_channel_core::input::INPUT_FRAME_BYTES { continue; } if let Ok(frame) = serde_json::from_slice(message.as_slice()) { diff --git a/prototype/channel-native/src/peer/transport.rs b/prototype/channel-native/src/peer/transport.rs index a1dbac794..9f958ba01 100644 --- a/prototype/channel-native/src/peer/transport.rs +++ b/prototype/channel-native/src/peer/transport.rs @@ -56,6 +56,8 @@ impl Estimate { } } +const INPUT_SEND_BUFFER_BYTES: usize = 8192; + // Finite SDK probing target when source demand is unknown, not a media limit. // An explicitly idle connection requests zero instead. const UNKNOWN_DEMAND_PROBE_BPS: u64 = 100_000_000; @@ -1768,7 +1770,7 @@ impl Channel { .context("channel not open")?; if input { ensure!( - channel.buffered_amount() + bytes.len() <= 8192, + channel.buffered_amount() + bytes.len() <= INPUT_SEND_BUFFER_BYTES, "input_channel_busy" ); } diff --git a/src/client/channel/input.ts b/src/client/channel/input.ts index 02ea70b2b..47463a5ab 100644 --- a/src/client/channel/input.ts +++ b/src/client/channel/input.ts @@ -1,3 +1,4 @@ +import { inputFrameFits } from "../remote-control/protocol"; import { EncryptedInput, type InputPacket, type InputTransport } from "../remote-control/input-route"; import { loadRoomHosting } from "./hosting"; import type { ChannelCommand, ChannelSnapshot } from "./protocol"; @@ -39,7 +40,7 @@ export class ChannelInput { this.channels.delete(pairId); if (channel) { const message = (event: MessageEvent) => { - if (typeof event.data !== "string" || event.data.length > 8192) return; + if (typeof event.data !== "string" || !inputFrameFits(event.data)) return; void this.receive(pairId, channel, event.data).catch(() => { /* Invalid input has no authority. */ }); }; const refresh = () => this.update(); diff --git a/src/client/channel/transport.ts b/src/client/channel/transport.ts index ef7666a25..d6b08a35f 100644 --- a/src/client/channel/transport.ts +++ b/src/client/channel/transport.ts @@ -1,4 +1,5 @@ import { data_frame_bytes, data_queue_frames } from "../../../prototype/channel-browser/pkg/piik_channel_browser"; +import { inputFrameFits } from "../remote-control/protocol"; import { LinearCandidateAdmission } from "../webrtc/linear-ice-candidate"; import { addRemoteIceCandidate } from "../webrtc/remote-ice-candidate"; import { collectTrackConnectionMetrics, decodedVideoFrameSamples, type StatsAccumulator } from "../webrtc/stats"; @@ -14,6 +15,7 @@ import { cloneSenderVideoTrack, senderCaptureTrack, stopSenderVideoTrack } from import { waitForConnectionOperation } from "../webrtc/connection-operation"; const TRANSPORT_PREPARE_MS = 20_000; +const INPUT_SEND_BUFFER_BYTES = 8192; const DATA_SEND_BUFFER_BYTES = 65536; export interface OutgoingMedia { @@ -243,7 +245,7 @@ export class ChannelTransport { sendInput(frame: string): boolean { const channel = this.input; if (!this.inputEnabled || channel?.readyState !== "open" || this.closed || this.pc.connectionState !== "connected") return false; - if (frame.length > 8192 || channel.bufferedAmount > 8192) { channel.close(); return false; } + if (!inputFrameFits(frame) || channel.bufferedAmount > INPUT_SEND_BUFFER_BYTES) { channel.close(); return false; } try { channel.send(frame); return true; } catch { channel.close(); return false; } } diff --git a/src/client/components/living/RemoteKeyboard.tsx b/src/client/components/living/RemoteKeyboard.tsx index 002e0f4fb..92ada85fc 100644 --- a/src/client/components/living/RemoteKeyboard.tsx +++ b/src/client/components/living/RemoteKeyboard.tsx @@ -1,7 +1,7 @@ import { useCallback, useEffect, useId, useMemo, useRef, useState, type CSSProperties, type ReactNode, type RefObject } from "react"; import { createPortal } from "react-dom"; import type { RemoteInputEvent } from "../../remote-control/input-session"; -import { REMOTE_TEXT_BYTES, type RemoteInputPlatform } from "../../remote-control/protocol"; +import { remoteTextFits, type RemoteInputPlatform } from "../../remote-control/protocol"; import { RemoteKeyboardPresses } from "../../remote-control/keyboard"; import { readRoomPreferences, saveRoomPreferences, REMOTE_KEYBOARD_PAGES, type RoomPreferences } from "../../lib/room-preferences"; import { onDocumentInactive } from "../../ui/document-active"; @@ -68,7 +68,7 @@ export function RemoteKeyboard({ input, close, mouseControl, inputSurface, touch const [combineKeys, setCombineKeys] = useState(() => readRoomPreferences().combineKeys); const composing = useRef(false); const editor = useRef(null); - const textTooLong = new TextEncoder().encode(text).length > REMOTE_TEXT_BYTES; + const textTooLong = !remoteTextFits(text); const panel = useRef(null); const panelWindow = usePanelWindow(true, onSurfaceChange); const owner = panelWindow.surfaceDocument ?? document; diff --git a/src/client/remote-control/input-route.ts b/src/client/remote-control/input-route.ts index 7024f5f4c..decbeeb5d 100644 --- a/src/client/remote-control/input-route.ts +++ b/src/client/remote-control/input-route.ts @@ -2,6 +2,8 @@ export type InputIdentity = { endpointId: string; secret: string }; export type InputPacket = { id?: string; epoch?: string; data?: string; closed?: boolean; ready?: boolean }; export type InputTransport = Pick; +const MAX_QUEUED_BASE64_CHARS = 8192; + // Keys arrive over authenticated room signaling. An intermediate Viewer/SFU // transports ciphertext and cannot impersonate the approved controller. export class EncryptedInput extends EventTarget implements InputTransport { @@ -12,7 +14,7 @@ export class EncryptedInput extends EventTarget implements InputTransport { private readonly key: Promise; private outbound = Promise.resolve(); private inbound = Promise.resolve(); - private incomingBytes = 0; + private incomingBase64Chars = 0; constructor(private readonly identity: InputIdentity, private readonly counter: { sent: bigint }, private readonly transmit: (packet: InputPacket) => void, epoch = crypto.randomUUID().replaceAll("-", "")) { super(); @@ -37,8 +39,8 @@ export class EncryptedInput extends EventTarget implements InputTransport { }).catch(() => this.close()).finally(() => { this.bufferedAmount -= plain.length; }); } receive(data: string): void { - if (this.incomingBytes + data.length > 8192) { this.close(); return; } - this.incomingBytes += data.length; + if (this.incomingBase64Chars + data.length > MAX_QUEUED_BASE64_CHARS) { this.close(); return; } + this.incomingBase64Chars += data.length; this.inbound = this.inbound.then(async () => { if (this.readyState !== "open") return; const bytes = Uint8Array.from(atob(data), c => c.charCodeAt(0)); @@ -51,7 +53,7 @@ export class EncryptedInput extends EventTarget implements InputTransport { this.received = sequence; this.dispatchEvent(new MessageEvent("message", { data: new TextDecoder().decode(plain) })); }).catch(() => { /* Unauthenticated relay data has no input meaning. */ }) - .finally(() => { this.incomingBytes -= data.length; }); + .finally(() => { this.incomingBase64Chars -= data.length; }); } close(): void { if (this.readyState === "closed") return; diff --git a/src/client/remote-control/input-session.ts b/src/client/remote-control/input-session.ts index 0c88bbf1b..df26bca7a 100644 --- a/src/client/remote-control/input-session.ts +++ b/src/client/remote-control/input-session.ts @@ -1,7 +1,9 @@ import type { InputTransport } from "./input-route"; import { debugError, debugEvent } from "../lib/debug"; -import { remoteInputStateSchema, remoteTextAvailable, remoteGamepadAvailable, type RemoteInputState, type RemoteGamepadReport } from "./protocol"; +import { remoteInputStateSchema, remoteTextFits, remoteTextAvailable, remoteGamepadAvailable, type RemoteInputState, type RemoteGamepadReport } from "./protocol"; export type { RemoteInputState } from "./protocol"; +const MAX_QUEUED_PLAINTEXT_BYTES = 8192; + // Each virtual contact has its own source. Physical keys use the default source. type KeyInput = { type: "key"; code: string; down: boolean; source?: symbol; repeat?: boolean }; @@ -110,7 +112,7 @@ export class RemoteInputSession { if (this.disposed || this.channel.readyState !== "open") return false; try { // A stalled input queue must not replay seconds of old actions later. - if (this.channel.bufferedAmount > 8192) throw new Error("input queue stalled"); + if (this.channel.bufferedAmount > MAX_QUEUED_PLAINTEXT_BYTES) throw new Error("input queue stalled"); this.channel.send(JSON.stringify(event)); return true; } catch (error) { @@ -183,6 +185,7 @@ export class RemoteInputSession { const state = this.state; if (!this.intent || !state?.grant || state.intent !== this.intent || (state.state !== "active" && !((event.type === "reset" || event.type === "gamepad-reset" || event.type === "gamepad-stop") && state.state === "suspended"))) return; + if (event.type === "text" && !remoteTextFits(event.text, state.grant)) return; if (event.type === "key") { const { type, code, down } = event; if (this.keyTransition(event)) this.send({ type, code, down, grant: state.grant }); diff --git a/src/client/remote-control/protocol.ts b/src/client/remote-control/protocol.ts index 68854aaf6..a36015d46 100644 --- a/src/client/remote-control/protocol.ts +++ b/src/client/remote-control/protocol.ts @@ -1,8 +1,22 @@ import { z } from "zod"; import { isComposingOrAltGraph } from "../ui/shortcut-key"; -// A text submission still fits one encrypted input packet and the existing queue. +export const INPUT_FRAME_BYTES = 8192; +export const REMOTE_INPUT_COMMAND_BYTES = 4096; export const REMOTE_TEXT_BYTES = 2048; + +const encoder = new TextEncoder(); +export function inputFrameFits(frame: string): boolean { + return frame.length <= INPUT_FRAME_BYTES && encoder.encode(frame).byteLength <= INPUT_FRAME_BYTES; +} + +// The editor can measure the command before sending. Every grant has the same hex length. +const exampleGrant = "0".repeat(64); +export function remoteTextFits(text: string, grant = exampleGrant): boolean { + return text.length <= REMOTE_TEXT_BYTES && encoder.encode(text).byteLength <= REMOTE_TEXT_BYTES + && encoder.encode(JSON.stringify({ type: "text", text, grant })).byteLength <= REMOTE_INPUT_COMMAND_BYTES; +} + // F12 is reserved by Windows debuggers, including for global modified chords. export const remoteShortcutKeySchema = z.number().int().min(1).max(11); export const REMOTE_SHORTCUT_KEYS = Array.from({ length: 11 }, (_, index) => index + 1); diff --git a/tests/channel-wire-images.test.ts b/tests/channel-wire-images.test.ts index ffc016bcb..080422058 100644 --- a/tests/channel-wire-images.test.ts +++ b/tests/channel-wire-images.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { readFile } from "node:fs/promises"; +import { INPUT_FRAME_BYTES, REMOTE_INPUT_COMMAND_BYTES, REMOTE_TEXT_BYTES } from "../src/client/remote-control/protocol"; import { CHANNEL_EVENT_BYTES, CHANNEL_PROTOCOL, CHANNEL_ROOM_LIMIT, CHANNEL_SESSION_LIMIT, IDENTITY_IMAGE_URL_BYTES, PROFILE_PAGE_SIZE, ChannelEventDecoder } from "../src/client/channel/protocol"; const picture = "data:image/png;base64,YWJj"; @@ -31,6 +32,7 @@ it("matches the compiled Core wire contract for schemas built before WASM initia await core.default({ module_or_path: await readFile("prototype/channel-browser/pkg/piik_channel_browser_bg.wasm") }); expect(JSON.parse(core.channel_wire_limits())).toEqual({ protocol: CHANNEL_PROTOCOL, sessions: CHANNEL_SESSION_LIMIT, rooms: CHANNEL_ROOM_LIMIT, + inputFrameBytes: INPUT_FRAME_BYTES, inputCommandBytes: REMOTE_INPUT_COMMAND_BYTES, inputTextBytes: REMOTE_TEXT_BYTES, profilePage: PROFILE_PAGE_SIZE, eventBytes: CHANNEL_EVENT_BYTES, identityImageBytes: IDENTITY_IMAGE_URL_BYTES, }); }); diff --git a/tests/remote-input.test.ts b/tests/remote-input.test.ts index a8cd753fa..5510fcdd5 100644 --- a/tests/remote-input.test.ts +++ b/tests/remote-input.test.ts @@ -1,7 +1,7 @@ import { expect, it, vi } from "vitest"; import { RemoteInputSession } from "../src/client/remote-control/input-session"; import { picturePoint, rotatePicturePoint, rotatePictureDelta, type VideoRotation } from "../src/client/media/video-geometry"; -import { matchesRemoteShortcut, remoteInputStateSchema } from "../src/client/remote-control/protocol"; +import { INPUT_FRAME_BYTES, inputFrameFits, matchesRemoteShortcut, remoteInputStateSchema, remoteTextFits } from "../src/client/remote-control/protocol"; import { RemoteGamepad } from "../src/client/remote-control/gamepad"; it("recognizes only the selected local release chord outside IME composition", () => { @@ -15,6 +15,20 @@ it("recognizes only the selected local release chord outside IME composition", ( } }); +it("measures the complete input frame in UTF-8 bytes", () => { + const frame = JSON.stringify({ data: "😀" }); + const atLimit = frame + " ".repeat(INPUT_FRAME_BYTES - new TextEncoder().encode(frame).byteLength); + expect(inputFrameFits(atLimit)).toBe(true); + expect(inputFrameFits(atLimit + " ")).toBe(false); +}); + +it("admits text by both UTF-8 content and escaped command size", () => { + expect(remoteTextFits("😀".repeat(512))).toBe(true); + expect(remoteTextFits("😀".repeat(512) + "a")).toBe(false); + expect(remoteTextFits('"'.repeat(1998))).toBe(true); + expect(remoteTextFits('"'.repeat(1998) + "a")).toBe(false); +}); + class Channel extends EventTarget { readyState = "open"; bufferedAmount = 0;