-
-
Notifications
You must be signed in to change notification settings - Fork 196
Expand file tree
/
Copy pathlogin-service.js
More file actions
761 lines (680 loc) · 31 KB
/
Copy pathlogin-service.js
File metadata and controls
761 lines (680 loc) · 31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/*global path, logger*/
/**
* Shared Login Service
*
* This module contains shared login service functionality used by both
* browser and desktop login implementations, including entitlements management.
*/
define(function (require, exports, module) {
require("./setup-login-service"); // this adds loginService to KernalModeTrust
require("./promotions");
require("./login-utils");
const NodeUtils = require("utils/NodeUtils"),
PreferencesManager = require("preferences/PreferencesManager"),
Commands = require("command/Commands"),
CommandManager = require("command/CommandManager");
const EntitlementsDirectImport = require("./EntitlementsManager"); // this adds Entitlements to KernalModeTrust
const Metrics = require("utils/Metrics"),
Strings = require("strings");
const PREF_STATE_LICENSED_DEVICE_CHECK = "LICENSED_DEVICE_CHECK";
PreferencesManager.stateManager.definePreference(PREF_STATE_LICENSED_DEVICE_CHECK, "boolean", false);
const MS_IN_DAY = 10 * 24 * 60 * 60 * 1000;
const TEN_MINUTES = 10 * 60 * 1000;
const FREE_PLAN_VALIDITY_DAYS = 10000;
// the fallback salt is always a constant as this will only fail in rare circumstatnces and it needs to
// be exactly same across versions of the app. Changing this will not affect the large majority of users and
// for the ones who are affected, the app will reset the signed data with new salt but will not grant ant trial
// when tampering is detected.
const FALLBACK_SALT = 'fallback-salt-2f309322-b32d-4d59-85b4-2baef666a9f4';
let currentSalt;
// Cache file path for desktop app entitlements
const CACHED_ENTITLEMENTS_FILE = path.join(Phoenix.app.getApplicationSupportDirectory(),
"cached_entitlements.json");
// save a copy of window.fetch so that extensions wont tamper with it.
let fetchFn = window.fetch;
let dateNowFn = Date.now;
const KernalModeTrust = window.KernalModeTrust;
if(!KernalModeTrust){
// integrated extensions will have access to kernal mode, but not external extensions
throw new Error("Login service should have access to KernalModeTrust. Cannot boot without trust ring");
}
const LoginService = KernalModeTrust.loginService;
// Event constants
const EVENT_ENTITLEMENTS_CHANGED = "entitlements_changed";
// Cached entitlements data
let cachedEntitlements = undefined;
// Last recorded state for entitlements monitoring
let lastRecordedState = null;
// Debounced trigger for entitlements changed
let entitlementsChangedTimer = null;
const ENTITLEMENT_CHANGED_DEBOUNCE_WINDOW = Phoenix.isTestWindow ? 100 : 1000;
function _debounceEntitlementsChanged() {
if (entitlementsChangedTimer) {
// already scheduled, skip
return;
}
// atmost 1 entitlement changed event will be triggered in this window to prevent too many entitlment changed
// events firing.
entitlementsChangedTimer = setTimeout(() => {
LoginService.trigger(EVENT_ENTITLEMENTS_CHANGED);
entitlementsChangedTimer = null;
}, ENTITLEMENT_CHANGED_DEBOUNCE_WINDOW);
}
/**
* Get per-user salt for signature generation, creating and persisting one if it doesn't exist
* Used for signing cached data to prevent tampering
*/
async function getSalt() {
// Fallback salt constant for rare circumstances where salt generation fails
if(currentSalt) {
return currentSalt;
}
try {
if (Phoenix.isNativeApp) {
// Native app: use KernalModeTrust credential store
let salt = await KernalModeTrust.getCredential(KernalModeTrust.SIGNATURE_SALT_KEY);
if (!salt) {
// Generate and store new salt
salt = crypto.randomUUID();
await KernalModeTrust.setCredential(KernalModeTrust.SIGNATURE_SALT_KEY, salt);
}
currentSalt = salt;
return salt;
}
// In browser app, there is no way to securely store salt without extensions being able to
// read it. Return a static salt for basic integrity checking.
currentSalt = FALLBACK_SALT;
return FALLBACK_SALT;
} catch (error) {
console.error("Error getting signature salt:", error);
// Return a fallback salt to prevent crashes
Metrics.countEvent(Metrics.EVENT_TYPE.AUTH, "saltGet", "Err");
currentSalt = FALLBACK_SALT;
return FALLBACK_SALT;
}
}
/**
* Load cached entitlements from disk with signature validation
* Returns null if no cache, invalid signature, or error
*/
async function _loadCachedEntitlements() {
if (!Phoenix.isNativeApp) {
return null; // No caching for browser app
}
try {
const fileData = await Phoenix.VFS.readFileResolves(CACHED_ENTITLEMENTS_FILE, 'utf8');
if (fileData.error || !fileData.data) {
return null; // No cached file exists
}
const cachedData = JSON.parse(fileData.data);
if (!cachedData.jsonData || !cachedData.sign) {
console.warn("Invalid cached entitlements format - missing jsonData or sign");
await _clearCachedEntitlements();
return null;
}
// Validate signature
const salt = await getSalt();
const isValidSignature = await KernalModeTrust.validateDataSignature(
cachedData.jsonData,
cachedData.sign,
salt
);
if (!isValidSignature) {
console.warn("Cached entitlements signature validation failed - possible tampering detected");
Metrics.countEvent(Metrics.EVENT_TYPE.PRO, "entCacheLD", "signInvalid");
await _clearCachedEntitlements();
return null;
}
// Parse and return the entitlements
return JSON.parse(cachedData.jsonData);
} catch (error) {
console.error("Error loading cached entitlements:", error);
Metrics.countEvent(Metrics.EVENT_TYPE.PRO, "entCacheLD", "error");
await _clearCachedEntitlements(); // Clear corrupted cache
return null;
}
}
/**
* Save entitlements to cache with signature
*/
async function _saveCachedEntitlements(entitlements) {
if (!Phoenix.isNativeApp || !entitlements) {
return; // No caching for browser app
}
try {
const jsonData = JSON.stringify(entitlements);
const salt = await getSalt();
const signature = await KernalModeTrust.generateDataSignature(jsonData, salt);
const cacheData = {
jsonData: jsonData,
sign: signature
};
await Phoenix.VFS.writeFileAsync(CACHED_ENTITLEMENTS_FILE, JSON.stringify(cacheData), 'utf8');
console.log("Entitlements cached successfully");
} catch (error) {
Metrics.countEvent(Metrics.EVENT_TYPE.PRO, "entCacheSave", "err");
console.error("Error saving cached entitlements:", error);
}
}
/**
* Clear cached entitlements file
*/
async function _clearCachedEntitlements() {
if (!Phoenix.isNativeApp) {
return; // No caching for browser app
}
try {
await Phoenix.VFS.unlinkResolves(CACHED_ENTITLEMENTS_FILE);
console.log("Cached entitlements cleared");
} catch (error) {
console.log("Error clearing cached entitlements:", error);
}
}
let deviceIDCached = undefined;
async function getDeviceID() {
if(!Phoenix.isNativeApp) {
// We only grant device licenses to desktop apps. Browsers cannot be uniquely device identified obviously.
return null;
}
if(deviceIDCached !== undefined) {
return deviceIDCached;
}
try {
const deviceID = await NodeUtils.getDeviceID();
if(!deviceID) {
deviceIDCached = null;
Metrics.countEvent(Metrics.EVENT_TYPE.AUTH, "deviceID", "nullErr");
return null;
}
deviceIDCached = KernalModeTrust.generateDataSignature(deviceID);
} catch (e) {
logger.reportError(e, "failed to sign deviceID");
Metrics.countEvent(Metrics.EVENT_TYPE.AUTH, "deviceID", "SignErr");
deviceIDCached = null;
}
return deviceIDCached;
}
let deviceLicensePrimed = false,
licencedDeviceCredsAvailable = false;
/**
* Get entitlements from API or disc cache.
* @param {string} forceRefresh If provided will always fetch from server and bypass cache. Use rarely like
* when a user logs in/out/some other user activity/ account-related events.
* Returns null if the user is not logged in
*/
async function getEntitlements(forceRefresh = false) {
if(!deviceLicensePrimed) {
deviceLicensePrimed = true;
// we cache this as device license is only checked at app start. As invoves some files in system loactions,
// we dont want file access errors to happen on every entitlement check.
licencedDeviceCredsAvailable = await isLicensedDevice();
}
// Return null if not logged in
if (!LoginService.isLoggedIn() && !licencedDeviceCredsAvailable) {
return null;
}
// Return cached data if available and not forcing refresh
if (cachedEntitlements !== undefined && !forceRefresh) {
return cachedEntitlements;
}
if (cachedEntitlements && !navigator.onLine) {
return cachedEntitlements;
}
async function _processDiscCachedEntitlement() {
const diskCachedEntitlements = await _loadCachedEntitlements();
if (diskCachedEntitlements) {
console.log("offline/network/server error: Using cached entitlements from disk");
const entitlementsChanged =
JSON.stringify(cachedEntitlements) !== JSON.stringify(diskCachedEntitlements);
cachedEntitlements = diskCachedEntitlements;
// Trigger event if entitlements changed
if (entitlementsChanged) {
_debounceEntitlementsChanged();
}
return cachedEntitlements;
}
return null;
}
try {
const accountBaseURL = LoginService.getAccountBaseURL();
const language = brackets.getLocale();
const currentVersion = window.AppConfig.apiVersion || "1.0.0";
let url = `${accountBaseURL}/getAppEntitlements?lang=${language}&version=${currentVersion}`+
`&platform=${Phoenix.platform}&appType=${Phoenix.isNativeApp ? "desktop" : "browser"}`;
if(licencedDeviceCredsAvailable) {
url += `&deviceID=${await getDeviceID()}`;
}
let fetchOptions = {
method: 'GET',
headers: {
'Accept': 'application/json'
}
};
// Handle different authentication methods for browser vs desktop
if (Phoenix.isNativeApp) {
// Desktop app: use appSessionID and validationCode
const profile = LoginService.getProfile();
if (profile && profile.apiKey && profile.validationCode) {
url += `&appSessionID=${encodeURIComponent(profile.apiKey)}&validationCode=${encodeURIComponent(profile.validationCode)}`;
} else if(!licencedDeviceCredsAvailable){
console.error('Missing appSessionID or validationCode for desktop app entitlements');
return null;
}
} else {
// Browser app: use session cookies
fetchOptions.credentials = 'include';
}
// For desktop app, if offline, try to return disc cached entitlements
if (Phoenix.isNativeApp && !navigator.onLine) {
const processedEntitlement = await _processDiscCachedEntitlement();
if (processedEntitlement) {
return processedEntitlement;
}
}
const response = await fetchFn(url, fetchOptions);
if (response.ok) {
const result = await response.json();
if (result.isSuccess) {
// Check if entitlements actually changed
const entitlementsChanged = JSON.stringify(cachedEntitlements) !== JSON.stringify(result);
cachedEntitlements = result;
// Save to disk cache for desktop app
if (Phoenix.isNativeApp) {
await _saveCachedEntitlements(result);
}
// Trigger event if entitlements changed
if (entitlementsChanged) {
_debounceEntitlementsChanged();
}
return cachedEntitlements;
}
} else if (response.status >= 500 && response.status < 600) {
// Handle 5xx errors by loading from cache.
if (Phoenix.isNativeApp) {
console.warn('Fetch entitlements server error:', response.status);
const processedEntitlement = await _processDiscCachedEntitlement();
if (processedEntitlement) {
return processedEntitlement;
}
}
} else if (Phoenix.isNativeApp) {
// 4xx errors are genuine auth fail errors, so our cache is not good then
console.warn('Cearing entitlements, entitlements server error:', response.status);
await _clearCachedEntitlements();
}
} catch (error) {
console.error('Failed to fetch entitlements:', error);
// errors that happen during the fetch operation itself, which are typically not HTTP errors
// returned by the server, but rather issues at the network or browser level.
// For desktop app, fall back to cached entitlements if available
if (Phoenix.isNativeApp) {
const processedEntitlement = await _processDiscCachedEntitlement();
if (processedEntitlement) {
return processedEntitlement;
}
}
}
return null;
}
/**
* Clear cached entitlements and trigger change event
* Called when user logs out
*/
async function clearEntitlements() {
if (cachedEntitlements) {
cachedEntitlements = undefined;
_debounceEntitlementsChanged();
}
// Reset device license state so it's re-evaluated on next entitlement check
deviceLicensePrimed = false;
}
/**
* Start the 10-minute interval timer for monitoring entitlements
*/
function startEffectiveEntitlementsMonitor() {
// Reconcile effective entitlements from server. So the effective entitlements api injects trial
// entitlements data. but only the server fetch will trigger the entitlements change event.
// so in here, we observe the effective entitlements, and if the effective entitlements are changed,
// since the last triggered state, we trigger a change event. This only concerens with the effective
// entitlement changes. This will not logout the user if user logged out from the server admin panel,
// but his entitlements will be cleared by this call anyways.
// At app start we refresh entitlements, then only one each user action like user clicks on profile icon,
// or if some user hits some backend api, we will refresh entitlements. But here, we periodically refresh
// entitlements from the server every 10 minutes, but only trigger entitlement change events only if some
// effective entitlement(Eg. trial) data changed or any validity expired.
if(Phoenix.isTestWindow){
return;
}
setTimeout( async function() {
// prime the entitlement monitor with the current effective entitlements, after app start, the system would
// have resolved any existing login info by now and effective entitlements would be available if any.
lastRecordedState = await getEffectiveEntitlements(false);
}, 30000);
setInterval(async () => {
try {
// Get fresh effective entitlements
const freshEntitlements = await getEffectiveEntitlements(true);
// Check if we need to refresh
const expiredPlanName = KernalModeTrust.LoginUtils
.validTillExpired(freshEntitlements, lastRecordedState);
const hasChanged = KernalModeTrust.LoginUtils
.haveEntitlementsChanged(freshEntitlements, lastRecordedState);
if (expiredPlanName || hasChanged) {
console.log(`Entitlements monitor detected changes, Expired: ${expiredPlanName},` +
`changed: ${hasChanged} refreshing...`);
Metrics.countEvent(Metrics.EVENT_TYPE.PRO, "entRefresh",
expiredPlanName ? "exp_"+expiredPlanName : "changed");
// if not logged in, the getEffectiveEntitlements will not trigger change even if some trial
// entitlements changed. so we trigger a change anyway here. The debounce will take care of
// multi fire and we are ok with multi fire 1 second apart.
_debounceEntitlementsChanged();
}
// Update last recorded state
lastRecordedState = freshEntitlements;
} catch (error) {
console.error('Entitlements monitor error:', error);
}
}, TEN_MINUTES);
console.log('Entitlements monitor started (10-minute interval)');
}
function _validateAndFilterEntitlements(entitlements) {
if (!entitlements) {
return;
}
const currentDate = dateNowFn();
if(entitlements.plan && (!entitlements.plan.validTill || currentDate > entitlements.plan.validTill)) {
entitlements.plan = {
...entitlements.plan,
isSubscriber: false,
paidSubscriber: false,
name: Strings.USER_FREE_PLAN_NAME_DO_NOT_TRANSLATE,
fullName: Strings.USER_FREE_PLAN_NAME_DO_NOT_TRANSLATE,
validTill: currentDate + (FREE_PLAN_VALIDITY_DAYS * MS_IN_DAY)
};
}
const featureEntitlements = entitlements.entitlements;
if (!featureEntitlements) {
return;
}
for(const featureName in featureEntitlements) {
const feature = featureEntitlements[featureName];
if(feature && (!feature.validTill || currentDate > feature.validTill)) {
feature.activated = false;
feature.upgradeToPlan = feature.upgradeToPlan || brackets.config.main_pro_plan;
feature.subscribeURL = feature.subscribeURL || brackets.config.purchase_url;
feature.validTill = feature.validTill || (currentDate - MS_IN_DAY);
}
}
}
/**
* Get effective entitlements for determining feature availability.
* This is for internal use only. All consumers in phoenix should use `KernalModeTrust.EntitlementsManager` APIs.
*
* @returns {Promise<Object|null>} Entitlements object or null if not logged in and no trial active
*
* @description Response shapes vary based on user state:
*
* **For non-logged-in users:**
* - Returns `null` if no trial is active
* - Returns synthetic entitlements if trial is active:
* ```javascript
* {
* plan: {
* isSubscriber: true, // Always true for trial users
* paidSubscriber: false, // if the user is a paid for the plan, or is it an unpaid promo
* name: "Phoenix Pro"
* fullName: "Phoenix Pro" // this can be deceptive name like "Phoenix Pro For Education" to use in
* // profile popup, not main branding
* },
* isInProTrial: true, // Indicates this is a trial user
* trialDaysRemaining: number, // Days left in trial
* entitlements: {
* liveEdit: {
* activated: true // Trial users get liveEdit access
* }
* }
* }
* ```
*
* **For logged-in trial users:**
* - If remote response has `plan.isSubscriber: false`, injects `isSubscriber: true`
* - Adds `isInProTrial: true` and `trialDaysRemaining`
* - Injects `entitlements.liveEdit.activated: true`
* - Note: Trial users may not be actual paid subscribers, but `isSubscriber: true` is set
* so all Phoenix code treats them as subscribers. to check if they actually paid or not, use
* `paidSubscriber` field.
*
* **For logged-in users (full remote response):**
* ```javascript
* {
* isSuccess: boolean,
* lang: string,
* plan: {
* name: "Phoenix Pro",
* fullName: "Phoenix Pro" // this can be deceptive name like "Phoenix Pro For Education" to use in
* // profile popup, not main branding
* isSubscriber: boolean,
* paidSubscriber: boolean,
* validTill: number // Timestamp
* },
* profileview: {
* quota: {
* titleText: "Ai Quota Used",
* usageText: "100 / 200 credits",
* usedPercent: number
* },
* htmlMessage: string // HTML alert message
* },
* entitlements: {
* liveEdit: {
* activated: boolean,
* subscribeURL: string, // URL to subscribe if not activated
* upgradeToPlan: string, // Plan name that includes this entitlement
* validTill: number // Timestamp when entitlement expires
* },
* aiAgent: {
* activated: boolean,
* aiBrandName: string,
* subscribeURL: string,
* upgradeToPlan: string,
* validTill: number,
* upsellDialog: {
* title: "if activated is false, server can send a custom upsell dialog to show",
* message: "this is the message to show",
* buyURL: "if this url is present from server, this will be shown to as buy link"
* }
* }
* }
* }
* ```
*
* @example
* // Listen for entitlements changes
* const LoginService = window.KernelModeTrust.loginService;
* LoginService.on(LoginService.EVENT_ENTITLEMENTS_CHANGED, async() => {
* const entitlements = await LoginService.getEffectiveEntitlements();
* console.log('Entitlements changed:', entitlements);
* // Update UI based on new entitlements
* });
*
* // Get current entitlements
* const entitlements = await LoginService.getEffectiveEntitlements();
* if (entitlements?.plan?.isSubscriber) {
* // Enable pro features
* }
* if (entitlements?.entitlements?.liveEdit?.activated) {
* // Enable live edit feature
* }
*/
async function getEffectiveEntitlements(forceRefresh = false) {
// Get raw server entitlements
const serverEntitlements = await getEntitlements(forceRefresh);
_validateAndFilterEntitlements(serverEntitlements); // will prune invalid entitlements
// Get trial days remaining
const trialDaysRemaining = await LoginService.getProTrialDaysRemaining();
// If no trial is active, return server entitlements as-is
if (trialDaysRemaining <= 0) {
return serverEntitlements;
}
// now we need to grant trial, as user is entitled to trial if he is here.
// User has active server plan(either with login or device license)
if (serverEntitlements && serverEntitlements.plan) {
if (serverEntitlements.plan.isSubscriber) {
// Already a subscriber(or has device license), return as-is
// never inject trail data in this case.
return serverEntitlements;
}
// Enhance entitlements for trial user
// user in not a paid subscriber(nor he has device license), inject trial
return {
...serverEntitlements,
plan: {
...serverEntitlements.plan,
isSubscriber: true,
paidSubscriber: serverEntitlements.plan.paidSubscriber || false,
name: brackets.config.main_pro_plan,
fullName: brackets.config.main_pro_plan,
validTill: dateNowFn() + trialDaysRemaining * MS_IN_DAY
},
isInProTrial: true,
trialDaysRemaining: trialDaysRemaining,
entitlements: {
...serverEntitlements.entitlements,
// below we only override things we grant in trial. AI which is not part of trial
// is always server injected. the EntitlementsManager will resolve it appropriately.
liveEdit: {
activated: true,
subscribeURL: brackets.config.purchase_url,
upgradeToPlan: brackets.config.main_pro_plan,
validTill: dateNowFn() + trialDaysRemaining * MS_IN_DAY
}
}
};
}
// Non-logged-in, non licensed user with trial - return synthetic entitlements
return {
plan: {
isSubscriber: true,
paidSubscriber: false,
name: brackets.config.main_pro_plan,
fullName: brackets.config.main_pro_plan,
validTill: dateNowFn() + trialDaysRemaining * MS_IN_DAY
},
isInProTrial: true,
trialDaysRemaining: trialDaysRemaining,
entitlements: {
// below we only override things we grant in trial. AI which is not part of trial
// is always server injected. the EntitlementsManager will resolve it appropriately.
liveEdit: {
activated: true,
subscribeURL: brackets.config.purchase_url,
upgradeToPlan: brackets.config.main_pro_plan,
validTill: dateNowFn() + trialDaysRemaining * MS_IN_DAY
}
}
};
}
async function addDeviceLicense() {
deviceLicensePrimed = false;
PreferencesManager.stateManager.set(PREF_STATE_LICENSED_DEVICE_CHECK, true);
return NodeUtils.addDeviceLicenseSystemWide();
}
async function removeDeviceLicense() {
deviceLicensePrimed = false;
PreferencesManager.stateManager.set(PREF_STATE_LICENSED_DEVICE_CHECK, false);
return NodeUtils.removeDeviceLicenseSystemWide();
}
async function isLicensedDeviceSystemWide() {
return NodeUtils.isLicensedDeviceSystemWide();
}
let _isLicensedDeviceFlagForTest = false;
/**
* Checks if app is configured to check for device licenses at app start at system or user level.
*
* @returns {Promise<boolean>} - Resolves with `true` if the device is licensed, `false` otherwise.
*/
async function isLicensedDevice() {
if(Phoenix.isTestWindow) {
return _isLicensedDeviceFlagForTest;
}
if(!Phoenix.isNativeApp) {
// browser app doesn't support device licence keys, obviously.
return false;
}
const userCheck = PreferencesManager.stateManager.get(PREF_STATE_LICENSED_DEVICE_CHECK);
const systemCheck = await isLicensedDeviceSystemWide();
return userCheck || systemCheck;
}
// Add functions to secure exports
LoginService.getEntitlements = getEntitlements;
LoginService.getEffectiveEntitlements = getEffectiveEntitlements;
LoginService.clearEntitlements = clearEntitlements;
LoginService.getSalt = getSalt;
LoginService.addDeviceLicense = addDeviceLicense;
LoginService.removeDeviceLicense = removeDeviceLicense;
LoginService.isLicensedDevice = isLicensedDevice;
LoginService.isLicensedDeviceSystemWide = isLicensedDeviceSystemWide;
LoginService.getDeviceID = getDeviceID;
LoginService.EVENT_ENTITLEMENTS_CHANGED = EVENT_ENTITLEMENTS_CHANGED;
async function handleReinstallCreds() {
if(!Phoenix.isNativeApp) {
throw new Error("Reinstall credentials is only available in native apps");
}
try {
await KernalModeTrust.reinstallCreds();
console.log("Credentials reinstalled successfully");
} catch (error) {
console.error("Error reinstalling credentials:", error);
throw error;
}
}
let inited = false;
function init() {
if(inited){
return;
}
inited = true;
EntitlementsDirectImport.init();
// Register reinstall credentials command for native apps only
if(Phoenix.isNativeApp) {
CommandManager.register("Reinstall Credentials", Commands.REINSTALL_CREDS, handleReinstallCreds);
}
}
// Test-only exports for integration testing
if (Phoenix.isTestWindow) {
window._test_login_service_exports = {
LoginService,
setIsLicensedDevice: function (_isLicensedDevice) {
_isLicensedDeviceFlagForTest = _isLicensedDevice;
},
setFetchFn: function (fn) {
fetchFn = fn;
},
setDateNowFn: function (fn) {
dateNowFn = fn;
},
_validateAndFilterEntitlements: _validateAndFilterEntitlements
};
}
// Start the entitlements monitor timer
startEffectiveEntitlementsMonitor();
exports.init = init;
// no public exports to prevent extension tampering
});