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
@@ -1,11 +1,15 @@
1
1
  import { EventEmitter } from "node:events";
2
2
  import os from "node:os";
3
- import { CastDeviceCache, type CastDevice } from "./device-cache.ts";
4
- import { decodeDnsPacket, encodeMdnsQuery, RecordType, type DnsPacket } from "./dns-packet.ts";
3
+ import { CastDeviceCache, type CacheChange, type CastDevice } from "./device-cache.ts";
4
+ import { decodeDnsPacket, encodeMdnsQuery, RecordType, type DnsPacket, type DnsRecord } from "./dns-packet.ts";
5
5
  import { openUdpMdnsSocket } from "./udp-socket.ts";
6
6
 
7
- /** An external IPv4 interface. */
8
- export interface NetworkInterfaceInfo { name: string; address: string }
7
+ /**
8
+ * An interface mDNS runs on. `family` is "IPv4" when absent. For "IPv6" it is the interface's link-local address
9
+ * and `scopeId` its zone. An IPv4 entry may carry the `scopeId` of the same adapter's link-local address, so
10
+ * link-local AAAA records heard on it can be turned into addresses that can be connected to (`fe80::1%12`).
11
+ */
12
+ export interface NetworkInterfaceInfo { name: string; address: string; family?: "IPv4" | "IPv6"; scopeId?: number }
9
13
 
10
14
  /** Callbacks for an mDNS socket: incoming packets and socket errors. */
11
15
  export interface MdnsSocketHandlers {
@@ -42,14 +46,47 @@ export function listIPv4Interfaces(nets?: NodeJS.Dict<os.NetworkInterfaceInfo[]>
42
46
  return out;
43
47
  }
44
48
 
49
+ const LINK_LOCAL_V6 = /^fe[89ab][0-9a-f]:/i;
50
+
51
+ /**
52
+ * The interfaces mDNS should run on: every external IPv4 address (see {@link listIPv4Interfaces}), then one IPv6
53
+ * link-local address per adapter (mDNS over IPv6 is per link, whatever global addresses the adapter has).
54
+ */
55
+ export function listMdnsInterfaces(nets?: NodeJS.Dict<os.NetworkInterfaceInfo[]>): NetworkInterfaceInfo[] {
56
+ const all = nets ?? os.networkInterfaces();
57
+ const scopes = new Map<string, { address: string; scopeId: number }>();
58
+ for (const [name, addrs] of Object.entries(all)) {
59
+ for (const addr of addrs ?? []) {
60
+ const family: unknown = addr.family;
61
+ if (family !== "IPv6" && family !== 6) continue;
62
+ if (addr.internal || !LINK_LOCAL_V6.test(addr.address)) continue;
63
+ const scopeId = (addr as { scopeid?: number }).scopeid;
64
+ if (typeof scopeId !== "number" || scopeId <= 0) continue;
65
+ if (!scopes.has(name)) scopes.set(name, { address: addr.address.split("%")[0] ?? addr.address, scopeId });
66
+ }
67
+ }
68
+ const v4 = listIPv4Interfaces(all).map((i): NetworkInterfaceInfo => {
69
+ const scope = scopes.get(i.name);
70
+ return scope ? { ...i, scopeId: scope.scopeId } : i;
71
+ });
72
+ const v6 = [...scopes].map(([name, { address, scopeId }]): NetworkInterfaceInfo => ({ name, address, family: "IPv6", scopeId }));
73
+ return [...v4, ...v6];
74
+ }
75
+
76
+ /** Identifies an interface: IPv6 link-local addresses repeat across adapters, so they carry their scope. */
77
+ function ifaceKey(iface: NetworkInterfaceInfo): string {
78
+ return iface.family === "IPv6" ? `${iface.address}%${iface.scopeId ?? iface.name}` : iface.address;
79
+ }
80
+
45
81
  export interface CastDiscoveryOptions {
46
82
  serviceName?: string; // default "_googlecast._tcp.local"
47
- interfaces?: () => NetworkInterfaceInfo[]; // default () => listIPv4Interfaces()
83
+ interfaces?: () => NetworkInterfaceInfo[]; // default () => listMdnsInterfaces() (IPv4, plus IPv6 link-local)
48
84
  openSocket?: OpenMdnsSocket; // default openUdpMdnsSocket
49
85
  followUpQueriesMs?: number[]; // default [1000, 3000], measured from start
50
86
  refreshMs?: number; // default 60000
51
87
  expireCheckMs?: number; // default 1000
52
88
  interfaceCheckMs?: number; // default 10000
89
+ resumeGapMs?: number; // default 3 x interfaceCheckMs: a check this late means the machine slept
53
90
  }
54
91
 
55
92
  export interface CastDiscoveryEvents {
@@ -64,13 +101,24 @@ interface SocketEntry {
64
101
  socket: MdnsSocket;
65
102
  }
66
103
 
104
+ /**
105
+ * A link-local AAAA record (`fe80::...`) only names a device together with the link it was heard on, so the
106
+ * interface's scope is appended (`fe80::1%12`); with no known scope the address is unusable and the record is
107
+ * dropped. Everything else passes through.
108
+ */
109
+ function scopeLinkLocal(record: DnsRecord, iface: NetworkInterfaceInfo): DnsRecord[] {
110
+ if (record.type !== "AAAA" || !LINK_LOCAL_V6.test(record.data) || record.data.includes("%")) return [record];
111
+ if (iface.scopeId === undefined) return [];
112
+ return [{ ...record, data: `${record.data}%${iface.scopeId}` }];
113
+ }
114
+
67
115
  function toError(error: unknown): Error {
68
116
  return error instanceof Error ? error : new Error(String(error));
69
117
  }
70
118
 
71
119
  /**
72
120
  * Discovers Cast devices by sending mDNS PTR queries on every external IPv4
73
- * interface and joining the answers into {@link CastDevice}s.
121
+ * interface (and over IPv6 link-local where it works) and joining the answers into {@link CastDevice}s.
74
122
  */
75
123
  export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
76
124
  private readonly serviceName: string;
@@ -80,10 +128,16 @@ export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
80
128
  private readonly refreshMs: number;
81
129
  private readonly expireCheckMs: number;
82
130
  private readonly interfaceCheckMs: number;
131
+ private readonly resumeGapMs: number;
83
132
  private readonly queryPacket: Buffer;
84
133
  private cache: CastDeviceCache;
85
134
  private sockets: SocketEntry[] = [];
86
135
  private readonly pending = new Set<string>();
136
+ /** Interfaces whose last open failed and was reported, so a retry loop does not repeat the report. */
137
+ private readonly failed = new Set<string>();
138
+ /** Interface keys of the last listing, to tell which interfaces went away. */
139
+ private lastListed = new Set<string>();
140
+ private lastCheckAt = 0;
87
141
  private timers: NodeJS.Timeout[] = [];
88
142
  private startPromise: Promise<void> | null = null;
89
143
  private stopped = false;
@@ -91,12 +145,13 @@ export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
91
145
  constructor(options: CastDiscoveryOptions = {}) {
92
146
  super();
93
147
  this.serviceName = options.serviceName ?? DEFAULT_SERVICE_NAME;
94
- this.listIfaces = options.interfaces ?? (() => listIPv4Interfaces());
148
+ this.listIfaces = options.interfaces ?? (() => listMdnsInterfaces());
95
149
  this.openSocketFn = options.openSocket ?? openUdpMdnsSocket;
96
150
  this.followUpQueriesMs = options.followUpQueriesMs ?? [1000, 3000];
97
151
  this.refreshMs = options.refreshMs ?? 60_000;
98
152
  this.expireCheckMs = options.expireCheckMs ?? 1000;
99
153
  this.interfaceCheckMs = options.interfaceCheckMs ?? 10_000;
154
+ this.resumeGapMs = options.resumeGapMs ?? this.interfaceCheckMs * 3;
100
155
  this.cache = new CastDeviceCache(this.serviceName);
101
156
  this.queryPacket = encodeMdnsQuery(this.serviceName, RecordType.PTR);
102
157
  }
@@ -107,6 +162,7 @@ export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
107
162
  if (this.startPromise !== null) return this.startPromise;
108
163
  this.startTimers();
109
164
  const ifaces = this.listIfaces();
165
+ this.lastListed = new Set(ifaces.map(ifaceKey));
110
166
  this.startPromise = Promise.allSettled(ifaces.map((iface) => this.openIface(iface))).then(
111
167
  () => undefined,
112
168
  );
@@ -141,6 +197,7 @@ export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
141
197
  for (const entry of this.sockets) this.closeQuietly(entry.socket);
142
198
  this.sockets = [];
143
199
  this.pending.clear();
200
+ this.failed.clear();
144
201
  this.cache = new CastDeviceCache(this.serviceName);
145
202
  }
146
203
 
@@ -161,12 +218,14 @@ export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
161
218
  for (const device of change.removed) this.emit("deviceDown", device);
162
219
  }, this.expireCheckMs),
163
220
  );
221
+ this.lastCheckAt = Date.now();
164
222
  this.timers.push(setInterval(() => this.checkInterfaces(), this.interfaceCheckMs));
165
223
  }
166
224
 
167
225
  /** Opens a socket on `iface`; on success adds it and sends one query on it. */
168
226
  private openIface(iface: NetworkInterfaceInfo): Promise<void> {
169
- this.pending.add(iface.address);
227
+ const key = ifaceKey(iface);
228
+ this.pending.add(key);
170
229
  const work = (async (): Promise<void> => {
171
230
  // Errors are matched to this socket, not to its address: a late error from a replaced socket must not
172
231
  // close the socket that replaced it.
@@ -175,28 +234,32 @@ export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
175
234
  try {
176
235
  socket = await this.openSocketFn(iface, this.makeHandlers(iface, holder));
177
236
  } catch (error) {
178
- if (!this.stopped) this.emit("socketError", iface, toError(error));
237
+ if (!this.stopped && !this.failed.has(key)) {
238
+ this.failed.add(key);
239
+ this.emit("socketError", iface, toError(error));
240
+ }
179
241
  return;
180
242
  }
181
243
  holder.socket = socket;
182
- if (this.stopped || this.sockets.some((s) => s.iface.address === iface.address)) {
244
+ this.failed.delete(key);
245
+ if (this.stopped || this.sockets.some((s) => ifaceKey(s.iface) === key)) {
183
246
  this.closeQuietly(socket);
184
247
  return;
185
248
  }
186
249
  this.sockets.push({ iface, socket });
187
250
  this.safeQuery(iface, socket);
188
251
  })();
189
- return work.finally(() => this.pending.delete(iface.address));
252
+ return work.finally(() => this.pending.delete(key));
190
253
  }
191
254
 
192
255
  private makeHandlers(iface: NetworkInterfaceInfo, holder: { socket?: MdnsSocket }): MdnsSocketHandlers {
193
256
  return {
194
- message: (packet: Buffer) => this.onMessage(packet),
257
+ message: (packet: Buffer) => this.onMessage(packet, iface),
195
258
  error: (error: Error) => this.onSocketError(iface, error, holder.socket),
196
259
  };
197
260
  }
198
261
 
199
- private onMessage(packet: Buffer): void {
262
+ private onMessage(packet: Buffer, iface: NetworkInterfaceInfo): void {
200
263
  if (this.stopped) return;
201
264
  let decoded: DnsPacket;
202
265
  try {
@@ -205,8 +268,13 @@ export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
205
268
  return;
206
269
  }
207
270
  if (!decoded.isResponse) return;
208
- const records = [...decoded.answers, ...decoded.authorities, ...decoded.additionals];
209
- const change = this.cache.ingest(records, Date.now());
271
+ const records = [...decoded.answers, ...decoded.authorities, ...decoded.additionals].flatMap((r) =>
272
+ scopeLinkLocal(r, iface),
273
+ );
274
+ this.emitChange(this.cache.ingest(records, Date.now(), ifaceKey(iface)));
275
+ }
276
+
277
+ private emitChange(change: CacheChange): void {
210
278
  for (const device of change.removed) this.emit("deviceDown", device);
211
279
  for (const device of change.updated) this.emit("deviceChanged", device);
212
280
  for (const device of change.added) this.emit("deviceUp", device);
@@ -242,15 +310,32 @@ export class CastDiscovery extends EventEmitter<CastDiscoveryEvents> {
242
310
  } catch {
243
311
  return;
244
312
  }
245
- const listed = new Set(ifaces.map((i) => i.address));
313
+ // A timer that fires long after it was due means the machine slept. Sockets can come back from sleep alive but
314
+ // deaf (lost multicast membership, no error), so open fresh ones rather than trust them.
315
+ const now = Date.now();
316
+ const resumed = now - this.lastCheckAt > this.resumeGapMs;
317
+ this.lastCheckAt = now;
318
+ if (resumed) {
319
+ for (const entry of this.sockets) this.closeQuietly(entry.socket);
320
+ this.sockets = [];
321
+ }
322
+ const listed = new Set(ifaces.map(ifaceKey));
246
323
  this.sockets = this.sockets.filter((entry) => {
247
- if (listed.has(entry.iface.address)) return true;
324
+ if (listed.has(ifaceKey(entry.iface))) return true;
248
325
  this.closeQuietly(entry.socket);
249
326
  return false;
250
327
  });
328
+ // Devices that were only heard on an interface that is gone cannot be reached, so they go now, not after their TTL.
329
+ for (const key of this.lastListed) {
330
+ if (listed.has(key)) continue;
331
+ this.failed.delete(key);
332
+ this.emitChange(this.cache.dropSource(key));
333
+ }
334
+ this.lastListed = listed;
251
335
  for (const iface of ifaces) {
252
- if (this.sockets.some((s) => s.iface.address === iface.address)) continue;
253
- if (this.pending.has(iface.address)) continue;
336
+ const key = ifaceKey(iface);
337
+ if (this.sockets.some((s) => ifaceKey(s.iface) === key)) continue;
338
+ if (this.pending.has(key)) continue;
254
339
  void this.openIface(iface);
255
340
  }
256
341
  }
@@ -26,6 +26,8 @@ interface StoredRecord {
26
26
  record: DnsRecord;
27
27
  receivedAt: number;
28
28
  expiresAt: number;
29
+ /** Interfaces this record was heard on (see {@link CastDeviceCache.dropSource}). */
30
+ sources: Set<string>;
29
31
  }
30
32
 
31
33
  /** Data-identity component of a storage key ("" for TXT, which is keyed by name alone). */
@@ -79,6 +81,17 @@ function deepEqual(a: unknown, b: unknown): boolean {
79
81
  return true;
80
82
  }
81
83
 
84
+ interface Seen { address: string; receivedAt: number }
85
+
86
+ /** Addresses, most recently heard first: after a DHCP change the new one leads even before the old one expires. */
87
+ function newestFirst(list: Seen[]): string[] {
88
+ return [...list].sort((a, b) => b.receivedAt - a.receivedAt).map((a) => a.address);
89
+ }
90
+
91
+ function isLinkLocal(address: string): boolean {
92
+ return /^fe[89ab][0-9a-f]:/i.test(address);
93
+ }
94
+
82
95
  /** Parses the TXT `ca` value: a non-negative base-10 integer, or 0 otherwise. */
83
96
  function parseCapabilities(raw: string | undefined): number {
84
97
  if (typeof raw !== "string" || !/^\d+$/.test(raw)) return 0;
@@ -108,9 +121,20 @@ export class CastDeviceCache {
108
121
  }
109
122
 
110
123
  /** Ingests a batch of records (in arrival order) and reports device changes. */
111
- ingest(records: DnsRecord[], now: number): CacheChange {
124
+ ingest(records: DnsRecord[], now: number, source?: string): CacheChange {
125
+ const before = this.devices();
126
+ for (const record of records) this.store(record, now, source);
127
+ return this.diff(before);
128
+ }
129
+
130
+ /**
131
+ * Forgets that `source` (an interface) heard anything, and removes the records that nothing else heard. Used when
132
+ * an interface goes away: its devices are not reachable any more, so they should not wait out their TTL.
133
+ */
134
+ dropSource(source: string): CacheChange {
112
135
  const before = this.devices();
113
- for (const record of records) this.store(record, now);
136
+ const kept = this.stored.filter((r) => !r.sources.delete(source) || r.sources.size > 0);
137
+ this.stored.splice(0, this.stored.length, ...kept);
114
138
  return this.diff(before);
115
139
  }
116
140
 
@@ -126,7 +150,7 @@ export class CastDeviceCache {
126
150
  return this.snapshot().map(copyDevice);
127
151
  }
128
152
 
129
- private store(record: DnsRecord, now: number): void {
153
+ private store(record: DnsRecord, now: number, source?: string): void {
130
154
  const key = keyOf(record);
131
155
  if (record.ttl === 0) {
132
156
  // Goodbye: drop the matching stored record, do not store it.
@@ -145,8 +169,10 @@ export class CastDeviceCache {
145
169
  ),
146
170
  );
147
171
  }
148
- const entry = { record, receivedAt: now, expiresAt: now + record.ttl * 1000 };
149
172
  const idx = this.stored.findIndex((r) => keyOf(r.record) === key);
173
+ const sources = new Set(idx !== -1 ? this.stored[idx]?.sources : undefined);
174
+ if (source !== undefined) sources.add(source);
175
+ const entry = { record, receivedAt: now, expiresAt: now + record.ttl * 1000, sources };
150
176
  if (idx !== -1) this.stored[idx] = entry;
151
177
  else this.stored.push(entry);
152
178
  }
@@ -156,7 +182,7 @@ export class CastDeviceCache {
156
182
  const service = this.serviceName.toLowerCase();
157
183
  const srvByInstance = new Map<string, { record: Extract<DnsRecord, { type: "SRV" }>; receivedAt: number }>();
158
184
  const txtByInstance = new Map<string, { record: Extract<DnsRecord, { type: "TXT" }>; receivedAt: number }>();
159
- const addrsByHost = new Map<string, { v4: string[]; v6: string[] }>();
185
+ const addrsByHost = new Map<string, { v4: Seen[]; v6: Seen[] }>();
160
186
  for (const s of this.stored) {
161
187
  const rec = s.record;
162
188
  const name = rec.name.toLowerCase();
@@ -172,7 +198,7 @@ export class CastDeviceCache {
172
198
  list = { v4: [], v6: [] };
173
199
  addrsByHost.set(name, list);
174
200
  }
175
- (rec.type === "A" ? list.v4 : list.v6).push(rec.data);
201
+ (rec.type === "A" ? list.v4 : list.v6).push({ address: rec.data, receivedAt: s.receivedAt });
176
202
  }
177
203
  }
178
204
  const byId = new Map<string, { device: CastDevice; recency: number }>();
@@ -188,6 +214,10 @@ export class CastDeviceCache {
188
214
  if (!id) continue;
189
215
  const addrs = addrsByHost.get(srv.record.data.target.toLowerCase());
190
216
  if (!addrs || (addrs.v4.length + addrs.v6.length) === 0) continue;
217
+ const v4 = newestFirst(addrs.v4);
218
+ const v6 = newestFirst(addrs.v6);
219
+ // IPv4 first (Chromium's Cast discovery only resolves A records), then global IPv6, then link-local.
220
+ const ordered = [...v4, ...v6.filter((a) => !isLinkLocal(a)), ...v6.filter(isLinkLocal)];
191
221
  const txtData = txt.record.data;
192
222
  const fn = txtData["fn"];
193
223
  const dot = instance.indexOf(".");
@@ -197,8 +227,8 @@ export class CastDeviceCache {
197
227
  id,
198
228
  name: fn && fn !== "" ? fn : label,
199
229
  model: txtData["md"] ?? "",
200
- host: addrs.v4[0] ?? addrs.v6[0] ?? "",
201
- addresses: [...addrs.v4, ...addrs.v6],
230
+ host: ordered[0] ?? "",
231
+ addresses: ordered,
202
232
  port: srv.record.data.port,
203
233
  capabilities,
204
234
  isGroup: (capabilities & 32) !== 0,
@@ -2,6 +2,7 @@ import dgram from "node:dgram";
2
2
  import type { MdnsSocket, MdnsSocketHandlers, NetworkInterfaceInfo } from "./cast-discovery.ts";
3
3
 
4
4
  export const MDNS_GROUP = "224.0.0.251";
5
+ export const MDNS_GROUP_V6 = "ff02::fb";
5
6
  export const MDNS_PORT = 5353;
6
7
 
7
8
  type CreateSocket = (options: dgram.SocketOptions) => dgram.Socket;
@@ -42,12 +43,13 @@ function makeSocket(
42
43
  socket: dgram.Socket,
43
44
  handlers: MdnsSocketHandlers,
44
45
  mode: "multicast" | "unicast",
46
+ group: string,
45
47
  ): MdnsSocket & { mode: "multicast" | "unicast" } {
46
48
  let closed = false;
47
49
  return {
48
50
  mode,
49
51
  send(packet: Buffer): void {
50
- socket.send(packet, MDNS_PORT, MDNS_GROUP, (error) => {
52
+ socket.send(packet, MDNS_PORT, group, (error) => {
51
53
  if (error) handlers.error(error);
52
54
  });
53
55
  },
@@ -84,7 +86,7 @@ async function setupMulticast(
84
86
  throw error;
85
87
  }
86
88
  attach(socket, handlers);
87
- return makeSocket(socket, handlers, "multicast");
89
+ return makeSocket(socket, handlers, "multicast", MDNS_GROUP);
88
90
  }
89
91
 
90
92
  /** mDNS legacy unicast: bind an ephemeral port on the interface; responders answer straight back. */
@@ -107,15 +109,72 @@ async function setupUnicast(
107
109
  throw error;
108
110
  }
109
111
  attach(socket, handlers);
110
- return makeSocket(socket, handlers, "unicast");
112
+ return makeSocket(socket, handlers, "unicast", MDNS_GROUP);
111
113
  }
112
114
 
113
- /** Opens an mDNS socket on one interface: multicast on port 5353 if possible, else a unicast socket. */
115
+ /** An IPv6 interface address with its zone, e.g. `fe80::1%12`: link-local addresses are ambiguous without one. */
116
+ function scoped(iface: NetworkInterfaceInfo): string {
117
+ return iface.scopeId === undefined ? iface.address : `${iface.address}%${iface.scopeId}`;
118
+ }
119
+
120
+ async function setupMulticast6(
121
+ create: CreateSocket,
122
+ iface: NetworkInterfaceInfo,
123
+ handlers: MdnsSocketHandlers,
124
+ ): Promise<MdnsSocket & { mode: "multicast" | "unicast" }> {
125
+ const socket = create({ type: "udp6", reuseAddr: true, ipv6Only: true });
126
+ try {
127
+ await waitForBind(socket, { port: MDNS_PORT, exclusive: false });
128
+ socket.addMembership(MDNS_GROUP_V6, scoped(iface));
129
+ socket.setMulticastInterface(`::%${iface.scopeId ?? iface.name}`);
130
+ socket.setMulticastTTL(255);
131
+ socket.setMulticastLoopback(false);
132
+ } catch (error) {
133
+ try {
134
+ socket.close();
135
+ } catch {
136
+ // already closed
137
+ }
138
+ throw error;
139
+ }
140
+ attach(socket, handlers);
141
+ return makeSocket(socket, handlers, "multicast", MDNS_GROUP_V6);
142
+ }
143
+
144
+ async function setupUnicast6(
145
+ create: CreateSocket,
146
+ iface: NetworkInterfaceInfo,
147
+ handlers: MdnsSocketHandlers,
148
+ ): Promise<MdnsSocket & { mode: "multicast" | "unicast" }> {
149
+ const socket = create({ type: "udp6", ipv6Only: true });
150
+ try {
151
+ await waitForBind(socket, { port: 0, address: scoped(iface) });
152
+ socket.setMulticastInterface(`::%${iface.scopeId ?? iface.name}`);
153
+ socket.setMulticastTTL(255);
154
+ } catch (error) {
155
+ try {
156
+ socket.close();
157
+ } catch {
158
+ // already closed
159
+ }
160
+ throw error;
161
+ }
162
+ attach(socket, handlers);
163
+ return makeSocket(socket, handlers, "unicast", MDNS_GROUP_V6);
164
+ }
165
+
166
+ /**
167
+ * Opens an mDNS socket on one interface: multicast on port 5353 if possible, else a unicast socket. An IPv6
168
+ * interface (`family: "IPv6"`) uses ff02::fb on that interface's scope.
169
+ */
114
170
  export function openUdpMdnsSocket(
115
171
  iface: NetworkInterfaceInfo,
116
172
  handlers: MdnsSocketHandlers,
117
173
  options?: { createSocket?: CreateSocket },
118
174
  ): Promise<MdnsSocket & { mode: "multicast" | "unicast" }> {
119
175
  const create = options?.createSocket ?? ((opts: dgram.SocketOptions) => dgram.createSocket(opts));
176
+ if (iface.family === "IPv6") {
177
+ return setupMulticast6(create, iface, handlers).catch(() => setupUnicast6(create, iface, handlers));
178
+ }
120
179
  return setupMulticast(create, iface, handlers).catch(() => setupUnicast(create, iface, handlers));
121
180
  }