@kne/fastify-oidc 0.0.0-stage → 0.1.0

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.
Files changed (38) hide show
  1. package/README.md +681 -2
  2. package/index.js +146 -0
  3. package/libs/controllers/admin.js +150 -0
  4. package/libs/controllers/backchannel.js +49 -0
  5. package/libs/controllers/interaction.js +87 -0
  6. package/libs/controllers/service.js +59 -0
  7. package/libs/idp/adapters/sequelize.js +82 -0
  8. package/libs/idp/create-provider.js +286 -0
  9. package/libs/idp/grant-helpers.js +31 -0
  10. package/libs/idp/grants/token-exchange.js +82 -0
  11. package/libs/idp/identity.js +108 -0
  12. package/libs/idp/index.js +123 -0
  13. package/libs/idp/mount.js +26 -0
  14. package/libs/locale/en-US.js +63 -0
  15. package/libs/locale/index.js +4 -0
  16. package/libs/locale/zh-CN.js +63 -0
  17. package/libs/models/client.js +43 -0
  18. package/libs/models/key.js +44 -0
  19. package/libs/models/payload.js +50 -0
  20. package/libs/models/resource-server.js +42 -0
  21. package/libs/models/session-tenant.js +26 -0
  22. package/libs/resource/authenticate.js +203 -0
  23. package/libs/resource/dpop.js +52 -0
  24. package/libs/resource/normalize-user.js +42 -0
  25. package/libs/resource/revocation.js +62 -0
  26. package/libs/resource/service-client.js +91 -0
  27. package/libs/resource/user-mirror.js +60 -0
  28. package/libs/resource/verify-token.js +51 -0
  29. package/libs/services/client.js +167 -0
  30. package/libs/services/grant.js +104 -0
  31. package/libs/services/interaction.js +118 -0
  32. package/libs/services/key.js +103 -0
  33. package/libs/services/resource-server.js +99 -0
  34. package/libs/services/session-tenant.js +32 -0
  35. package/libs/utils/crypto.js +25 -0
  36. package/libs/utils/intl.js +71 -0
  37. package/libs/utils/resolve-options.js +68 -0
  38. package/package.json +83 -4
@@ -0,0 +1,103 @@
1
+ const fp = require('fastify-plugin');
2
+ const crypto = require('node:crypto');
3
+ const { encrypt, decrypt } = require('../utils/crypto');
4
+
5
+ const STATUS_ORDER = { active: 0, next: 1, retired: 2 };
6
+
7
+ module.exports = fp(async (fastify, options) => {
8
+ const { models, services } = fastify[options.name];
9
+ if (!options.runtime.idpEnabled) {
10
+ return;
11
+ }
12
+ const { Op } = fastify.sequelize.Sequelize;
13
+ const secret = options.keyEncryptionSecret;
14
+
15
+ const generate = async ({ status, transaction }) => {
16
+ const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
17
+ const kid = crypto.randomUUID();
18
+ const alg = 'RS256';
19
+ const privateJwk = Object.assign(privateKey.export({ format: 'jwk' }), { kid, alg, use: 'sig' });
20
+ const publicJwk = Object.assign(publicKey.export({ format: 'jwk' }), { kid, alg, use: 'sig' });
21
+ return models.key.create(
22
+ {
23
+ kid,
24
+ alg,
25
+ status,
26
+ privateJwk: encrypt(secret, JSON.stringify(privateJwk)),
27
+ publicJwk,
28
+ activatedAt: status === 'active' ? new Date() : null
29
+ },
30
+ { transaction }
31
+ );
32
+ };
33
+
34
+ const pruneRetired = async ({ transaction } = {}) => {
35
+ await models.key.destroy({
36
+ where: {
37
+ status: 'retired',
38
+ retiredAt: { [Op.lt]: new Date(Date.now() - options.retiredKeyTTL * 1000) }
39
+ },
40
+ transaction
41
+ });
42
+ };
43
+
44
+ const ensureKeys = async () => {
45
+ await fastify.sequelize.instance.transaction(async transaction => {
46
+ if (!(await models.key.count({ where: { status: 'active' }, transaction }))) {
47
+ await generate({ status: 'active', transaction });
48
+ }
49
+ if (!(await models.key.count({ where: { status: 'next' }, transaction }))) {
50
+ await generate({ status: 'next', transaction });
51
+ }
52
+ });
53
+ };
54
+
55
+ const sortedKeys = async () => {
56
+ const list = await models.key.findAll();
57
+ return list.sort((a, b) => STATUS_ORDER[a.status] - STATUS_ORDER[b.status] || b.createdAt - a.createdAt);
58
+ };
59
+
60
+ // active 必须排在第一位:oidc-provider 签名时选用第一把匹配算法的密钥
61
+ const getPrivateJwks = async () => {
62
+ return { keys: (await sortedKeys()).map(item => JSON.parse(decrypt(secret, item.privateJwk))) };
63
+ };
64
+
65
+ const getPublicJwks = async () => {
66
+ return { keys: (await sortedKeys()).map(item => item.publicJwk) };
67
+ };
68
+
69
+ const fingerprint = async () => {
70
+ return (await sortedKeys()).map(item => `${item.kid}:${item.status}`).join(',');
71
+ };
72
+
73
+ const list = async () => {
74
+ return (await sortedKeys()).map(item => ({
75
+ id: item.id,
76
+ kid: item.kid,
77
+ alg: item.alg,
78
+ status: item.status,
79
+ activatedAt: item.activatedAt,
80
+ retiredAt: item.retiredAt,
81
+ createdAt: item.createdAt
82
+ }));
83
+ };
84
+
85
+ const rotate = async () => {
86
+ await fastify.sequelize.instance.transaction(async transaction => {
87
+ const now = new Date();
88
+ await models.key.update({ status: 'retired', retiredAt: now }, { where: { status: 'active' }, transaction });
89
+ const next = await models.key.findOne({ where: { status: 'next' }, order: [['createdAt', 'ASC']], transaction });
90
+ if (next) {
91
+ await next.update({ status: 'active', activatedAt: now }, { transaction });
92
+ } else {
93
+ await generate({ status: 'active', transaction });
94
+ }
95
+ await generate({ status: 'next', transaction });
96
+ await pruneRetired({ transaction });
97
+ });
98
+ await fastify[options.name].idp.reload();
99
+ return list();
100
+ };
101
+
102
+ services.key = { ensureKeys, getPrivateJwks, getPublicJwks, fingerprint, list, rotate, pruneRetired };
103
+ });
@@ -0,0 +1,99 @@
1
+ const fp = require('fastify-plugin');
2
+ const httpErrors = require('http-errors');
3
+ const { createError } = require('../utils/intl');
4
+
5
+ const { NotFound, BadRequest } = httpErrors;
6
+
7
+ module.exports = fp(async (fastify, options) => {
8
+ const { models, services } = fastify[options.name];
9
+ if (!options.runtime.idpEnabled) {
10
+ return;
11
+ }
12
+ const { Op } = fastify.sequelize.Sequelize;
13
+
14
+ const assertIdentifier = identifier => {
15
+ try {
16
+ new URL(identifier);
17
+ } catch (e) {
18
+ throw createError(BadRequest, 'resourceServerIdentifierInvalid');
19
+ }
20
+ };
21
+
22
+ const getInstance = async ({ id }) => {
23
+ const item = await models.resourceServer.findByPk(id);
24
+ if (!item) {
25
+ throw createError(NotFound, 'resourceServerNotFound');
26
+ }
27
+ return item;
28
+ };
29
+
30
+ const list = async ({ filter = {}, perPage = 20, currentPage = 1 } = {}) => {
31
+ const where = {};
32
+ if (filter.keyword) {
33
+ where[Op.or] = [{ identifier: { [Op.like]: `%${filter.keyword}%` } }, { name: { [Op.like]: `%${filter.keyword}%` } }];
34
+ }
35
+ if (filter.status) {
36
+ where.status = filter.status;
37
+ }
38
+ const { rows, count } = await models.resourceServer.findAndCountAll({
39
+ where,
40
+ offset: perPage * (currentPage - 1),
41
+ limit: perPage,
42
+ order: [['createdAt', 'DESC']]
43
+ });
44
+ return { pageData: rows, totalCount: count };
45
+ };
46
+
47
+ const detail = async ({ id }) => getInstance({ id });
48
+
49
+ const create = async ({ identifier, name, scope, accessTokenTTL, includePermissions, description }) => {
50
+ assertIdentifier(identifier);
51
+ if (await models.resourceServer.count({ where: { identifier } })) {
52
+ throw createError(BadRequest, 'resourceServerExists', { identifier });
53
+ }
54
+ return models.resourceServer.create({
55
+ identifier,
56
+ name,
57
+ scope: scope || options.defaultResourceScope,
58
+ accessTokenTTL,
59
+ includePermissions,
60
+ description
61
+ });
62
+ };
63
+
64
+ const save = async ({ id, name, scope, accessTokenTTL, includePermissions, description }) => {
65
+ const item = await getInstance({ id });
66
+ await item.update({ name, scope: scope || options.defaultResourceScope, accessTokenTTL, includePermissions, description });
67
+ return item;
68
+ };
69
+
70
+ const setStatus = async ({ id, status }) => {
71
+ const item = await getInstance({ id });
72
+ await item.update({ status });
73
+ };
74
+
75
+ const remove = async ({ id }) => {
76
+ const item = await getInstance({ id });
77
+ await item.destroy();
78
+ };
79
+
80
+ const findByIdentifier = async identifier => {
81
+ return models.resourceServer.findOne({ where: { identifier, status: 'open' } });
82
+ };
83
+
84
+ const listIdentifiers = async () => {
85
+ const rows = await models.resourceServer.findAll({ attributes: ['identifier'], where: { status: 'open' } });
86
+ return rows.map(row => row.identifier);
87
+ };
88
+
89
+ const seed = async resourceServers => {
90
+ for (const item of resourceServers || []) {
91
+ if (await models.resourceServer.count({ where: { identifier: item.identifier } })) {
92
+ continue;
93
+ }
94
+ await create(item);
95
+ }
96
+ };
97
+
98
+ services.resourceServer = { list, detail, create, save, setStatus, remove, findByIdentifier, listIdentifiers, seed };
99
+ });
@@ -0,0 +1,32 @@
1
+ const fp = require('fastify-plugin');
2
+
3
+ module.exports = fp(async (fastify, options) => {
4
+ const { models, services } = fastify[options.name];
5
+ if (!options.runtime.idpEnabled) {
6
+ return;
7
+ }
8
+
9
+ const get = async ({ sessionUid }) => {
10
+ if (!sessionUid) {
11
+ return null;
12
+ }
13
+ const item = await models.sessionTenant.findOne({ where: { sessionUid } });
14
+ return item ? { sessionUid, accountId: item.accountId, tenantId: item.tenantId } : null;
15
+ };
16
+
17
+ const set = async ({ sessionUid, accountId, tenantId }) => {
18
+ const values = { accountId: String(accountId), tenantId: String(tenantId) };
19
+ const item = await models.sessionTenant.findOne({ where: { sessionUid } });
20
+ if (item) {
21
+ await item.update(values);
22
+ return;
23
+ }
24
+ await models.sessionTenant.create(Object.assign({ sessionUid }, values));
25
+ };
26
+
27
+ const remove = async ({ sessionUid }) => {
28
+ await models.sessionTenant.destroy({ where: { sessionUid } });
29
+ };
30
+
31
+ services.sessionTenant = { get, set, remove };
32
+ });
@@ -0,0 +1,25 @@
1
+ const crypto = require('node:crypto');
2
+
3
+ const deriveKey = (secret, purpose = 'encryption') => crypto.createHash('sha256').update(`${purpose}:${secret}`).digest();
4
+
5
+ const encrypt = (secret, plaintext) => {
6
+ const iv = crypto.randomBytes(12);
7
+ const cipher = crypto.createCipheriv('aes-256-gcm', deriveKey(secret), iv);
8
+ const data = Buffer.concat([cipher.update(String(plaintext), 'utf8'), cipher.final()]);
9
+ const tag = cipher.getAuthTag();
10
+ return ['v1', iv.toString('base64url'), tag.toString('base64url'), data.toString('base64url')].join('.');
11
+ };
12
+
13
+ const decrypt = (secret, text) => {
14
+ const [version, iv, tag, data] = String(text).split('.');
15
+ if (version !== 'v1' || !iv || !tag || !data) {
16
+ throw new Error('无法识别的加密数据格式');
17
+ }
18
+ const decipher = crypto.createDecipheriv('aes-256-gcm', deriveKey(secret), Buffer.from(iv, 'base64url'));
19
+ decipher.setAuthTag(Buffer.from(tag, 'base64url'));
20
+ return Buffer.concat([decipher.update(Buffer.from(data, 'base64url')), decipher.final()]).toString('utf8');
21
+ };
22
+
23
+ const randomSecret = (bytes = 32) => crypto.randomBytes(bytes).toString('base64url');
24
+
25
+ module.exports = { deriveKey, encrypt, decrypt, randomSecret };
@@ -0,0 +1,71 @@
1
+ const locale = require('../locale');
2
+
3
+ const FALLBACK_LOCALE = 'zh-CN';
4
+
5
+ // 依赖插件(如 fastify-account)的错误也可能带 messageId,只翻译本包抛出的错误
6
+ const MESSAGE_SCOPE = '@kne/fastify-oidc';
7
+
8
+ const format = (template, values) => template.replace(/\{(\w+)\}/g, (match, key) => (values && values[key] !== undefined ? String(values[key]) : match));
9
+
10
+ const fallbackMessage = (messageId, messageValues) => format(locale[FALLBACK_LOCALE][messageId] || messageId, messageValues);
11
+
12
+ /**
13
+ * 创建带 messageId 的错误:message 先取内置中文,经 translator 按请求语言替换
14
+ */
15
+ const createError = (ErrorClass, messageId, messageValues) => {
16
+ const message = fallbackMessage(messageId, messageValues);
17
+ const error = ErrorClass ? new ErrorClass(message) : new Error(message);
18
+ return Object.assign(error, { messageScope: MESSAGE_SCOPE, messageId, messageValues });
19
+ };
20
+
21
+ /**
22
+ * 通过 @kne/fastify-intl 按请求语言翻译;未注册 fastify-intl 或语言包缺失时回退到内置中文
23
+ */
24
+ const createTranslator = ({ fastify, options }) => {
25
+ const getIntl = () => {
26
+ const intl = fastify[options.intlNamespace];
27
+ return intl && typeof intl.createIntl === 'function' ? intl : null;
28
+ };
29
+
30
+ const getLocale = request => {
31
+ const intl = getIntl();
32
+ return intl && request ? intl.getRequestLocale(request) : null;
33
+ };
34
+
35
+ const t = async (target, messageId, messageValues) => {
36
+ const intl = getIntl();
37
+ if (intl) {
38
+ const requestLocale = typeof target === 'string' ? target : getLocale(target);
39
+ for (const lang of [requestLocale, intl.options?.defaultLocale]) {
40
+ if (!lang) {
41
+ continue;
42
+ }
43
+ const instance = await intl.createIntl(lang, options.name);
44
+ if (instance.messages[messageId]) {
45
+ return instance.formatMessage({ id: messageId }, messageValues);
46
+ }
47
+ }
48
+ }
49
+ return fallbackMessage(messageId, messageValues);
50
+ };
51
+
52
+ const translateError = async (target, error) => {
53
+ if (error && error.messageScope === MESSAGE_SCOPE && error.messageId) {
54
+ error.message = await t(target, error.messageId, error.messageValues);
55
+ }
56
+ return error;
57
+ };
58
+
59
+ const wrap = handler =>
60
+ async function (request, reply) {
61
+ try {
62
+ return await handler.call(this, request, reply);
63
+ } catch (e) {
64
+ throw await translateError(request, e);
65
+ }
66
+ };
67
+
68
+ return { getLocale, t, translateError, wrap };
69
+ };
70
+
71
+ module.exports = { locale, createError, createTranslator };
@@ -0,0 +1,68 @@
1
+ const MODES = ['standalone', 'central'];
2
+
3
+ const normalizeOrigin = (value, label) => {
4
+ if (!value) {
5
+ throw new Error(`fastify-oidc: 缺少 ${label}`);
6
+ }
7
+ let url;
8
+ try {
9
+ url = new URL(value);
10
+ } catch (e) {
11
+ throw new Error(`fastify-oidc: ${label} 不是合法的 URL: ${value}`);
12
+ }
13
+ return url.origin;
14
+ };
15
+
16
+ const stripTrailingSlash = value => value.replace(/\/+$/, '');
17
+
18
+ const claimNames = namespace => ({
19
+ tenantId: `${namespace}tenant_id`,
20
+ tenantUserId: `${namespace}tenant_user_id`,
21
+ roles: `${namespace}roles`,
22
+ permissions: `${namespace}permissions`,
23
+ clientToken: `${namespace}client_token`
24
+ });
25
+
26
+ /**
27
+ * 根据 mode / ORIGIN / issuer 推导运行期配置,结果挂在 options 上供各模块读取
28
+ */
29
+ module.exports = options => {
30
+ if (!MODES.includes(options.mode)) {
31
+ throw new Error(`fastify-oidc: mode 只能是 ${MODES.join(' / ')},当前为 ${options.mode}`);
32
+ }
33
+ const idpEnabled = options.mode === 'standalone';
34
+ const origin = normalizeOrigin(options.origin, 'origin(环境变量 ORIGIN)');
35
+
36
+ let issuer = options.issuer ? stripTrailingSlash(options.issuer) : null;
37
+ if (!issuer) {
38
+ if (!idpEnabled) {
39
+ throw new Error('fastify-oidc: central 模式必须配置 issuer(环境变量 OIDC_ISSUER),指向主项目的 issuer');
40
+ }
41
+ issuer = `${origin}${options.mountPath}`;
42
+ }
43
+ const issuerUrl = new URL(issuer);
44
+ const mountPath = stripTrailingSlash(issuerUrl.pathname);
45
+ if (idpEnabled && !mountPath) {
46
+ throw new Error('fastify-oidc: issuer 需要包含路径(如 https://example.com/oidc),不能直接挂在根路径');
47
+ }
48
+
49
+ const claimNamespace = options.claimNamespace || `${idpEnabled ? origin : issuerUrl.origin}/`;
50
+
51
+ return {
52
+ idpEnabled,
53
+ origin,
54
+ issuer,
55
+ issuerOrigin: issuerUrl.origin,
56
+ mountPath,
57
+ serviceAudience: options.serviceAudience || `${issuerUrl.origin}${options.prefix}`,
58
+ idpApiBase: options.idpApiBase || `${issuerUrl.origin}${options.prefix}`,
59
+ audience: options.audience || `${origin}/api`,
60
+ clientId: options.clientId || `${options.name}-spa`,
61
+ claimNamespace,
62
+ claims: claimNames(claimNamespace),
63
+ jwksUri: options.jwksUri || `${issuer}/jwks`
64
+ };
65
+ };
66
+
67
+ module.exports.claimNames = claimNames;
68
+ module.exports.normalizeOrigin = normalizeOrigin;
package/package.json CHANGED
@@ -1,6 +1,85 @@
1
1
  {
2
2
  "name": "@kne/fastify-oidc",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "基于 oidc-provider 的 Fastify OIDC 认证插件,支持 standalone / central 多项目单点登录、租户与跨项目令牌",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "init": "husky",
8
+ "build:md": "npx @kne/md-doc",
9
+ "start:md": "npx @kne/md-doc --watch",
10
+ "prettier": "prettier --config .prettierrc --write '{libs/**/*,index}.{js,jsx,ts,tsx,json,css,scss}'",
11
+ "lint-staged": "npx lint-staged",
12
+ "test": "mocha 'test/**/*.test.js'",
13
+ "test:coverage": "nyc --reporter=html --reporter=text mocha 'test/**/*.test.js'"
14
+ },
15
+ "lint-staged": {
16
+ "{libs/**/*,index}.{js,jsx,ts,tsx,json,css,scss}": [
17
+ "prettier --config .prettierrc --write",
18
+ "git add"
19
+ ]
20
+ },
21
+ "files": [
22
+ "index.js",
23
+ "libs"
24
+ ],
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/kne-union/fastify-oidc.git"
28
+ },
29
+ "keywords": [
30
+ "fastify",
31
+ "oidc",
32
+ "oauth2",
33
+ "sso",
34
+ "oidc-provider",
35
+ "authentication",
36
+ "jwt",
37
+ "pkce",
38
+ "dpop",
39
+ "token-exchange",
40
+ "multi-tenant",
41
+ "kne"
42
+ ],
43
+ "author": "linzp",
44
+ "license": "ISC",
45
+ "bugs": {
46
+ "url": "https://github.com/kne-union/fastify-oidc/issues"
47
+ },
48
+ "homepage": "https://github.com/kne-union/fastify-oidc#readme",
49
+ "peerDependencies": {
50
+ "@kne/fastify-account": ">=2.0.8",
51
+ "@kne/fastify-namespace": "*",
52
+ "@kne/fastify-sequelize": "*",
53
+ "fastify-plugin": ">=5"
54
+ },
55
+ "devDependencies": {
56
+ "@fastify/env": "^5.0.2",
57
+ "@kne/fastify-namespace": "^1.2.1",
58
+ "@kne/fastify-sequelize": "^3.0.6",
59
+ "chai": "^6.3.0",
60
+ "fastify": "^5.4.0",
61
+ "fastify-plugin": "^5.0.1",
62
+ "husky": "^9.0.11",
63
+ "mocha": "^12.0.3",
64
+ "nodemon": "^3.1.3",
65
+ "nyc": "^17.1.0",
66
+ "oauth4webapi": "^3.8.8",
67
+ "prettier": "^3.2.5",
68
+ "sqlite3": "^5.1.7"
69
+ },
70
+ "dependencies": {
71
+ "@kne/fastify-intl": "^0.1.5",
72
+ "http-errors": "^2.0.1",
73
+ "jose": "^6.2.12",
74
+ "lodash": "^4.18.1",
75
+ "oidc-provider": "^9.12.2"
76
+ },
77
+ "engines": {
78
+ "node": ">=22.12.0"
79
+ },
80
+ "peerDependenciesMeta": {
81
+ "@kne/fastify-account": {
82
+ "optional": true
83
+ }
84
+ }
85
+ }