## Problem and outcome Connection recovery and packet repair could leave stale pictures, missing sound or unreliable remote input. This maintenance release repairs media/route ownership, H.264 negotiation, voice forwarding and Windows input recovery, and makes shared mobile controls and popovers easier to use. ## Release notes **Piik, now in your pocket.** Piik App supports Android screen sharing, with touch controls for a friend's computer. **手机,也能开播。** Piik App 支持 Android 屏幕分享,也能用手机控制朋友的电脑。 ### English Piik v2.5.1 improves sharing recovery, voice playback and remote control, with clearer mobile controls. It keeps the existing 2.x compatibility baseline. - Improve H.264 selection and picture recovery after reconnecting, changing sources or recovering lost packets; keep a working share when a replacement source fails. - Keep audio and room voice continuous, and prevent duplicate sound when switching playback windows. - Improve Windows input recovery and release remote-control permissions when their connection ends. - Keep mobile controls together and popovers usable after layout changes or in short viewports. - Open the appropriate Android update download, including the Gitee ZIP containing the APK. Self-hosted SFU servers refresh public addresses for new connections without a restart. - Add macOS source-thumbnail support. Update the App and self-hosted site together to receive all fixes. Browser settings and existing room data are retained. ### 中文 Piik v2.5.1 改善分享恢复、语音播放与远程控制的稳定性,让手机操作更顺手,沿用现有 2.x 兼容基线。 - 改善 H.264 编码选择,以及重连、切换分享源和丢包后的画面恢复;新分享源切换失败时保留正常分享。 - 保持声音与房间语音连续,避免切换播放窗口时出现双重声音。 - 改善 Windows 输入恢复,并在连接结束时释放远程控制授权。 - 手机控件保持成组,浮层在布局变化或可见高度较小时仍可操作。 - Android 更新打开对应下载入口,Gitee 提供内含 APK 的 ZIP;自部署 SFU 为新连接刷新公网地址,无需重启服务。 - 补齐 macOS 选源缩略图支持。 请一起更新 App 与自部署站点,以获得全部修复。浏览器设置与已有房间数据保留。 ## Validation - Full frontend typecheck, test and production-build acceptance; current Windows App/Server packaging, extracted-file checks and exact served JavaScript verified locally. - Existing Go, vulnerability, native media and controlled-network results retained at their tested revisions. The final production delta from the fully checked candidate is the shared short-viewport popover correction. - The diagnostic report supplied for #502 informed the Windows input fixes. #500 sharing is confirmed working; its missing source previews are implemented. Original-device follow-up remains separate from this release's verified local fixes. ## Compatibility and scope Preserves the published 2.x Browser/server, Native control, capture and SQLite contracts. No 3.0 or iOS implementation or external contributor patch is included. Related: #500, #502, #510, #512.
195 lines
9.4 KiB
TypeScript
195 lines
9.4 KiB
TypeScript
export const INPUT_CHANNEL = "piik-remote-input-prototype-v1";
|
|
export type InputIdentity = { endpointId: string; secret: string };
|
|
type Packet = { id?: string; epoch?: string; data?: string; closed?: boolean; ready?: boolean };
|
|
export type InputTransport = Pick<RTCDataChannel, "readyState" | "bufferedAmount" | "send" | "close" | "addEventListener" | "removeEventListener">;
|
|
// Local relay metadata bound, independent of ciphertext authorization or route age.
|
|
const MAX_UNCLOSED_EPOCHS_PER_CHILD = 128;
|
|
|
|
function packet(data: unknown): Packet | null {
|
|
if (typeof data !== "string" || data.length > 6144) return null;
|
|
try {
|
|
const p = JSON.parse(data) as Packet;
|
|
return p && (typeof p.ready === "boolean" || typeof p.id === "string" && /^[0-9a-f]{32}$/.test(p.id) &&
|
|
typeof p.epoch === "string" && /^[0-9a-f]{32}$/.test(p.epoch) && (p.closed === true || typeof p.data === "string")) ? p : null;
|
|
} catch { return null; }
|
|
}
|
|
function send(channel: RTCDataChannel | null, p: Packet): void {
|
|
if (channel?.readyState !== "open") return;
|
|
if (channel.bufferedAmount > 8192) { channel.close(); return; }
|
|
try { channel.send(JSON.stringify(p)); } catch { channel.close(); }
|
|
}
|
|
|
|
// One small adapter follows the committed media input and existing relay edges.
|
|
// It selects no route and keeps neither permissions nor input history.
|
|
export class InputRoute {
|
|
private up: RTCDataChannel | null = null;
|
|
private ready = false;
|
|
private endpoint: EncryptedInput | null = null;
|
|
private identity: InputIdentity | null = null;
|
|
private counter = { sent: 0n };
|
|
private register: ((identity: InputIdentity) => boolean) | null = null;
|
|
private children = new Map<RTCDataChannel, Map<string, Set<string>>>();
|
|
constructor(private readonly changed: () => void) {}
|
|
get current(): InputTransport | null { return this.endpoint; }
|
|
|
|
enable(register: (identity: InputIdentity) => boolean): void {
|
|
this.register = register;
|
|
this.reauthenticate();
|
|
}
|
|
reauthenticate(): void {
|
|
this.retireEndpoint();
|
|
this.identity = null;
|
|
this.counter = { sent: 0n };
|
|
this.refreshEndpoint();
|
|
}
|
|
setUpstream(channel: RTCDataChannel | null): void {
|
|
if (this.up === channel) return;
|
|
if (this.up) {
|
|
this.up.removeEventListener("message", this.received);
|
|
this.up.removeEventListener("close", this.lost);
|
|
this.up.removeEventListener("open", this.opened);
|
|
for (const child of this.children.keys()) this.loseChild(child);
|
|
}
|
|
this.retireEndpoint();
|
|
this.ready = false;
|
|
this.up = channel;
|
|
this.broadcast({ ready: false });
|
|
channel?.addEventListener("message", this.received);
|
|
channel?.addEventListener("close", this.lost);
|
|
channel?.addEventListener("open", this.opened);
|
|
if (channel?.readyState === "open") this.opened();
|
|
}
|
|
private readonly opened = (): void => send(this.up, { ready: true });
|
|
private readonly lost = (): void => { this.ready = false; this.retireEndpoint(); this.broadcast({ ready: false }); };
|
|
private readonly received = (event: MessageEvent): void => {
|
|
const p = packet(event.data); if (!p) return;
|
|
if (p.ready !== undefined && p.id) {
|
|
if (p.ready && p.id === this.identity?.endpointId) this.endpoint?.send(JSON.stringify({ type: "sync" }));
|
|
} else if (p.ready !== undefined) {
|
|
this.ready = p.ready;
|
|
if (!p.ready) this.retireEndpoint(); else this.refreshEndpoint();
|
|
} else if (p.id === this.identity?.endpointId && p.epoch === this.endpoint?.epoch && p.data) this.endpoint?.receive(p.data);
|
|
this.broadcast(p);
|
|
};
|
|
private broadcast(p: Packet): void { for (const child of this.children.keys()) send(child, p); }
|
|
private refreshEndpoint(): void {
|
|
if (this.endpoint || !this.ready || !this.register || !crypto.subtle) return;
|
|
if (!this.identity) {
|
|
const identity = { endpointId: crypto.randomUUID().replaceAll("-", ""),
|
|
secret: Array.from(crypto.getRandomValues(new Uint8Array(32)), b => b.toString(16).padStart(2, "0")).join("") };
|
|
if (!this.register(identity)) return;
|
|
this.identity = identity;
|
|
}
|
|
this.endpoint = new EncryptedInput(this.identity, this.counter, p => send(this.up, p));
|
|
this.changed();
|
|
}
|
|
private retireEndpoint(): void {
|
|
this.endpoint?.close();
|
|
this.endpoint = null;
|
|
this.changed();
|
|
}
|
|
private loseChild(channel: RTCDataChannel, detach = false): void {
|
|
const ids = this.children.get(channel);
|
|
if (!ids) return;
|
|
if (detach) this.children.delete(channel);
|
|
for (const [id, epochs] of ids) for (const epoch of epochs) send(this.up, { id, epoch, closed: true });
|
|
ids.clear();
|
|
}
|
|
attachChild(channel: RTCDataChannel, connection: RTCPeerConnection): void {
|
|
const ids = new Map<string, Set<string>>();
|
|
this.children.set(channel, ids);
|
|
connection.addEventListener("connectionstatechange", () => {
|
|
if (!this.children.has(channel)) return;
|
|
if (connection.connectionState === "disconnected" || connection.connectionState === "failed" || connection.connectionState === "closed") {
|
|
this.loseChild(channel);
|
|
}
|
|
});
|
|
channel.addEventListener("open", () => send(channel, { ready: this.ready }));
|
|
channel.addEventListener("message", event => {
|
|
const p = packet(event.data); if (!p || !this.children.has(channel)) return;
|
|
if (p.ready !== undefined) { send(channel, { ready: this.ready }); return; }
|
|
if (!this.ready || !p.id || !p.epoch) return;
|
|
const epochs = ids.get(p.id);
|
|
if (p.closed) {
|
|
epochs?.delete(p.epoch);
|
|
if (epochs?.size === 0) ids.delete(p.id);
|
|
} else if (!epochs?.has(p.epoch)) {
|
|
if (!epochs && ids.size >= 20) return;
|
|
if ([...ids.values()].reduce((total, epochs) => total + epochs.size, 0) >= MAX_UNCLOSED_EPOCHS_PER_CHILD) {
|
|
this.loseChild(channel, true);
|
|
channel.close();
|
|
return;
|
|
}
|
|
if (epochs) epochs.add(p.epoch); else ids.set(p.id, new Set([p.epoch]));
|
|
}
|
|
send(this.up, p);
|
|
});
|
|
channel.addEventListener("close", () => this.loseChild(channel, true));
|
|
if (channel.readyState === "open") send(channel, { ready: this.ready });
|
|
}
|
|
dispose(): void {
|
|
this.setUpstream(null);
|
|
this.identity = null;
|
|
this.register = null;
|
|
for (const child of this.children.keys()) child.close();
|
|
this.children.clear();
|
|
}
|
|
}
|
|
|
|
// Keys arrive over authenticated room signaling. An intermediate Viewer/SFU
|
|
// transports ciphertext and cannot impersonate the approved controller.
|
|
class EncryptedInput extends EventTarget implements InputTransport {
|
|
readonly epoch = crypto.randomUUID().replaceAll("-", "");
|
|
readyState: RTCDataChannelState = "open";
|
|
bufferedAmount = 0;
|
|
private received = 0n;
|
|
private readonly key: Promise<CryptoKey>;
|
|
private outbound = Promise.resolve();
|
|
private inbound = Promise.resolve();
|
|
private incomingBytes = 0;
|
|
constructor(private readonly identity: InputIdentity, private readonly counter: { sent: bigint }, private readonly transmit: (packet: Packet) => void) {
|
|
super();
|
|
this.key = crypto.subtle.importKey("raw", Uint8Array.from(identity.secret.match(/../g)!, b => parseInt(b, 16)), "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
}
|
|
send(data: string | Blob | ArrayBuffer | ArrayBufferView): void {
|
|
if (this.readyState !== "open" || typeof data !== "string") return;
|
|
const plain = new TextEncoder().encode(data);
|
|
this.bufferedAmount += plain.length;
|
|
this.outbound = this.outbound.then(async () => {
|
|
if (this.readyState !== "open") return;
|
|
const header = new Uint8Array(20);
|
|
new DataView(header.buffer).setBigUint64(0, ++this.counter.sent);
|
|
crypto.getRandomValues(header.subarray(8));
|
|
const aad = new Uint8Array(41); aad.set(header.subarray(0, 8), 1); aad.set(new TextEncoder().encode(this.epoch), 9);
|
|
const encrypted = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv: header.subarray(8), additionalData: aad }, await this.key, plain));
|
|
if (this.readyState !== "open") return;
|
|
const bytes = new Uint8Array(header.length + encrypted.length);
|
|
bytes.set(header); bytes.set(encrypted, header.length);
|
|
this.transmit({ id: this.identity.endpointId, epoch: this.epoch, data: btoa(String.fromCharCode(...bytes)) });
|
|
}).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;
|
|
this.inbound = this.inbound.then(async () => {
|
|
if (this.readyState !== "open") return;
|
|
const bytes = Uint8Array.from(atob(data), c => c.charCodeAt(0));
|
|
if (bytes.length < 36) return;
|
|
const sequence = new DataView(bytes.buffer).getBigUint64(0);
|
|
if (sequence <= this.received) return;
|
|
const aad = new Uint8Array(41); aad[0] = 1; aad.set(bytes.subarray(0, 8), 1); aad.set(new TextEncoder().encode(this.epoch), 9);
|
|
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.slice(8, 20), additionalData: aad }, await this.key, bytes.slice(20));
|
|
if (this.readyState !== "open") return;
|
|
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; });
|
|
}
|
|
close(): void {
|
|
if (this.readyState === "closed") return;
|
|
this.readyState = "closed";
|
|
this.transmit({ id: this.identity.endpointId, epoch: this.epoch, closed: true });
|
|
this.dispatchEvent(new Event("close"));
|
|
}
|
|
}
|