Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 7.6 KiBRawPermalink
1import * as crypto from "crypto";
2import * as fs from "fs";
3import * as os from "os";
4import * as path from "path";
5import * as plist from "plist";
6
7export interface MdmKeys {
8 licenseKey: string;
9 apiUrl: string;
10}
11
12const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
13MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1pFVzsW2UScSnaPAwFp
1493QU4+txtyJj8AOC3Kx7YkX1d48DGU2Fy1he7SXPHgcuhXYIqfWGn/Vy/4yJxXD7
15HlU8RM7LlWHRk7ecAvF4WtxZDjPE0OSG5T69w5f7tMCtQPQseInCKqleJuCjxrvA
16zyTWTwKA1S6e+KxXS/kbqsumriljFujNr6Gmh8ygDnpF055Xo0vTenkMipVw/oYn
17U0EHx5ic+Fmcob3EyOj25lu/CVYtU1Rn8jPbrBOMiIq5sePh2QXOwGRsuTiZk2mP
18LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar
19FQIDAQAB
20-----END PUBLIC KEY-----`;
21
22export interface LicenseData {
23 customerId: string;
24 createdAt: string;
25 expiresAt: string;
26}
27
28export function validateLicenseKey(licenseKey: string): boolean {
29 try {
30 // Decode the base64 license key
31 const decodedString = Buffer.from(licenseKey, "base64").toString("utf8");
32 const { data, signature } = JSON.parse(decodedString);
33
34 // Verify the signature
35 const verify = crypto.createVerify("SHA256");
36 verify.update(data);
37 verify.end();
38
39 const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64");
40
41 if (!isValid) return false;
42
43 // Check license expiration
44 const licenseData: LicenseData = JSON.parse(data);
45 const expirationDate = new Date(licenseData.expiresAt);
46 const now = new Date();
47
48 return expirationDate > now;
49 } catch (error) {
50 console.error("License validation error:", error);
51 return false;
52 }
53}
54
55function extractConfigFromArray(config: any[]): Record<string, string> {
56 const configObj: Record<string, string> = {};
57
58 for (let i = 0; i < config.length; i += 2) {
59 if (i + 1 < config.length) {
60 const key = config[i];
61 const value = config[i + 1];
62 if (typeof key === "string") {
63 configObj[key] = value as string;
64 }
65 }
66 }
67
68 return configObj;
69}
70
71const MACOS_MDM_PATHS = [
72 // Organization-specific MDM plist
73 "/Library/Managed Preferences/dev.continue.app.plist",
74 // User-specific MDM plist
75 path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"),
76];
77
78function readMdmKeysMacOS(): MdmKeys | undefined {
79 try {
80 // MDM configuration is typically stored in /Library/Managed Preferences/ on macOS
81 // The filename is often the bundle identifier of the application
82
83 // Try to find a valid MDM configuration file
84 for (const mdmPath of MACOS_MDM_PATHS) {
85 if (fs.existsSync(mdmPath)) {
86 // Read the file content
87 const fileContent = fs.readFileSync(mdmPath, "utf8");
88
89 try {
90 // Parse the plist file using the plist package
91 const config = plist.parse(fileContent);
92
93 // Extract the relevant fields from the config
94 // Config is an array of alternating keys and values
95 if (Array.isArray(config)) {
96 const configObj = extractConfigFromArray(config);
97
98 // Check if required keys are present
99 if (configObj.licenseKey && configObj.apiUrl) {
100 return {
101 licenseKey: configObj.licenseKey,
102 apiUrl: configObj.apiUrl,
103 };
104 }
105 }
106 } catch (parseError) {
107 console.error(`Error parsing MDM configuration: ${parseError}`);
108 }
109 }
110 }
111
112 return undefined;
113 } catch (error) {
114 console.error("Error reading macOS MDM keys:", error);
115 return undefined;
116 }
117}
118
119function readMdmKeysWindows(): MdmKeys | undefined {
120 try {
121 // For Windows, we need to read from the registry
122 // Using regedit or another synchronous registry access module
123 const { execSync } = require("child_process");
124
125 // Path to the registry where MDM configuration is stored
126 const regPath = "HKLM\\Software\\Continue\\MDM";
127 const userRegPath = "HKCU\\Software\\Continue\\MDM";
128
129 // Try to read from HKEY_LOCAL_MACHINE first
130 try {
131 // Use REG QUERY command to read registry values
132 const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
133 const apiUrlCmd = `reg query "${regPath}" /v apiUrl`;
134
135 const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
136 const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
137
138 // Extract values from command output
139 const licenseKey = extractRegValue(licenseKeyOutput);
140 const apiUrl = extractRegValue(apiUrlOutput);
141
142 if (licenseKey && apiUrl) {
143 return { licenseKey, apiUrl };
144 }
145 } catch (error) {
146 // Registry key might not exist, fallback to HKEY_CURRENT_USER
147 }
148
149 // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
150 try {
151 const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
152 const apiUrlCmd = `reg query "${userRegPath}" /v apiUrl`;
153
154 const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
155 const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
156
157 // Extract values from command output
158 const licenseKey = extractRegValue(licenseKeyOutput);
159 const apiUrl = extractRegValue(apiUrlOutput);
160
161 if (licenseKey && apiUrl) {
162 return { licenseKey, apiUrl };
163 }
164 } catch (error) {
165 // Registry key might not exist in HKCU either
166 }
167
168 return undefined;
169 } catch (error) {
170 console.error("Error reading Windows MDM keys:", error);
171 return undefined;
172 }
173}
174
175// Helper function to extract registry values from reg query output
176function extractRegValue(output: string): string | undefined {
177 const match = output.match(/REG_SZ\s+(.+)$/m);
178 return match ? match[1].trim() : undefined;
179}
180
181// Common locations for MDM configurations in Linux systems
182const LINUX_MDM_PATHS = [
183 // System-wide configuration
184 "/etc/continue/mdm.json",
185 "/var/lib/continue/mdm.json",
186 // User-specific configuration
187 path.join(os.homedir(), ".config/continue/mdm.json"),
188];
189
190function readMdmKeysLinux(): MdmKeys | undefined {
191 try {
192 // Try to find a valid MDM configuration file
193 for (const mdmPath of LINUX_MDM_PATHS) {
194 if (fs.existsSync(mdmPath)) {
195 // Read the file content
196 const fileContent = fs.readFileSync(mdmPath, "utf8");
197
198 try {
199 // Parse the JSON configuration file
200 const config = JSON.parse(fileContent);
201
202 // Check if required keys are present
203 if (config.licenseKey && config.apiUrl) {
204 return {
205 licenseKey: config.licenseKey,
206 apiUrl: config.apiUrl,
207 };
208 }
209 } catch (parseError) {
210 console.error(`Error parsing Linux MDM configuration: ${parseError}`);
211 }
212 }
213 }
214
215 return undefined;
216 } catch (error) {
217 console.error("Error reading Linux MDM keys:", error);
218 return undefined;
219 }
220}
221
222function readMdmKeys(): MdmKeys | undefined {
223 const platform = os.platform();
224
225 switch (platform) {
226 case "darwin":
227 return readMdmKeysMacOS();
228
229 case "win32":
230 return readMdmKeysWindows();
231
232 case "linux":
233 return readMdmKeysLinux();
234
235 default:
236 console.error(`MDM keys not supported on platform: ${platform}`);
237 return undefined;
238 }
239}
240
241/**
242 * Read and validate MDM keys from the operating system's configuration files or registry.
243 */
244export function getMdmKeys(): MdmKeys | undefined {
245 try {
246 const mdmKeys = readMdmKeys();
247
248 if (mdmKeys) {
249 if (!validateLicenseKey(mdmKeys.licenseKey)) {
250 console.error("Invalid license key found: ", mdmKeys.licenseKey);
251 return undefined;
252 }
253
254 return mdmKeys;
255 }
256
257 return undefined;
258 } catch (e) {
259 console.warn("Error reading MDM keys: ", e);
260 return undefined;
261 }
262}