@rapidmx/meet-plugin 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +382 -0
- package/README.md +38 -0
- package/apps/meet/[token].tsx +144 -0
- package/apps/meet/_CallControls.tsx +69 -0
- package/apps/meet/_CallView.tsx +338 -0
- package/apps/meet/_MeetChrome.tsx +30 -0
- package/apps/meet/_MeetLobby.tsx +223 -0
- package/apps/meet/_ParticipantTile.tsx +66 -0
- package/apps/meet/_layout.tsx +34 -0
- package/apps/meet/_meetApi.ts +66 -0
- package/apps/meet/index.tsx +22 -0
- package/apps/settings-video-conferencing/_PersonalRoomCard.tsx +140 -0
- package/apps/settings-video-conferencing/_layout.tsx +47 -0
- package/apps/settings-video-conferencing/index.tsx +192 -0
- package/apps/shared/media/activeSpeaker.ts +45 -0
- package/apps/shared/media/deviceMedia.ts +141 -0
- package/apps/shared/media/levelMeter.ts +91 -0
- package/apps/shared/push/GuestSignalingClient.ts +338 -0
- package/apps/shared/webrtc/MeshConnectionManager.ts +350 -0
- package/apps/shared/webrtc/realPeerConnection.ts +37 -0
- package/apps/shared/webrtc/types.ts +90 -0
- package/dist/apps/meet/[token].d.ts +33 -0
- package/dist/apps/meet/[token].js +101 -0
- package/dist/apps/meet/_CallControls.d.ts +18 -0
- package/dist/apps/meet/_CallControls.js +6 -0
- package/dist/apps/meet/_CallView.d.ts +41 -0
- package/dist/apps/meet/_CallView.js +225 -0
- package/dist/apps/meet/_MeetChrome.d.ts +13 -0
- package/dist/apps/meet/_MeetChrome.js +10 -0
- package/dist/apps/meet/_MeetLobby.d.ts +29 -0
- package/dist/apps/meet/_MeetLobby.js +120 -0
- package/dist/apps/meet/_ParticipantTile.d.ts +18 -0
- package/dist/apps/meet/_ParticipantTile.js +25 -0
- package/dist/apps/meet/_layout.d.ts +9 -0
- package/dist/apps/meet/_layout.js +8 -0
- package/dist/apps/meet/_meetApi.d.ts +47 -0
- package/dist/apps/meet/_meetApi.js +23 -0
- package/dist/apps/meet/index.d.ts +5 -0
- package/dist/apps/meet/index.js +8 -0
- package/dist/apps/settings-video-conferencing/_PersonalRoomCard.d.ts +24 -0
- package/dist/apps/settings-video-conferencing/_PersonalRoomCard.js +77 -0
- package/dist/apps/settings-video-conferencing/_layout.d.ts +16 -0
- package/dist/apps/settings-video-conferencing/_layout.js +8 -0
- package/dist/apps/settings-video-conferencing/index.d.ts +16 -0
- package/dist/apps/settings-video-conferencing/index.js +92 -0
- package/dist/apps/shared/media/activeSpeaker.d.ts +20 -0
- package/dist/apps/shared/media/activeSpeaker.js +39 -0
- package/dist/apps/shared/media/deviceMedia.d.ts +65 -0
- package/dist/apps/shared/media/deviceMedia.js +110 -0
- package/dist/apps/shared/media/levelMeter.d.ts +40 -0
- package/dist/apps/shared/media/levelMeter.js +61 -0
- package/dist/apps/shared/push/GuestSignalingClient.d.ts +89 -0
- package/dist/apps/shared/push/GuestSignalingClient.js +291 -0
- package/dist/apps/shared/webrtc/MeshConnectionManager.d.ts +97 -0
- package/dist/apps/shared/webrtc/MeshConnectionManager.js +262 -0
- package/dist/apps/shared/webrtc/realPeerConnection.d.ts +7 -0
- package/dist/apps/shared/webrtc/realPeerConnection.js +26 -0
- package/dist/apps/shared/webrtc/types.d.ts +94 -0
- package/dist/apps/shared/webrtc/types.js +9 -0
- package/dist/lib/index.js +25 -0
- package/dist/lib/index.js.map +1 -0
- package/dist/lib/models/mongo/VideoMeetingInviteeMongo.js +87 -0
- package/dist/lib/models/mongo/VideoMeetingInviteeMongo.js.map +1 -0
- package/dist/lib/models/mongo/VideoMeetingMongo.js +126 -0
- package/dist/lib/models/mongo/VideoMeetingMongo.js.map +1 -0
- package/dist/lib/models/sql/VideoMeetingInviteeSQL.js +87 -0
- package/dist/lib/models/sql/VideoMeetingInviteeSQL.js.map +1 -0
- package/dist/lib/models/sql/VideoMeetingSQL.js +127 -0
- package/dist/lib/models/sql/VideoMeetingSQL.js.map +1 -0
- package/dist/lib/models/types.js +19 -0
- package/dist/lib/models/types.js.map +1 -0
- package/dist/lib/mongo.js +13 -0
- package/dist/lib/mongo.js.map +1 -0
- package/dist/lib/routes/BaseVideoMeetingRoute.js +743 -0
- package/dist/lib/routes/BaseVideoMeetingRoute.js.map +1 -0
- package/dist/lib/routes/mongo/VideoMeetingRouteMongo.js +31 -0
- package/dist/lib/routes/mongo/VideoMeetingRouteMongo.js.map +1 -0
- package/dist/lib/routes/sql/VideoMeetingRouteSQL.js +31 -0
- package/dist/lib/routes/sql/VideoMeetingRouteSQL.js.map +1 -0
- package/dist/lib/sql.js +13 -0
- package/dist/lib/sql.js.map +1 -0
- package/dist/lib/util/BookingIntegrationUtils.js +115 -0
- package/dist/lib/util/BookingIntegrationUtils.js.map +1 -0
- package/dist/lib/util/IceServerUtils.js +68 -0
- package/dist/lib/util/IceServerUtils.js.map +1 -0
- package/dist/lib/util/PublicUrlUtils.js +37 -0
- package/dist/lib/util/PublicUrlUtils.js.map +1 -0
- package/dist/lib/util/RouteAccessUtils.js +32 -0
- package/dist/lib/util/RouteAccessUtils.js.map +1 -0
- package/dist/lib/util/TokenUtils.js +33 -0
- package/dist/lib/util/TokenUtils.js.map +1 -0
- package/dist/types/index.d.ts +20 -0
- package/dist/types/models/mongo/VideoMeetingInviteeMongo.d.ts +16 -0
- package/dist/types/models/mongo/VideoMeetingMongo.d.ts +23 -0
- package/dist/types/models/sql/VideoMeetingInviteeSQL.d.ts +16 -0
- package/dist/types/models/sql/VideoMeetingSQL.d.ts +23 -0
- package/dist/types/models/types.d.ts +131 -0
- package/dist/types/mongo.d.ts +8 -0
- package/dist/types/routes/BaseVideoMeetingRoute.d.ts +368 -0
- package/dist/types/routes/mongo/VideoMeetingRouteMongo.d.ts +10 -0
- package/dist/types/routes/sql/VideoMeetingRouteSQL.d.ts +10 -0
- package/dist/types/sql.d.ts +8 -0
- package/dist/types/util/BookingIntegrationUtils.d.ts +51 -0
- package/dist/types/util/IceServerUtils.d.ts +57 -0
- package/dist/types/util/PublicUrlUtils.d.ts +11 -0
- package/dist/types/util/RouteAccessUtils.d.ts +8 -0
- package/dist/types/util/TokenUtils.d.ts +23 -0
- package/package.json +181 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
2
|
+
// Copyright (C) 2026 Jean-Philippe Steinmetz. All rights reserved.
|
|
3
|
+
// SPDX-License-Identifier: MPL-2.0
|
|
4
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
5
|
+
/**
|
|
6
|
+
* Thin, dependency-injectable wrappers over `navigator.mediaDevices` - `enumerateDevices()`/`getUserMedia()`/
|
|
7
|
+
* `getDisplayMedia()` - used by both the join/lobby page's device preview and the in-call view's mute/camera/share
|
|
8
|
+
* controls (see this plugin's Phase 2 `.claude/NOTES.md` entry). Kept under `src/` rather than `apps/meet/` because
|
|
9
|
+
* it is pure logic with no JSX, reused by more than one page/component.
|
|
10
|
+
*
|
|
11
|
+
* Every function accepts an optional `MediaDevicesLike` so a test can inject a fake without a real browser; the
|
|
12
|
+
* real `navigator.mediaDevices` is used by default, resolved lazily inside each function (never at module scope)
|
|
13
|
+
* so importing this module is safe during this plugin's page SSR, where no browser globals exist at all.
|
|
14
|
+
*
|
|
15
|
+
* Nothing here ever throws: every browser-API call is wrapped in `classifyMediaError()` and returned as a
|
|
16
|
+
* discriminated `{ ok: false, error }` result, so a caller (a React component) never needs a try/catch of its own.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** The subset of `MediaDevices` this module calls - what a test's fake implements. */
|
|
20
|
+
export interface MediaDevicesLike {
|
|
21
|
+
enumerateDevices?: () => Promise<MediaDeviceInfo[]>;
|
|
22
|
+
getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;
|
|
23
|
+
getDisplayMedia?: (constraints?: DisplayMediaStreamOptions) => Promise<MediaStream>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type MediaAccessErrorKind = "unsupported" | "permission-denied" | "not-found" | "unknown";
|
|
27
|
+
|
|
28
|
+
export interface MediaAccessError {
|
|
29
|
+
kind: MediaAccessErrorKind;
|
|
30
|
+
/** Already a complete, user-facing sentence - a caller shows this directly, no further mapping needed. */
|
|
31
|
+
message: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type MediaResult<T> = { ok: true; value: T } | { ok: false; error: MediaAccessError };
|
|
35
|
+
|
|
36
|
+
/** `navigator.mediaDevices`, or `undefined` where there is none (SSR, a non-HTTPS/insecure context in some
|
|
37
|
+
* browsers, or a very old browser) - resolved lazily so this is safe to call from module code executed under SSR,
|
|
38
|
+
* where `navigator` itself does not exist. */
|
|
39
|
+
export function defaultMediaDevices(): MediaDevicesLike | undefined {
|
|
40
|
+
return typeof navigator === "undefined" ? undefined : (navigator.mediaDevices);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Whether `devices.getUserMedia` is actually callable - the one capability every caller here needs at minimum. */
|
|
44
|
+
export function isMediaDevicesSupported(devices: MediaDevicesLike | undefined = defaultMediaDevices()): boolean {
|
|
45
|
+
return typeof devices?.getUserMedia === "function";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const UNSUPPORTED_ERROR: MediaAccessError = {
|
|
49
|
+
kind: "unsupported",
|
|
50
|
+
message: "This browser (or this page's connection) doesn't support camera/microphone access. Try a modern browser over HTTPS.",
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** Maps a `getUserMedia()`/`getDisplayMedia()`/`enumerateDevices()` rejection to a friendly, already-complete
|
|
54
|
+
* message - the handful of `DOMException` names a browser actually raises for these calls, matched by name rather
|
|
55
|
+
* than `instanceof DOMException` (a test's fake rejection need not be a real `DOMException`). */
|
|
56
|
+
export function classifyMediaError(err: unknown): MediaAccessError {
|
|
57
|
+
const name: string = err instanceof Error ? err.name : "";
|
|
58
|
+
switch (name) {
|
|
59
|
+
case "NotAllowedError":
|
|
60
|
+
case "SecurityError":
|
|
61
|
+
return { kind: "permission-denied", message: "Camera/microphone access was denied. Allow access in your browser and try again." };
|
|
62
|
+
case "NotFoundError":
|
|
63
|
+
case "OverconstrainedError":
|
|
64
|
+
return { kind: "not-found", message: "No camera or microphone was found on this device." };
|
|
65
|
+
default:
|
|
66
|
+
return { kind: "unknown", message: "Could not access your camera or microphone. Please try again." };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface DeviceLists {
|
|
71
|
+
cameras: MediaDeviceInfo[];
|
|
72
|
+
microphones: MediaDeviceInfo[];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Lists the available camera/microphone devices. Labels are only populated once permission has been granted (a
|
|
77
|
+
* browser rule, not something this function can work around) - a caller wanting labeled devices should call
|
|
78
|
+
* `requestUserMedia()` first, then this again.
|
|
79
|
+
*/
|
|
80
|
+
export async function listDevices(devices: MediaDevicesLike | undefined = defaultMediaDevices()): Promise<MediaResult<DeviceLists>> {
|
|
81
|
+
if (!devices?.enumerateDevices) {
|
|
82
|
+
return { ok: false, error: UNSUPPORTED_ERROR };
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const all: MediaDeviceInfo[] = await devices.enumerateDevices();
|
|
86
|
+
return {
|
|
87
|
+
ok: true,
|
|
88
|
+
value: {
|
|
89
|
+
cameras: all.filter((d) => d.kind === "videoinput"),
|
|
90
|
+
microphones: all.filter((d) => d.kind === "audioinput"),
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
} catch (err) {
|
|
94
|
+
return { ok: false, error: classifyMediaError(err) };
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** Requests camera/microphone access. `constraints` lets the caller ask for a specific `deviceId` (device
|
|
99
|
+
* switching) or disable a track kind entirely (e.g. `{ video: false, audio: true }` for a mic-only preview). */
|
|
100
|
+
export async function requestUserMedia(
|
|
101
|
+
constraints: MediaStreamConstraints,
|
|
102
|
+
devices: MediaDevicesLike | undefined = defaultMediaDevices(),
|
|
103
|
+
): Promise<MediaResult<MediaStream>> {
|
|
104
|
+
if (!devices?.getUserMedia) {
|
|
105
|
+
return { ok: false, error: UNSUPPORTED_ERROR };
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
return { ok: true, value: await devices.getUserMedia(constraints) };
|
|
109
|
+
} catch (err) {
|
|
110
|
+
return { ok: false, error: classifyMediaError(err) };
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Requests a screen/window/tab share via the browser's own picker. Audio is never requested (this design shares
|
|
115
|
+
* camera-equivalent video only - see this plugin's Phase 2 `.claude/NOTES.md` entry on presentation mode). */
|
|
116
|
+
export async function requestDisplayMedia(devices: MediaDevicesLike | undefined = defaultMediaDevices()): Promise<MediaResult<MediaStream>> {
|
|
117
|
+
if (!devices?.getDisplayMedia) {
|
|
118
|
+
return { ok: false, error: UNSUPPORTED_ERROR };
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
return { ok: true, value: await devices.getDisplayMedia({ video: true, audio: false }) };
|
|
122
|
+
} catch (err) {
|
|
123
|
+
return { ok: false, error: classifyMediaError(err) };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Stops every track of `stream` (releasing the camera/microphone/screen-share indicator) - tolerates `undefined`/
|
|
128
|
+
* `null` so a caller never needs its own guard. */
|
|
129
|
+
export function stopStream(stream: MediaStream | undefined | null): void {
|
|
130
|
+
stream?.getTracks().forEach((track) => track.stop());
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Enables/disables every track of `stream` matching `kind`, for the mute/camera-off toggles - tracks are kept
|
|
134
|
+
* (not stopped/removed), matching every mainstream video-call app's "mute" behavior: instant, reversible, and
|
|
135
|
+
* without re-requesting `getUserMedia()` or renegotiating the `RTCPeerConnection`. */
|
|
136
|
+
export function setTracksEnabled(stream: MediaStream | undefined | null, kind: "audio" | "video", enabled: boolean): void {
|
|
137
|
+
const tracks: MediaStreamTrack[] = kind === "audio" ? (stream?.getAudioTracks() ?? []) : (stream?.getVideoTracks() ?? []);
|
|
138
|
+
for (const track of tracks) {
|
|
139
|
+
track.enabled = enabled;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
2
|
+
// Copyright (C) 2026 Jean-Philippe Steinmetz. All rights reserved.
|
|
3
|
+
// SPDX-License-Identifier: MPL-2.0
|
|
4
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
5
|
+
/**
|
|
6
|
+
* `Web Audio API` `AnalyserNode` wiring for a per-track volume meter - the browser-glue half of active-speaker
|
|
7
|
+
* detection; `activeSpeaker.ts` holds the actual selection logic as plain, DOM-free functions over the numbers
|
|
8
|
+
* this module produces. Every browser constructor is behind an injectable factory, so a test never needs a real
|
|
9
|
+
* `AudioContext`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** The subset of `AnalyserNode` this module uses - what a test's fake implements. */
|
|
13
|
+
export interface AnalyserNodeLike {
|
|
14
|
+
fftSize: number;
|
|
15
|
+
getByteTimeDomainData(array: Uint8Array): void;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** The subset of `AudioContext` this module uses. */
|
|
19
|
+
export interface AudioContextLike {
|
|
20
|
+
createAnalyser(): AnalyserNodeLike;
|
|
21
|
+
createMediaStreamSource(stream: MediaStream): { connect(node: AnalyserNodeLike): void };
|
|
22
|
+
close(): Promise<void> | void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type AudioContextFactory = () => AudioContextLike;
|
|
26
|
+
|
|
27
|
+
/** The real `AudioContext`/`webkitAudioContext` constructor, or `undefined` where there is none (SSR, a browser
|
|
28
|
+
* with no Web Audio support). Resolved lazily - never at module scope - so importing this module is SSR-safe. */
|
|
29
|
+
export function defaultAudioContextFactory(): AudioContextFactory | undefined {
|
|
30
|
+
if (typeof window === "undefined") {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
const Ctor: (new () => AudioContextLike) | undefined =
|
|
34
|
+
(window as unknown as { AudioContext?: new () => AudioContextLike }).AudioContext ??
|
|
35
|
+
(window as unknown as { webkitAudioContext?: new () => AudioContextLike }).webkitAudioContext;
|
|
36
|
+
return Ctor ? () => new Ctor() : undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface LevelMeterHandle {
|
|
40
|
+
/** Stops polling and releases the `AudioContext` - idempotent. */
|
|
41
|
+
stop(): void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** How often the meter samples and reports a level, in milliseconds. Fast enough to feel responsive for
|
|
45
|
+
* active-speaker switching without generating excessive React state churn. */
|
|
46
|
+
export const DEFAULT_LEVEL_METER_INTERVAL_MS = 200;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Starts reporting `stream`'s audio level (0-100, a simple mean-absolute-deviation-from-silence over each sample
|
|
50
|
+
* window - not true RMS/dBFS, deliberately: this is a threshold heuristic, not a metering instrument) to `onLevel`
|
|
51
|
+
* every `intervalMs`. Returns `undefined` (nothing started) when there is no usable `AudioContext` or `stream` has
|
|
52
|
+
* no audio track to measure - a caller treats that the same as "can't tell, don't auto-switch on this stream".
|
|
53
|
+
*/
|
|
54
|
+
export function startLevelMeter(
|
|
55
|
+
stream: MediaStream,
|
|
56
|
+
onLevel: (level: number) => void,
|
|
57
|
+
options: { factory?: AudioContextFactory; intervalMs?: number } = {},
|
|
58
|
+
): LevelMeterHandle | undefined {
|
|
59
|
+
const factory: AudioContextFactory | undefined = options.factory ?? defaultAudioContextFactory();
|
|
60
|
+
if (!factory || stream.getAudioTracks().length === 0) {
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
const context: AudioContextLike = factory();
|
|
64
|
+
const analyser: AnalyserNodeLike = context.createAnalyser();
|
|
65
|
+
analyser.fftSize = 512;
|
|
66
|
+
context.createMediaStreamSource(stream).connect(analyser);
|
|
67
|
+
const buffer = new Uint8Array(analyser.fftSize);
|
|
68
|
+
|
|
69
|
+
const timer: ReturnType<typeof setInterval> = setInterval(() => {
|
|
70
|
+
analyser.getByteTimeDomainData(buffer);
|
|
71
|
+
let sum = 0;
|
|
72
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
73
|
+
sum += Math.abs(buffer[i] - 128);
|
|
74
|
+
}
|
|
75
|
+
// The maximum possible mean deviation from the 128 midpoint is 128 (a square wave at full scale) -
|
|
76
|
+
// normalized to a friendlier 0-100 range, matching `activeSpeaker.ts`'s `DEFAULT_ACTIVE_SPEAKER_THRESHOLD`.
|
|
77
|
+
onLevel(Math.min(100, (sum / buffer.length / 128) * 100));
|
|
78
|
+
}, options.intervalMs ?? DEFAULT_LEVEL_METER_INTERVAL_MS);
|
|
79
|
+
|
|
80
|
+
let stopped = false;
|
|
81
|
+
return {
|
|
82
|
+
stop: () => {
|
|
83
|
+
if (stopped) {
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
stopped = true;
|
|
87
|
+
clearInterval(timer);
|
|
88
|
+
void context.close();
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
2
|
+
// Copyright (C) 2026 Jean-Philippe Steinmetz. All rights reserved.
|
|
3
|
+
// SPDX-License-Identifier: MPL-2.0
|
|
4
|
+
///////////////////////////////////////////////////////////////////////////////
|
|
5
|
+
/**
|
|
6
|
+
* A standalone `SignalingChannel` (`../webrtc/types.js`) over `@rapidrest/service-core`'s `/push` WebSocket -
|
|
7
|
+
* built from scratch rather than reusing `@rapidmx/react-shared`'s `PushClient`/`getPushClient()`.
|
|
8
|
+
*
|
|
9
|
+
* ## Why not `PushClient`
|
|
10
|
+
*
|
|
11
|
+
* `PushClient` was investigated first, as this plugin's Phase 2 `.claude/NOTES.md` entry required. Its `connect()`
|
|
12
|
+
* opens a bare `new WebSocket(url)` and relies entirely on the browser automatically attaching this deployment's
|
|
13
|
+
* `jwt` `HttpOnly` cookie to the upgrade request - it never sends a token of its own (see its own doc comment:
|
|
14
|
+
* "a script can't read that cookie, so there is no token to send"). That fits the webmail tab's own authenticated
|
|
15
|
+
* session perfectly, but this plugin's anonymous guest has no such cookie at all - only the bearer `token`
|
|
16
|
+
* `BaseVideoMeetingRoute.join()` minted, handed to this client explicitly. `PushClient`'s API has no parameter
|
|
17
|
+
* anywhere to supply that token, and its shared-singleton design (`getPushClient()`, one client per tab) is itself
|
|
18
|
+
* the wrong shape here too: a guest's signaling identity must never be confused with (or silently share a socket
|
|
19
|
+
* with) whatever webmail session, if any, happens to already be open in the same browser. So this module
|
|
20
|
+
* implements the same wire protocol independently instead - see `../../.claude/NOTES.md` and
|
|
21
|
+
* `BasePushRoute`/`JWTStrategy` (`@rapidrest/service-core`) for the protocol this matches:
|
|
22
|
+
*
|
|
23
|
+
* - `wss://<origin>/push` - authenticated at the WebSocket upgrade. A real browser `WebSocket` cannot attach a
|
|
24
|
+
* custom `Authorization` header to that upgrade request at all (a WHATWG API limitation, not something any
|
|
25
|
+
* client-side code can work around) - `JWTStrategy.getAuthToken()`'s only other source is the same `jwt` cookie
|
|
26
|
+
* `PushClient` already relies on. When `token` is supplied (the common anonymous/guest case -
|
|
27
|
+
* `VideoMeetingJoinResult.authenticated` is `false`), this client sets that cookie itself, to `token`, immediately
|
|
28
|
+
* before connecting (`applyAuthCookie()`). When `token` is omitted (the caller already authenticated as a real
|
|
29
|
+
* RapidMX identity in `join()` - `authenticated: true` - see the FIXED LIMITATION below), this client writes no
|
|
30
|
+
* cookie at all and simply lets the browser attach whatever real `jwt` session cookie already exists for this
|
|
31
|
+
* origin, exactly as `PushClient` does for an ordinary webmail session.
|
|
32
|
+
* - Right after connecting, the server sends `{ id: 0, type: "SUBSCRIBED", data: [...] }` (channels the socket
|
|
33
|
+
* already holds - the caller's own uid channel, never this meeting's). `connect()` then explicitly `SUBSCRIBE`s to
|
|
34
|
+
* the one meeting channel and waits for the matching `{ id, type: "SUBSCRIBED", data }` reply, resolving once
|
|
35
|
+
* `channel` is actually in that reply's `data` (rejecting otherwise - an unauthorized/expired token, or the
|
|
36
|
+
* meeting's ACL grant somehow missing).
|
|
37
|
+
* - Publishing (`send()`) is **not** a WebSocket message at all - `BasePushRoute.send()` is `POST /push/:id`, a
|
|
38
|
+
* perfectly ordinary authenticated HTTP endpoint. When `token` is supplied it's sent there as a normal
|
|
39
|
+
* `Authorization: Bearer` header (no browser limitation applies to a plain `fetch()`); when it's omitted, the
|
|
40
|
+
* request carries no `Authorization` header at all and instead relies on `fetch()`'s own default same-origin
|
|
41
|
+
* credentials mode, which already attaches the browser's real `jwt` cookie to a same-origin request with zero
|
|
42
|
+
* extra code - `JWTStrategy.getAuthToken()`'s cookie fallback authenticates it exactly as it would any other
|
|
43
|
+
* same-origin authenticated call. Fire-and-forget either way, matching every other push publish in this codebase -
|
|
44
|
+
* a failed send is logged, never thrown, since a caller (`MeshConnectionManager`) has no meaningful per-message
|
|
45
|
+
* retry of its own.
|
|
46
|
+
* - An incoming meeting message arrives wrapped `{ type: "MESSAGE", channel, data: <the posted body> }` - this
|
|
47
|
+
* client unwraps it and delivers `data` (expected to be a `SignalMessage`) to `onMessage()` listeners.
|
|
48
|
+
*
|
|
49
|
+
* ## FIXED: the browser-session-collision limitation this module used to carry
|
|
50
|
+
*
|
|
51
|
+
* Phase 2 originally always wrote the guest `token` as the `jwt` cookie before connecting, unconditionally. If the
|
|
52
|
+
* visiting browser already held a *real*, `HttpOnly` `jwt` session cookie for this exact origin (a logged-in
|
|
53
|
+
* RapidMX user, e.g. with webmail open), that write was silently blocked by the browser's own "script cannot
|
|
54
|
+
* override an `HttpOnly` cookie of the same name" protection - the WebSocket then authenticated as that real
|
|
55
|
+
* session instead of the intended guest identity, and since the meeting's `AccessControlList` grant only named the
|
|
56
|
+
* guest uid, the real session's `SUBSCRIBE` was simply refused. Net effect: a logged-in user could never actually
|
|
57
|
+
* join a call at all (safe - never a cross-identity leak - but broken).
|
|
58
|
+
*
|
|
59
|
+
* The fix is in `BaseVideoMeetingRoute.join()` (backend): when the caller already presents a valid session for a
|
|
60
|
+
* real RapidMX identity, it grants *that* identity's own uid on the meeting's channel directly and returns
|
|
61
|
+
* `authenticated: true` with no guest `token` at all - see `VideoMeetingJoinResult`'s doc comment. This module's
|
|
62
|
+
* own half of the fix is simply to stop writing a cookie (and stop sending a bearer header) whenever `token` is
|
|
63
|
+
* absent, as described above - the browser's real cookie was always going to win that write anyway, so the
|
|
64
|
+
* correct behavior is to not fight it and let it authenticate normally instead.
|
|
65
|
+
*/
|
|
66
|
+
import { apiOrigin } from "@rapidmx/react-shared/util/api.js";
|
|
67
|
+
import { pushUrl } from "@rapidmx/react-shared/mail/pushClient.js";
|
|
68
|
+
import type { SignalMessage, SignalingChannel } from "../webrtc/types.js";
|
|
69
|
+
|
|
70
|
+
/** The subset of the browser's `WebSocket` this client uses - matches `PushClient`'s own identical seam, so a
|
|
71
|
+
* test's fake can be a plain object with no real socket behind it. */
|
|
72
|
+
export interface PushSocket {
|
|
73
|
+
readyState: number;
|
|
74
|
+
send(data: string): void;
|
|
75
|
+
close(code?: number, reason?: string): void;
|
|
76
|
+
onopen: ((event: unknown) => void) | null;
|
|
77
|
+
onmessage: ((event: { data: unknown }) => void) | null;
|
|
78
|
+
onclose: ((event: unknown) => void) | null;
|
|
79
|
+
onerror: ((event: unknown) => void) | null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export type PushSocketFactory = (url: string) => PushSocket;
|
|
83
|
+
|
|
84
|
+
const SOCKET_OPEN = 1;
|
|
85
|
+
|
|
86
|
+
function defaultSocketFactory(): PushSocketFactory | undefined {
|
|
87
|
+
return typeof WebSocket === "undefined" ? undefined : (url) => new WebSocket(url) as unknown as PushSocket;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The cookie name `JWTStrategyOptions.cookieName` defaults to (and this deployment always uses - see
|
|
91
|
+
* `BaseVideoMeetingRoute`'s guest JWT doc comment, signed with the same `auth` config every other token is). */
|
|
92
|
+
const AUTH_COOKIE_NAME = "jwt";
|
|
93
|
+
|
|
94
|
+
export interface GuestSignalingClientOptions {
|
|
95
|
+
/** The meeting's own uid - both its push channel and the `POST /push/:id` target. */
|
|
96
|
+
channel: string;
|
|
97
|
+
/** The guest JWT from `VideoMeetingJoinResult.token`. Omitted when the caller already authenticated as a real
|
|
98
|
+
* RapidMX identity (`VideoMeetingJoinResult.authenticated`) - this client then writes no cookie and sends no
|
|
99
|
+
* `Authorization` header at all, relying entirely on the browser's own already-existing `jwt` session cookie
|
|
100
|
+
* for both the WebSocket upgrade and each `POST /push/:id` publish - see this module's doc comment. */
|
|
101
|
+
token?: string;
|
|
102
|
+
/** Defaults to `@rapidmx/react-shared`'s `pushUrl()` - the exact URL `PushClient` itself connects to. */
|
|
103
|
+
url?: () => string | undefined;
|
|
104
|
+
createSocket?: PushSocketFactory;
|
|
105
|
+
fetchImpl?: typeof fetch;
|
|
106
|
+
/** Overrides `document`, for a test - see `applyAuthCookie()`. */
|
|
107
|
+
documentRef?: Pick<Document, "cookie"> & { location?: Pick<Location, "protocol"> };
|
|
108
|
+
random?: () => number;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The first reconnect waits about this long, doubling on each further failure, matching `PushClient`'s own
|
|
112
|
+
* constants (kept independent rather than imported, since this module deliberately doesn't depend on
|
|
113
|
+
* `pushClient.ts` beyond its `pushUrl()` helper - see this module's doc comment on why it isn't `PushClient` itself). */
|
|
114
|
+
export const SIGNALING_BACKOFF_BASE_MS = 1_000;
|
|
115
|
+
export const SIGNALING_BACKOFF_MAX_MS = 30_000;
|
|
116
|
+
|
|
117
|
+
export class GuestSignalingClient implements SignalingChannel {
|
|
118
|
+
private socket: PushSocket | undefined;
|
|
119
|
+
private closed = false;
|
|
120
|
+
private nextRequestId = 1;
|
|
121
|
+
private attempt = 0;
|
|
122
|
+
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
123
|
+
private cookieApplied = false;
|
|
124
|
+
private readonly listeners = new Set<(message: SignalMessage) => void>();
|
|
125
|
+
private pendingConnect: { resolve: () => void; reject: (err: Error) => void } | undefined;
|
|
126
|
+
|
|
127
|
+
constructor(private readonly options: GuestSignalingClientOptions) {}
|
|
128
|
+
|
|
129
|
+
/** Connects, authenticates (see this module's doc comment) and subscribes to the meeting's own channel.
|
|
130
|
+
* Resolves once genuinely ready to send/receive; rejects if the channel is refused (an invalid/expired token,
|
|
131
|
+
* or - now fixed rather than merely possible, see the FIXED LIMITATION section above - a stale grant) or there
|
|
132
|
+
* is nothing to connect with at all (no `WebSocket`, e.g. a non-HTTPS context in some browsers - the lobby's
|
|
133
|
+
* own device-support checks already cover the more common case of no `mediaDevices`, but this is an
|
|
134
|
+
* independent capability). Calling this a second time on an already-closed client rejects immediately. */
|
|
135
|
+
connect(): Promise<void> {
|
|
136
|
+
if (this.closed) {
|
|
137
|
+
return Promise.reject(new Error("This signaling client has already been closed."));
|
|
138
|
+
}
|
|
139
|
+
return new Promise<void>((resolve, reject) => {
|
|
140
|
+
this.pendingConnect = { resolve, reject };
|
|
141
|
+
this.openSocket();
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Closes the socket, stops reconnecting and clears the guest auth cookie this client applied (see
|
|
146
|
+
* `applyAuthCookie()`) - idempotent. */
|
|
147
|
+
close(): void {
|
|
148
|
+
if (this.closed) {
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
this.closed = true;
|
|
152
|
+
clearTimeout(this.timer);
|
|
153
|
+
this.timer = undefined;
|
|
154
|
+
const socket = this.socket;
|
|
155
|
+
this.socket = undefined;
|
|
156
|
+
if (socket) {
|
|
157
|
+
socket.onopen = socket.onmessage = socket.onclose = socket.onerror = null;
|
|
158
|
+
try {
|
|
159
|
+
socket.close(1000, "closing");
|
|
160
|
+
} catch {
|
|
161
|
+
// Already gone.
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
this.clearAuthCookie();
|
|
165
|
+
this.listeners.clear();
|
|
166
|
+
this.pendingConnect?.reject(new Error("Closed before the signaling channel connected."));
|
|
167
|
+
this.pendingConnect = undefined;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
onMessage(handler: (message: SignalMessage) => void): () => void {
|
|
171
|
+
this.listeners.add(handler);
|
|
172
|
+
return () => this.listeners.delete(handler);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Publishes over `POST /push/:id`, with `token` as a bearer credential when present - see this module's doc
|
|
176
|
+
* comment on why this, unlike subscribing, needs no cookie workaround at all, and on the omitted-`token` case
|
|
177
|
+
* (an already-authenticated real caller), which relies on the browser's own real `jwt` cookie instead.
|
|
178
|
+
* Fire-and-forget: a failure is swallowed (there is nothing a signaling message's own sender can usefully do
|
|
179
|
+
* about a dropped publish beyond what the mesh's own `hello` re-announcement/renegotiation already tolerates -
|
|
180
|
+
* see `MeshConnectionManager`'s doc comment on fire-and-forget delivery). */
|
|
181
|
+
send(message: SignalMessage): void {
|
|
182
|
+
const fetchImpl = this.options.fetchImpl ?? (typeof fetch === "undefined" ? undefined : fetch);
|
|
183
|
+
if (!fetchImpl) {
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const origin = apiOrigin() || (typeof window !== "undefined" ? window.location.origin : "");
|
|
187
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
188
|
+
if (this.options.token) {
|
|
189
|
+
headers.Authorization = `Bearer ${this.options.token}`;
|
|
190
|
+
}
|
|
191
|
+
void fetchImpl(`${origin}/push/${encodeURIComponent(this.options.channel)}`, {
|
|
192
|
+
method: "POST",
|
|
193
|
+
headers,
|
|
194
|
+
body: JSON.stringify(message),
|
|
195
|
+
}).catch(() => {
|
|
196
|
+
// Best-effort - see this method's doc comment.
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
private openSocket(): void {
|
|
201
|
+
const url = (this.options.url ?? pushUrl)();
|
|
202
|
+
const createSocket = this.options.createSocket ?? defaultSocketFactory();
|
|
203
|
+
if (!url || !createSocket) {
|
|
204
|
+
this.failConnect(new Error("This browser (or this page's connection) doesn't support the signaling channel."));
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
this.applyAuthCookie();
|
|
208
|
+
let socket: PushSocket;
|
|
209
|
+
try {
|
|
210
|
+
socket = createSocket(url);
|
|
211
|
+
} catch {
|
|
212
|
+
this.scheduleReconnect();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
this.socket = socket;
|
|
216
|
+
socket.onmessage = (event) => this.handleFrame(event.data);
|
|
217
|
+
socket.onclose = () => {
|
|
218
|
+
// Guards against a stale socket's belated close event: `close()` always sets `this.socket = undefined`
|
|
219
|
+
// synchronously (before this handler could possibly be detached asynchronously), so once this client
|
|
220
|
+
// is closed, `this.socket` can never equal `socket` again and this always returns here first.
|
|
221
|
+
if (this.socket !== socket) {
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
this.socket = undefined;
|
|
225
|
+
this.scheduleReconnect();
|
|
226
|
+
};
|
|
227
|
+
socket.onerror = () => undefined;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
private scheduleReconnect(): void {
|
|
231
|
+
const ceiling = Math.min(SIGNALING_BACKOFF_MAX_MS, SIGNALING_BACKOFF_BASE_MS * 2 ** Math.min(this.attempt, 10));
|
|
232
|
+
const delay = ceiling / 2 + ((this.options.random ?? Math.random)() * ceiling) / 2;
|
|
233
|
+
this.attempt += 1;
|
|
234
|
+
this.timer = setTimeout(() => {
|
|
235
|
+
this.timer = undefined;
|
|
236
|
+
this.openSocket();
|
|
237
|
+
}, delay);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private handleFrame(raw: unknown): void {
|
|
241
|
+
if (typeof raw !== "string") {
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
let frame: Record<string, unknown>;
|
|
245
|
+
try {
|
|
246
|
+
const parsed: unknown = JSON.parse(raw);
|
|
247
|
+
if (!parsed || typeof parsed !== "object") {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
frame = parsed as Record<string, unknown>;
|
|
251
|
+
} catch {
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (frame.type === "SUBSCRIBED") {
|
|
255
|
+
this.handleSubscribed(frame);
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
if (frame.type === "MESSAGE" && frame.channel === this.options.channel) {
|
|
259
|
+
const data = frame.data;
|
|
260
|
+
if (data && typeof data === "object" && (data as { type?: unknown }).type === "video-meeting-signal") {
|
|
261
|
+
this.emit(data as SignalMessage);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
private handleSubscribed(frame: Record<string, unknown>): void {
|
|
267
|
+
const channels = Array.isArray(frame.data) ? frame.data.filter((c): c is string => typeof c === "string") : [];
|
|
268
|
+
if (frame.id === 0) {
|
|
269
|
+
// The connect-time greeting: now actually subscribe to the one channel this client cares about.
|
|
270
|
+
const id = this.nextRequestId++;
|
|
271
|
+
this.send0({ id, type: "SUBSCRIBE", data: [this.options.channel] });
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (channels.includes(this.options.channel)) {
|
|
275
|
+
this.attempt = 0;
|
|
276
|
+
this.pendingConnect?.resolve();
|
|
277
|
+
this.pendingConnect = undefined;
|
|
278
|
+
} else if (this.pendingConnect) {
|
|
279
|
+
this.failConnect(new Error("This meeting's signaling channel refused the subscription."));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
private send0(message: object): void {
|
|
284
|
+
const socket = this.socket;
|
|
285
|
+
if (!socket || socket.readyState !== SOCKET_OPEN) {
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
try {
|
|
289
|
+
socket.send(JSON.stringify(message));
|
|
290
|
+
} catch {
|
|
291
|
+
// The close that follows a dead socket reconnects and re-subscribes.
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
private failConnect(err: Error): void {
|
|
296
|
+
this.pendingConnect?.reject(err);
|
|
297
|
+
this.pendingConnect = undefined;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private emit(message: SignalMessage): void {
|
|
301
|
+
for (const listener of [...this.listeners]) {
|
|
302
|
+
listener(message);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Sets the `jwt` cookie to `token` for this origin, so the browser attaches it (as `PushClient`'s own doc
|
|
307
|
+
* comment describes for a real session) to the WebSocket upgrade this client is about to open - see this
|
|
308
|
+
* module's doc comment for the full reasoning. A no-op when `token` is omitted (the caller already
|
|
309
|
+
* authenticated as a real RapidMX identity - see the FIXED LIMITATION section above): there is then no guest
|
|
310
|
+
* token to apply, and writing nothing leaves the browser's own real `jwt` session cookie, whatever it is,
|
|
311
|
+
* untouched and free to authenticate the connection normally. */
|
|
312
|
+
private applyAuthCookie(): void {
|
|
313
|
+
if (!this.options.token) {
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
const doc = this.options.documentRef ?? (typeof document === "undefined" ? undefined : document);
|
|
317
|
+
if (!doc) {
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
this.cookieApplied = true;
|
|
321
|
+
const secure = (doc.location ?? (typeof location === "undefined" ? undefined : location))?.protocol === "https:" ? "; Secure" : "";
|
|
322
|
+
doc.cookie = `${AUTH_COOKIE_NAME}=${encodeURIComponent(this.options.token)}; path=/; SameSite=Lax${secure}`;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Expires the cookie `applyAuthCookie()` set - a no-op if that write was itself silently blocked, or never
|
|
326
|
+
* attempted at all because `token` was omitted (see `applyAuthCookie()`'s own doc comment), either way leaving
|
|
327
|
+
* whatever real session cookie was already there untouched. `cookieApplied` is only ever set once
|
|
328
|
+
* `applyAuthCookie()` has already confirmed both a `token` to write and a `doc` to write it to, and neither
|
|
329
|
+
* `this.options.token`, `this.options.documentRef` nor the real global `document` can change mid-call, so
|
|
330
|
+
* resolving it here is guaranteed to succeed too - no second `!doc` guard needed. */
|
|
331
|
+
private clearAuthCookie(): void {
|
|
332
|
+
if (!this.cookieApplied) {
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const doc = this.options.documentRef ?? (typeof document === "undefined" ? undefined : document);
|
|
336
|
+
doc!.cookie = `${AUTH_COOKIE_NAME}=; path=/; Max-Age=0`;
|
|
337
|
+
}
|
|
338
|
+
}
|