electron-cast 0.3.0 → 0.4.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.
Files changed (204) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/README.md +122 -12
  3. package/dist/cjs/client/auth/build-time.d.ts +7 -0
  4. package/dist/cjs/client/auth/build-time.js +11 -0
  5. package/dist/cjs/client/auth/build-time.js.map +1 -0
  6. package/dist/cjs/client/auth/cast-auth.d.ts +44 -0
  7. package/dist/cjs/client/auth/cast-auth.js +145 -0
  8. package/dist/cjs/client/auth/cast-auth.js.map +1 -0
  9. package/dist/cjs/client/auth/cast-cert-validator.d.ts +34 -0
  10. package/dist/cjs/client/auth/cast-cert-validator.js +89 -0
  11. package/dist/cjs/client/auth/cast-cert-validator.js.map +1 -0
  12. package/dist/cjs/client/auth/crl.d.ts +45 -0
  13. package/dist/cjs/client/auth/crl.js +227 -0
  14. package/dist/cjs/client/auth/crl.js.map +1 -0
  15. package/dist/cjs/client/auth/der.d.ts +62 -0
  16. package/dist/cjs/client/auth/der.js +208 -0
  17. package/dist/cjs/client/auth/der.js.map +1 -0
  18. package/dist/cjs/client/auth/names.d.ts +52 -0
  19. package/dist/cjs/client/auth/names.js +447 -0
  20. package/dist/cjs/client/auth/names.js.map +1 -0
  21. package/dist/cjs/client/auth/path-validator.d.ts +29 -0
  22. package/dist/cjs/client/auth/path-validator.js +421 -0
  23. package/dist/cjs/client/auth/path-validator.js.map +1 -0
  24. package/dist/cjs/client/auth/trust-data.d.ts +24 -0
  25. package/dist/cjs/client/auth/trust-data.js +97 -0
  26. package/dist/cjs/client/auth/trust-data.js.map +1 -0
  27. package/dist/cjs/client/auth/x509.d.ts +109 -0
  28. package/dist/cjs/client/auth/x509.js +442 -0
  29. package/dist/cjs/client/auth/x509.js.map +1 -0
  30. package/dist/cjs/client/cast-client.d.ts +111 -0
  31. package/dist/cjs/client/cast-client.js +505 -0
  32. package/dist/cjs/client/cast-client.js.map +1 -0
  33. package/dist/cjs/client/errors.d.ts +28 -0
  34. package/dist/cjs/client/errors.js +50 -0
  35. package/dist/cjs/client/errors.js.map +1 -0
  36. package/dist/cjs/client/index.d.ts +6 -0
  37. package/dist/cjs/client/index.js +21 -0
  38. package/dist/cjs/client/index.js.map +1 -0
  39. package/dist/cjs/client/namespaces.d.ts +9 -0
  40. package/dist/cjs/client/namespaces.js +13 -0
  41. package/dist/cjs/client/namespaces.js.map +1 -0
  42. package/dist/cjs/client/types.d.ts +27 -0
  43. package/dist/cjs/client/types.js +3 -0
  44. package/dist/cjs/client/types.js.map +1 -0
  45. package/dist/cjs/discovery/cast-discovery.d.ts +103 -0
  46. package/dist/cjs/discovery/cast-discovery.js +323 -0
  47. package/dist/cjs/discovery/cast-discovery.js.map +1 -0
  48. package/dist/cjs/discovery/device-cache.d.ts +45 -0
  49. package/dist/cjs/discovery/device-cache.js +240 -0
  50. package/dist/cjs/discovery/device-cache.js.map +1 -0
  51. package/dist/cjs/discovery/dns-packet.d.ts +70 -0
  52. package/dist/cjs/discovery/dns-packet.js +251 -0
  53. package/dist/cjs/discovery/dns-packet.js.map +1 -0
  54. package/dist/cjs/discovery/index.d.ts +4 -0
  55. package/dist/cjs/discovery/index.js +21 -0
  56. package/dist/cjs/discovery/index.js.map +1 -0
  57. package/dist/cjs/discovery/udp-socket.d.ts +16 -0
  58. package/dist/cjs/discovery/udp-socket.js +163 -0
  59. package/dist/cjs/discovery/udp-socket.js.map +1 -0
  60. package/dist/cjs/electron/main.d.ts +86 -0
  61. package/dist/cjs/electron/main.js +408 -0
  62. package/dist/cjs/electron/main.js.map +1 -0
  63. package/dist/cjs/electron/manager-api.d.ts +132 -0
  64. package/dist/cjs/electron/manager-api.js +207 -0
  65. package/dist/cjs/electron/manager-api.js.map +1 -0
  66. package/dist/cjs/electron/preload.d.ts +39 -0
  67. package/dist/cjs/electron/preload.js +96 -0
  68. package/dist/cjs/electron/preload.js.map +1 -0
  69. package/dist/cjs/electron/presentation-envelope.d.ts +60 -0
  70. package/dist/cjs/electron/presentation-envelope.js +318 -0
  71. package/dist/cjs/electron/presentation-envelope.js.map +1 -0
  72. package/dist/cjs/electron/presentation-handler.d.ts +100 -0
  73. package/dist/cjs/electron/presentation-handler.js +499 -0
  74. package/dist/cjs/electron/presentation-handler.js.map +1 -0
  75. package/dist/cjs/electron/session-service.d.ts +174 -0
  76. package/dist/cjs/electron/session-service.js +891 -0
  77. package/dist/cjs/electron/session-service.js.map +1 -0
  78. package/dist/cjs/index.d.ts +8 -0
  79. package/dist/cjs/index.js +26 -0
  80. package/dist/cjs/index.js.map +1 -0
  81. package/dist/cjs/package.json +1 -0
  82. package/dist/cjs/polyfill/bridge-types.d.ts +86 -0
  83. package/dist/cjs/polyfill/bridge-types.js +3 -0
  84. package/dist/cjs/polyfill/bridge-types.js.map +1 -0
  85. package/dist/cjs/polyfill/install.d.ts +12 -0
  86. package/dist/cjs/polyfill/install.js +1569 -0
  87. package/dist/cjs/polyfill/install.js.map +1 -0
  88. package/dist/cjs/polyfill/presentation-standin.d.ts +13 -0
  89. package/dist/cjs/polyfill/presentation-standin.js +279 -0
  90. package/dist/cjs/polyfill/presentation-standin.js.map +1 -0
  91. package/dist/cjs/protocol/cast-message.d.ts +20 -0
  92. package/dist/cjs/protocol/cast-message.js +171 -0
  93. package/dist/cjs/protocol/cast-message.js.map +1 -0
  94. package/dist/cjs/protocol/device-auth.d.ts +61 -0
  95. package/dist/cjs/protocol/device-auth.js +113 -0
  96. package/dist/cjs/protocol/device-auth.js.map +1 -0
  97. package/dist/cjs/protocol/errors.d.ts +4 -0
  98. package/dist/cjs/protocol/errors.js +12 -0
  99. package/dist/cjs/protocol/errors.js.map +1 -0
  100. package/dist/cjs/protocol/framing.d.ts +18 -0
  101. package/dist/cjs/protocol/framing.js +100 -0
  102. package/dist/cjs/protocol/framing.js.map +1 -0
  103. package/dist/cjs/protocol/index.d.ts +4 -0
  104. package/dist/cjs/protocol/index.js +21 -0
  105. package/dist/cjs/protocol/index.js.map +1 -0
  106. package/dist/cjs/protocol/proto-wire.d.ts +11 -0
  107. package/dist/cjs/protocol/proto-wire.js +64 -0
  108. package/dist/cjs/protocol/proto-wire.js.map +1 -0
  109. package/dist/client/auth/build-time.d.ts +7 -0
  110. package/dist/client/auth/build-time.js +8 -0
  111. package/dist/client/auth/build-time.js.map +1 -0
  112. package/dist/client/auth/cast-auth.d.ts +44 -0
  113. package/dist/client/auth/cast-auth.js +141 -0
  114. package/dist/client/auth/cast-auth.js.map +1 -0
  115. package/dist/client/auth/cast-cert-validator.d.ts +34 -0
  116. package/dist/client/auth/cast-cert-validator.js +86 -0
  117. package/dist/client/auth/cast-cert-validator.js.map +1 -0
  118. package/dist/client/auth/crl.d.ts +45 -0
  119. package/dist/client/auth/crl.js +221 -0
  120. package/dist/client/auth/crl.js.map +1 -0
  121. package/dist/client/auth/der.d.ts +62 -0
  122. package/dist/client/auth/der.js +196 -0
  123. package/dist/client/auth/der.js.map +1 -0
  124. package/dist/client/auth/names.d.ts +52 -0
  125. package/dist/client/auth/names.js +438 -0
  126. package/dist/client/auth/names.js.map +1 -0
  127. package/dist/client/auth/path-validator.d.ts +29 -0
  128. package/dist/client/auth/path-validator.js +417 -0
  129. package/dist/client/auth/path-validator.js.map +1 -0
  130. package/dist/client/auth/trust-data.d.ts +24 -0
  131. package/dist/client/auth/trust-data.js +94 -0
  132. package/dist/client/auth/trust-data.js.map +1 -0
  133. package/dist/client/auth/x509.d.ts +109 -0
  134. package/dist/client/auth/x509.js +430 -0
  135. package/dist/client/auth/x509.js.map +1 -0
  136. package/dist/client/cast-client.d.ts +20 -1
  137. package/dist/client/cast-client.js +74 -3
  138. package/dist/client/cast-client.js.map +1 -1
  139. package/dist/client/errors.d.ts +11 -0
  140. package/dist/client/errors.js +13 -0
  141. package/dist/client/errors.js.map +1 -1
  142. package/dist/client/index.d.ts +2 -0
  143. package/dist/discovery/cast-discovery.d.ts +21 -2
  144. package/dist/discovery/cast-discovery.js +94 -14
  145. package/dist/discovery/cast-discovery.js.map +1 -1
  146. package/dist/discovery/device-cache.d.ts +6 -1
  147. package/dist/discovery/device-cache.js +31 -7
  148. package/dist/discovery/device-cache.js.map +1 -1
  149. package/dist/discovery/udp-socket.d.ts +5 -1
  150. package/dist/discovery/udp-socket.js +56 -5
  151. package/dist/discovery/udp-socket.js.map +1 -1
  152. package/dist/electron/main.d.ts +26 -4
  153. package/dist/electron/main.js +193 -55
  154. package/dist/electron/main.js.map +1 -1
  155. package/dist/electron/manager-api.d.ts +132 -0
  156. package/dist/electron/manager-api.js +198 -0
  157. package/dist/electron/manager-api.js.map +1 -0
  158. package/dist/electron/preload.d.ts +5 -0
  159. package/dist/electron/preload.js +9 -1
  160. package/dist/electron/preload.js.map +1 -1
  161. package/dist/electron/presentation-envelope.js +7 -1
  162. package/dist/electron/presentation-envelope.js.map +1 -1
  163. package/dist/electron/presentation-handler.js +16 -9
  164. package/dist/electron/presentation-handler.js.map +1 -1
  165. package/dist/electron/session-service.d.ts +50 -1
  166. package/dist/electron/session-service.js +256 -33
  167. package/dist/electron/session-service.js.map +1 -1
  168. package/dist/polyfill/presentation-standin.js +3 -2
  169. package/dist/polyfill/presentation-standin.js.map +1 -1
  170. package/dist/protocol/device-auth.d.ts +61 -0
  171. package/dist/protocol/device-auth.js +106 -0
  172. package/dist/protocol/device-auth.js.map +1 -0
  173. package/dist/protocol/index.d.ts +1 -0
  174. package/dist/protocol/index.js +1 -0
  175. package/dist/protocol/index.js.map +1 -1
  176. package/dist/protocol/proto-wire.d.ts +11 -0
  177. package/dist/protocol/proto-wire.js +60 -0
  178. package/dist/protocol/proto-wire.js.map +1 -0
  179. package/package.json +47 -12
  180. package/src/client/auth/build-time.ts +7 -0
  181. package/src/client/auth/cast-auth.ts +184 -0
  182. package/src/client/auth/cast-cert-validator.ts +133 -0
  183. package/src/client/auth/crl.ts +228 -0
  184. package/src/client/auth/der.ts +193 -0
  185. package/src/client/auth/names.ts +411 -0
  186. package/src/client/auth/path-validator.ts +449 -0
  187. package/src/client/auth/trust-data.ts +95 -0
  188. package/src/client/auth/x509.ts +488 -0
  189. package/src/client/cast-client.ts +85 -3
  190. package/src/client/errors.ts +29 -0
  191. package/src/client/index.ts +2 -0
  192. package/src/discovery/cast-discovery.ts +104 -19
  193. package/src/discovery/device-cache.ts +38 -8
  194. package/src/discovery/udp-socket.ts +63 -4
  195. package/src/electron/main.ts +220 -60
  196. package/src/electron/manager-api.ts +312 -0
  197. package/src/electron/preload.ts +15 -1
  198. package/src/electron/presentation-envelope.ts +7 -1
  199. package/src/electron/presentation-handler.ts +16 -10
  200. package/src/electron/session-service.ts +265 -34
  201. package/src/polyfill/presentation-standin.ts +3 -2
  202. package/src/protocol/device-auth.ts +126 -0
  203. package/src/protocol/index.ts +1 -0
  204. package/src/protocol/proto-wire.ts +55 -0
@@ -2,6 +2,9 @@ import type { BridgeEvent, BridgeResult, SessionSnapshot, VolumeSnapshot } from
2
2
  import type { CastDevice } from "../discovery/index.ts";
3
3
  import type { ReceiverApplication, ReceiverStatus, ReceiverVolume } from "../client/index.ts";
4
4
  import { CastTimeoutError } from "../client/index.ts";
5
+ import {
6
+ ObservedMap, createPickerContext, createSinksObservers, type DevicePickerContext, type MediaRoute,
7
+ } from "./manager-api.ts";
5
8
 
6
9
  /** Capability bit names in bit order: 1 video_out, 2 video_in, 4 audio_out, 8 audio_in, 32 multizone_group. */
7
10
  export function capabilityNames(bits: number): string[] {
@@ -71,7 +74,7 @@ export interface CastSessionServiceOptions {
71
74
  * Ask the user which device to cast to. Resolves a device, `null` (cancel) or
72
75
  * `"stop"` (stop `request.session`, the sender's current session, if it has one).
73
76
  */
74
- selectDevice(devices: CastDevice[], request: CastRequestInfo): Promise<DeviceChoice>;
77
+ selectDevice(devices: CastDevice[], request: CastRequestInfo, picker: DevicePickerContext): Promise<DeviceChoice>;
75
78
  allowOrigin?(origin: string): boolean;
76
79
  emit(senderId: number, event: BridgeEvent): void;
77
80
  }
@@ -89,12 +92,24 @@ interface SessionRecord {
89
92
  origin: string;
90
93
  appId: string;
91
94
  members: Set<number>;
95
+ /**
96
+ * Senders whose page navigated away (a reload, say) while a member. Like Chrome's Media Router, the session outlives
97
+ * the page: it stays open on the device so the sender's next page can rejoin it. Parked senders get no events.
98
+ */
99
+ parked: Set<number>;
92
100
  lastVolume: ReceiverVolume;
93
101
  lastSnapshot: SessionSnapshot | null;
94
102
  /** Set while a stopSession is in flight; onClientStatus skips this sender when it ends the session. */
95
103
  stoppingBy?: number;
96
104
  }
97
105
 
106
+ interface PendingRequest {
107
+ discard: { value: boolean };
108
+ cancelled: { value: boolean };
109
+ /** The live picker context while the picker is open. */
110
+ picker?: { close(): void };
111
+ }
112
+
98
113
  interface ClientEntry {
99
114
  client: CastClientLike;
100
115
  device: CastDevice;
@@ -113,6 +128,8 @@ const CAPABILITY_BITS: Record<string, number> = {
113
128
  };
114
129
 
115
130
  const DEFAULT_TIMEOUT_MS = 60000;
131
+ /** The caller id of a stop that comes from the main process, not from a page. */
132
+ const MAIN_CALLER = -1;
116
133
 
117
134
  /** A request that must be reported as a specific chrome.cast error code. */
118
135
  class MappedError extends Error {
@@ -229,14 +246,17 @@ function sameValue(a: unknown, b: unknown): boolean {
229
246
  export class CastSessionService {
230
247
  private readonly options: CastSessionServiceOptions;
231
248
  private readonly senders = new Map<number, SenderRecord>();
232
- private readonly sessions = new Map<string, SessionRecord>();
249
+ private readonly sessions = new ObservedMap<string, SessionRecord>((kind, rec) => this.notifySession(kind, rec));
250
+ private readonly sessionListeners = new Set<() => void>();
251
+ private readonly sinks;
233
252
  private readonly clients = new Map<string, ClientEntry>();
234
- private readonly pendingRequests = new Map<number, { discard: { value: boolean }; cancelled: { value: boolean } }>();
253
+ private readonly pendingRequests = new Map<number, PendingRequest>();
235
254
  private readonly deviceListener = (): void => this.onDevicesChanged();
236
255
  private disposed = false;
237
256
 
238
257
  constructor(options: CastSessionServiceOptions) {
239
258
  this.options = options;
259
+ this.sinks = createSinksObservers(options.devices);
240
260
  options.devices.on("deviceUp", this.deviceListener);
241
261
  options.devices.on("deviceDown", this.deviceListener);
242
262
  options.devices.on("deviceChanged", this.deviceListener);
@@ -255,7 +275,9 @@ export class CastSessionService {
255
275
  case "requestSession":
256
276
  return await this.handleRequestSession(sender, params);
257
277
  case "joinSession":
258
- return this.handleJoinSession(sender, params);
278
+ return this.handleJoinSession(sender, params, true);
279
+ case "joinRunningSession":
280
+ return await this.handleJoinRunningSession(sender, params);
259
281
  case "sendMessage":
260
282
  return this.handleSendMessage(sender, params);
261
283
  case "stopSession":
@@ -276,24 +298,48 @@ export class CastSessionService {
276
298
 
277
299
  /** Detach a sender that went away: cancel its pending request, leave its sessions, drop its bookkeeping. */
278
300
  senderGone(senderId: number): void {
279
- const pending = this.pendingRequests.get(senderId);
280
- if (pending !== undefined) pending.cancelled.value = true;
281
- this.pendingRequests.delete(senderId);
282
- this.senders.delete(senderId);
301
+ this.forgetSender(senderId);
283
302
  for (const rec of [...this.sessions.values()]) {
284
- if (!rec.members.has(senderId)) continue;
303
+ if (!rec.members.has(senderId) && !rec.parked.has(senderId)) continue;
285
304
  this.leave(rec, senderId);
286
305
  }
287
306
  }
288
307
 
308
+ /**
309
+ * The sender's page navigated (a reload or a new page): cancel its pending request and drop its bookkeeping, but
310
+ * keep its sessions open on the device, parked, so the next page can rejoin them (auto-join or joinSession) as it
311
+ * would in Chrome. A parked session ends as usual if the receiver app stops or the device drops; senderGone ends
312
+ * the sender's share of it for good.
313
+ */
314
+ senderNavigated(senderId: number): void {
315
+ this.forgetSender(senderId);
316
+ for (const rec of this.sessions.values()) {
317
+ if (!rec.members.delete(senderId)) continue;
318
+ rec.parked.add(senderId);
319
+ this.notifySession("updated", rec);
320
+ }
321
+ }
322
+
323
+ private forgetSender(senderId: number): void {
324
+ const pending = this.pendingRequests.get(senderId);
325
+ if (pending !== undefined) {
326
+ pending.cancelled.value = true;
327
+ pending.picker?.close();
328
+ }
329
+ this.pendingRequests.delete(senderId);
330
+ this.senders.delete(senderId);
331
+ }
332
+
289
333
  /** Unsubscribe, close every client and clear all state. */
290
334
  async dispose(): Promise<void> {
291
335
  if (this.disposed) return;
292
336
  this.disposed = true;
337
+ this.sinks.dispose();
293
338
  const d = this.options.devices;
294
339
  d.off("deviceUp", this.deviceListener);
295
340
  d.off("deviceDown", this.deviceListener);
296
341
  d.off("deviceChanged", this.deviceListener);
342
+ for (const pending of this.pendingRequests.values()) pending.picker?.close();
297
343
  const entries = [...this.clients.values()];
298
344
  this.clients.clear();
299
345
  for (const entry of entries) entry.client.close();
@@ -310,10 +356,12 @@ export class CastSessionService {
310
356
  const joined: SessionSnapshot[] = [];
311
357
  for (const rec of this.sessions.values()) {
312
358
  if (rec.appId !== p.appId || rec.origin !== sender.origin) continue;
313
- if (p.autoJoinPolicy === "origin_scoped") {
359
+ // tab_and_origin_scoped: this sender (the same tab) is a member, or was one before its page navigated
360
+ const sameTab = rec.members.has(sender.id) || rec.parked.has(sender.id);
361
+ if (p.autoJoinPolicy === "origin_scoped" || (p.autoJoinPolicy === "tab_and_origin_scoped" && sameTab)) {
362
+ rec.parked.delete(sender.id);
314
363
  rec.members.add(sender.id);
315
- joined.push(this.snapshotOf(rec));
316
- } else if (p.autoJoinPolicy === "tab_and_origin_scoped" && rec.members.has(sender.id)) {
364
+ this.notifySession("updated", rec);
317
365
  joined.push(this.snapshotOf(rec));
318
366
  }
319
367
  }
@@ -326,7 +374,8 @@ export class CastSessionService {
326
374
  if (this.pendingRequests.has(sender.id)) return bad("invalid_parameter");
327
375
  const discard = { value: false };
328
376
  const cancelled = { value: false };
329
- this.pendingRequests.set(sender.id, { discard, cancelled });
377
+ const pending: PendingRequest = { discard, cancelled };
378
+ this.pendingRequests.set(sender.id, pending);
330
379
  try {
331
380
  const eligible = this.options.devices.devices().filter((d) => deviceMatches(d, p.capabilities));
332
381
  if (eligible.length === 0) return bad("receiver_unavailable");
@@ -341,10 +390,15 @@ export class CastSessionService {
341
390
  request.session = { sessionId: current.app.sessionId, deviceId: current.device.id };
342
391
  }
343
392
  let choice: DeviceChoice;
393
+ // The picker gets live device updates until it answers; closing aborts its signal.
394
+ const pick = createPickerContext(this.sinks, (d) => deviceMatches(d, p.capabilities));
395
+ pending.picker = pick;
344
396
  try {
345
- choice = await this.options.selectDevice(eligible, request);
397
+ choice = await this.options.selectDevice(eligible, request, pick.context);
346
398
  } catch (err) {
347
399
  return bad("session_error", describe(err));
400
+ } finally {
401
+ pick.close();
348
402
  }
349
403
  if (choice === null) return bad("cancel");
350
404
  if (choice === "stop") {
@@ -382,12 +436,19 @@ export class CastSessionService {
382
436
  }
383
437
  }
384
438
 
385
- private handleJoinSession(sender: SenderInfo, params: unknown): BridgeResult {
439
+ /**
440
+ * `checkOrigin` is joinSession's own rule (mode "chromecast", which is frozen and has no
441
+ * Chromium counterpart). Joining by id, as Chrome's Presentation API path does, has none: AppActivity::CanJoinSession checks only
442
+ * the app and that the client is not connected yet.
443
+ */
444
+ private handleJoinSession(sender: SenderInfo, params: unknown, checkOrigin: boolean): BridgeResult {
386
445
  const p = parseSessionId(params);
387
446
  if (p === null) return bad("invalid_parameter");
388
447
  const rec = this.sessions.get(p.sessionId);
389
- if (rec === undefined || rec.origin !== sender.origin) return bad("session_error");
448
+ if (rec === undefined || (checkOrigin && rec.origin !== sender.origin)) return bad("session_error");
449
+ rec.parked.delete(sender.id);
390
450
  rec.members.add(sender.id);
451
+ this.notifySession("updated", rec);
391
452
  return good(this.snapshotOf(rec));
392
453
  }
393
454
 
@@ -484,6 +545,112 @@ export class CastSessionService {
484
545
  return good(undefined);
485
546
  }
486
547
 
548
+ /** The device's client entry, created and connecting on first use. */
549
+ private clientFor(device: CastDevice): ClientEntry {
550
+ const existing = this.clients.get(device.id);
551
+ if (existing !== undefined) return existing;
552
+ const client = this.options.createClient(device);
553
+ this.bindClient(client, device);
554
+ const entry: ClientEntry = {
555
+ client,
556
+ device,
557
+ ready: client.connect().catch((err: unknown) => {
558
+ // Remove the entry and close the client once so the next request starts fresh.
559
+ this.dropClient(device.id, client);
560
+ throw err;
561
+ }),
562
+ opening: 0,
563
+ };
564
+ // A lookup may never await this; openSession still sees the rejection.
565
+ entry.ready.catch(() => {});
566
+ this.clients.set(device.id, entry);
567
+ return entry;
568
+ }
569
+
570
+ /**
571
+ * Join a session by its id, as Chrome's Media Router does for `reconnect("cast-session_<id>")`. A session this
572
+ * service already holds is joined without an origin check, like one found on a device. Otherwise the id is looked up
573
+ * in the receiver status of
574
+ * every known device: Chrome's CastSessionTracker learns the sessions running on all sinks and
575
+ * CastActivityManager::AddNonLocalActivity makes them joinable by id (and only by id: auto-join skips them, and no
576
+ * origin is checked). `appId`, when given, must be the session's app (CastActivity::CanJoinSession). Unlike Chrome
577
+ * the lookup runs when asked instead of tracking every device all the time.
578
+ */
579
+ private async handleJoinRunningSession(sender: SenderInfo, params: unknown): Promise<BridgeResult> {
580
+ const p = parseSessionId(params);
581
+ if (p === null) return bad("invalid_parameter");
582
+ const appId = isRecord(params) && typeof params.appId === "string" ? params.appId : undefined;
583
+ const known = this.sessions.get(p.sessionId);
584
+ if (known !== undefined) {
585
+ if (appId !== undefined && known.appId !== appId) return bad("session_error");
586
+ return this.handleJoinSession(sender, params, false);
587
+ }
588
+ const found = await this.findRunningSession(p.sessionId);
589
+ if (found === undefined) return bad("session_error");
590
+ const { entry, app, volume } = found;
591
+ try {
592
+ if (this.disposed || (appId !== undefined && app.appId !== appId)) return bad("session_error");
593
+ // Another join of the same session finished while this one looked.
594
+ if (this.sessions.has(app.sessionId)) return this.handleJoinSession(sender, params, false);
595
+ entry.client.connectTransport(app.transportId);
596
+ const rec: SessionRecord = {
597
+ device: entry.device,
598
+ client: entry.client,
599
+ app,
600
+ origin: sender.origin,
601
+ appId: app.appId,
602
+ members: new Set([sender.id]),
603
+ parked: new Set(),
604
+ lastVolume: volume,
605
+ lastSnapshot: null,
606
+ };
607
+ rec.lastSnapshot = this.snapshotOf(rec);
608
+ this.sessions.set(app.sessionId, rec);
609
+ return good(rec.lastSnapshot);
610
+ } finally {
611
+ entry.opening -= 1;
612
+ if (!this.sessions.has(app.sessionId)) this.cleanupIdle(entry.device.id, entry.client);
613
+ }
614
+ }
615
+
616
+ /**
617
+ * Ask every known device what it runs and resolve with the one running `sessionId`. The winner's `opening` count
618
+ * stays raised for the caller to release; a device that cannot be reached or runs something else is let go.
619
+ */
620
+ private findRunningSession(sessionId: string): Promise<{ entry: ClientEntry; app: ReceiverApplication; volume: ReceiverVolume } | undefined> {
621
+ const devices = this.options.devices.devices();
622
+ return new Promise((resolve) => {
623
+ let pending = devices.length;
624
+ let won = false;
625
+ if (pending === 0) resolve(undefined);
626
+ for (const device of devices) {
627
+ const entry = this.clientFor(device);
628
+ entry.opening += 1;
629
+ void (async () => {
630
+ let app: ReceiverApplication | undefined;
631
+ let volume: ReceiverVolume | undefined;
632
+ try {
633
+ await entry.ready;
634
+ const status = await entry.client.getStatus();
635
+ app = status.applications.find((a) => a.sessionId === sessionId);
636
+ volume = status.volume;
637
+ } catch {
638
+ // unreachable: not this device
639
+ }
640
+ if (app !== undefined && volume !== undefined && !won) {
641
+ won = true;
642
+ resolve({ entry, app, volume });
643
+ return;
644
+ }
645
+ entry.opening -= 1;
646
+ this.cleanupIdle(device.id, entry.client);
647
+ pending -= 1;
648
+ if (pending === 0 && !won) resolve(undefined);
649
+ })();
650
+ }
651
+ });
652
+ }
653
+
487
654
  /** Connect (or reuse) the device's client, launch the app and register the session. */
488
655
  private async openSession(
489
656
  device: CastDevice,
@@ -492,23 +659,7 @@ export class CastSessionService {
492
659
  discard: { value: boolean },
493
660
  cancelled: { value: boolean },
494
661
  ): Promise<SessionSnapshot> {
495
- const existing = this.clients.get(device.id);
496
- let entry = existing;
497
- if (entry === undefined) {
498
- const client = this.options.createClient(device);
499
- this.bindClient(client, device);
500
- entry = {
501
- client,
502
- device,
503
- ready: client.connect().catch((err: unknown) => {
504
- // Remove the entry and close the client once so the next request starts fresh.
505
- this.dropClient(device.id, client);
506
- throw err;
507
- }),
508
- opening: 0,
509
- };
510
- this.clients.set(device.id, entry);
511
- }
662
+ const entry = this.clientFor(device);
512
663
  const client = entry.client;
513
664
  entry.opening += 1;
514
665
  let registered = false;
@@ -559,6 +710,7 @@ export class CastSessionService {
559
710
  origin: sender.origin,
560
711
  appId,
561
712
  members: new Set([sender.id]),
713
+ parked: new Set(),
562
714
  lastVolume: status.volume,
563
715
  lastSnapshot: null,
564
716
  };
@@ -576,10 +728,13 @@ export class CastSessionService {
576
728
  /** Remove a sender from a session; when it was the last one, tear the session down. */
577
729
  private leave(rec: SessionRecord, senderId: number): void {
578
730
  rec.members.delete(senderId);
579
- if (rec.members.size === 0) {
731
+ rec.parked.delete(senderId);
732
+ if (rec.members.size === 0 && rec.parked.size === 0) {
580
733
  rec.client.closeTransport(rec.app.transportId);
581
734
  this.sessions.delete(rec.app.sessionId);
582
735
  this.cleanupIdle(rec.device.id, rec.client);
736
+ } else {
737
+ this.notifySession("updated", rec);
583
738
  }
584
739
  }
585
740
 
@@ -623,6 +778,7 @@ export class CastSessionService {
623
778
  const snapshot = this.snapshotOf(rec);
624
779
  if (!sameValue(snapshot, rec.lastSnapshot)) {
625
780
  rec.lastSnapshot = snapshot;
781
+ this.notifySession("updated", rec);
626
782
  for (const member of rec.members) {
627
783
  this.emitTo(member, { type: "sessionUpdated", session: snapshot });
628
784
  }
@@ -684,6 +840,81 @@ export class CastSessionService {
684
840
  client.close();
685
841
  }
686
842
 
843
+ // Main-process API (see manager-api.ts). Control goes through the paths the pages use, so pages see the same events.
844
+
845
+ /** Every live session, parked ones included. */
846
+ mediaRoutes(): MediaRoute[] {
847
+ return [...this.sessions.values()].map((rec) => this.routeOf(rec));
848
+ }
849
+
850
+ /** Be told when a session starts, changes (status, volume, pages) or ends; returns the unsubscribe function. */
851
+ observeSessions(listener: () => void): () => void {
852
+ this.sessionListeners.add(listener);
853
+ return () => void this.sessionListeners.delete(listener);
854
+ }
855
+
856
+ /** Stop a session on the device for every page, as if a member had called stopSession. */
857
+ async terminateSession(sessionId: string): Promise<BridgeResult> {
858
+ const rec = this.sessions.get(sessionId);
859
+ if (rec === undefined) return bad("session_error", "unknown session");
860
+ // No page is the caller, so every member is told sessionEnded.
861
+ return this.stopSessionRecord(rec, MAIN_CALLER, false);
862
+ }
863
+
864
+ async setSessionVolume(sessionId: string, volume: { level: number } | { muted: boolean }): Promise<BridgeResult> {
865
+ const rec = this.sessions.get(sessionId);
866
+ if (rec === undefined) return bad("session_error", "unknown session");
867
+ try {
868
+ await rec.client.setVolume(volume);
869
+ } catch (err) {
870
+ return bad("session_error", describe(err));
871
+ }
872
+ return good(undefined);
873
+ }
874
+
875
+ /** Detach every page from the session and close its transport; the receiver app keeps running. */
876
+ detachSession(sessionId: string): BridgeResult {
877
+ const rec = this.sessions.get(sessionId);
878
+ if (rec === undefined) return bad("session_error", "unknown session");
879
+ for (const member of rec.members) {
880
+ this.emitTo(member, { type: "sessionEnded", sessionId, status: "disconnected" });
881
+ }
882
+ rec.members.clear();
883
+ rec.parked.clear();
884
+ rec.client.closeTransport(rec.app.transportId);
885
+ this.sessions.delete(sessionId);
886
+ this.cleanupIdle(rec.device.id, rec.client);
887
+ return good(undefined);
888
+ }
889
+
890
+ /** Tell the route observers something changed (the arguments only fit the ObservedMap callback). */
891
+ private notifySession(_kind: "started" | "updated" | "ended", _rec: SessionRecord): void {
892
+ if (this.disposed) return;
893
+ for (const listener of [...this.sessionListeners]) {
894
+ try {
895
+ listener();
896
+ } catch (err) {
897
+ console.error("electron-cast: a session listener failed", err);
898
+ }
899
+ }
900
+ }
901
+
902
+ private routeOf(rec: SessionRecord): MediaRoute {
903
+ return {
904
+ id: rec.app.sessionId,
905
+ mediaSource: `cast:${rec.appId}`,
906
+ sinkId: rec.device.id,
907
+ description: rec.app.statusText || rec.app.displayName,
908
+ appId: rec.appId,
909
+ displayName: rec.app.displayName,
910
+ origin: rec.origin,
911
+ volume: { level: rec.lastVolume.level ?? null, muted: rec.lastVolume.muted ?? null },
912
+ members: [...rec.members],
913
+ parkedSenders: [...rec.parked],
914
+ parked: rec.members.size === 0,
915
+ };
916
+ }
917
+
687
918
  private snapshotOf(rec: SessionRecord): SessionSnapshot {
688
919
  const app = rec.app;
689
920
  const volume: VolumeSnapshot = {
@@ -172,7 +172,8 @@ export function installPresentationStandIn(bridgeKey: string): boolean {
172
172
  const nav = g.navigator;
173
173
  const ua = nav ? nav.userActivation : undefined;
174
174
  if (ua && ua.isActive === false) {
175
- return Promise.reject(new DE("Presentation.start() requires a user gesture.", "AbortError"));
175
+ // Blink's PresentationRequest::start() throws kInvalidAccessError with this message
176
+ return Promise.reject(new DE("PresentationRequest::start() requires user gesture.", "InvalidAccessError"));
176
177
  }
177
178
  if (pendingStart) {
178
179
  return Promise.reject(new DE("A call to start() is already in progress.", "OperationError"));
@@ -181,7 +182,7 @@ export function installPresentationStandIn(bridgeKey: string): boolean {
181
182
  const connectionId = uuid();
182
183
  const conn = new PresentationConnection(connectionId, "connecting");
183
184
  connections.set(connectionId, conn);
184
- return Promise.resolve(bridge.call("start", { connectionId, urls: [...this.urls], hasGesture: !(ua && ua.isActive === false) }))
185
+ return Promise.resolve(bridge.call("start", { connectionId, urls: [...this.urls] }))
185
186
  .then((result: any) => settleConnection(conn, connectionId, result))
186
187
  .finally(() => {
187
188
  pendingStart = false;
@@ -0,0 +1,126 @@
1
+ import { CastProtocolError } from "./errors.ts";
2
+ import { forEachField, lengthDelimited } from "./proto-wire.ts";
3
+
4
+ /**
5
+ * The device authentication messages of cast_channel.proto (DeviceAuthMessage and its parts), hand-coded like
6
+ * {@link ./cast-message.ts}. They travel as the binary payload of a CastMessage on the deviceauth namespace.
7
+ */
8
+
9
+ /** SignatureAlgorithm enum values. */
10
+ export const SignatureAlgorithm = { UNSPECIFIED: 0, RSASSA_PKCS1v15: 1, RSASSA_PSS: 2 } as const;
11
+ export type SignatureAlgorithm = (typeof SignatureAlgorithm)[keyof typeof SignatureAlgorithm];
12
+
13
+ /** HashAlgorithm enum values. */
14
+ export const HashAlgorithm = { SHA1: 0, SHA256: 1 } as const;
15
+ export type HashAlgorithm = (typeof HashAlgorithm)[keyof typeof HashAlgorithm];
16
+
17
+ /** AuthError.ErrorType enum values. */
18
+ export const AuthErrorType = { INTERNAL_ERROR: 0, NO_TLS: 1, SIGNATURE_ALGORITHM_UNAVAILABLE: 2 } as const;
19
+ export type AuthErrorType = (typeof AuthErrorType)[keyof typeof AuthErrorType];
20
+
21
+ /** A decoded AuthResponse. Absent optional fields carry the proto2 defaults. */
22
+ export interface AuthResponse {
23
+ signature: Buffer;
24
+ clientAuthCertificate: Buffer;
25
+ intermediateCertificates: Buffer[];
26
+ signatureAlgorithm: number;
27
+ senderNonce: Buffer;
28
+ hashAlgorithm: number;
29
+ crl: Buffer | undefined;
30
+ }
31
+
32
+ /** A decoded DeviceAuthMessage; a device's reply has `response` or `error`. */
33
+ export interface DeviceAuthMessage {
34
+ response?: AuthResponse;
35
+ error?: { errorType: number };
36
+ }
37
+
38
+ /** Encode a DeviceAuthMessage carrying only an AuthChallenge (the sender's half). */
39
+ export function encodeAuthChallenge(challenge: {
40
+ senderNonce: Uint8Array;
41
+ hashAlgorithm?: HashAlgorithm;
42
+ signatureAlgorithm?: SignatureAlgorithm;
43
+ }): Buffer {
44
+ const inner: Buffer[] = [];
45
+ if (challenge.signatureAlgorithm !== undefined) inner.push(Buffer.from([0x08, challenge.signatureAlgorithm]));
46
+ inner.push(lengthDelimited(2, challenge.senderNonce));
47
+ if (challenge.hashAlgorithm !== undefined) inner.push(Buffer.from([0x18, challenge.hashAlgorithm]));
48
+ // DeviceAuthMessage.challenge is field 1.
49
+ return lengthDelimited(1, Buffer.concat(inner));
50
+ }
51
+
52
+ /** Encode an AuthResponse inside a DeviceAuthMessage. Used by tests and fake receivers. */
53
+ export function encodeAuthResponse(response: {
54
+ signature: Uint8Array;
55
+ clientAuthCertificate: Uint8Array;
56
+ intermediateCertificates?: Uint8Array[];
57
+ signatureAlgorithm?: number;
58
+ senderNonce?: Uint8Array;
59
+ hashAlgorithm?: number;
60
+ crl?: Uint8Array;
61
+ }): Buffer {
62
+ const inner: Buffer[] = [lengthDelimited(1, response.signature), lengthDelimited(2, response.clientAuthCertificate)];
63
+ for (const cert of response.intermediateCertificates ?? []) inner.push(lengthDelimited(3, cert));
64
+ if (response.signatureAlgorithm !== undefined) inner.push(Buffer.from([0x20, response.signatureAlgorithm]));
65
+ if (response.senderNonce !== undefined) inner.push(lengthDelimited(5, response.senderNonce));
66
+ if (response.hashAlgorithm !== undefined) inner.push(Buffer.from([0x30, response.hashAlgorithm]));
67
+ if (response.crl !== undefined) inner.push(lengthDelimited(7, response.crl));
68
+ return lengthDelimited(2, Buffer.concat(inner));
69
+ }
70
+
71
+ /** Encode a DeviceAuthMessage carrying an AuthError. Used by tests and fake receivers. */
72
+ export function encodeAuthError(errorType: number): Buffer {
73
+ return lengthDelimited(3, Buffer.from([0x08, errorType]));
74
+ }
75
+
76
+ /** Decode a DeviceAuthMessage, keeping only what a sender needs. Throws {@link CastProtocolError} on malformed input. */
77
+ export function decodeDeviceAuthMessage(bytes: Uint8Array): DeviceAuthMessage {
78
+ const out: DeviceAuthMessage = {};
79
+ forEachField(bytes, (number, wireType, value) => {
80
+ if (number === 2 && wireType === 2) out.response = decodeAuthResponse(value as Uint8Array);
81
+ else if (number === 3 && wireType === 2) out.error = decodeAuthError(value as Uint8Array);
82
+ });
83
+ return out;
84
+ }
85
+
86
+ function decodeAuthResponse(bytes: Uint8Array): AuthResponse {
87
+ let signature: Buffer | undefined;
88
+ let clientAuthCertificate: Buffer | undefined;
89
+ const intermediateCertificates: Buffer[] = [];
90
+ const response: AuthResponse = {
91
+ signature: Buffer.alloc(0),
92
+ clientAuthCertificate: Buffer.alloc(0),
93
+ intermediateCertificates,
94
+ signatureAlgorithm: SignatureAlgorithm.RSASSA_PKCS1v15,
95
+ senderNonce: Buffer.alloc(0),
96
+ hashAlgorithm: HashAlgorithm.SHA1,
97
+ crl: undefined,
98
+ };
99
+ forEachField(bytes, (number, wireType, value) => {
100
+ if (wireType === 2) {
101
+ const data = Buffer.from(value as Uint8Array);
102
+ if (number === 1) signature = data;
103
+ else if (number === 2) clientAuthCertificate = data;
104
+ else if (number === 3) intermediateCertificates.push(data);
105
+ else if (number === 5) response.senderNonce = data;
106
+ else if (number === 7) response.crl = data;
107
+ } else if (wireType === 0) {
108
+ if (number === 4) response.signatureAlgorithm = Number(value);
109
+ else if (number === 6) response.hashAlgorithm = Number(value);
110
+ }
111
+ });
112
+ if (signature === undefined) throw new CastProtocolError("AuthResponse is missing required field signature");
113
+ if (clientAuthCertificate === undefined) throw new CastProtocolError("AuthResponse is missing required field client_auth_certificate");
114
+ response.signature = signature;
115
+ response.clientAuthCertificate = clientAuthCertificate;
116
+ return response;
117
+ }
118
+
119
+ function decodeAuthError(bytes: Uint8Array): { errorType: number } {
120
+ let errorType: number | undefined;
121
+ forEachField(bytes, (number, wireType, value) => {
122
+ if (number === 1 && wireType === 0) errorType = Number(value);
123
+ });
124
+ if (errorType === undefined) throw new CastProtocolError("AuthError is missing required field error_type");
125
+ return { errorType };
126
+ }
@@ -1,3 +1,4 @@
1
1
  export * from "./cast-message.ts";
2
2
  export * from "./errors.ts";
3
3
  export * from "./framing.ts";
4
+ export * from "./device-auth.ts";
@@ -0,0 +1,55 @@
1
+ import { CastProtocolError } from "./errors.ts";
2
+
3
+ /**
4
+ * Minimal protobuf wire reading shared by the device authentication messages and the Cast revocation list. Not
5
+ * exported from the package: only the typed decoders built on it are.
6
+ */
7
+
8
+ /** Append a length-delimited field (wire type 2). */
9
+ export function lengthDelimited(fieldNumber: number, payload: Uint8Array): Buffer {
10
+ const header: number[] = [(fieldNumber << 3) | 2];
11
+ let length = payload.length;
12
+ while (length >= 0x80) {
13
+ header.push((length & 0x7f) | 0x80);
14
+ length = Math.floor(length / 128);
15
+ }
16
+ header.push(length);
17
+ return Buffer.concat([Buffer.from(header), payload]);
18
+ }
19
+
20
+ /**
21
+ * Visit each field in order. Varints arrive as bigint (so uint64 survives), length-delimited fields as byte slices;
22
+ * fixed-width fields are skipped. Throws {@link CastProtocolError} on truncated or unsupported input.
23
+ */
24
+ export function forEachField(bytes: Uint8Array, visit: (number: number, wireType: number, value: bigint | Uint8Array) => void): void {
25
+ let pos = 0;
26
+ const varint = (): bigint => {
27
+ let value = 0n;
28
+ for (let i = 0; i < 10; i++) {
29
+ const byte = bytes[pos++];
30
+ if (byte === undefined) throw new CastProtocolError("varint runs past end of input");
31
+ value |= BigInt(byte & 0x7f) << BigInt(7 * i);
32
+ if ((byte & 0x80) === 0) return value;
33
+ }
34
+ throw new CastProtocolError("varint longer than 10 bytes");
35
+ };
36
+ while (pos < bytes.length) {
37
+ const tag = varint();
38
+ const number = Number(tag >> 3n);
39
+ const wireType = Number(tag & 7n);
40
+ if (wireType === 0) {
41
+ visit(number, 0, varint());
42
+ } else if (wireType === 2) {
43
+ const length = Number(varint());
44
+ if (pos + length > bytes.length) throw new CastProtocolError("length-delimited field runs past end of input");
45
+ visit(number, 2, bytes.subarray(pos, pos + length));
46
+ pos += length;
47
+ } else if (wireType === 1 || wireType === 5) {
48
+ const size = wireType === 1 ? 8 : 4;
49
+ if (pos + size > bytes.length) throw new CastProtocolError("truncated fixed-size field");
50
+ pos += size;
51
+ } else {
52
+ throw new CastProtocolError(`unsupported wire type ${wireType}`);
53
+ }
54
+ }
55
+ }