@kne/fastify-oidc 0.1.9 → 0.1.11

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.
@@ -1,6 +1,12 @@
1
+ const { scopePermissions, isAppEnabledIn } = require('../utils/app-permissions');
2
+ const { COMPANY_FIELDS } = require('../utils/tenant-images');
3
+
1
4
  const ACTIVE_USER_STATUS = [0, 1];
5
+ const SNAPSHOT_TENANT_FIELDS = ['themeColor', 'description', 'accountCount', 'supportLanguage', 'defaultLanguage', 'serviceStartTime', 'serviceEndTime'];
2
6
 
3
7
  const plain = item => (item && typeof item.get === 'function' ? item.get({ plain: true }) : item);
8
+ const pickFields = (item, fields) => Object.fromEntries(fields.filter(key => item[key] !== undefined).map(key => [key, item[key]]));
9
+ const toOrgIds = member => (Array.isArray(member.tenantOrgIds) ? member.tenantOrgIds : member.tenantOrgId ? [member.tenantOrgId] : []).map(String);
4
10
 
5
11
  /**
6
12
  * oidc-provider 与 kne 包之间的唯一桥接层:
@@ -14,10 +20,23 @@ module.exports = ({ fastify, options }) => {
14
20
  }
15
21
  return ns;
16
22
  };
17
- const tenant = () => fastify[options.tenantNamespace];
23
+ const tenant = () => options.getTenant();
24
+ const prefix = options.appPermissionPrefix;
18
25
 
19
26
  const tenantEnabled = () => !!tenant();
20
27
 
28
+ const getTenantPermissionCodes = async tenantId => {
29
+ try {
30
+ return (await tenant().services.permission.list({ tenantId })).codes || [];
31
+ } catch (e) {
32
+ return [];
33
+ }
34
+ };
35
+
36
+ const isAppEnabled = async (tenantId, appCode) => isAppEnabledIn(await getTenantPermissionCodes(tenantId), appCode, prefix);
37
+
38
+ const scopeAppPermissions = (permissions, appCode) => scopePermissions(permissions, appCode, prefix);
39
+
21
40
  const getUser = async id => {
22
41
  try {
23
42
  return await account().services.user.getUser({ id });
@@ -70,33 +89,51 @@ module.exports = ({ fastify, options }) => {
70
89
  return services.account.verifyCredentials(credentials);
71
90
  };
72
91
 
73
- const listTenants = async accountId => {
74
- if (!tenantEnabled()) {
92
+ // appCode:只保留已开通该子应用的租户;appOpen=false(应用已停用 / 删除)时没有可用租户
93
+ const listTenants = async (accountId, { appCode, appOpen = true } = {}) => {
94
+ if (!tenantEnabled() || (appCode && !appOpen)) {
75
95
  return { list: [], defaultTenantId: null };
76
96
  }
77
97
  const { list, defaultTenantId } = await tenant().services.user.tenantList({ id: accountId });
98
+ let result = list
99
+ .map(plain)
100
+ .filter(item => item.status === 'open' && (!item.tenant || item.tenant.status === 'open'))
101
+ .map(item => ({
102
+ tenantId: String(item.tenantId),
103
+ tenantUserId: String(item.id),
104
+ name: item.tenant?.name,
105
+ logo: item.tenant?.logo,
106
+ companyName: item.tenant?.company?.name
107
+ }));
108
+ if (appCode) {
109
+ const enabled = await Promise.all(result.map(item => isAppEnabled(item.tenantId, appCode)));
110
+ result = result.filter((item, index) => enabled[index]);
111
+ }
112
+ const normalizedDefault = defaultTenantId ? String(defaultTenantId) : null;
78
113
  return {
79
- list: list
80
- .map(plain)
81
- .filter(item => item.status === 'open' && (!item.tenant || item.tenant.status === 'open'))
82
- .map(item => ({
83
- tenantId: String(item.tenantId),
84
- tenantUserId: String(item.id),
85
- name: item.tenant?.name,
86
- logo: item.tenant?.logo,
87
- companyName: item.tenant?.company?.name
88
- })),
89
- defaultTenantId: defaultTenantId ? String(defaultTenantId) : null
114
+ list: result,
115
+ defaultTenantId: result.some(item => item.tenantId === normalizedDefault) ? normalizedDefault : result[0]?.tenantId || null
90
116
  };
91
117
  };
92
118
 
93
- const isTenantMember = async (accountId, tenantId) => {
94
- const { list } = await listTenants(accountId);
119
+ const isTenantMember = async (accountId, tenantId, scope = {}) => {
120
+ const { list } = await listTenants(accountId, scope);
95
121
  return list.some(item => item.tenantId === String(tenantId));
96
122
  };
97
123
 
98
- const getTenantContext = async ({ accountId, tenantId }) => {
99
- if (!tenantEnabled() || !tenantId) {
124
+ const getTenantUserInfo = async ({ accountId, tenantId, appCode }) => {
125
+ const info = plain(await tenant().services.user.getTenantUserInfo({ id: accountId, tenantId }));
126
+ if (!appCode) {
127
+ return info;
128
+ }
129
+ return Object.assign({}, info, { permissions: scopeAppPermissions(info.permissions, appCode) });
130
+ };
131
+
132
+ const getTenantContext = async ({ accountId, tenantId, appCode, appOpen = true }) => {
133
+ if (!tenantEnabled() || !tenantId || (appCode && !appOpen)) {
134
+ return null;
135
+ }
136
+ if (appCode && !(await isAppEnabled(tenantId, appCode))) {
100
137
  return null;
101
138
  }
102
139
  let info;
@@ -112,9 +149,103 @@ module.exports = ({ fastify, options }) => {
112
149
  tenantId: String(info.tenantId),
113
150
  tenantUserId: String(info.id),
114
151
  roles: (info.roleDetails || []).map(role => role.code || String(role.id)).filter(Boolean),
115
- permissions: info.permissions || []
152
+ permissions: appCode ? scopeAppPermissions(info.permissions, appCode) : info.permissions || []
153
+ };
154
+ };
155
+
156
+ // independent 子应用回拉的租户快照,id 均为宿主侧 id,权限已按应用去前缀;成员另走分页接口
157
+ const getTenantSnapshot = async ({ tenantId, appCode, appOpen = true }) => {
158
+ const { models, services } = tenant();
159
+ // 宿主已删除该租户:返回 removed,子应用据此关闭托管租户(否则回拉一直失败,托管租户停在 open)
160
+ if (!(await models.tenant.findByPk(tenantId))) {
161
+ return { tenant: { id: String(tenantId), status: 'closed' }, enabled: false, removed: true, permissions: [], roles: [], orgs: [] };
162
+ }
163
+ const hostTenant = plain(await services.tenant.detail({ id: tenantId, withTenantSetting: false }));
164
+ const codes = await getTenantPermissionCodes(tenantId);
165
+ const enabled = appOpen && isAppEnabledIn(codes, appCode, prefix);
166
+ const snapshot = {
167
+ tenant: Object.assign(pickFields(hostTenant, SNAPSHOT_TENANT_FIELDS), {
168
+ id: String(hostTenant.id),
169
+ name: hostTenant.name,
170
+ status: hostTenant.status,
171
+ logo: hostTenant.logo || null,
172
+ companyName: hostTenant.tenantCompany?.name || hostTenant.company?.name,
173
+ company: pickFields(plain(hostTenant.tenantCompany || hostTenant.company) || {}, COMPANY_FIELDS)
174
+ }),
175
+ enabled,
176
+ permissions: [],
177
+ roles: [],
178
+ orgs: []
179
+ };
180
+ if (!enabled) {
181
+ return snapshot;
182
+ }
183
+ snapshot.permissions = scopeAppPermissions(codes, appCode);
184
+ const roles = await models.role.findAll({ where: { tenantId } });
185
+ snapshot.roles = roles.map(plain).map(role => ({
186
+ id: String(role.id),
187
+ code: role.code || `role-${role.id}`,
188
+ name: role.name,
189
+ description: role.description,
190
+ type: role.type,
191
+ status: role.status,
192
+ permissions: scopeAppPermissions(role.permissions, appCode)
193
+ }));
194
+ const orgs = await models.org.findAll({ where: { tenantId } });
195
+ snapshot.orgs = orgs.map(plain).map(org => ({
196
+ id: String(org.id),
197
+ parentId: org.parentId != null ? String(org.parentId) : null,
198
+ name: org.name,
199
+ description: org.description,
200
+ index: org.index,
201
+ status: org.status,
202
+ leaderTenantUserId: org.leaderUserId != null ? String(org.leaderUserId) : null
203
+ }));
204
+ return snapshot;
205
+ };
206
+
207
+ // 只同步已关联账号的成员(未加入的邀请没有 userId,子应用无法建立镜像用户)
208
+ const listTenantMembers = async ({ tenantId, currentPage = 1, perPage = 200 }) => {
209
+ const { models } = tenant();
210
+ const { Op } = fastify.sequelize.Sequelize;
211
+ const roleCodes = new Map((await models.role.findAll({ where: { tenantId } })).map(plain).map(role => [String(role.id), role.code || `role-${role.id}`]));
212
+ const { rows, count } = await models.user.findAndCountAll({
213
+ where: { tenantId, userId: { [Op.ne]: null } },
214
+ offset: perPage * (currentPage - 1),
215
+ limit: perPage,
216
+ order: [['createdAt', 'ASC']]
217
+ });
218
+ return {
219
+ pageData: rows.map(plain).map(member => ({
220
+ id: String(member.id),
221
+ userId: String(member.userId),
222
+ name: member.name,
223
+ email: member.email,
224
+ phone: member.phone,
225
+ avatar: member.avatar,
226
+ status: member.status,
227
+ roleCodes: (member.roles || []).map(id => roleCodes.get(String(id))).filter(Boolean),
228
+ tenantOrgIds: toOrgIds(member)
229
+ })),
230
+ totalCount: count
116
231
  };
117
232
  };
118
233
 
119
- return { tenantEnabled, getUser, isSuperAdmin, toProfileClaims, findAccount, verifyCredentials, listTenants, isTenantMember, getTenantContext };
234
+ return {
235
+ tenant,
236
+ tenantEnabled,
237
+ getUser,
238
+ isSuperAdmin,
239
+ toProfileClaims,
240
+ findAccount,
241
+ verifyCredentials,
242
+ listTenants,
243
+ isTenantMember,
244
+ getTenantUserInfo,
245
+ getTenantContext,
246
+ isAppEnabled,
247
+ scopePermissions: scopeAppPermissions,
248
+ getTenantSnapshot,
249
+ listTenantMembers
250
+ };
120
251
  };
package/libs/idp/index.js CHANGED
@@ -2,6 +2,7 @@ const { createLocalJWKSet } = require('jose');
2
2
  const createIdentity = require('./identity');
3
3
  const createProvider = require('./create-provider');
4
4
  const createSequelizeAdapter = require('./adapters/sequelize');
5
+ const { createMemoryStore } = require('../resource/revocation');
5
6
 
6
7
  /**
7
8
  * IdP 运行期:持有当前 oidc-provider 实例,负责初始化、密钥轮换后的热替换和定时清理
@@ -75,6 +76,15 @@ module.exports = ({ fastify, options, translator }) => {
75
76
  }
76
77
  };
77
78
 
79
+ // 多实例部署时其他实例注册 / 停用的应用靠周期重载同步到本实例的权限树
80
+ const reloadApps = async () => {
81
+ try {
82
+ await getServices().app.reload();
83
+ } catch (e) {
84
+ fastify.log.warn({ err: e }, 'fastify-oidc: 重载应用中心失败');
85
+ }
86
+ };
87
+
78
88
  const cleanup = async () => {
79
89
  try {
80
90
  const { models } = fastify[options.name];
@@ -99,11 +109,20 @@ module.exports = ({ fastify, options, translator }) => {
99
109
  };
100
110
 
101
111
  const init = async () => {
102
- PayloadAdapter = options.adapter || createSequelizeAdapter({ models: fastify[options.name].models });
112
+ PayloadAdapter =
113
+ options.adapter ||
114
+ createSequelizeAdapter({
115
+ models: fastify[options.name].models,
116
+ endedStore: options.revocationStore || createMemoryStore(),
117
+ sessionTTL: options.ttl.session
118
+ });
103
119
  await getServices().key.ensureKeys();
104
120
  await seed();
121
+ await getServices().app.reload();
122
+ getServices().tenantPush?.start();
105
123
  await build();
106
124
  schedule(reloadIfKeysChanged, options.keyReloadInterval);
125
+ schedule(reloadApps, options.keyReloadInterval);
107
126
  schedule(cleanup, options.cleanupInterval);
108
127
  };
109
128
 
@@ -59,5 +59,13 @@ module.exports = {
59
59
  subjectTokenAccountInvalid: 'The user of subject_token does not exist or is disabled',
60
60
  logoutPageTitle: 'Log out',
61
61
  logoutConfirm: 'Confirm log out',
62
- logoutSuccess: 'You have been logged out'
62
+ logoutSuccess: 'You have been logged out',
63
+ appNotFound: 'App does not exist',
64
+ appCodeInvalid: 'App code may only contain letters, digits, underscores and hyphens',
65
+ appTenantModeInvalid: 'tenantMode must be client or independent',
66
+ appCodeTaken: 'App {code} has been registered by another client',
67
+ appClientMismatch: 'The current client cannot access data of app {code}',
68
+ appNotEnabled: 'The tenant has not enabled this app or the app is disabled',
69
+ tenantSyncTokenInvalid: 'tenant_sync_token is invalid or expired',
70
+ tenantSyncTokenReplayed: 'tenant_sync_token has already been used'
63
71
  };
@@ -59,5 +59,13 @@ module.exports = {
59
59
  subjectTokenAccountInvalid: 'subject_token 对应的用户不存在或已被禁用',
60
60
  logoutPageTitle: '退出登录',
61
61
  logoutConfirm: '确认退出',
62
- logoutSuccess: '已退出登录'
62
+ logoutSuccess: '已退出登录',
63
+ appNotFound: '子应用不存在',
64
+ appCodeInvalid: '应用 code 只能包含字母、数字、下划线和中划线',
65
+ appTenantModeInvalid: 'tenantMode 只能是 client 或 independent',
66
+ appCodeTaken: '应用 {code} 已由其他 client 注册',
67
+ appClientMismatch: '当前 client 无权访问应用 {code} 的数据',
68
+ appNotEnabled: '租户未开通该应用或应用已停用',
69
+ tenantSyncTokenInvalid: 'tenant_sync_token 无效或已过期',
70
+ tenantSyncTokenReplayed: 'tenant_sync_token 已被使用'
63
71
  };
@@ -0,0 +1,65 @@
1
+ module.exports = ({ DataTypes }) => {
2
+ return {
3
+ model: {
4
+ code: {
5
+ type: DataTypes.STRING(64),
6
+ allowNull: false,
7
+ comment: '应用编码,宿主权限 code 前缀 apps:<code>'
8
+ },
9
+ name: {
10
+ type: DataTypes.STRING(255),
11
+ comment: '应用名称'
12
+ },
13
+ description: {
14
+ type: DataTypes.TEXT,
15
+ comment: '描述'
16
+ },
17
+ tenantMode: {
18
+ type: DataTypes.STRING(16),
19
+ allowNull: false,
20
+ defaultValue: 'client',
21
+ comment: 'client: 租户由宿主提供, independent: 子应用本地租户,宿主同步的租户由宿主接管'
22
+ },
23
+ serviceClientId: {
24
+ type: DataTypes.STRING(255),
25
+ allowNull: false,
26
+ comment: '首次注册的服务 client_id,其他 client 不能覆盖该应用'
27
+ },
28
+ clientIds: {
29
+ type: DataTypes.JSON,
30
+ comment: '子应用登录用的 client_id 列表,用于交互与签发 token 时识别应用'
31
+ },
32
+ resource: {
33
+ type: DataTypes.STRING(255),
34
+ comment: '子应用资源服务 identifier(access_token 的 aud)'
35
+ },
36
+ permissions: {
37
+ type: DataTypes.JSON,
38
+ comment: '子应用权限树(不含 apps 前缀)'
39
+ },
40
+ permissionsHash: {
41
+ type: DataTypes.STRING(64),
42
+ comment: '权限树摘要'
43
+ },
44
+ tenantSyncUri: {
45
+ type: DataTypes.STRING(1024),
46
+ comment: 'independent 模式接收租户变更通知的地址'
47
+ },
48
+ registeredAt: {
49
+ type: DataTypes.DATE,
50
+ comment: '最近一次注册时间'
51
+ },
52
+ status: {
53
+ type: DataTypes.STRING(16),
54
+ allowNull: false,
55
+ defaultValue: 'open',
56
+ comment: 'open: 启用, closed: 停用, removed: 已删除(子应用重新注册时恢复)'
57
+ }
58
+ },
59
+ options: {
60
+ comment: 'OIDC 子应用(应用中心)',
61
+ paranoid: false,
62
+ indexes: [{ fields: ['code'], unique: true }]
63
+ }
64
+ };
65
+ };
@@ -0,0 +1,76 @@
1
+ /**
2
+ * 子应用启动时把权限树注册到宿主应用中心;宿主不可用时退避重试,不阻塞启动。
3
+ * 宿主按 permissionsHash 比对,权限树没变化时不会重建宿主权限树
4
+ */
5
+ module.exports = ({ fastify, options, serviceClient }) => {
6
+ const { runtime } = options;
7
+ let timer = null;
8
+ let stopped = false;
9
+ let firstAttempt = Promise.resolve(null);
10
+ const state = { registered: false, result: null, lastError: null };
11
+
12
+ const getPermissions = () => {
13
+ const { app } = runtime;
14
+ if (app.permissions) {
15
+ return app.permissions;
16
+ }
17
+ return (app.tenantMode === 'independent' && options.getTenant()?.permissions) || { modules: [] };
18
+ };
19
+
20
+ const register = async () => {
21
+ const { app } = runtime;
22
+ const result = await serviceClient.registerApp({
23
+ code: app.code,
24
+ name: app.name,
25
+ description: app.description,
26
+ tenantMode: app.tenantMode,
27
+ clientId: runtime.clientId,
28
+ resource: runtime.audience,
29
+ permissions: getPermissions(),
30
+ tenantSyncUri: app.tenantSyncUri
31
+ });
32
+ Object.assign(state, { registered: true, result, lastError: null });
33
+ return result;
34
+ };
35
+
36
+ const start = () => {
37
+ if (!runtime.app) {
38
+ return firstAttempt;
39
+ }
40
+ if (!serviceClient.enabled()) {
41
+ fastify.log.warn('fastify-oidc: 配置了 app 但未配置 serviceClient,无法向宿主注册权限');
42
+ return firstAttempt;
43
+ }
44
+ let attempt = 0;
45
+ const run = async () => {
46
+ if (stopped) {
47
+ return null;
48
+ }
49
+ try {
50
+ return await register();
51
+ } catch (err) {
52
+ state.lastError = err;
53
+ // 宿主明确拒绝(如 appCodeTaken、参数非法、未授权 scope)重试也不会成功,停止并报错,修正配置后重启
54
+ const status = err.upstreamStatus;
55
+ if (status >= 400 && status < 500 && status !== 408 && status !== 429) {
56
+ fastify.log.error({ err, status }, 'fastify-oidc: 宿主拒绝注册应用,已停止重试');
57
+ return null;
58
+ }
59
+ const delay = Math.min(options.appRegisterRetryMax * 1000, 1000 * 2 ** attempt++);
60
+ fastify.log.warn({ err, delay }, 'fastify-oidc: 向宿主注册应用失败,稍后重试');
61
+ timer = setTimeout(run, delay);
62
+ timer.unref?.();
63
+ return null;
64
+ }
65
+ };
66
+ firstAttempt = run();
67
+ return firstAttempt;
68
+ };
69
+
70
+ const stop = () => {
71
+ stopped = true;
72
+ clearTimeout(timer);
73
+ };
74
+
75
+ return { start, stop, register, whenStarted: () => firstAttempt, getState: () => Object.assign({}, state) };
76
+ };
@@ -38,16 +38,33 @@ const extractToken = request => {
38
38
  * 与 fastify.account.authenticate 同形的认证中间件:
39
39
  * 填充 request.user(统一结构)以及兼容字段 request.userInfo / request.authenticatePayload / request.tenantUserInfo
40
40
  */
41
- module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, translator }) => {
41
+ module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, serviceClient, tenantSync, translator }) => {
42
42
  const { runtime } = options;
43
43
  const account = () => fastify[options.accountNamespace];
44
- const tenant = () => fastify[options.tenantNamespace];
44
+ const tenant = () => options.getTenant();
45
+ const independent = runtime.tenantRole === 'independent';
45
46
 
46
47
  const tenantSource = () => {
47
48
  if (options.tenantSource) {
48
49
  return options.tenantSource;
49
50
  }
50
- return runtime.idpEnabled && tenant() ? 'local' : 'claims';
51
+ if (runtime.tenantRole === 'client') {
52
+ return 'remote';
53
+ }
54
+ return (runtime.idpEnabled || independent) && tenant() ? 'local' : 'claims';
55
+ };
56
+
57
+ // independent:token 里是宿主租户,换成本地托管租户;当前租户交给本地 fastify-tenant 的默认租户决定
58
+ const resolveIndependentTenant = async normalized => {
59
+ normalized.hostTenantId = normalized.tenantId;
60
+ normalized.tenantId = null;
61
+ if (normalized.hostTenantId) {
62
+ try {
63
+ normalized.localTenantId = await tenantSync.ensureFresh(normalized.hostTenantId);
64
+ } catch (err) {
65
+ fastify.log.warn({ err, hostTenantId: normalized.hostTenantId }, 'fastify-oidc: 解析宿主租户对应的本地租户失败');
66
+ }
67
+ }
51
68
  };
52
69
 
53
70
  const getRequestUrl = request => (options.getRequestUrl ? options.getRequestUrl(request) : `${runtime.origin}${request.raw.url}`);
@@ -114,12 +131,27 @@ module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, se
114
131
  if (normalized.isClient) {
115
132
  throw createError(Unauthorized, 'userTokenRequired');
116
133
  }
134
+ if (independent) {
135
+ await resolveIndependentTenant(normalized);
136
+ }
117
137
  request.user = normalized;
118
138
  request.authenticatePayload = { id: normalized.userId, tenantId: normalized.tenantId };
119
139
  request.userInfo = await resolveUserInfo(normalized.userId);
120
140
  request.appName = request.headers['x-app-name'];
121
141
  };
122
142
 
143
+ const getIndependentTenantUser = async currentUser => {
144
+ const { services } = tenant();
145
+ try {
146
+ return await services.user.getTenantUserInfo({ id: currentUser.userId });
147
+ } catch (e) {
148
+ if (!currentUser.localTenantId) {
149
+ throw e;
150
+ }
151
+ return services.user.getTenantUserInfo({ id: currentUser.userId, tenantId: currentUser.localTenantId });
152
+ }
153
+ };
154
+
123
155
  const buildTenantUserFromClaims = currentUser => ({
124
156
  id: currentUser.tenantUserId,
125
157
  tenantId: currentUser.tenantId,
@@ -143,6 +175,12 @@ module.exports = ({ fastify, options, verifier, dpop, revocation, userMirror, se
143
175
  await tenant().authenticate.tenantUser(request);
144
176
  return;
145
177
  }
178
+ if (independent && !options.tenantSource) {
179
+ const info = await getIndependentTenantUser(request.user);
180
+ request[contextName] = info;
181
+ request.user.tenantId = info?.tenantId ? String(info.tenantId) : null;
182
+ return;
183
+ }
146
184
  if (!request.user.tenantId) {
147
185
  throw createError(Forbidden, 'tenantNotSelected');
148
186
  }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * client 子应用的租户门面:租户相关数据全部来自宿主服务接口,权限已去掉 apps:<code>: 前缀,租户已按是否开通本应用过滤
3
+ */
4
+ module.exports = ({ serviceClient }) => ({
5
+ getTenantUserInfo: ({ userId, tenantId }) => serviceClient.getTenantUser({ userId, tenantId }),
6
+ tenantList: ({ userId }) => serviceClient.getTenantList({ userId })
7
+ });
@@ -60,21 +60,38 @@ module.exports = ({ options, fetch = globalThis.fetch }) => {
60
60
  return data.access_token;
61
61
  };
62
62
 
63
- const callService = async (path, query) => {
64
- const token = await getServiceToken();
63
+ // 每个接口只申请自己需要的 scope:宿主未升级(服务接口资源没有新 scope)时,旧接口仍可用
64
+ const callService = async (path, { query, method = 'GET', body, scope } = {}) => {
65
+ const token = await getServiceToken(scope ? { scope } : undefined);
65
66
  const url = new URL(`${runtime.idpApiBase}${path}`);
66
- Object.entries(query || {}).forEach(([key, value]) => value !== undefined && url.searchParams.set(key, value));
67
- const response = await fetch(url, { headers: { authorization: `Bearer ${token}` } });
67
+ Object.entries(query || {}).forEach(([key, value]) => value !== undefined && value !== null && url.searchParams.set(key, value));
68
+ const headers = { authorization: `Bearer ${token}` };
69
+ if (body !== undefined) {
70
+ headers['content-type'] = 'application/json';
71
+ }
72
+ const response = await fetch(url, { method, headers, body: body !== undefined ? JSON.stringify(body) : undefined });
68
73
  const data = await response.json().catch(() => null);
69
74
  if (!response.ok) {
70
- throw createError(null, 'idpServiceCallFailed', { path, status: String(response.status), reason: data?.message || '' });
75
+ const error = createError(null, 'idpServiceCallFailed', { path, status: String(response.status), reason: data?.message || '' });
76
+ error.upstreamStatus = response.status;
77
+ throw error;
71
78
  }
72
79
  return data && Object.prototype.hasOwnProperty.call(data, 'data') && Object.prototype.hasOwnProperty.call(data, 'code') ? data.data : data;
73
80
  };
74
81
 
75
- const getUserProfile = async userId => callService('/service/user', { id: userId });
82
+ const appCode = () => runtime.app?.code;
83
+
84
+ const getUserProfile = async userId => callService('/service/user', { query: { id: userId }, scope: 'user:read' });
85
+
86
+ const getTenantUser = async ({ userId, tenantId }) => callService('/service/tenant-user', { query: { userId, tenantId, app: appCode() }, scope: 'tenant:read' });
87
+
88
+ const getTenantList = async ({ userId }) => callService('/service/tenant-list', { query: { userId, app: appCode() }, scope: 'tenant:read' });
89
+
90
+ const registerApp = async body => callService('/service/app/register', { method: 'POST', body, scope: 'app:register' });
91
+
92
+ const getTenantSnapshot = async ({ tenantId }) => callService('/service/tenant-snapshot', { query: { tenantId, app: appCode() }, scope: 'tenant:sync' });
76
93
 
77
- const getTenantUser = async ({ userId, tenantId }) => callService('/service/tenant-user', { userId, tenantId });
94
+ const getTenantMembers = async ({ tenantId, currentPage, perPage }) => callService('/service/tenant-members', { query: { tenantId, app: appCode(), currentPage, perPage }, scope: 'tenant:sync' });
78
95
 
79
96
  const exchangeToken = async ({ subjectToken, resource, scope }) => {
80
97
  assertEnabled();
@@ -87,5 +104,5 @@ module.exports = ({ options, fetch = globalThis.fetch }) => {
87
104
  });
88
105
  };
89
106
 
90
- return { enabled, getServiceToken, getUserProfile, getTenantUser, exchangeToken };
107
+ return { enabled, getServiceToken, callService, getUserProfile, getTenantUser, getTenantList, registerApp, getTenantSnapshot, getTenantMembers, exchangeToken };
91
108
  };