electron-cast 0.3.1 → 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 +60 -0
  2. package/README.md +123 -14
  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 +191 -54
  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 +42 -1
  166. package/dist/electron/session-service.js +226 -23
  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 +218 -59
  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 +230 -26
  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
  }
@@ -100,6 +103,13 @@ interface SessionRecord {
100
103
  stoppingBy?: number;
101
104
  }
102
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
+
103
113
  interface ClientEntry {
104
114
  client: CastClientLike;
105
115
  device: CastDevice;
@@ -118,6 +128,8 @@ const CAPABILITY_BITS: Record<string, number> = {
118
128
  };
119
129
 
120
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;
121
133
 
122
134
  /** A request that must be reported as a specific chrome.cast error code. */
123
135
  class MappedError extends Error {
@@ -234,14 +246,17 @@ function sameValue(a: unknown, b: unknown): boolean {
234
246
  export class CastSessionService {
235
247
  private readonly options: CastSessionServiceOptions;
236
248
  private readonly senders = new Map<number, SenderRecord>();
237
- 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;
238
252
  private readonly clients = new Map<string, ClientEntry>();
239
- private readonly pendingRequests = new Map<number, { discard: { value: boolean }; cancelled: { value: boolean } }>();
253
+ private readonly pendingRequests = new Map<number, PendingRequest>();
240
254
  private readonly deviceListener = (): void => this.onDevicesChanged();
241
255
  private disposed = false;
242
256
 
243
257
  constructor(options: CastSessionServiceOptions) {
244
258
  this.options = options;
259
+ this.sinks = createSinksObservers(options.devices);
245
260
  options.devices.on("deviceUp", this.deviceListener);
246
261
  options.devices.on("deviceDown", this.deviceListener);
247
262
  options.devices.on("deviceChanged", this.deviceListener);
@@ -260,7 +275,9 @@ export class CastSessionService {
260
275
  case "requestSession":
261
276
  return await this.handleRequestSession(sender, params);
262
277
  case "joinSession":
263
- return this.handleJoinSession(sender, params);
278
+ return this.handleJoinSession(sender, params, true);
279
+ case "joinRunningSession":
280
+ return await this.handleJoinRunningSession(sender, params);
264
281
  case "sendMessage":
265
282
  return this.handleSendMessage(sender, params);
266
283
  case "stopSession":
@@ -299,12 +316,16 @@ export class CastSessionService {
299
316
  for (const rec of this.sessions.values()) {
300
317
  if (!rec.members.delete(senderId)) continue;
301
318
  rec.parked.add(senderId);
319
+ this.notifySession("updated", rec);
302
320
  }
303
321
  }
304
322
 
305
323
  private forgetSender(senderId: number): void {
306
324
  const pending = this.pendingRequests.get(senderId);
307
- if (pending !== undefined) pending.cancelled.value = true;
325
+ if (pending !== undefined) {
326
+ pending.cancelled.value = true;
327
+ pending.picker?.close();
328
+ }
308
329
  this.pendingRequests.delete(senderId);
309
330
  this.senders.delete(senderId);
310
331
  }
@@ -313,10 +334,12 @@ export class CastSessionService {
313
334
  async dispose(): Promise<void> {
314
335
  if (this.disposed) return;
315
336
  this.disposed = true;
337
+ this.sinks.dispose();
316
338
  const d = this.options.devices;
317
339
  d.off("deviceUp", this.deviceListener);
318
340
  d.off("deviceDown", this.deviceListener);
319
341
  d.off("deviceChanged", this.deviceListener);
342
+ for (const pending of this.pendingRequests.values()) pending.picker?.close();
320
343
  const entries = [...this.clients.values()];
321
344
  this.clients.clear();
322
345
  for (const entry of entries) entry.client.close();
@@ -338,6 +361,7 @@ export class CastSessionService {
338
361
  if (p.autoJoinPolicy === "origin_scoped" || (p.autoJoinPolicy === "tab_and_origin_scoped" && sameTab)) {
339
362
  rec.parked.delete(sender.id);
340
363
  rec.members.add(sender.id);
364
+ this.notifySession("updated", rec);
341
365
  joined.push(this.snapshotOf(rec));
342
366
  }
343
367
  }
@@ -350,7 +374,8 @@ export class CastSessionService {
350
374
  if (this.pendingRequests.has(sender.id)) return bad("invalid_parameter");
351
375
  const discard = { value: false };
352
376
  const cancelled = { value: false };
353
- this.pendingRequests.set(sender.id, { discard, cancelled });
377
+ const pending: PendingRequest = { discard, cancelled };
378
+ this.pendingRequests.set(sender.id, pending);
354
379
  try {
355
380
  const eligible = this.options.devices.devices().filter((d) => deviceMatches(d, p.capabilities));
356
381
  if (eligible.length === 0) return bad("receiver_unavailable");
@@ -365,10 +390,15 @@ export class CastSessionService {
365
390
  request.session = { sessionId: current.app.sessionId, deviceId: current.device.id };
366
391
  }
367
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;
368
396
  try {
369
- choice = await this.options.selectDevice(eligible, request);
397
+ choice = await this.options.selectDevice(eligible, request, pick.context);
370
398
  } catch (err) {
371
399
  return bad("session_error", describe(err));
400
+ } finally {
401
+ pick.close();
372
402
  }
373
403
  if (choice === null) return bad("cancel");
374
404
  if (choice === "stop") {
@@ -406,13 +436,19 @@ export class CastSessionService {
406
436
  }
407
437
  }
408
438
 
409
- 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 {
410
445
  const p = parseSessionId(params);
411
446
  if (p === null) return bad("invalid_parameter");
412
447
  const rec = this.sessions.get(p.sessionId);
413
- if (rec === undefined || rec.origin !== sender.origin) return bad("session_error");
448
+ if (rec === undefined || (checkOrigin && rec.origin !== sender.origin)) return bad("session_error");
414
449
  rec.parked.delete(sender.id);
415
450
  rec.members.add(sender.id);
451
+ this.notifySession("updated", rec);
416
452
  return good(this.snapshotOf(rec));
417
453
  }
418
454
 
@@ -509,6 +545,112 @@ export class CastSessionService {
509
545
  return good(undefined);
510
546
  }
511
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
+
512
654
  /** Connect (or reuse) the device's client, launch the app and register the session. */
513
655
  private async openSession(
514
656
  device: CastDevice,
@@ -517,23 +659,7 @@ export class CastSessionService {
517
659
  discard: { value: boolean },
518
660
  cancelled: { value: boolean },
519
661
  ): Promise<SessionSnapshot> {
520
- const existing = this.clients.get(device.id);
521
- let entry = existing;
522
- if (entry === undefined) {
523
- const client = this.options.createClient(device);
524
- this.bindClient(client, device);
525
- entry = {
526
- client,
527
- device,
528
- ready: client.connect().catch((err: unknown) => {
529
- // Remove the entry and close the client once so the next request starts fresh.
530
- this.dropClient(device.id, client);
531
- throw err;
532
- }),
533
- opening: 0,
534
- };
535
- this.clients.set(device.id, entry);
536
- }
662
+ const entry = this.clientFor(device);
537
663
  const client = entry.client;
538
664
  entry.opening += 1;
539
665
  let registered = false;
@@ -607,6 +733,8 @@ export class CastSessionService {
607
733
  rec.client.closeTransport(rec.app.transportId);
608
734
  this.sessions.delete(rec.app.sessionId);
609
735
  this.cleanupIdle(rec.device.id, rec.client);
736
+ } else {
737
+ this.notifySession("updated", rec);
610
738
  }
611
739
  }
612
740
 
@@ -650,6 +778,7 @@ export class CastSessionService {
650
778
  const snapshot = this.snapshotOf(rec);
651
779
  if (!sameValue(snapshot, rec.lastSnapshot)) {
652
780
  rec.lastSnapshot = snapshot;
781
+ this.notifySession("updated", rec);
653
782
  for (const member of rec.members) {
654
783
  this.emitTo(member, { type: "sessionUpdated", session: snapshot });
655
784
  }
@@ -711,6 +840,81 @@ export class CastSessionService {
711
840
  client.close();
712
841
  }
713
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
+
714
918
  private snapshotOf(rec: SessionRecord): SessionSnapshot {
715
919
  const app = rec.app;
716
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
+ }