@kne/fastify-oidc 0.1.8 → 0.1.10

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.
@@ -2,8 +2,9 @@ const fp = require('fastify-plugin');
2
2
  const httpErrors = require('http-errors');
3
3
  const { pick } = require('lodash');
4
4
  const { createError } = require('../utils/intl');
5
+ const { collectTenantImages } = require('../utils/tenant-images');
5
6
 
6
- const { NotFound } = httpErrors;
7
+ const { NotFound, Forbidden } = httpErrors;
7
8
 
8
9
  const PROFILE_FIELDS = ['id', 'nickname', 'avatar', 'email', 'phone', 'gender', 'birthday', 'description', 'status'];
9
10
 
@@ -14,11 +15,39 @@ module.exports = fp(async (fastify, options) => {
14
15
  if (!options.runtime.idpEnabled) {
15
16
  return;
16
17
  }
17
- const { authenticate, translator } = fastify[options.name];
18
+ const { authenticate, translator, services } = fastify[options.name];
18
19
  const { wrap } = translator;
19
20
  const getIdp = () => fastify[options.name].idp;
20
21
  const tags = ['OIDC 服务接口'];
21
22
 
23
+ // 头像、租户 logo 是主项目文件库的 id,子项目无法解析,额外给出可直接下载的地址
24
+ const resolveFileUrl = async fileId => {
25
+ if (!fileId) {
26
+ return null;
27
+ }
28
+ if (/^https?:\/\//.test(fileId)) {
29
+ return fileId;
30
+ }
31
+ const getFileUrl = fastify[options.fileNamespace]?.services?.getFileUrl;
32
+ if (typeof getFileUrl !== 'function') {
33
+ return null;
34
+ }
35
+ try {
36
+ const url = await getFileUrl({ id: fileId });
37
+ return url ? new URL(url, options.runtime.origin).href : null;
38
+ } catch (e) {
39
+ fastify.log.warn({ err: e, fileId }, 'fastify-oidc: 解析主项目文件地址失败');
40
+ return null;
41
+ }
42
+ };
43
+
44
+ // { 宿主文件 id: 可下载地址 },解析不到的不返回
45
+ const resolveFileUrls = async fileIds => {
46
+ const ids = [...new Set(fileIds.filter(Boolean))];
47
+ const urls = await Promise.all(ids.map(resolveFileUrl));
48
+ return Object.fromEntries(ids.map((id, index) => [id, urls[index]]).filter(([, url]) => url));
49
+ };
50
+
22
51
  fastify.get(
23
52
  `${options.prefix}/service/user`,
24
53
  {
@@ -31,10 +60,37 @@ module.exports = fp(async (fastify, options) => {
31
60
  if (!user) {
32
61
  throw createError(NotFound, 'userNotFound');
33
62
  }
34
- return Object.assign(pick(user, PROFILE_FIELDS), { id: String(user.id), isSuperAdmin: await identity.isSuperAdmin(user.id) });
63
+ return Object.assign(pick(user, PROFILE_FIELDS), {
64
+ id: String(user.id),
65
+ avatarUrl: await resolveFileUrl(user.avatar),
66
+ isSuperAdmin: await identity.isSuperAdmin(user.id)
67
+ });
35
68
  })
36
69
  );
37
70
 
71
+ const assertTenantEnabled = () => {
72
+ if (!getIdp().identity.tenantEnabled()) {
73
+ throw createError(NotFound, 'tenantNotEnabled');
74
+ }
75
+ };
76
+
77
+ // 只能以注册该应用的服务 client 身份读取应用相关数据
78
+ const resolveApp = async (request, code) => {
79
+ if (!code) {
80
+ return null;
81
+ }
82
+ const app = await services.app.getByCode(code);
83
+ if (!app) {
84
+ throw createError(NotFound, 'appNotFound');
85
+ }
86
+ if (app.serviceClientId !== request.user.clientId) {
87
+ throw createError(Forbidden, 'appClientMismatch', { code });
88
+ }
89
+ return app;
90
+ };
91
+
92
+ const appQuery = { app: { type: 'string', description: '子应用 code,传入后只返回已开通该应用的数据,权限去掉 apps:<code>: 前缀' } };
93
+
38
94
  fastify.get(
39
95
  `${options.prefix}/service/tenant-user`,
40
96
  {
@@ -42,19 +98,111 @@ module.exports = fp(async (fastify, options) => {
42
98
  schema: {
43
99
  tags,
44
100
  summary: '获取用户在租户内的身份、角色与权限',
45
- query: { type: 'object', required: ['userId', 'tenantId'], properties: { userId: { type: 'string' }, tenantId: { type: 'string' } } }
101
+ query: { type: 'object', required: ['userId', 'tenantId'], properties: Object.assign({ userId: { type: 'string' }, tenantId: { type: 'string' } }, appQuery) }
46
102
  }
47
103
  },
48
104
  wrap(async request => {
49
- const tenant = fastify[options.tenantNamespace];
50
- if (!tenant) {
51
- throw createError(NotFound, 'tenantNotEnabled');
52
- }
105
+ assertTenantEnabled();
53
106
  const { userId, tenantId } = request.query;
54
- if (!(await getIdp().identity.isTenantMember(userId, tenantId))) {
55
- throw createError(NotFound, 'tenantMemberNotFound');
107
+ const app = await resolveApp(request, request.query.app);
108
+ const { identity } = getIdp();
109
+ if (app && app.status !== 'open') {
110
+ throw createError(NotFound, 'appNotEnabled');
111
+ }
112
+ if (!(await identity.isTenantMember(userId, tenantId, { appCode: app?.code }))) {
113
+ throw createError(NotFound, app ? 'appNotEnabled' : 'tenantMemberNotFound');
114
+ }
115
+ return identity.getTenantUserInfo({ accountId: userId, tenantId, appCode: app?.code });
116
+ })
117
+ );
118
+
119
+ fastify.get(
120
+ `${options.prefix}/service/tenant-list`,
121
+ {
122
+ onRequest: [authenticate.client('tenant:read')],
123
+ schema: { tags, summary: '用户可用租户列表', query: { type: 'object', required: ['userId'], properties: Object.assign({ userId: { type: 'string' } }, appQuery) } }
124
+ },
125
+ wrap(async request => {
126
+ assertTenantEnabled();
127
+ const app = await resolveApp(request, request.query.app);
128
+ if (app && app.status !== 'open') {
129
+ return { list: [], defaultTenantId: null };
130
+ }
131
+ return getIdp().identity.listTenants(request.query.userId, { appCode: app?.code });
132
+ })
133
+ );
134
+
135
+ fastify.post(
136
+ `${options.prefix}/service/app/register`,
137
+ {
138
+ onRequest: [authenticate.client('app:register')],
139
+ schema: {
140
+ tags,
141
+ summary: '子应用注册权限树到应用中心',
142
+ body: {
143
+ type: 'object',
144
+ required: ['code'],
145
+ properties: {
146
+ code: { type: 'string' },
147
+ name: { type: 'string' },
148
+ description: { type: 'string' },
149
+ tenantMode: { type: 'string', enum: ['client', 'independent'] },
150
+ clientId: { type: 'string' },
151
+ resource: { type: 'string' },
152
+ permissions: { type: 'object', additionalProperties: true },
153
+ tenantSyncUri: { type: 'string' }
154
+ }
155
+ }
156
+ }
157
+ },
158
+ wrap(async request => services.app.register(Object.assign({}, request.body, { serviceClientId: request.user.clientId })))
159
+ );
160
+
161
+ fastify.get(
162
+ `${options.prefix}/service/tenant-snapshot`,
163
+ {
164
+ onRequest: [authenticate.client('tenant:sync')],
165
+ schema: {
166
+ tags,
167
+ summary: '租户快照(基本信息、租户权限、角色、组织),供 independent 子应用接管',
168
+ query: { type: 'object', required: ['tenantId', 'app'], properties: Object.assign({ tenantId: { type: 'string' } }, appQuery) }
169
+ }
170
+ },
171
+ wrap(async request => {
172
+ assertTenantEnabled();
173
+ const app = await resolveApp(request, request.query.app);
174
+ const snapshot = await getIdp().identity.getTenantSnapshot({ tenantId: request.query.tenantId, appCode: app.code, appOpen: app.status === 'open' });
175
+ if (!snapshot.removed) {
176
+ snapshot.fileUrls = await resolveFileUrls(collectTenantImages(snapshot.tenant));
177
+ }
178
+ return snapshot;
179
+ })
180
+ );
181
+
182
+ fastify.get(
183
+ `${options.prefix}/service/tenant-members`,
184
+ {
185
+ onRequest: [authenticate.client('tenant:sync')],
186
+ schema: {
187
+ tags,
188
+ summary: '租户成员分页(含角色 code 与所属组织),供 independent 子应用接管',
189
+ query: {
190
+ type: 'object',
191
+ required: ['tenantId', 'app'],
192
+ properties: Object.assign({ tenantId: { type: 'string' }, currentPage: { type: 'number', default: 1 }, perPage: { type: 'number', default: 200, maximum: 1000 } }, appQuery)
193
+ }
194
+ }
195
+ },
196
+ wrap(async request => {
197
+ assertTenantEnabled();
198
+ const app = await resolveApp(request, request.query.app);
199
+ const { identity } = getIdp();
200
+ const { tenantId, currentPage, perPage } = request.query;
201
+ if (app.status !== 'open' || !(await identity.isAppEnabled(tenantId, app.code))) {
202
+ return { pageData: [], totalCount: 0 };
56
203
  }
57
- return tenant.services.user.getTenantUserInfo({ id: userId, tenantId });
204
+ const result = await identity.listTenantMembers({ tenantId, currentPage, perPage });
205
+ return Object.assign(result, { fileUrls: await resolveFileUrls(result.pageData.map(member => member.avatar)) });
58
206
  })
59
207
  );
60
208
  });
@@ -0,0 +1,31 @@
1
+ const fp = require('fastify-plugin');
2
+
3
+ /**
4
+ * 宿主租户端:当前租户已开通且启用的子应用。当前租户与 fastify-tenant 的 tenantUser 一致(token 中的租户,否则默认租户)
5
+ */
6
+ module.exports = fp(async (fastify, options) => {
7
+ if (options.runtime.tenantRole !== 'host') {
8
+ return;
9
+ }
10
+ const { authenticate, translator, services } = fastify[options.name];
11
+ const { wrap } = translator;
12
+ const resolveTenantUser = request => options.getTenant().authenticate.tenantUser(request);
13
+
14
+ fastify.get(
15
+ `${options.prefix}/tenant/apps`,
16
+ {
17
+ onRequest: [authenticate.user, resolveTenantUser],
18
+ schema: { tags: ['OIDC 应用中心'], summary: '当前租户已开通的子应用' }
19
+ },
20
+ wrap(async request => {
21
+ const tenantId = request[options.tenantUserContextName]?.tenantId;
22
+ if (!tenantId) {
23
+ return [];
24
+ }
25
+ const { identity } = fastify[options.name].idp;
26
+ const apps = services.app.listOpen();
27
+ const enabled = await Promise.all(apps.map(app => identity.isAppEnabled(String(tenantId), app.code)));
28
+ return apps.filter((app, index) => enabled[index]).map(({ code, name, description, tenantMode }) => ({ code, name, description, tenantMode }));
29
+ })
30
+ );
31
+ });
@@ -0,0 +1,64 @@
1
+ const fp = require('fastify-plugin');
2
+
3
+ const FORWARD_HEADERS = ['content-type', 'accept', 'accept-language', 'x-app-name'];
4
+
5
+ /**
6
+ * client 子应用的 /api/tenant 代理:getUserInfo、available-list 走服务接口(权限已去前缀、租户已按应用过滤),
7
+ * 其余请求以 token exchange 换成宿主 API 的令牌后转发给宿主 fastify-tenant。只转发 JSON 请求
8
+ */
9
+ module.exports = fp(async (fastify, options) => {
10
+ if (options.runtime.tenantRole !== 'client' || !options.tenantProxy) {
11
+ return;
12
+ }
13
+ const { runtime } = options;
14
+ const { authenticate, serviceClient } = fastify[options.name];
15
+ const proxy = Object.assign({ prefix: '/api/tenant', resource: `${runtime.issuerOrigin}/api`, target: null }, options.tenantProxy === true ? {} : options.tenantProxy);
16
+ const target = proxy.target || `${runtime.issuerOrigin}${proxy.prefix}`;
17
+ const exchanged = new Map();
18
+
19
+ const getHostToken = async subjectToken => {
20
+ const now = Date.now();
21
+ exchanged.forEach((item, key) => item.expiresAt <= now && exchanged.delete(key));
22
+ const cached = exchanged.get(subjectToken);
23
+ if (cached && cached.expiresAt - 30 * 1000 > now) {
24
+ return cached.accessToken;
25
+ }
26
+ const data = await serviceClient.exchangeToken({ subjectToken, resource: proxy.resource });
27
+ exchanged.set(subjectToken, { accessToken: data.access_token, expiresAt: now + data.expires_in * 1000 });
28
+ return data.access_token;
29
+ };
30
+
31
+ // 与 fastify-tenant available-list 同形,前端无需区分
32
+ const toTenantList = ({ list = [], defaultTenantId = null }) => ({
33
+ list: list.map(item => ({
34
+ id: item.tenantUserId,
35
+ tenantId: item.tenantId,
36
+ status: 'open',
37
+ tenant: { id: item.tenantId, name: item.name, logo: item.logo, status: 'open', company: item.companyName ? { name: item.companyName } : null }
38
+ })),
39
+ defaultTenantId
40
+ });
41
+
42
+ fastify.get(`${proxy.prefix}/getUserInfo`, { onRequest: [authenticate.user, authenticate.tenantUser] }, async request => {
43
+ const info = request[options.tenantUserContextName];
44
+ return { userInfo: request.userInfo, tenantUserInfo: info, company: info?.tenant?.tenantCompany || info?.tenant?.company || null, tenant: info?.tenant || null };
45
+ });
46
+
47
+ fastify.get(`${proxy.prefix}/available-list`, { onRequest: [authenticate.user] }, async request => toTenantList(await serviceClient.getTenantList({ userId: request.user.userId })));
48
+
49
+ fastify.all(`${proxy.prefix}/*`, { onRequest: [authenticate.user] }, async (request, reply) => {
50
+ const subjectToken = String(request.headers.authorization || '').replace(/^(bearer|dpop)\s+/i, '');
51
+ const headers = { authorization: `Bearer ${await getHostToken(subjectToken)}` };
52
+ FORWARD_HEADERS.forEach(name => request.headers[name] && (headers[name] = request.headers[name]));
53
+ const url = new URL(`${target}/${request.params['*']}`);
54
+ url.search = new URL(request.raw.url, 'http://localhost').search;
55
+ const hasBody = !['GET', 'HEAD'].includes(request.method) && request.body !== undefined;
56
+ const response = await fetch(url, { method: request.method, headers, body: hasBody ? JSON.stringify(request.body) : undefined });
57
+ reply.code(response.status);
58
+ const contentType = response.headers.get('content-type');
59
+ if (contentType) {
60
+ reply.header('content-type', contentType);
61
+ }
62
+ return reply.send(Buffer.from(await response.arrayBuffer()));
63
+ });
64
+ });
@@ -0,0 +1,59 @@
1
+ const fp = require('fastify-plugin');
2
+ const httpErrors = require('http-errors');
3
+ const { createError } = require('../utils/intl');
4
+
5
+ const { BadRequest } = httpErrors;
6
+
7
+ /**
8
+ * independent 子应用接收宿主的租户变更通知:验签 + jti 防重放后后台回拉快照,立即返回
9
+ */
10
+ module.exports = fp(async (fastify, options) => {
11
+ if (options.runtime.tenantRole !== 'independent') {
12
+ return;
13
+ }
14
+ const { verifier, tenantSync, translator } = fastify[options.name];
15
+ const usedJti = new Map();
16
+
17
+ const consumeJti = (jti, exp) => {
18
+ const now = Date.now();
19
+ usedJti.forEach((expiresAt, key) => expiresAt < now && usedJti.delete(key));
20
+ if (usedJti.has(jti)) {
21
+ return false;
22
+ }
23
+ usedJti.set(jti, exp * 1000 + options.clockTolerance * 1000);
24
+ return true;
25
+ };
26
+
27
+ fastify.register(async child => {
28
+ if (!child.hasContentTypeParser('application/x-www-form-urlencoded')) {
29
+ child.addContentTypeParser('application/x-www-form-urlencoded', { parseAs: 'string' }, (request, body, done) => {
30
+ done(null, Object.fromEntries(new URLSearchParams(body)));
31
+ });
32
+ }
33
+
34
+ child.post(
35
+ `${options.prefix}/tenant-sync`,
36
+ {
37
+ schema: {
38
+ tags: ['OIDC 服务接口'],
39
+ summary: '接收宿主租户变更通知(independent 子应用)',
40
+ body: { type: 'object', required: ['tenant_sync_token'], properties: { tenant_sync_token: { type: 'string' } } }
41
+ }
42
+ },
43
+ translator.wrap(async (request, reply) => {
44
+ let payload;
45
+ try {
46
+ payload = await verifier.verifyTenantSyncToken(request.body.tenant_sync_token, { audience: options.serviceClient.clientId });
47
+ } catch (e) {
48
+ throw createError(BadRequest, 'tenantSyncTokenInvalid');
49
+ }
50
+ if (!consumeJti(payload.jti, payload.exp)) {
51
+ throw createError(BadRequest, 'tenantSyncTokenReplayed');
52
+ }
53
+ tenantSync.syncInBackground(payload.tenant_id);
54
+ reply.header('cache-control', 'no-store');
55
+ return {};
56
+ })
57
+ );
58
+ });
59
+ });
@@ -3,8 +3,13 @@ const epochTime = date => Math.floor(date.getTime() / 1000);
3
3
  /**
4
4
  * 基于 fastify-sequelize 的 oidc-provider Adapter。
5
5
  * Client 不走这里,由 create-provider 中的 client adapter 从 client 表读取。
6
+ *
7
+ * 退出时 end_session 要先等 back-channel 通知完才销毁 Session,期间同一 cookie 的并发请求(如子应用 401 后静默登录)
8
+ * 已读到旧 Session,会在销毁后把它原样写回;这里记下已销毁的 Session id,拒绝写回与读取。
6
9
  */
7
- module.exports = ({ models }) => {
10
+ module.exports = ({ models, endedStore, sessionTTL = 0 }) => {
11
+ const endedKey = id => `session-ended:${id}`;
12
+ const isEnded = async (name, id) => name === 'Session' && !!endedStore && !!(await endedStore.get(endedKey(id)));
8
13
  const toPayload = row => {
9
14
  if (!row) {
10
15
  return undefined;
@@ -25,6 +30,9 @@ module.exports = ({ models }) => {
25
30
  }
26
31
 
27
32
  async upsert(id, payload, expiresIn) {
33
+ if (await isEnded(this.name, id)) {
34
+ return;
35
+ }
28
36
  const values = {
29
37
  payload,
30
38
  grantId: payload.grantId || null,
@@ -43,6 +51,9 @@ module.exports = ({ models }) => {
43
51
  }
44
52
 
45
53
  async find(id) {
54
+ if (await isEnded(this.name, id)) {
55
+ return undefined;
56
+ }
46
57
  return toPayload(await models.payload.findOne({ where: { modelName: this.name, payloadId: id } }));
47
58
  }
48
59
 
@@ -59,6 +70,13 @@ module.exports = ({ models }) => {
59
70
  }
60
71
 
61
72
  async destroy(id) {
73
+ if (this.name === 'Session' && endedStore) {
74
+ const row = await models.payload.findOne({ attributes: ['expiresAt'], where: { modelName: this.name, payloadId: id } });
75
+ const ttl = row?.expiresAt ? Math.ceil((row.expiresAt.getTime() - Date.now()) / 1000) : sessionTTL;
76
+ if (ttl > 0) {
77
+ await endedStore.set(endedKey(id), 1, ttl);
78
+ }
79
+ }
62
80
  await models.payload.destroy({ where: { modelName: this.name, payloadId: id } });
63
81
  }
64
82
 
@@ -68,21 +68,23 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
68
68
  const sessionUid = oidc.session.uid;
69
69
  const requested = oidc.params.tenant_id ? String(oidc.params.tenant_id) : null;
70
70
  const chosen = oidc.result?.tenant?.tenantId ? String(oidc.result.tenant.tenantId) : null;
71
+ // 子应用的 client 只考虑已开通该应用的租户
72
+ const scope = services.app.scopeOfClient(oidc.client.clientId);
71
73
  const select = async tenantId => {
72
74
  await services.sessionTenant.set({ sessionUid, accountId, tenantId });
73
75
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
74
76
  };
75
77
 
76
- if (chosen && (await identity.isTenantMember(accountId, chosen))) {
78
+ if (chosen && (await identity.isTenantMember(accountId, chosen, scope))) {
77
79
  return select(chosen);
78
80
  }
79
81
  const current = await services.sessionTenant.get({ sessionUid });
80
- const currentTenantId = current && current.accountId === String(accountId) && (await identity.isTenantMember(accountId, current.tenantId)) ? current.tenantId : null;
82
+ const currentTenantId = current && current.accountId === String(accountId) && (await identity.isTenantMember(accountId, current.tenantId, scope)) ? current.tenantId : null;
81
83
  if (requested) {
82
84
  if (requested === currentTenantId) {
83
85
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
84
86
  }
85
- if (await identity.isTenantMember(accountId, requested)) {
87
+ if (await identity.isTenantMember(accountId, requested, scope)) {
86
88
  return select(requested);
87
89
  }
88
90
  return interactionPolicy.Check.REQUEST_PROMPT;
@@ -90,7 +92,7 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
90
92
  if (currentTenantId) {
91
93
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
92
94
  }
93
- const { list } = await identity.listTenants(accountId);
95
+ const { list } = await identity.listTenants(accountId, scope);
94
96
  if (list.length === 0) {
95
97
  return interactionPolicy.Check.NO_NEED_TO_PROMPT;
96
98
  }
@@ -207,7 +209,8 @@ module.exports = async ({ fastify, options, identity, translator, jwks, getLocal
207
209
  if (!tenantId && token.sessionUid) {
208
210
  tenantId = (await services.sessionTenant.get({ sessionUid: token.sessionUid }))?.tenantId;
209
211
  }
210
- const tenantContext = await identity.getTenantContext({ accountId, tenantId });
212
+ // 资源属于子应用时:租户未开通该应用则不带租户 claims,权限只下发该应用的并去掉 apps:<code>: 前缀
213
+ const tenantContext = await identity.getTenantContext(Object.assign({ accountId, tenantId }, services.app.scopeOfResource(token.resourceServer?.identifier())));
211
214
  if (tenantContext) {
212
215
  extra[claims.tenantId] = tenantContext.tenantId;
213
216
  extra[claims.tenantUserId] = tenantContext.tenantUserId;
@@ -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
  };