Elffuss BraidHub

kikocis/continue public

main · 10.0 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, {
136 encoding: "utf8",
137 stdio: ["pipe", "pipe", "pipe"],
138 });
139 // Extract values from command output
140 const licenseKey = extractRegValue(licenseKeyOutput);
141 if (licenseKey) {
142 return { licenseKey };
143 }
144 } catch (error) {
145 // Registry key might not exist, fallback to HKEY_CURRENT_USER
146 }
147
148 // Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
149 try {
150 const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
151 const licenseKeyOutput = execSync(licenseKeyCmd, {
152 encoding: "utf8",
153 stdio: ["pipe", "pipe", "pipe"],
154 });
155 // Extract values from command output
156 const licenseKey = extractRegValue(licenseKeyOutput);
157 if (licenseKey) {
158 return { licenseKey };
159 }
160 } catch (error) {
161 // Registry key might not exist in HKCU either
162 }
163
164 return undefined;
165 } catch (error) {
166 console.error("Error reading Windows MDM keys:", error);
167 return undefined;
168 }
169}
170
171// Helper function to extract registry values from reg query output
172function extractRegValue(output: string): string | undefined {
173 const match = output.match(/REG_SZ\s+(.+)$/m);
174 return match ? match[1].trim() : undefined;
175}
176
177// Common locations for MDM configurations in Linux systems
178const LINUX_MDM_PATHS = [
179 // System-wide configuration
180 "/etc/continue/mdm.json",
181 "/var/lib/continue/mdm.json",
182 // User-specific configuration
183 path.join(os.homedir(), ".config/continue/mdm.json"),
184];
185
186function readMdmKeysLinux(): MdmKeys | undefined {
187 try {
188 // Try to find a valid MDM configuration file
189 for (const mdmPath of LINUX_MDM_PATHS) {
190 if (fs.existsSync(mdmPath)) {
191 // Read the file content
192 const fileContent = fs.readFileSync(mdmPath, "utf8");
193
194 try {
195 // Parse the JSON configuration file
196 const config = JSON.parse(fileContent);
197
198 // Check if required key is present
199 if (config.licenseKey) {
200 return {
201 licenseKey: config.licenseKey,
202 };
203 }
204 } catch (parseError) {
205 console.error(`Error parsing Linux MDM configuration: ${parseError}`);
206 }
207 }
208 }
209
210 return undefined;
211 } catch (error) {
212 console.error("Error reading Linux MDM keys:", error);
213 return undefined;
214 }
215}
216
217function readMdmKeys(): MdmKeys | undefined {
218 const platform = os.platform();
219
220 switch (platform) {
221 case "darwin":
222 return readMdmKeysMacOS();
223
224 case "win32":
225 return readMdmKeysWindows();
226
227 case "linux":
228 return readMdmKeysLinux();
229
230 default:
231 console.error(`MDM keys not supported on platform: ${platform}`);
232 return undefined;
233 }
234}
235
236/**
237 * Read and validate MDM keys from the operating system's configuration files or registry.
238 */
239export function getLicenseKeyData(): LicenseKey | undefined {
240 try {
241 const mdmKeys = readMdmKeys();
242
243 if (mdmKeys) {
244 const { isValid, licenseKeyData } = validateLicenseKey(
245 mdmKeys.licenseKey,
246 );
247 if (!isValid) {
248 console.error("Invalid license key found: ", mdmKeys.licenseKey);
249 return undefined;
250 }
251
252 return licenseKeyData;
253 }
254
255 return undefined;
256 } catch (e) {
257 console.warn("Error reading MDM keys: ", e);
258 return undefined;
259 }
260}
261
262function writeMdmKeysMacOS(licenseKey: string): boolean {
263 try {
264 // Write to user-specific MDM plist
265 const userMdmPath = path.join(
266 os.homedir(),
267 "Library/Managed Preferences/dev.continue.app.plist",
268 );
269
270 const config = {
271 licenseKey,
272 };
273
274 // Ensure directory exists
275 fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
276
277 // Write the plist file
278 const plistContent = plist.build(config);
279 fs.writeFileSync(userMdmPath, plistContent, "utf8");
280
281 return true;
282 } catch (error) {
283 console.error("Error writing macOS MDM keys:", error);
284 return false;
285 }
286}
287
288function writeMdmKeysWindows(licenseKey: string): boolean {
289 try {
290 const { execSync } = require("child_process");
291
292 // Use HKEY_CURRENT_USER to avoid needing admin privileges
293 const userRegPath = "HKCU\\Software\\Continue\\MDM";
294
295 // Create the registry key if it doesn't exist
296 try {
297 execSync(`reg add "${userRegPath}" /f`);
298 } catch (error) {
299 // Key might already exist
300 }
301
302 // Set the license key and API URL
303 execSync(
304 `reg add "${userRegPath}" /v licenseKey /t REG_SZ /d "${licenseKey}" /f`,
305 );
306
307 return true;
308 } catch (error) {
309 console.error("Error writing Windows MDM keys:", error);
310 return false;
311 }
312}
313
314function writeMdmKeysLinux(licenseKey: string): boolean {
315 try {
316 // Write to user-specific configuration
317 const userMdmPath = path.join(os.homedir(), ".config/continue/mdm.json");
318
319 const config = {
320 licenseKey,
321 };
322
323 // Ensure directory exists
324 fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
325
326 // Write the JSON configuration file
327 fs.writeFileSync(userMdmPath, JSON.stringify(config, null, 2), "utf8");
328
329 return true;
330 } catch (error) {
331 console.error("Error writing Linux MDM keys:", error);
332 return false;
333 }
334}
335
336/**
337 * Store the license key in the appropriate OS-specific location.
338 * For now, we'll use a default API URL since it's not provided in the command.
339 */
340export function setMdmLicenseKey(licenseKey: string): boolean {
341 try {
342 // Validate the license key first
343 const { isValid } = validateLicenseKey(licenseKey);
344 if (!isValid) {
345 return false;
346 }
347
348 const platform = os.platform();
349
350 switch (platform) {
351 case "darwin":
352 return writeMdmKeysMacOS(licenseKey);
353
354 case "win32":
355 return writeMdmKeysWindows(licenseKey);
356
357 case "linux":
358 return writeMdmKeysLinux(licenseKey);
359
360 default:
361 console.error(
362 `Setting MDM keys not supported on platform: ${platform}`,
363 );
364 return false;
365 }
366 } catch (error) {
367 console.error("Error setting MDM license key:", error);
368 return false;
369 }
370}