-
-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathlogin-service.js
More file actions
339 lines (302 loc) · 12.5 KB
/
login-service.js
File metadata and controls
339 lines (302 loc) · 12.5 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
/*
* 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.
*
*/
/**
* 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");
const Metrics = require("utils/Metrics");
const LoginUtils = require("./login-utils");
const MS_IN_DAY = 10 * 24 * 60 * 60 * 1000;
const TEN_MINUTES = 10 * 60 * 1000;
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 = null;
// Last recorded state for entitlements monitoring
let lastRecordedState = null;
// Debounced trigger for entitlements changed
let entitlementsChangedTimer = null;
function _debounceEntitlementsChanged() {
if (entitlementsChangedTimer) {
// already scheduled, skip
return;
}
entitlementsChangedTimer = setTimeout(() => {
LoginService.trigger(EVENT_ENTITLEMENTS_CHANGED);
entitlementsChangedTimer = null;
}, 1000); // atmost 1 entitlement changed event will be triggered in a second
}
/**
* Get entitlements from API or cache
* Returns null if user is not logged in
*/
async function getEntitlements(forceRefresh = false) {
// Return null if not logged in
if (!LoginService.isLoggedIn()) {
return null;
}
// Return cached data if available and not forcing refresh
if (cachedEntitlements && !forceRefresh) {
return cachedEntitlements;
}
try {
const accountBaseURL = LoginService.getAccountBaseURL();
const language = brackets.getLocale();
let url = `${accountBaseURL}/getAppEntitlements?lang=${language}`;
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 {
console.error('Missing appSessionID or validationCode for desktop app entitlements');
return null;
}
} else {
// Browser app: use session cookies
fetchOptions.credentials = 'include';
}
const response = await fetch(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;
// Trigger event if entitlements changed
if (entitlementsChanged) {
_debounceEntitlementsChanged();
}
return cachedEntitlements;
}
}
} catch (error) {
console.error('Failed to fetch entitlements:', error);
}
return null;
}
/**
* Clear cached entitlements and trigger change event
* Called when user logs out
*/
function clearEntitlements() {
if (cachedEntitlements) {
cachedEntitlements = null;
_debounceEntitlementsChanged();
}
}
/**
* Start the 10-minute interval timer for monitoring entitlements
*/
function startEntitlementsMonitor() {
setInterval(async () => {
try {
const current = await getEffectiveEntitlements(false); // Get effective entitlements
// Check if we need to refresh
const expiredPlanName = LoginUtils.validTillExpired(current, lastRecordedState);
const hasChanged = LoginUtils.haveEntitlementsChanged(current, 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");
await getEffectiveEntitlements(true); // Force refresh
// 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 = current;
} catch (error) {
console.error('Entitlements monitor error:', error);
}
}, TEN_MINUTES);
console.log('Entitlements monitor started (10-minute interval)');
}
/**
* Get effective entitlements for determining feature availability throughout the app.
* This is the primary API that should be used across Phoenix to check entitlements and enable/disable features.
*
* @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: {
* paidSubscriber: true, // Always true for trial users
* name: "Phoenix Pro"
* },
* 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.paidSubscriber: false`, injects `paidSubscriber: true`
* - Adds `isInProTrial: true` and `trialDaysRemaining`
* - Injects `entitlements.liveEdit.activated: true`
* - Note: Trial users may not be actual paid subscribers, but `paidSubscriber: true` is set
* so all Phoenix code treats them as paid subscribers
*
* **For logged-in users (full remote response):**
* ```javascript
* {
* isSuccess: boolean,
* lang: string,
* plan: {
* name: "Phoenix Pro",
* 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
* },
* liveEditAI: {
* activated: boolean,
* subscribeURL: string,
* purchaseCreditsURL: string, // URL to purchase AI credits
* upgradeToPlan: string,
* validTill: number
* }
* }
* }
* ```
*
* @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?.paidSubscriber) {
* // 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);
// Get trial days remaining
const trialDaysRemaining = await LoginService.getProTrialDaysRemaining();
// If no trial is active, return server entitlements as-is
if (trialDaysRemaining <= 0) {
return serverEntitlements;
}
// User has active trial
if (serverEntitlements && serverEntitlements.plan) {
// Logged-in user with trial
if (serverEntitlements.plan.paidSubscriber) {
// Already a paid subscriber, return as-is
return serverEntitlements;
}
// Enhance entitlements for trial user
return {
...serverEntitlements,
plan: {
...serverEntitlements.plan,
paidSubscriber: true,
name: brackets.config.main_pro_plan,
validTill: Date.now() + trialDaysRemaining * MS_IN_DAY
},
isInProTrial: true,
trialDaysRemaining: trialDaysRemaining,
entitlements: {
...serverEntitlements.entitlements,
liveEdit: {
activated: true,
subscribeURL: brackets.config.purchase_url,
upgradeToPlan: brackets.config.main_pro_plan,
validTill: Date.now() + trialDaysRemaining * MS_IN_DAY
}
}
};
}
// Non-logged-in user with trial - return synthetic entitlements
return {
plan: {
paidSubscriber: true,
name: brackets.config.main_pro_plan,
validTill: Date.now() + trialDaysRemaining * MS_IN_DAY
},
isInProTrial: true,
trialDaysRemaining: trialDaysRemaining,
entitlements: {
liveEdit: {
activated: true,
subscribeURL: brackets.config.purchase_url,
upgradeToPlan: brackets.config.main_pro_plan,
validTill: Date.now() + trialDaysRemaining * MS_IN_DAY
}
}
};
}
// Add functions to secure exports
LoginService.getEntitlements = getEntitlements;
LoginService.getEffectiveEntitlements = getEffectiveEntitlements;
LoginService.clearEntitlements = clearEntitlements;
LoginService.EVENT_ENTITLEMENTS_CHANGED = EVENT_ENTITLEMENTS_CHANGED;
// Start the entitlements monitor timer
startEntitlementsMonitor();
});