This repository has been archived by the owner on May 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 136
/
ncc_cf-worker.js
4208 lines (3717 loc) · 139 KB
/
ncc_cf-worker.js
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
globalThis.__dirname="";
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 417:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
function __ncc_wildcard$0 (arg) {
if (arg === "alidrive") return __nccwpck_require__(593);
else if (arg === "coding") return __nccwpck_require__(642);
else if (arg === "googledrive") return __nccwpck_require__(844);
else if (arg === "node_fs") return __nccwpck_require__(679);
else if (arg === "onedrive") return __nccwpck_require__(8);
else if (arg === "phony") return __nccwpck_require__(155);
else if (arg === "teambition") return __nccwpck_require__(824);
}
function __ncc_wildcard$1 (arg) {
if (arg === "simple.art") return __nccwpck_require__(533);
else if (arg === "w.w.art") return __nccwpck_require__(529);
else if (arg === "w.w") return __nccwpck_require__(463);
}
const op = __nccwpck_require__(525);
const app = __nccwpck_require__(750);
const { MODULES, THEMES } = __nccwpck_require__(791);
const { modules, themes } = op;
MODULES.forEach((k) => {
modules[k] = __ncc_wildcard$0(k);
});
THEMES.forEach((k) => {
themes[k] = __ncc_wildcard$1(k);
});
const header = __nccwpck_require__(37);
const template = __nccwpck_require__(203);
const admin = __nccwpck_require__(970);
const invokeModule = __nccwpck_require__(228);
const logger = __nccwpck_require__(885);
// fake koa app
app.use(header);
app.use(template);
app.use(admin);
app.use(__nccwpck_require__(554));
app.use(__nccwpck_require__(873));
app.use(__nccwpck_require__(158));
app.use(invokeModule);
module.exports = {
initialize(starter) {
op.initialize(starter);
},
async _handle(req) {
if (op.config.version === -1) {
// ? 代表未加载设置,尝试加载,若加载失败自动使用默认配置
await op.readConfig();
}
return app.handleRequest(req).then(({ response }) => {
if (typeof response.status !== 'number' || typeof response.headers !== 'object' || typeof response.body !== 'string') {
throw new Error('Internal Response Error');
}
return response;
});
},
async handleRequest(req) {
return this._handle(req).catch((err) => {
// 这一步遇到的错误一般都是请求类错误 格式错误 无法解析之类的
logger.error(err);
return {
status: 500,
headers: {
'access-control-allow-origin': '*',
'content-type': 'application/json',
},
body: JSON.stringify({ error: 'InternalError', message: err.message }),
};
});
},
};
/***/ }),
/***/ 791:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
// 系统配置参数,运行时只读
const config = {
PORT: 8020,
NODE_ENV: 'production',
SIGN_DELIMITER: '.',
PAGE_SIZE: 200,
ID_SIGN_LEN: 7,
PAGE_SIGN_LEN: 7,
CACHE_TIME_FILE: 15 * 60 * 1000,
CACHE_TIME_LIST: 30 * 60 * 1000,
AC_PASS_FILE: '.password=',
PATH_ADMIN: '/admin/',
PATH_API: '/api/',
PATH_DOWN: '/down:',
THEMES: ['w.w.art', 'simple.art'],
MODULES: ['node_fs', 'onedrive', 'coding', 'teambition', 'googledrive', 'alidrive', 'phony'],
};
const configTemplate = {
html: '<div>这是一段自定义html,你也可以在这里放置一些脚本文件</div>',
logo: 'https://cdn.onesrc.cn/uploads/images/onepoint_30.png',
name: 'DemoSite',
readme: `## 部署成功
恭喜部署成功,但这并不意味着系统能使用了
接下来,你需要进入 [admin](/admin/) 页面,完成一些必须的配置
要注意,某些平台的配置参数,可能需要你在平台上自行配置
配置完成后,就可以添加云盘了
`,
cors: ['*'],
proxy: [],
theme: config.THEMES[0],
};
config.configTemplate = configTemplate;
const { _P } = __nccwpck_require__(166);
const commonSParams = [
_P('theme', '', '', 8, config.THEMES, false, false),
_P('logo', '', '', 6, 'consume your own logo', false, false),
_P('name', '', '', 6, 'consume your site name', false, false),
_P('html', '', '', 6, 'embed html code', true, false),
_P('readme', '', '', 6, 'markdown supported', true, false),
_P('proxy', [], 'proxy for download', 4, '', false, false),
_P('cors', [], 'Allow CORS', 4, '', false, false),
];
commonSParams.forEach((e) => {
e.value = configTemplate[e.name];
});
config.commonSParams = commonSParams;
const commonMParams = [
_P('path', '', '', 8, 'mount path', false, true),
_P('module', '', '', 8, config.MODULES, false, true),
_P('password', '', '', 2, 'drive password', false, false),
_P('readme', '', '', 2, 'markdown supported', true, false),
// _P('desc', '', '', 2, 'short desc', false, false),
_P('hidden', [], '當前想要隱藏的文件或文件夾,例如 /images/today, /video/something.mp4', 2, '', false, false),
];
config.commonMParams = commonMParams;
config.getAdminHtml = function (baseURL, version) {
return `<!DOCTYPE html><html lang="en"><head><script>window.opConfigVersion=${version};window.opConfig=${JSON.stringify({
baseURL,
PATH_ADMIN: config.PATH_ADMIN,
PATH_API: config.PATH_API,
})}</script><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="same-origin"><link rel="icon" href="https://cdn.onesrc.cn/uploads/images/onepoint_30.png"><title>Just One Point</title><link href="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/css/app.820c0513.css" rel="preload" as="style"><link href="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/css/chunk-elementUI.6e808e7d.css" rel="preload" as="style"><link href="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/css/chunk-libs.1fd47c5d.css" rel="preload" as="style"><link href="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/js/app.1397f3a6.js" rel="preload" as="script"><link href="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/js/chunk-elementUI.46046ffc.js" rel="preload" as="script"><link href="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/js/chunk-libs.e78b2083.js" rel="preload" as="script"><link href="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/css/chunk-elementUI.6e808e7d.css" rel="stylesheet"><link href="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/css/chunk-libs.1fd47c5d.css" rel="stylesheet"><link href="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/css/app.820c0513.css" rel="stylesheet"></head><body><noscript><strong>We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.</strong></noscript><div id="app"></div><script>(function(e){function t(t){for(var n,i,l=t[0],p=t[1],a=t[2],c=0,s=[];c<l.length;c++)i=l[c],Object.prototype.hasOwnProperty.call(o,i)&&o[i]&&s.push(o[i][0]),o[i]=0;for(n in p)Object.prototype.hasOwnProperty.call(p,n)&&(e[n]=p[n]);f&&f(t);while(s.length)s.shift()();return u.push.apply(u,a||[]),r()}function r(){for(var e,t=0;t<u.length;t++){for(var r=u[t],n=!0,l=1;l<r.length;l++){var p=r[l];0!==o[p]&&(n=!1)}n&&(u.splice(t--,1),e=i(i.s=r[0]))}return e}var n={},o={runtime:0},u=[];function i(t){if(n[t])return n[t].exports;var r=n[t]={i:t,l:!1,exports:{}};return e[t].call(r.exports,r,r.exports,i),r.l=!0,r.exports}i.m=e,i.c=n,i.d=function(e,t,r){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},i.r=function(e){"undefined"!==typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"===typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(i.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var n in e)i.d(r,n,function(t){return e[t]}.bind(null,n));return r},i.n=function(e){var t=e&&e.__esModule?function(){return e["default"]}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/";var l=window["webpackJsonp"]=window["webpackJsonp"]||[],p=l.push.bind(l);l.push=t,l=l.slice();for(var a=0;a<l.length;a++)t(l[a]);var f=p;r()})([]);</script><script src="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/js/chunk-elementUI.46046ffc.js"></script><script src="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/js/chunk-libs.e78b2083.js"></script><script src="https://cdn.jsdelivr.net/gh/ukuq/onepoint-vue@v210503/dist/static/js/app.1397f3a6.js"></script></body></html>`;
};
module.exports = config;
/***/ }),
/***/ 750:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const { RTError, cookie2Str, query2Obj } = __nccwpck_require__(166);
class AppRequest {
constructor({ method, path, headers, body, query, cookies, baseURL, ip }) {
// UpperCase
this.method = method;
// parse path, path is just path,not url
this.path = decodeURIComponent(/^[^?]+/.exec(path)[0]);
this.headers = headers;
// parse body, stream is not supposed
this.body = typeof body === 'object' ? body : {};
if (method === 'POST' && typeof body === 'string' && headers['content-type']) {
if (headers['content-type'].includes('application/x-www-form-urlencoded')) {
this.body = query2Obj(body);
} else if (headers['content-type'].includes('application/json')) {
this.body = JSON.parse(body);
}
}
// parse query, object or like ?a=1&b=2 or a=1&b=2 or /a/b?aa
this.query = typeof query === 'string' ? query2Obj(query[0] === '/' ? /^[^?]+(.*)$/.exec(query)[1] : query) : query;
// parse cookie
this.cookies = cookies ? cookies : headers.cookie ? query2Obj(headers.cookie.replace(/;\s/g, '&')) : {};
// empty or like https://example.com or https://example.com/sub
if (baseURL) {
this.baseURL = baseURL;
const p0 = new URL(baseURL).pathname;
this.baseURLP0 = p0.endsWith('/') ? p0.slice(0, -1) : p0;
} else {
this.baseURL = 'https://' + headers.host;
this.baseURLP0 = '';
}
this.ip = ip;
}
}
class AppResponse {
constructor() {
this.headers = { 'content-type': 'text/html; charset=utf-8' };
this.body = '[Default Message]';
this.update(200);
}
update(status, type = '', data = { message: 'success' }) {
this.status = status;
this.type = type;
this.data = data;
}
get isPlain() {
return this.type === '';
}
get isFile() {
return this.type === 'file';
}
get isFolder() {
return this.type === 'folder';
}
get isList() {
return this.type === 'list';
}
get isRaw() {
return this.type === 'raw';
}
addCookie(name, value, options) {
if (!this.headers['set-cookie']) {
this.headers['set-cookie'] = [];
}
this.headers['set-cookie'].push(cookie2Str(name, value, options));
}
}
class AppContext {
constructor(request) {
this.request = new AppRequest(request);
this.response = new AppResponse();
this.state = { level: 0, time: Date.now(), p1: '', p2: '/' };
}
get path() {
return this.state.p1 + this.state.p2;
}
throw(status, msg, properties) {
throw new RTError(status, msg, properties);
}
assert(value, status, message, properties) {
if (!value) {
this.throw(status, message, properties);
}
}
respond(status, data = 'success') {
if (typeof data === 'string') {
this.response.update(status, '', { message: data });
} else {
this.response.update(status, '', data);
}
}
respondList(list, nextToken = null) {
this.response.update(200, 'list', { list, nextToken });
}
respondOne(item, down = null) {
if (item.type === 0) {
this.response.update(200, 'file', { file: item });
this.response.down = down;
} else {
this.response.update(200, 'folder', { folder: item });
}
}
respondRaw(status, headers = {}, body) {
headers['content-type'] = headers['content-type'] || 'text/html; charset=utf-8';
this.response.update(status, 'raw', '[raw object]');
this.response.headers = headers;
this.response.body = body;
}
redirect(url, always = false) {
if (url.startsWith('&')) {
const { path, query, baseURL } = this.request;
url = baseURL + encodeURI(path) + '?' + new URLSearchParams(Object.assign({}, query, query2Obj(url))).toString();
} else if (url.startsWith('?')) {
const { path, baseURL } = this.request;
url = baseURL + encodeURI(path) + url;
} else if (!url.startsWith('//') && url.startsWith('/')) {
url = this.request.baseURL + encodeURI(url);
}
const headers = this.response.headers;
headers.Location = url;
headers['content-type'] = 'text/html; charset=utf-8';
headers['referrer-policy'] = 'same-origin'; // ali-drive none referrer
this.respondRaw(always ? 301 : 302, headers, `Redirecting to <a href="${url}">${url}</a>.`);
}
addCookie(name, value, options) {
if (this.request.baseURLP0 && options && options.path) {
options.path = this.request.baseURLP0 + options.path;
}
this.response.addCookie(name, value, options);
}
}
module.exports = {
middleware: [],
use(fn) {
if (typeof fn === 'function' && !this.middleware.includes(fn)) {
this.middleware.push(fn);
}
return this;
},
async handleRequest(req) {
const ctx = new AppContext(req);
const middleware = this.middleware;
await (async function useMiddleware(ctx, index) {
if (index < middleware.length) {
return middleware[index](ctx, async () => useMiddleware(ctx, index + 1));
}
})(ctx, 0);
return ctx;
},
};
/***/ }),
/***/ 525:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const sysConfig = __nccwpck_require__(791);
const logger = __nccwpck_require__(885);
const { _sha1, NumberUtil, RTError, beautifyObject } = __nccwpck_require__(166);
const packageInfo = __nccwpck_require__(306);
module.exports = {
modules: {},
themes: {},
handleRequest: null,
server: {
version: packageInfo.version,
version2: packageInfo.version2,
},
initialize(starter) {
this.runtime = {
time_start: Date.now(),
time_read: null,
time_save: null,
error_read: null,
error_write: null,
};
this.starter = starter;
this.loadConfig({ version: -1 });
},
get params() {
return (this.starter.params || []).concat(sysConfig.commonSParams);
},
get privateModuleParams() {
return Object.entries(this.modules).reduce((o, [k, m]) => {
o[k] = typeof m.params === 'function' ? m.params() : m.params || [];
return o;
}, {});
},
get needConfig() {
return this.config.version === 1;
},
loadConfig(config) {
config = config || {};
config.site = Object.assign({}, sysConfig.configTemplate, config.site);
config.drives = config.drives || {};
config.users = config.users || { admin: { password: 'admin' } };
config.starter = config.starter || {};
config.version = config.version || 1;
const root = { $config: {}, $path: '/', next: {}, $cache: {} };
Object.entries(config.drives).forEach(([path, c]) => {
const m = this.modules[c.module];
if (m) {
let p = root;
for (const i of path.split('/').filter((e) => e)) {
if (!p.next[i]) {
p.next[i] = { $config: {}, $path: p.$path + i + '/', next: {}, $cache: {} };
}
p = p.next[i];
}
p.$config = c;
p.$module = m;
} else {
logger.warn('no such module: ' + path + ' ' + c.module);
}
});
this.root = root;
this.config = config;
this.salt = config.salt || '';
},
async readConfig() {
logger.debug('read config...');
this.runtime.time_read = Date.now();
this.runtime.error_read = null;
return this.starter
.readConfig()
.catch((e) => {
this.runtime.error_read = e;
logger.warn('read config... err:' + this.runtime.time_read);
logger.warn(e);
throw new RTError(500, 'ReadError', { msg: e.message });
})
.then((d) => {
logger.debug('read config... ok');
this.loadConfig(d);
});
},
// @Todo 后续可以考虑使用version解决 nowsh 异步保存的问题
async saveConfig(msg = '') {
logger.debug('save config...');
this.runtime.time_save = Date.now();
this.runtime.last_save = msg;
this.runtime.error_write = null;
const copy = beautifyObject(this.config);
copy.versionLast = copy.version;
copy.version = Date.now();
return await this.starter
.writeConfig(copy, copy.starter)
.then((m) => {
logger.debug('save config... ok');
this.config.version = copy.version;
this.config.versionLast = copy.versionLast;
this.salt = copy.salt;
return m || 'success';
})
.catch((err) => {
this.runtime.error_write = err;
logger.error('save config... err:' + this.runtime.time_save);
throw new RTError(500, 'SaveError', { msg: err.message });
});
},
sign(text, hours = 24, len = 16) {
const time = NumberUtil.to62(Math.floor(Date.now() / 1000 / 3600 + hours));
return time + _sha1(this.salt + time + text).slice(0, len - 4);
},
verify(text, sign, len = 16) {
const time = NumberUtil.parse62(sign.slice(0, 4)) * 3600 * 1000;
return time > Date.now() && sign.slice(4) === _sha1(this.salt + sign.slice(0, 4) + text).slice(0, len - 4);
},
signUser(name) {
const { password } = this.config.users[name];
return name + '.' + this.sign('$' + name + '.' + password + '$', 24);
},
verifyUser(token) {
const [n, s] = token.split('.');
const user = this.config.users[n];
return user && this.verify('$' + n + '.' + user.password + '$', s) && n;
},
deepestNode(path) {
let p = this.root;
for (const i of path.split('/').filter((e) => e)) {
if (p.next[i]) {
p = p.next[i];
} else {
return p;
}
}
return p;
},
// 设置p1 p2 $node, 调用模块前必须调用此函数以确认调用哪一个
parsePathBeforeInvoke(ctx, path) {
const node = this.deepestNode(path);
const p1 = node.$path.slice(0, -1);
ctx.assert(path.startsWith(p1), 400, 'InvalidRequestPath', { path, format: p1 + '**' });
const p2 = path.slice(node.$path.length - 1);
ctx.$node = node;
ctx.state.p1 = p1;
ctx.state.p2 = p2;
},
};
/***/ }),
/***/ 554:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const logger = __nccwpck_require__(885);
const op = __nccwpck_require__(525);
const { AC_PASS_FILE } = __nccwpck_require__(791);
/**
* @errors [Unauthorized,ItemNotExist]
*/
module.exports = async (ctx, next) => {
const { hidden, password } = ctx.$node.$config;
if (ctx.state.level === 0) {
// hidden file
if (hidden && hidden.length > 0) {
ctx.assert(!hidden.find((e) => ctx.state.p2.startsWith(e)), 404, 'ItemNotExist', { path: ctx.state.p1 + ctx.state.p2 });
}
// drive-pass
if (password) {
checkPass(ctx, 'drive_pass', password, ctx.state.p1 + '/');
}
}
await next();
if (ctx.state.level === 0 && ctx.response.isList) {
// hidden list item
if (hidden && hidden.length > 0) {
const p2 = ctx.state.p2;
const h = hidden.map((e) => (e.startsWith(p2) ? e.slice(p2.length) : null)).filter((e) => e && !e.includes('/'));
if (h.length > 0) {
ctx.response.data.list = ctx.response.data.list.filter((e) => !h.includes(e.name));
}
}
// list-pass
const o = ctx.response.data.list.reduce(
(o, e) => {
if (e.name.startsWith(AC_PASS_FILE)) {
o[0].push(e.name.slice(AC_PASS_FILE.length));
} else {
o[1].push(e);
}
return o;
},
[[], []]
);
ctx.response.data.list = o[1];
if (o[0].length > 0) {
checkPass(ctx, 'list_pass', o[0], ctx.state.p1 + ctx.state.p2);
}
}
};
function checkPass(ctx, name, pass, path) {
const { cookies, body, method, query } = ctx.request;
let type = 'empty';
const uname = name.toUpperCase();
if (cookies[uname]) {
type = 'expired';
if (op.verify(uname + path, cookies[uname])) {
logger.log('use cookie:' + cookies[uname]);
return;
}
}
if (method === 'POST' && (body[name] || body.password)) {
type = 'wrong';
// 可以使用通用字段password,也可以用对应的专用字段name
const uPass = body[name] || body.password;
if (uPass === pass || (Array.isArray(pass) && pass.includes(uPass))) {
// 单个云盘登录
logger.log('use pass:' + uPass);
ctx.addCookie(uname, op.sign(uname + path, 24 * 31), { path, maxAge: 3600 * 24 * 30 });
return;
}
}
// 分享专用
if (method === 'GET' && query[name]) {
type = 'invalid';
if (op.verify(uname + path, query[name])) {
ctx.addCookie(uname, op.sign(uname + path, 24 * 31), { path, maxAge: 3600 * 24 * 30 });
return;
}
}
ctx.throw(401, 'Unauthorized', { field: name, type });
}
/***/ }),
/***/ 970:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const logger = __nccwpck_require__(885);
const sysConfig = __nccwpck_require__(791);
const op = __nccwpck_require__(525);
const SimpleRouter = __nccwpck_require__(979);
const { P } = __nccwpck_require__(166);
const { beautifyObject } = __nccwpck_require__(166);
const { PATH_API, PATH_ADMIN, PATH_DOWN } = sysConfig;
const api_router = new SimpleRouter();
api_router.setDefault((ctx) => {
ctx.throw(400, 'UnsupportedAPI', { path: ctx.request.path });
});
function equalsObj(a, b) {
return JSON.stringify(beautifyObject(a)) === JSON.stringify(beautifyObject(b));
}
function paramsCopy(params, src) {
if (!src) {
return {};
}
const c = {};
params.forEach(({ name }) => {
if (src[name]) {
c[name] = src[name];
}
});
return c;
}
async function versionCheckAndLazySave(a, f, v, ctx) {
if (!op.needConfig && equalsObj(a[0], a[1])) {
logger.info('Nothing Changed, Lazy Save');
ctx.respond(200, { message: 'Nothing Changed', version: op.config.version });
} else {
ctx.assert(v === op.config.version, 400, 'InvalidVersion', { version: op.config.version });
f();
ctx.respond(200, { message: await op.saveConfig(), version: op.config.version });
}
}
// 读写基本配置
api_router.get('config/basic', async (ctx) => {
const params = op.params;
if (op.needConfig) {
[
P('admin_salt', String(Math.random()), '签名salt,仅限输入一次,以后不可更改', 9, '', false, false),
P('admin_pass', 'admin', '密码', 9, '', false, true),
P('admin_name', 'admin', '用户名,仅限输入一次,以后不可更改', 9, '', false, true),
].forEach((e) => params.unshift(e));
}
ctx.respond(200, {
basic: Object.assign({}, paramsCopy(sysConfig.commonSParams, op.config.site), paramsCopy(op.starter.params, op.config.starter)),
params: params,
version: op.config.version,
});
});
api_router.post('config/basic', async (ctx) => {
const { basic, version } = ctx.request.body;
const c0 = paramsCopy(sysConfig.commonSParams, basic);
const c1 = paramsCopy(op.starter.params, basic);
const flag = op.needConfig;
await versionCheckAndLazySave(
[
[op.config.site, op.config.starter],
[c0, c1],
],
() => {
if (op.config.version === 1) {
op.config.salt = basic.admin_salt;
const users = {};
users[basic.admin_name] = { password: basic.admin_pass };
op.config.users = users;
}
op.config.site = c0;
op.config.starter = c1;
},
version,
ctx
);
if (flag) {
ctx.response.data.token = op.signUser(basic.admin_name);
}
});
// 获取所有的云盘信息,增加乐观锁,弥补token不能识别多处登录的问题
api_router.get('config/drives', async (ctx) => {
ctx.respond(200, {
drives: op.config.drives,
moduleParams: sysConfig.commonMParams,
privateModuleParams: op.privateModuleParams,
version: op.config.version,
});
});
// 如果要删除一个盘,需要传递一个空值,否则不执行删除操作
api_router.post('config/drives', async (ctx) => {
const copy = beautifyObject(op.config.drives);
const { drives, version } = ctx.request.body;
Object.entries(drives).forEach(([p, c]) => {
if (!c) {
delete copy[p];
} else {
copy[p] = paramsCopy(sysConfig.commonMParams, c);
const m = op.modules[c.module];
copy[p].config = m ? paramsCopy(typeof m.params === 'function' ? m.params() : m.params, c.config) : {};
}
});
await versionCheckAndLazySave(
[op.config.drives, copy],
() => {
op.config.drives = copy;
op.loadConfig(op.config);
},
version,
ctx
);
});
api_router.post('config/export', async (ctx) => {
const u = op.config.users[ctx.state.user];
ctx.assert(ctx.request.body.password === u.password, 400, 'InvalidUserAuth', { user: ctx.state.user });
ctx.respond(200, { config: op.config });
});
// 整体导入的配置 不再检验version的有效性
api_router.post('config/import', async (ctx) => {
const u = op.config.users[ctx.state.user];
const { config, password } = ctx.request.body;
ctx.assert(password === u.password, 400, 'InvalidUserAuth', { user: ctx.state.user });
await versionCheckAndLazySave(
[op.config, config],
() => {
op.loadConfig(config);
},
op.config.version,
ctx
);
});
// 修改密码
api_router.post('user/password', async (ctx) => {
const u = op.config.users[ctx.state.user];
const { password0, password, version } = ctx.request.body;
ctx.assert(password0 === u.password, 400, 'InvalidUserAuth', { user: ctx.state.user });
await versionCheckAndLazySave(
[u.password, password],
() => {
// change password
u.password = password;
},
version,
ctx
);
});
api_router.get('system/runtime', async (ctx) => {
ctx.respond(200, { runtime: op.runtime, version: op.config.version });
});
api_router.get('system/reload', async (ctx) => {
op.config.version = -1;
ctx.respond(200);
});
api_router.prefix('file:', async (ctx, next, path) => {
const m = ctx.request.method;
const b = ctx.request.body;
const $data = (ctx.$data = {});
b.path && (path = b.path);
ctx.assert(path, 400, 'InvalidRequestParam', { expect: ['path'] });
if (m === 'GET') {
$data.command = 'ls';
} else if (m === 'DELETE') {
$data.command = 'rm';
} else if (m === 'POST') {
const c = ($data.command = b.command);
if (c === 'mkdir' || c === 'ren' || c === 'touch' || c === 'upload') {
ctx.assert(($data.name = b.name), 400, 'InvalidRequestParam', { expect: ['name'] });
if (c === 'touch') {
const { content, base64 } = b;
ctx.assert(content !== undefined || base64, 400, 'InvalidRequestParam', { expect: ['content||base64'] });
$data.mime = b.mime || 'text/plain';
if (content) {
$data.content = Buffer.from(content, 'utf-8');
} else if (base64) {
// base64
$data.content = Buffer.from(base64, 'base64');
}
}
} else if (c === 'mv' || c === 'cp') {
const { desPath } = b;
ctx.assert(path !== desPath && op.deepestNode(path) === op.deepestNode(desPath), 400, 'InvalidRequestParam', { expect: ['desPath'] });
$data.desPath = desPath.slice(op.deepestNode(desPath).$path.length - 1);
} else {
ctx.throw(400, 'InvalidRequestParam', { expect: ['command'] });
}
}
op.parsePathBeforeInvoke(ctx, path);
await next();
});
const router = new SimpleRouter();
router.prefix(PATH_ADMIN, async (ctx, _, path) => {
if (path === '') {
ctx.respondRaw(200, {}, sysConfig.getAdminHtml(ctx.request.baseURL, op.config.version));
} else {
ctx.assert(ctx.state.level > 0, 401, 'Unauthorized', {
field: 'admin-token',
type: 'login please',
});
}
});
router.prefix(PATH_API, async (ctx, next, path) => {
if (path === 'login') {
const { username, password } = ctx.request.body;
const u = op.config.users[username];
ctx.assert(u && password && u.password === password, 400, 'InvalidUserAuth', { username });
const token = op.signUser(username);
ctx.addCookie('X_TOKEN', token, { path: '/' });
ctx.respond(200, { token, version: op.config.version });
} else if (path === 'public/site') {
ctx.respond(200, {
site: op.config.site,
drives: Object.entries(op.config.drives).map(([path, { readme = '' }]) => ({ path, readme })),
version: op.server.version,
version2: op.server.version2,
});
} else {
ctx.assert(op.needConfig || ctx.state.level > 0, 401, 'UnauthorizedToken', { token: null });
await api_router.handle(ctx, next, path);
}
});
router.prefix(PATH_DOWN, async (ctx, next, path) => {
ctx.$data = { command: 'download' };
op.parsePathBeforeInvoke(ctx, path);
await next();
});
router.setDefault(async (ctx, next) => {
ctx.state.html = ctx.request.headers.accept !== 'application/json';
ctx.state.useCache = ctx.request.query.refresh === undefined;
ctx.$data = { command: 'ls' };
op.parsePathBeforeInvoke(ctx, ctx.request.path);
await next();
});
module.exports = async (ctx, next) => {
const { cookies, path, headers } = ctx.request;
const token = headers['x-token'] || cookies.X_TOKEN;
if (token) {
const user = op.verifyUser(token);
if (user) {
ctx.state.user = user;
ctx.state.level = 1;
} else {
ctx.addCookie('X_TOKEN', '', { path: '/' });
ctx.throw(401, 'UnauthorizedToken', { token });
}
}
await router.handle(ctx, next, path);
};
/***/ }),
/***/ 158:
/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => {
const logger = __nccwpck_require__(885);
const { RTError } = __nccwpck_require__(166);
const { CACHE_TIME_FILE, CACHE_TIME_LIST } = __nccwpck_require__(791);
module.exports = async (ctx, next) => {
const path = ctx.state.p1 + ctx.state.p2;
// use cache
if (ctx.state.useCache) {
const m = oneCache.getMsg(path, ctx.$data.page);
if (m) {
logger.info('cache hit');
if (m.list) {
ctx.respondList(m.list, m.nextToken);
} else if (m.one) {
ctx.respondOne(m.one, m.down);
}
ctx.response.data.cached = m.time;
return;
}
}
await next();
if (ctx.response.isList) {
const d = ctx.response.data;
oneCache.addList(path, d.list, d.nextToken, ctx.$data.page);
} else if (ctx.response.isFile) {
oneCache.addOne(path, ctx.response.data.file, ctx.response.down);
} else if (ctx.response.isFolder) {
oneCache.addOne(path, ctx.response.data.folder);
}
};
class OneCache {
constructor() {
this.root = { next: {} };
}
addList(path, list, nextToken, page = 0) {
const p = this.getNode(path, true);
const oNext = p.next;
const next = {};
const time = Date.now();
list.forEach((e) => {
next[e.name] = {
value: e,
next: oNext[e.name] ? oNext[e.name].next : {},
time: e.url || e.type !== 0 ? time : 0,
};
});
p.next = next;
if (page || nextToken) {
// 一锅炖不下
if (!p.pages) {
p.pages = {};
}
const t = { list, nextToken, listTime: Date.now() };
t.time = t.listTime;
p.pages[page] = t;
} else {
p.listTime = Date.now();
}
}
addOne(path, item, down = null) {
const p = this.getNode(path, true);
p.value = item;
p.down = down ? JSON.stringify(down) : null;
p.time = Date.now();
}
getNode(path, addIfAbsent) {
let p = this.root;
for (const i of path.split('/').filter((e) => e)) {
if (!p.next[i]) {
if (!addIfAbsent) {
return;
}
p.next[i] = { next: {} };
}
p = p.next[i];
}
return p;
}
getMsg(path, page = 0) {
const p = this.getNode(path);
if (!p) {
return;
}
if (path.endsWith('/')) {
if ((p.listTime || 0) > Date.now() - CACHE_TIME_LIST) {
return { list: Object.values(p.next).map((e) => e.value), time: p.listTime };
}
if (p.pages && p.pages[page] && p.pages[page].listTime > Date.now() - CACHE_TIME_LIST) {
return p.pages[page];
}
if (p.value && p.value.type === 0) {
throw new RTError(400, 'ItemIsFile');
}
} else {
if ((p.time || 0) > Date.now() - CACHE_TIME_FILE) {
return { one: p.value, down: p.down ? JSON.parse(p.down) : null, time: p.time };
}
}
}
drop(path = '/') {
if (path.endsWith('/')) {
path = path.slice(0, -1);
}
const pPath = path.slice(0, path.lastIndexOf('/'));
if (pPath === '') {