@kne/fastify-oidc 0.1.9 → 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.
@@ -0,0 +1,133 @@
1
+ const fp = require('fastify-plugin');
2
+ const crypto = require('node:crypto');
3
+ const { SignJWT, importJWK } = require('jose');
4
+ const { TENANT_SYNC_EVENT } = require('../utils/app-permissions');
5
+
6
+ const NOTIFY_TYPES = ['tenant', 'tenant-permission'];
7
+
8
+ /**
9
+ * 宿主订阅 fastify-tenant 变更,通知 independent 子应用回拉租户快照。
10
+ * 导入 / 同步成员时每个成员都会触发一次事件,按租户防抖合并;推送尽力而为,失败由子应用过期拉取兜底
11
+ */
12
+ module.exports = fp(async (fastify, options) => {
13
+ const { services } = fastify[options.name];
14
+ if (options.runtime.tenantRole !== 'host') {
15
+ return;
16
+ }
17
+ const pending = new Map();
18
+ const running = new Set();
19
+ let unsubscribe = null;
20
+
21
+ const track = promise => {
22
+ running.add(promise);
23
+ promise.finally(() => running.delete(promise));
24
+ return promise;
25
+ };
26
+
27
+ const signToken = async ({ app, tenantId }) => {
28
+ const { keys } = await services.key.getPrivateJwks();
29
+ const jwk = keys[0];
30
+ return new SignJWT({ tenant_id: String(tenantId), events: { [TENANT_SYNC_EVENT]: {} } })
31
+ .setProtectedHeader({ alg: jwk.alg, kid: jwk.kid, typ: 'tenant-sync+jwt' })
32
+ .setIssuer(options.runtime.issuer)
33
+ .setAudience(app.serviceClientId)
34
+ .setIssuedAt()
35
+ .setExpirationTime(`${options.tenantSyncTokenTTL}s`)
36
+ .setJti(crypto.randomUUID())
37
+ .sign(await importJWK(jwk, jwk.alg));
38
+ };
39
+
40
+ const pushTo = async ({ app, tenantId }) => {
41
+ const response = await fetch(app.tenantSyncUri, {
42
+ method: 'POST',
43
+ headers: { 'content-type': 'application/json' },
44
+ body: JSON.stringify({ tenant_sync_token: await signToken({ app, tenantId }) }),
45
+ signal: AbortSignal.timeout(options.tenantSyncTimeout)
46
+ });
47
+ if (!response.ok) {
48
+ throw new Error(`tenant-sync 通知返回 ${response.status}`);
49
+ }
50
+ };
51
+
52
+ // 租户状态或租户权限变化时可能是刚关闭了应用,未开通也要通知子应用把托管租户置为 closed
53
+ const push = async (tenantId, types = new Set(NOTIFY_TYPES)) => {
54
+ const apps = services.app.listOpen().filter(app => app.tenantMode === 'independent' && app.tenantSyncUri);
55
+ if (!apps.length) {
56
+ return;
57
+ }
58
+ const { identity } = fastify[options.name].idp;
59
+ const mayHaveClosed = NOTIFY_TYPES.some(type => types.has(type));
60
+ for (const app of apps) {
61
+ try {
62
+ if (!mayHaveClosed && !(await identity.isAppEnabled(tenantId, app.code))) {
63
+ continue;
64
+ }
65
+ await pushTo({ app, tenantId });
66
+ } catch (err) {
67
+ fastify.log.warn({ err, tenantId, app: app.code }, 'fastify-oidc: 推送租户变更通知失败');
68
+ }
69
+ }
70
+ };
71
+
72
+ // 应用被停用 / 启用 / 删除:通知开通过它的租户(租户权限里仍有 apps:<code>),子应用回拉后关闭或恢复托管租户
73
+ const notifyApp = app => track(notifyAppTenants(app));
74
+
75
+ const notifyAppTenants = async app => {
76
+ const tenant = options.getTenant();
77
+ if (!tenant || app.tenantMode !== 'independent' || !app.tenantSyncUri) {
78
+ return;
79
+ }
80
+ const { identity } = fastify[options.name].idp;
81
+ const rows = await tenant.models.tenant.findAll({ attributes: ['id'] });
82
+ for (const { id } of rows) {
83
+ const tenantId = String(id);
84
+ try {
85
+ if (await identity.isAppEnabled(tenantId, app.code)) {
86
+ await pushTo({ app, tenantId });
87
+ }
88
+ } catch (err) {
89
+ fastify.log.warn({ err, tenantId, app: app.code }, 'fastify-oidc: 推送应用状态变化通知失败');
90
+ }
91
+ }
92
+ };
93
+
94
+ const schedule = ({ tenantId, type } = {}) => {
95
+ if (!tenantId) {
96
+ return;
97
+ }
98
+ const key = String(tenantId);
99
+ const entry = pending.get(key) || { types: new Set() };
100
+ entry.types.add(type);
101
+ clearTimeout(entry.timer);
102
+ entry.timer = setTimeout(() => {
103
+ pending.delete(key);
104
+ track(push(key, entry.types));
105
+ }, options.tenantSyncDebounce);
106
+ entry.timer.unref?.();
107
+ pending.set(key, entry);
108
+ };
109
+
110
+ const start = () => {
111
+ const tenant = options.getTenant();
112
+ if (!unsubscribe && tenant && typeof tenant.onChange === 'function') {
113
+ unsubscribe = tenant.onChange(schedule);
114
+ }
115
+ };
116
+
117
+ const stop = () => {
118
+ pending.forEach(entry => clearTimeout(entry.timer));
119
+ pending.clear();
120
+ unsubscribe?.();
121
+ unsubscribe = null;
122
+ };
123
+
124
+ // 进行中的推送会让子应用回调宿主,关闭前等它们结束,避免宿主 close 挂起
125
+ const whenIdle = () => Promise.allSettled([...running]);
126
+
127
+ fastify.addHook('onClose', async () => {
128
+ stop();
129
+ await whenIdle();
130
+ });
131
+
132
+ services.tenantPush = { start, stop, schedule, push, notifyApp, whenIdle, signToken };
133
+ });
@@ -0,0 +1,52 @@
1
+ const crypto = require('node:crypto');
2
+
3
+ const TENANT_SYNC_EVENT = 'urn:kne:oidc:tenant-sync';
4
+
5
+ /**
6
+ * 子应用权限在宿主侧统一挂在 `${prefix}:<appCode>:` 之下,模块 code `${prefix}:<appCode>` 即租户是否开通该应用的开关
7
+ */
8
+ const appModuleCode = (prefix, appCode) => `${prefix}:${appCode}`;
9
+
10
+ const scopePermissions = (permissions, appCode, prefix) => {
11
+ const head = `${appModuleCode(prefix, appCode)}:`;
12
+ return [...new Set((permissions || []).filter(code => typeof code === 'string' && code.startsWith(head)).map(code => code.slice(head.length)))];
13
+ };
14
+
15
+ const isAppEnabledIn = (permissions, appCode, prefix) => (permissions || []).includes(appModuleCode(prefix, appCode));
16
+
17
+ const wrapAppTree = ({ prefix, centerName, app }) => ({
18
+ modules: [
19
+ {
20
+ code: prefix,
21
+ name: centerName,
22
+ index: -2,
23
+ modules: [
24
+ {
25
+ code: app.code,
26
+ name: app.name || app.code,
27
+ modules: app.permissions?.modules || [],
28
+ permissions: app.permissions?.permissions || []
29
+ }
30
+ ]
31
+ }
32
+ ]
33
+ });
34
+
35
+ const countPermissions = tree => {
36
+ let count = 0;
37
+ const walk = modules =>
38
+ (modules || []).forEach(module => {
39
+ count += (module.permissions || []).length;
40
+ walk(module.modules);
41
+ });
42
+ walk(tree?.modules);
43
+ return count + (tree?.permissions || []).length;
44
+ };
45
+
46
+ const hashPermissions = tree =>
47
+ crypto
48
+ .createHash('sha256')
49
+ .update(JSON.stringify(tree || {}))
50
+ .digest('hex');
51
+
52
+ module.exports = { TENANT_SYNC_EVENT, appModuleCode, scopePermissions, isAppEnabledIn, wrapAppTree, countPermissions, hashPermissions };
@@ -23,6 +23,32 @@ const claimNames = namespace => ({
23
23
  clientToken: `${namespace}client_token`
24
24
  });
25
25
 
26
+ const TENANT_MODES = ['client', 'independent'];
27
+
28
+ // 子应用配置:code 会拼进宿主权限 code(apps:<code>:...),不能含冒号
29
+ const resolveApp = (options, { idpEnabled, origin }) => {
30
+ if (!options.app) {
31
+ return null;
32
+ }
33
+ if (idpEnabled) {
34
+ throw new Error('fastify-oidc: app 只用于 central 模式的子应用');
35
+ }
36
+ const app = Object.assign({ tenantMode: 'client' }, options.app);
37
+ if (!app.code || !/^[A-Za-z0-9_-]+$/.test(app.code)) {
38
+ throw new Error('fastify-oidc: app.code 必填,只能包含字母、数字、下划线和中划线');
39
+ }
40
+ if (!TENANT_MODES.includes(app.tenantMode)) {
41
+ throw new Error(`fastify-oidc: app.tenantMode 只能是 ${TENANT_MODES.join(' / ')},当前为 ${app.tenantMode}`);
42
+ }
43
+ if (app.tenantMode === 'independent' && !options.tenant) {
44
+ throw new Error('fastify-oidc: independent 模式需要通过 tenant 选项传入本地 fastify-tenant');
45
+ }
46
+ if (app.tenantMode === 'independent' && !app.tenantSyncUri) {
47
+ app.tenantSyncUri = `${origin}${options.prefix}/tenant-sync`;
48
+ }
49
+ return app;
50
+ };
51
+
26
52
  /**
27
53
  * 根据 mode / ORIGIN / issuer 推导运行期配置,结果挂在 options 上供各模块读取
28
54
  */
@@ -47,9 +73,13 @@ module.exports = options => {
47
73
  }
48
74
 
49
75
  const claimNamespace = options.claimNamespace || `${idpEnabled ? origin : issuerUrl.origin}/`;
76
+ const app = resolveApp(options, { idpEnabled, origin });
50
77
 
51
78
  return {
52
79
  idpEnabled,
80
+ // host: 宿主显式传入 fastify-tenant,开启应用中心;client / independent: 子应用租户模式
81
+ tenantRole: idpEnabled ? (options.tenant ? 'host' : 'none') : app ? app.tenantMode : 'none',
82
+ app,
53
83
  origin,
54
84
  issuer,
55
85
  issuerOrigin: issuerUrl.origin,
@@ -0,0 +1,34 @@
1
+ const COMPANY_FIELDS = ['name', 'fullName', 'logo', 'industry', 'scale', 'address', 'phone', 'email', 'foundedDate', 'companyTags', 'website', 'description', 'banners', 'teamDescription', 'developmentHistory', 'contact'];
2
+
3
+ const isFileId = value => typeof value === 'string' && value !== '';
4
+
5
+ /**
6
+ * 租户快照里引用宿主文件库的图片:租户 logo、公司 logo / banner / 团队头像 / 发展历程图片。
7
+ * mapper 收到宿主文件 id,返回替换后的值
8
+ */
9
+ const mapTenantImages = (tenant, mapper) => {
10
+ const map = value => (isFileId(value) ? mapper(value) : value);
11
+ const mapList = list => (Array.isArray(list) ? list.map(map) : list);
12
+ const result = Object.assign({}, tenant);
13
+ if ('logo' in tenant) {
14
+ result.logo = map(tenant.logo);
15
+ }
16
+ const { company } = tenant;
17
+ if (company) {
18
+ result.company = Object.assign({}, company, {
19
+ logo: map(company.logo),
20
+ banners: mapList(company.banners),
21
+ teamDescription: Array.isArray(company.teamDescription) ? company.teamDescription.map(item => (item ? Object.assign({}, item, { avatar: map(item.avatar) }) : item)) : company.teamDescription,
22
+ developmentHistory: Array.isArray(company.developmentHistory) ? company.developmentHistory.map(item => (item ? Object.assign({}, item, { images: mapList(item.images) }) : item)) : company.developmentHistory
23
+ });
24
+ }
25
+ return result;
26
+ };
27
+
28
+ const collectTenantImages = tenant => {
29
+ const ids = new Set();
30
+ mapTenantImages(tenant, id => ids.add(id) && id);
31
+ return [...ids];
32
+ };
33
+
34
+ module.exports = { COMPANY_FIELDS, mapTenantImages, collectTenantImages };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kne/fastify-oidc",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "基于 oidc-provider 的 Fastify OIDC 认证插件,支持 standalone / central 多项目单点登录、租户与跨项目令牌",
5
5
  "main": "index.js",
6
6
  "scripts": {