diff --git a/README.md b/README.md index c5cffd07..a3a5244f 100644 --- a/README.md +++ b/README.md @@ -2999,6 +2999,22 @@ This implementation keeps the published SDK pin unchanged. Release waits for a matching SDK prerelease and accepted API contract; source support does not imply package publication or beta availability. +## Guest participants and waiting rooms (unreleased) + +Call participant output preserves optional `guest` and `name` fields. A name is unverified display text; the public participant ID remains the identity used for controls. A phone number is optional. + +`calls media --control-input commands.jsonl` reads explicit host commands on the same media connection. Use a file or pipe separate from PCM input; `--control-input -` reads stdin when `--input` does not use stdin. Each nonblank line is one command: + +```json +{"action":"set_approval_required","enabled":true} +{"action":"admit","participantId":"739182640518203"} +{"action":"deny","participantId":"739182640518204"} +``` + +The command reports waiting-room state and matching results to stderr, as JSON lines with `--json`. It never opens another connection to impersonate the host or retries an uncertain command. Check the current roster before deciding to send another action after `waiting_room_control_unknown`. Rendered names are quoted so control characters cannot become terminal instructions. + +The flag requires a Calls SDK that implements waiting-room controls and fails before connecting if the installed SDK lacks them. Source verification uses the SDK pinned by `contracts/connections.json`. Earlier guest candidate evidence is recorded in `contracts/calls-guests.candidate.json`. Publication requires a matching registry SDK and API environment acceptance. + ## Channel update metadata Use the existing event stream to read `newsletter.update` observations as JSON lines: diff --git a/contracts/calls-guests.candidate.json b/contracts/calls-guests.candidate.json new file mode 100644 index 00000000..ed92f59b --- /dev/null +++ b/contracts/calls-guests.candidate.json @@ -0,0 +1,27 @@ +{ + "sourceAccepted": false, + "published": false, + "apiVersion": "2026-09-22", + "apiSource": "c544725b57f198a9eebf70a6edf18383bad07073", + "sdkSource": "aaee221bdead14897922d56e9ccb144c1de55668", + "sdkSnippetExport": "08940b3c0625fc21a1a8abcfbe3663f22017e944", + "physicalPackageSha256": "cd7fed327c16ca3d7b7aeb96755291683f9f150890b9ab9a6673dab60c78c66c", + "publishedDependencyUnchanged": true, + "operations": ["set_approval_required", "admit", "deny"], + "authority": "same held live media connection; each moderation command requires live signaling permission and exact team, Number, generation, participant and provider-admin authority", + "replay": "never automatic; a matching acknowledgement is required", + "evidence": "POLYMORFA_GUEST_SDK_REQUIRED=1 native CLI calls-sockets fixture with candidate package", + "releaseGates": [ + "accepted API and SDK source", + "matching staging acceptance before nightly", + "matching production acceptance before stable", + "native paired-host waiting-room moderation acceptance", + "matching published SDK version before dependency pin", + "CLI merge and publication after the matching SDK dependency is pinned" + ], + "acceptance": { + "publishedDependency": "ordinary npm run verify passes: 1245 tests passed, one candidate-only test skipped; format, lint, types, build, reference, browser and physical bundled-runtime checks pass; published SDK dependency unchanged", + "candidatePackage": "physical SDK archive cd7fed327c16ca3d7b7aeb96755291683f9f150890b9ab9a6673dab60c78c66c: 1246 tests passed with POLYMORFA_GUEST_SDK_REQUIRED=1, typecheck and browser verification passed; no registry or environment acceptance claimed", + "dependencyPin": "published version remains unchanged until matching SDK publication and API environment acceptance" + } +} diff --git a/contracts/cli-reference.json b/contracts/cli-reference.json index b4795c27..fba702ad 100644 --- a/contracts/cli-reference.json +++ b/contracts/cli-reference.json @@ -12625,6 +12625,18 @@ "env": null, "helpGroup": null }, + { + "name": "control-input", + "char": null, + "type": "option", + "required": false, + "multiple": false, + "default": null, + "options": [], + "description": "Read waiting-room commands as JSON lines from a file or - for stdin, on this live connection. Requires a Calls SDK with waiting-room support.", + "env": null, + "helpGroup": null + }, { "name": "exclusive", "char": null, diff --git a/src/commands/calls/media.ts b/src/commands/calls/media.ts index d97cd27b..35acb706 100644 --- a/src/commands/calls/media.ts +++ b/src/commands/calls/media.ts @@ -1,8 +1,12 @@ -import {assertCallMediaMuteSupported} from '../../services/call-media-controls.js' +import { + assertCallMediaMuteSupported, + assertWaitingRoomSupported, +} from '../../services/call-media-controls.js' import {createWriteStream, type ReadStream, type WriteStream} from 'node:fs' import {open, stat} from 'node:fs/promises' import {once} from 'node:events' import {resolve} from 'node:path' +import type {Readable} from 'node:stream' import {Args, Flags} from '@oclif/core' import {PolymorfaConfigurationError} from '@polymorfa/sdk' @@ -37,6 +41,10 @@ export default class CallsMedia extends BaseCommand { ] static override flags = { + 'control-input': Flags.string({ + description: + 'Read waiting-room commands as JSON lines from a file or - for stdin, on this live connection. Requires a Calls SDK with waiting-room support.', + }), muted: Flags.boolean({ exclusive: ['input'], description: @@ -81,6 +89,27 @@ export default class CallsMedia extends BaseCommand { async run(): Promise { const {args, flags} = await this.parse(CallsMedia) if (flags.muted) assertCallMediaMuteSupported() + if (flags['control-input'] !== undefined) assertWaitingRoomSupported() + if ( + flags['control-input'] === '-' && + (flags.input === '-' || process.stdin.isTTY) + ) { + throw new PolymorfaConfigurationError( + 'Pipe JSON lines to --control-input - separately from PCM input.', + 'control-input', + ) + } + if ( + flags['control-input'] && + flags['control-input'] !== '-' && + flags.output !== '-' && + (await sameFile(flags['control-input'], flags.output)) + ) { + throw new PolymorfaConfigurationError( + '--control-input and --output name the same file.', + 'control-input', + ) + } if (flags.output === '-' && process.stdout.isTTY) { throw new PolymorfaConfigurationError( 'Received audio is binary. Redirect standard output or pass --output .', @@ -119,6 +148,18 @@ export default class CallsMedia extends BaseCommand { throw inputFailed(inputPath, error) } } + let controls: Readable | undefined + if (flags['control-input'] !== undefined) { + try { + controls = + flags['control-input'] === '-' + ? process.stdin + : (await open(flags['control-input'], 'r')).createReadStream() + } catch (error) { + inputFile?.destroy() + throw inputFailed(flags['control-input'], error) + } + } const json = this.outputMode(flags) === 'json' const quiet = this.outputMode(flags) === 'quiet' const report = (value: object, human: string): void => { @@ -158,6 +199,7 @@ export default class CallsMedia extends BaseCommand { halt.abort() } input?.on('error', onInputError) + controls?.on('error', onInputError) // Flush and close the output file once; its errors arrive asynchronously. let outputClosed = false @@ -177,6 +219,7 @@ export default class CallsMedia extends BaseCommand { exclusive: flags.exclusive, muted: flags.muted, input, + controls, leaveOnEnd: flags['leave-on-eof'], output, participant: flags.participant, @@ -202,6 +245,8 @@ export default class CallsMedia extends BaseCommand { // it (a microphone, tail -f), which would keep the process alive. if (input === process.stdin) process.stdin.destroy() input?.off('error', onInputError) + controls?.destroy() + controls?.off('error', onInputError) await closeOutput() } if (fileError !== undefined) throw outputFailed(flags.output, fileError) @@ -222,6 +267,8 @@ function renderMediaStatus( return `Connected to call ${status.callId} as connection ${status.connectionId} at ${status.sampleRate} Hz.` case 'placed': return `Placed call ${status.callId}; waiting for an answer.` + case 'waiting_room_control_result': + return `Waiting-room command ${status.sequence} (${status.action}): ${status.ok ? 'confirmed' : (status.code ?? 'failed')}.` case 'input_ended': return `Sent all input audio (${status.bytes} bytes).` default: diff --git a/src/developer/render.ts b/src/developer/render.ts index d84be288..8c69b8cc 100644 --- a/src/developer/render.ts +++ b/src/developer/render.ts @@ -167,7 +167,7 @@ export function terminalText(value: string | number | boolean | null): string { if (value === null) return '-' return String(value).replace( // eslint-disable-next-line no-control-regex - /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, + /[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, '0')}`, ) diff --git a/src/listener/forwarding.ts b/src/listener/forwarding.ts index 3ece93bd..457d6c0e 100644 --- a/src/listener/forwarding.ts +++ b/src/listener/forwarding.ts @@ -322,7 +322,9 @@ function send( path: `${destination.url.pathname}${destination.url.search}`, port: destination.url.port || undefined, rejectUnauthorized: !(input.skipVerify && destination.loopback), - servername: hostname(destination.url), + servername: isIP(hostname(destination.url)) + ? '' + : hostname(destination.url), signal: input.signal, timeout: 10_000, }, diff --git a/src/output/calls.ts b/src/output/calls.ts index a3051ef7..f6d9656f 100644 --- a/src/output/calls.ts +++ b/src/output/calls.ts @@ -1,3 +1,4 @@ +import {terminalText} from '../developer/render.js' import type {CallActivity, CallsStatus} from '../services/calls.js' /** An abort signal for Ctrl-C and SIGTERM, removed when the command ends. */ @@ -58,12 +59,26 @@ export function renderCallActivity(activity: CallActivity): string { `participant=${activity.participant.id}`, `state=${activity.participant.state}`, ) + if ((activity.participant as {guest?: boolean}).guest === true) + fields.push('guest=true') + if (typeof (activity.participant as {name?: string}).name === 'string') + fields.push( + `name=${terminalText(JSON.stringify((activity.participant as {name?: string}).name))}`, + ) break case 'participant_left': fields.push(`participant=${activity.participantId}`) if (activity.reason !== undefined) fields.push(`reason=${activity.reason}`) break + case 'waiting_room': + fields.push( + `approvalRequired=${activity.room.enabled}`, + `isAdmin=${activity.room.isAdmin}`, + `inWaitingRoom=${activity.room.inWaitingRoom}`, + `users=${terminalText(JSON.stringify(activity.room.users))}`, + ) + break case 'ended': fields.push(`reason=${activity.reason}`, `duration=${activity.duration}s`) break diff --git a/src/services/call-media-controls.ts b/src/services/call-media-controls.ts index 6c7259de..8e6b1158 100644 --- a/src/services/call-media-controls.ts +++ b/src/services/call-media-controls.ts @@ -30,3 +30,123 @@ export async function muteCallMedia(call: object): Promise { ) } } + +export interface WaitingRoomCommand { + readonly action: 'set_approval_required' | 'admit' | 'deny' + readonly enabled?: boolean + readonly participantId?: string +} +interface WaitingRoomControls { + setApprovalRequired(enabled: boolean): Promise + admitParticipant(participantId: string): Promise + denyParticipant(participantId: string): Promise +} + +export function assertWaitingRoomSupported( + candidate: object = Call.prototype, +): asserts candidate is WaitingRoomControls { + const controls = candidate as Partial + if ( + typeof controls.setApprovalRequired !== 'function' || + typeof controls.admitParticipant !== 'function' || + typeof controls.denyParticipant !== 'function' + ) { + throw new PolymorfaConfigurationError( + 'This CLI build needs a published Calls SDK with waiting-room support before --control-input can be used.', + 'control-input', + ) + } +} + +/** One command uses only the Call's current media connection. Never retry it. */ +export async function moderateWaitingRoom( + call: object, + command: WaitingRoomCommand, +): Promise { + assertWaitingRoomSupported(call) + if (command.action === 'set_approval_required') + await call.setApprovalRequired(command.enabled!) + else if (command.action === 'admit') + await call.admitParticipant(command.participantId!) + else await call.denyParticipant(command.participantId!) +} + +/** Read bounded UTF-8 JSON lines from a file or pipe, separate from PCM input. */ +export async function* waitingRoomCommands( + input: AsyncIterable, +): AsyncGenerator { + const decoder = new TextDecoder('utf-8', {fatal: true}) + let pending = '' + function parse(line: string): WaitingRoomCommand { + let value: unknown + try { + value = JSON.parse(line) + } catch { + throw invalidControl() + } + if (!value || typeof value !== 'object' || Array.isArray(value)) + throw invalidControl() + const command = value as Record + const keys = Object.keys(command).sort().join(',') + if ( + command.action === 'set_approval_required' && + keys === 'action,enabled' && + typeof command.enabled === 'boolean' + ) + return {action: command.action, enabled: command.enabled} + if ( + (command.action === 'admit' || command.action === 'deny') && + keys === 'action,participantId' && + typeof command.participantId === 'string' && + /^[1-9][0-9]{0,18}$/.test(command.participantId) + ) + return {action: command.action, participantId: command.participantId} + throw invalidControl() + } + for await (const chunk of input) { + // Process pieces so one large read never grows the pending line without bound. + for (let offset = 0; offset < chunk.length; offset += 1024) { + pending += decoder.decode(chunk.subarray(offset, offset + 1024), { + stream: true, + }) + let newline: number + while ((newline = pending.indexOf('\n')) !== -1) { + const line = pending.slice(0, newline).trim() + if (newline > 4096) throw invalidControl() + pending = pending.slice(newline + 1) + if (line) yield parse(line) + } + if (pending.length > 4096) throw invalidControl() + } + } + pending += decoder.decode() + if (pending.trim()) yield parse(pending.trim()) +} +function invalidControl(): PolymorfaConfigurationError { + return new PolymorfaConfigurationError( + 'Expected a JSON line with action set_approval_required and enabled, or action admit/deny and a public participantId. Lines must be at most 4096 characters.', + 'control-input', + ) +} + +export interface CallWaitingRoom { + readonly enabled: boolean + readonly isAdmin: boolean + readonly inWaitingRoom: boolean + readonly users: readonly { + readonly id: string + readonly state: string + readonly guest?: boolean + readonly name?: string + }[] +} +export function observeWaitingRoom( + call: object, + listener: (state: CallWaitingRoom) => void, +): void { + ;( + call as { + on(event: 'waitingRoom', listener: (state: CallWaitingRoom) => void): void + } + ).on('waitingRoom', listener) +} diff --git a/src/services/calls.ts b/src/services/calls.ts index 349aabfd..9b6bb210 100644 --- a/src/services/calls.ts +++ b/src/services/calls.ts @@ -1,8 +1,14 @@ import { assertCallMediaMuteSupported, muteCallMedia, + assertWaitingRoomSupported, + moderateWaitingRoom, + waitingRoomCommands, + observeWaitingRoom, + type CallWaitingRoom, } from './call-media-controls.js' import {randomBytes} from 'node:crypto' +import {terminalText} from '../developer/render.js' import { CallClaimedError, @@ -656,6 +662,12 @@ export function renderCallParticipant(participant: VoipParticipant): string { participant.username === undefined ? undefined : `Username\t${participant.username}`, + (participant as VoipParticipant & {guest?: boolean}).guest === true + ? 'Guest\tYes' + : undefined, + typeof (participant as VoipParticipant & {name?: string}).name === 'string' + ? `Name\t${terminalText(JSON.stringify((participant as VoipParticipant & {name?: string}).name))}` + : undefined, `State\t${participant.state}`, ] .filter((value): value is string => value !== undefined) @@ -904,6 +916,11 @@ export type CallActivity = readonly participantId: string readonly reason?: string } + | { + readonly type: 'waiting_room' + readonly callId: string + readonly room: CallWaitingRoom + } | { readonly type: 'ended' readonly callId: string @@ -921,6 +938,9 @@ function followCall( call: Call, activity: (activity: CallActivity) => void, ): void { + observeWaitingRoom(call, (room) => + activity({type: 'waiting_room', callId: call.id, room}), + ) call.on('claim', (claim) => activity({type: 'claim', callId: call.id, ...claim}), ) @@ -1048,6 +1068,8 @@ export async function watchCalls( } export interface CallMediaInput extends CallsClientInput { + /** Explicit JSONL controls sent on this connection only, once it connects. */ + readonly controls?: AsyncIterable | undefined readonly muted?: boolean | undefined /** Answer this inbound call; without it, the next inbound call. */ readonly callId?: string | undefined @@ -1075,6 +1097,13 @@ export type CallMediaStatus = } | {readonly type: 'placed'; readonly callId: string} | {readonly type: 'input_ended'; readonly bytes: number} + | { + readonly type: 'waiting_room_control_result' + readonly sequence: number + readonly action: string + readonly ok: boolean + readonly code?: string + } export interface CallMediaSummary { readonly bytesReceived: number @@ -1110,6 +1139,7 @@ export async function bridgeCallMedia( input.place === undefined ? undefined : validateCallTarget(input.place) if (input.callId !== undefined) validateCallId(input.callId) if (input.muted === true) assertCallMediaMuteSupported() + if (input.controls !== undefined) assertWaitingRoomSupported() const client = createCallsClient(input, 'Carrying call media') let bytesReceived = 0 @@ -1216,6 +1246,41 @@ export async function bridgeCallMedia( connectionId: call.connectionId, sampleRate: call.audio.sampleRate, }) + if (input.controls !== undefined) { + const runControls = async (): Promise => { + let sequence = 0 + for await (const command of waitingRoomCommands(input.controls!)) { + if (finished || call.ended) return + sequence += 1 + try { + await moderateWaitingRoom(call, command) + status({ + type: 'waiting_room_control_result', + sequence, + action: command.action, + ok: true, + }) + } catch (error) { + // An uncertain command stays uncertain. The next line is a new user command. + const code = + error instanceof CallsError && + /^[a-z_]{1,80}$/.test(error.code) + ? error.code + : 'waiting_room_control_failed' + status({ + type: 'waiting_room_control_result', + sequence, + action: command.action, + ok: false, + code, + }) + } + } + } + void runControls().catch((error: unknown) => + finish(callsClientError(error)), + ) + } if (input.input === undefined) return pacePcm({ input: input.input, diff --git a/test/commands/calls-sockets.test.ts b/test/commands/calls-sockets.test.ts index 45393c6f..33ef787a 100644 --- a/test/commands/calls-sockets.test.ts +++ b/test/commands/calls-sockets.test.ts @@ -1,3 +1,4 @@ +import {Call} from '@polymorfa/sdk/calls' import { link, mkdir, @@ -29,6 +30,12 @@ const API_KEY = 'pmfa_BAUGBwgJCgsMDQ4PEBESExQVFhfgvFaM' const CLIENT_TOKEN = 'pmfa_ct_cG1mYV9jdF9zb2NrZXRfdGVzdF90b2tlbg' const TIMESTAMP = '2026-09-16T10:00:00.000Z' +const guestSdk = + typeof (Call.prototype as unknown as {admitParticipant?: unknown}) + .admitParticipant === 'function' +if (process.env.POLYMORFA_GUEST_SDK_REQUIRED === '1' && !guestSdk) + throw new Error('Guest acceptance requires the pinned candidate SDK package') + describe('calls watch and media', () => { let server: CallsServer | undefined let directory: string @@ -43,6 +50,112 @@ describe('calls watch and media', () => { await rm(directory, {force: true, recursive: true}) }) + test.runIf(guestSdk)( + 'moderates a guest over the same live media connection and matches the result', + async () => { + const outputPath = join(directory, 'guest.pcm') + const controlsPath = join(directory, 'controls.jsonl') + await writeFile( + controlsPath, + '{"action":"admit","participantId":"123"}\n', + ) + const commands: Record[] = [] + server = await startCallsServer({ + onSocket: async (socket) => { + await socket.next() + if (socket.path.startsWith('/voip/ws')) { + socket.sendJson({participant: 'server:default', type: 'ready'}) + await delay(100) + sendEvent(socket, 'call.accepted', 'call_guest', { + answeredBy: 'server:default', + exclusive: false, + }) + return + } + socket.sendJson({ + callId: 'call_guest', + sampleRate: 16000, + type: 'ready', + video: false, + }) + socket.sendJson({ + type: 'waiting_room', + state: { + enabled: true, + isAdmin: true, + inWaitingRoom: false, + users: [ + { + id: '123', + state: 'invited', + audioMuted: false, + video: false, + guest: true, + name: 'Ada Guest', + }, + ], + }, + }) + const command = JSON.parse(String(await socket.next())) as Record< + string, + unknown + > + commands.push(command) + socket.sendJson({ + type: 'waiting_room_result', + requestId: 'unrelated_update', + ok: true, + }) + await delay(25) + socket.sendJson({ + type: 'waiting_room_result', + requestId: command.requestId, + ok: true, + }) + await delay(25) + socket.close(1000) + }, + rest: () => ({ + body: { + data: {callId: 'call_guest', connection: 'support', video: false}, + success: true, + }, + status: 201, + }), + }) + const result = await apiKey(() => + runCommand( + `calls media --connection support --place +15550100 --output ${outputPath} --control-input ${controlsPath} --json`, + ), + ) + expect(result.error, result.stderr).toBeUndefined() + expect(commands).toHaveLength(1) + expect(commands[0]).toMatchObject({ + type: 'waiting_room_control', + operation: 'admit', + participantId: '123', + }) + expect( + server.sockets.filter((s) => s.path.includes('/media')), + ).toHaveLength(1) + const statuses = result.stderr + .trim() + .split('\n') + .map((line) => JSON.parse(line) as Record) + expect(statuses).toContainEqual({ + type: 'waiting_room_control_result', + sequence: 1, + action: 'admit', + ok: true, + }) + expect( + statuses.find((value) => value.type === 'waiting_room'), + ).toMatchObject({ + room: {users: [{id: '123', guest: true, name: 'Ada Guest'}]}, + }) + }, + ) + test('streams call updates as JSON lines after first-frame authentication', async () => { server = await startCallsServer({ onSocket: async (socket) => { diff --git a/test/developer/render.test.ts b/test/developer/render.test.ts index 8fbb50bc..b1cb20c4 100644 --- a/test/developer/render.test.ts +++ b/test/developer/render.test.ts @@ -142,4 +142,15 @@ describe('developer detail renderers', () => { expect(terminalText(null)).toBe('-') expect(terminalText(false)).toBe('false') }) + + test('escapes directional controls while retaining ordinary RTL text and emoji', () => { + expect( + terminalText( + '\u061c\u200e\u200f\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069', + ), + ).toBe( + '\\u061c\\u200e\\u200f\\u202a\\u202b\\u202c\\u202d\\u202e\\u2066\\u2067\\u2068\\u2069', + ) + expect(terminalText('مرحبا café 👩‍💻')).toBe('مرحبا café 👩‍💻') + }) }) diff --git a/test/output/call-guest-labels.test.ts b/test/output/call-guest-labels.test.ts new file mode 100644 index 00000000..20b38677 --- /dev/null +++ b/test/output/call-guest-labels.test.ts @@ -0,0 +1,65 @@ +import {describe, expect, test} from 'vitest' + +import {renderCallActivity} from '../../src/output/calls.js' +import {renderValue} from '../../src/output/render.js' +import {renderCallParticipant} from '../../src/services/calls.js' + +describe('untrusted guest labels', () => { + test('quotes terminal controls in every human view while preserving JSON data', () => { + const name = 'Ada\u009b31m\u202eGuest\u2066' + const participant = { + audioMuted: false, + guest: true, + id: '123', + name, + state: 'connected' as const, + video: false, + } + const views = [ + renderCallActivity({ + callId: 'call_1', + participant, + type: 'participant_joined', + }), + renderCallActivity({ + callId: 'call_1', + room: { + enabled: true, + inWaitingRoom: false, + isAdmin: true, + users: [participant], + }, + type: 'waiting_room', + }), + renderCallParticipant(participant), + ] + expect(views.map((view) => /[\u009b\u202e\u2066]/u.test(view))).toEqual([ + false, + false, + false, + ]) + for (const view of views) + expect(view).toContain('Ada\\u009b31m\\u202eGuest\\u2066') + expect(views[0]).toContain('participant=123') + expect(views[2]).toContain('Participant\t123') + expect(JSON.parse(renderValue(participant, 'json', views[2])!)).toEqual( + participant, + ) + expect(renderValue(participant, 'quiet', views[2])).toBeUndefined() + }) + + test('keeps ordinary Unicode names and absent-name behavior', () => { + const participant = { + id: '123', + state: 'connected' as const, + video: false, + audioMuted: false, + } + const name = 'مرحبا café 👩‍💻' + const namedParticipant = {...participant, name} + expect(renderCallParticipant(namedParticipant)).toContain( + `Name\t${JSON.stringify(name)}`, + ) + expect(renderCallParticipant(participant)).not.toContain('Name\t') + }) +}) diff --git a/test/services/call-guest-controls.test.ts b/test/services/call-guest-controls.test.ts new file mode 100644 index 00000000..870af8ca --- /dev/null +++ b/test/services/call-guest-controls.test.ts @@ -0,0 +1,58 @@ +import {Readable} from 'node:stream' +import {describe, expect, test, vi} from 'vitest' +import { + assertWaitingRoomSupported, + moderateWaitingRoom, + waitingRoomCommands, +} from '../../src/services/call-media-controls.js' + +describe('live guest moderation', () => { + test('refuses old SDKs before a connection', () => { + expect(() => assertWaitingRoomSupported({})).toThrow('published Calls SDK') + }) + test('uses the held connection and never retries an unknown outcome', async () => { + const admitParticipant = vi.fn(() => + Promise.reject(new Error('waiting_room_control_unknown')), + ) + const call = { + setApprovalRequired: vi.fn(), + admitParticipant, + denyParticipant: vi.fn(), + } + await expect( + moderateWaitingRoom(call, {action: 'admit', participantId: '123'}), + ).rejects.toThrow('unknown') + expect(admitParticipant).toHaveBeenCalledExactlyOnceWith('123') + expect(call.denyParticipant).not.toHaveBeenCalled() + }) + test('reads strict commands separately from PCM', async () => { + const commands = [] + for await (const command of waitingRoomCommands( + Readable.from([ + Buffer.from( + '{"action":"admit","participantId":"123"}\n{"action":"set_approval_required","enabled":true}\n', + ), + ]), + )) + commands.push(command) + expect(commands).toEqual([ + {action: 'admit', participantId: '123'}, + {action: 'set_approval_required', enabled: true}, + ]) + }) + test.each([ + '{"action":"admit","participantId":"123@lid"}', + '{"action":"deny","participantId":"123","connectionId":"foreign"}', + 'x'.repeat(4097), + ])('rejects invalid or unbounded commands', async (line) => { + await expect( + (async () => { + for await (const _ of waitingRoomCommands( + Readable.from([Buffer.from(line)]), + )) { + void _ + } + })(), + ).rejects.toThrow() + }) +}) diff --git a/vitest.config.ts b/vitest.config.ts index ed3126a6..17c20d5a 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,8 +1,11 @@ +import {availableParallelism} from 'node:os' import {defineConfig} from 'vitest/config' export default defineConfig({ test: { clearMocks: true, + // Bound cold CLI/SDK imports without relaxing command deadlines. + maxWorkers: Math.min(4, availableParallelism()), disableConsoleIntercept: true, include: ['test/**/*.test.ts'], },