backend-manager 3.2.170 → 3.2.172

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +1 -1
  3. package/dist/cli/cli.js +1534 -0
  4. package/dist/manager/functions/core/actions/api/admin/backup.js +338 -0
  5. package/dist/manager/functions/core/actions/api/admin/create-post.js +388 -0
  6. package/dist/manager/functions/core/actions/api/admin/cron.js +37 -0
  7. package/dist/manager/functions/core/actions/api/admin/database-read.js +35 -0
  8. package/dist/manager/functions/core/actions/api/admin/database-write.js +39 -0
  9. package/dist/manager/functions/core/actions/api/admin/edit-post.js +158 -0
  10. package/dist/manager/functions/core/actions/api/admin/firestore-query.js +165 -0
  11. package/dist/manager/functions/core/actions/api/admin/firestore-read.js +38 -0
  12. package/dist/manager/functions/core/actions/api/admin/firestore-write.js +54 -0
  13. package/dist/manager/functions/core/actions/api/admin/get-stats.js +269 -0
  14. package/dist/manager/functions/core/actions/api/admin/payment-processor.js +57 -0
  15. package/dist/manager/functions/core/actions/api/admin/run-hook.js +95 -0
  16. package/dist/manager/functions/core/actions/api/admin/send-notification.js +197 -0
  17. package/dist/manager/functions/core/actions/api/admin/sync-users.js +125 -0
  18. package/dist/manager/functions/core/actions/api/admin/templates/post.html +16 -0
  19. package/dist/manager/functions/core/actions/api/firebase/get-providers.js +102 -0
  20. package/dist/manager/functions/core/actions/api/general/emails/general:download-app-link.js +21 -0
  21. package/dist/manager/functions/core/actions/api/general/fetch-post.js +99 -0
  22. package/dist/manager/functions/core/actions/api/general/generate-uuid.js +41 -0
  23. package/dist/manager/functions/core/actions/api/general/send-email.js +112 -0
  24. package/dist/manager/functions/core/actions/api/handler/create-post.js +146 -0
  25. package/dist/manager/functions/core/actions/api/special/setup-electron-manager-client.js +103 -0
  26. package/dist/manager/functions/core/actions/api/template.js +33 -0
  27. package/dist/manager/functions/core/actions/api/test/authenticate.js +22 -0
  28. package/dist/manager/functions/core/actions/api/test/create-test-accounts.js +27 -0
  29. package/dist/manager/functions/core/actions/api/test/lab.js +55 -0
  30. package/dist/manager/functions/core/actions/api/test/redirect.js +26 -0
  31. package/dist/manager/functions/core/actions/api/test/webhook.js +30 -0
  32. package/dist/manager/functions/core/actions/api/user/create-custom-token.js +32 -0
  33. package/dist/manager/functions/core/actions/api/user/delete.js +68 -0
  34. package/dist/manager/functions/core/actions/api/user/get-active-sessions.js +45 -0
  35. package/dist/manager/functions/core/actions/api/user/get-subscription-info.js +49 -0
  36. package/dist/manager/functions/core/actions/api/user/oauth2/discord.js +114 -0
  37. package/dist/manager/functions/core/actions/api/user/oauth2/google.js +99 -0
  38. package/dist/manager/functions/core/actions/api/user/oauth2.js +476 -0
  39. package/dist/manager/functions/core/actions/api/user/regenerate-api-keys.js +54 -0
  40. package/dist/manager/functions/core/actions/api/user/resolve.js +32 -0
  41. package/dist/manager/functions/core/actions/api/user/sign-out-all-sessions.js +118 -0
  42. package/dist/manager/functions/core/actions/api/user/sign-up copy.js +544 -0
  43. package/dist/manager/functions/core/actions/api/user/sign-up.js +99 -0
  44. package/dist/manager/functions/core/actions/api/user/submit-feedback.js +96 -0
  45. package/dist/manager/functions/core/actions/api/user/validate-settings.js +86 -0
  46. package/dist/manager/functions/core/actions/api.js +354 -0
  47. package/dist/manager/functions/core/actions/create-post-handler.js +184 -0
  48. package/dist/manager/functions/core/actions/generate-uuid.js +62 -0
  49. package/dist/manager/functions/core/actions/sign-up-handler.js +205 -0
  50. package/dist/manager/functions/core/admin/create-post.js +206 -0
  51. package/dist/manager/functions/core/admin/firestore-write.js +72 -0
  52. package/dist/manager/functions/core/admin/get-stats.js +218 -0
  53. package/dist/manager/functions/core/admin/query.js +198 -0
  54. package/dist/manager/functions/core/admin/send-notification.js +206 -0
  55. package/dist/manager/functions/core/cron/daily/ghostii-auto-publisher.js +377 -0
  56. package/dist/manager/functions/core/cron/daily/reset-usage.js +197 -0
  57. package/dist/manager/functions/core/cron/daily.js +114 -0
  58. package/dist/manager/functions/core/events/auth/before-create.js +124 -0
  59. package/dist/manager/functions/core/events/auth/before-signin.js +62 -0
  60. package/dist/manager/functions/core/events/auth/on-create copy.js +121 -0
  61. package/dist/manager/functions/core/events/auth/on-create.js +564 -0
  62. package/dist/manager/functions/core/events/auth/on-delete.js +72 -0
  63. package/dist/manager/functions/core/events/firestore/on-subscription.js +107 -0
  64. package/dist/manager/functions/test/authenticate.js +38 -0
  65. package/dist/manager/functions/test/create-test-accounts.js +144 -0
  66. package/dist/manager/functions/test/webhook.js +37 -0
  67. package/dist/manager/functions/wrappers/mailchimp/addToList.js +25 -0
  68. package/dist/manager/helpers/analytics copy.js +217 -0
  69. package/dist/manager/helpers/analytics.js +467 -0
  70. package/dist/manager/helpers/api-manager.js +324 -0
  71. package/dist/manager/helpers/assistant.js +1043 -0
  72. package/dist/manager/helpers/metadata.js +32 -0
  73. package/dist/manager/helpers/middleware.js +154 -0
  74. package/dist/manager/helpers/roles.js +69 -0
  75. package/dist/manager/helpers/settings.js +158 -0
  76. package/dist/manager/helpers/subscription-resolver-new.js +828 -0
  77. package/dist/manager/helpers/subscription-resolver.js +842 -0
  78. package/dist/manager/helpers/usage.js +381 -0
  79. package/dist/manager/helpers/user.js +198 -0
  80. package/dist/manager/helpers/utilities.js +292 -0
  81. package/dist/manager/index.js +1076 -0
  82. package/dist/manager/libraries/openai.js +460 -0
  83. package/dist/manager/routes/restart/index.js +52 -0
  84. package/dist/manager/routes/test/index.js +43 -0
  85. package/dist/manager/schemas/restart.js +13 -0
  86. package/dist/manager/schemas/test.js +13 -0
  87. package/dist/require.js +3 -0
  88. package/package.json +19 -9
@@ -0,0 +1,324 @@
1
+ const moment = require('moment');
2
+ const fetch = require('node-fetch');
3
+ const uuidv5 = require('uuid').v5;
4
+ const { get, set, merge } = require('lodash');
5
+
6
+ let sampleUser = {
7
+ api: {},
8
+ auth: {},
9
+ plan: {
10
+ id: '',
11
+ limits: {
12
+
13
+ }
14
+ },
15
+ authenticated: false,
16
+ _APIManager: {
17
+ meta: {
18
+ lastStatsReset: new Date(),
19
+ lastUserFetch: new Date(),
20
+ }
21
+ }
22
+ }
23
+
24
+ function ApiManager(m) {
25
+ const self = this;
26
+ self.Manager = m;
27
+ self.options = {
28
+ appId: '',
29
+ plans: {},
30
+ maxUsersStored: 10000,
31
+ refetchInterval: 60,
32
+ resetInterval: 60 * 24,
33
+ officialAPIKeys: [],
34
+ };
35
+ self.userList = [];
36
+ self.initialized = false;
37
+ }
38
+
39
+ ApiManager.prototype.init = function (options) {
40
+ const self = this;
41
+ return new Promise(async function(resolve, reject) {
42
+ options = options || {};
43
+ options.app = options.app || '';
44
+ options.plans = options.plans || {};
45
+
46
+ // await self.Manager.libraries.admin.firestore
47
+ // options.plans.basic = options.plans.basic || {requests: 100};
48
+
49
+ options.maxUsersStored = options.maxUsersStored || 10000;
50
+ options.refetchInterval = options.refetchInterval || 60;
51
+ options.resetInterval = options.resetInterval || (60 * 24);
52
+ options.officialAPIKeys = options.officialAPIKeys || [];
53
+ options.whitelistedAPIKeys = options.whitelistedAPIKeys || [];
54
+
55
+ await fetch('https://us-central1-itw-creative-works.cloudfunctions.net/getApp', {
56
+ method: 'POST',
57
+ headers: { 'Content-Type': 'application/json' },
58
+ body: JSON.stringify({
59
+ id: options.app,
60
+ }),
61
+ })
62
+ .then(res => {
63
+ res.text()
64
+ .then(text => {
65
+ if (res.ok) {
66
+ const data = JSON.parse(text);
67
+
68
+ options.plans = {};
69
+
70
+ Object.keys(data.products)
71
+ .forEach((id, i) => {
72
+ const product = data.products[id]
73
+ options.plans[product.planId] = {}
74
+ options.plans[product.planId].limits = product.limits || {};
75
+ });
76
+
77
+ self.options = options;
78
+ self.initialized = true;
79
+
80
+ return resolve(self);
81
+ } else {
82
+ throw new Error(text || res.statusText || 'Unknown error.')
83
+ }
84
+ })
85
+ })
86
+ .catch(e => {
87
+ return reject(e)
88
+ })
89
+ });
90
+ };
91
+
92
+ ApiManager.prototype._createNewUser = function (authenticatedUser, planId, persistentData, isRefetch, apiKey) {
93
+ const self = this;
94
+ const _APIManager_default = {
95
+ stats: {
96
+ requests: 0,
97
+ },
98
+ meta: {
99
+ lastStatsReset: new Date(),
100
+ lastUserFetch: new Date(),
101
+ },
102
+ providedAPIKey: apiKey,
103
+ }
104
+ persistentData = persistentData || {};
105
+ persistentData._APIManager = persistentData._APIManager || merge({}, _APIManager_default);
106
+
107
+ let newUser = {
108
+ api: get(authenticatedUser, 'api', {}),
109
+ auth: get(authenticatedUser, 'auth', {}),
110
+ plan: {
111
+ id: planId,
112
+ limits: {
113
+ }
114
+ },
115
+ authenticated: authenticatedUser.authenticated,
116
+ ip: authenticatedUser.ip,
117
+ country: authenticatedUser.country,
118
+ _APIManager: merge({}, _APIManager_default),
119
+ }
120
+
121
+ // Setup newUser
122
+ const currentPlan = get(self.options, `plans.${planId}.limits`, {})
123
+ Object.keys(currentPlan)
124
+ .forEach((id, i) => {
125
+ // console.log('----id', id);
126
+ // console.log('======currentPlan[id]', currentPlan[id]);
127
+ newUser.plan.limits[id] = get(authenticatedUser, `plan.limits.${id}`, currentPlan[id])
128
+ // const product = data.products[id]
129
+ // options.plans[product.planId] = {}
130
+ // options.plans[product.planId].limits = product.limits || {};
131
+ });
132
+
133
+
134
+
135
+ // console.log('-----MIN', moment().diff(moment(persistentData._APIManager.meta.lastStatsReset), 'minutes', true), self.options.resetInterval);
136
+ if (moment().diff(moment(persistentData._APIManager.meta.lastStatsReset), 'minutes', true) < self.options.resetInterval) {
137
+ newUser._APIManager.meta.lastStatsReset = persistentData._APIManager.meta.lastStatsReset || newUser._APIManager.meta.lastStatsReset;
138
+ newUser._APIManager.meta.lastUserFetch = persistentData._APIManager.meta.lastUserFetch || newUser._APIManager.meta.lastUserFetch;
139
+ Object.keys(persistentData._APIManager.stats)
140
+ .forEach((key, i) => {
141
+ newUser._APIManager.stats[key] = persistentData._APIManager.stats[key];
142
+ });
143
+ } else {
144
+ // console.log('---RESSET INTERVAL REACHED');
145
+ newUser._APIManager.meta.lastUserFetch = persistentData._APIManager.meta.lastUserFetch;
146
+ }
147
+
148
+ if (isRefetch) {
149
+ newUser._APIManager.meta.lastUserFetch = new Date();
150
+ }
151
+
152
+ return newUser;
153
+ }
154
+
155
+ ApiManager.prototype.getUser = async function (assistant) {
156
+ const self = this;
157
+
158
+ let newUser;
159
+ let apiKey = assistant.request.data.apiKey;
160
+ let authenticatedUser;
161
+ let persistentData = {set: false};
162
+ // console.log('---getuser for', apiKey);
163
+ if (apiKey) {
164
+ newUser = self.userList.filter(user => user.api.privateKey === apiKey);
165
+ if (newUser[0]) {
166
+ if (newUser.length > 1 || moment().diff(moment(newUser[0]._APIManager.meta.lastUserFetch), 'minutes', true) > self.options.refetchInterval) {
167
+ // console.log('----REFETCHING');
168
+ persistentData = {set: true, _APIManager: merge({}, newUser[0]._APIManager)};
169
+
170
+ self.userList = self.userList.filter(user => user.api.privateKey !== apiKey)
171
+ newUser = null;
172
+ } else {
173
+ persistentData = {set: true, _APIManager: merge({}, newUser[0]._APIManager)};
174
+
175
+ newUser = newUser[0];
176
+ }
177
+ } else {
178
+ newUser = null;
179
+ }
180
+ }
181
+
182
+ // console.log('---persistentData', persistentData);
183
+
184
+ if (!newUser) {
185
+ // console.log('---doesnt exist so reauthing');
186
+ authenticatedUser = await assistant.authenticate({apiKey: apiKey});
187
+ // console.log('---authenticatedUser', authenticatedUser);
188
+ const planId = get(authenticatedUser, 'plan.id', 'basic');
189
+ let workingUID = !authenticatedUser.authenticated
190
+ ? uuidv5(assistant.request.geolocation.ip, '1b671a64-40d5-491e-99b0-da01ff1f3341')
191
+ : authenticatedUser.auth.uid
192
+ authenticatedUser.ip = assistant.request.geolocation.ip;
193
+ authenticatedUser.country = assistant.request.geolocation.country;
194
+ // console.log('---workingUID', workingUID);
195
+ // console.log('----self.userList', self.userList);
196
+ let existingUser = self.userList.find(user => user.auth.uid === workingUID);
197
+ if (existingUser) {
198
+ // console.log('---actually does exist so setting');
199
+ // console.log('----1111 MIN lastUserFetch', moment().diff(moment(existingUser._APIManager.meta.lastUserFetch), 'minutes', true), self.options.refetchInterval);
200
+ persistentData = !persistentData.set ? {set: true, _APIManager: merge({}, existingUser._APIManager)} : persistentData;
201
+ // console.log('----persistentData 2', persistentData);
202
+ if (moment().diff(moment(existingUser._APIManager.meta.lastUserFetch), 'minutes', true) > self.options.refetchInterval) {
203
+ // console.log('----REFETCHING');
204
+ self.userList = self.userList.filter(user => user.auth.uid !== workingUID)
205
+ existingUser = self._createNewUser(authenticatedUser, planId, persistentData, true, apiKey);
206
+ existingUser.auth.uid = workingUID;
207
+ self.userList = self.userList.concat(existingUser);
208
+ }
209
+ newUser = existingUser
210
+ } else {
211
+ // console.log('---actually doesnt exist making new user');
212
+ newUser = self._createNewUser(authenticatedUser, planId, persistentData, false, apiKey)
213
+ newUser.auth.uid = workingUID;
214
+ self.userList = self.userList.concat(newUser);
215
+ }
216
+
217
+ }
218
+
219
+ return newUser;
220
+ // console.log('---workingUID', workingUID);
221
+
222
+ };
223
+
224
+ function _getUserStat(self, user, stat, def) {
225
+ const isWhitelistedAPIKey = self.options.whitelistedAPIKeys.includes(
226
+ get(user, `api.privateKey`, get(user, `_APIManager.providedAPIKey`))
227
+ );
228
+ // console.log('----user', user);
229
+ // console.log('----isWhitelistedAPIKey', isWhitelistedAPIKey);
230
+ return {
231
+ current: !isWhitelistedAPIKey ? get(user, `_APIManager.stats.${stat}`, typeof def !== 'undefined' ? def : 0) : 0,
232
+ limit: !isWhitelistedAPIKey ? get(user, `plan.limits.${stat}`, typeof def !== 'undefined' ? def : 0) : Infinity,
233
+ }
234
+ }
235
+
236
+ ApiManager.prototype.isUserOverStat = function (user, stat, def, frame) {
237
+ const self = this;
238
+ if (!user || !stat) {
239
+ throw new Error('<user> and <stat> required')
240
+ }
241
+ const result = self.getUserStat(user, stat, def);
242
+ frame = frame || 'daily';
243
+ let limit = result.limit;
244
+ // console.log('---result', result);
245
+ // console.log('---typeof result.current', typeof result.current);
246
+ // console.log('----limit', limit);
247
+ if (typeof result.limit === 'number') {
248
+ if (frame === 'daily') {
249
+ limit = Math.floor(result.limit / 31);
250
+ }
251
+ // console.log('----limit', limit);
252
+ // console.log('-----result.current < limit', result.current < limit);
253
+ return limit >= result.current;
254
+ }
255
+
256
+ return false;
257
+ }
258
+
259
+ ApiManager.prototype.getUserStat = function (user, stat, def, ) {
260
+ const self = this;
261
+ if (!user || !stat) {
262
+ throw new Error('<user> and <stat> required')
263
+ }
264
+ return _getUserStat(self, user, stat, def);
265
+ }
266
+
267
+ ApiManager.prototype.incrementUserStat = function (user, stat, amount) {
268
+ const self = this;
269
+ if (!user || !stat) {
270
+ throw new Error('<user> and <stat> required')
271
+ }
272
+ set(user, `_APIManager.stats.${stat}`, get(user, `_APIManager.stats.${stat}`, 0) + amount)
273
+ return _getUserStat(self, user, stat, 0);
274
+ }
275
+
276
+
277
+ ApiManager.prototype.validateOfficialRequest = async function (assistant, apiUser) {
278
+ const self = this
279
+ let data = assistant.request.data;
280
+ let multipartData;
281
+ assistant.ref.Manager.libraries.hcaptcha = assistant.ref.Manager.libraries.hcaptcha || assistant.ref.Manager.require('hcaptcha');
282
+ const hcaptcha = assistant.ref.Manager.libraries.hcaptcha;
283
+
284
+ const contentType = get(assistant.ref.req.headers, 'content-type', '');
285
+ const requestType = !contentType || contentType.includes('application/json') ? 'json' : 'form';
286
+
287
+ // console.log('----requestType', requestType);
288
+ if (requestType !== 'json') {
289
+ multipartData = await assistant.parseMultipartFormData();
290
+ data = multipartData.fields;
291
+ // console.log('----multipartData', multipartData);
292
+ }
293
+
294
+ if (self.options.officialAPIKeys.includes(data.apiKey)) {
295
+ const captchaResult = await hcaptcha.verify(process.env.HCAPTCHA_SECRET, data['h-captcha-response'])
296
+ .then((data) => data)
297
+ .catch((e) => e);
298
+ if (!captchaResult || captchaResult instanceof Error || !captchaResult.success) {
299
+ // console.log(`Cap`);
300
+ assistant.ref.res.status(400).send(new Error(`Captcha verification failed.`).message);
301
+ return {
302
+ ok: false,
303
+ official: true,
304
+ verified: false,
305
+ }
306
+ } else {
307
+ self.incrementUserStat(apiUser, 'requests', -1);
308
+ return {
309
+ ok: true,
310
+ official: true,
311
+ verified: true,
312
+ }
313
+ }
314
+ // workingUser.requestsCurrent--;
315
+ } else {
316
+ return {
317
+ ok: true,
318
+ official: false,
319
+ verified: true,
320
+ }
321
+ }
322
+ }
323
+
324
+ module.exports = ApiManager;