@workopilot/webapp-sdk 0.1.0 → 0.1.1

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,66 +1,120 @@
1
- # WiseAiFrontSDK
1
+ # @workopilot/webapp-sdk
2
2
 
3
- 这个 SDK 面向挂在宿主项目里的 iframe 三方应用。
3
+ WiseAI 三方前端应用 SDK,适用于挂载在宿主项目中的 iframe 应用。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ npm install @workopilot/webapp-sdk
9
+ ```
4
10
 
5
11
  ## 初始化
6
12
 
7
13
  ```ts
8
- import { createWiseAiFrontSdk } from 'wiseai-front-sdk';
14
+ import { createWiseAiFrontSdk } from '@workopilot/webapp-sdk';
9
15
 
10
16
  const sdk = createWiseAiFrontSdk({
11
- env: 'dev',
12
17
  appCode: 'third-party-mysql-demo',
13
- javaBasePath: '',
18
+ env: 'prod',
19
+ javaBasePath: '/prod-api',
14
20
  netBasePath: '/net-api',
15
21
  });
16
22
 
17
23
  await sdk.init();
18
24
  ```
19
25
 
20
- ## token 规则
26
+ 初始化参数:
27
+
28
+ | 参数 | 必填 | 默认值 | 说明 |
29
+ | --- | --- | --- | --- |
30
+ | `appCode` | 是 | 无 | 三方应用编号 |
31
+ | `env` | 否 | 自动判断 | `dev` 或 `prod` |
32
+ | `javaBasePath` | 否 | `''` | Java 接口前缀 |
33
+ | `netBasePath` | 否 | `/net-api` | NET 接口前缀 |
34
+ | `enableEncrypt` | 否 | 读取环境变量 | 是否启用开发环境登录请求加密 |
35
+ | `clientId` | 否 | 读取环境变量 | 登录请求使用的客户端编号 |
36
+ | `rsaPublicKey` | 否 | 读取环境变量 | 启用加密时使用的 RSA 公钥 |
37
+
38
+ 生产环境建议由宿主项目的 `.env.*` 文件管理环境参数,再传给 SDK:
39
+
40
+ ```text
41
+ VITE_WISEAI_ENV=prod
42
+ VITE_WISEAI_APP_CODE=third-party-mysql-demo
43
+ VITE_WISEAI_JAVA_BASE_PATH=/prod-api
44
+ VITE_WISEAI_NET_BASE_PATH=/net-api
45
+ VITE_GLOB_ENABLE_ENCRYPT=true
46
+ VITE_GLOB_RSA_PUBLIC_KEY=...
47
+ VITE_GLOB_APP_CLIENT_ID=...
48
+ ```
49
+
50
+ ## 提供能力
21
51
 
22
- - 优先从本地存储读取 `accessToken`
23
- - 读取不到时:
24
- - `prod`:通过 `postMessage` 通知父窗口重新登录,并抛错
25
- - `dev`:弹出登录窗,输入用户名和密码后登录换取 token
52
+ ### Token 和登录
26
53
 
27
- ## iframe 通讯
54
+ - 自动读取和保存 `accessToken`。
55
+ - 自动检查 JWT 是否过期。
56
+ - 生产环境没有 token 时,通过 iframe `postMessage` 通知宿主重新登录。
57
+ - 开发环境没有 token 时,自动请求 `{javaBasePath}/auth/code` 获取验证码配置并弹出登录窗口。
58
+ - 根据 `captchaEnabled` 决定是否显示验证码。
59
+ - 登录接口默认使用 `POST {javaBasePath}/auth/login`,请求体不包含 `appCode`。
60
+ - 支持按参考项目规则使用 AES + RSA 加密登录请求。
61
+ - 业务请求自动携带 `Authorization: Bearer <token>`。
28
62
 
29
- 当生产环境下没有 token 时,SDK 会向父窗口发送消息:
63
+ ### 接口请求
30
64
 
31
65
  ```ts
32
- {
33
- source: 'wiseai-front-sdk',
34
- type: 'WISEAI_FRONT_SDK:RELOGIN_REQUIRED',
35
- payload: {
36
- appCode,
37
- env,
38
- reason: 'missing-token'
39
- }
40
- }
66
+ const user = await sdk.get('/plugins/third-party-mysql-demo/me');
67
+
68
+ const result = await sdk.postJson('/some/api', {
69
+ name: 'demo',
70
+ });
71
+
72
+ const data = await sdk.request('/some/api', {
73
+ base: 'net',
74
+ method: 'PATCH',
75
+ params: { id: 1 },
76
+ body: { name: 'demo' },
77
+ bodyType: 'json',
78
+ headers: {
79
+ 'X-Custom-Header': 'value',
80
+ },
81
+ });
41
82
  ```
42
83
 
43
- 父窗口可按自己的方式处理,比如:
84
+ 支持 `get`、`postJson` 和泛化 `request`。泛化请求支持自定义接口前缀、请求方法、查询参数、请求体类型和请求头。
85
+
86
+ ### 文件上传
44
87
 
45
- - 打开宿主登录页
46
- - 关闭当前 iframe
47
- - 提示用户重新认证
88
+ ```ts
89
+ const result = await sdk.uploadFile(file, {
90
+ path: '/api/smart_classify/upload',
91
+ fileFieldName: 'file',
92
+ extraData: {
93
+ businessType: 'smart_classify',
94
+ },
95
+ });
96
+ ```
48
97
 
49
- 如需父窗口主动告诉 SDK 重新登录,也可以回传:
98
+ 上传请求使用 `FormData` 并自动携带 token。默认上传地址为 `/api/file/upload`,可通过 `path` 覆盖。
99
+
100
+ ### 路由权限
50
101
 
51
102
  ```ts
52
- {
53
- source: 'wiseai-front-sdk-host',
54
- type: 'WISEAI_FRONT_SDK:RELOGIN',
55
- payload: { appCode }
56
- }
103
+ const menus = await sdk.getRoutePermissions();
104
+ ```
105
+
106
+ 默认调用:
107
+
108
+ ```text
109
+ GET {netBasePath}/app/menu/getRouters
57
110
  ```
58
111
 
59
- ## 导出能力
112
+ 返回路由菜单权限数据,宿主项目可以根据结果生成左侧菜单和受保护路由。
113
+
114
+ ### Token 清理
60
115
 
61
- - `request`
62
- - `get`
63
- - `postJson`
64
- - `uploadFile`
65
- - `getRoutePermissions`
116
+ ```ts
117
+ sdk.clearToken();
118
+ ```
66
119
 
120
+ 完整的 SDK 开发维护说明见 [SDK-DEVELOPMENT.md](./SDK-DEVELOPMENT.md)。
package/dist/dialog.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { LoginCredentials, LoginModalOptions } from './types';
2
2
  interface DialogConfig extends LoginModalOptions {
3
+ captchaEnabled: boolean;
3
4
  onSubmit: (credentials: LoginCredentials) => Promise<void>;
4
5
  }
5
6
  export declare function openDevLoginDialog(config: DialogConfig): Promise<LoginCredentials>;
package/dist/dialog.js CHANGED
@@ -37,9 +37,23 @@ export function openDevLoginDialog(config) {
37
37
  title.style.fontWeight = '700';
38
38
  const username = createInput('用户名');
39
39
  const password = createInput('密码', 'password');
40
- const captcha = config.captchaEnabled === false
41
- ? null
42
- : createInput(config.captchaLabel ?? '验证码');
40
+ let captchaImage = null;
41
+ if (config.captchaEnabled && config.captchaImage) {
42
+ captchaImage = document.createElement('img');
43
+ captchaImage.src = config.captchaImage.startsWith('data:')
44
+ ? config.captchaImage
45
+ : `data:image/png;base64,${config.captchaImage}`;
46
+ captchaImage.alt = '验证码';
47
+ captchaImage.style.width = '160px';
48
+ captchaImage.style.height = '60px';
49
+ captchaImage.style.objectFit = 'contain';
50
+ captchaImage.style.border = '1px solid #d0d7de';
51
+ captchaImage.style.borderRadius = '8px';
52
+ captchaImage.style.background = '#f8fafc';
53
+ }
54
+ const captcha = config.captchaEnabled
55
+ ? createInput(config.captchaLabel ?? '验证码')
56
+ : null;
43
57
  const actions = document.createElement('div');
44
58
  actions.style.display = 'flex';
45
59
  actions.style.justifyContent = 'flex-end';
@@ -77,6 +91,9 @@ export function openDevLoginDialog(config) {
77
91
  };
78
92
  if (captcha) {
79
93
  credentials.captcha = captcha.input.value.trim();
94
+ credentials.code = credentials.captcha;
95
+ credentials.captchaId = config.captchaUuid;
96
+ credentials.uuid = config.captchaUuid;
80
97
  }
81
98
  await config.onSubmit(credentials);
82
99
  handleClose();
@@ -89,6 +106,9 @@ export function openDevLoginDialog(config) {
89
106
  });
90
107
  actions.append(cancel, submit);
91
108
  panel.append(title, username.wrapper, password.wrapper);
109
+ if (captchaImage) {
110
+ panel.append(captchaImage);
111
+ }
92
112
  if (captcha) {
93
113
  panel.append(captcha.wrapper);
94
114
  }
@@ -0,0 +1,8 @@
1
+ export declare function randomStr(length?: number): string;
2
+ export declare function encodeBase64(value: string): string;
3
+ export declare function encryptAesEcbPkcs7(data: string, key: string): string;
4
+ export declare function encryptRsa(data: string, publicKey: string): string;
5
+ export declare function encryptRequestBody(body: unknown, publicKey: string): {
6
+ body: string;
7
+ encryptKey: string;
8
+ };
@@ -0,0 +1,37 @@
1
+ import CryptoJS from 'crypto-js';
2
+ import JSEncrypt from 'jsencrypt';
3
+ const RANDOM_CHARS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
4
+ export function randomStr(length = 32) {
5
+ let result = '';
6
+ for (let i = length; i > 0; --i) {
7
+ result += RANDOM_CHARS[Math.floor(Math.random() * RANDOM_CHARS.length)];
8
+ }
9
+ return result;
10
+ }
11
+ export function encodeBase64(value) {
12
+ return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(value));
13
+ }
14
+ export function encryptAesEcbPkcs7(data, key) {
15
+ const aesKey = CryptoJS.enc.Utf8.parse(key);
16
+ return CryptoJS.AES.encrypt(data, aesKey, {
17
+ mode: CryptoJS.mode.ECB,
18
+ padding: CryptoJS.pad.Pkcs7,
19
+ }).toString();
20
+ }
21
+ export function encryptRsa(data, publicKey) {
22
+ const instance = new JSEncrypt();
23
+ instance.setPublicKey(publicKey);
24
+ const encrypted = instance.encrypt(data);
25
+ if (encrypted === false) {
26
+ throw new Error('WiseAiFrontSDK: RSA encrypt error');
27
+ }
28
+ return encrypted;
29
+ }
30
+ export function encryptRequestBody(body, publicKey) {
31
+ const secret = randomStr(32);
32
+ const plainText = typeof body === 'string' ? body : JSON.stringify(body);
33
+ return {
34
+ body: encryptAesEcbPkcs7(plainText, secret),
35
+ encryptKey: encryptRsa(encodeBase64(secret), publicKey),
36
+ };
37
+ }
package/dist/http.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import type { MenuPermissionNode, RequestOptions, UploadOptions, WiseAiFrontSdkOptions, WiseAiFrontSdkState } from './types';
2
2
  export declare class WiseAiFrontSdk {
3
3
  private readonly appCode;
4
+ private readonly captchaPath;
5
+ private readonly clientId;
6
+ private readonly enableEncrypt;
4
7
  private readonly env;
5
8
  private readonly javaBasePath;
6
9
  private readonly loginModal?;
@@ -9,6 +12,7 @@ export declare class WiseAiFrontSdk {
9
12
  private readonly onReloginRequired?;
10
13
  private readonly parentWindow?;
11
14
  private readonly requestTimeoutMs;
15
+ private readonly rsaPublicKey;
12
16
  private readonly storage?;
13
17
  private readonly tokenKey;
14
18
  private readonly tokenStorageKey;
@@ -21,7 +25,9 @@ export declare class WiseAiFrontSdk {
21
25
  private getCurrentToken;
22
26
  private ensureToken;
23
27
  private loginInDev;
28
+ private buildLoginRequest;
24
29
  private openLoginModal;
30
+ private fetchCaptchaConfig;
25
31
  init(): Promise<WiseAiFrontSdkState>;
26
32
  private buildHeaders;
27
33
  private resolveBase;
package/dist/http.js CHANGED
@@ -1,7 +1,39 @@
1
1
  import { notifyReloginRequired, } from './bridge';
2
+ import { encryptRequestBody, } from './encryption';
2
3
  import { isJwtExpired, } from './jwt';
3
4
  import { clearToken, persistToken, resolveTokenFromStorage, } from './storage';
4
5
  import { openDevLoginDialog } from './dialog';
6
+ function inferEnvironment() {
7
+ if (typeof import.meta !== 'undefined') {
8
+ const env = import.meta.env;
9
+ if (env?.PROD) {
10
+ return 'prod';
11
+ }
12
+ if (env?.DEV || env?.MODE === 'development') {
13
+ return 'dev';
14
+ }
15
+ }
16
+ if (typeof location !== 'undefined') {
17
+ return ['127.0.0.1', 'localhost'].includes(location.hostname)
18
+ ? 'dev'
19
+ : 'prod';
20
+ }
21
+ return 'prod';
22
+ }
23
+ function readImportMetaEnv(key) {
24
+ if (typeof import.meta === 'undefined') {
25
+ return '';
26
+ }
27
+ const env = import.meta.env;
28
+ const value = env?.[key];
29
+ return typeof value === 'string' ? value : '';
30
+ }
31
+ function inferEnableEncrypt(explicit) {
32
+ if (explicit !== undefined) {
33
+ return explicit;
34
+ }
35
+ return readImportMetaEnv('VITE_GLOB_ENABLE_ENCRYPT') === 'true';
36
+ }
5
37
  function normalizeBasePath(basePath = '') {
6
38
  const trimmed = basePath.trim();
7
39
  if (!trimmed) {
@@ -44,11 +76,24 @@ async function parseResponse(response) {
44
76
  }
45
77
  return (await response.blob());
46
78
  }
79
+ function unwrapEnvelope(body) {
80
+ if (body &&
81
+ typeof body === 'object' &&
82
+ 'data' in body &&
83
+ body.data) {
84
+ return body.data;
85
+ }
86
+ return body;
87
+ }
47
88
  export class WiseAiFrontSdk {
48
89
  constructor(options) {
49
90
  this.accessToken = '';
50
91
  this.appCode = options.appCode;
51
- this.env = options.env;
92
+ this.captchaPath = options.captchaPath || '/auth/code';
93
+ this.clientId =
94
+ options.clientId || readImportMetaEnv('VITE_GLOB_APP_CLIENT_ID');
95
+ this.enableEncrypt = inferEnableEncrypt(options.enableEncrypt);
96
+ this.env = options.env || inferEnvironment();
52
97
  this.javaBasePath = normalizeBasePath(options.javaBasePath);
53
98
  this.loginModal = options.loginModal;
54
99
  this.loginPath = options.loginPath || '/auth/login';
@@ -56,6 +101,8 @@ export class WiseAiFrontSdk {
56
101
  this.onReloginRequired = options.onReloginRequired;
57
102
  this.parentWindow = options.parentWindow ?? (typeof window !== 'undefined' ? window.parent : undefined);
58
103
  this.requestTimeoutMs = options.requestTimeoutMs ?? 30000;
104
+ this.rsaPublicKey =
105
+ options.rsaPublicKey || readImportMetaEnv('VITE_GLOB_RSA_PUBLIC_KEY');
59
106
  this.storage = options.storage;
60
107
  this.tokenKey = options.tokenKey || 'accessToken';
61
108
  this.tokenStorageKey = options.tokenStorageKey || 'accessToken';
@@ -113,47 +160,92 @@ export class WiseAiFrontSdk {
113
160
  return token;
114
161
  }
115
162
  const credentials = await this.openLoginModal();
163
+ const loginBody = {
164
+ password: credentials.password,
165
+ username: credentials.username,
166
+ code: credentials.code || credentials.captcha,
167
+ uuid: credentials.uuid || credentials.captchaId,
168
+ grantType: 'password',
169
+ clientId: this.clientId,
170
+ };
171
+ const loginRequest = this.buildLoginRequest(loginBody);
116
172
  const response = await fetch(joinPath(this.javaBasePath, this.loginPath), {
117
- body: JSON.stringify({
118
- password: credentials.password,
119
- username: credentials.username,
120
- captcha: credentials.captcha,
121
- captchaId: credentials.captchaId,
122
- grantType: 'password',
123
- appCode: this.appCode,
124
- }),
125
- headers: {
126
- 'Content-Type': 'application/json;charset=utf-8',
127
- },
173
+ body: loginRequest.body,
174
+ headers: loginRequest.headers,
128
175
  method: 'POST',
129
176
  });
130
177
  if (!response.ok) {
131
178
  throw new Error(`WiseAiFrontSDK: login failed with ${response.status}`);
132
179
  }
133
180
  const data = (await response.json());
134
- const token = data.access_token || data.accessToken || '';
181
+ const loginResult = unwrapEnvelope(data);
182
+ const token = loginResult.access_token || loginResult.accessToken || '';
135
183
  if (!token) {
136
184
  throw new Error('WiseAiFrontSDK: login response missing token');
137
185
  }
138
186
  persistToken(this.storage, this.tokenKey, this.tokenStorageKey, token);
139
187
  return token;
140
188
  }
189
+ buildLoginRequest(body) {
190
+ const headers = {
191
+ 'Content-Type': 'application/json;charset=utf-8',
192
+ };
193
+ if (this.clientId) {
194
+ headers.ClientID = this.clientId;
195
+ }
196
+ if (!this.enableEncrypt) {
197
+ return {
198
+ body: JSON.stringify(body),
199
+ headers,
200
+ };
201
+ }
202
+ if (!this.rsaPublicKey) {
203
+ throw new Error('WiseAiFrontSDK: rsaPublicKey is required when enableEncrypt=true');
204
+ }
205
+ const encrypted = encryptRequestBody(body, this.rsaPublicKey);
206
+ headers['encrypt-key'] = encrypted.encryptKey;
207
+ return {
208
+ body: encrypted.body,
209
+ headers,
210
+ };
211
+ }
141
212
  async openLoginModal() {
213
+ const captcha = await this.fetchCaptchaConfig();
142
214
  return openDevLoginDialog({
143
- captchaEnabled: this.loginModal?.captchaEnabled ?? false,
215
+ captchaEnabled: Boolean(captcha?.captchaEnabled),
216
+ captchaImage: captcha?.img,
144
217
  captchaLabel: this.loginModal?.captchaLabel,
218
+ captchaUuid: captcha?.uuid,
145
219
  title: this.loginModal?.title,
146
220
  onSubmit: async () => undefined,
147
221
  }).catch(() => {
148
222
  throw new Error('WiseAiFrontSDK: login cancelled');
149
223
  });
150
224
  }
225
+ async fetchCaptchaConfig() {
226
+ const response = await fetch(joinPath(this.javaBasePath, this.captchaPath), {
227
+ headers: {
228
+ Accept: 'application/json',
229
+ },
230
+ method: 'GET',
231
+ });
232
+ if (!response.ok) {
233
+ throw new Error(`WiseAiFrontSDK: captcha request failed with ${response.status}`);
234
+ }
235
+ const body = (await response.json());
236
+ return unwrapEnvelope(body);
237
+ }
151
238
  async init() {
152
239
  await this.ensureToken();
153
240
  return this.state;
154
241
  }
155
- buildHeaders(headers = {}, token) {
156
- return token ? { Authorization: `Bearer ${token}`, ...headers } : headers;
242
+ buildHeaders(headers = {}, token, bodyType) {
243
+ const contentType = bodyType === 'json'
244
+ ? { 'Content-Type': 'application/json;charset=utf-8' }
245
+ : {};
246
+ return token
247
+ ? { ...contentType, Authorization: `Bearer ${token}`, ...headers }
248
+ : { ...contentType, ...headers };
157
249
  }
158
250
  resolveBase(base) {
159
251
  if (base === 'net') {
@@ -175,7 +267,7 @@ export class WiseAiFrontSdk {
175
267
  try {
176
268
  const response = await fetch(url, {
177
269
  body: this.resolveRequestBody(options.body, options.bodyType),
178
- headers: this.buildHeaders(options.headers, token),
270
+ headers: this.buildHeaders(options.headers, token, options.bodyType),
179
271
  method: options.method || 'GET',
180
272
  signal: controller.signal,
181
273
  });
package/dist/types.d.ts CHANGED
@@ -5,8 +5,10 @@ export type ApiBase = 'java' | 'net' | 'absolute';
5
5
  export interface LoginCredentials {
6
6
  captcha?: string;
7
7
  captchaId?: string;
8
+ code?: string;
8
9
  password: string;
9
10
  username: string;
11
+ uuid?: string;
10
12
  }
11
13
  export interface LoginResult {
12
14
  access_token?: string;
@@ -14,6 +16,18 @@ export interface LoginResult {
14
16
  refresh_token?: string;
15
17
  refreshToken?: string;
16
18
  }
19
+ export interface CaptchaResult {
20
+ captchaEnabled: boolean;
21
+ img?: string;
22
+ uuid?: string;
23
+ }
24
+ export interface ApiEnvelope<T> {
25
+ code?: number;
26
+ data?: T;
27
+ msg?: string;
28
+ rows?: T;
29
+ [key: string]: unknown;
30
+ }
17
31
  export interface JwtPayload {
18
32
  exp?: number;
19
33
  iat?: number;
@@ -43,13 +57,17 @@ export interface UploadOptions {
43
57
  path?: string;
44
58
  }
45
59
  export interface LoginModalOptions {
46
- captchaEnabled?: boolean;
60
+ captchaImage?: string;
47
61
  captchaLabel?: string;
62
+ captchaUuid?: string;
48
63
  title?: string;
49
64
  }
50
65
  export interface WiseAiFrontSdkOptions {
51
66
  appCode: string;
52
- env: WiseAiEnvironment;
67
+ captchaPath?: string;
68
+ clientId?: string;
69
+ enableEncrypt?: boolean;
70
+ env?: WiseAiEnvironment;
53
71
  javaBasePath?: string;
54
72
  loginModal?: LoginModalOptions;
55
73
  loginPath?: string;
@@ -61,6 +79,7 @@ export interface WiseAiFrontSdkOptions {
61
79
  }) => void;
62
80
  parentWindow?: Window;
63
81
  requestTimeoutMs?: number;
82
+ rsaPublicKey?: string;
64
83
  storage?: Storage;
65
84
  tokenKey?: string;
66
85
  tokenStorageKey?: string;
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@workopilot/webapp-sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "WiseAI front-end SDK for iframe-hosted third-party apps",
5
- "keywords":"wiseai,workopilot",
6
- "author":"workopilot",
5
+ "keywords": "wiseai,workopilot",
6
+ "author": "workopilot",
7
7
  "license": "MIT",
8
8
  "type": "module",
9
9
  "main": "dist/index.js",
@@ -22,8 +22,12 @@
22
22
  "scripts": {
23
23
  "build": "tsc -p tsconfig.json"
24
24
  },
25
+ "dependencies": {
26
+ "crypto-js": "^4.2.0",
27
+ "jsencrypt": "^3.3.2"
28
+ },
25
29
  "devDependencies": {
30
+ "@types/crypto-js": "^4.2.2",
26
31
  "typescript": "^5.7.2"
27
32
  }
28
33
  }
29
-