ddan-js 2.8.2 → 2.8.4

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.
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const ali_oss_1 = require("ali-oss");
4
+ const pop_core_1 = require("@alicloud/pop-core");
5
+ class Aliyun {
6
+ bucket;
7
+ accessKeyId;
8
+ accessKeySecret;
9
+ region;
10
+ __oss;
11
+ __cdn;
12
+ constructor({ bucket, accessKeyId, accessKeySecret, region }) {
13
+ this.bucket = bucket;
14
+ this.accessKeyId = accessKeyId;
15
+ this.accessKeySecret = accessKeySecret;
16
+ this.region = region;
17
+ this.__oss = this._getOSS();
18
+ }
19
+ get client() {
20
+ if (!this.__oss) {
21
+ this.__oss = this._getOSS();
22
+ }
23
+ return this.__oss;
24
+ }
25
+ _getOSS() {
26
+ return new ali_oss_1.default({
27
+ region: this.region,
28
+ accessKeyId: this.accessKeyId,
29
+ accessKeySecret: this.accessKeySecret,
30
+ bucket: this.bucket,
31
+ });
32
+ }
33
+ async read(name) {
34
+ try {
35
+ if (!(await this.exist(name)))
36
+ return '';
37
+ const result = await this.client.get(name);
38
+ return result.content?.toString() || '';
39
+ }
40
+ catch (err) {
41
+ console.log(`aliyun read ${name} error`, err);
42
+ return undefined;
43
+ }
44
+ }
45
+ async delete(name) {
46
+ try {
47
+ await this.client.delete(name);
48
+ return true;
49
+ }
50
+ catch (err) {
51
+ console.log(`aliyun delete ${name} error`, err);
52
+ return false;
53
+ }
54
+ }
55
+ async exist(name, options = {}) {
56
+ try {
57
+ await this.client.head(name, options);
58
+ return true;
59
+ }
60
+ catch (err) {
61
+ return false;
62
+ }
63
+ }
64
+ async upload(name, localname) {
65
+ try {
66
+ if (!name || !localname)
67
+ return false;
68
+ await this.client.put(name, localname);
69
+ return true;
70
+ }
71
+ catch (err) {
72
+ console.log(`aliyun upload ${localname} error`, err);
73
+ return false;
74
+ }
75
+ }
76
+ async put(name, content) {
77
+ try {
78
+ if (!name || !content)
79
+ return false;
80
+ await this.client.put(name, Buffer.from(content));
81
+ return true;
82
+ }
83
+ catch (err) {
84
+ console.log(`aliyun put content ${name} error`, err);
85
+ return false;
86
+ }
87
+ }
88
+ async putSymlink(symlinkName, sourceName) {
89
+ try {
90
+ if (!symlinkName || !sourceName)
91
+ return false;
92
+ // @ts-ignore
93
+ const res = await this.client.putSymlink(symlinkName, sourceName);
94
+ return res;
95
+ }
96
+ catch (error) {
97
+ return false;
98
+ }
99
+ }
100
+ async browse(name, cb) {
101
+ let token = undefined;
102
+ let flag = false;
103
+ const maxKeys = "50";
104
+ const prefix = name.endsWith('/') ? name : `${name}/`;
105
+ try {
106
+ do {
107
+ const result = await this.client.listV2({
108
+ prefix,
109
+ 'continuation-token': token,
110
+ 'max-keys': maxKeys,
111
+ }, {});
112
+ for (let item of result.objects || []) {
113
+ cb && (await cb(item.name));
114
+ }
115
+ // @ts-ignore
116
+ token = result.nextContinuationToken;
117
+ flag = result.isTruncated;
118
+ } while (flag);
119
+ return true;
120
+ }
121
+ catch (err) {
122
+ console.log(`aliyun browse ${name} error`, err);
123
+ return false;
124
+ }
125
+ }
126
+ get cdn() {
127
+ if (this.__cdn)
128
+ return this.__cdn;
129
+ this.__cdn = new pop_core_1.default({
130
+ accessKeyId: this.accessKeyId,
131
+ accessKeySecret: this.accessKeySecret,
132
+ endpoint: 'https://cdn.aliyuncs.com',
133
+ apiVersion: '2018-05-10',
134
+ });
135
+ return this.__cdn;
136
+ }
137
+ async refreshCDN(url, type = 'File') {
138
+ try {
139
+ let params = {
140
+ ObjectPath: url,
141
+ ObjectType: type,
142
+ };
143
+ const requestOption = {
144
+ method: 'POST',
145
+ formatParams: false,
146
+ };
147
+ await this.cdn.request('RefreshObjectCaches', params, requestOption);
148
+ return true;
149
+ }
150
+ catch (err) {
151
+ console.log(`aliyun refreshCDN ${url} err`, err);
152
+ return false;
153
+ }
154
+ }
155
+ }
156
+ exports.default = Aliyun;
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const fs_1 = require("fs");
4
+ const readDirectory = (dir, callback) => {
5
+ return new Promise((resolve, reject) => {
6
+ fs_1.default.readdir(dir, async (err, files) => {
7
+ if (err) {
8
+ return reject(err);
9
+ }
10
+ resolve(readFiles(dir, files, callback));
11
+ });
12
+ });
13
+ };
14
+ const readFiles = async (dir, files, callback) => {
15
+ for (let file of files) {
16
+ const localname = `${dir}\\${file}`;
17
+ if (fs_1.default.lstatSync(localname).isDirectory()) {
18
+ await readDirectory(`${localname}`, callback);
19
+ }
20
+ else {
21
+ callback && (await callback(localname));
22
+ }
23
+ }
24
+ };
25
+ exports.default = { readDirectory, readFiles };
@@ -7,4 +7,5 @@ const child_1 = require("./child");
7
7
  const proxy_1 = require("./proxy");
8
8
  const ecdh_web_1 = require("./ecdh-web");
9
9
  const rsa_web_1 = require("./rsa-web");
10
- exports.default = { ...brotli_1.default, ...child_1.default, ...proxy_1.default, Ecdh: ecdh_1.default, EcdhWeb: ecdh_web_1.default, Socks5: socks5_1.Socks5, rsa: rsa_web_1.default };
10
+ const file_1 = require("./file");
11
+ exports.default = { ...file_1.default, ...brotli_1.default, ...child_1.default, ...proxy_1.default, Ecdh: ecdh_1.default, EcdhWeb: ecdh_web_1.default, Socks5: socks5_1.Socks5, rsa: rsa_web_1.default };
@@ -14,7 +14,6 @@ class Socks5 {
14
14
  upstreamProxy;
15
15
  server = null;
16
16
  clientSockets = new Set();
17
- allowedDomains;
18
17
  systemProxy = null;
19
18
  useSystemProxy = false;
20
19
  __debug = false;
@@ -25,10 +24,9 @@ class Socks5 {
25
24
  __logger;
26
25
  __totalReceived = 0;
27
26
  __totalSent = 0;
28
- constructor(upstreamProxy, allowedDomains = ['*'], debug = false, logger) {
27
+ constructor(upstreamProxy, debug = false, logger) {
29
28
  this.__event = new event_1.default();
30
- this.upstreamProxy = upstreamProxy;
31
- this.allowedDomains = new Set(allowedDomains);
29
+ this.upstreamProxy = this.filterProxyConfigs(upstreamProxy);
32
30
  this.__debug = debug;
33
31
  this.__uuid = (0, uuid_1.default)();
34
32
  this.__pipeline = new pipeline_1.default(1);
@@ -51,7 +49,7 @@ class Socks5 {
51
49
  get totalSent() {
52
50
  return this.__totalSent;
53
51
  }
54
- validateProxyConfig(proxyConfig = this.upstreamProxy) {
52
+ validateProxyConfig(proxyConfig) {
55
53
  const { ipaddress, port, userId, password } = proxyConfig || {};
56
54
  if (!ipaddress || typeof ipaddress !== 'string') {
57
55
  return '无效的上游代理 IP 地址';
@@ -67,8 +65,24 @@ class Socks5 {
67
65
  }
68
66
  return '';
69
67
  }
68
+ filterProxyConfigs(proxyConfig) {
69
+ let configs = [];
70
+ if (proxyConfig && Array.isArray(proxyConfig)) {
71
+ configs = proxyConfig;
72
+ }
73
+ else {
74
+ configs = [proxyConfig];
75
+ }
76
+ const filterCfgs = [];
77
+ for (const cfg of configs) {
78
+ if (!this.validateProxyConfig(cfg)) {
79
+ filterCfgs.push(cfg);
80
+ }
81
+ }
82
+ return filterCfgs;
83
+ }
70
84
  async start(startPort = 8838) {
71
- if (this.validateProxyConfig())
85
+ if (this.upstreamProxy.length <= 0)
72
86
  return 0;
73
87
  if (this.server) {
74
88
  this.__debug && console.info(`[socks5] server is already running`);
@@ -91,9 +105,10 @@ class Socks5 {
91
105
  setUpstreamProxy(upstreamProxy) {
92
106
  if (!upstreamProxy)
93
107
  return false;
94
- if (this.validateProxyConfig(upstreamProxy))
108
+ const configs = this.filterProxyConfigs(upstreamProxy);
109
+ if (!configs || configs.length <= 0)
95
110
  return false;
96
- this.upstreamProxy = upstreamProxy;
111
+ this.upstreamProxy = configs;
97
112
  return true;
98
113
  }
99
114
  setSystemProxy(use, config) {
@@ -102,9 +117,6 @@ class Socks5 {
102
117
  this.systemProxy = config;
103
118
  }
104
119
  }
105
- setAllowedDomains(allowedDomains = []) {
106
- this.allowedDomains = new Set(allowedDomains);
107
- }
108
120
  /**
109
121
  * 查找可用端口
110
122
  * @param startPort
@@ -150,10 +162,11 @@ class Socks5 {
150
162
  const addr = destination.addr;
151
163
  addrport = `${addr}:${destination.port}`;
152
164
  this.__debug && this.__logger?.info(`[socks5] handle connection`, addrport);
153
- if (this.isAllowedDomain(addr)) {
165
+ const proxyConfig = this.getProxyConfig(addr);
166
+ if (proxyConfig) {
154
167
  // 走上游代理
155
- const upstreamSocket = await this.connectToUpstreamProxy(destination);
156
- this.__logger?.info(`[socks5] handle connection upstream`, addrport);
168
+ const upstreamSocket = await this.connectToUpstreamProxy(destination, proxyConfig);
169
+ this.__logger?.info(`[socks5] handle connection upstream`, addrport, proxyConfig.userId);
157
170
  this.setupDataForwarding(clientSocket, upstreamSocket, 'upstream');
158
171
  }
159
172
  else if (this.useSystemProxy && this.systemProxy && !index_1.default.isLocalIpAddress(addr)) {
@@ -241,9 +254,15 @@ class Socks5 {
241
254
  });
242
255
  }
243
256
  // 上游代理连接
244
- async connectToUpstreamProxy(destination) {
257
+ async connectToUpstreamProxy(destination, config) {
245
258
  const options = {
246
- proxy: { ...this.upstreamProxy, type: 5 },
259
+ proxy: {
260
+ ipaddress: config.ipaddress,
261
+ port: config.port,
262
+ type: 5,
263
+ userId: config.userId,
264
+ password: config.password,
265
+ },
247
266
  command: 'connect',
248
267
  destination: {
249
268
  host: destination.addr,
@@ -320,10 +339,21 @@ class Socks5 {
320
339
  clientSocket.end();
321
340
  });
322
341
  }
323
- isAllowedDomain(addr) {
342
+ getProxyConfig(addr) {
324
343
  if (index_1.default.isLocalIpAddress(addr))
344
+ return undefined;
345
+ for (const cfg of this.upstreamProxy) {
346
+ if (this.isAllowedDomain(addr, cfg.rules || []))
347
+ return cfg;
348
+ }
349
+ return undefined;
350
+ }
351
+ isAllowedDomain(addr, rules) {
352
+ if (index_1.default.isLocalIpAddress(addr))
353
+ return false;
354
+ if (!rules || !Array.isArray(rules))
325
355
  return false;
326
- for (const pattern of this.allowedDomains) {
356
+ for (const pattern of rules) {
327
357
  if (pattern === '*')
328
358
  return true;
329
359
  if (index_1.default.shExpMatch(addr, pattern))
@@ -109,6 +109,7 @@ declare const dUtil: {
109
109
  bytes2hex: (bytes: Uint8Array) => string;
110
110
  toUint32: (str: string) => Uint32Array;
111
111
  fromUint32: (uint32: Uint32Array) => string;
112
+ flatten: <T_3>(data: T_3[], recursive?: boolean, list?: T_3[]) => T_3[];
112
113
  gbk: {
113
114
  gbkLength: (str: string) => number;
114
115
  gbkCut: (source: string, len: number) => string;
@@ -135,16 +136,16 @@ declare const dUtil: {
135
136
  };
136
137
  };
137
138
  list: {
138
- stepAction: <T_3>(list: T_3[], func: import("./typings").Ddan.Task<T_3, void>, stepCount?: number) => void;
139
- skip: <T_4>(list: T_4[], count: number) => T_4[];
140
- take: <T_5>(list: T_5[], count: number, skip?: number) => T_5[];
141
- distinct: <T_6>(list: T_6[]) => T_6[];
142
- randoms: <T_7>(list: T_7[], count?: number, repeat?: boolean) => T_7[];
139
+ stepAction: <T_4>(list: T_4[], func: import("./typings").Ddan.Task<T_4, void>, stepCount?: number) => void;
140
+ skip: <T_5>(list: T_5[], count: number) => T_5[];
141
+ take: <T_6>(list: T_6[], count: number, skip?: number) => T_6[];
142
+ distinct: <T_7>(list: T_7[]) => T_7[];
143
+ randoms: <T_8>(list: T_8[], count?: number, repeat?: boolean) => T_8[];
143
144
  toKV: (list: import("./typings").Ddan.KV<any>[], key: string, value: string) => import("./typings").Ddan.KV<any>;
144
- groupBy: <T_8>(list: T_8[], key: string) => Record<string, T_8[]>;
145
- first: <T_9>(list: T_9[]) => T_9 | undefined;
146
- last: <T_10>(list: T_10[]) => T_10 | undefined;
147
- toList: <T_11>(val: T_11 | T_11[]) => T_11[];
145
+ groupBy: <T_9>(list: T_9[], key: string) => Record<string, T_9[]>;
146
+ first: <T_10>(list: T_10[]) => T_10 | undefined;
147
+ last: <T_11>(list: T_11[]) => T_11 | undefined;
148
+ toList: <T_12>(val: T_12 | T_12[]) => T_12[];
148
149
  };
149
150
  string: {
150
151
  toString: (value: any) => any;
@@ -394,6 +395,7 @@ declare const dHook: {
394
395
  bytes2hex: (bytes: Uint8Array) => string;
395
396
  toUint32: (str: string) => Uint32Array;
396
397
  fromUint32: (uint32: Uint32Array) => string;
398
+ flatten: <T_6>(data: T_6[], recursive?: boolean, list?: T_6[]) => T_6[];
397
399
  };
398
400
  declare const dMini: {
399
401
  mini: {
@@ -675,6 +677,8 @@ declare const dNode: {
675
677
  child_exec: (cmd: string) => Promise<[any, string]>;
676
678
  brotliCompress: typeof import("./modules/node/brotli").brotliCompress;
677
679
  brotliDecompress: typeof import("./modules/node/brotli").brotliDecompress;
680
+ readDirectory: (dir: string, callback?: import("./typings").Ddan.Func1<string, any> | undefined) => Promise<unknown>;
681
+ readFiles: (dir: string, files: string[], callback?: import("./typings").Ddan.Func1<string, any> | undefined) => Promise<void>;
678
682
  };
679
683
  export { dUtil, dHook, dWeb, dMini, dCdn, dStore, dJoker, dTracker, dLogger, dNode, Event, KValue, Mapping };
680
684
  declare const _default: {
@@ -1038,6 +1042,7 @@ declare const _default: {
1038
1042
  bytes2hex: (bytes: Uint8Array) => string;
1039
1043
  toUint32: (str: string) => Uint32Array;
1040
1044
  fromUint32: (uint32: Uint32Array) => string;
1045
+ flatten: <T_17>(data: T_17[], recursive?: boolean, list?: T_17[]) => T_17[];
1041
1046
  };
1042
1047
  KValue: typeof KValue;
1043
1048
  Mapping: typeof Mapping;
@@ -1,3 +1,4 @@
1
+ declare function flatten<T>(data: T[], recursive?: boolean, list?: T[]): T[];
1
2
  declare const _default: {
2
3
  bytes2str: (bytes: Uint8Array) => string;
3
4
  str2bytes: (str?: string) => Uint8Array;
@@ -10,5 +11,6 @@ declare const _default: {
10
11
  bytes2hex: (bytes: Uint8Array) => string;
11
12
  toUint32: (str: string) => Uint32Array;
12
13
  fromUint32: (uint32: Uint32Array) => string;
14
+ flatten: typeof flatten;
13
15
  };
14
16
  export default _default;
@@ -28,5 +28,6 @@ declare const _default: {
28
28
  bytes2hex: (bytes: Uint8Array) => string;
29
29
  toUint32: (str: string) => Uint32Array;
30
30
  fromUint32: (uint32: Uint32Array) => string;
31
+ flatten: <T>(data: T[], recursive?: boolean, list?: T[]) => T[];
31
32
  };
32
33
  export default _default;
@@ -0,0 +1,27 @@
1
+ import OSS from 'ali-oss';
2
+ import { Ddan } from '../../typings';
3
+ export default class Aliyun {
4
+ bucket: string;
5
+ accessKeyId: string;
6
+ accessKeySecret: string;
7
+ region: string;
8
+ __oss: OSS;
9
+ __cdn: any;
10
+ constructor({ bucket, accessKeyId, accessKeySecret, region }: {
11
+ bucket: any;
12
+ accessKeyId: any;
13
+ accessKeySecret: any;
14
+ region: any;
15
+ });
16
+ get client(): OSS;
17
+ _getOSS(): OSS;
18
+ read(name: string): Promise<string | undefined>;
19
+ delete(name: string): Promise<boolean>;
20
+ exist(name: string, options?: {}): Promise<boolean>;
21
+ upload(name: string, localname: string): Promise<boolean>;
22
+ put(name: string, content: string): Promise<boolean>;
23
+ putSymlink(symlinkName: string, sourceName: string): Promise<any>;
24
+ browse(name: string, cb?: Ddan.Func1<string>): Promise<boolean>;
25
+ get cdn(): any;
26
+ refreshCDN(url: string, type?: 'File' | 'Directory'): Promise<boolean>;
27
+ }
@@ -0,0 +1,6 @@
1
+ import { Ddan } from '../../typings';
2
+ declare const _default: {
3
+ readDirectory: (dir: string, callback?: Ddan.Func1<string, any> | undefined) => Promise<unknown>;
4
+ readFiles: (dir: string, files: string[], callback?: Ddan.Func1<string, any> | undefined) => Promise<void>;
5
+ };
6
+ export default _default;
@@ -34,5 +34,7 @@ declare const _default: {
34
34
  child_exec: (cmd: string) => Promise<[any, string]>;
35
35
  brotliCompress: typeof import("./brotli").brotliCompress;
36
36
  brotliDecompress: typeof import("./brotli").brotliDecompress;
37
+ readDirectory: (dir: string, callback?: import("../..").Ddan.Func1<string, any> | undefined) => Promise<unknown>;
38
+ readFiles: (dir: string, files: string[], callback?: import("../..").Ddan.Func1<string, any> | undefined) => Promise<void>;
37
39
  };
38
40
  export default _default;
@@ -1,12 +1,15 @@
1
1
  import DEvent from '../../class/event';
2
2
  import DPipeline from '../hook/modules/pipeline';
3
- interface IProxyConfig {
3
+ interface IProxy {
4
4
  ipaddress: string;
5
5
  port: number;
6
6
  type?: 5;
7
7
  userId?: string;
8
8
  password?: string;
9
9
  }
10
+ interface IRuleProxy extends IProxy {
11
+ rules?: string[];
12
+ }
10
13
  declare const Socks5Event: {
11
14
  readonly Error: "error";
12
15
  };
@@ -21,7 +24,6 @@ export declare class Socks5 {
21
24
  private upstreamProxy;
22
25
  private server;
23
26
  private clientSockets;
24
- private allowedDomains;
25
27
  private systemProxy;
26
28
  private useSystemProxy;
27
29
  __debug: boolean;
@@ -32,17 +34,17 @@ export declare class Socks5 {
32
34
  __logger: ILogger;
33
35
  __totalReceived: number;
34
36
  __totalSent: number;
35
- constructor(upstreamProxy: IProxyConfig, allowedDomains?: string[] | ['*'], debug?: boolean, logger?: ILogger);
37
+ constructor(upstreamProxy: IRuleProxy | IRuleProxy[], debug?: boolean, logger?: ILogger);
36
38
  get id(): string;
37
39
  get port(): number;
38
40
  get url(): string;
39
41
  get totalReceived(): number;
40
42
  get totalSent(): number;
41
- validateProxyConfig(proxyConfig?: IProxyConfig): "" | "无效的上游代理 IP 地址" | "无效的上游代理端口" | "无效的上游代理用户名" | "无效的上游代理密码";
43
+ validateProxyConfig(proxyConfig: IProxy): "" | "无效的上游代理 IP 地址" | "无效的上游代理端口" | "无效的上游代理用户名" | "无效的上游代理密码";
44
+ private filterProxyConfigs;
42
45
  start(startPort?: number): Promise<number>;
43
- setUpstreamProxy(upstreamProxy: IProxyConfig): boolean;
44
- setSystemProxy(use: boolean, config?: IProxyConfig): void;
45
- setAllowedDomains(allowedDomains?: string[]): void;
46
+ setUpstreamProxy(upstreamProxy: IRuleProxy | IRuleProxy[]): boolean;
47
+ setSystemProxy(use: boolean, config?: IProxy): void;
46
48
  /**
47
49
  * 查找可用端口
48
50
  * @param startPort
@@ -83,6 +85,7 @@ export declare class Socks5 {
83
85
  private connectToProxy;
84
86
  private connectToLocal;
85
87
  private setupDataForwarding;
88
+ private getProxyConfig;
86
89
  private isAllowedDomain;
87
90
  close(): void;
88
91
  on(name: Socks5EventType, listener: (...args: any[]) => void): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ddan-js",
3
- "version": "2.8.2",
3
+ "version": "2.8.4",
4
4
  "description": "",
5
5
  "keywords": [
6
6
  "ddan-js",
@@ -101,6 +101,9 @@
101
101
  ]
102
102
  },
103
103
  "devDependencies": {
104
+ "@alicloud/pop-core": "^1.7.12",
105
+ "ali-oss": "^6.17.1",
106
+ "@types/ali-oss": "^6.16.7",
104
107
  "@commitlint/cli": "^17.6.1",
105
108
  "@commitlint/config-conventional": "^17.6.1",
106
109
  "@rollup/plugin-node-resolve": "^15.1.0",