Elffuss BraidHub

kikocis/continue public

a36aa2a5e5e6 · 9.9 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}
10
11const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
12MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1pFVzsW2UScSnaPAwFp
1393QU4+txtyJj8AOC3Kx7YkX1d48DGU2Fy1he7SXPHgcuhXYIqfWGn/Vy/4yJxXD7
14HlU8RM7LlWHRk7ecAvF4WtxZDjPE0OSG5T69w5f7tMCtQPQseInCKqleJuCjxrvA
15zyTWTwKA1S6e+KxXS/kbqsumriljFujNr6Gmh8ygDnpF055Xo0vTenkMipVw/oYn
16U0EHx5ic+Fmcob3EyOj25lu/CVYtU1Rn8jPbrBOMiIq5sePh2QXOwGRsuTiZk2mP
17LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar
18FQIDAQAB
19-----END PUBLIC KEY-----`;
20
21interface LicenseKeyUnsignedData {
22 apiUrl: string;
23}
24
25export interface LicenseKey {
26 signature: string;
27 data: string;
28 unsignedData: LicenseKeyUnsignedData;
29}
30
31export interface LicenseKeyData {
32 customerId: string;
33 createdAt: string;
34 expiresAt: string;
35}
36
37export function validateLicenseKey(licenseKey: string): {
38 isValid: boolean;
39 licenseKeyData?: LicenseKey;
40} {
41 try {
42 // Decode the base64 license key
43 const decodedString = Buffer.from(licenseKey, "base64").toString("utf8");
44 const { data, signature, unsignedData } = JSON.parse(decodedString);
45
46 // Verify the signature
47 const verify = crypto.createVerify("SHA256");
48 verify.update(data);
49 verify.end();
50
51 const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64");
52
53 if (!isValid) return { isValid: false };
54
55 // Check license expiration
56 const licenseData: LicenseKeyData = JSON.parse(data);
57 const expirationDate = new Date(licenseData.expiresAt);
58 const now = new Date();
59
60 const isNotExpired = expirationDate > now;
61
62 if (!isNotExpired) return { isValid: false };
63
64 // Return both validation result and license key data
65 const licenseKeyData: LicenseKey = {
66 signature,
67 data,
68 unsignedData,
69 };
70
71 return { isValid: true, licenseKeyData };
72 } catch (error) {
73 console.error("License validation error:", error);
74 return { isValid: false };
75 }
76}
77
78const MACOS_MDM_PATHS = [
79 // Organization-specific MDM plist
80 "/Library/Managed Preferences/dev.continue.app.plist",
81 // User-specific MDM plist
82 path.join(os.homedir(), "Library/Managed Preferences/dev.continue.app.plist"),
83];
84
85function readMdmKeysMacOS(): MdmKeys | undefined {
86 try {
87 // MDM configuration is typically stored in /Library/Managed Preferences/ on macOS
88 // The filename is often the bundle identifier of the application
89
90 // Try to find a valid MDM configuration file
91 for (const mdmPath of MACOS_MDM_PATHS) {
92 if (fs.existsSync(mdmPath)) {
93 // Read the file content
94 const fileContent = fs.readFileSync(mdmPath, "utf8");
95
96 try {
97 // Parse the plist file using the plist package
98 const config = plist.parse(fileContent) as
99 | { licenseKey: string | undefined }
100 | undefined;
101
102 if (config && config?.licenseKey) {
103 // Extract the license key from the configuration
104 return { licenseKey: config?.licenseKey };
105 } else {
106 console.error("Invalid MDM configuration format");
107 }
108 } catch (parseError) {
109 console.error(`Error parsing MDM configuration: ${parseError}`);
110 }
111 }
112 }
113
114 return undefined;
115 } catch (error) {
116 console.error("Error reading macOS MDM keys:", error);
117 return undefined;
118 }
119}
120
121function readMdmKeysWindows(): MdmKeys | undefined {
122 try {
123 // For Windows, we need to read from the registry
124 // Using regedit or another synchronous registry access module
125 const { execSync } = require("child_process");
126
127 // Path to the registry where MDM configuration is stored
128 const regPath = "HKLM\\Software\\Continue\\MDM";
129 const userRegPath = "HKCU\\Software\\Continue\\MDM";
130
131 // Try to read from HKEY_LOCAL_MACHINE first
132 try {
133 // Use REG QUERY command to read registry values
134 const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
135 const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
136 // Extract values from command output
137 const licenseKey = extractRegValue(licenseKeyOutput);
138 if (licenseKey) {
139 return { licenseKey };
140 }
141 } catch (error) {
142 // Registry key might not exist, fallback to HKEY_CURRENT_USER
143 }
144
145 // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
146 try {
147 const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
148 const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
149 // Extract values from command output
150 const licenseKey = extractRegValue(licenseKeyOutput);
151 if (licenseKey) {
152 return { licenseKey };
153 }
154 } catch (error) {
155 // Registry key might not exist in HKCU either
156 }
157
158 return undefined;
159 } catch (error) {
160 console.error("Error reading Windows MDM keys:", error);
161 return undefined;
162 }
163}
164
165// Helper function to extract registry values from reg query output
166function extractRegValue(output: string): string | undefined {
167 const match = output.match(/REG_SZ\s+(.+)$/m);
168 return match ? match[1].trim() : undefined;
169}
170
171// Common locations for MDM configurations in Linux systems
172const LINUX_MDM_PATHS = [
173 // System-wide configuration
174 "/etc/continue/mdm.json",
175 "/var/lib/continue/mdm.json",
176 // User-specific configuration
177 path.join(os.homedir(), ".config/continue/mdm.json"),
178];
179
180function readMdmKeysLinux(): MdmKeys | undefined {
181 try {
182 // Try to find a valid MDM configuration file
183 for (const mdmPath of LINUX_MDM_PATHS) {
184 if (fs.existsSync(mdmPath)) {
185 // Read the file content
186 const fileContent = fs.readFileSync(mdmPath, "utf8");
187
188 try {
189 // Parse the JSON configuration file
190 const config = JSON.parse(fileContent);
191
192 // Check if required key is present
193 if (config.licenseKey) {
194 return {
195 licenseKey: config.licenseKey,
196 };
197 }
198 } catch (parseError) {
199 console.error(`Error parsing Linux MDM configuration: ${parseError}`);
200 }
201 }
202 }
203
204 return undefined;
205 } catch (error) {
206 console.error("Error reading Linux MDM keys:", error);
207 return undefined;
208 }
209}
210
211function readMdmKeys(): MdmKeys | undefined {
212 const platform = os.platform();
213
214 switch (platform) {
215 case "darwin":
216 return readMdmKeysMacOS();
217
218 case "win32":
219 return readMdmKeysWindows();
220
221 case "linux":
222 return readMdmKeysLinux();
223
224 default:
225 console.error(`MDM keys not supported on platform: ${platform}`);
226 return undefined;
227 }
228}
229
230/**
231 * Read and validate MDM keys from the operating system's configuration files or registry.
232 */
233export function getLicenseKeyData(): LicenseKey | undefined {
234 try {
235 const mdmKeys = readMdmKeys();
236
237 if (mdmKeys) {
238 const { isValid, licenseKeyData } = validateLicenseKey(
239 mdmKeys.licenseKey,
240 );
241 if (!isValid) {
242 console.error("Invalid license key found: ", mdmKeys.licenseKey);
243 return undefined;
244 }
245
246 return licenseKeyData;
247 }
248
249 return undefined;
250 } catch (e) {
251 console.warn("Error reading MDM keys: ", e);
252 return undefined;
253 }
254}
255
256function writeMdmKeysMacOS(licenseKey: string): boolean {
257 try {
258 // Write to user-specific MDM plist
259 const userMdmPath = path.join(
260 os.homedir(),
261 "Library/Managed Preferences/dev.continue.app.plist",
262 );
263
264 const config = {
265 licenseKey,
266 };
267
268 // Ensure directory exists
269 fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
270
271 // Write the plist file
272 const plistContent = plist.build(config);
273 fs.writeFileSync(userMdmPath, plistContent, "utf8");
274
275 return true;
276 } catch (error) {
277 console.error("Error writing macOS MDM keys:", error);
278 return false;
279 }
280}
281
282function writeMdmKeysWindows(licenseKey: string): boolean {
283 try {
284 const { execSync } = require("child_process");
285
286 // Use HKEY_CURRENT_USER to avoid needing admin privileges
287 const userRegPath = "HKCU\\Software\\Continue\\MDM";
288
289 // Create the registry key if it doesn't exist
290 try {
291 execSync(`reg add "${userRegPath}" /f`);
292 } catch (error) {
293 // Key might already exist
294 }
295
296 // Set the license key and API URL
297 execSync(
298 `reg add "${userRegPath}" /v licenseKey /t REG_SZ /d "${licenseKey}" /f`,
299 );
300
301 return true;
302 } catch (error) {
303 console.error("Error writing Windows MDM keys:", error);
304 return false;
305 }
306}
307
308function writeMdmKeysLinux(licenseKey: string): boolean {
309 try {
310 // Write to user-specific configuration
311 const userMdmPath = path.join(os.homedir(), ".config/continue/mdm.json");
312
313 const config = {
314 licenseKey,
315 };
316
317 // Ensure directory exists
318 fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
319
320 // Write the JSON configuration file
321 fs.writeFileSync(userMdmPath, JSON.stringify(config, null, 2), "utf8");
322
323 return true;
324 } catch (error) {
325 console.error("Error writing Linux MDM keys:", error);
326 return false;
327 }
328}
329
330/**
331 * Store the license key in the appropriate OS-specific location.
332 * For now, we'll use a default API URL since it's not provided in the command.
333 */
334export function setMdmLicenseKey(licenseKey: string): boolean {
335 try {
336 // Validate the license key first
337 const { isValid } = validateLicenseKey(licenseKey);
338 if (!isValid) {
339 return false;
340 }
341
342 const platform = os.platform();
343
344 switch (platform) {
345 case "darwin":
346 return writeMdmKeysMacOS(licenseKey);
347
348 case "win32":
349 return writeMdmKeysWindows(licenseKey);
350
351 case "linux":
352 return writeMdmKeysLinux(licenseKey);
353
354 default:
355 console.error(
356 `Setting MDM keys not supported on platform: ${platform}`,
357 );
358 return false;
359 }
360 } catch (error) {
361 console.error("Error setting MDM license key:", error);
362 return false;
363 }
364}