electron-cast 0.2.0 → 0.3.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.
@@ -1,4 +1,5 @@
1
1
  import { installChromeCast } from "../polyfill/install.ts";
2
+ import { installPresentationStandIn } from "../polyfill/presentation-standin.ts";
2
3
  import type { BridgeEvent, BridgeMethod, BridgeResult } from "../polyfill/bridge-types.ts";
3
4
 
4
5
  /** The subset of an Electron `contextBridge` the bridge needs. */
@@ -10,6 +11,8 @@ export interface ContextBridgeLike {
10
11
  export interface IpcRendererLike {
11
12
  invoke(channel: string, ...args: unknown[]): Promise<unknown>;
12
13
  on(channel: string, listener: (event: unknown, ...args: any[]) => void): unknown;
14
+ /** Needed in presentation mode (the default). */
15
+ send?(channel: string, ...args: unknown[]): void;
13
16
  }
14
17
  /** Dependencies of {@link installCastBridge}; the Electron objects are passed in, never imported. */
15
18
  export interface CastBridgeOptions {
@@ -17,15 +20,31 @@ export interface CastBridgeOptions {
17
20
  ipcRenderer: IpcRendererLike;
18
21
  channel?: string; // default "electron-cast"
19
22
  bridgeKey?: string; // default "__electronCastBridge"
23
+ /**
24
+ * "presentation" (default) installs a stand-in Presentation API, so the page's own copy of Google's Cast SDK
25
+ * loads and runs unmodified. "chromecast" installs electron-cast's own chrome.cast instead and blocks Google's
26
+ * loader scripts.
27
+ */
28
+ mode?: "chromecast" | "presentation";
29
+ presentationBridgeKey?: string; // default "__electronCastPresentationBridge"
20
30
  }
21
31
 
22
32
  function describe(err: unknown): string {
23
33
  return err instanceof Error ? err.message : String(err);
24
34
  }
25
35
 
26
- /** Call from a preload script: exposes the bridge and installs chrome.cast in the page before its scripts run. */
36
+ /**
37
+ * Call from a preload script. Exposes the bridge and, before the page's scripts run, installs the Presentation API
38
+ * stand-in (default) or, with `mode: "chromecast"`, electron-cast's own chrome.cast.
39
+ */
27
40
  export function installCastBridge(options: CastBridgeOptions): void {
28
41
  const channel = options.channel ?? "electron-cast";
42
+ const mode = options.mode ?? "presentation";
43
+ if (mode !== "presentation" && mode !== "chromecast") throw new TypeError(`unknown mode: ${String(mode)}`);
44
+ if (mode === "presentation") {
45
+ installPresentationBridge(options, channel);
46
+ return;
47
+ }
29
48
  const bridgeKey = options.bridgeKey ?? "__electronCastBridge";
30
49
  const bridge = {
31
50
  /** Forward one bridge call to the main process; never rejects. */
@@ -55,3 +74,42 @@ export function installCastBridge(options: CastBridgeOptions): void {
55
74
  options.contextBridge.exposeInMainWorld(bridgeKey, bridge);
56
75
  options.contextBridge.executeInMainWorld({ func: installChromeCast, args: [bridgeKey] });
57
76
  }
77
+
78
+ /** Presentation mode: expose the stand-in's bridge and install the stand-in; chrome.cast is left to Google's SDK. */
79
+ function installPresentationBridge(options: CastBridgeOptions, channel: string): void {
80
+ const key = options.presentationBridgeKey ?? "__electronCastPresentationBridge";
81
+ const ipc = options.ipcRenderer;
82
+ if (typeof ipc.send !== "function") throw new TypeError("presentation mode needs ipcRenderer.send");
83
+ const send = ipc.send.bind(ipc);
84
+ const bridge = {
85
+ /** Forward one call to the main process; never rejects. */
86
+ call(method: string, params: unknown): Promise<unknown> {
87
+ let invoked: Promise<unknown>;
88
+ try {
89
+ invoked = ipc.invoke(`${channel}:presentation`, method, params);
90
+ } catch (err) {
91
+ invoked = Promise.reject(err);
92
+ }
93
+ return invoked.then(
94
+ (result) => result,
95
+ (err: unknown) => ({ ok: false, code: "OperationError", description: describe(err) }),
96
+ );
97
+ },
98
+ /** Page -> main: one message on an open connection; the reply comes back in-band. */
99
+ send(connectionId: string, data: string): void {
100
+ send(`${channel}:presentation:send`, connectionId, data);
101
+ },
102
+ /** Relay `<channel>:presentation:event` payloads to the page, dropping the IPC event object. */
103
+ onEvent(listener: (event: unknown) => void): void {
104
+ ipc.on(`${channel}:presentation:event`, (_event, payload) => {
105
+ try {
106
+ listener(payload);
107
+ } catch (err) {
108
+ console.error(err);
109
+ }
110
+ });
111
+ },
112
+ };
113
+ options.contextBridge.exposeInMainWorld(key, bridge);
114
+ options.contextBridge.executeInMainWorld({ func: installPresentationStandIn, args: [key] });
115
+ }
@@ -0,0 +1,311 @@
1
+ // Codec between Chromium's private Cast "router message" envelope (what Google's clank.js sender speaks over a
2
+ // PresentationConnection) and electron-cast's snapshot types. Pure module: no Electron imports.
3
+ import { createHash } from "node:crypto";
4
+ import type { ReceiverSnapshot, SessionSnapshot } from "../polyfill/bridge-types.ts";
5
+
6
+ /** The Cast media namespace; the only reserved namespace kept by {@link filterNamespaces}. */
7
+ export const MEDIA_NAMESPACE = "urn:x-cast:com.google.cast.media";
8
+
9
+ /** The fields parsed out of a presentation request URL. */
10
+ export interface PresentationUrl {
11
+ appId: string;
12
+ capabilities: string[];
13
+ clientId: string | null;
14
+ autoJoinPolicy: string;
15
+ defaultActionPolicy: string;
16
+ launchTimeout: number | null;
17
+ }
18
+
19
+ /** A validated inbound router message, with `timeoutMillis` dropped and object messages null-stripped. */
20
+ export interface ParsedEnvelope {
21
+ type: string;
22
+ message: unknown;
23
+ sequenceNumber?: number;
24
+ clientId: string;
25
+ }
26
+
27
+ const APP_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
28
+
29
+ /** Splits `<appId>(cap,cap)` into its parts; no suffix means no capabilities. */
30
+ function splitAppId(raw: string): { appId: string; capabilities: string[] } {
31
+ const open = raw.indexOf("(");
32
+ if (open === -1 || !raw.endsWith(")")) return { appId: raw, capabilities: [] };
33
+ return { appId: raw.slice(0, open), capabilities: raw.slice(open + 1, -1).split(",").filter((c) => c !== "") };
34
+ }
35
+
36
+ /** A positive integer millisecond count, or null for anything else. */
37
+ function parseLaunchTimeout(raw: string | null): number | null {
38
+ if (raw === null || !/^\d+$/.test(raw)) return null;
39
+ const n = Number(raw);
40
+ return Number.isInteger(n) && n > 0 ? n : null;
41
+ }
42
+
43
+ /**
44
+ * Parses a presentation request URL (the legacy `https://google.com/cast#__castAppId__=...` form or
45
+ * `cast:<appId>?...`) into its launch fields, or null for anything that is not one of those forms.
46
+ */
47
+ export function parsePresentationUrl(url: string): PresentationUrl | null {
48
+ if (typeof url !== "string" || url.length === 0 || url.length > 4096) return null;
49
+ const legacyPrefix = "https://google.com/cast#";
50
+ if (url.startsWith(legacyPrefix)) {
51
+ let appId: string | null = null;
52
+ let capabilities: string[] = [];
53
+ let clientId: string | null = null;
54
+ let autoJoinPolicy = "tab_and_origin_scoped";
55
+ let defaultActionPolicy = "create_session";
56
+ let launchTimeout: number | null = null;
57
+ for (const part of url.slice(legacyPrefix.length).split("/")) {
58
+ const eq = part.indexOf("=");
59
+ const key = eq === -1 ? part : part.slice(0, eq);
60
+ const value = eq === -1 ? "" : part.slice(eq + 1);
61
+ switch (key) {
62
+ case "__castAppId__": {
63
+ const split = splitAppId(value);
64
+ appId = split.appId;
65
+ capabilities = split.capabilities;
66
+ break;
67
+ }
68
+ case "__castClientId__":
69
+ clientId = value === "" ? null : value;
70
+ break;
71
+ case "__castAutoJoinPolicy__":
72
+ if (value !== "") autoJoinPolicy = value;
73
+ break;
74
+ case "__castDefaultActionPolicy__":
75
+ if (value !== "") defaultActionPolicy = value;
76
+ break;
77
+ case "__castLaunchTimeout__":
78
+ launchTimeout = parseLaunchTimeout(value);
79
+ break;
80
+ case "__dialPostData__":
81
+ // Its base64 value may contain "/", which would break the split: stop parsing here.
82
+ return appId !== null && APP_ID_RE.test(appId)
83
+ ? { appId, capabilities, clientId, autoJoinPolicy, defaultActionPolicy, launchTimeout }
84
+ : null;
85
+ default:
86
+ // Unknown keys and __dialAppName__ are ignored.
87
+ break;
88
+ }
89
+ }
90
+ return appId !== null && APP_ID_RE.test(appId)
91
+ ? { appId, capabilities, clientId, autoJoinPolicy, defaultActionPolicy, launchTimeout }
92
+ : null;
93
+ }
94
+ if (url.startsWith("cast:")) {
95
+ const rest = url.slice("cast:".length);
96
+ const q = rest.indexOf("?");
97
+ const split = splitAppId(q === -1 ? rest : rest.slice(0, q));
98
+ if (!APP_ID_RE.test(split.appId)) return null;
99
+ const params = new URLSearchParams(q === -1 ? "" : rest.slice(q + 1));
100
+ const param = (k: string): string | null => {
101
+ const v = params.get(k);
102
+ return v === null || v === "" ? null : v;
103
+ };
104
+ const queryCaps = param("capabilities");
105
+ return {
106
+ appId: split.appId,
107
+ capabilities: split.capabilities.length > 0
108
+ ? split.capabilities
109
+ : queryCaps !== null ? queryCaps.split(",").filter((c) => c !== "") : [],
110
+ clientId: param("clientId"),
111
+ autoJoinPolicy: param("autoJoinPolicy") ?? "tab_and_origin_scoped",
112
+ defaultActionPolicy: param("defaultActionPolicy") ?? "create_session",
113
+ launchTimeout: parseLaunchTimeout(param("launchTimeout")),
114
+ };
115
+ }
116
+ return null;
117
+ }
118
+
119
+ /** Deep-copies a value, dropping every object property whose value is null (null array elements are kept). */
120
+ export function stripNulls(v: unknown): unknown {
121
+ if (Array.isArray(v)) return v.map((x) => stripNulls(x));
122
+ if (v !== null && typeof v === "object") {
123
+ const out: Record<string, unknown> = {};
124
+ for (const [k, val] of Object.entries(v as Record<string, unknown>)) {
125
+ if (val === null) continue;
126
+ out[k] = stripNulls(val);
127
+ }
128
+ return out;
129
+ }
130
+ return v;
131
+ }
132
+
133
+ /** Escapes the five HTML metacharacters, as Chromium's `base::EscapeForHTML` does for receiver names. */
134
+ export function escapeHtml(s: string): string {
135
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")
136
+ .replace(/"/g, "&quot;").replace(/'/g, "&#39;");
137
+ }
138
+
139
+ /** Chromium's receiver label: unpadded base64url of sha256(deviceId + per-process token). */
140
+ export function receiverLabel(deviceId: string, token: string): string {
141
+ return createHash("sha256").update(deviceId + token).digest("base64url");
142
+ }
143
+
144
+ /** Shapes a ReceiverSnapshot into the receiver object clank reads, with an escaped name and hashed label. */
145
+ export function toReceiver(r: ReceiverSnapshot, label: string) {
146
+ return {
147
+ label,
148
+ friendlyName: escapeHtml(r.friendlyName),
149
+ capabilities: r.capabilities,
150
+ volume: r.volume,
151
+ isActiveInput: r.isActiveInput ?? null,
152
+ displayStatus: null,
153
+ receiverType: "cast",
154
+ };
155
+ }
156
+
157
+ /** Reserved namespaces Chromium never advertises to senders (the media namespace is not among them). */
158
+ const RESERVED_NAMESPACES = new Set([
159
+ "urn:x-cast:com.google.cast.tp.deviceauth",
160
+ "urn:x-cast:com.google.cast.tp.heartbeat",
161
+ "urn:x-cast:com.google.cast.tp.connection",
162
+ "urn:x-cast:com.google.cast.receiver",
163
+ "urn:x-cast:com.google.cast.remoting",
164
+ "urn:x-cast:com.google.cast.webrtc",
165
+ ]);
166
+
167
+ /** Drops the reserved namespaces from a session's namespace list, keeping everything else in order. */
168
+ export function filterNamespaces(ns: { name: string }[]): { name: string }[] {
169
+ return ns.filter((n) => !RESERVED_NAMESPACES.has(n.name));
170
+ }
171
+
172
+ /** Shapes a SessionSnapshot into the new_session/update_session message clank's converter copies onto the session. */
173
+ export function toSession(s: SessionSnapshot, label: string, media?: object[]) {
174
+ const out: Record<string, unknown> = {
175
+ sessionId: s.sessionId,
176
+ appId: s.appId,
177
+ displayName: s.displayName ?? "",
178
+ appImages: s.appImages ?? [],
179
+ receiver: toReceiver(s.receiver, label),
180
+ transportId: s.transportId,
181
+ namespaces: filterNamespaces(s.namespaces),
182
+ statusText: s.statusText,
183
+ senderApps: s.senderApps ?? [],
184
+ };
185
+ if (media !== undefined) out.media = media;
186
+ return out;
187
+ }
188
+
189
+ /** The receiver's supportedMediaCommands bitmask bits, in the order clank's supportsCommand expects. */
190
+ const MEDIA_COMMAND_BITS: Array<[number, string]> = [
191
+ [1, "pause"],
192
+ [2, "seek"],
193
+ [4, "stream_volume"],
194
+ [8, "stream_mute"],
195
+ [64, "queue_next"],
196
+ [128, "queue_prev"],
197
+ ];
198
+
199
+ /** Converts a supportedMediaCommands bitmask (or passes through an array of strings) into command names. */
200
+ export function mediaCommands(v: unknown): string[] {
201
+ if (typeof v === "number" && Number.isFinite(v)) {
202
+ return MEDIA_COMMAND_BITS.filter(([bit]) => (v & bit) !== 0).map(([, name]) => name);
203
+ }
204
+ if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string");
205
+ return [];
206
+ }
207
+
208
+ /** Shallow-copies a media-status entry, stamping its sessionId and converting its media commands to strings. */
209
+ export function toMediaEntry(entry: Record<string, unknown>, sessionId: string): Record<string, unknown> {
210
+ const out: Record<string, unknown> = { ...entry };
211
+ if ("supportedMediaCommands" in out) out.supportedMediaCommands = mediaCommands(out.supportedMediaCommands);
212
+ out.sessionId = sessionId;
213
+ return out;
214
+ }
215
+
216
+ /** True for objects made by an object literal or JSON.parse (and nothing else, including arrays). */
217
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
218
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
219
+ const proto = Object.getPrototypeOf(v);
220
+ return proto === Object.prototype || proto === null;
221
+ }
222
+
223
+ /** Serialises an outbound Chromium router message; undefined/null/empty-object messages become null. */
224
+ export function envelope(type: string, message: unknown, clientId: string, sequenceNumber?: number): string {
225
+ const empty = message !== undefined && message !== null && isPlainObject(message) && Object.keys(message).length === 0;
226
+ const out: Record<string, unknown> = { type, message: message === undefined || message === null || empty ? null : message };
227
+ if (typeof sequenceNumber === "number") out.sequenceNumber = sequenceNumber;
228
+ out.timeoutMillis = 0;
229
+ out.clientId = clientId;
230
+ return JSON.stringify(out);
231
+ }
232
+
233
+ /** The eight router message types Chromium's parser accepts; anything else is dropped. */
234
+ const ENVELOPE_TYPES = new Set([
235
+ "client_connect",
236
+ "app_message",
237
+ "v2_message",
238
+ "leave_session",
239
+ "receiver_action",
240
+ "new_session",
241
+ "update_session",
242
+ "error",
243
+ ]);
244
+
245
+ /** Validates an inbound router message the way Chromium's CIM parser does, stripping nulls from object messages. */
246
+ export function parseEnvelope(raw: string): ParsedEnvelope | null {
247
+ let data: unknown;
248
+ try {
249
+ data = JSON.parse(raw);
250
+ } catch {
251
+ return null;
252
+ }
253
+ if (!isPlainObject(data)) return null;
254
+ const { type, clientId, message, sequenceNumber } = data;
255
+ if (typeof type !== "string" || !ENVELOPE_TYPES.has(type)) return null;
256
+ if (typeof clientId !== "string" || clientId.length === 0) return null;
257
+ if (type === "app_message") {
258
+ if (!isPlainObject(message)) return null;
259
+ if (typeof message.sessionId !== "string" || typeof message.namespaceName !== "string") return null;
260
+ const inner = message.message;
261
+ if (!(typeof inner === "string" || isPlainObject(inner))) return null;
262
+ } else if (type === "v2_message") {
263
+ if (!isPlainObject(message)) return null;
264
+ if (typeof message.type !== "string" || typeof message.sessionId !== "string") return null;
265
+ } else if (!(typeof message === "string" || isPlainObject(message))) {
266
+ return null;
267
+ }
268
+ const out: ParsedEnvelope = {
269
+ type,
270
+ message: typeof message === "string" ? message : stripNulls(message),
271
+ clientId,
272
+ };
273
+ if (typeof sequenceNumber === "number") out.sequenceNumber = sequenceNumber;
274
+ return out;
275
+ }
276
+
277
+ /** The v2_message media request types clank sends; SET_VOLUME/STOP/LAUNCH are not among them. */
278
+ const MEDIA_REQUEST_TYPES = new Set([
279
+ "LOAD",
280
+ "QUEUE_LOAD",
281
+ "MEDIA_GET_STATUS",
282
+ "PLAY",
283
+ "PAUSE",
284
+ "SEEK",
285
+ "STOP_MEDIA",
286
+ "MEDIA_SET_VOLUME",
287
+ "EDIT_TRACKS_INFO",
288
+ "QUEUE_INSERT",
289
+ "QUEUE_UPDATE",
290
+ "QUEUE_REMOVE",
291
+ "QUEUE_REORDER",
292
+ ]);
293
+
294
+ /** True when a v2_message type is one of the media requests forwarded to the receiver. */
295
+ export function isMediaRequest(type: string): boolean {
296
+ return MEDIA_REQUEST_TYPES.has(type);
297
+ }
298
+
299
+ /** Maps the media request types to the receiver's protocol names, leaving all other types unchanged. */
300
+ export function receiverMediaType(type: string): string {
301
+ switch (type) {
302
+ case "STOP_MEDIA":
303
+ return "STOP";
304
+ case "MEDIA_SET_VOLUME":
305
+ return "SET_VOLUME";
306
+ case "MEDIA_GET_STATUS":
307
+ return "GET_STATUS";
308
+ default:
309
+ return type;
310
+ }
311
+ }