t880216t-server 1.5.20

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 (104) hide show
  1. package/LICENSE +124 -0
  2. package/README.md +191 -0
  3. package/bin/nohost.js +178 -0
  4. package/bin/plugin.js +70 -0
  5. package/bin/util.js +93 -0
  6. package/index.js +89 -0
  7. package/lib/config.js +42 -0
  8. package/lib/index.js +205 -0
  9. package/lib/main/cgi/getSettings.js +11 -0
  10. package/lib/main/cgi/getVersion.js +12 -0
  11. package/lib/main/cgi/login.js +14 -0
  12. package/lib/main/cgi/restart.js +5 -0
  13. package/lib/main/cgi/setAdmin.js +6 -0
  14. package/lib/main/cgi/setDomain.js +13 -0
  15. package/lib/main/cgi/status.js +122 -0
  16. package/lib/main/index.js +94 -0
  17. package/lib/main/router.js +79 -0
  18. package/lib/main/storage.js +132 -0
  19. package/lib/main/util.js +138 -0
  20. package/lib/main/whistleMgr.js +56 -0
  21. package/lib/main/worker.js +52 -0
  22. package/lib/main/workerNum.js +11 -0
  23. package/lib/plugins/account/whistle.share/menu.html +171 -0
  24. package/lib/plugins/account/whistle.share/package.json +20 -0
  25. package/lib/plugins/account/whistle.storage/index.js +43 -0
  26. package/lib/plugins/account/whistle.storage/package.json +8 -0
  27. package/lib/plugins/account/whistle.storage/rules.txt +1 -0
  28. package/lib/plugins/whistle.nohost/_rules.txt +38 -0
  29. package/lib/plugins/whistle.nohost/index.js +3 -0
  30. package/lib/plugins/whistle.nohost/initial.js +9 -0
  31. package/lib/plugins/whistle.nohost/lib/accountMgr.js +750 -0
  32. package/lib/plugins/whistle.nohost/lib/envMgr.js +114 -0
  33. package/lib/plugins/whistle.nohost/lib/rulesServer.js +85 -0
  34. package/lib/plugins/whistle.nohost/lib/tunnelRulesServer.js +71 -0
  35. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/account/changePassword.js +8 -0
  36. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/activeAccount.js +9 -0
  37. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/addAccount.js +8 -0
  38. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/allAccounts.js +9 -0
  39. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/changeNotice.js +8 -0
  40. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/changePassword.js +8 -0
  41. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/enableGuest.js +5 -0
  42. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/getAuthKey.js +3 -0
  43. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/getSettings.js +22 -0
  44. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/login.js +14 -0
  45. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/move.js +9 -0
  46. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/removeAccount.js +9 -0
  47. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/setAccountRules.js +5 -0
  48. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/setAuthKey.js +5 -0
  49. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/setDefaultRules.js +5 -0
  50. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/setEntryPatterns.js +6 -0
  51. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/setJsonData.js +5 -0
  52. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/setRulesTpl.js +5 -0
  53. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/setTestRules.js +5 -0
  54. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/admin/specPattern.js +4 -0
  55. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/allowlist.js +4 -0
  56. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/entryRules.js +4 -0
  57. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/follow.js +17 -0
  58. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/getEnv.js +12 -0
  59. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/list.js +43 -0
  60. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/patterns.js +14 -0
  61. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/pluginRules.js +61 -0
  62. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/proxy.js +42 -0
  63. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/proxyNetwork.js +12 -0
  64. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/redirect.js +10 -0
  65. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/selectEnv.js +30 -0
  66. package/lib/plugins/whistle.nohost/lib/uiServer/cgi/unfollow.js +4 -0
  67. package/lib/plugins/whistle.nohost/lib/uiServer/index.js +60 -0
  68. package/lib/plugins/whistle.nohost/lib/uiServer/network.js +38 -0
  69. package/lib/plugins/whistle.nohost/lib/uiServer/openAPI.js +94 -0
  70. package/lib/plugins/whistle.nohost/lib/uiServer/router.js +85 -0
  71. package/lib/plugins/whistle.nohost/lib/util.js +230 -0
  72. package/lib/plugins/whistle.nohost/lib/whistle.js +149 -0
  73. package/lib/plugins/whistle.nohost/lib/whistleMgr.js +94 -0
  74. package/lib/plugins/whistle.nohost/package.json +7 -0
  75. package/lib/plugins/whistle.nohost/rules.txt +3 -0
  76. package/lib/service/cgi/export.js +76 -0
  77. package/lib/service/cgi/import.js +33 -0
  78. package/lib/service/cgi/util.js +35 -0
  79. package/lib/service/index.js +37 -0
  80. package/lib/service/router.js +7 -0
  81. package/lib/service/server.js +25 -0
  82. package/lib/util/address.js +55 -0
  83. package/lib/util/getPort.js +19 -0
  84. package/lib/util/login.js +55 -0
  85. package/lib/util/parseDomain.js +17 -0
  86. package/lib/whistle.js +86 -0
  87. package/package.json +135 -0
  88. package/pnpm-workspace.yaml +6 -0
  89. package/public/admin.75d42731d4aa7f7a558d3abf2a375fcb.js +2 -0
  90. package/public/admin.75d42731d4aa7f7a558d3abf2a375fcb.js.LICENSE.txt +76 -0
  91. package/public/admin.html +11 -0
  92. package/public/button.js +2 -0
  93. package/public/button.js.LICENSE.txt +31 -0
  94. package/public/capture.7bab900f27c9bb1b0e33523e994554ae.js +2 -0
  95. package/public/capture.7bab900f27c9bb1b0e33523e994554ae.js.LICENSE.txt +83 -0
  96. package/public/capture.html +11 -0
  97. package/public/eed368d0656f03932671530c3132ed61.svg +1 -0
  98. package/public/favicon.ico +0 -0
  99. package/public/network.e4814ec8c966a8a789296679619ec573.js +2 -0
  100. package/public/network.e4814ec8c966a8a789296679619ec573.js.LICENSE.txt +76 -0
  101. package/public/network.html +11 -0
  102. package/public/select.cb638be6656d02a558f2690acd59901a.js +2 -0
  103. package/public/select.cb638be6656d02a558f2690acd59901a.js.LICENSE.txt +24 -0
  104. package/public/select.html +26 -0
@@ -0,0 +1,750 @@
1
+ const getValue = require('lodash.get');
2
+ const { isIP } = require('net');
3
+ const httpMgr = require('whistle/lib/util/http-mgr');
4
+ const util = require('./util');
5
+ const { getServerIp } = require('../../../util/address');
6
+ const parseDomain = require('../../../util/parseDomain');
7
+
8
+ const generateShortId = () => {
9
+ return Date.now().toString(36) + Math.random().toString(36).substring(2, 8);
10
+ };
11
+
12
+ const { parseJSON, shasum } = util;
13
+ const MAX_ACCOUNT_COUNT = 120;
14
+ const MAX_PASSWORD_LENGTH = 24;
15
+ const KEY_RE = /^@(?:([\w.-]{1,64})(\/[^\s]+)?|\(([^\s]+)\))$/mg;
16
+ const NAME_RE = /^[\w.-]{1,24}$/;
17
+ const CRLF_RE = /\s*[\r\n]+\s*/g;
18
+ const CONFIG_RE = /^([\w-]{1,64}:?|[\w.-]{1,64}:)(?:\s+([\w.:/-]*[\w-]))?$/mg;
19
+ const ACCOUNT_NAME_VAR = /\$\{name\}/g;
20
+ const VAR_RE = /\$\{([\w.]+)\}/g;
21
+ const MAX_TEXT_LEN = 1512 * 10;
22
+ const NOHOST_VAR_RE = /^nohost_\w+$/;
23
+ const AUTH_KEY_RE = /^[\w.@-]{1,32}$/;
24
+ const SPECIAL_CHAR_RE = /[.$]/g;
25
+ const VALUE_RE = /(?:^[^\n\r\S]*(```+)[^\n\r\S]*\S+[^\n\r\S]*[\r\n][\s\S]+?[\r\n][^\n\r\S]*\1\s*|#.*)$/mg;
26
+ const INDEX_RE = /^(-?\d{1,15})\)/;
27
+ const INLINE_RULE_RE = /^\s*rules(``?)\s*[\r\n]([\w\W]+?)[\r\n]\s*\1\s*$/mg;
28
+ const DOMAIN_RE = /^(?:\*(\**)|[\w-]+)(?:\.[\w-]+)+$/;
29
+ const REG_EXP_RE = /^(\+)?\/(.+)\/([ium]{0,3})$/;
30
+ const REMOTE_RULES_RE = /^\s*@(https?:\/\/[^\s]+)\s*?$/gim;
31
+
32
+ let port = 8080;
33
+ let accountMap;
34
+ let storage;
35
+ let certsDomain;
36
+ let domainList = [];
37
+
38
+ const trimRules = (rules) => {
39
+ return rules.trim().replace(VALUE_RE, all => (all[0] === '#' ? '' : all)).replace(CRLF_RE, '\n');
40
+ };
41
+
42
+ const parseValues = (rules) => {
43
+ const values = {};
44
+ let index = 0;
45
+ rules = rules.trim().replace(VALUE_RE, (all) => {
46
+ if (all[0] === '#') {
47
+ return '';
48
+ }
49
+ const key = `#${++index}`;
50
+ values[key] = all;
51
+ return key;
52
+ }).replace(CRLF_RE, '\n');
53
+ return { rules, values };
54
+ };
55
+
56
+ const getString = (data) => {
57
+ const type = typeof data;
58
+ if (type === 'number') {
59
+ return String(data);
60
+ }
61
+ return typeof data === 'string' ? data : '';
62
+ };
63
+
64
+ const getStringProperty = (name) => {
65
+ return getString(storage.getProperty(name));
66
+ };
67
+
68
+ const sorter = (cur, next) => {
69
+ if (cur.index === next.index) {
70
+ return 0;
71
+ }
72
+ return cur.index > next.index ? -1 : 1;
73
+ };
74
+
75
+ const parseEntryPatterns = (str) => {
76
+ let patterns = [];
77
+ const preRules = [];
78
+ const postRules = [];
79
+ const allowlist = [];
80
+
81
+ str.trim().replace(INLINE_RULE_RE, (_, pos, rules) => {
82
+ rules = rules.trim();
83
+ if (!rules) {
84
+ return;
85
+ }
86
+ if (pos.length === 1) {
87
+ preRules.push(rules);
88
+ } else {
89
+ postRules.push(rules);
90
+ }
91
+ return '';
92
+ }).split(/\s+/).map((pattern) => {
93
+ if (pattern[0] === '#') {
94
+ return;
95
+ }
96
+ let index = 0;
97
+ if (INDEX_RE.test(pattern)) {
98
+ index = parseInt(RegExp.$1, 10);
99
+ pattern = pattern.substring(pattern.indexOf(')') + 1);
100
+ if (!pattern) {
101
+ return;
102
+ }
103
+ }
104
+ if (pattern[0] === '-') {
105
+ const ignore = pattern[1] === '-';
106
+ pattern = pattern.substring(ignore ? 2 : 1);
107
+ if (pattern) {
108
+ patterns.push({ pattern, index, ignore });
109
+ }
110
+ } else {
111
+ patterns.push({ pattern, index, button: true });
112
+ }
113
+ return pattern;
114
+ });
115
+ if (certsDomain) {
116
+ certsDomain.forEach((domain) => {
117
+ patterns.push({ pattern: domain, index: 0, button: true });
118
+ });
119
+ }
120
+ const map = {};
121
+ const entryRules = [];
122
+ const addAllowlist = (pattern) => {
123
+ if (pattern && allowlist.indexOf(pattern) === -1) {
124
+ allowlist.push(pattern);
125
+ }
126
+ };
127
+ patterns = patterns.sort(sorter).filter((item) => {
128
+ let { pattern } = item;
129
+ if (!map[pattern]) {
130
+ map[pattern] = 1;
131
+ if (DOMAIN_RE.test(pattern) || pattern === 'localhost') {
132
+ const stars = RegExp.$1;
133
+ if (stars) {
134
+ pattern = pattern.replace(stars, '');
135
+ if (stars.length > 1) {
136
+ addAllowlist(pattern.substring(2));
137
+ }
138
+ }
139
+ addAllowlist(pattern);
140
+ }
141
+ entryRules.push(`${item.pattern} whistle.nohost://${item.button ? '' : 'none'}`);
142
+ return true;
143
+ }
144
+ });
145
+ if (!map['local.whistlejs.com']) {
146
+ entryRules.push('local.whistlejs.com whistle.nohost://none');
147
+ }
148
+ return {
149
+ patterns,
150
+ preRules,
151
+ postRules,
152
+ allowlist,
153
+ entryRules: entryRules.join('\n'),
154
+ };
155
+ };
156
+
157
+ function parseSpecPattern(pattern) {
158
+ if (!pattern || !REG_EXP_RE.test(pattern)) {
159
+ return null;
160
+ }
161
+ const append = RegExp.$1;
162
+ pattern = RegExp.$2;
163
+ const mode = RegExp.$3;
164
+ const flags = [];
165
+ if (mode.includes('i')) {
166
+ flags.push('i');
167
+ }
168
+ if (mode.includes('u')) {
169
+ flags.push('u');
170
+ }
171
+ if (mode.includes('m')) {
172
+ flags.push('m');
173
+ }
174
+ return {
175
+ append,
176
+ pattern: new RegExp(pattern, flags.join('')),
177
+ };
178
+ }
179
+
180
+ class AccountMgr {
181
+ constructor() {
182
+ this.parseJsonData(getStringProperty('jsonData'));
183
+ this.parsePatterns();
184
+ httpMgr.addChangeListener(this._parseRules.bind(this));
185
+ this.parseRules();
186
+ }
187
+
188
+ parseRules() {
189
+ httpMgr.triggerChange();
190
+ }
191
+
192
+ enableGuest(enable) {
193
+ storage.setProperty('enableGuest', enable);
194
+ }
195
+
196
+ isEnableGuest() {
197
+ const enable = storage.getProperty('enableGuest');
198
+ return !!enable || enable === undefined;
199
+ }
200
+
201
+ parseTpl(name) {
202
+ let { pureRulesTpl, jsonData } = this;
203
+ if (!pureRulesTpl) {
204
+ return '';
205
+ }
206
+ pureRulesTpl = pureRulesTpl.replace(ACCOUNT_NAME_VAR, name);
207
+ pureRulesTpl = pureRulesTpl.replace(VAR_RE, (all, varName) => getString(getValue(jsonData, varName)));
208
+ return pureRulesTpl;
209
+ }
210
+
211
+ parsePatterns() {
212
+ const entryPatterns = getStringProperty('entryPatterns');
213
+ this.entryPatterns = entryPatterns;
214
+ const {
215
+ entryRules,
216
+ patterns,
217
+ preRules,
218
+ postRules,
219
+ allowlist,
220
+ } = parseEntryPatterns(entryPatterns);
221
+ this.entryRules = entryRules;
222
+ this.patterns = patterns;
223
+ this.preRules = preRules;
224
+ this.postRules = postRules;
225
+ this.allowlist = allowlist;
226
+ }
227
+
228
+ _parseRule(rules, defaultRules, testRules, varRegExp, keyValueMap) {
229
+ const headers = {};
230
+ const { rules: pureRules, values } = parseValues(rules);
231
+ let isSpec;
232
+ rules = pureRules.replace(CONFIG_RE, (_, key, value) => {
233
+ if (value) {
234
+ if (key.slice(-1) === ':') {
235
+ key = key.slice(0, -1);
236
+ }
237
+ key = `x-nohost-${key}`;
238
+ if (!headers[key]) {
239
+ isSpec = true;
240
+ headers[key] = value;
241
+ }
242
+ }
243
+ return '';
244
+ }).trim();
245
+ if (this.specPatternRE && (!isSpec || !this.specPatternRE.append)) {
246
+ isSpec = this.specPatternRE.pattern.test(rules);
247
+ }
248
+ Object.keys(values).forEach((k) => {
249
+ rules = rules.replace(k, values[k]);
250
+ });
251
+ rules = [rules];
252
+ if (isSpec && testRules) {
253
+ rules.push(testRules);
254
+ }
255
+ if (defaultRules) {
256
+ rules.push(defaultRules);
257
+ }
258
+ rules = rules.join('\n');
259
+ if (keyValueMap) {
260
+ rules = rules.replace(varRegExp, (all, space, key) => {
261
+ return `${space || ''}${keyValueMap[key]}`;
262
+ });
263
+ }
264
+ return { rules, headers };
265
+ }
266
+
267
+ _parseRules() {
268
+ const result = {};
269
+ const accountList = this.loadAllAccounts();
270
+ const list = [];
271
+ const rulesTpl = getStringProperty('rulesTpl');
272
+ let defaultRules = getStringProperty('defaultRules');
273
+ let testRules = getStringProperty('testRules');
274
+ this.rulesTpl = rulesTpl;
275
+ this.pureRulesTpl = trimRules(rulesTpl);
276
+ this.accountRules = getStringProperty('accountRules');
277
+ this.specPattern = getStringProperty('specPattern');
278
+ this.specPatternRE = parseSpecPattern(this.specPattern);
279
+ this.defaultRules = defaultRules;
280
+ this.testRules = testRules;
281
+ defaultRules = defaultRules && defaultRules.replace(REMOTE_RULES_RE, (_, rulesUrl) => {
282
+ return httpMgr.add(rulesUrl);
283
+ });
284
+ testRules = testRules && testRules.replace(REMOTE_RULES_RE, (_, rulesUrl) => {
285
+ return httpMgr.add(rulesUrl);
286
+ });
287
+ this.parsedMap = {};
288
+ accountMap = {};
289
+ accountList.forEach((account) => {
290
+ const { name, envList, active } = account;
291
+ accountMap[name] = account;
292
+ if (!active) {
293
+ return;
294
+ }
295
+ envList.forEach((env) => {
296
+ const rules = trimRules(`${env.rules}`);
297
+ const key = `${name}/${env.name}`;
298
+ env = { key, rules };
299
+ result[key] = rules;
300
+ list.push(env);
301
+ });
302
+ });
303
+
304
+ const dependencies = {};
305
+ list.forEach((env) => {
306
+ let { key, rules } = env;
307
+ if (!rules) {
308
+ return;
309
+ }
310
+ const { rules: pureRules, values } = parseValues(rules);
311
+ rules = pureRules.replace(KEY_RE, (all, name, envName, value) => {
312
+ envName = envName && envName.slice(1);
313
+ if (value || !envName) {
314
+ return this.parseTpl(value || name);
315
+ }
316
+ all = `${name}/${envName}`;
317
+ if (all === key || result[all] == null) {
318
+ return '';
319
+ }
320
+ const deps = dependencies[key];
321
+ if (deps) {
322
+ const index = deps.indexOf(all);
323
+ if (index === -1) {
324
+ deps.push(all);
325
+ }
326
+ } else {
327
+ dependencies[key] = [all];
328
+ }
329
+ return all;
330
+ });
331
+ Object.keys(values).forEach((k) => {
332
+ rules = rules.replace(k, values[k]);
333
+ });
334
+ result[key] = rules;
335
+ });
336
+ list.forEach((env) => {
337
+ const { key } = env;
338
+ const allDeps = { [key]: 1 };
339
+ const parseDeps = (k) => {
340
+ let rules = result[k];
341
+ if (!rules) {
342
+ allDeps[k] = 1;
343
+ return '';
344
+ }
345
+ const deps = dependencies[k];
346
+ if (deps) {
347
+ deps.forEach((d) => {
348
+ const exists = allDeps[d];
349
+ rules = rules.split(d);
350
+ if (!exists) {
351
+ allDeps[d] = 1;
352
+ rules.splice(rules.length - 1, 0, parseDeps(d));
353
+ }
354
+ rules = rules.join('');
355
+ });
356
+ }
357
+ return rules;
358
+ };
359
+ env.rules = parseDeps(key);
360
+ });
361
+ defaultRules = trimRules(defaultRules);
362
+ testRules = trimRules(testRules);
363
+ const { varRegExp, keyValueMap } = this;
364
+ list.forEach((env) => {
365
+ this.parsedMap[env.key] = this._parseRule(env.rules, defaultRules, testRules, varRegExp, keyValueMap);
366
+ });
367
+ }
368
+
369
+ parseJsonData(data) {
370
+ this.jsonDataStr = data;
371
+ data = parseJSON(data) || {};
372
+ this.jsonData = data;
373
+ this.keyValueMap = null;
374
+ this.varRegExp = null;
375
+ const regExp = [];
376
+ Object.keys(data).forEach((key) => {
377
+ const value = data[key];
378
+ if (value) {
379
+ const isVar = NOHOST_VAR_RE.test(key);
380
+ if (isVar || (isIP(key) === 4 && isIP(value) === 4)) {
381
+ this.keyValueMap = this.keyValueMap || {};
382
+ key = `${isVar ? '$' : ''}${key}`;
383
+ this.keyValueMap[key] = value;
384
+ regExp.push(`${key.replace(SPECIAL_CHAR_RE, '\\$&')}`);
385
+ }
386
+ }
387
+ });
388
+ if (this.keyValueMap) {
389
+ this.varRegExp = new RegExp(`(^|\\s)(${regExp.join('|')})\\b`, 'mg');
390
+ }
391
+ }
392
+
393
+ setJsonData(str) {
394
+ str = getString(str);
395
+ if (str.length > MAX_TEXT_LEN) {
396
+ return;
397
+ }
398
+ this.parseJsonData(str);
399
+ storage.setProperty('jsonData', str);
400
+ this.parseRules();
401
+ }
402
+
403
+ setRulesTpl(str) {
404
+ str = getString(str);
405
+ if (str.length > MAX_TEXT_LEN) {
406
+ return;
407
+ }
408
+ storage.setProperty('rulesTpl', str);
409
+ this.parseRules();
410
+ }
411
+
412
+ setEntryPatterns(str) {
413
+ str = getString(str);
414
+ if (str.length > MAX_TEXT_LEN) {
415
+ return;
416
+ }
417
+ storage.setProperty('entryPatterns', str);
418
+ this.parsePatterns();
419
+ }
420
+
421
+ setDefaultRules(str) {
422
+ str = getString(str);
423
+ if (str.length > MAX_TEXT_LEN) {
424
+ return;
425
+ }
426
+ storage.setProperty('defaultRules', str);
427
+ this.parseRules();
428
+ }
429
+
430
+ setSpecPattern(str) {
431
+ str = typeof str === 'string' ? str.trim() : '';
432
+ if (str.length <= 256) {
433
+ storage.setProperty('specPattern', str);
434
+ this.parseRules();
435
+ }
436
+ }
437
+
438
+ setAccountRules(str) {
439
+ str = getString(str);
440
+ if (str.length > MAX_TEXT_LEN) {
441
+ return;
442
+ }
443
+ storage.setProperty('accountRules', str);
444
+ this.parseRules();
445
+ }
446
+
447
+ setTestRules(str) {
448
+ str = getString(str);
449
+ if (str.length > MAX_TEXT_LEN) {
450
+ return;
451
+ }
452
+ storage.setProperty('testRules', str);
453
+ this.parseRules();
454
+ }
455
+
456
+ loadAllAccounts() {
457
+ let count = MAX_ACCOUNT_COUNT;
458
+ const result = [];
459
+ storage.getFileList(true).some((file) => {
460
+ let { account } = file;
461
+ if (!account) {
462
+ account = parseJSON(file.data);
463
+ file.account = account;
464
+ }
465
+ if (!account || !this.checkName(account.name)
466
+ || this.checkPassword(account.password)
467
+ || !Array.isArray(account.envList)) {
468
+ return false;
469
+ }
470
+ if (--count < 0) {
471
+ return true;
472
+ }
473
+ result.push(account);
474
+ return false;
475
+ });
476
+ return result;
477
+ }
478
+
479
+ addEnvList(accountName, envList) {
480
+ const account = this.getAccount(accountName);
481
+ if (!account) {
482
+ return false;
483
+ }
484
+ const list = [];
485
+ const existingEnvMap = {};
486
+ (account.envList || []).forEach((env) => {
487
+ existingEnvMap[env.name] = env;
488
+ });
489
+ envList.forEach(({ name, id, data }) => {
490
+ if (name) {
491
+ const existingEnv = existingEnvMap[name];
492
+ // 优先级:传入的id > 已存在的id > 自动生成
493
+ const envId = id || (existingEnv && existingEnv.id) || generateShortId();
494
+ list.push({
495
+ name,
496
+ id: envId,
497
+ rules: data,
498
+ });
499
+ }
500
+ });
501
+ account.envList = list;
502
+ this.saveAccount(account);
503
+ this.parseRules();
504
+ return true;
505
+ }
506
+
507
+ renameEnv(accountName, oldName, newName) {
508
+ const account = this.getAccount(accountName);
509
+ if (!account || !account.envList) {
510
+ return false;
511
+ }
512
+ const env = account.envList.find((e) => e.name === oldName);
513
+ if (!env) {
514
+ return false;
515
+ }
516
+ env.name = newName;
517
+ this.saveAccount(account);
518
+ this.parseRules();
519
+ return true;
520
+ }
521
+
522
+ checkName(name) {
523
+ return typeof name === 'string' && NAME_RE.test(name);
524
+ }
525
+
526
+ checkPassword(password) {
527
+ if (typeof password !== 'string') {
528
+ return false;
529
+ }
530
+ const len = password.length;
531
+ return len > 0 && len <= MAX_PASSWORD_LENGTH;
532
+ }
533
+
534
+ changePassword(name, password) {
535
+ if (!this.checkPassword(password)) {
536
+ return false;
537
+ }
538
+ const account = this.getAccount(name);
539
+ if (!account) {
540
+ return false;
541
+ }
542
+ account.password = shasum(password);
543
+ this.saveAccount(account);
544
+ return true;
545
+ }
546
+
547
+ /**
548
+ * 修改通知内容
549
+ */
550
+ changeNotice(name, notice) {
551
+ const account = this.getAccount(name);
552
+ if (!account) {
553
+ return false;
554
+ }
555
+
556
+ if (typeof notice !== 'string' || notice.trim().length > 32) {
557
+ return false;
558
+ }
559
+
560
+ account.notice = notice;
561
+ this.saveAccount(account);
562
+ return true;
563
+ }
564
+
565
+ addAccount(account) {
566
+ const { name, password } = account;
567
+ if (!this.checkName(name) || !this.checkPassword(password)
568
+ || storage.existsFile(name)) {
569
+ return false;
570
+ }
571
+ if (Object.keys(accountMap).length >= MAX_ACCOUNT_COUNT) {
572
+ return false;
573
+ }
574
+ account = {
575
+ name,
576
+ password: shasum(password),
577
+ active: true,
578
+ envList: [],
579
+ };
580
+ this.saveAccount(account);
581
+ this.parseRules();
582
+ return true;
583
+ }
584
+
585
+ moveAccount(fromName, toName) {
586
+ return storage.moveTo(fromName, toName);
587
+ }
588
+
589
+ removeAccount(name) {
590
+ const account = this.getAccount(name);
591
+ if (account) {
592
+ delete accountMap[name];
593
+ storage.removeFile(name);
594
+ }
595
+ this.parseRules();
596
+ return true;
597
+ }
598
+
599
+ activeAccount(name, active) {
600
+ const account = this.getAccount(name);
601
+ if (!account) {
602
+ return false;
603
+ }
604
+ account.active = active;
605
+ this.saveAccount(account);
606
+ this.parseRules();
607
+ return true;
608
+ }
609
+
610
+ saveAccount(account) {
611
+ storage.writeFile(account.name, JSON.stringify(account));
612
+ }
613
+
614
+ getAccount(name) {
615
+ return this.checkName(name) ? accountMap[name] : null;
616
+ }
617
+
618
+ getRulesByEnvId(accountName, envId) {
619
+ const account = this.getAccount(accountName);
620
+ if (!account || !account.envList) {
621
+ return { rules: '', headers: undefined };
622
+ }
623
+ const env = account.envList.find((e) => e.id === envId);
624
+ if (!env) {
625
+ return { rules: '', headers: undefined };
626
+ }
627
+ return this.parsedMap[`${accountName}/${env.name}`] || { rules: '', headers: undefined };
628
+ }
629
+
630
+ getEnvNameById(accountName, envId) {
631
+ const account = this.getAccount(accountName);
632
+ if (!account || !account.envList) {
633
+ return '';
634
+ }
635
+ const env = account.envList.find((e) => e.id === envId);
636
+ return env ? env.name : '';
637
+ }
638
+
639
+ getRules(name, envName) {
640
+ return this.parsedMap[`${name}/${envName}`] || { rules: '', headers: undefined };
641
+ }
642
+
643
+ getAllAccounts() {
644
+ const accountList = [];
645
+ this.loadAllAccounts().forEach((account) => {
646
+ account = this.getAccount(account.name);
647
+ if (account) {
648
+ accountList.push({
649
+ name: account.name,
650
+ active: account.active,
651
+ notice: account.notice,
652
+ });
653
+ }
654
+ });
655
+ return accountList;
656
+ }
657
+
658
+ getAccountList(parsed) {
659
+ const list = [];
660
+ const { parsedMap } = this;
661
+ this.loadAllAccounts().forEach((account) => {
662
+ const accountName = account.name;
663
+ account = this.getAccount(accountName);
664
+ if (!account || !account.active) {
665
+ return;
666
+ }
667
+ const envList = [];
668
+ account.envList.forEach(({ name, id, rules }) => {
669
+ if (!name || name[0] === '\r') {
670
+ return;
671
+ }
672
+ if (parsed === '1') {
673
+ rules = parsedMap[`${accountName}/${name}`];
674
+ } else if (parsed !== '0') {
675
+ rules = undefined;
676
+ }
677
+ envList.push({
678
+ name,
679
+ id: id || encodeURIComponent(name),
680
+ envId: id || encodeURIComponent(name),
681
+ rules,
682
+ });
683
+ });
684
+ list.push({
685
+ name: accountName,
686
+ active: account.active,
687
+ notice: account.notice,
688
+ envList,
689
+ });
690
+ });
691
+ return list;
692
+ }
693
+
694
+ getAuthKey() {
695
+ return storage.getProperty('authKey') || '';
696
+ }
697
+
698
+ setAuthKey(authKey) {
699
+ authKey = authKey || '';
700
+ if (!AUTH_KEY_RE.test(authKey)) {
701
+ return;
702
+ }
703
+ storage.setProperty('authKey', authKey);
704
+ }
705
+
706
+ setDefaultAuthKey(key) {
707
+ this.defaultAuthKey = AUTH_KEY_RE.test(key) ? key : null;
708
+ }
709
+
710
+ setDomain(domain) {
711
+ domainList = parseDomain(domain);
712
+ }
713
+
714
+ getDomainList() {
715
+ return domainList;
716
+ }
717
+
718
+ getBaseUrl() {
719
+ const domain = domainList[0] || getServerIp();
720
+ if (domain) {
721
+ return `${domain}:${port}`;
722
+ }
723
+ return 'local.whistlejs.com/plugin.nohost';
724
+ }
725
+ }
726
+
727
+ module.exports = (options) => {
728
+ storage = options.storage;
729
+ port = options.data.realPort;
730
+ const { getCustomCertsInfo } = options;
731
+ const accountMgr = new AccountMgr();
732
+ accountMgr.setDomain(options.data.domain);
733
+ (function loadCerts() {
734
+ getCustomCertsInfo((certs) => {
735
+ if (certs) {
736
+ // 如果更新证书会重启整个服务,所以无需一直轮询调用
737
+ certsDomain = Object.keys(certs);
738
+ accountMgr.parsePatterns();
739
+ } else {
740
+ setTimeout(loadCerts, 1000);
741
+ }
742
+ });
743
+ }());
744
+ accountMgr.storageServer = options.data.storageServer;
745
+ accountMgr.dnsServer = options.data.dnsServer;
746
+ accountMgr.accountPluginPath = options.data.accountPluginPath;
747
+ accountMgr.setDefaultAuthKey(options.data.authKey);
748
+ module.exports = accountMgr;
749
+ return accountMgr;
750
+ };