@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.
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
  };
@@ -0,0 +1,171 @@
1
+ const { mapTenantImages } = require('../utils/tenant-images');
2
+
3
+ const FAILURE_RETRY_MS = 30 * 1000;
4
+ const FILE_SOURCE = 'oidcHostFileSource';
5
+
6
+ /**
7
+ * independent 子应用:回拉宿主租户快照与成员,写入本地 fastify-tenant 托管租户。
8
+ * 同一租户的同步串行执行,进行中再收到通知只标记一次重跑;过期拉取在后台进行,不阻塞请求
9
+ */
10
+ module.exports = ({ fastify, options, serviceClient, userMirror }) => {
11
+ const { runtime } = options;
12
+ const running = new Map();
13
+ const fresh = new Map();
14
+ const ttl = () => options.tenantSyncTTL * 1000;
15
+ const managed = () => options.getTenant().services.managed;
16
+ const fetchMembers = async tenantId => {
17
+ const members = [];
18
+ const fileUrls = {};
19
+ for (let currentPage = 1; ; currentPage++) {
20
+ const { pageData = [], totalCount = 0, fileUrls: pageFileUrls } = await serviceClient.getTenantMembers({ tenantId, currentPage, perPage: options.tenantSyncPageSize });
21
+ members.push(...pageData);
22
+ Object.assign(fileUrls, pageFileUrls);
23
+ if (!pageData.length || members.length >= totalCount) {
24
+ return { members, fileUrls };
25
+ }
26
+ }
27
+ };
28
+
29
+ // 成员关联的是镜像用户:先确保镜像存在;宿主租户内没有单独头像时用镜像用户已拷到本地的头像
30
+ const mirrorMembers = async members => {
31
+ for (const member of members) {
32
+ try {
33
+ const user = await userMirror.ensure(String(member.userId));
34
+ member.userAvatar = user.avatar || null;
35
+ } catch (err) {
36
+ member.userAvatar = null;
37
+ fastify.log.warn({ err, userId: member.userId }, 'fastify-oidc: 同步租户成员时创建镜像用户失败');
38
+ }
39
+ }
40
+ return members;
41
+ };
42
+
43
+ /**
44
+ * 宿主文件 id 在子应用无法解析:按宿主给出的地址拷到本地文件库,返回 { 宿主 id: 本地 id }。
45
+ * 上次同步的映射记在托管租户 options.managedBy.files,宿主文件不变且本地文件还在就不再下载;本地没有文件库时返回 null
46
+ */
47
+ const mirrorFiles = async (hostTenantId, fileUrls) => {
48
+ const files = fastify[options.fileNamespace]?.services;
49
+ if (typeof files?.uploadFromUrl !== 'function') {
50
+ return null;
51
+ }
52
+ const local = await managed().findByHostTenantId({ issuer: runtime.issuer, hostTenantId });
53
+ const previous = local?.options?.managedBy?.files || {};
54
+ const mapping = {};
55
+ for (const [source, url] of Object.entries(fileUrls)) {
56
+ const current = previous[source];
57
+ if (current && (await Promise.resolve(files.getFileInstance({ id: current })).catch(() => null))) {
58
+ mapping[source] = current;
59
+ continue;
60
+ }
61
+ try {
62
+ mapping[source] = String((await files.uploadFromUrl({ url, options: { [FILE_SOURCE]: source } })).id);
63
+ } catch (err) {
64
+ fastify.log.warn({ err, source }, 'fastify-oidc: 拷贝宿主租户图片失败');
65
+ }
66
+ }
67
+ return mapping;
68
+ };
69
+
70
+ const localizeFiles = async (hostTenantId, snapshot, members, memberFileUrls) => {
71
+ const mapping = await mirrorFiles(hostTenantId, Object.assign({}, snapshot.fileUrls, memberFileUrls));
72
+ const resolve = source => (mapping ? mapping[source] || null : source);
73
+ const { fileUrls, ...rest } = snapshot;
74
+ return {
75
+ snapshot: Object.assign(rest, { tenant: mapTenantImages(snapshot.tenant, resolve) }, mapping ? { files: mapping } : {}),
76
+ members: members.map(({ userAvatar, ...member }) => Object.assign(member, { avatar: (member.avatar && resolve(member.avatar)) || userAvatar }))
77
+ };
78
+ };
79
+
80
+ // 宿主已删除租户时快照只有 id:沿用本地托管租户名关闭它,本地没有则无需处理
81
+ const resolveRemoved = async (hostTenantId, snapshot) => {
82
+ const local = await managed().findByHostTenantId({ issuer: runtime.issuer, hostTenantId });
83
+ return local ? Object.assign({}, snapshot, { tenant: Object.assign({}, snapshot.tenant, { name: local.name }) }) : null;
84
+ };
85
+
86
+ const runOnce = async hostTenantId => {
87
+ let snapshot = await serviceClient.getTenantSnapshot({ tenantId: hostTenantId });
88
+ if (snapshot.removed) {
89
+ snapshot = await resolveRemoved(hostTenantId, snapshot);
90
+ if (!snapshot) {
91
+ fresh.set(hostTenantId, { tenantId: null, syncedAt: Date.now() });
92
+ return null;
93
+ }
94
+ }
95
+ const { members: hostMembers, fileUrls: memberFileUrls } = snapshot.enabled ? await fetchMembers(hostTenantId) : { members: [], fileUrls: {} };
96
+ const localized = await localizeFiles(hostTenantId, snapshot, await mirrorMembers(hostMembers), memberFileUrls);
97
+ const tenant = await managed().applySnapshot({ issuer: runtime.issuer, snapshot: Object.assign(localized.snapshot, { members: localized.members }) });
98
+ fresh.set(hostTenantId, { tenantId: tenant && snapshot.enabled ? String(tenant.id) : null, syncedAt: Date.now() });
99
+ return tenant;
100
+ };
101
+
102
+ const sync = hostTenantId => {
103
+ const key = String(hostTenantId);
104
+ const current = running.get(key);
105
+ if (current) {
106
+ current.rerun = true;
107
+ return current.promise;
108
+ }
109
+ const entry = { rerun: false };
110
+ entry.promise = (async () => {
111
+ try {
112
+ let result;
113
+ do {
114
+ entry.rerun = false;
115
+ result = await runOnce(key);
116
+ } while (entry.rerun);
117
+ return result;
118
+ } finally {
119
+ running.delete(key);
120
+ }
121
+ })();
122
+ running.set(key, entry);
123
+ return entry.promise;
124
+ };
125
+
126
+ const syncInBackground = key =>
127
+ sync(key).catch(err => {
128
+ fastify.log.warn({ err, hostTenantId: key }, 'fastify-oidc: 同步宿主租户失败');
129
+ return null;
130
+ });
131
+
132
+ /**
133
+ * 返回宿主租户对应的本地托管租户 id(未开通 / 拉取失败为 null)。
134
+ * 本地还没有时同步拉取;已过 tenantSyncTTL 时后台刷新,先用本地已有数据
135
+ */
136
+ const ensureFresh = async hostTenantId => {
137
+ const key = String(hostTenantId);
138
+ let cached = fresh.get(key);
139
+ if (!cached) {
140
+ const local = await managed().findByHostTenantId({ issuer: runtime.issuer, hostTenantId: key });
141
+ if (local) {
142
+ cached = { tenantId: local.status === 'open' ? String(local.id) : null, syncedAt: Date.parse(local.options?.managedBy?.syncedAt) || 0 };
143
+ fresh.set(key, cached);
144
+ }
145
+ }
146
+ if (!cached) {
147
+ try {
148
+ await sync(key);
149
+ return fresh.get(key)?.tenantId || null;
150
+ } catch (err) {
151
+ fastify.log.warn({ err, hostTenantId: key }, 'fastify-oidc: 首次同步宿主租户失败');
152
+ fresh.set(key, { tenantId: null, syncedAt: Date.now() - ttl() + FAILURE_RETRY_MS });
153
+ return null;
154
+ }
155
+ }
156
+ if (Date.now() - cached.syncedAt >= ttl() && !running.has(key)) {
157
+ cached.syncedAt = Date.now();
158
+ syncInBackground(key);
159
+ }
160
+ return cached.tenantId;
161
+ };
162
+
163
+ const whenIdle = async hostTenantId => {
164
+ const entry = running.get(String(hostTenantId));
165
+ return entry ? entry.promise.catch(() => null) : null;
166
+ };
167
+
168
+ const close = () => Promise.allSettled([...running.values()].map(entry => entry.promise));
169
+
170
+ return { sync, syncInBackground, ensureFresh, whenIdle, close };
171
+ };
@@ -3,6 +3,7 @@ const { pick } = require('lodash');
3
3
 
4
4
  const PROFILE_FIELDS = ['nickname', 'avatar', 'email', 'phone', 'gender', 'birthday', 'description'];
5
5
  const USER_FIELDS = ['id', ...PROFILE_FIELDS, 'status'];
6
+ const AVATAR_SOURCE = 'oidcAvatarSource';
6
7
 
7
8
  /**
8
9
  * central 模式:子项目保留 fastify-account 的用户表作为镜像,按 sub 即时创建 / 定期同步,
@@ -12,13 +13,50 @@ module.exports = ({ fastify, options, serviceClient }) => {
12
13
  const cache = new Map();
13
14
  const getModel = () => fastify[options.accountNamespace].models.user;
14
15
 
15
- const fetchProfile = async userId => {
16
+ // 主项目 avatar 是主项目文件库的 id:拷到本地文件库,镜像存本地文件 id;文件记录 options 记来源 id,主项目头像不变就不再下载
17
+ const syncAvatar = async (remote, current) => {
18
+ const files = fastify[options.fileNamespace]?.services;
19
+ if (typeof files?.uploadFromUrl !== 'function') {
20
+ return remote.avatar;
21
+ }
22
+ if (!remote.avatar) {
23
+ return null;
24
+ }
25
+ const mirrored = current ? await Promise.resolve(files.getFileInstance({ id: current })).catch(() => null) : null;
26
+ const mirroredSource = mirrored?.options?.[AVATAR_SOURCE];
27
+ if (mirroredSource && mirroredSource === remote.avatar) {
28
+ return current;
29
+ }
30
+ const fallback = mirroredSource ? current : null;
31
+ if (!remote.avatarUrl) {
32
+ return fallback;
33
+ }
34
+ try {
35
+ const file = await files.uploadFromUrl({
36
+ id: mirroredSource ? current : undefined,
37
+ url: remote.avatarUrl,
38
+ options: { [AVATAR_SOURCE]: remote.avatar }
39
+ });
40
+ return file.id;
41
+ } catch (e) {
42
+ fastify.log.warn({ err: e, avatar: remote.avatar }, 'fastify-oidc: 同步主项目用户头像失败');
43
+ return fallback;
44
+ }
45
+ };
46
+
47
+ const fetchProfile = async (userId, current) => {
16
48
  if (!serviceClient.enabled()) {
17
49
  return null;
18
50
  }
19
51
  try {
20
52
  const remote = await serviceClient.getUserProfile(userId);
21
53
  const profile = pick(remote, PROFILE_FIELDS);
54
+ const avatar = await syncAvatar(remote, current?.avatar);
55
+ if (avatar === undefined) {
56
+ delete profile.avatar;
57
+ } else {
58
+ profile.avatar = avatar;
59
+ }
22
60
  // 主项目超级管理员身份以主项目为准,升降级都同步到镜像,子项目 authenticate.admin 照常读本地 isSuperAdmin
23
61
  if (typeof remote?.isSuperAdmin === 'boolean' && getModel().rawAttributes.isSuperAdmin) {
24
62
  profile.isSuperAdmin = remote.isSuperAdmin;
@@ -72,7 +110,7 @@ module.exports = ({ fastify, options, serviceClient }) => {
72
110
  }
73
111
  const model = getModel();
74
112
  let row = await model.findByPk(userId);
75
- const profile = await fetchProfile(userId);
113
+ const profile = await fetchProfile(userId, row);
76
114
  if (!row) {
77
115
  row = await createMirror(userId, profile);
78
116
  } else if (profile) {
@@ -1,5 +1,6 @@
1
1
  const { jwtVerify, createRemoteJWKSet } = require('jose');
2
2
  const { createError } = require('../utils/intl');
3
+ const { TENANT_SYNC_EVENT } = require('../utils/app-permissions');
3
4
 
4
5
  const LOGOUT_EVENT = 'http://schemas.openid.net/event/backchannel-logout';
5
6
 
@@ -47,5 +48,19 @@ module.exports = ({ options, getLocalJWKS }) => {
47
48
  return payload;
48
49
  };
49
50
 
50
- return { verifyAccessToken, verifyLogoutToken };
51
+ const verifyTenantSyncToken = async (token, { audience }) => {
52
+ const { payload } = await jwtVerify(token, getJWKS(), {
53
+ issuer: runtime.issuer,
54
+ audience,
55
+ typ: 'tenant-sync+jwt',
56
+ clockTolerance: options.clockTolerance,
57
+ requiredClaims: ['jti', 'exp', 'tenant_id']
58
+ });
59
+ if (!payload.events || typeof payload.events[TENANT_SYNC_EVENT] !== 'object') {
60
+ throw createError(null, 'tenantSyncTokenInvalid');
61
+ }
62
+ return payload;
63
+ };
64
+
65
+ return { verifyAccessToken, verifyLogoutToken, verifyTenantSyncToken };
51
66
  };