@seaverse/auth-sdk 0.1.5 → 0.2.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,103 +1,230 @@
1
- # @seaverseai/auth-sdk
1
+ # @seaverse/auth-sdk
2
2
 
3
- SeaVerse 认证 SDK - 提供完整的用户认证功能和精美的登录注册 UI 组件
3
+ SeaVerse Backend API 客户端 SDK - 提供完整的认证、容器管理、技能市场等功能
4
4
 
5
- [![npm version](https://img.shields.io/npm/v/@seaverseai/auth-sdk.svg)](https://www.npmjs.com/package/@seaverseai/auth-sdk)
5
+ [![npm version](https://img.shields.io/npm/v/@seaverse/auth-sdk.svg)](https://www.npmjs.com/package/@seaverse/auth-sdk)
6
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
7
 
8
8
  ## 功能特性
9
9
 
10
- - 🔐 **邮箱登录/注册** - 传统用户名密码认证
11
- - 🌐 **OAuth 第三方登录** - 支持 Google、Discord、GitHub
12
- - 🎨 **精美登录 UI** - 开箱即用的登录弹窗组件
13
- - 📱 **完全响应式** - 适配移动端/平板/桌面
14
- - 🎭 **主题支持** - 暗色/亮色主题切换
10
+ - 🔐 **用户认证** - 注册、登录、登出、密码重置
11
+ - 🌐 **OAuth登录** - Google、Discord、GitHub 第三方登录
12
+ - 🎨 **登录UI组件** - 开箱即用的精美登录弹窗
13
+ - 📦 **容器管理** - Container 注册、心跳、状态查询
14
+ - 🛍️ **技能市场** - Marketplace Skills 浏览、安装、卸载
15
+ - 🗣️ **语音服务** - Speech Token 获取
16
+ - 🌍 **多环境支持** - Production、Staging、Development、Local
15
17
  - ⚡ **TypeScript** - 完整的类型定义
16
- - 🔒 **安全** - 内置 CSRF 保护
17
- - 🌍 **多环境支持** - 一键切换生产/测试/开发环境
18
+ - 🔧 **认证集成** - 内置Auth、Hooks系统支持
18
19
 
19
20
  ## 安装
20
21
 
21
22
  ```bash
22
- npm install @seaverseai/auth-sdk
23
+ npm install @seaverse/auth-sdk
24
+ # 或
25
+ pnpm add @seaverse/auth-sdk
23
26
  ```
24
27
 
25
- ## 快速开始
28
+ ## 核心概念
29
+
30
+ ### App ID 和多租户架构
31
+
32
+ **重要**: 从 v0.2.0 开始,`appId` 是初始化 SDK 时的**必需参数**。
33
+
34
+ #### 什么是 App ID?
35
+
36
+ 每个应用都有唯一的 `app_id`:
37
+ - `app_id = "your app id"`
38
+
39
+ #### 多租户隔离
40
+
41
+ - 用户数据按 `app_id` 隔离
42
+ - 同一邮箱可在不同应用中注册,使用不同密码
43
+ - 每个应用拥有独立的用户池
44
+
45
+ #### X-App-ID 请求头
46
+
47
+ SDK 会自动在**每个请求**的请求头中添加 `X-App-ID`,无需手动设置:
48
+
49
+ ```typescript
50
+ const client = new SeaVerseBackendAPIClient({
51
+ appId: 'game-abc123', // SDK 自动将此值添加到所有请求的 X-App-ID header
52
+ });
53
+
54
+ // 所有 API 调用都会自动携带 X-App-ID: game-abc123
55
+ await client.login({ email, password });
56
+ await client.getCurrentUser();
57
+ ```
26
58
 
27
- ### 1. API 客户端使用
59
+ ## 快速开始
28
60
 
29
- #### 方式 A:指定环境(推荐)
61
+ ### 1. 基本使用
30
62
 
31
63
  ```typescript
32
- import { SeaVerseBackendAPIClient } from '@seaverseai/auth-sdk';
64
+ import { SeaVerseBackendAPIClient } from '@seaverse/auth-sdk';
33
65
 
34
- // 正式环境
66
+ // 方式1: SeaVerse 平台应用(自动检测环境)
35
67
  const client = new SeaVerseBackendAPIClient({
36
- environment: 'production', // 'production' | 'staging' | 'development' | 'local'
68
+ appId: 'your app id', // 必需:应用ID
37
69
  });
38
70
 
39
- // 或者测试环境
71
+ // 方式2: 第三方应用(指定环境)
40
72
  const client = new SeaVerseBackendAPIClient({
41
- environment: 'staging',
73
+ appId: 'your app id', // 必需:您的应用ID
74
+ environment: 'production', // 'production' | 'staging' | 'development' | 'local'
42
75
  });
43
- ```
44
76
 
45
- #### 方式 B:自动检测环境
77
+ // 方式3: 自定义URL
78
+ const client = new SeaVerseBackendAPIClient({
79
+ appId: 'your app id', // 必需:您的应用ID
80
+ baseURL: 'https://custom-api.example.com',
81
+ });
46
82
 
47
- ```typescript
48
- import { SeaVerseBackendAPIClient } from '@seaverseai/auth-sdk';
83
+ // 健康检查
84
+ const health = await client.getHealth();
85
+ console.log('Health:', health);
86
+ ```
49
87
 
50
- // SDK 会根据当前域名自动选择环境
51
- const client = new SeaVerseBackendAPIClient();
88
+ ### 2. 用户认证
52
89
 
53
- // 注册
90
+ ```typescript
91
+ // 注册新用户
54
92
  const registerResult = await client.register({
55
93
  email: 'user@example.com',
56
- password: 'password123',
94
+ password: 'SecurePassword123',
95
+ username: 'johndoe', // 可选,未提供则从邮箱自动生成
96
+ invitation_code: 'INVITE123', // 可选
57
97
  });
58
98
 
59
99
  // 登录
60
100
  const loginResult = await client.login({
61
101
  email: 'user@example.com',
62
- password: 'password123',
102
+ password: 'SecurePassword123',
63
103
  });
64
104
 
65
- // 保存 token
105
+ // 保存token
66
106
  localStorage.setItem('token', loginResult.token);
67
107
 
68
- // 获取当前用户
108
+ // 获取当前用户信息
69
109
  const user = await client.getCurrentUser();
110
+ console.log('User:', user);
111
+ console.log('App ID:', user.app_id); // 多租户应用ID
112
+ console.log('Email verified:', user.email_verified);
70
113
 
71
114
  // 登出
72
115
  await client.logout();
116
+
117
+ // 忘记密码
118
+ await client.forgotPassword({
119
+ email: 'user@example.com',
120
+ });
121
+
122
+ // 重置密码
123
+ await client.resetPassword({
124
+ token: 'reset-token-from-email',
125
+ new_password: 'NewSecurePassword123',
126
+ });
127
+ ```
128
+
129
+ ### 3. OAuth 第三方登录
130
+
131
+ #### Google 登录
132
+
133
+ ```typescript
134
+ // 步骤1: 获取Google授权码后,交换token
135
+ const result = await client.googleCodeToToken({
136
+ code: 'google-auth-code',
137
+ redirectUri: 'https://yourdomain.com/auth/callback',
138
+ });
139
+
140
+ localStorage.setItem('token', result.token);
141
+
142
+ // 解绑Google账号
143
+ await client.unlinkGoogle();
144
+ ```
145
+
146
+ #### Discord 登录
147
+
148
+ ```typescript
149
+ const result = await client.discordCodeToToken({
150
+ code: 'discord-auth-code',
151
+ redirectUri: 'https://yourdomain.com/auth/callback',
152
+ });
153
+
154
+ // 解绑Discord账号
155
+ await client.unlinkDiscord();
73
156
  ```
74
157
 
75
- ### 2. 使用登录弹窗 UI
158
+ #### GitHub 登录
76
159
 
77
160
  ```typescript
78
- import { SeaVerseBackendAPIClient, createAuthModal } from '@seaverseai/auth-sdk';
79
- import '@seaverseai/auth-sdk/src/auth-modal.css';
161
+ const result = await client.githubCodeToToken({
162
+ code: 'github-auth-code',
163
+ redirectUri: 'https://yourdomain.com/auth/callback',
164
+ });
165
+
166
+ // 解绑GitHub账号
167
+ await client.unlinkGithub();
168
+ ```
169
+
170
+ ### 4. 使用登录UI组件
171
+
172
+ SDK 提供精美的登录弹窗组件,支持深色和浅色两种主题:
173
+
174
+ #### 主题对比
175
+
176
+ | 主题 | 设计风格 | 适用场景 |
177
+ |------|---------|---------|
178
+ | **Dark** 🌙 | 动态网格渐变 + 玻璃态效果 | 科技感产品、游戏平台、深色界面应用 |
179
+ | **Light** ☀️ | 提升的卡片设计 + 柔和阴影 | 商务应用、内容平台、浅色界面应用 |
180
+
181
+ #### 基础用法
182
+
183
+ ```typescript
184
+ import { SeaVerseBackendAPIClient, AuthModal } from '@seaverse/auth-sdk';
185
+ import '@seaverse/auth-sdk/auth-modal.css'; // 导入样式
80
186
 
81
187
  const client = new SeaVerseBackendAPIClient({
82
- baseURL: 'https://account-hub.sg.seaverse.dev',
188
+ appId: 'your app id', // 必需:您的应用ID
189
+ environment: 'production',
83
190
  });
84
191
 
85
- const authModal = createAuthModal({
192
+ // 创建登录弹窗(深色主题)
193
+ const authModal = new AuthModal({
86
194
  client,
87
- theme: 'dark', // 'dark' 'light'
195
+ theme: 'dark', // 'dark' | 'light' - 默认为 'dark'
88
196
 
197
+ // 登录成功回调
89
198
  onLoginSuccess: (token, user) => {
90
199
  localStorage.setItem('token', token);
91
200
  console.log('登录成功:', user);
92
201
  },
93
202
 
203
+ // 注册成功回调
94
204
  onSignupSuccess: (token, user) => {
95
205
  localStorage.setItem('token', token);
96
206
  console.log('注册成功:', user);
97
207
  },
98
208
 
209
+ // 错误回调
99
210
  onError: (error) => {
100
- console.error('错误:', error.message);
211
+ console.error('认证错误:', error.message);
212
+ },
213
+
214
+ // OAuth配置(可选)
215
+ oauthConfig: {
216
+ google: {
217
+ clientId: 'YOUR_GOOGLE_CLIENT_ID', // 必填
218
+ redirectUri: window.location.origin, // 可选,默认为 window.location.origin
219
+ },
220
+ discord: {
221
+ clientId: 'YOUR_DISCORD_CLIENT_ID', // 必填
222
+ redirectUri: window.location.origin, // 可选,默认为 window.location.origin
223
+ },
224
+ github: {
225
+ clientId: 'YOUR_GITHUB_CLIENT_ID', // 必填
226
+ redirectUri: window.location.origin, // 可选,默认为 window.location.origin
227
+ },
101
228
  },
102
229
  });
103
230
 
@@ -106,127 +233,276 @@ authModal.show('login');
106
233
 
107
234
  // 显示注册界面
108
235
  authModal.show('signup');
109
- ```
110
236
 
111
- ## OAuth 第三方登录
237
+ // 隐藏弹窗
238
+ authModal.hide();
239
+
240
+ // 销毁弹窗
241
+ authModal.destroy();
242
+ #### OAuth 配置说明
243
+
244
+ `oauthConfig` 参数是**完全可选的**:
112
245
 
113
- ### 1. 配置 OAuth
246
+ - 如果**不提供** `oauthConfig`,则不会显示任何第三方登录按钮
247
+ - 如果**部分配置**(如只配置 Google),则只显示已配置的按钮
248
+ - 如果**完整配置**所有平台,则显示所有第三方登录按钮
249
+
250
+ **配置字段说明**:
251
+ - `clientId`:**必填** - OAuth 应用的客户端 ID
252
+ - `redirectUri`:**可选** - OAuth 回调地址,不填则默认为 `window.location.origin`
253
+ - `scope`:**可选** - OAuth 权限范围,每个平台有默认值
114
254
 
115
255
  ```typescript
116
- const authModal = createAuthModal({
117
- client,
256
+ // 示例1:无OAuth按钮
257
+ const client1 = new SeaVerseBackendAPIClient({ appId: 'your app id' });
258
+ const authModal1 = new AuthModal({
259
+ client: client1,
260
+ theme: 'dark',
261
+ // 不传 oauthConfig,不显示任何OAuth按钮
262
+ });
118
263
 
264
+ // 示例2:只显示Google登录
265
+ const client2 = new SeaVerseBackendAPIClient({ appId: 'your app id' });
266
+ const authModal2 = new AuthModal({
267
+ client: client2,
268
+ theme: 'light',
119
269
  oauthConfig: {
120
270
  google: {
121
271
  clientId: 'YOUR_GOOGLE_CLIENT_ID',
122
- redirectUri: 'https://yourdomain.com/auth/callback',
272
+ // redirectUri 可选,不填则默认为 window.location.origin
273
+ },
274
+ // Discord 和 GitHub 未配置,不会显示这些按钮
275
+ },
276
+ });
277
+
278
+ // 示例3:显示所有OAuth按钮(自定义 redirectUri)
279
+ const client3 = new SeaVerseBackendAPIClient({ appId: 'your app id' });
280
+ const authModal3 = new AuthModal({
281
+ client: client3,
282
+ theme: 'dark',
283
+ oauthConfig: {
284
+ google: {
285
+ clientId: '...',
286
+ redirectUri: 'https://yourdomain.com/auth/callback' // 自定义回调地址
123
287
  },
124
288
  discord: {
125
- clientId: 'YOUR_DISCORD_CLIENT_ID',
126
- redirectUri: 'https://yourdomain.com/auth/callback',
289
+ clientId: '...'
290
+ // redirectUri 可选,不填则默认为 window.location.origin
127
291
  },
128
292
  github: {
129
- clientId: 'YOUR_GITHUB_CLIENT_ID',
130
- redirectUri: 'https://yourdomain.com/auth/callback',
293
+ clientId: '...'
294
+ // redirectUri 可选,不填则默认为 window.location.origin
131
295
  },
132
296
  },
297
+ });
298
+ ```
133
299
 
134
- onLoginSuccess: (token, user) => {
135
- localStorage.setItem('token', token);
300
+ ### 5. 容器管理
301
+
302
+ ```typescript
303
+ // 列出所有容器
304
+ const containers = await client.listContainers();
305
+
306
+ // 注册新容器
307
+ const result = await client.registerContainer({
308
+ containerId: 'container-123',
309
+ metadata: {
310
+ version: '1.0.0',
311
+ capabilities: ['skill-execution'],
136
312
  },
137
313
  });
138
314
 
139
- authModal.show('login');
140
- ```
315
+ // 获取容器信息
316
+ const container = await client.getContainer({
317
+ containerId: 'container-123',
318
+ });
141
319
 
142
- ### 2. 处理 OAuth 回调
320
+ // 容器心跳
321
+ await client.containerHeartbeat({
322
+ containerId: 'container-123',
323
+ status: 'healthy',
324
+ });
143
325
 
144
- 在你的回调页面(如 `/auth/callback`)添加:
326
+ // 注销容器
327
+ await client.unregisterContainer({
328
+ containerId: 'container-123',
329
+ });
330
+
331
+ // 获取容器统计
332
+ const stats = await client.getContainerStats();
333
+ ```
334
+
335
+ ### 6. 技能市场
145
336
 
146
337
  ```typescript
147
- import { SeaVerseBackendAPIClient, AuthModal } from '@seaverseai/auth-sdk';
338
+ // 列出市场技能
339
+ const skills = await client.listMarketplaceSkills({
340
+ category: 'productivity',
341
+ page: 1,
342
+ pageSize: 20,
343
+ });
148
344
 
149
- const client = new SeaVerseBackendAPIClient({
150
- baseURL: 'https://account-hub.sg.seaverse.dev',
345
+ // 获取技能详情
346
+ const skill = await client.getMarketplaceSkill({
347
+ skillId: 'skill-123',
151
348
  });
152
349
 
153
- // 自动处理 OAuth 回调
154
- AuthModal.handleOAuthCallbackFromUrl(client, {
155
- onLoginSuccess: (token, user) => {
156
- localStorage.setItem('token', token);
157
- window.location.href = '/dashboard';
158
- },
159
- onError: (error) => {
160
- console.error('登录失败:', error);
161
- window.location.href = '/';
162
- },
350
+ // 安装技能
351
+ await client.installSkill({
352
+ skillId: 'skill-123',
163
353
  });
164
- ```
165
354
 
166
- ### 3. 获取 OAuth Client ID
355
+ // 列出已安装的技能
356
+ const userSkills = await client.listUserSkills();
167
357
 
168
- | 平台 | 配置地址 |
169
- |------|---------|
170
- | Google | https://console.cloud.google.com/ → 创建 OAuth 客户端 ID |
171
- | Discord | https://discord.com/developers/applications → OAuth2 设置 |
172
- | GitHub | https://github.com/settings/developers → OAuth Apps |
358
+ // 卸载技能
359
+ await client.uninstallSkill({
360
+ skillId: 'skill-123',
361
+ });
362
+ ```
173
363
 
174
- **重要**:在 OAuth 应用中配置的 Redirect URI 必须与代码中的 `redirectUri` 完全一致。
364
+ ### 7. 其他功能
175
365
 
176
- ## API 参考
366
+ ```typescript
367
+ // 获取API Service Token
368
+ const apiToken = await client.getApiServiceToken();
177
369
 
178
- ### 认证方法
370
+ // 获取对话状态
371
+ const status = await client.getConversationStatus({
372
+ conversationId: 'conv-123',
373
+ });
179
374
 
180
- ```typescript
181
- // 注册
182
- await client.register({ email, password, invitationCode? })
375
+ // 获取语音Token
376
+ const speechToken = await client.getSpeechToken();
377
+ ```
183
378
 
184
- // 登录
185
- await client.login({ email, password })
379
+ ## 高级配置
186
380
 
187
- // 获取当前用户
188
- await client.getCurrentUser()
381
+ ### 自定义认证
189
382
 
190
- // 登出
191
- await client.logout()
383
+ ```typescript
384
+ import { AuthFactory } from '@seaverse/auth-sdk';
192
385
 
193
- // 忘记密码
194
- await client.forgotPassword({ email })
386
+ const client = new SeaVerseBackendAPIClient({
387
+ appId: 'your app id', // 必需:应用ID
388
+ environment: 'production',
195
389
 
196
- // 重置密码
197
- await client.resetPassword({ token, newPassword })
390
+ // 使用JWT认证
391
+ auth: AuthFactory.create({
392
+ type: 'jwt',
393
+ credentials: {
394
+ type: 'jwt',
395
+ token: localStorage.getItem('token'),
396
+ },
397
+ }),
398
+ });
198
399
  ```
199
400
 
200
- ### OAuth 方法
401
+ ### 自定义Hooks
201
402
 
202
403
  ```typescript
203
- // Google 登录
204
- await client.googleCodeToToken({ code })
404
+ import { BuiltInHooks } from '@seaverse/auth-sdk';
205
405
 
206
- // Discord 登录
207
- await client.discordCodeToToken({ code })
406
+ const client = new SeaVerseBackendAPIClient({
407
+ appId: 'your app id', // 必需:应用ID
408
+ environment: 'production',
409
+
410
+ hooks: {
411
+ hooks: [
412
+ // 日志Hook
413
+ BuiltInHooks.createLoggerHook({
414
+ logLevel: 'debug',
415
+ logRequestBody: true,
416
+ logResponseBody: true,
417
+ }),
418
+
419
+ // 请求ID Hook
420
+ BuiltInHooks.createRequestIdHook(),
421
+
422
+ // 自定义Hook
423
+ {
424
+ type: 'beforeRequest',
425
+ name: 'custom-hook',
426
+ priority: 100,
427
+ handler: async (context) => {
428
+ console.log('Before request:', context.config.url);
429
+ },
430
+ },
431
+ ],
432
+ },
433
+ });
434
+ ```
208
435
 
209
- // GitHub 登录
210
- await client.githubCodeToToken({ code })
436
+ ### 环境配置
211
437
 
212
- // 解绑账号
213
- await client.unlinkGoogle()
214
- await client.unlinkDiscord()
215
- await client.unlinkGithub()
216
- ```
438
+ SDK支持以下环境:
217
439
 
218
- ### UI 方法
440
+ | 环境 | 描述 | BaseURL |
441
+ |------|------|---------|
442
+ | `production` | 生产环境 | `https://api.seaverse.com` |
443
+ | `staging` | 测试环境 | `https://api.staging.seaverse.dev` |
444
+ | `development` | 开发环境 | `https://api.dev.seaverse.dev` |
445
+ | `local` | 本地环境 | `http://localhost:3000` |
219
446
 
220
- ```typescript
221
- // 显示登录/注册
222
- authModal.show('login') // 'signup'
447
+ 自动检测规则:
448
+ - `*.seaverse.com` → production
449
+ - `*.staging.seaverse.dev` staging
450
+ - `*.dev.seaverse.dev` → development
451
+ - `localhost` → local
223
452
 
224
- // 隐藏弹窗
225
- authModal.hide()
453
+ ## API 参考
226
454
 
227
- // 销毁弹窗
228
- authModal.destroy()
229
- ```
455
+ ### 认证相关
456
+
457
+ | 方法 | 参数 | 返回值 | 说明 |
458
+ |------|------|--------|------|
459
+ | `register()` | `{ email, password, username?, invitation_code? }` | `RegisterResponse` | 注册新用户 |
460
+ | `login()` | `{ email, password }` | `LoginResponse` | 用户登录 |
461
+ | `getCurrentUser()` | - | `User` | 获取当前用户 |
462
+ | `logout()` | - | `SuccessResponse` | 登出 |
463
+ | `forgotPassword()` | `{ email }` | `SuccessResponse` | 忘记密码 |
464
+ | `resetPassword()` | `{ token, new_password }` | `SuccessResponse` | 重置密码 |
465
+ | `getApiServiceToken()` | - | `ApiServiceTokenResponse` | 获取API Token |
466
+
467
+ ### OAuth相关
468
+
469
+ | 方法 | 参数 | 返回值 | 说明 |
470
+ |------|------|--------|------|
471
+ | `googleCodeToToken()` | `{ code, redirectUri }` | `OAuthTokenResponse` | Google登录 |
472
+ | `discordCodeToToken()` | `{ code, redirectUri }` | `OAuthTokenResponse` | Discord登录 |
473
+ | `githubCodeToToken()` | `{ code, redirectUri }` | `OAuthTokenResponse` | GitHub登录 |
474
+ | `unlinkGoogle()` | - | `SuccessResponse` | 解绑Google |
475
+ | `unlinkDiscord()` | - | `SuccessResponse` | 解绑Discord |
476
+ | `unlinkGithub()` | - | `SuccessResponse` | 解绑GitHub |
477
+
478
+ ### 容器管理
479
+
480
+ | 方法 | 参数 | 返回值 | 说明 |
481
+ |------|------|--------|------|
482
+ | `listContainers()` | - | `ContainerListResponse` | 列出容器 |
483
+ | `registerContainer()` | `{ containerId, metadata }` | `SuccessResponse` | 注册容器 |
484
+ | `getContainer()` | `{ containerId }` | `Container` | 获取容器信息 |
485
+ | `unregisterContainer()` | `{ containerId }` | `SuccessResponse` | 注销容器 |
486
+ | `containerHeartbeat()` | `{ containerId, status }` | `SuccessResponse` | 容器心跳 |
487
+ | `getContainerStats()` | - | `ContainerStatsResponse` | 容器统计 |
488
+
489
+ ### 技能市场
490
+
491
+ | 方法 | 参数 | 返回值 | 说明 |
492
+ |------|------|--------|------|
493
+ | `listMarketplaceSkills()` | `{ category?, page?, pageSize? }` | `MarketplaceSkillsListResponse` | 列出市场技能 |
494
+ | `getMarketplaceSkill()` | `{ skillId }` | `MarketplaceSkill` | 获取技能详情 |
495
+ | `installSkill()` | `{ skillId }` | `SuccessResponse` | 安装技能 |
496
+ | `listUserSkills()` | - | `UserInstalledSkillsListResponse` | 列出已安装技能 |
497
+ | `uninstallSkill()` | `{ skillId }` | `SuccessResponse` | 卸载技能 |
498
+
499
+ ### 其他
500
+
501
+ | 方法 | 参数 | 返回值 | 说明 |
502
+ |------|------|--------|------|
503
+ | `getHealth()` | - | `HealthResponse` | 健康检查 |
504
+ | `getConversationStatus()` | `{ conversationId }` | `ConversationStatusResponse` | 获取对话状态 |
505
+ | `getSpeechToken()` | - | `SpeechTokenResponse` | 获取语音Token |
230
506
 
231
507
  ## 类型定义
232
508
 
@@ -234,12 +510,21 @@ authModal.destroy()
234
510
  // 用户信息
235
511
  interface User {
236
512
  id?: string;
513
+ app_id?: string | null; // 应用ID(多租户支持)
237
514
  email?: string;
238
515
  username?: string;
239
- emailVerified?: boolean;
240
- googleId?: string;
241
- discordId?: string;
242
- githubId?: string;
516
+ created_at?: number; // Unix时间戳
517
+ email_verified?: boolean; // 邮箱验证状态
518
+ google_id?: string | null; // Google账号ID
519
+ discord_id?: string | null; // Discord账号ID
520
+ github_id?: string | null; // GitHub账号ID
521
+
522
+ // 已弃用字段(向后兼容)
523
+ createdAt?: number; // @deprecated 使用 created_at
524
+ emailVerified?: boolean; // @deprecated 使用 email_verified
525
+ googleId?: string; // @deprecated 使用 google_id
526
+ discordId?: string; // @deprecated 使用 discord_id
527
+ githubId?: string; // @deprecated 使用 github_id
243
528
  }
244
529
 
245
530
  // 登录响应
@@ -255,119 +540,141 @@ interface RegisterResponse {
255
540
  userId: string;
256
541
  }
257
542
 
258
- // OAuth 配置
543
+ // AuthModal选项
544
+ interface AuthModalOptions {
545
+ client: SeaVerseBackendAPIClient;
546
+ theme?: 'dark' | 'light';
547
+ onLoginSuccess?: (token: string, user: any) => void;
548
+ onSignupSuccess?: (token: string, user: any) => void;
549
+ onError?: (error: Error) => void;
550
+ oauthConfig?: OAuthConfig;
551
+ }
552
+
553
+ // OAuth配置
259
554
  interface OAuthConfig {
260
555
  google?: {
261
- clientId: string;
262
- redirectUri: string;
263
- scope?: string; // 默认: 'openid email profile'
556
+ clientId: string; // 必填
557
+ redirectUri?: string; // 可选,默认为 window.location.origin
558
+ scope?: string; // 可选,默认为 'openid email profile'
264
559
  };
265
560
  discord?: {
266
- clientId: string;
267
- redirectUri: string;
268
- scope?: string; // 默认: 'identify email'
561
+ clientId: string; // 必填
562
+ redirectUri?: string; // 可选,默认为 window.location.origin
563
+ scope?: string; // 可选,默认为 'identify email'
269
564
  };
270
565
  github?: {
271
- clientId: string;
272
- redirectUri: string;
273
- scope?: string; // 默认: 'read:user user:email'
566
+ clientId: string; // 必填
567
+ redirectUri?: string; // 可选,默认为 window.location.origin
568
+ scope?: string; // 可选,默认为 'read:user user:email'
274
569
  };
275
570
  }
276
571
  ```
277
572
 
278
573
  ## 完整示例
279
574
 
280
- ```html
281
- <!DOCTYPE html>
282
- <html>
283
- <head>
284
- <meta charset="UTF-8">
285
- <title>登录示例</title>
286
- <link rel="stylesheet" href="node_modules/@seaverseai/auth-sdk/src/auth-modal.css">
287
- </head>
288
- <body>
289
- <h1>欢迎</h1>
290
- <button id="loginBtn">登录</button>
291
-
292
- <script type="module">
293
- import { SeaVerseBackendAPIClient, createAuthModal } from '@seaverseai/auth-sdk';
294
-
295
- const client = new SeaVerseBackendAPIClient({
296
- baseURL: 'https://account-hub.sg.seaverse.dev',
297
- });
298
-
299
- const authModal = createAuthModal({
300
- client,
301
- theme: 'dark',
302
-
303
- oauthConfig: {
304
- google: {
305
- clientId: 'YOUR_GOOGLE_CLIENT_ID',
306
- redirectUri: window.location.origin + '/callback.html',
307
- },
308
- },
575
+ 查看 [examples/auth-sdk-demo](../../examples/auth-sdk-demo) 目录获取完整的可运行示例。
309
576
 
310
- onLoginSuccess: (token, user) => {
311
- localStorage.setItem('token', token);
312
- alert('登录成功: ' + user.email);
313
- },
314
- });
315
-
316
- document.getElementById('loginBtn').onclick = () => {
317
- authModal.show('login');
318
- };
319
- </script>
320
- </body>
321
- </html>
577
+ ```bash
578
+ # 运行示例
579
+ cd examples/auth-sdk-demo
580
+ pnpm install
581
+ pnpm dev
322
582
  ```
323
583
 
324
- ## React 集成
584
+ ## 从旧版本迁移
325
585
 
326
- ```tsx
327
- import { useEffect, useState } from 'react';
328
- import { SeaVerseBackendAPIClient, createAuthModal } from '@seaverseai/auth-sdk';
329
- import '@seaverseai/auth-sdk/src/auth-modal.css';
586
+ ### v0.1.x → v0.2.0 升级指南
330
587
 
331
- function App() {
332
- const [authModal, setAuthModal] = useState(null);
588
+ #### 1. 向后兼容性
589
+ 好消息!v0.2.0 完全向后兼容,现有代码**无需修改**即可继续工作。
333
590
 
334
- useEffect(() => {
335
- const client = new SeaVerseBackendAPIClient({
336
- baseURL: 'https://account-hub.sg.seaverse.dev',
337
- });
591
+ #### 2. 推荐的迁移步骤
338
592
 
339
- const modal = createAuthModal({
340
- client,
341
- onLoginSuccess: (token) => {
342
- localStorage.setItem('token', token);
343
- },
344
- });
593
+ 虽然不是必须的,但我们建议逐步迁移到新的字段命名规范:
345
594
 
346
- setAuthModal(modal);
347
- return () => modal?.destroy();
348
- }, []);
595
+ ```typescript
596
+ // 旧代码(仍然可用)
597
+ const user = await client.getCurrentUser();
598
+ console.log(user.emailVerified); // ⚠️ 已弃用但可用
599
+ console.log(user.createdAt); // ⚠️ 已弃用但可用
349
600
 
350
- return (
351
- <button onClick={() => authModal?.show('login')}>
352
- 登录
353
- </button>
354
- );
355
- }
601
+ // 新代码(推荐)
602
+ const user = await client.getCurrentUser();
603
+ console.log(user.email_verified); // ✅ 推荐使用
604
+ console.log(user.created_at); // ✅ 推荐使用
605
+ console.log(user.app_id); // ✅ 新字段:多租户支持
356
606
  ```
357
607
 
358
- ## 常见问题
608
+ #### 3. 注册接口更新
609
+
610
+ ```typescript
611
+ // 旧代码(仍然可用)
612
+ await client.register({
613
+ email: 'user@example.com',
614
+ password: 'password123',
615
+ invitationCode: 'INVITE123', // ⚠️ 已弃用但可用
616
+ });
617
+
618
+ // 新代码(推荐)
619
+ await client.register({
620
+ email: 'user@example.com',
621
+ password: 'password123',
622
+ username: 'myusername', // ✨ 新功能
623
+ invitation_code: 'INVITE123', // ✅ 推荐使用
624
+ });
625
+ ```
626
+
627
+ #### 4. 密码重置接口更新
628
+
629
+ ```typescript
630
+ // 旧代码(需要更新)
631
+ await client.resetPassword({
632
+ token: 'reset-token',
633
+ newPassword: 'NewPass123', // ⚠️ 已弃用
634
+ });
359
635
 
360
- ### OAuth redirect_uri_mismatch 错误?
636
+ // 新代码(推荐)
637
+ await client.resetPassword({
638
+ token: 'reset-token',
639
+ new_password: 'NewPass123', // ✅ 推荐使用
640
+ });
641
+ ```
361
642
 
362
- 确保 OAuth 应用配置中的重定向 URI 与代码中完全一致(包括协议、域名、端口、路径)。
643
+ #### 5. TypeScript 类型提示
363
644
 
364
- ### 如何自动携带 Token?
645
+ 如果你使用 TypeScript,编译器会自动提示已弃用的字段:
365
646
 
366
647
  ```typescript
367
- import { AuthFactory } from '@seaverseai/auth-sdk';
648
+ const user = await client.getCurrentUser();
649
+ user.emailVerified; // TypeScript 会显示删除线和弃用警告
650
+ user.email_verified; // ✅ 无警告
651
+ ```
368
652
 
369
- const client = new SeaVerseBackendAPIClient({
370
- baseURL: 'https://account-hub.sg.seaverse.dev',
653
+ #### 6. 多租户功能(新增)
654
+
655
+ 如果你的应用需要支持多租户架构,可以使用新的 `app_id` 字段:
656
+
657
+ ```typescript
658
+ const user = await client.getCurrentUser();
659
+
660
+ console.log('your app id:', user.app_id);
661
+ ```
662
+
663
+ ## 常见问题
664
+
665
+ ### 如何处理认证token?
666
+
667
+ ```typescript
668
+ // 登录成功后保存token
669
+ const loginResult = await client.login({ email, password });
670
+ localStorage.setItem('token', loginResult.token);
671
+
672
+ // 创建带认证的client
673
+ import { AuthFactory } from '@seaverse/auth-sdk';
674
+
675
+ const authenticatedClient = new SeaVerseBackendAPIClient({
676
+ appId: 'your app id', // 必需:应用ID
677
+ environment: 'production',
371
678
  auth: AuthFactory.create({
372
679
  type: 'jwt',
373
680
  credentials: {
@@ -378,20 +685,28 @@ const client = new SeaVerseBackendAPIClient({
378
685
  });
379
686
  ```
380
687
 
381
- ### 如何只启用部分 OAuth 登录?
688
+ ### OAuth redirect_uri_mismatch错误?
382
689
 
383
- 只配置需要的平台即可,未配置的平台按钮点击时会提示错误:
690
+ 确保OAuth应用配置中的重定向URI与代码中的`redirectUri`完全一致(包括协议、域名、端口、路径)。
691
+
692
+ ### 如何自定义请求超时?
384
693
 
385
694
  ```typescript
386
- oauthConfig: {
387
- google: { /* ... */ },
388
- // 不配置 discord 和 github
389
- }
695
+ const client = new SeaVerseBackendAPIClient({
696
+ appId: 'your app id', // 必需:应用ID
697
+ environment: 'production',
698
+ timeout: 30000, // 30秒
699
+ });
390
700
  ```
391
701
 
392
- ### 本地开发如何测试 OAuth
702
+ ### 本地开发如何连接到本地API
393
703
 
394
- 大多数 OAuth 提供商允许 `http://localhost:PORT` 作为开发环境的重定向 URI。
704
+ ```typescript
705
+ const client = new SeaVerseBackendAPIClient({
706
+ appId: 'your app id', // 必需:应用ID
707
+ environment: 'local', // 或使用 baseURL: 'http://localhost:3000'
708
+ });
709
+ ```
395
710
 
396
711
  ## 开发
397
712
 
@@ -400,18 +715,55 @@ oauthConfig: {
400
715
  pnpm install
401
716
 
402
717
  # 构建
403
- pnpm run build
718
+ pnpm build
719
+
720
+ # Watch模式
721
+ pnpm dev
404
722
 
405
723
  # 测试
406
724
  pnpm test
407
725
  ```
408
726
 
409
- ## License
727
+ ## 相关链接
410
728
 
411
- MIT © SeaVerse Team
729
+ - 📦 [NPM Package](https://www.npmjs.com/package/@seaverse/auth-sdk)
730
+ - 📖 [示例项目](../../examples/auth-sdk-demo)
731
+ - 🐛 [Issues](https://github.com/seaverseai/sv-sdk/issues)
732
+ - 💬 [Discussions](https://github.com/seaverseai/sv-sdk/discussions)
412
733
 
413
- ## 技术支持
734
+ ## License
414
735
 
415
- - 📧 Email: support@seaverse.com
416
- - 🐛 Issues: https://github.com/seaverseai/sv-sdk/issues
417
- - 📖 Docs: https://docs.seaverse.dev
736
+ MIT © [SeaVerse Team](mailto:support@seaverse.com)
737
+
738
+ ## 更新日志
739
+
740
+ ### v0.2.0 (当前版本)
741
+ - 🔄 **API路径更新**: 所有认证API从 `/api/auth/*` 迁移到 `/sdk/v1/auth/*`
742
+ - 🏢 **多租户支持**: User模型新增 `app_id` 字段,支持多应用隔离
743
+ - 🔑 **重要变更**: `appId` 现在是**必需参数**,SDK 自动在所有请求中添加 `X-App-ID` 请求头
744
+ - ✨ **新功能**:
745
+ - 注册时支持自定义 `username`(可选)
746
+ - 所有字段标准化为 snake_case(保留 camelCase 向后兼容)
747
+ - 📝 **字段更新**:
748
+ - `SeaVerseBackendAPIClientOptions`: 新增必需字段 `appId`
749
+ - `User`: 新增 `app_id`, `created_at`, `email_verified`, `google_id`, `discord_id`, `github_id`
750
+ - `RegisterRequest`: 新增 `username`, `invitation_code`
751
+ - `ResetPasswordRequest`: `newPassword` → `new_password`
752
+ - ⚠️ **Breaking Changes**:
753
+ - 必须提供 `appId` 参数才能初始化 client
754
+ - API 路径变更需要后端支持
755
+ - ✅ **向后兼容**: 除 `appId` 外,所有旧字段仍然可用
756
+
757
+ ### v0.1.5
758
+ - 修复OAuth state管理,从sessionStorage切换到localStorage
759
+ - 增强API响应处理
760
+
761
+ ### v0.1.4
762
+ - 增强API响应处理
763
+ - 优化错误处理
764
+
765
+ ### v0.1.2
766
+ - 更新包名为@seaverse/auth-sdk
767
+ - 添加多环境支持
768
+
769
+ 查看完整更新日志:[CHANGELOG.md](./CHANGELOG.md)