cloud189-sdk 1.0.6-alpha.3 → 1.0.6-alpha.5

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.
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # cloud189-sdk
2
2
 
3
+ [![NPM](https://nodei.co/npm/cloud189-sdk.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/cloud189-sdk/)
4
+
3
5
  > 基于node.js的天翼网盘sdk
4
6
 
5
7
  <div align="center">
@@ -1,11 +1,9 @@
1
1
  import { Got } from 'got';
2
- import { UserSignResponse, UserSizeInfoResponse, FamilyListResponse, FamilyUserSignResponse, ConfigurationOptions, ClientSession, RefreshTokenSession, TokenSession, AccessTokenStore } from './types';
3
- interface CacheQuery {
4
- captchaToken: string;
5
- reqId: string;
6
- lt: string;
7
- paramId: string;
8
- }
2
+ import { UserSignResponse, UserSizeInfoResponse, FamilyListResponse, FamilyUserSignResponse, ConfigurationOptions, ClientSession, RefreshTokenSession, TokenSession, CacheQuery } from './types';
3
+ import { Store } from './store';
4
+ /**
5
+ * @public
6
+ */
9
7
  export declare class CloudAuthClient {
10
8
  #private;
11
9
  readonly request: Got;
@@ -33,6 +31,10 @@ export declare class CloudAuthClient {
33
31
  * token登录
34
32
  */
35
33
  loginByAccessToken(accessToken: string): Promise<TokenSession>;
34
+ /**
35
+ * sso登录
36
+ */
37
+ loginBySsoCooike(cookie: string): Promise<TokenSession>;
36
38
  /**
37
39
  * 刷新token
38
40
  */
@@ -46,7 +48,8 @@ export declare class CloudClient {
46
48
  #private;
47
49
  username: string;
48
50
  password: string;
49
- token: AccessTokenStore;
51
+ ssonCookie: string;
52
+ tokenStore: Store;
50
53
  readonly request: Got;
51
54
  readonly authClient: CloudAuthClient;
52
55
  readonly session: ClientSession;
@@ -80,4 +83,3 @@ export declare class CloudClient {
80
83
  */
81
84
  familyUserSign(familyId: number): Promise<FamilyUserSignResponse>;
82
85
  }
83
- export {};
@@ -15,11 +15,16 @@ const got_1 = __importDefault(require("got"));
15
15
  const log_1 = require("./log");
16
16
  const util_1 = require("./util");
17
17
  const const_1 = require("./const");
18
+ const store_1 = require("./store");
19
+ const error_1 = require("./error");
18
20
  const config = {
19
21
  clientId: '538135150693412',
20
22
  model: 'KB2000',
21
23
  version: '9.0.6'
22
24
  };
25
+ /**
26
+ * @public
27
+ */
23
28
  class CloudAuthClient {
24
29
  constructor() {
25
30
  _CloudAuthClient_builLoginForm.set(this, (encrypt, appConf, username, password) => {
@@ -52,6 +57,7 @@ class CloudAuthClient {
52
57
  afterResponse: [
53
58
  async (response, retryWithMergedOptions) => {
54
59
  log_1.log.debug(`url: ${response.requestUrl}, response: ${response.body})}`);
60
+ (0, error_1.checkError)(response.body.toString());
55
61
  return response;
56
62
  }
57
63
  ]
@@ -119,9 +125,6 @@ class CloudAuthClient {
119
125
  form: data
120
126
  })
121
127
  .json();
122
- if (loginRes.result !== 0) {
123
- throw new Error(loginRes.msg);
124
- }
125
128
  return await this.getSessionForPC({ redirectURL: loginRes.toUrl });
126
129
  }
127
130
  catch (e) {
@@ -136,6 +139,26 @@ class CloudAuthClient {
136
139
  log_1.log.debug('loginByAccessToken...');
137
140
  return await this.getSessionForPC({ accessToken });
138
141
  }
142
+ /**
143
+ * sso登录
144
+ */
145
+ async loginBySsoCooike(cookie) {
146
+ log_1.log.debug('loginBySsoCooike...');
147
+ const res = await this.request.get(`${const_1.WEB_URL}/api/portal/unifyLoginForPC.action`, {
148
+ searchParams: {
149
+ appId: const_1.AppID,
150
+ clientType: const_1.ClientType,
151
+ returnURL: const_1.ReturnURL,
152
+ timeStamp: Date.now()
153
+ }
154
+ });
155
+ const redirect = await this.request(res.url, {
156
+ headers: {
157
+ Cookie: `SSON=${cookie}`
158
+ }
159
+ });
160
+ return await this.getSessionForPC({ redirectURL: redirect.url });
161
+ }
139
162
  /**
140
163
  * 刷新token
141
164
  */
@@ -170,7 +193,8 @@ class CloudClient {
170
193
  __classPrivateFieldGet(this, _CloudClient_valid, "f").call(this, _options);
171
194
  this.username = _options.username;
172
195
  this.password = _options.password;
173
- this.token = _options.token;
196
+ this.ssonCookie = _options.ssonCookie;
197
+ this.tokenStore = _options.token || new store_1.MemoryStore();
174
198
  this.authClient = new CloudAuthClient();
175
199
  this.session = {
176
200
  accessToken: '',
@@ -182,7 +206,8 @@ class CloudClient {
182
206
  },
183
207
  headers: {
184
208
  'User-Agent': const_1.UserAgent,
185
- Referer: `${const_1.WEB_URL}/web/main/`
209
+ Referer: `${const_1.WEB_URL}/web/main/`,
210
+ Accept: 'application/json;charset=UTF-8'
186
211
  },
187
212
  hooks: {
188
213
  beforeRequest: [
@@ -196,7 +221,6 @@ class CloudClient {
196
221
  options.headers['Signature'] = signature;
197
222
  options.headers['Timestamp'] = time;
198
223
  options.headers['Accesstoken'] = accessToken;
199
- options.headers['Accept'] = 'application/json;charset=UTF-8';
200
224
  }
201
225
  else if (options.url.href.includes(const_1.WEB_URL)) {
202
226
  const urlObj = new URL(options.url);
@@ -240,33 +264,50 @@ class CloudClient {
240
264
  });
241
265
  }
242
266
  async getSession() {
243
- if (this.token) {
244
- if (this.token.accessToken) {
245
- try {
246
- return await this.authClient.loginByAccessToken(this.token.accessToken);
247
- }
248
- catch (e) {
249
- log_1.log.error(e);
250
- }
267
+ const { accessToken, expiresIn, refreshToken } = await this.tokenStore.get();
268
+ if (accessToken && expiresIn && expiresIn > Date.now()) {
269
+ try {
270
+ return await this.authClient.loginByAccessToken(accessToken);
251
271
  }
252
- if (this.token.refreshToken) {
253
- try {
254
- const refreshTokenSession = await this.authClient.refreshToken(this.token.refreshToken);
255
- this.token.accessToken = refreshTokenSession.accessToken;
256
- return await this.authClient.loginByAccessToken(this.token.accessToken);
257
- }
258
- catch (e) {
259
- log_1.log.error(e);
260
- }
272
+ catch (e) {
273
+ log_1.log.error(e);
274
+ }
275
+ }
276
+ if (refreshToken) {
277
+ try {
278
+ const refreshTokenSession = await this.authClient.refreshToken(refreshToken);
279
+ await this.tokenStore.update({
280
+ accessToken: refreshTokenSession.accessToken,
281
+ expiresIn: new Date(Date.now() + refreshTokenSession.expiresIn * 1000).getTime()
282
+ });
283
+ return await this.authClient.loginByAccessToken(refreshTokenSession.accessToken);
284
+ }
285
+ catch (e) {
286
+ log_1.log.error(e);
287
+ }
288
+ }
289
+ if (this.ssonCookie) {
290
+ try {
291
+ const loginToken = await this.authClient.loginBySsoCooike(this.ssonCookie);
292
+ await this.tokenStore.update({
293
+ accessToken: loginToken.accessToken,
294
+ refreshToken: loginToken.refreshToken,
295
+ expiresIn: new Date(Date.now() + 8640 * 1000).getTime()
296
+ });
297
+ return loginToken;
298
+ }
299
+ catch (e) {
300
+ log_1.log.error(e);
261
301
  }
262
302
  }
263
303
  if (this.username && this.password) {
264
304
  try {
265
305
  const loginToken = await this.authClient.loginByPassword(this.username, this.password);
266
- this.token = {
306
+ await this.tokenStore.update({
267
307
  accessToken: loginToken.accessToken,
268
- refreshToken: loginToken.refreshToken
269
- };
308
+ refreshToken: loginToken.refreshToken,
309
+ expiresIn: new Date(Date.now() + 8640 * 1000).getTime()
310
+ });
270
311
  return loginToken;
271
312
  }
272
313
  catch (e) {
@@ -296,11 +337,7 @@ class CloudClient {
296
337
  * @returns 账号容量结果
297
338
  */
298
339
  getUserSizeInfo() {
299
- return this.request
300
- .get(`${const_1.WEB_URL}/api/portal/getUserSizeInfo.action`, {
301
- headers: { Accept: 'application/json;charset=UTF-8' }
302
- })
303
- .json();
340
+ return this.request.get(`${const_1.WEB_URL}/api/portal/getUserSizeInfo.action`).json();
304
341
  }
305
342
  /**
306
343
  * 个人签到任务
@@ -0,0 +1,5 @@
1
+ export declare class InvalidRefreshTokenError extends Error {
2
+ }
3
+ export declare class AuthApiError extends Error {
4
+ }
5
+ export declare const checkError: (response: any) => void;
package/dist/error.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.checkError = exports.AuthApiError = exports.InvalidRefreshTokenError = void 0;
4
+ class InvalidRefreshTokenError extends Error {
5
+ }
6
+ exports.InvalidRefreshTokenError = InvalidRefreshTokenError;
7
+ class AuthApiError extends Error {
8
+ }
9
+ exports.AuthApiError = AuthApiError;
10
+ const checkError = (response) => {
11
+ let res;
12
+ try {
13
+ res = JSON.parse(response);
14
+ }
15
+ catch (e) {
16
+ return;
17
+ }
18
+ // auth
19
+ if ('result' in res && 'msg' in res) {
20
+ switch (res.result) {
21
+ case 0:
22
+ return;
23
+ case -117:
24
+ throw new InvalidRefreshTokenError(res.msg);
25
+ default:
26
+ throw new AuthApiError(res.msg);
27
+ }
28
+ }
29
+ };
30
+ exports.checkError = checkError;
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './CloudClient';
2
2
  export * from './types';
3
+ export { Store, MemoryStore, FileTokenStore } from './store';
package/dist/index.js CHANGED
@@ -14,5 +14,10 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.FileTokenStore = exports.MemoryStore = exports.Store = void 0;
17
18
  __exportStar(require("./CloudClient"), exports);
18
19
  __exportStar(require("./types"), exports);
20
+ var store_1 = require("./store");
21
+ Object.defineProperty(exports, "Store", { enumerable: true, get: function () { return store_1.Store; } });
22
+ Object.defineProperty(exports, "MemoryStore", { enumerable: true, get: function () { return store_1.MemoryStore; } });
23
+ Object.defineProperty(exports, "FileTokenStore", { enumerable: true, get: function () { return store_1.FileTokenStore; } });
package/dist/log.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /// <reference types="node" />
2
2
  import WritableStream = NodeJS.WritableStream;
3
- export declare const debug: boolean;
3
+ export declare const debug = true;
4
4
  export interface Fields {
5
5
  [index: string]: any;
6
6
  }
package/dist/log.js CHANGED
@@ -6,7 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.log = exports.Logger = exports.PADDING = exports.debug = void 0;
7
7
  const chalk_1 = __importDefault(require("chalk"));
8
8
  let printer = null;
9
- exports.debug = process.env.CLOUD189_VERBOSE === '1';
9
+ exports.debug = true;
10
10
  exports.PADDING = 2;
11
11
  class Logger {
12
12
  constructor(stream) {
@@ -0,0 +1,14 @@
1
+ import { MemoryStore } from './memstore';
2
+ /**
3
+ * @public
4
+ */
5
+ export declare class FileTokenStore extends MemoryStore {
6
+ #private;
7
+ filePath: string;
8
+ constructor(filePath: string);
9
+ update(token: {
10
+ accessToken: string;
11
+ refreshToken?: string;
12
+ expiresIn?: number;
13
+ }): Promise<void>;
14
+ }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
26
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
27
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
28
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
29
+ };
30
+ var _FileTokenStore_instances, _FileTokenStore_loadFromFile, _FileTokenStore_saveToFile;
31
+ Object.defineProperty(exports, "__esModule", { value: true });
32
+ exports.FileTokenStore = void 0;
33
+ const fs = __importStar(require("node:fs"));
34
+ const promisesFs = __importStar(require("node:fs/promises"));
35
+ const memstore_1 = require("./memstore");
36
+ /**
37
+ * @public
38
+ */
39
+ class FileTokenStore extends memstore_1.MemoryStore {
40
+ constructor(filePath) {
41
+ super();
42
+ _FileTokenStore_instances.add(this);
43
+ this.filePath = filePath;
44
+ if (!filePath) {
45
+ throw new Error('Unknown file for read/write token');
46
+ }
47
+ const dataJson = __classPrivateFieldGet(this, _FileTokenStore_instances, "m", _FileTokenStore_loadFromFile).call(this, filePath);
48
+ if (dataJson) {
49
+ super.update(dataJson);
50
+ }
51
+ }
52
+ update(token) {
53
+ super.update(token);
54
+ return __classPrivateFieldGet(this, _FileTokenStore_instances, "m", _FileTokenStore_saveToFile).call(this, this.filePath, this.store);
55
+ }
56
+ }
57
+ exports.FileTokenStore = FileTokenStore;
58
+ _FileTokenStore_instances = new WeakSet(), _FileTokenStore_loadFromFile = function _FileTokenStore_loadFromFile(filePath) {
59
+ let data = null;
60
+ if (fs.existsSync(filePath)) {
61
+ data = fs.readFileSync(filePath, {
62
+ encoding: 'utf-8'
63
+ });
64
+ }
65
+ if (data) {
66
+ try {
67
+ return JSON.parse(data);
68
+ }
69
+ catch (e) {
70
+ throw new Error(`Could not parse token file ${filePath}. Please ensure it is not corrupted.`);
71
+ }
72
+ }
73
+ return null;
74
+ }, _FileTokenStore_saveToFile = function _FileTokenStore_saveToFile(filePath, data) {
75
+ return promisesFs.writeFile(filePath, JSON.stringify(data), {
76
+ encoding: 'utf-8'
77
+ });
78
+ };
@@ -0,0 +1,3 @@
1
+ export * from './store';
2
+ export * from './memstore';
3
+ export * from './file-token-store';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./store"), exports);
18
+ __exportStar(require("./memstore"), exports);
19
+ __exportStar(require("./file-token-store"), exports);
@@ -0,0 +1,22 @@
1
+ import { Store } from './store';
2
+ /**
3
+ * @public
4
+ */
5
+ export declare class MemoryStore extends Store {
6
+ store: {
7
+ accessToken: string;
8
+ refreshToken: string;
9
+ expiresIn: number;
10
+ };
11
+ constructor();
12
+ get(): {
13
+ accessToken: string;
14
+ refreshToken: string;
15
+ expiresIn: number;
16
+ };
17
+ update(token: {
18
+ accessToken: string;
19
+ refreshToken?: string;
20
+ expiresIn?: number;
21
+ }): void;
22
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MemoryStore = void 0;
4
+ const store_1 = require("./store");
5
+ /**
6
+ * @public
7
+ */
8
+ class MemoryStore extends store_1.Store {
9
+ constructor() {
10
+ super();
11
+ this.store = {
12
+ accessToken: '',
13
+ refreshToken: '',
14
+ expiresIn: 0
15
+ };
16
+ }
17
+ get() {
18
+ return this.store;
19
+ }
20
+ update(token) {
21
+ var _a, _b;
22
+ this.store = {
23
+ accessToken: token.accessToken,
24
+ refreshToken: (_a = token.refreshToken) !== null && _a !== void 0 ? _a : this.store.refreshToken,
25
+ expiresIn: (_b = token.expiresIn) !== null && _b !== void 0 ? _b : this.store.expiresIn
26
+ };
27
+ }
28
+ }
29
+ exports.MemoryStore = MemoryStore;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @public
3
+ */
4
+ export declare abstract class Store {
5
+ constructor();
6
+ abstract get(): {
7
+ accessToken: string;
8
+ refreshToken: string;
9
+ expiresIn: number;
10
+ } | Promise<{
11
+ accessToken: string;
12
+ refreshToken: string;
13
+ expiresIn: number;
14
+ }>;
15
+ abstract update(token: {
16
+ accessToken: string;
17
+ refreshToken?: string;
18
+ expiresIn?: number;
19
+ }): void | Promise<void>;
20
+ }
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Store = void 0;
4
+ /**
5
+ * @public
6
+ */
7
+ class Store {
8
+ constructor() { }
9
+ }
10
+ exports.Store = Store;
package/dist/types.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { Store } from './store';
1
2
  /**
2
3
  * 账户家庭信息
3
4
  * @public
@@ -124,6 +125,15 @@ export interface UserTaskResponse {
124
125
  */
125
126
  prizeName: string;
126
127
  }
128
+ /**
129
+ * @public
130
+ */
131
+ export interface CacheQuery {
132
+ captchaToken: string;
133
+ reqId: string;
134
+ lt: string;
135
+ paramId: string;
136
+ }
127
137
  /**
128
138
  * 客户端初始化参数
129
139
  * @public
@@ -133,27 +143,35 @@ export interface ConfigurationOptions {
133
143
  username?: string;
134
144
  /** 密码 */
135
145
  password?: string;
136
- token: AccessTokenStore;
146
+ token?: Store;
147
+ ssonCookie?: string;
137
148
  }
138
149
  /**
150
+ * @public
139
151
  * accessToken 有效期7天,可以通过refreshToken取新的accessToken
140
152
  */
141
- export interface TokenSession extends AccessTokenStore {
153
+ export interface TokenSession {
142
154
  res_code: number;
143
155
  res_message: string;
156
+ accessToken: string;
144
157
  familySessionKey: string;
145
158
  familySessionSecret: string;
159
+ refreshToken: string;
146
160
  loginName: string;
147
161
  sessionKey: string;
148
162
  }
149
- export interface RefreshTokenSession extends AccessTokenStore {
163
+ /**
164
+ * @public
165
+ */
166
+ export interface RefreshTokenSession {
150
167
  expiresIn: number;
168
+ accessToken: string;
169
+ refreshToken: string;
151
170
  }
171
+ /**
172
+ * @public
173
+ */
152
174
  export interface ClientSession {
153
175
  accessToken: string;
154
176
  sessionKey: string;
155
177
  }
156
- export interface AccessTokenStore {
157
- accessToken: string;
158
- refreshToken: string;
159
- }
package/dist/util.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export declare const getSignature: (data: any) => string;
2
- export declare const rsaEncrypt: (publicKey: string, origData: string | Uint8Array) => string;
2
+ export declare const rsaEncrypt: (publicKey: string, origData: string) => string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cloud189-sdk",
3
- "version": "1.0.6-alpha.3",
3
+ "version": "1.0.6-alpha.5",
4
4
  "description": "基于node.js的第三方天翼云盘SDK",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -13,6 +13,8 @@
13
13
  "start": "node ./test/app.js",
14
14
  "debug": "CLOUD189_VERBOSE=1 npm run start",
15
15
  "build": "tsc",
16
+ "docs:build": "npm run build && cd docs && npm run build",
17
+ "docs:dev": "npm run build && cd docs && npm run dev",
16
18
  "test": "mocha",
17
19
  "coverage": "nyc npm run test"
18
20
  },