Room defaults and personal relay limits now use the existing route controller. Hosts can set the room default; viewers can follow it or select a lower or higher personal limit, including zero. Lowering a limit uses the existing handoff, and retired connection attempts no longer consume a later viewer's opportunity. The candidate also preserves native sharing when its local preview fails, prefers a preview-compatible codec in Auto mode when the App supports it, and improves terminal shutdown, input failure feedback and attached-menu positioning. Validation: Web type checks, 1,936 frontend tests and the production Web build pass. Server, routing, Native host and media-edge tests and vet pass. Real three-viewer browser checks cover default/override synchronization, receive-only, signaling reconnect, downscaling to a chain and automatic recovery after increasing an exhausted route's limit. Narrow-screen, theme and visual-mode control previews were inspected. Current field investigations remain open: the niri-specific capture failure (#499), the Windows input-refusal trigger (#502), the UU title-only load report and the older capture/source-cadence reports. These are not claimed fixed by this release. ## 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 - Set a room-wide default relay limit. Viewers can follow it or set their own higher or lower limit; zero receives without forwarding. Limits still follow each device's capability, and route selection remains automatic. - Improve connection recovery when viewers join during route preparation or a peer connection is rebuilt. Canceled connection attempts no longer prevent later retries, and rebuilt routes require fresh media before showing as ready. - Keep native sharing active when the host's local preview cannot play. Automatic selection prefers a codec the browser can preview when the App supports it, and restoring a preview preserves its playback state. - Improve App shutdown when its terminal closes and complete macOS permission descriptions. - Retain useful remote-input failure feedback while pending key releases clear. Fix attached-menu scroll jumps, invisible tooltips intercepting clicks and volume guidance when source sound is unavailable. This update preserves the existing 2.x compatibility baseline. The new relay settings require an updated site; older pages retain their previous relay behavior. ### 中文 - 房主可以设置房间默认转发上限。观众可跟随默认,也可自行调高或调低;设为 0 时只接收、不转发。实际额度仍受设备能力约束,线路继续自动安排。 - 改善观众在建立线路期间加入,以及连接重建后的恢复。取消连接尝试后,后续连接仍可正常重试;重建后的线路收到新画面才会显示就绪。 - 房主本地预览无法播放时,原生分享继续。App 支持时,自动选择优先采用浏览器可预览的编码,恢复预览时保留原有播放状态。 - 改善终端关闭时 App 的退出流程,补齐 macOS 权限用途说明。 - 释放待处理按键期间保留远控失败提示;修复附属菜单导致的滚动跳动、不可见提示拦截点击,以及没有分享声音时的音量说明。 本次更新保持现有 2.x 兼容约定。新的转发设置需要更新站点,旧页面保留原有转发行为。
1404 lines
46 KiB
TypeScript
1404 lines
46 KiB
TypeScript
import { z } from "zod";
|
|
import { MAX_CHAT_CODE_POINTS, normalizeChatText, REACTION_IDS, isThrow } from "./room-interactions.js";
|
|
|
|
import { MAX_ENDPOINT_MEDIA_COPY_CAPACITY } from "./media-copy-accounting.js";
|
|
import { isCanonicalVideoCodecEvidence } from "./video-codec-evidence.js";
|
|
import { NAT_TRAVERSAL_PATHS } from "./nat-candidate.js";
|
|
|
|
export const MAX_VIEWERS_PER_ROOM_LIMIT = 20;
|
|
export const MAX_PARTICIPANTS_PER_ROOM_LIMIT = MAX_VIEWERS_PER_ROOM_LIMIT + 1;
|
|
export const MAX_SIGNAL_BYTES = 64 * 1024;
|
|
export const SIGNALING_PROTOCOL = "piik-v24";
|
|
export const SIGNAL_CLOSE_CODES = {
|
|
serviceRestart: 1012,
|
|
sessionReplaced: 4001,
|
|
clientReconnect: 4002,
|
|
authenticationFailed: 4003,
|
|
viewerAccessRevoked: 4004,
|
|
} as const;
|
|
export const ROOM_CODE_LENGTH = 4;
|
|
export const MAX_MEDIA_ROUTE_REVISION = Number.MAX_SAFE_INTEGER;
|
|
export const MAX_ICE_SERVER_URLS = 8;
|
|
export const MAX_NAT_PREDICTION_AUXILIARY_STUN_URLS = 2;
|
|
export const MAX_VIEWER_QUALITY_EVIDENCE_BYTES = 2 * 1024;
|
|
export const VIEWER_QUALITY_EVIDENCE_INTERVAL_MS = 2_000;
|
|
export const VIEWER_QUALITY_EVIDENCE_EXPIRY_MS = 5_000;
|
|
export const PERSISTENT_NATIVE_EDGE_DEGRADED_WINDOWS = 3;
|
|
export const MAX_DISPLAY_NAME_CODE_POINTS = 24;
|
|
export const DEFAULT_VIEWER_DISPLAY_NAME = "观众";
|
|
export const DEFAULT_HOST_DISPLAY_NAME_PREFIX = "房主";
|
|
export const MIN_VIEWER_PASSWORD_LENGTH = 1;
|
|
export const MAX_VIEWER_PASSWORD_LENGTH = 64;
|
|
|
|
const FORBIDDEN_DISPLAY_NAME_CHARACTERS =
|
|
/[\p{Cc}\p{Zl}\p{Zp}\u061c\u200b\u200e\u200f\u202a-\u202e\u2060\u2066-\u2069\ufeff]/u;
|
|
|
|
export function normalizeDisplayName(value: string): string | null {
|
|
if (FORBIDDEN_DISPLAY_NAME_CHARACTERS.test(value)) {
|
|
return null;
|
|
}
|
|
for (const character of value) {
|
|
const codePoint = character.codePointAt(0)!;
|
|
if (codePoint >= 0xd800 && codePoint <= 0xdfff) {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
const normalized = value.normalize("NFC").trim().replace(/\p{Zs}+/gu, " ");
|
|
const codePointCount = Array.from(normalized).length;
|
|
return codePointCount >= 1 && codePointCount <= MAX_DISPLAY_NAME_CODE_POINTS
|
|
? normalized
|
|
: null;
|
|
}
|
|
|
|
export const displayNameSchema = z
|
|
.string()
|
|
.min(1)
|
|
.max(MAX_DISPLAY_NAME_CODE_POINTS * 4)
|
|
.refine((value) => normalizeDisplayName(value) === value, {
|
|
message: "Display name must be canonical",
|
|
});
|
|
export type DisplayName = z.infer<typeof displayNameSchema>;
|
|
|
|
const opaqueIdSchema = z
|
|
.string()
|
|
.min(8)
|
|
.max(128)
|
|
.regex(/^[A-Za-z0-9_-]+$/);
|
|
|
|
const coPlayGrantSchema = z.object({
|
|
endpointId: z.string().regex(/^[0-9a-f]{32}$/),
|
|
}).strict();
|
|
const coPlayParticipantSchema = z.object({ peerId: opaqueIdSchema }).strict();
|
|
export type CoPlayGrant = z.infer<typeof coPlayGrantSchema>;
|
|
export type CoPlayParticipant = z.infer<typeof coPlayParticipantSchema>;
|
|
|
|
const chatPayloadSchema = z.object({ kind: z.literal("chat"),
|
|
text: z.string().min(1).max(MAX_CHAT_CODE_POINTS * 2)
|
|
.refine(value => normalizeChatText(value) === value) }).strict();
|
|
const reactionPayloadSchema = z.object({ kind: z.literal("reaction"),
|
|
reaction: z.string().min(1).max(32).regex(/^[a-z][a-z0-9-]*$/),
|
|
targetPeerId: opaqueIdSchema.optional() }).strict()
|
|
.refine(payload => !isThrow(payload.reaction) || !!payload.targetPeerId,
|
|
{ message: "Throwing a prop requires a participant" });
|
|
// Commands require a registered effect; received events may carry a future
|
|
// display-only identifier. Identity, payload shape and target bounds stay strict.
|
|
export const interactionPayloadSchema = z.discriminatedUnion("kind", [
|
|
chatPayloadSchema, reactionPayloadSchema.safeExtend({ reaction: z.enum(REACTION_IDS) }),
|
|
]);
|
|
const receivedInteractionPayloadSchema = z.discriminatedUnion("kind", [
|
|
chatPayloadSchema, reactionPayloadSchema,
|
|
]);
|
|
export type InteractionPayload = z.infer<typeof interactionPayloadSchema>;
|
|
|
|
const noMediaRouteUpstreamSchema = z
|
|
.object({ kind: z.literal("none") })
|
|
.strict();
|
|
const peerMediaRouteUpstreamSchema = z
|
|
.object({
|
|
kind: z.literal("peer"),
|
|
peerId: opaqueIdSchema,
|
|
})
|
|
.strict();
|
|
const sfuMediaRouteUpstreamSchema = z
|
|
.object({ kind: z.literal("sfu") })
|
|
.strict();
|
|
|
|
export const mediaRouteUpstreamSchema = z.discriminatedUnion("kind", [
|
|
noMediaRouteUpstreamSchema,
|
|
peerMediaRouteUpstreamSchema,
|
|
sfuMediaRouteUpstreamSchema,
|
|
]);
|
|
export type MediaRouteUpstream = z.infer<typeof mediaRouteUpstreamSchema>;
|
|
|
|
const activeMediaRouteUpstreamSchema = z.discriminatedUnion("kind", [
|
|
peerMediaRouteUpstreamSchema,
|
|
sfuMediaRouteUpstreamSchema,
|
|
]);
|
|
|
|
export const viewerPresenceEntrySchema = z
|
|
.object({
|
|
role: z.literal("viewer"),
|
|
peerId: opaqueIdSchema,
|
|
displayName: displayNameSchema,
|
|
upstream: mediaRouteUpstreamSchema,
|
|
mediaReady: z.literal(true).optional(),
|
|
})
|
|
.strict();
|
|
export type ViewerPresenceEntry = z.infer<typeof viewerPresenceEntrySchema>;
|
|
|
|
export const participantPresenceEntrySchema = z.discriminatedUnion("role", [
|
|
z
|
|
.object({
|
|
role: z.literal("host"),
|
|
peerId: opaqueIdSchema,
|
|
displayName: displayNameSchema,
|
|
upstream: z.object({ kind: z.literal("none") }).strict(),
|
|
})
|
|
.strict(),
|
|
viewerPresenceEntrySchema,
|
|
]);
|
|
export type ParticipantPresenceEntry = z.infer<
|
|
typeof participantPresenceEntrySchema
|
|
>;
|
|
|
|
const tokenSchema = z
|
|
.string()
|
|
.min(32)
|
|
.max(128)
|
|
.regex(/^[A-Za-z0-9_-]+$/);
|
|
|
|
export const viewerGrantSchema = z
|
|
.string()
|
|
.length(22)
|
|
.regex(/^[A-Za-z0-9_-]{21}[AQgw]$/);
|
|
|
|
export const viewerPasswordSchema = z
|
|
.string()
|
|
.min(MIN_VIEWER_PASSWORD_LENGTH)
|
|
.max(MAX_VIEWER_PASSWORD_LENGTH)
|
|
.regex(/^[\x21-\x7e]+$/);
|
|
|
|
export const codeEntryPolicySchema = z.enum(["open", "private"]);
|
|
export type CodeEntryPolicy = z.infer<typeof codeEntryPolicySchema>;
|
|
|
|
|
|
export const roomCodeSchema = z
|
|
.string()
|
|
.length(ROOM_CODE_LENGTH)
|
|
.max(ROOM_CODE_LENGTH)
|
|
.regex(/^[1-9]\d*$/);
|
|
|
|
export const roleSchema = z.enum(["host", "viewer"]);
|
|
export type Role = z.infer<typeof roleSchema>;
|
|
|
|
// Describes a requested ceiling, not encoder availability or an allocation.
|
|
// WebRTC uses unsigned-long dimensions/bitrates and a double frame rate.
|
|
// Alignment, usable ranges and allocation budgets belong to the media adapter.
|
|
export const positiveUint32Schema = z.number().int().positive().max(0xffff_ffff);
|
|
export const qualityResolutionSchema = z.object({
|
|
width: positiveUint32Schema,
|
|
height: positiveUint32Schema,
|
|
}).strict();
|
|
export type QualityResolution = z.infer<typeof qualityResolutionSchema>;
|
|
|
|
export const degradationPreferenceSchema = z.enum([
|
|
"maintain-resolution",
|
|
"balanced",
|
|
"maintain-framerate",
|
|
]);
|
|
export type DegradationPreference = z.infer<
|
|
typeof degradationPreferenceSchema
|
|
>;
|
|
|
|
export const MIN_AUDIO_BITRATE = 6_000;
|
|
export const MAX_AUDIO_BITRATE = 510_000;
|
|
export const maxAudioBitrateSchema = z.number().int().min(MIN_AUDIO_BITRATE).max(MAX_AUDIO_BITRATE);
|
|
|
|
export const qualitySettingsSchema = z
|
|
.object({
|
|
resolution: qualityResolutionSchema,
|
|
maxFramerate: z.number().positive().max(Number.MAX_SAFE_INTEGER),
|
|
maxBitrate: positiveUint32Schema,
|
|
degradationPreference: degradationPreferenceSchema,
|
|
maxAudioBitrate: maxAudioBitrateSchema.optional(),
|
|
})
|
|
.strict();
|
|
export type QualitySettings = z.infer<typeof qualitySettingsSchema>;
|
|
export const DEFAULT_QUALITY_SETTINGS = {
|
|
resolution: { width: 1920, height: 1080 },
|
|
maxFramerate: 30,
|
|
maxBitrate: 5_000_000,
|
|
degradationPreference: "balanced",
|
|
maxAudioBitrate: 128000,
|
|
} as const satisfies QualitySettings;
|
|
|
|
export const routePolicySchema = z
|
|
.object({
|
|
peerOnly: z.boolean(),
|
|
topologyOptimization: z.boolean(),
|
|
natPrediction: z.boolean(),
|
|
})
|
|
.strict();
|
|
export type RoutePolicy = z.infer<typeof routePolicySchema>;
|
|
export const viewerRoutePreferenceSchema = z.enum(["auto", "p2p", "sfu"]);
|
|
export type ViewerRoutePreference = z.infer<typeof viewerRoutePreferenceSchema>;
|
|
export const DEFAULT_ROUTE_POLICY = {
|
|
peerOnly: false,
|
|
topologyOptimization: true,
|
|
natPrediction: false,
|
|
} as const satisfies RoutePolicy;
|
|
|
|
export const runtimeCapabilitiesSchema = z.object({
|
|
sfu: z.boolean().default(false),
|
|
sfuOnly: z.boolean().optional(),
|
|
natPrediction: z.boolean().default(false),
|
|
roomInteractions: z.boolean().default(false),
|
|
roomVoice: z.boolean().default(false),
|
|
roomVoiceListeningPresence: z.boolean().default(false),
|
|
roomVoiceBitrate: z.boolean().optional(),
|
|
relayVolunteer: z.boolean().default(false),
|
|
roomRelayCapacity: z.boolean().optional(),
|
|
roomReactionIds: z.array(z.string().max(32).regex(/^[a-z][a-z0-9-]*$/)).max(64).optional(),
|
|
hostRoomSession: z.boolean().default(false),
|
|
remoteInput: z.boolean().default(false),
|
|
viewerRouteSelection: z.boolean().default(false),
|
|
audioPresence: z.boolean().default(false),
|
|
coPlayPresence: z.boolean().default(false),
|
|
});
|
|
export type RuntimeCapabilities = z.infer<typeof runtimeCapabilitiesSchema>;
|
|
|
|
export const relayDownstreamEdgesSchema = z
|
|
.number()
|
|
.int()
|
|
.min(0)
|
|
.max(MAX_ENDPOINT_MEDIA_COPY_CAPACITY);
|
|
export type RelayDownstreamEdges = z.infer<typeof relayDownstreamEdgesSchema>;
|
|
|
|
function isValidStunUrl(value: string): boolean {
|
|
const schemeSeparator = value.indexOf(":");
|
|
if (
|
|
schemeSeparator <= 0 ||
|
|
value.slice(0, schemeSeparator).toLowerCase() !== "stun"
|
|
) {
|
|
return false;
|
|
}
|
|
|
|
const authorityText = value.slice(schemeSeparator + 1);
|
|
if (
|
|
!authorityText ||
|
|
/[\\/\s?#]/.test(authorityText) ||
|
|
authorityText.endsWith(":")
|
|
) {
|
|
return false;
|
|
}
|
|
|
|
let authority: URL;
|
|
try {
|
|
authority = new URL(`http://${authorityText}`);
|
|
} catch {
|
|
return false;
|
|
}
|
|
return Boolean(
|
|
authority.hostname &&
|
|
!authority.username &&
|
|
!authority.password &&
|
|
authority.pathname === "/" &&
|
|
!authority.search &&
|
|
!authority.hash &&
|
|
(!authority.port || Number(authority.port) > 0),
|
|
);
|
|
}
|
|
|
|
export const stunUrlSchema = z
|
|
.string()
|
|
.min(1)
|
|
.max(512)
|
|
.refine(isValidStunUrl, { message: "Invalid STUN URL" });
|
|
|
|
const iceServerSchema = z
|
|
.object({
|
|
urls: z.union([
|
|
stunUrlSchema,
|
|
z.array(stunUrlSchema).min(1).max(MAX_ICE_SERVER_URLS),
|
|
]),
|
|
})
|
|
.strict();
|
|
|
|
export const iceConfigSchema = z
|
|
.object({
|
|
iceServers: z.array(iceServerSchema).max(8),
|
|
natPredictionStunUrls: z
|
|
.array(stunUrlSchema)
|
|
.max(MAX_NAT_PREDICTION_AUXILIARY_STUN_URLS),
|
|
})
|
|
.strict();
|
|
export type WireIceConfig = z.infer<typeof iceConfigSchema>;
|
|
export type IceConfig = {
|
|
iceServers: Array<z.infer<typeof iceServerSchema>>;
|
|
natPredictionStunUrls?: string[];
|
|
};
|
|
|
|
const sessionDescriptionSchema = z
|
|
.object({
|
|
type: z.enum(["offer", "answer"]),
|
|
sdp: z.string().min(1).max(48 * 1024),
|
|
})
|
|
.strict();
|
|
|
|
export const iceCandidateSchema = z
|
|
.object({
|
|
candidate: z.string().max(4096),
|
|
sdpMid: z.string().max(128).nullable().optional(),
|
|
sdpMLineIndex: z.number().int().min(0).max(255).nullable().optional(),
|
|
usernameFragment: z.string().max(256).nullable().optional(),
|
|
})
|
|
.strict();
|
|
|
|
export const voiceDescriptionSchema = z.object({
|
|
revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
|
|
sdp: sessionDescriptionSchema,
|
|
tracks: z.array(z.object({ mid: z.string().min(1).max(128), publicationId: opaqueIdSchema }).strict())
|
|
.max(MAX_PARTICIPANTS_PER_ROOM_LIMIT * 2),
|
|
}).strict();
|
|
export type VoiceDescription = z.infer<typeof voiceDescriptionSchema>;
|
|
|
|
const voiceSignalShape = {
|
|
connectionId: opaqueIdSchema,
|
|
description: voiceDescriptionSchema.optional(),
|
|
candidate: iceCandidateSchema.optional(),
|
|
renegotiate: z.literal(true).optional(),
|
|
};
|
|
export const roomVoiceCommandSchema = z.discriminatedUnion("action", [
|
|
z.object({ action: z.literal("join") }).strict(),
|
|
z.object({ action: z.literal("leave") }).strict(),
|
|
z.object({ action: z.literal("publish") }).strict(),
|
|
z.object({ action: z.literal("unpublish"), publicationId: opaqueIdSchema }).strict(),
|
|
z.object({ action: z.literal("deafen"), deafened: z.boolean() }).strict(),
|
|
z.object({ action: z.literal("bitrate"), bitrate: maxAudioBitrateSchema }).strict(),
|
|
]);
|
|
export type RoomVoiceCommand = z.infer<typeof roomVoiceCommandSchema>;
|
|
export const roomVoiceStateSchema = z.object({
|
|
type: z.literal("room-voice-state"),
|
|
bitrate: maxAudioBitrateSchema.optional(),
|
|
revision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
enabled: z.boolean(),
|
|
hostPeerId: opaqueIdSchema.nullable(),
|
|
members: z.array(z.object({ peerId: opaqueIdSchema, connected: z.boolean(), joined: z.boolean(),
|
|
upstream: mediaRouteUpstreamSchema, publicationId: opaqueIdSchema.optional(), deafened: z.boolean().optional() }).strict())
|
|
.max(MAX_PARTICIPANTS_PER_ROOM_LIMIT),
|
|
publications: z.array(z.object({ id: opaqueIdSchema, peerId: opaqueIdSchema }).strict())
|
|
.max(MAX_PARTICIPANTS_PER_ROOM_LIMIT),
|
|
connections: z.array(z.object({ connectionId: opaqueIdSchema, parentPeerId: opaqueIdSchema.optional(),
|
|
childPeerId: opaqueIdSchema, transport: z.enum(["peer", "sfu"]), pending: z.boolean(),
|
|
revision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
send: z.array(opaqueIdSchema).max(MAX_PARTICIPANTS_PER_ROOM_LIMIT),
|
|
receive: z.array(opaqueIdSchema).max(MAX_PARTICIPANTS_PER_ROOM_LIMIT),
|
|
}).strict()).max(MAX_PARTICIPANTS_PER_ROOM_LIMIT + 1),
|
|
unavailable: z.array(opaqueIdSchema).max(MAX_PARTICIPANTS_PER_ROOM_LIMIT),
|
|
}).strict();
|
|
export type RoomVoiceState = z.infer<typeof roomVoiceStateSchema>;
|
|
export type VoiceConnection = RoomVoiceState["connections"][number];
|
|
|
|
export const punchPredictionSchema = z.object({
|
|
address: z.ipv4(),
|
|
port: z.number().int().min(1024).max(65535),
|
|
step: z.number().int().min(0).max(16),
|
|
}).strict().refine(({ port, step }) => port + 4 * step <= 65535);
|
|
export type PunchPrediction = z.infer<typeof punchPredictionSchema>;
|
|
|
|
export const punchSignalSchema = z.discriminatedUnion("phase", [
|
|
z.object({ phase: z.literal("prepare"), secret: z.string().regex(/^[0-9a-f]{64}$/) }).strict(),
|
|
z.object({ phase: z.literal("ready"), prediction: punchPredictionSchema.optional() }).strict(),
|
|
z.object({ phase: z.literal("start"), prediction: punchPredictionSchema }).strict(),
|
|
z.object({ phase: z.literal("complete"), connected: z.boolean() }).strict(),
|
|
]);
|
|
export type PunchSignal = z.infer<typeof punchSignalSchema>;
|
|
|
|
export const signalPayloadSchema = z.discriminatedUnion("kind", [
|
|
z.object({ kind: z.literal("punch"), connectionId: opaqueIdSchema, punch: punchSignalSchema }).strict(),
|
|
z
|
|
.object({
|
|
kind: z.literal("description"),
|
|
connectionId: opaqueIdSchema,
|
|
description: sessionDescriptionSchema,
|
|
punched: z.literal(true).optional(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
kind: z.literal("candidate"),
|
|
connectionId: opaqueIdSchema,
|
|
candidate: iceCandidateSchema.nullable(),
|
|
})
|
|
.strict(),
|
|
]);
|
|
export type SignalPayload = z.infer<typeof signalPayloadSchema>;
|
|
|
|
export const sfuMediaSchema = z.object({
|
|
codec: z.enum(["h264", "vp8"]),
|
|
layers: z.array(z.object({
|
|
rid: z.string().max(16),
|
|
width: positiveUint32Schema,
|
|
height: positiveUint32Schema,
|
|
bitrate: positiveUint32Schema,
|
|
}).strict()).min(1).max(3),
|
|
audio: z.boolean(),
|
|
audioBitrate: z.number().int().min(0).max(MAX_AUDIO_BITRATE),
|
|
}).strict().refine((media) =>
|
|
(!media.audio || media.audioBitrate > 0) &&
|
|
new Set(media.layers.map((layer) => layer.rid)).size === media.layers.length &&
|
|
(media.layers.length === 1 || media.layers.every((layer) => layer.rid !== "")),
|
|
);
|
|
export type SfuMedia = z.infer<typeof sfuMediaSchema>;
|
|
|
|
const sfuSignalMessageSchema = z.object({
|
|
type: z.literal("sfu-signal"),
|
|
revision: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
publicationGeneration: opaqueIdSchema,
|
|
connectionId: opaqueIdSchema,
|
|
kind: z.enum(["subscribe", "description", "candidate", "media", "layers"]),
|
|
description: sessionDescriptionSchema.optional(),
|
|
candidate: iceCandidateSchema.optional(),
|
|
media: sfuMediaSchema.optional(),
|
|
activeCount: z.number().int().min(0).max(3).optional(),
|
|
}).strict().refine((message) => {
|
|
if (message.kind === "layers") return message.activeCount !== undefined && !message.description && !message.candidate && !message.media;
|
|
if (message.activeCount !== undefined) return false;
|
|
if (message.kind === "media") return Boolean(message.media) && !message.description && !message.candidate;
|
|
if (message.kind === "subscribe") return !message.description && !message.candidate && !message.media;
|
|
if (message.kind === "candidate") return !message.description && !message.media;
|
|
return Boolean(message.description) && !message.candidate && (!message.media || message.description?.type === "offer");
|
|
});
|
|
export type SfuSignalMessage = z.infer<typeof sfuSignalMessageSchema>;
|
|
|
|
export const preparedRouteCandidateSchema = z
|
|
.object({
|
|
childPeerId: opaqueIdSchema,
|
|
connectionId: opaqueIdSchema,
|
|
transport: z.enum(["direct", "sfu"]),
|
|
qualityProbe: z.boolean(),
|
|
connectionAttempt: z.object({
|
|
current: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
total: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
|
|
}).strict().refine(({ current, total }) => current <= total).optional(),
|
|
})
|
|
.strict();
|
|
export type PreparedRouteCandidate = z.infer<
|
|
typeof preparedRouteCandidateSchema
|
|
>;
|
|
|
|
export const mediaRouteRevisionSchema = z
|
|
.number()
|
|
.int()
|
|
.min(0)
|
|
.max(MAX_MEDIA_ROUTE_REVISION);
|
|
|
|
export const mediaRoutePhaseSchema = z.enum(["prepare", "active"]);
|
|
export type MediaRoutePhase = z.infer<typeof mediaRoutePhaseSchema>;
|
|
|
|
export const routeDemandReasonSchema = z.enum([
|
|
"join",
|
|
"edge-unavailable",
|
|
"parent-departed",
|
|
"capacity-reduction",
|
|
"sfu-bootstrap",
|
|
"direct-convergence",
|
|
"quality-convergence",
|
|
"root-convergence",
|
|
"publication-attach",
|
|
]);
|
|
export type RouteDemandReason = z.infer<typeof routeDemandReasonSchema>;
|
|
|
|
export const routeDiagnosticFinalRouteSchema = z.enum([
|
|
"direct",
|
|
"sfu",
|
|
"waiting",
|
|
"failed",
|
|
]);
|
|
export type RouteDiagnosticFinalRoute = z.infer<
|
|
typeof routeDiagnosticFinalRouteSchema
|
|
>;
|
|
|
|
export const routeDiagnosticRejectionBucketSchema = z.enum([
|
|
"none",
|
|
"stale",
|
|
"endpoint-capacity",
|
|
"sfu-admission",
|
|
"candidate-failed",
|
|
"first-frame-timeout",
|
|
"operation-deadline",
|
|
"aborted",
|
|
]);
|
|
export type RouteDiagnosticRejectionBucket = z.infer<
|
|
typeof routeDiagnosticRejectionBucketSchema
|
|
>;
|
|
|
|
const routeDiagnosticDurationSchema = z
|
|
.number()
|
|
.int()
|
|
.min(0)
|
|
.max(Number.MAX_SAFE_INTEGER)
|
|
.nullable();
|
|
const routeDiagnosticOrdinalSchema = z
|
|
.number()
|
|
.int()
|
|
.min(1)
|
|
.max(MAX_VIEWERS_PER_ROOM_LIMIT);
|
|
const routeDiagnosticParentSchema = z.discriminatedUnion("kind", [
|
|
z.object({ kind: z.literal("none") }).strict(),
|
|
z.object({ kind: z.literal("host") }).strict(),
|
|
z.object({ kind: z.literal("sfu") }).strict(),
|
|
z
|
|
.object({
|
|
kind: z.literal("viewer"),
|
|
ordinal: routeDiagnosticOrdinalSchema,
|
|
})
|
|
.strict(),
|
|
]);
|
|
const routeDiagnosticQualityValueSchema = z
|
|
.number()
|
|
.int()
|
|
.min(0)
|
|
.max(Number.MAX_SAFE_INTEGER);
|
|
const routeDiagnosticQualitySchema = z
|
|
.object({
|
|
eligibleWindows: routeDiagnosticQualityValueSchema,
|
|
eligibleDurationMs: routeDiagnosticQualityValueSchema,
|
|
freezeWindows: routeDiagnosticQualityValueSchema,
|
|
freezeCount: routeDiagnosticQualityValueSchema,
|
|
freezeDurationMs: routeDiagnosticQualityValueSchema,
|
|
pauseCount: routeDiagnosticQualityValueSchema,
|
|
pauseDurationMs: routeDiagnosticQualityValueSchema,
|
|
})
|
|
.strict();
|
|
const routeDiagnosticChildSchema = z
|
|
.object({
|
|
ordinal: routeDiagnosticOrdinalSchema,
|
|
parent: routeDiagnosticParentSchema,
|
|
effectiveCapacity: z
|
|
.number()
|
|
.int()
|
|
.min(0)
|
|
.max(MAX_VIEWERS_PER_ROOM_LIMIT),
|
|
childCount: z
|
|
.number()
|
|
.int()
|
|
.min(0)
|
|
.max(MAX_VIEWERS_PER_ROOM_LIMIT),
|
|
demandAgeMs: routeDiagnosticDurationSchema,
|
|
queueWaitMs: routeDiagnosticDurationSchema,
|
|
candidateStartMs: routeDiagnosticDurationSchema,
|
|
firstDecodedFrameMs: routeDiagnosticDurationSchema,
|
|
finalMs: routeDiagnosticDurationSchema,
|
|
finalRoute: routeDiagnosticFinalRouteSchema,
|
|
rejectionBucket: routeDiagnosticRejectionBucketSchema,
|
|
quality: routeDiagnosticQualitySchema.nullable(),
|
|
})
|
|
.strict();
|
|
const routeDiagnosticOperationSchema = z
|
|
.object({
|
|
childOrdinal: routeDiagnosticOrdinalSchema,
|
|
reason: routeDemandReasonSchema,
|
|
stage: z.enum(["admission", "first-frame", "quality-proof"]),
|
|
cursor: z.number().int().min(0).max(MAX_VIEWERS_PER_ROOM_LIMIT),
|
|
candidateCount: z.number().int().min(1).max(MAX_VIEWERS_PER_ROOM_LIMIT + 1),
|
|
})
|
|
.strict();
|
|
|
|
export const routeDiagnosticSnapshotSchema = z
|
|
.object({
|
|
children: z
|
|
.array(routeDiagnosticChildSchema)
|
|
.max(MAX_VIEWERS_PER_ROOM_LIMIT),
|
|
operation: routeDiagnosticOperationSchema.nullable(),
|
|
})
|
|
.strict()
|
|
.superRefine((snapshot, context) => {
|
|
const ordinals = new Set(snapshot.children.map((child) => child.ordinal));
|
|
if (ordinals.size !== snapshot.children.length) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "Route diagnostic ordinals must be unique",
|
|
path: ["children"],
|
|
});
|
|
return;
|
|
}
|
|
for (const [index, child] of snapshot.children.entries()) {
|
|
if (
|
|
child.parent.kind === "viewer" &&
|
|
(!ordinals.has(child.parent.ordinal) ||
|
|
child.parent.ordinal === child.ordinal)
|
|
) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "Route diagnostic parent ordinal is invalid",
|
|
path: ["children", index, "parent"],
|
|
});
|
|
}
|
|
}
|
|
if (
|
|
snapshot.operation &&
|
|
(!ordinals.has(snapshot.operation.childOrdinal) ||
|
|
snapshot.operation.cursor >= snapshot.operation.candidateCount)
|
|
) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "Route diagnostic operation is invalid",
|
|
path: ["operation"],
|
|
});
|
|
}
|
|
});
|
|
export type RouteDiagnosticSnapshot = z.infer<
|
|
typeof routeDiagnosticSnapshotSchema
|
|
>;
|
|
|
|
export const sfuPublicationGenerationSchema = opaqueIdSchema;
|
|
|
|
export const participantRouteAssignmentSchema = z
|
|
.object({
|
|
upstream: mediaRouteUpstreamSchema,
|
|
childPeerIds: z
|
|
.array(opaqueIdSchema)
|
|
.max(MAX_VIEWERS_PER_ROOM_LIMIT)
|
|
.refine((peerIds) => new Set(peerIds).size === peerIds.length),
|
|
sfuPublicationGeneration: sfuPublicationGenerationSchema.nullable(),
|
|
})
|
|
.strict()
|
|
.superRefine((assignment, context) => {
|
|
if (
|
|
assignment.upstream.kind === "sfu" &&
|
|
assignment.sfuPublicationGeneration === null
|
|
) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "An SFU upstream requires its publication generation",
|
|
path: ["sfuPublicationGeneration"],
|
|
});
|
|
}
|
|
if (
|
|
assignment.upstream.kind === "peer" &&
|
|
assignment.sfuPublicationGeneration !== null
|
|
) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "A peer upstream cannot own an SFU publication generation",
|
|
path: ["sfuPublicationGeneration"],
|
|
});
|
|
}
|
|
});
|
|
export type ParticipantRouteAssignment = z.infer<
|
|
typeof participantRouteAssignmentSchema
|
|
>;
|
|
|
|
const nullableEvidenceNumber = (maximum: number) =>
|
|
z.number().finite().min(0).max(maximum).nullable();
|
|
|
|
const nullableSignedEvidenceNumber = (absoluteMaximum: number) =>
|
|
z.number().finite().min(-absoluteMaximum).max(absoluteMaximum).nullable();
|
|
|
|
export const nullableSafeEvidenceNumber = z
|
|
.number()
|
|
.finite()
|
|
.min(0)
|
|
.max(Number.MAX_SAFE_INTEGER)
|
|
.nullable();
|
|
|
|
export const nullableSafeEvidenceInteger = z
|
|
.number()
|
|
.int()
|
|
.min(0)
|
|
.max(Number.MAX_SAFE_INTEGER)
|
|
.nullable();
|
|
|
|
export const viewerQualityEvidenceMetricsSchema = z
|
|
.object({
|
|
natTraversalPath: z.enum(NAT_TRAVERSAL_PATHS),
|
|
width: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).nullable(),
|
|
height: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER).nullable(),
|
|
framesPerSecond: nullableSafeEvidenceNumber,
|
|
bitrateKbps: nullableSafeEvidenceNumber,
|
|
packetsReceivedDelta: nullableSafeEvidenceInteger,
|
|
packetsLostDelta: nullableSafeEvidenceInteger,
|
|
rttMs: nullableSafeEvidenceNumber,
|
|
jitterMs: nullableSafeEvidenceNumber,
|
|
framesDecodedDelta: nullableSafeEvidenceInteger,
|
|
framesDroppedDelta: nullableSafeEvidenceInteger,
|
|
decodeMsPerFrame: nullableSafeEvidenceNumber,
|
|
freezeCountDelta: nullableSafeEvidenceInteger,
|
|
freezeDurationMsDelta: nullableSafeEvidenceNumber,
|
|
pauseCountDelta: nullableSafeEvidenceInteger,
|
|
pauseDurationMsDelta: nullableSafeEvidenceNumber,
|
|
codec: z
|
|
.string()
|
|
.max(64)
|
|
.regex(/^video\/[A-Za-z0-9.+-]{1,32}$/i)
|
|
.nullable(),
|
|
codecProfile: z
|
|
.string()
|
|
.max(64)
|
|
.regex(/^[a-z0-9-]+=[a-z0-9]+$/)
|
|
.nullable(),
|
|
codecParameters: z
|
|
.string()
|
|
.max(128)
|
|
.regex(/^[a-z0-9-]+=[a-z0-9]+(?:; [a-z0-9-]+=[a-z0-9]+)*$/)
|
|
.nullable(),
|
|
audioBitrateKbps: nullableSafeEvidenceNumber,
|
|
audioPacketLossPercent: nullableEvidenceNumber(100),
|
|
audioJitterMs: nullableSafeEvidenceNumber,
|
|
audioVideoPlayoutDeltaMs: nullableSignedEvidenceNumber(Number.MAX_SAFE_INTEGER),
|
|
videoJitterBufferDelayMs: nullableSafeEvidenceNumber,
|
|
audioJitterBufferDelayMs: nullableSafeEvidenceNumber,
|
|
audioConcealedSamplesPercent: nullableEvidenceNumber(100),
|
|
audioConcealmentEventsDelta: nullableSafeEvidenceInteger,
|
|
audioCodec: z
|
|
.string()
|
|
.max(64)
|
|
.regex(/^audio\/[A-Za-z0-9.+-]{1,32}$/i)
|
|
.nullable(),
|
|
})
|
|
.strict()
|
|
.refine(
|
|
(metrics) =>
|
|
(metrics.width === null && metrics.height === null) ||
|
|
(metrics.width !== null && metrics.height !== null),
|
|
{ message: "Viewer quality dimensions must be present together" },
|
|
)
|
|
.refine(isCanonicalVideoCodecEvidence, {
|
|
message: "Viewer codec evidence is not canonical",
|
|
path: ["codecParameters"],
|
|
});
|
|
export type ViewerQualityEvidenceMetrics = z.infer<
|
|
typeof viewerQualityEvidenceMetricsSchema
|
|
>;
|
|
|
|
const viewerQualityEvidenceGuardSchema = z
|
|
.object({
|
|
connectionId: opaqueIdSchema,
|
|
routeRevision: mediaRouteRevisionSchema,
|
|
presentationEpoch: z
|
|
.number()
|
|
.int()
|
|
.min(0)
|
|
.max(Number.MAX_SAFE_INTEGER),
|
|
})
|
|
.strict();
|
|
|
|
const viewerQualityEvidenceWindowShape = {
|
|
sequence: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
windowMs: z.number().int().min(1_000).max(5_000),
|
|
metrics: viewerQualityEvidenceMetricsSchema,
|
|
};
|
|
|
|
const senderQualityDiagnosticsSchema = z
|
|
.object({
|
|
natTraversalPath: z.enum(NAT_TRAVERSAL_PATHS),
|
|
reason: z.enum(["none", "bandwidth", "cpu"]).nullable(),
|
|
framesPerSecond: nullableSafeEvidenceNumber,
|
|
bitrateKbps: nullableSafeEvidenceNumber,
|
|
captureFramesPerSecond: nullableSafeEvidenceNumber.optional(),
|
|
mediaSourceFramesPerSecond: nullableSafeEvidenceNumber.optional(),
|
|
width: nullableSafeEvidenceInteger.optional(),
|
|
height: nullableSafeEvidenceInteger.optional(),
|
|
videoEncodingCount: nullableSafeEvidenceInteger.optional(),
|
|
activeVideoEncodingCount: nullableSafeEvidenceInteger.optional(),
|
|
availableOutgoingKbps: nullableSafeEvidenceNumber.optional(),
|
|
rttMs: nullableSafeEvidenceNumber.optional(),
|
|
packetLossPercent: nullableEvidenceNumber(100).optional(),
|
|
})
|
|
.strict();
|
|
|
|
export const viewerQualityEvidenceMessageSchema = z
|
|
.object({
|
|
type: z.literal("viewer-quality-evidence"),
|
|
guard: viewerQualityEvidenceGuardSchema,
|
|
...viewerQualityEvidenceWindowShape,
|
|
})
|
|
.strict();
|
|
|
|
export const senderQualityEvidenceMessageSchema = z
|
|
.object({
|
|
type: z.literal("sender-quality-evidence"),
|
|
childPeerId: opaqueIdSchema,
|
|
connectionId: opaqueIdSchema,
|
|
rtpStatsId: z.string().min(1).max(256).nullable(),
|
|
trackIdentifier: z.string().min(1).max(256).nullable(),
|
|
sampleTimestampMs: z
|
|
.number()
|
|
.finite()
|
|
.min(0)
|
|
.max(Number.MAX_SAFE_INTEGER)
|
|
.nullable(),
|
|
routeRevision: mediaRouteRevisionSchema,
|
|
state: z.enum(["unknown", "healthy", "degraded"]),
|
|
diagnostics: senderQualityDiagnosticsSchema,
|
|
})
|
|
.strict()
|
|
.superRefine((message, context) => {
|
|
if (
|
|
(message.state !== "unknown" &&
|
|
(message.rtpStatsId === null ||
|
|
message.trackIdentifier === null ||
|
|
message.sampleTimestampMs === null))
|
|
) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "Known sender quality needs exact RTP identity",
|
|
path: ["rtpStatsId"],
|
|
});
|
|
}
|
|
const reason = message.diagnostics.reason;
|
|
if (
|
|
(message.state === "healthy" && reason !== "none") ||
|
|
(message.state === "degraded" &&
|
|
reason !== "bandwidth" &&
|
|
reason !== "cpu") ||
|
|
(message.state === "unknown" && reason !== null)
|
|
) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "Sender quality reason must match its native state",
|
|
path: ["diagnostics", "reason"],
|
|
});
|
|
}
|
|
});
|
|
|
|
export const sfuPublisherQualityEvidenceMessageSchema = z
|
|
.object({
|
|
type: z.literal("sfu-publisher-quality-evidence"),
|
|
publicationGeneration: opaqueIdSchema,
|
|
routeRevision: mediaRouteRevisionSchema,
|
|
state: z.enum(["unknown", "healthy", "degraded"]),
|
|
sampleTimestampMs: z
|
|
.number()
|
|
.finite()
|
|
.min(0)
|
|
.max(Number.MAX_SAFE_INTEGER)
|
|
.nullable(),
|
|
diagnostics: senderQualityDiagnosticsSchema,
|
|
})
|
|
.strict()
|
|
.superRefine((message, context) => {
|
|
if (message.state !== "unknown" && message.sampleTimestampMs === null) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "Known SFU publisher quality needs an exact sample",
|
|
path: ["sampleTimestampMs"],
|
|
});
|
|
}
|
|
const reason = message.diagnostics.reason;
|
|
if (
|
|
(message.state === "healthy" && reason !== "none") ||
|
|
(message.state === "degraded" &&
|
|
reason !== "bandwidth" &&
|
|
reason !== "cpu") ||
|
|
(message.state === "unknown" && reason !== null)
|
|
) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "SFU publisher reason must match its native state",
|
|
path: ["diagnostics", "reason"],
|
|
});
|
|
}
|
|
});
|
|
|
|
const authenticateMessageSchema = z.discriminatedUnion("role", [
|
|
z
|
|
.object({
|
|
type: z.literal("authenticate"),
|
|
protocol: z.literal(SIGNALING_PROTOCOL),
|
|
roomId: roomCodeSchema,
|
|
role: z.literal("host"),
|
|
token: tokenSchema,
|
|
clientId: opaqueIdSchema,
|
|
shareGeneration: opaqueIdSchema.optional(),
|
|
roomOnly: z.literal(true).optional(),
|
|
roomSession: z.literal(true).optional(),
|
|
sharingPaused: z.boolean().optional(),
|
|
qualitySettings: qualitySettingsSchema.optional(),
|
|
routePolicy: routePolicySchema.default(DEFAULT_ROUTE_POLICY),
|
|
viewerPresence: z.literal(true).optional(),
|
|
displayName: displayNameSchema.optional(),
|
|
})
|
|
.strict()
|
|
.superRefine((message, context) => {
|
|
if (message.roomOnly === true && message.roomSession !== true) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "roomOnly requires roomSession",
|
|
path: ["roomOnly"],
|
|
});
|
|
}
|
|
}),
|
|
z
|
|
.object({
|
|
type: z.literal("authenticate"),
|
|
protocol: z.literal(SIGNALING_PROTOCOL),
|
|
roomId: roomCodeSchema,
|
|
role: z.literal("viewer"),
|
|
clientId: opaqueIdSchema,
|
|
viewerGrant: viewerGrantSchema.optional(),
|
|
viewerPassword: viewerPasswordSchema.optional(),
|
|
routePreference: viewerRoutePreferenceSchema.optional(),
|
|
displayName: displayNameSchema.optional(),
|
|
viewerPresence: z.literal(true).optional(),
|
|
})
|
|
.strict(),
|
|
]);
|
|
|
|
const signalingChallengeSequenceSchema = z
|
|
.number()
|
|
.int()
|
|
.min(0)
|
|
.max(Number.MAX_SAFE_INTEGER);
|
|
|
|
export const clientMessageSchema = z.union([
|
|
z.object({ type: z.literal("set-relay-volunteer"), enabled: z.boolean(),
|
|
capacity: z.number().int().min(0).max(MAX_VIEWERS_PER_ROOM_LIMIT),
|
|
settings: z.boolean().optional(), physicalCapacity: z.number().int().min(0).max(MAX_VIEWERS_PER_ROOM_LIMIT).optional(),
|
|
}).strict().refine(value => Boolean(value.settings) === (value.physicalCapacity !== undefined)),
|
|
z.object({ type: z.literal("subscribe-room-voice"), deafened: z.boolean().optional(), bitrate: z.literal(true).optional() }).strict(),
|
|
z.object({ type: z.literal("room-voice-command"), command: roomVoiceCommandSchema }).strict(),
|
|
z.object({ type: z.literal("room-voice-signal"), ...voiceSignalShape }).strict()
|
|
.refine(value => Number(!!value.description) + Number(!!value.candidate) + Number(!!value.renegotiate) === 1),
|
|
z.object({ type: z.literal("room-voice-transport"), connectionId: opaqueIdSchema,
|
|
state: z.enum(["connected", "failed"]) }).strict(),
|
|
z.object({ type: z.literal("set-viewer-route-preference"), preference: viewerRoutePreferenceSchema }).strict(),
|
|
z.object({ type: z.literal("subscribe-audio-presence") }).strict(),
|
|
z.object({ type: z.literal("subscribe-co-play-presence") }).strict(),
|
|
z.object({ type: z.literal("set-co-play-presence"), shareGeneration: opaqueIdSchema,
|
|
grants: z.array(coPlayGrantSchema).max(MAX_VIEWERS_PER_ROOM_LIMIT)
|
|
.refine(grants => new Set(grants.map(grant => grant.endpointId)).size === grants.length) }).strict(),
|
|
z.object({ type: z.literal("set-audio-presence"), shareGeneration: opaqueIdSchema, available: z.boolean() }).strict(),
|
|
z.object({ type: z.literal("subscribe-remote-input"), endpointId: z.string().regex(/^[0-9a-f]{32}$/).optional(),
|
|
secret: z.string().regex(/^[0-9a-f]{64}$/).optional() }).strict(),
|
|
z.object({ type: z.literal("subscribe-room-interactions") }).strict(),
|
|
z.object({ type: z.literal("send-room-interaction"), requestId: opaqueIdSchema,
|
|
payload: interactionPayloadSchema }).strict(),
|
|
authenticateMessageSchema,
|
|
z
|
|
.object({
|
|
type: z.literal("signaling-challenge"),
|
|
sequence: signalingChallengeSequenceSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("signal"),
|
|
targetPeerId: opaqueIdSchema.optional(),
|
|
payload: signalPayloadSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("restart-request"),
|
|
targetPeerId: opaqueIdSchema.optional(),
|
|
connectionId: opaqueIdSchema,
|
|
rebuild: z.boolean(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("set-quality-settings"),
|
|
qualitySettings: qualitySettingsSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("relay-capacity"),
|
|
downstreamEdges: relayDownstreamEdgesSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("route-ready"),
|
|
revision: mediaRouteRevisionSchema,
|
|
phase: mediaRoutePhaseSchema,
|
|
qualityApproved: z.literal(true).optional(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("route-transport-connected"),
|
|
revision: mediaRouteRevisionSchema,
|
|
connectionId: opaqueIdSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("route-media-unavailable"),
|
|
revision: mediaRouteRevisionSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("route-failed"),
|
|
revision: mediaRouteRevisionSchema,
|
|
phase: mediaRoutePhaseSchema,
|
|
connectionId: opaqueIdSchema.nullable(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("refresh-sfu"),
|
|
revision: mediaRouteRevisionSchema,
|
|
})
|
|
.strict(),
|
|
sfuSignalMessageSchema,
|
|
z.object({ type: z.literal("request-route-diagnostic") }).strict(),
|
|
viewerQualityEvidenceMessageSchema,
|
|
senderQualityEvidenceMessageSchema,
|
|
sfuPublisherQualityEvidenceMessageSchema,
|
|
z.object({ type: z.literal("reset-sender-quality") }).strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("set-display-name"),
|
|
displayName: displayNameSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("set-sharing-paused"),
|
|
shareGeneration: opaqueIdSchema,
|
|
paused: z.boolean(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("stop-sharing"),
|
|
shareGeneration: opaqueIdSchema.optional(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("start-sharing"),
|
|
shareGeneration: opaqueIdSchema,
|
|
sharingPaused: z.boolean().optional(),
|
|
qualitySettings: qualitySettingsSchema.optional(),
|
|
routePolicy: routePolicySchema,
|
|
})
|
|
.strict(),
|
|
z.object({ type: z.literal("abandon-room") }).strict(),
|
|
]);
|
|
export type ClientMessage = z.infer<typeof clientMessageSchema>;
|
|
|
|
const errorCodeSchema = z.enum([
|
|
"AUTH_REQUIRED",
|
|
"INVALID_MESSAGE",
|
|
"INVALID_TOKEN",
|
|
"ROOM_ACCESS_DENIED",
|
|
"ROOM_NOT_FOUND",
|
|
"ROOM_FULL",
|
|
"HOST_ALREADY_CONNECTED",
|
|
"PEER_NOT_FOUND",
|
|
"FORBIDDEN",
|
|
"SERVER_ERROR",
|
|
]);
|
|
|
|
const authenticatedMessageShape = {
|
|
type: z.literal("authenticated"),
|
|
protocol: z.literal(SIGNALING_PROTOCOL),
|
|
peerId: opaqueIdSchema,
|
|
maxViewers: z.number().int().min(1).max(MAX_VIEWERS_PER_ROOM_LIMIT),
|
|
endpointMediaCopyCapacity: z
|
|
.number()
|
|
.int()
|
|
.min(1)
|
|
.max(MAX_ENDPOINT_MEDIA_COPY_CAPACITY),
|
|
hostOnline: z.boolean(),
|
|
hostPaused: z.boolean().optional(),
|
|
connectionId: opaqueIdSchema.nullable(),
|
|
iceConfig: iceConfigSchema,
|
|
routePolicy: routePolicySchema.default(DEFAULT_ROUTE_POLICY),
|
|
codeEntryPolicy: codeEntryPolicySchema,
|
|
viewerAuthorizationGeneration: opaqueIdSchema,
|
|
};
|
|
|
|
const authenticatedHostMessageShape = {
|
|
...authenticatedMessageShape,
|
|
role: z.literal("host"),
|
|
viewerPasswordEnabled: z.boolean(),
|
|
};
|
|
|
|
const authenticatedViewerMessageShape = {
|
|
...authenticatedMessageShape,
|
|
role: z.literal("viewer"),
|
|
};
|
|
|
|
const routeAuthenticatedShape = {
|
|
mediaMode: z.literal("peer-assisted"),
|
|
shareGeneration: opaqueIdSchema.nullable(),
|
|
routeRevision: mediaRouteRevisionSchema,
|
|
routeAssignment: participantRouteAssignmentSchema,
|
|
qualitySettings: qualitySettingsSchema,
|
|
};
|
|
|
|
const authenticatedMessageSchema = z.union([
|
|
z
|
|
.object({
|
|
...authenticatedHostMessageShape,
|
|
...routeAuthenticatedShape,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
...authenticatedViewerMessageShape,
|
|
...routeAuthenticatedShape,
|
|
})
|
|
.strict(),
|
|
]);
|
|
|
|
export const serverMessageSchema = z.union([
|
|
z.object({ type: z.literal("relay-volunteer"), enabled: z.boolean(),
|
|
capacity: z.number().int().min(0).max(MAX_VIEWERS_PER_ROOM_LIMIT),
|
|
roomCapacity: z.number().int().min(1).max(MAX_VIEWERS_PER_ROOM_LIMIT).optional(),
|
|
}).strict(),
|
|
roomVoiceStateSchema,
|
|
z.object({ type: z.literal("room-voice-signal"), ...voiceSignalShape }).strict()
|
|
.refine(value => Number(!!value.description) + Number(!!value.candidate) + Number(!!value.renegotiate) === 1),
|
|
z.object({ type: z.literal("room-voice-error"),
|
|
code: z.enum(["not-allowed", "not-enabled", "connection-unavailable"]) }).strict(),
|
|
z.object({ type: z.literal("viewer-route-preference"), preference: viewerRoutePreferenceSchema, accepted: z.boolean() }).strict(),
|
|
z.object({ type: z.literal("audio-presence"), available: z.boolean().nullable() }).strict(),
|
|
z.object({ type: z.literal("co-play-presence"), participants: z.array(coPlayParticipantSchema).max(MAX_VIEWERS_PER_ROOM_LIMIT)
|
|
.refine(participants => new Set(participants.map(person => person.peerId)).size === participants.length) }).strict(),
|
|
z.object({ type: z.literal("remote-input-peers"), peers: z.array(z.object({ peerId: opaqueIdSchema,
|
|
endpointId: z.string().regex(/^[0-9a-f]{32}$/), secret: z.string().regex(/^[0-9a-f]{64}$/) }).strict()).max(MAX_VIEWERS_PER_ROOM_LIMIT) }).strict(),
|
|
z.object({ type: z.literal("room-interactions-ready"), serverTime: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER) }).strict(),
|
|
z.object({ type: z.literal("room-interaction-rejected"), requestId: opaqueIdSchema,
|
|
reason: z.enum(["rate-limited", "target-unavailable", "not-subscribed", "busy"]) }).strict(),
|
|
z.object({ type: z.literal("room-interaction"), id: opaqueIdSchema, requestId: opaqueIdSchema,
|
|
occurredAt: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
|
sender: z.object({ peerId: opaqueIdSchema, role: z.enum(["host", "viewer"]), displayName: displayNameSchema }).strict(),
|
|
payload: receivedInteractionPayloadSchema }).strict(),
|
|
authenticatedMessageSchema,
|
|
z.object({
|
|
type: z.literal("sharing-start-failed"),
|
|
shareGeneration: opaqueIdSchema,
|
|
code: z.enum(["FORBIDDEN", "SERVER_ERROR"]),
|
|
}).strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("sharing-started"),
|
|
shareGeneration: opaqueIdSchema,
|
|
routePolicy: routePolicySchema,
|
|
routeRevision: mediaRouteRevisionSchema,
|
|
routeAssignment: participantRouteAssignmentSchema,
|
|
qualitySettings: qualitySettingsSchema,
|
|
paused: z.boolean(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("signaling-challenge-response"),
|
|
sequence: signalingChallengeSequenceSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("signal"),
|
|
fromPeerId: opaqueIdSchema,
|
|
payload: signalPayloadSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("restart-request"),
|
|
fromPeerId: opaqueIdSchema,
|
|
connectionId: opaqueIdSchema,
|
|
rebuild: z.boolean(),
|
|
})
|
|
.strict(),
|
|
z.discriminatedUnion("phase", [
|
|
z
|
|
.object({
|
|
type: z.literal("route-update"),
|
|
revision: mediaRouteRevisionSchema,
|
|
phase: z.literal("prepare"),
|
|
assignment: participantRouteAssignmentSchema,
|
|
candidate: preparedRouteCandidateSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("route-update"),
|
|
revision: mediaRouteRevisionSchema,
|
|
phase: z.literal("active"),
|
|
assignment: participantRouteAssignmentSchema,
|
|
})
|
|
.strict(),
|
|
]),
|
|
z.discriminatedUnion("state", [
|
|
z
|
|
.object({
|
|
type: z.literal("route-status"),
|
|
revision: mediaRouteRevisionSchema,
|
|
state: z.literal("waiting"),
|
|
reason: z.literal("sfu-admission"),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("route-status"),
|
|
revision: mediaRouteRevisionSchema,
|
|
state: z.literal("failed"),
|
|
reason: z.literal("route-exhausted"),
|
|
})
|
|
.strict(),
|
|
]),
|
|
z
|
|
.object({
|
|
type: z.literal("route-diagnostic-snapshot"),
|
|
snapshot: routeDiagnosticSnapshotSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("sfu-config"),
|
|
revision: mediaRouteRevisionSchema,
|
|
publicationGeneration: opaqueIdSchema,
|
|
connectionId: opaqueIdSchema,
|
|
})
|
|
.strict(),
|
|
sfuSignalMessageSchema,
|
|
z
|
|
.object({
|
|
type: z.literal("quality-settings"),
|
|
qualitySettings: qualitySettingsSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("route-policy"),
|
|
shareGeneration: opaqueIdSchema,
|
|
routePolicy: routePolicySchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("pause-sharing-source"),
|
|
shareGeneration: opaqueIdSchema,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("viewer-quality-evidence"),
|
|
viewerPeerId: opaqueIdSchema,
|
|
upstream: activeMediaRouteUpstreamSchema,
|
|
guard: viewerQualityEvidenceGuardSchema,
|
|
...viewerQualityEvidenceWindowShape,
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("host-status"),
|
|
online: z.boolean(),
|
|
paused: z.boolean(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("viewer-presence"),
|
|
viewers: z
|
|
.array(participantPresenceEntrySchema)
|
|
.max(MAX_PARTICIPANTS_PER_ROOM_LIMIT),
|
|
})
|
|
.strict()
|
|
.superRefine((message, context) => {
|
|
const peerIds = new Set<string>();
|
|
for (const viewer of message.viewers) {
|
|
if (peerIds.has(viewer.peerId)) {
|
|
context.addIssue({
|
|
code: "custom",
|
|
message: "Viewer presence peer IDs must be unique",
|
|
path: ["viewers"],
|
|
});
|
|
return;
|
|
}
|
|
peerIds.add(viewer.peerId);
|
|
}
|
|
}),
|
|
z
|
|
.object({
|
|
type: z.literal("viewer-grant-revoked"),
|
|
viewerAuthorizationGeneration: opaqueIdSchema,
|
|
})
|
|
.strict(),
|
|
z.object({ type: z.literal("sharing-stopped") }).strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("room-closed"),
|
|
reason: z.literal("host-ended"),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("error"),
|
|
code: errorCodeSchema,
|
|
message: z.string().min(1).max(256),
|
|
})
|
|
.strict(),
|
|
]);
|
|
export type ServerMessage = z.infer<typeof serverMessageSchema>;
|
|
|
|
export const createRoomResponseSchema = z
|
|
.object({
|
|
roomId: roomCodeSchema,
|
|
hostToken: tokenSchema,
|
|
inviteUrl: z.string().url().max(2048),
|
|
codeEntryPolicy: codeEntryPolicySchema,
|
|
})
|
|
.strict();
|
|
export type CreateRoomResponse = z.infer<typeof createRoomResponseSchema>;
|
|
|
|
export const createRoomRequestSchema = z
|
|
.object({
|
|
codeEntryPolicy: codeEntryPolicySchema,
|
|
roomPassword: viewerPasswordSchema.nullable().optional(),
|
|
preferredRoomId: roomCodeSchema.optional(),
|
|
})
|
|
.strict();
|
|
|
|
export const replaceRoomRequestSchema = z
|
|
.object({
|
|
codeEntryPolicy: codeEntryPolicySchema,
|
|
roomPassword: viewerPasswordSchema.nullable().optional(),
|
|
})
|
|
.strict();
|
|
export type ReplaceRoomRequest = z.infer<typeof replaceRoomRequestSchema>;
|
|
|
|
export const roomAccessUpdateRequestSchema = z.discriminatedUnion("action", [
|
|
z
|
|
.object({
|
|
action: z.literal("set-code-entry-policy"),
|
|
policy: codeEntryPolicySchema,
|
|
})
|
|
.strict(),
|
|
z.object({ action: z.literal("rotate-viewer-grant") }).strict(),
|
|
z.object({ action: z.literal("revoke-viewer-grant") }).strict(),
|
|
z
|
|
.object({
|
|
action: z.literal("set-viewer-password"),
|
|
password: viewerPasswordSchema.nullable(),
|
|
})
|
|
.strict(),
|
|
]);
|
|
export type RoomAccessUpdateRequest = z.infer<
|
|
typeof roomAccessUpdateRequestSchema
|
|
>;
|
|
|
|
export const roomAccessUpdateResponseSchema = z.discriminatedUnion("type", [
|
|
z
|
|
.object({
|
|
type: z.literal("code-entry-policy-updated"),
|
|
codeEntryPolicy: codeEntryPolicySchema,
|
|
viewerPasswordEnabled: z.boolean(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("viewer-grant-updated"),
|
|
viewerAuthorizationGeneration: opaqueIdSchema,
|
|
inviteUrl: z.string().url().max(2048).nullable(),
|
|
})
|
|
.strict(),
|
|
z
|
|
.object({
|
|
type: z.literal("viewer-password-updated"),
|
|
enabled: z.boolean(),
|
|
})
|
|
.strict(),
|
|
]);
|
|
export type RoomAccessUpdateResponse = z.infer<
|
|
typeof roomAccessUpdateResponseSchema
|
|
>;
|
|
|
|
export function decodeClientMessage(value: string): ClientMessage {
|
|
return clientMessageSchema.parse(JSON.parse(value));
|
|
}
|
|
|
|
export function decodeServerMessage(value: string): ServerMessage {
|
|
return serverMessageSchema.parse(JSON.parse(value));
|
|
}
|