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
@@ -0,0 +1,488 @@
1
+ import { constants, createPublicKey, verify as cryptoVerify, type KeyObject } from "node:crypto";
2
+ import {
3
+ children,
4
+ contextTag,
5
+ DerError,
6
+ DerReader,
7
+ oidString,
8
+ parseBitString,
9
+ parseBoolean,
10
+ parseTime,
11
+ parseUnsignedInteger,
12
+ Tag,
13
+ type Tlv,
14
+ } from "./der.ts";
15
+ import { type GeneralNames, NameConstraints, normalizeName, type NormalizedName, parseGeneralNames, namesEqual } from "./names.ts";
16
+
17
+ /**
18
+ * X.509 parsing for the Cast certificate verifier. It follows BoringSSL's pki library (pki/parse_certificate.cc,
19
+ * pki/parsed_certificate.cc, pki/signature_algorithm.cc, pki/verify_signed_data.cc), which Chromium's Cast
20
+ * verification runs on. Node exposes none of the extensions that matter here (key usage bits, policies,
21
+ * name constraints, path length), hence the parser.
22
+ */
23
+
24
+ export class CertParseError extends Error {
25
+ constructor(message: string, options?: { cause?: unknown }) {
26
+ super(message, options);
27
+ this.name = "CertParseError";
28
+ }
29
+ }
30
+
31
+ export const OID = {
32
+ BASIC_CONSTRAINTS: "2.5.29.19",
33
+ KEY_USAGE: "2.5.29.15",
34
+ EXT_KEY_USAGE: "2.5.29.37",
35
+ NAME_CONSTRAINTS: "2.5.29.30",
36
+ SUBJECT_ALT_NAME: "2.5.29.17",
37
+ CERTIFICATE_POLICIES: "2.5.29.32",
38
+ POLICY_MAPPINGS: "2.5.29.33",
39
+ POLICY_CONSTRAINTS: "2.5.29.36",
40
+ INHIBIT_ANY_POLICY: "2.5.29.54",
41
+ MS_APPLICATION_POLICIES: "1.3.6.1.4.1.311.21.10",
42
+ ANY_POLICY: "2.5.29.32.0",
43
+ ANY_EKU: "2.5.29.37.0",
44
+ CLIENT_AUTH: "1.3.6.1.5.5.7.3.2",
45
+ COMMON_NAME: "2.5.4.3",
46
+ /** The Cast audio-only policy, 1.3.6.1.4.1.11129.2.5.2 (cast_cert_validator.cc, AudioOnlyPolicyOid). */
47
+ CAST_AUDIO_ONLY_POLICY: "1.3.6.1.4.1.11129.2.5.2",
48
+ } as const;
49
+
50
+ export const KEY_USAGE_BIT = { DIGITAL_SIGNATURE: 0, KEY_CERT_SIGN: 5 } as const;
51
+
52
+ // --- Signature algorithms -------------------------------------------------------------------------------------
53
+
54
+ export type HashName = "sha1" | "sha256" | "sha384" | "sha512";
55
+
56
+ export interface SignatureAlgorithm {
57
+ family: "rsa-pkcs1" | "ecdsa" | "rsa-pss";
58
+ hash: HashName;
59
+ }
60
+
61
+ const SIGNATURE_OIDS: Record<string, { family: SignatureAlgorithm["family"]; hash: HashName; params: "null-or-absent" | "absent" }> = {
62
+ "1.2.840.113549.1.1.5": { family: "rsa-pkcs1", hash: "sha1", params: "null-or-absent" },
63
+ "1.2.840.113549.1.1.11": { family: "rsa-pkcs1", hash: "sha256", params: "null-or-absent" },
64
+ "1.2.840.113549.1.1.12": { family: "rsa-pkcs1", hash: "sha384", params: "null-or-absent" },
65
+ "1.2.840.113549.1.1.13": { family: "rsa-pkcs1", hash: "sha512", params: "null-or-absent" },
66
+ // sha1WithRSASignature, an older OID for the same algorithm that BoringSSL also accepts.
67
+ "1.3.14.3.2.29": { family: "rsa-pkcs1", hash: "sha1", params: "null-or-absent" },
68
+ "1.2.840.10045.4.1": { family: "ecdsa", hash: "sha1", params: "absent" },
69
+ "1.2.840.10045.4.3.2": { family: "ecdsa", hash: "sha256", params: "absent" },
70
+ "1.2.840.10045.4.3.3": { family: "ecdsa", hash: "sha384", params: "absent" },
71
+ "1.2.840.10045.4.3.4": { family: "ecdsa", hash: "sha512", params: "absent" },
72
+ };
73
+ const OID_RSASSA_PSS = "1.2.840.113549.1.1.10";
74
+ const OID_MGF1 = "1.2.840.113549.1.1.8";
75
+ const HASH_OIDS: Record<string, HashName> = {
76
+ "1.3.14.3.2.26": "sha1",
77
+ "2.16.840.1.101.3.4.2.1": "sha256",
78
+ "2.16.840.1.101.3.4.2.2": "sha384",
79
+ "2.16.840.1.101.3.4.2.3": "sha512",
80
+ };
81
+ const PSS_SALT: Record<HashName, number> = { sha1: 20, sha256: 32, sha384: 48, sha512: 64 };
82
+
83
+ /** ParseAlgorithmIdentifier: the OID and the parameters TLV, if any. */
84
+ function parseAlgorithmIdentifier(tlv: Tlv): { oid: string; params: Tlv | undefined } | undefined {
85
+ try {
86
+ if (tlv.tag !== Tag.SEQUENCE) return undefined;
87
+ const r = new DerReader(tlv.value);
88
+ const oid = oidString(r.expect(Tag.OID).value);
89
+ const params = r.hasMore ? r.read() : undefined;
90
+ r.end();
91
+ return { oid, params };
92
+ } catch {
93
+ return undefined;
94
+ }
95
+ }
96
+
97
+ const isNull = (t: Tlv | undefined): boolean => t !== undefined && t.tag === Tag.NULL && t.value.length === 0;
98
+
99
+ function parseHashAlgorithm(tlv: Tlv): HashName | undefined {
100
+ const alg = parseAlgorithmIdentifier(tlv);
101
+ if (alg === undefined) return undefined;
102
+ if (alg.params !== undefined && !isNull(alg.params)) return undefined;
103
+ return HASH_OIDS[alg.oid];
104
+ }
105
+
106
+ function parseRsaPss(params: Tlv | undefined): SignatureAlgorithm | undefined {
107
+ if (params === undefined || params.tag !== Tag.SEQUENCE) return undefined;
108
+ try {
109
+ const r = new DerReader(params.value);
110
+ const hash = parseHashAlgorithm(new DerReader(r.expect(contextTag(0, true)).value).read());
111
+ const mgf = parseAlgorithmIdentifier(new DerReader(r.expect(contextTag(1, true)).value).read());
112
+ const saltReader = new DerReader(r.expect(contextTag(2, true)).value);
113
+ const salt = parseUnsignedInteger(saltReader.read());
114
+ saltReader.end();
115
+ r.end();
116
+ if (hash === undefined || mgf === undefined || mgf.oid !== OID_MGF1 || mgf.params === undefined) return undefined;
117
+ if (parseHashAlgorithm(mgf.params) !== hash) return undefined;
118
+ if (hash === "sha1" || salt !== BigInt(PSS_SALT[hash])) return undefined;
119
+ return { family: "rsa-pss", hash };
120
+ } catch {
121
+ return undefined;
122
+ }
123
+ }
124
+
125
+ /** ParseSignatureAlgorithm. */
126
+ export function parseSignatureAlgorithm(tlv: Tlv): SignatureAlgorithm | undefined {
127
+ const alg = parseAlgorithmIdentifier(tlv);
128
+ if (alg === undefined) return undefined;
129
+ const entry = SIGNATURE_OIDS[alg.oid];
130
+ if (entry !== undefined) {
131
+ const ok = entry.params === "absent" ? alg.params === undefined : alg.params === undefined || isNull(alg.params);
132
+ return ok ? { family: entry.family, hash: entry.hash } : undefined;
133
+ }
134
+ if (alg.oid === OID_RSASSA_PSS) return parseRsaPss(alg.params);
135
+ return undefined;
136
+ }
137
+
138
+ export const sameSignatureAlgorithm = (a: SignatureAlgorithm, b: SignatureAlgorithm): boolean => a.family === b.family && a.hash === b.hash;
139
+
140
+ /** VerifySignedData: false for any mismatch between the algorithm and the key. */
141
+ export function verifySignedData(alg: SignatureAlgorithm, data: Uint8Array, signature: Uint8Array, key: KeyObject): boolean {
142
+ try {
143
+ if (alg.family === "ecdsa") {
144
+ if (key.asymmetricKeyType !== "ec") return false;
145
+ return cryptoVerify(alg.hash, data, key, signature);
146
+ }
147
+ if (key.asymmetricKeyType !== "rsa") return false;
148
+ if (alg.family === "rsa-pkcs1") return cryptoVerify(alg.hash, data, key, signature);
149
+ return cryptoVerify(
150
+ alg.hash,
151
+ data,
152
+ { key, padding: constants.RSA_PKCS1_PSS_PADDING, saltLength: PSS_SALT[alg.hash] },
153
+ signature,
154
+ );
155
+ } catch {
156
+ return false;
157
+ }
158
+ }
159
+
160
+ // --- Certificates ---------------------------------------------------------------------------------------------
161
+
162
+ export interface PolicyMapping {
163
+ issuerDomainPolicy: string;
164
+ subjectDomainPolicy: string;
165
+ }
166
+
167
+ export interface Extension {
168
+ oid: string;
169
+ critical: boolean;
170
+ value: Buffer;
171
+ }
172
+
173
+ export interface ParsedCertificate {
174
+ der: Buffer;
175
+ version: 1 | 2 | 3;
176
+ tbsTlv: Buffer;
177
+ tbsSignatureAlgorithmTlv: Buffer;
178
+ signatureAlgorithmTlv: Buffer;
179
+ /** Undefined when the algorithm is not one BoringSSL recognizes. */
180
+ signatureAlgorithm: SignatureAlgorithm | undefined;
181
+ signatureValue: Buffer;
182
+ /** The serial number's content octets. */
183
+ serial: Buffer;
184
+ issuerContent: Buffer;
185
+ subjectContent: Buffer;
186
+ normalizedIssuer: NormalizedName;
187
+ normalizedSubject: NormalizedName;
188
+ /** Epoch milliseconds. */
189
+ notBefore: number;
190
+ notAfter: number;
191
+ spkiTlv: Buffer;
192
+ extensions: Map<string, Extension>;
193
+ basicConstraints: { isCa: boolean; pathLen: number | undefined } | undefined;
194
+ keyUsage: { bytes: Buffer; unusedBits: number } | undefined;
195
+ extendedKeyUsage: string[] | undefined;
196
+ policyOids: string[] | undefined;
197
+ policyMappings: PolicyMapping[] | undefined;
198
+ policyConstraints: { requireExplicitPolicy: number | undefined; inhibitPolicyMapping: number | undefined } | undefined;
199
+ inhibitAnyPolicy: number | undefined;
200
+ nameConstraints: NameConstraints | undefined;
201
+ subjectAltNames: GeneralNames | undefined;
202
+ /** The common name from the subject, if present. */
203
+ commonName: string | undefined;
204
+ }
205
+
206
+ const CPS_QUALIFIER_OID = "1.3.6.1.5.5.7.2.1";
207
+ const USER_NOTICE_QUALIFIER_OID = "1.3.6.1.5.5.7.2.2";
208
+
209
+ function fail(message: string): never {
210
+ throw new CertParseError(message);
211
+ }
212
+
213
+ /**
214
+ * ParseCertificatePoliciesExtensionOids. With `strictQualifiers`, a qualifier other than CPS or User Notice is an
215
+ * error: that is how BoringSSL decides whether a critical certificatePolicies extension is "handled".
216
+ */
217
+ function parsePolicyOids(value: Buffer, strictQualifiers: boolean): string[] {
218
+ const r = new DerReader(value);
219
+ const seq = r.expect(Tag.SEQUENCE);
220
+ r.end();
221
+ const infos = children(seq);
222
+ if (infos.length === 0) throw new DerError("certificatePolicies is empty");
223
+ const oids: string[] = [];
224
+ for (const info of infos) {
225
+ const ir = new DerReader(info.value);
226
+ if (info.tag !== Tag.SEQUENCE) throw new DerError("bad PolicyInformation");
227
+ const oid = oidString(ir.expect(Tag.OID).value);
228
+ if (oids.includes(oid)) throw new DerError("duplicate policy OID");
229
+ oids.push(oid);
230
+ if (ir.hasMore) {
231
+ const qualifiers = children(ir.expect(Tag.SEQUENCE));
232
+ for (const q of qualifiers) {
233
+ if (q.tag !== Tag.SEQUENCE) throw new DerError("bad PolicyQualifierInfo");
234
+ const qr = new DerReader(q.value);
235
+ const qid = oidString(qr.expect(Tag.OID).value);
236
+ qr.read();
237
+ qr.end();
238
+ if (strictQualifiers && qid !== CPS_QUALIFIER_OID && qid !== USER_NOTICE_QUALIFIER_OID) throw new DerError("unknown policy qualifier");
239
+ }
240
+ }
241
+ ir.end();
242
+ }
243
+ return oids;
244
+ }
245
+
246
+ /** Whether a critical certificatePolicies extension counts as handled (only known qualifiers). */
247
+ export function criticalPoliciesHandled(value: Buffer): boolean {
248
+ try {
249
+ parsePolicyOids(value, true);
250
+ return true;
251
+ } catch {
252
+ return false;
253
+ }
254
+ }
255
+
256
+ const uint8 = (tlv: Tlv): number => {
257
+ const v = parseUnsignedInteger(tlv);
258
+ if (v > 255n) throw new DerError("value exceeds uint8");
259
+ return Number(v);
260
+ };
261
+
262
+ function parseExtensions(tlv: Tlv): Map<string, Extension> {
263
+ const out = new Map<string, Extension>();
264
+ const seq = new DerReader(tlv.value).expect(Tag.SEQUENCE);
265
+ const items = children(seq);
266
+ if (items.length === 0) throw new DerError("empty extensions");
267
+ for (const item of items) {
268
+ if (item.tag !== Tag.SEQUENCE) throw new DerError("bad Extension");
269
+ const r = new DerReader(item.value);
270
+ const oid = oidString(r.expect(Tag.OID).value);
271
+ let critical = false;
272
+ const crit = r.optional(Tag.BOOLEAN);
273
+ if (crit !== undefined) {
274
+ critical = parseBoolean(crit);
275
+ if (!critical) throw new DerError("DEFAULT critical value must be omitted");
276
+ }
277
+ const value = r.expect(Tag.OCTET_STRING).value;
278
+ r.end();
279
+ if (out.has(oid)) throw new DerError("duplicate extension");
280
+ out.set(oid, { oid, critical, value });
281
+ }
282
+ return out;
283
+ }
284
+
285
+ /** ParsedCertificate::Create. Throws {@link CertParseError}. */
286
+ export function parseCertificate(der: Uint8Array): ParsedCertificate {
287
+ try {
288
+ return parseCertificateInner(Buffer.from(der.buffer, der.byteOffset, der.byteLength));
289
+ } catch (err) {
290
+ if (err instanceof CertParseError) throw err;
291
+ throw new CertParseError(err instanceof Error ? err.message : String(err), { cause: err });
292
+ }
293
+ }
294
+
295
+ function parseCertificateInner(der: Buffer): ParsedCertificate {
296
+ const top = new DerReader(der);
297
+ const cert = top.expect(Tag.SEQUENCE);
298
+ top.end();
299
+ const cr = new DerReader(cert.value);
300
+ const tbs = cr.expect(Tag.SEQUENCE);
301
+ const sigAlg = cr.read();
302
+ const sigBits = parseBitString(cr.expect(Tag.BIT_STRING));
303
+ cr.end();
304
+ if (sigBits.unusedBits !== 0) fail("signature BIT STRING has unused bits");
305
+
306
+ const t = new DerReader(tbs.value);
307
+ let version: 1 | 2 | 3 = 1;
308
+ const v = t.optional(contextTag(0, true));
309
+ if (v !== undefined) {
310
+ const vr = new DerReader(v.value);
311
+ const n = vr.read();
312
+ vr.end();
313
+ // INTEGER 0, 1 or 2; an explicit v1 is not DER (DEFAULT must be omitted).
314
+ if (n.tag !== Tag.INTEGER || n.value.length !== 1) fail("bad version");
315
+ const num = n.value[0] as number;
316
+ if (num !== 1 && num !== 2) fail("unsupported version");
317
+ version = (num + 1) as 2 | 3;
318
+ }
319
+ const serial = t.expect(Tag.INTEGER);
320
+ if (serial.value.length === 0 || serial.value.length > 21) fail("bad serial number");
321
+ const tbsSigAlg = t.read();
322
+ const issuer = t.expect(Tag.SEQUENCE);
323
+ const validity = new DerReader(t.expect(Tag.SEQUENCE).value);
324
+ const notBefore = parseTime(validity.read());
325
+ const notAfter = parseTime(validity.read());
326
+ validity.end();
327
+ const subject = t.expect(Tag.SEQUENCE);
328
+ const spki = t.expect(Tag.SEQUENCE);
329
+ if (version >= 2) {
330
+ t.optional(contextTag(1, false));
331
+ t.optional(contextTag(2, false));
332
+ }
333
+ const extTlv = version === 3 ? t.optional(contextTag(3, true)) : undefined;
334
+ t.end();
335
+
336
+ const extensions = extTlv === undefined ? new Map<string, Extension>() : parseExtensions(extTlv);
337
+ const out: ParsedCertificate = {
338
+ der,
339
+ version,
340
+ tbsTlv: tbs.raw,
341
+ tbsSignatureAlgorithmTlv: tbsSigAlg.raw,
342
+ signatureAlgorithmTlv: sigAlg.raw,
343
+ signatureAlgorithm: parseSignatureAlgorithm(sigAlg),
344
+ signatureValue: sigBits.bytes,
345
+ serial: serial.value,
346
+ issuerContent: issuer.value,
347
+ subjectContent: subject.value,
348
+ normalizedIssuer: normalizeName(issuer.value),
349
+ normalizedSubject: normalizeName(subject.value),
350
+ notBefore,
351
+ notAfter,
352
+ spkiTlv: spki.raw,
353
+ extensions,
354
+ basicConstraints: undefined,
355
+ keyUsage: undefined,
356
+ extendedKeyUsage: undefined,
357
+ policyOids: undefined,
358
+ policyMappings: undefined,
359
+ policyConstraints: undefined,
360
+ inhibitAnyPolicy: undefined,
361
+ nameConstraints: undefined,
362
+ subjectAltNames: undefined,
363
+ commonName: undefined,
364
+ };
365
+
366
+ const ext = (oid: string) => extensions.get(oid);
367
+ const bc = ext(OID.BASIC_CONSTRAINTS);
368
+ if (bc !== undefined) {
369
+ const r = new DerReader(new DerReader(bc.value).expect(Tag.SEQUENCE).value);
370
+ const ca = r.optional(Tag.BOOLEAN);
371
+ const isCa = ca === undefined ? false : parseBoolean(ca);
372
+ const pl = r.optional(Tag.INTEGER);
373
+ r.end();
374
+ out.basicConstraints = { isCa, pathLen: pl === undefined ? undefined : uint8(pl) };
375
+ }
376
+ const ku = ext(OID.KEY_USAGE);
377
+ if (ku !== undefined) {
378
+ const r = new DerReader(ku.value);
379
+ const bits = parseBitString(r.expect(Tag.BIT_STRING));
380
+ r.end();
381
+ if (bits.bytes.every((b) => b === 0)) fail("key usage asserts no bits");
382
+ out.keyUsage = bits;
383
+ }
384
+ const eku = ext(OID.EXT_KEY_USAGE);
385
+ if (eku !== undefined) {
386
+ const r = new DerReader(eku.value);
387
+ const items = children(r.expect(Tag.SEQUENCE));
388
+ r.end();
389
+ if (items.length === 0) fail("empty extendedKeyUsage");
390
+ out.extendedKeyUsage = items.map((i) => {
391
+ if (i.tag !== Tag.OID) fail("bad extendedKeyUsage");
392
+ return oidString(i.value);
393
+ });
394
+ }
395
+ const san = ext(OID.SUBJECT_ALT_NAME);
396
+ if (san !== undefined) out.subjectAltNames = parseGeneralNames(san.value);
397
+ const nc = ext(OID.NAME_CONSTRAINTS);
398
+ if (nc !== undefined) out.nameConstraints = NameConstraints.parse(nc.value, nc.critical);
399
+ const pol = ext(OID.CERTIFICATE_POLICIES);
400
+ if (pol !== undefined) out.policyOids = parsePolicyOids(pol.value, false);
401
+ const pm = ext(OID.POLICY_MAPPINGS);
402
+ if (pm !== undefined) {
403
+ const r = new DerReader(pm.value);
404
+ const items = children(r.expect(Tag.SEQUENCE));
405
+ r.end();
406
+ if (items.length === 0) fail("empty policyMappings");
407
+ out.policyMappings = items.map((i) => {
408
+ const ir = new DerReader(i.value);
409
+ const issuerDomainPolicy = oidString(ir.expect(Tag.OID).value);
410
+ const subjectDomainPolicy = oidString(ir.expect(Tag.OID).value);
411
+ ir.end();
412
+ return { issuerDomainPolicy, subjectDomainPolicy };
413
+ });
414
+ }
415
+ const pc = ext(OID.POLICY_CONSTRAINTS);
416
+ if (pc !== undefined) {
417
+ const r = new DerReader(new DerReader(pc.value).expect(Tag.SEQUENCE).value);
418
+ const req = r.optional(0x80);
419
+ const inh = r.optional(0x81);
420
+ r.end();
421
+ if (req === undefined && inh === undefined) fail("empty policyConstraints");
422
+ const implicit = (x: Tlv | undefined): number | undefined => (x === undefined ? undefined : uint8({ tag: Tag.INTEGER, value: x.value, raw: x.raw }));
423
+ out.policyConstraints = { requireExplicitPolicy: implicit(req), inhibitPolicyMapping: implicit(inh) };
424
+ }
425
+ const iap = ext(OID.INHIBIT_ANY_POLICY);
426
+ if (iap !== undefined) {
427
+ const r = new DerReader(iap.value);
428
+ out.inhibitAnyPolicy = uint8(r.expect(Tag.INTEGER));
429
+ r.end();
430
+ }
431
+
432
+ // The subject's common name: the first CN attribute (GetCommonNameFromSubject in cast_cert_validator.cc).
433
+ out.commonName = firstCommonName(subject.value);
434
+ return out;
435
+ }
436
+
437
+ function firstCommonName(nameContent: Buffer): string | undefined {
438
+ try {
439
+ const r = new DerReader(nameContent);
440
+ while (r.hasMore) {
441
+ for (const ava of children(r.expect(Tag.SET))) {
442
+ const ar = new DerReader(ava.value);
443
+ const oid = oidString(ar.expect(Tag.OID).value);
444
+ const value = ar.read();
445
+ if (oid === OID.COMMON_NAME) {
446
+ if (value.tag === Tag.BMP_STRING) return Buffer.from(value.value).swap16().toString("utf16le");
447
+ return value.value.toString("utf8");
448
+ }
449
+ }
450
+ }
451
+ } catch {
452
+ return undefined;
453
+ }
454
+ return undefined;
455
+ }
456
+
457
+ export const isSelfIssued = (cert: ParsedCertificate): boolean => namesEqual(cert.normalizedSubject, cert.normalizedIssuer);
458
+
459
+ export function keyUsageAsserts(ku: { bytes: Buffer }, bit: number): boolean {
460
+ const byte = ku.bytes[bit >> 3];
461
+ return byte !== undefined && (byte & (0x80 >> (bit & 7))) !== 0;
462
+ }
463
+
464
+ // --- Public keys ----------------------------------------------------------------------------------------------
465
+
466
+ const ACCEPTABLE_EC_CURVES = new Set(["prime256v1", "secp384r1", "secp521r1"]);
467
+
468
+ /**
469
+ * SimplePathBuilderDelegate::IsPublicKeyAcceptable as Chromium's CastPathBuilderDelegate configures it: RSA keys of at
470
+ * least `minRsaBits` bits, or ECDSA keys on P-256, P-384 or P-521.
471
+ */
472
+ export function parseAcceptablePublicKey(spkiTlv: Buffer, minRsaBits = 2048): KeyObject | undefined {
473
+ let key: KeyObject;
474
+ try {
475
+ key = createPublicKey({ key: spkiTlv, format: "der", type: "spki" });
476
+ } catch {
477
+ return undefined;
478
+ }
479
+ if (key.asymmetricKeyType === "rsa") {
480
+ const bits = key.asymmetricKeyDetails?.modulusLength;
481
+ return bits !== undefined && bits >= minRsaBits ? key : undefined;
482
+ }
483
+ if (key.asymmetricKeyType === "ec") {
484
+ const curve = key.asymmetricKeyDetails?.namedCurve;
485
+ return curve !== undefined && ACCEPTABLE_EC_CURVES.has(curve) ? key : undefined;
486
+ }
487
+ return undefined;
488
+ }
@@ -5,7 +5,9 @@ import type { TLSSocket } from "node:tls";
5
5
  import { decodeCastMessage, encodeCastMessage, frame, FrameDecoder, PayloadType } from "../protocol/index.ts";
6
6
  import type { CastMessage } from "../protocol/index.ts";
7
7
  import { NS, PLATFORM_RECEIVER_ID } from "./namespaces.ts";
8
- import { CastConnectionError, CastRequestError, CastTimeoutError } from "./errors.ts";
8
+ import { CastAuthError, CastConnectionError, CastRequestError, CastTimeoutError } from "./errors.ts";
9
+ import { authenticateChallengeReply, createAuthChallenge } from "./auth/cast-auth.ts";
10
+ import type { DeviceAuthOptions, DeviceAuthResult } from "./auth/cast-auth.ts";
9
11
  import type { ReceiverApplication, ReceiverStatus, ReceiverVolume } from "./types.ts";
10
12
 
11
13
  /** Options for {@link CastClient}. */
@@ -20,6 +22,16 @@ export interface CastClientOptions {
20
22
  heartbeatTimeoutMs?: number;
21
23
  tls?: Omit<tls.ConnectionOptions, "host" | "port">;
22
24
  connectPayload?: Record<string, unknown>;
25
+ /**
26
+ * Verify the device is a genuine Google-certified Cast device before use, as Chrome does (default true). A device
27
+ * that fails makes {@link CastClient.connect} reject with a {@link CastAuthError}. Set false to talk to
28
+ * uncertified receivers such as open-source ones.
29
+ */
30
+ verifyDevice?: boolean;
31
+ /** How long to wait for the device's authentication reply after the TLS handshake. Default 10000. */
32
+ authTimeoutMs?: number;
33
+ /** Trust roots and clock overrides for device authentication; for tests and private Cast deployments. */
34
+ deviceAuth?: DeviceAuthOptions;
23
35
  }
24
36
 
25
37
  /** Events emitted by {@link CastClient}. */
@@ -84,6 +96,10 @@ export class CastClient extends EventEmitter<CastClientEvents> {
84
96
  private heartbeatTimer: NodeJS.Timeout | null = null;
85
97
  private livenessTimer: NodeJS.Timeout | null = null;
86
98
  private connectTimer: NodeJS.Timeout | null = null;
99
+ private authNonce: Buffer | null = null;
100
+ private authPeerCert: Buffer | null = null;
101
+ private authResult: DeviceAuthResult | undefined;
102
+ private authFinish: ((err?: Error) => void) | null = null;
87
103
 
88
104
  constructor(options: CastClientOptions) {
89
105
  super();
@@ -96,7 +112,12 @@ export class CastClient extends EventEmitter<CastClientEvents> {
96
112
  return this.state === "connected";
97
113
  }
98
114
 
99
- /** Open the TLS connection and send CONNECT to the platform receiver. */
115
+ /** What device authentication established; undefined when it did not run (verifyDevice false). */
116
+ get deviceAuth(): DeviceAuthResult | undefined {
117
+ return this.authResult;
118
+ }
119
+
120
+ /** Open the TLS connection, authenticate the device (unless disabled) and send CONNECT to the platform receiver. */
100
121
  connect(): Promise<void> {
101
122
  if (this.state !== "idle") {
102
123
  return Promise.reject(new CastConnectionError(`cannot connect: client is ${this.state}`));
@@ -136,7 +157,26 @@ export class CastClient extends EventEmitter<CastClientEvents> {
136
157
 
137
158
  socket.on("secureConnect", () => {
138
159
  socket.on("data", (chunk: Buffer) => this.onData(chunk));
139
- settle();
160
+ if (this.options.verifyDevice === false) {
161
+ settle();
162
+ return;
163
+ }
164
+ const peer = socket.getPeerCertificate(false) as { raw?: Buffer };
165
+ if (peer.raw === undefined || peer.raw.length === 0) {
166
+ settle(new CastAuthError("no_tls_certificate", "the device presented no TLS certificate", { host }));
167
+ return;
168
+ }
169
+ const challenge = createAuthChallenge();
170
+ this.authNonce = challenge.nonce;
171
+ this.authPeerCert = peer.raw;
172
+ this.authFinish = settle;
173
+ // The TLS handshake timer is replaced by one for the authentication reply.
174
+ if (this.connectTimer !== null) clearTimeout(this.connectTimer);
175
+ const authTimeoutMs = this.options.authTimeoutMs ?? 10000;
176
+ this.connectTimer = setTimeout(() => {
177
+ settle(new CastAuthError("timeout", `no authentication reply within ${authTimeoutMs} ms`, { host }));
178
+ }, authTimeoutMs);
179
+ this.write(buildMessage("sender-0", NS.DEVICE_AUTH, PLATFORM_RECEIVER_ID, challenge.payload));
140
180
  });
141
181
  socket.on("error", (err: Error) => {
142
182
  if (this.state === "connecting") {
@@ -280,6 +320,10 @@ export class CastClient extends EventEmitter<CastClientEvents> {
280
320
  }
281
321
 
282
322
  private onData(chunk: Buffer): void {
323
+ if (this.state === "connecting" && this.authFinish !== null) {
324
+ this.onAuthData(chunk);
325
+ return;
326
+ }
283
327
  if (this.state !== "connected") return;
284
328
  this.resetLiveness();
285
329
  let bodies: Buffer[];
@@ -302,6 +346,44 @@ export class CastClient extends EventEmitter<CastClientEvents> {
302
346
  }
303
347
  }
304
348
 
349
+ /** Frames received while the device is still being authenticated: only its deviceauth reply is acceptable. */
350
+ private onAuthData(chunk: Buffer): void {
351
+ const finish = this.authFinish as (err?: Error) => void;
352
+ const host = this.options.host;
353
+ let bodies: Buffer[];
354
+ try {
355
+ bodies = this.decoder.push(chunk);
356
+ } catch (err) {
357
+ finish(new CastAuthError("malformed_reply", `protocol error: ${describe(err)}`, { host }));
358
+ return;
359
+ }
360
+ for (const body of bodies) {
361
+ let msg: CastMessage;
362
+ try {
363
+ msg = decodeCastMessage(body);
364
+ } catch (err) {
365
+ finish(new CastAuthError("malformed_reply", `protocol error: ${describe(err)}`, { host }));
366
+ return;
367
+ }
368
+ if (msg.namespace !== NS.DEVICE_AUTH) continue;
369
+ try {
370
+ this.authResult = authenticateChallengeReply(
371
+ { payloadType: msg.payloadType, payloadBinary: msg.payloadBinary },
372
+ this.authPeerCert as Buffer,
373
+ this.authNonce as Buffer,
374
+ this.options.deviceAuth,
375
+ );
376
+ } catch (err) {
377
+ if (err instanceof CastAuthError) finish(new CastAuthError(err.reason, err.message.replace(/^Cast device authentication failed: /, ""), { host }));
378
+ else finish(err instanceof Error ? err : new Error(String(err)));
379
+ return;
380
+ }
381
+ this.authFinish = null;
382
+ finish();
383
+ return;
384
+ }
385
+ }
386
+
305
387
  private handleMessage(msg: CastMessage): void {
306
388
  if (msg.namespace === NS.HEARTBEAT) {
307
389
  if (this.jsonType(msg) === "PING") this.sendJson(NS.HEARTBEAT, msg.sourceId, { type: "PONG" });
@@ -30,3 +30,32 @@ export class CastRequestError extends Error {
30
30
  this.response = response;
31
31
  }
32
32
  }
33
+
34
+ /** Why a device failed authentication; see {@link CastAuthError}. */
35
+ export type CastAuthReason =
36
+ | "timeout"
37
+ | "no_tls_certificate"
38
+ | "tls_certificate_invalid"
39
+ | "device_error"
40
+ | "malformed_reply"
41
+ | "unsupported_algorithm"
42
+ | "invalid_certificate"
43
+ | "untrusted_chain"
44
+ | "revoked"
45
+ | "crl_invalid"
46
+ | "bad_signature";
47
+
48
+ /** The device did not prove it is a genuine, Google-certified Cast device, so it was not used. */
49
+ export class CastAuthError extends Error {
50
+ readonly reason: CastAuthReason;
51
+ /** The device's address, when the client added it. */
52
+ readonly host: string | undefined;
53
+
54
+ constructor(reason: CastAuthReason, detail: string, options?: { host?: string }) {
55
+ const where = options?.host === undefined ? "" : ` for ${options.host}`;
56
+ super(`Cast device authentication failed${where}: ${detail}`);
57
+ this.name = "CastAuthError";
58
+ this.reason = reason;
59
+ this.host = options?.host;
60
+ }
61
+ }
@@ -2,3 +2,5 @@ export * from "./namespaces.ts";
2
2
  export * from "./errors.ts";
3
3
  export * from "./types.ts";
4
4
  export * from "./cast-client.ts";
5
+ export type { DeviceAuthOptions, DeviceAuthResult } from "./auth/cast-auth.ts";
6
+ export type { CastCertError, CastDeviceCertPolicy } from "./auth/cast-cert-validator.ts";