@albirex/platformatic-logto 1.5.5 → 1.6.1
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/README.md +3 -0
- package/lib/index.cjs +75 -0
- package/lib/index.cjs.map +1 -1
- package/lib/index.d.cts +26 -2
- package/lib/index.d.ts +26 -2
- package/lib/index.js +73 -0
- package/lib/index.js.map +1 -1
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -17,6 +17,9 @@ Based on [@platformatic/db-authorization](https://github.com/platformatic/platfo
|
|
|
17
17
|
- Customizable Hooks: Extend and customize authentication flows to fit your application's needs.
|
|
18
18
|
- TypeScript Support: Written in TypeScript for type safety and improved developer experience.
|
|
19
19
|
|
|
20
|
+
## Compatibility
|
|
21
|
+
For Platformatic 2.x use version < 3.x<br />
|
|
22
|
+
For Platformatic 3.x use version 3.x
|
|
20
23
|
## Installation
|
|
21
24
|
To install the package, use your preferred package manager:
|
|
22
25
|
|
package/lib/index.cjs
CHANGED
|
@@ -31,10 +31,12 @@ var index_exports = {};
|
|
|
31
31
|
__export(index_exports, {
|
|
32
32
|
checkFieldsFromRule: () => checkFieldsFromRule,
|
|
33
33
|
default: () => index_default,
|
|
34
|
+
deletePermissionsVersion: () => deletePermissionsVersion,
|
|
34
35
|
fastifyLogto: () => import_fastify_logto2.fastifyLogto,
|
|
35
36
|
findRuleForRequestUser: () => findRuleForRequestUser,
|
|
36
37
|
getRequestFromContext: () => getRequestFromContext,
|
|
37
38
|
getRoles: () => getRoles,
|
|
39
|
+
incrementPermissionsVersion: () => incrementPermissionsVersion,
|
|
38
40
|
platformaticLogto: () => platformaticLogto
|
|
39
41
|
});
|
|
40
42
|
module.exports = __toCommonJS(index_exports);
|
|
@@ -65,11 +67,38 @@ var ERROR_PREFIX = "PLT_DB_AUTH";
|
|
|
65
67
|
var Unauthorized = (0, import_error.default)(`${ERROR_PREFIX}_UNAUTHORIZED`, "operation not allowed", 401);
|
|
66
68
|
var UnauthorizedField = (0, import_error.default)(`${ERROR_PREFIX}_FIELD_UNAUTHORIZED`, "field not allowed: %s", 401);
|
|
67
69
|
var MissingNotNullableError = (0, import_error.default)(`${ERROR_PREFIX}_NOT_NULLABLE_MISSING`, 'missing not nullable field: "%s" in save rule for entity "%s"');
|
|
70
|
+
var PermissionsOutdated = (0, import_error.default)(`${ERROR_PREFIX}_VERSION_OUTDATED`, "Verision has been updated. Please logout and login again.", 403);
|
|
68
71
|
|
|
69
72
|
// src/index.ts
|
|
70
73
|
var import_fastify_logto = __toESM(require("@albirex/fastify-logto"), 1);
|
|
74
|
+
var import_redis = __toESM(require("@fastify/redis"), 1);
|
|
71
75
|
var import_fastify_logto2 = require("@albirex/fastify-logto");
|
|
72
76
|
|
|
77
|
+
// src/utils/permissions-version.ts
|
|
78
|
+
async function incrementPermissionsVersion(app, userId) {
|
|
79
|
+
if (!app.logto) {
|
|
80
|
+
throw new Error("Logto client not available");
|
|
81
|
+
}
|
|
82
|
+
const userResp = await app.logto.callAPI(`/api/users/${userId}`, "GET");
|
|
83
|
+
const userData = await userResp.json();
|
|
84
|
+
const existingCustomData = userData.customData || {};
|
|
85
|
+
const currentVersion = existingCustomData.sessionVersion || 0;
|
|
86
|
+
const newVersion = currentVersion + 1;
|
|
87
|
+
await app.logto.callAPI(`/api/users/${userId}`, "PATCH", JSON.stringify({ customData: { ...existingCustomData, sessionVersion: newVersion } }));
|
|
88
|
+
if (app.redis) {
|
|
89
|
+
const redisKey = `permissions:version:${userId}`;
|
|
90
|
+
await app.redis.set(redisKey, newVersion.toString());
|
|
91
|
+
}
|
|
92
|
+
return newVersion;
|
|
93
|
+
}
|
|
94
|
+
async function deletePermissionsVersion(app, userId) {
|
|
95
|
+
if (!app.redis) {
|
|
96
|
+
throw new Error("Redis client not available");
|
|
97
|
+
}
|
|
98
|
+
const redisKey = `permissions:version:${userId}`;
|
|
99
|
+
await app.redis.del(redisKey);
|
|
100
|
+
}
|
|
101
|
+
|
|
73
102
|
// src/utils/utils.ts
|
|
74
103
|
function getRequestFromContext(ctx) {
|
|
75
104
|
if (ctx && !ctx.reply) {
|
|
@@ -111,6 +140,16 @@ var platformaticLogto = (0, import_fastify_plugin.default)(async (app, opts) =>
|
|
|
111
140
|
app.decorate("platformaticLogTo", {
|
|
112
141
|
opts
|
|
113
142
|
});
|
|
143
|
+
if (opts.redis) {
|
|
144
|
+
await app.register(import_redis.default, {
|
|
145
|
+
host: opts.redis.host || "127.0.0.1",
|
|
146
|
+
port: opts.redis.port || 6379,
|
|
147
|
+
password: opts.redis.password,
|
|
148
|
+
username: opts.redis.username,
|
|
149
|
+
db: opts.redis.db || 0
|
|
150
|
+
});
|
|
151
|
+
app.log.info("Redis client registered for permissions version check");
|
|
152
|
+
}
|
|
114
153
|
app.register(import_fastify_logto.default, {
|
|
115
154
|
endpoint: opts.logtoBaseUrl || "https://auth.example.com",
|
|
116
155
|
appId: opts.logtoAppId || "your-app-id",
|
|
@@ -237,6 +276,8 @@ var platformaticLogto = (0, import_fastify_plugin.default)(async (app, opts) =>
|
|
|
237
276
|
}
|
|
238
277
|
});
|
|
239
278
|
}
|
|
279
|
+
} else {
|
|
280
|
+
await checkPermissionsVersion(app, opts, this.user);
|
|
240
281
|
}
|
|
241
282
|
if (forceAdminRole) {
|
|
242
283
|
this.user = {
|
|
@@ -476,14 +517,48 @@ function checkSaveMandatoryFieldsInRules(type, rules) {
|
|
|
476
517
|
}
|
|
477
518
|
}
|
|
478
519
|
}
|
|
520
|
+
async function checkPermissionsVersion(app, opts, user = null) {
|
|
521
|
+
if (!opts.enableTokenVersionCheck || !opts.redis || !app.redis || !user) {
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
const sessionVersionKey = opts.sessionVersionKey || "version";
|
|
525
|
+
const tokenVersion = user?.[sessionVersionKey];
|
|
526
|
+
const userId = user?.sub;
|
|
527
|
+
try {
|
|
528
|
+
const redisKey = `permissions:version:${userId}`;
|
|
529
|
+
const currentVersionStr = await app.redis.get(redisKey);
|
|
530
|
+
if (currentVersionStr === null) {
|
|
531
|
+
await app.redis.set(redisKey, tokenVersion.toString());
|
|
532
|
+
app.log.debug({ userId, version: tokenVersion }, "Initialized permissions version in Redis");
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
const currentVersion = parseInt(currentVersionStr, 10);
|
|
536
|
+
if (currentVersion !== tokenVersion) {
|
|
537
|
+
app.log.warn({
|
|
538
|
+
userId,
|
|
539
|
+
tokenVersion,
|
|
540
|
+
currentVersion
|
|
541
|
+
}, "Permissions version mismatch detected");
|
|
542
|
+
throw new PermissionsOutdated();
|
|
543
|
+
}
|
|
544
|
+
app.log.trace({ userId, version: tokenVersion }, "Token version check passed");
|
|
545
|
+
} catch (error) {
|
|
546
|
+
if (error.name === "FastifyError" && error.code === "PLT_DB_AUTH_VERSION_OUTDATED") {
|
|
547
|
+
throw error;
|
|
548
|
+
}
|
|
549
|
+
app.log.error({ err: error, userId }, "Error checking token version");
|
|
550
|
+
}
|
|
551
|
+
}
|
|
479
552
|
var index_default = platformaticLogto;
|
|
480
553
|
// Annotate the CommonJS export names for ESM import in node:
|
|
481
554
|
0 && (module.exports = {
|
|
482
555
|
checkFieldsFromRule,
|
|
556
|
+
deletePermissionsVersion,
|
|
483
557
|
fastifyLogto,
|
|
484
558
|
findRuleForRequestUser,
|
|
485
559
|
getRequestFromContext,
|
|
486
560
|
getRoles,
|
|
561
|
+
incrementPermissionsVersion,
|
|
487
562
|
platformaticLogto
|
|
488
563
|
});
|
|
489
564
|
//# sourceMappingURL=index.cjs.map
|
package/lib/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils/find-rule.ts","../src/utils/errors.ts","../src/utils/utils.ts"],"sourcesContent":["import fp from 'fastify-plugin'\nimport * as fastifyUser from 'fastify-user'\n\nimport findRule from './utils/find-rule.js'\nimport { Unauthorized, UnauthorizedField, MissingNotNullableError } from './utils/errors.js'\nimport fastifyLogto from '@albirex/fastify-logto';\nimport { FastifyInstance, FastifyPluginAsync } from 'fastify'\nimport type { FastifyUserPluginOptions } from 'fastify-user';\nimport type { Entity, PlatformaticContext } from '@platformatic/sql-mapper'\nexport { fastifyLogto } from '@albirex/fastify-logto';\n\nimport { getRequestFromContext, getRoles } from './utils/utils.js'\nexport { getRequestFromContext, getRoles } from './utils/utils.js'\n\nconst PLT_ADMIN_ROLE = 'platformatic-admin'\n\nexport type PlatformaticRule = {\n role: string;\n entity?: string;\n entities?: string[];\n defaults?: Record<string, string>;\n checks?: boolean;\n find?: boolean;\n save?: boolean;\n delete?: boolean;\n [action: string]: unknown;\n};\n\nexport type PlatformaticLogtoAuthOptions = {\n logtoBaseUrl?: string;\n logtoAppId?: string;\n logtoAppSecret?: string;\n adminSecret?: string;\n rolePath?: string;\n roleKey?: string;\n userPath?: string;\n userKey?: string;\n anonymousRole?: string;\n allowAnonymous?: boolean;\n checks?: boolean;\n defaults?: boolean;\n jwtPlugin: FastifyUserPluginOptions\n};\n\nexport const platformaticLogto: FastifyPluginAsync<PlatformaticLogtoAuthOptions> = fp(async (app: FastifyInstance, opts: PlatformaticLogtoAuthOptions) => {\n app.decorate('platformaticLogTo', {\n opts\n })\n\n app.register(fastifyLogto, {\n endpoint: opts.logtoBaseUrl || 'https://auth.example.com',\n appId: opts.logtoAppId || 'your-app-id',\n appSecret: opts.logtoAppSecret || 'your-app-secret',\n });\n\n await app.register(fastifyUser as unknown as FastifyPluginAsync, opts.jwtPlugin);\n\n const adminSecret = opts.adminSecret\n const roleKey = opts.rolePath || opts.roleKey || 'X-PLATFORMATIC-ROLE'\n const userKey = opts.userPath || opts.userKey || 'X-PLATFORMATIC-USER-ID'\n const isRolePath = !!opts.rolePath // if `true` the role is intepreted as path like `user.role`\n const anonymousRole = opts.anonymousRole || 'anonymous'\n\n async function composeLogToRules() {\n const rolesResp = await app.logto.callAPI('/api/roles?type=User', 'GET');\n\n if (!rolesResp.ok) {\n throw rolesResp;\n }\n\n const roles = await rolesResp.json();\n const rules: PlatformaticRule[] = [{\n role: anonymousRole,\n entities: Object.keys(app.platformatic.entities),\n find: opts.allowAnonymous,\n save: opts.allowAnonymous,\n delete: opts.allowAnonymous,\n }];\n\n for (const role of roles) {\n const scopesResp = await app.logto.callAPI(`/api/roles/${role.id}/scopes`, 'GET');\n\n if (!scopesResp.ok) {\n throw scopesResp;\n }\n\n const scopes = await scopesResp.json();\n\n for (const scope of scopes) {\n const roleName = role.name;\n // eslint-disable-next-line prefer-const\n let [scopeAction, entity] = scope.name.split(':');\n\n if (!app.platformatic.entities[entity]) {\n app.log.debug(`Unknown entity '${entity}' in authorization rule`)\n continue;\n }\n\n switch (scopeAction) {\n case 'create':\n scopeAction = 'save'\n break;\n case 'read':\n scopeAction = 'find'\n break;\n case 'update':\n scopeAction = 'updateMany'\n break;\n }\n\n const checkExists = rules.find(r => r.role === roleName && r.entity === entity);\n if (checkExists) {\n if (opts.checks) {\n checkExists[scopeAction] = {\n checks: {\n userId: userKey\n }\n };\n } else {\n checkExists[scopeAction] = true;\n }\n } else {\n const newRule: PlatformaticRule = {\n role: roleName,\n entity,\n };\n\n if (opts.checks) {\n newRule[scopeAction] = {\n checks: {\n userId: userKey\n }\n };\n } else {\n newRule[scopeAction] = true;\n }\n\n if (opts.defaults) {\n newRule.defaults = {\n userId: userKey\n };\n }\n\n rules.push(newRule);\n }\n }\n }\n\n const logRules = rules.reduce((prev, curr) => {\n (prev[curr['role']] ??= []).push(curr);\n return prev;\n }, {})\n\n for (const key in logRules) {\n app.log.info(`Rules set for role ${key}`);\n\n for (const element of logRules[key]) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { entity, entities, role, ...other } = element;\n app.log.info(`\\t${entity ?? entities.join(',')}: ${JSON.stringify(other)}`);\n }\n }\n\n const missingEntities = Object.keys(app.platformatic.entities).filter((e) => !rules.map((r) => r.entity).includes(e));\n\n if (missingEntities.length) {\n app.log.warn(`Missing rules for entities: ${missingEntities.join(', ')}`);\n }\n\n app.log.debug('LogTo calculated rules');\n app.log.debug(rules);\n return rules;\n }\n\n app.decorateRequest('setupDBAuthorizationUser', setupUser)\n\n async function setupUser() {\n // if (!adminSecret) {\n await this.extractUser()\n // }\n\n let forceAdminRole = false\n if (adminSecret && this.headers['x-platformatic-admin-secret'] === adminSecret) {\n if (opts.jwtPlugin.jwt) {\n forceAdminRole = true\n } else {\n this.log.info('admin secret is valid')\n this.user = new Proxy(this.headers, {\n get: (target, key) => {\n let value;\n if (!target[key.toString()]) {\n const newKey = key.toString().toLowerCase()\n value = target[newKey]\n } else {\n value = target[key.toString()]\n }\n\n if (!value && key.toString().toLowerCase() === roleKey.toLowerCase()) {\n value = PLT_ADMIN_ROLE\n }\n return value\n },\n })\n }\n }\n\n if (forceAdminRole) {\n // We replace just the role in `request.user`, all the rest is untouched\n this.user = {\n // ...request.user,\n [roleKey]: this.headers['x-platformatic-role'] ? [this.headers['x-platformatic-role']] : [PLT_ADMIN_ROLE]\n }\n }\n }\n\n app.addHook('onReady', async function () {\n const logToRules = await composeLogToRules();\n\n app.platformaticLogTo.rules = logToRules;\n\n // TODO validate that there is at most a rule for a given role\n const entityRules = {};\n for (let i = 0; i < logToRules.length; i++) {\n const rule = logToRules[i]\n\n let ruleEntities = null\n if (rule.entity) {\n ruleEntities = [rule.entity]\n } else if (rule.entities) {\n ruleEntities = [...rule.entities]\n } else {\n throw new Error(`Missing entity in authorization rule ${i}`)\n }\n\n for (const ruleEntity of ruleEntities) {\n const newRule = { ...rule, entity: ruleEntity, entities: undefined }\n if (!app.platformatic.entities[newRule.entity]) {\n throw new Error(`Unknown entity '${ruleEntity}' in authorization rule ${i}`)\n }\n\n if (!entityRules[ruleEntity]) {\n entityRules[ruleEntity] = []\n }\n entityRules[ruleEntity].push(newRule)\n }\n }\n\n for (const entityKey of Object.keys(app.platformatic.entities)) {\n const rules = entityRules[entityKey] || []\n const type = app.platformatic.entities[entityKey]\n\n // We have subscriptions!\n let userPropToFillForPublish\n const topicsWithoutChecks = false\n\n // mqtt\n // if (app.platformatic.mq) {\n // for (const rule of rules) {\n // const checks = rule.find?.checks\n // if (typeof checks !== 'object') {\n // topicsWithoutChecks = !!rule.find\n // continue\n // }\n // const keys = Object.keys(checks)\n // if (keys.length !== 1) {\n // throw new Error(`Subscription requires that the role \"${rule.role}\" has only one check in the find rule for entity \"${rule.entity}\"`)\n // }\n // const key = keys[0]\n\n // const val = typeof checks[key] === 'object' ? checks[key].eq : checks[key]\n // if (userPropToFillForPublish && userPropToFillForPublish.val !== val) {\n // throw new Error('Unable to configure subscriptions and authorization due to multiple check clauses in find')\n // }\n // userPropToFillForPublish = { key, val }\n // }\n // }\n\n if (userPropToFillForPublish && topicsWithoutChecks) {\n throw new Error(`Subscription for entity \"${entityKey}\" have conflictling rules across roles`)\n }\n\n // MUST set this after doing the security checks on the subscriptions\n if (adminSecret) {\n rules.push({\n role: PLT_ADMIN_ROLE,\n find: true,\n save: true,\n delete: true,\n updateMany: true\n })\n }\n\n // If we have `fields` in save rules, we need to check if all the not-nullable\n // fields are specified\n checkSaveMandatoryFieldsInRules(type, rules)\n\n function useOriginal(ctx: PlatformaticContext) {\n return !ctx\n }\n\n app.platformatic.addEntityHooks(entityKey, {\n async find(originalFind, { where, ctx, fields, ...restOpts } = {}) {\n if (useOriginal(ctx)) {\n return originalFind({ ...restOpts, where, ctx, fields })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n checkFieldsFromRule(rule.find, fields || Object.keys(app.platformatic.entities[entityKey].fields))\n where = await fromRuleToWhere(ctx, rule.find, where, request.user)\n\n return originalFind({ ...restOpts, where, ctx, fields })\n },\n async save(originalSave, { input, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalSave({ ctx, input, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n if (!rule.save) {\n throw new Unauthorized()\n }\n checkFieldsFromRule(rule.save, fields)\n checkInputFromRuleFields(rule.save, input)\n\n if (rule.defaults) {\n for (const key of Object.keys(rule.defaults)) {\n const defaults = rule.defaults[key]\n if (typeof defaults === 'function') {\n input[key] = await defaults({ user: request.user, ctx, input })\n } else {\n input[key] = request.user[defaults]\n }\n }\n }\n\n const hasAllPrimaryKeys = input[type.primaryKey] !== undefined;\n const whereConditions = {}\n whereConditions[type.primaryKey] = { eq: input[type.primaryKey] }\n\n if (hasAllPrimaryKeys) {\n const where = await fromRuleToWhere(ctx, rule.save, whereConditions, request.user)\n\n const found = await type.find({\n where,\n ctx,\n fields,\n })\n\n if (found.length === 0) {\n throw new Unauthorized()\n }\n\n return originalSave({ input, ctx, fields, ...restOpts })\n }\n\n return originalSave({ input, ctx, fields, ...restOpts })\n },\n\n async insert(originalInsert, { inputs, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalInsert({ inputs, ctx, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n if (!rule.save) {\n throw new Unauthorized()\n }\n\n checkFieldsFromRule(rule.save, fields)\n checkInputFromRuleFields(rule.save, inputs)\n\n /* istanbul ignore else */\n if (rule.defaults) {\n for (const input of inputs) {\n for (const key of Object.keys(rule.defaults)) {\n const defaults = rule.defaults[key]\n if (typeof defaults === 'function') {\n input[key] = await defaults({ user: request.user, ctx, input })\n } else {\n input[key] = request.user[defaults]\n }\n }\n }\n }\n\n return originalInsert({ inputs, ctx, fields, ...restOpts })\n },\n\n async delete(originalDelete, { where, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalDelete({ where, ctx, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n where = await fromRuleToWhere(ctx, rule.delete, where, request.user)\n\n return originalDelete({ where, ctx, fields, ...restOpts })\n },\n\n async updateMany(originalUpdateMany, { where, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalUpdateMany({ ...restOpts, where, ctx, fields })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n where = await fromRuleToWhere(ctx, rule.updateMany, where, request.user)\n\n return originalUpdateMany({ ...restOpts, where, ctx, fields })\n },\n })\n }\n })\n}, { name: '@albirex/platformatic-logto' });\n\nasync function fromRuleToWhere(ctx: PlatformaticContext, rule, where, user) {\n if (!rule) {\n throw new Unauthorized()\n }\n const request = getRequestFromContext(ctx)\n /* istanbul ignore next */\n where = where || {}\n\n if (typeof rule === 'object') {\n const { checks } = rule\n\n /* istanbul ignore else */\n if (checks) {\n for (const key of Object.keys(checks)) {\n const clauses = checks[key]\n if (typeof clauses === 'string') {\n // case: \"userId\": \"X-PLATFORMATIC-USER-ID\"\n where[key] = {\n eq: request.user[clauses],\n }\n } else {\n // case:\n // userId: {\n // eq: 'X-PLATFORMATIC-USER-ID'\n // }\n for (const clauseKey of Object.keys(clauses)) {\n const clause = clauses[clauseKey]\n where[key] = {\n [clauseKey]: request.user[clause],\n }\n }\n }\n }\n }\n } else if (typeof rule === 'function') {\n where = await rule({ user, ctx, where })\n }\n return where\n}\n\nexport async function findRuleForRequestUser(ctx: PlatformaticContext, rules: PlatformaticRule[], roleKey: string, anonymousRole: string, isRolePath = false) {\n const request = getRequestFromContext(ctx)\n await request.setupDBAuthorizationUser()\n const roles = getRoles(request, roleKey, anonymousRole, isRolePath)\n const rule = findRule(rules, roles)\n if (!rule) {\n ctx.reply.request.log.warn({ roles, rules }, 'no rule for roles')\n throw new Unauthorized()\n }\n ctx.reply.request.log.trace({ roles, rule }, 'found rule')\n return rule\n}\n\nexport function checkFieldsFromRule(rule, fields) {\n if (!rule) {\n throw new Unauthorized()\n }\n const { fields: fieldsFromRule } = rule\n /* istanbul ignore else */\n if (fieldsFromRule) {\n for (const field of fields) {\n if (!fieldsFromRule.includes(field)) {\n throw new UnauthorizedField(field)\n }\n }\n }\n}\n\nconst validateInputs = (inputs, fieldsFromRule) => {\n for (const input of inputs) {\n const inputFields = Object.keys(input)\n for (const inputField of inputFields) {\n if (!fieldsFromRule.includes(inputField)) {\n throw new UnauthorizedField(inputField)\n }\n }\n }\n}\n\nfunction checkInputFromRuleFields(rule, inputs) {\n const { fields: fieldsFromRule } = rule\n /* istanbul ignore else */\n if (fieldsFromRule) {\n if (!Array.isArray(inputs)) {\n // save\n validateInputs([inputs], fieldsFromRule)\n } else {\n // insert\n validateInputs(inputs, fieldsFromRule)\n }\n }\n}\n\nfunction checkSaveMandatoryFieldsInRules(type: Entity, rules) {\n // List of not nullable, not PKs field to validate save/insert when allowed fields are specified on the rule\n const mandatoryFields =\n Object.values(type.fields)\n .filter(k => (!k.isNullable && !k.primaryKey))\n .map(({ camelcase }) => (camelcase))\n\n for (const rule of rules) {\n const { entity, save } = rule\n if (save && save.fields) {\n const fields = save.fields\n for (const mField of mandatoryFields) {\n if (!fields.includes(mField)) {\n throw new MissingNotNullableError(mField, entity)\n }\n }\n }\n }\n}\n\nexport default platformaticLogto;\n\ndeclare module 'fastify' {\n interface FastifyInstance {\n platformaticLogTo: {\n opts: PlatformaticLogtoAuthOptions,\n rules?: PlatformaticRule[]\n }\n }\n}","'use strict'\n\nimport { PlatformaticRule } from '../index.js'\n\nfunction findRule(rules: PlatformaticRule[], roles: string[]) {\n let found = null\n for (const rule of rules) {\n for (const role of roles) {\n if (rule.role === role) {\n found = rule\n break\n }\n }\n if (found) {\n break\n }\n }\n return found\n}\n\nexport default findRule\n","'use strict'\n\nimport createError from '@fastify/error'\n\nconst ERROR_PREFIX = 'PLT_DB_AUTH'\n\nexport const Unauthorized = createError(`${ERROR_PREFIX}_UNAUTHORIZED`, 'operation not allowed', 401)\nexport const UnauthorizedField = createError(`${ERROR_PREFIX}_FIELD_UNAUTHORIZED`, 'field not allowed: %s', 401)\nexport const MissingNotNullableError = createError(`${ERROR_PREFIX}_NOT_NULLABLE_MISSING`, 'missing not nullable field: \"%s\" in save rule for entity \"%s\"')\n","'use strict'\n\nexport function getRequestFromContext (ctx) {\n if (ctx && !ctx.reply) {\n throw new Error('Missing reply in context. You should call this function with { ctx: { reply }}')\n }\n return ctx.reply.request\n}\n\nexport function getRoles (request, roleKey, anonymousRole, isRolePath = false) {\n let output = []\n const user = request.user\n if (!user) {\n output.push(anonymousRole)\n return output\n }\n\n let rolesRaw\n if (isRolePath) {\n const roleKeys = roleKey.split('.')\n rolesRaw = user\n for (const key of roleKeys) {\n rolesRaw = rolesRaw[key]\n }\n } else {\n rolesRaw = user[roleKey]\n }\n\n if (typeof rolesRaw === 'string') {\n output = rolesRaw.split(',')\n } else if (Array.isArray(rolesRaw)) {\n output = rolesRaw\n }\n if (output.length === 0) {\n output.push(anonymousRole)\n }\n\n return output\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAe;AACf,kBAA6B;;;ACG7B,SAAS,SAAS,OAA2B,OAAiB;AAC5D,MAAI,QAAQ;AACZ,aAAW,QAAQ,OAAO;AACxB,eAAW,QAAQ,OAAO;AACxB,UAAI,KAAK,SAAS,MAAM;AACtB,gBAAQ;AACR;AAAA,MACF;AAAA,IACF;AACA,QAAI,OAAO;AACT;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,IAAO,oBAAQ;;;AClBf,mBAAwB;AAExB,IAAM,eAAe;AAEd,IAAM,mBAAe,aAAAA,SAAY,GAAG,YAAY,iBAAiB,yBAAyB,GAAG;AAC7F,IAAM,wBAAoB,aAAAA,SAAY,GAAG,YAAY,uBAAuB,yBAAyB,GAAG;AACxG,IAAM,8BAA0B,aAAAA,SAAY,GAAG,YAAY,yBAAyB,+DAA+D;;;AFH1J,2BAAyB;AAIzB,IAAAC,wBAA6B;;;AGPtB,SAAS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yB,MAAM,QAAQ;AAC5C,QAAM,EAAE,QAAQ,eAAe,IAAI;AAEnC,MAAI,gBAAgB;AAChB,QAAI,CAAC,MAAM,QAAQ,MAAM,GAAG;AAExB,qBAAe,CAAC,MAAM,GAAG,cAAc;AAAA,IAC3C,OAAO;AAEH,qBAAe,QAAQ,cAAc;AAAA,IACzC;AAAA,EACJ;AACJ;AAEA,SAAS,gCAAgC,MAAc,OAAO;AAE1D,QAAM,kBACF,OAAO,OAAO,KAAK,MAAM,EACpB,OAAO,OAAM,CAAC,EAAE,cAAc,CAAC,EAAE,UAAW,EAC5C,IAAI,CAAC,EAAE,UAAU,MAAO,SAAU;AAE3C,aAAW,QAAQ,OAAO;AACtB,UAAM,EAAE,QAAQ,KAAK,IAAI;AACzB,QAAI,QAAQ,KAAK,QAAQ;AACrB,YAAM,SAAS,KAAK;AACpB,iBAAW,UAAU,iBAAiB;AAClC,YAAI,CAAC,OAAO,SAAS,MAAM,GAAG;AAC1B,gBAAM,IAAI,wBAAwB,QAAQ,MAAM;AAAA,QACpD;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;AAEA,IAAO,gBAAQ;","names":["createError","import_fastify_logto","fp","fastifyLogto"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils/find-rule.ts","../src/utils/errors.ts","../src/utils/permissions-version.ts","../src/utils/utils.ts"],"sourcesContent":["import fp from 'fastify-plugin'\nimport * as fastifyUser from 'fastify-user'\n\nimport findRule from './utils/find-rule.js'\nimport { Unauthorized, UnauthorizedField, MissingNotNullableError, PermissionsOutdated } from './utils/errors.js'\nimport fastifyLogto from '@albirex/fastify-logto';\nimport fastifyRedis from '@fastify/redis';\nimport { FastifyInstance, FastifyPluginAsync } from 'fastify'\nimport type { FastifyUserPluginOptions } from 'fastify-user';\nimport type { Entity, PlatformaticContext } from '@platformatic/sql-mapper'\n\nexport { fastifyLogto } from '@albirex/fastify-logto';\nexport { incrementPermissionsVersion, deletePermissionsVersion } from './utils/permissions-version.js';\n\nimport { getRequestFromContext, getRoles } from './utils/utils.js'\nexport { getRequestFromContext, getRoles } from './utils/utils.js'\n\nconst PLT_ADMIN_ROLE = 'platformatic-admin'\n\nexport type PlatformaticRule = {\n role: string;\n entity?: string;\n entities?: string[];\n defaults?: Record<string, string>;\n checks?: boolean;\n find?: boolean;\n save?: boolean;\n delete?: boolean;\n [action: string]: unknown;\n};\n\nexport type RedisConfig = {\n host?: string;\n port?: number;\n password?: string;\n username?: string;\n db?: number;\n};\n\nexport type PlatformaticLogtoAuthOptions = {\n logtoBaseUrl?: string;\n logtoAppId?: string;\n logtoAppSecret?: string;\n adminSecret?: string;\n rolePath?: string;\n roleKey?: string;\n userPath?: string;\n userKey?: string;\n anonymousRole?: string;\n allowAnonymous?: boolean;\n checks?: boolean;\n defaults?: boolean;\n jwtPlugin: FastifyUserPluginOptions;\n redis?: RedisConfig;\n enableTokenVersionCheck?: boolean;\n sessionVersionKey?: string;\n};\n\nexport const platformaticLogto: FastifyPluginAsync<PlatformaticLogtoAuthOptions> = fp(async (app: FastifyInstance, opts: PlatformaticLogtoAuthOptions) => {\n app.decorate('platformaticLogTo', {\n opts\n })\n\n // Register Redis if configured\n if (opts.redis) {\n await app.register(fastifyRedis, {\n host: opts.redis.host || '127.0.0.1',\n port: opts.redis.port || 6379,\n password: opts.redis.password,\n username: opts.redis.username,\n db: opts.redis.db || 0,\n });\n app.log.info('Redis client registered for permissions version check');\n }\n\n app.register(fastifyLogto, {\n endpoint: opts.logtoBaseUrl || 'https://auth.example.com',\n appId: opts.logtoAppId || 'your-app-id',\n appSecret: opts.logtoAppSecret || 'your-app-secret',\n });\n\n await app.register(fastifyUser as unknown as FastifyPluginAsync, opts.jwtPlugin);\n\n const adminSecret = opts.adminSecret\n const roleKey = opts.rolePath || opts.roleKey || 'X-PLATFORMATIC-ROLE'\n const userKey = opts.userPath || opts.userKey || 'X-PLATFORMATIC-USER-ID'\n const isRolePath = !!opts.rolePath // if `true` the role is intepreted as path like `user.role`\n const anonymousRole = opts.anonymousRole || 'anonymous'\n\n async function composeLogToRules() {\n const rolesResp = await app.logto.callAPI('/api/roles?type=User', 'GET');\n\n if (!rolesResp.ok) {\n throw rolesResp;\n }\n\n const roles = await rolesResp.json();\n const rules: PlatformaticRule[] = [{\n role: anonymousRole,\n entities: Object.keys(app.platformatic.entities),\n find: opts.allowAnonymous,\n save: opts.allowAnonymous,\n delete: opts.allowAnonymous,\n }];\n\n for (const role of roles) {\n const scopesResp = await app.logto.callAPI(`/api/roles/${role.id}/scopes`, 'GET');\n\n if (!scopesResp.ok) {\n throw scopesResp;\n }\n\n const scopes = await scopesResp.json();\n\n for (const scope of scopes) {\n const roleName = role.name;\n // eslint-disable-next-line prefer-const\n let [scopeAction, entity] = scope.name.split(':');\n\n if (!app.platformatic.entities[entity]) {\n app.log.debug(`Unknown entity '${entity}' in authorization rule`)\n continue;\n }\n\n switch (scopeAction) {\n case 'create':\n scopeAction = 'save'\n break;\n case 'read':\n scopeAction = 'find'\n break;\n case 'update':\n scopeAction = 'updateMany'\n break;\n }\n\n const checkExists = rules.find(r => r.role === roleName && r.entity === entity);\n if (checkExists) {\n if (opts.checks) {\n checkExists[scopeAction] = {\n checks: {\n userId: userKey\n }\n };\n } else {\n checkExists[scopeAction] = true;\n }\n } else {\n const newRule: PlatformaticRule = {\n role: roleName,\n entity,\n };\n\n if (opts.checks) {\n newRule[scopeAction] = {\n checks: {\n userId: userKey\n }\n };\n } else {\n newRule[scopeAction] = true;\n }\n\n if (opts.defaults) {\n newRule.defaults = {\n userId: userKey\n };\n }\n\n rules.push(newRule);\n }\n }\n }\n\n const logRules = rules.reduce((prev, curr) => {\n (prev[curr['role']] ??= []).push(curr);\n return prev;\n }, {})\n\n for (const key in logRules) {\n app.log.info(`Rules set for role ${key}`);\n\n for (const element of logRules[key]) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { entity, entities, role, ...other } = element;\n app.log.info(`\\t${entity ?? entities.join(',')}: ${JSON.stringify(other)}`);\n }\n }\n\n const missingEntities = Object.keys(app.platformatic.entities).filter((e) => !rules.map((r) => r.entity).includes(e));\n\n if (missingEntities.length) {\n app.log.warn(`Missing rules for entities: ${missingEntities.join(', ')}`);\n }\n\n app.log.debug('LogTo calculated rules');\n app.log.debug(rules);\n return rules;\n }\n\n app.decorateRequest('setupDBAuthorizationUser', setupUser)\n\n async function setupUser() {\n // if (!adminSecret) {\n await this.extractUser()\n // }\n\n let forceAdminRole = false\n if (adminSecret && this.headers['x-platformatic-admin-secret'] === adminSecret) {\n if (opts.jwtPlugin.jwt) {\n forceAdminRole = true\n } else {\n this.log.info('admin secret is valid')\n this.user = new Proxy(this.headers, {\n get: (target, key) => {\n let value;\n if (!target[key.toString()]) {\n const newKey = key.toString().toLowerCase()\n value = target[newKey]\n } else {\n value = target[key.toString()]\n }\n\n if (!value && key.toString().toLowerCase() === roleKey.toLowerCase()) {\n value = PLT_ADMIN_ROLE\n }\n return value\n },\n })\n }\n } else {\n await checkPermissionsVersion(app, opts, this.user)\n }\n\n if (forceAdminRole) {\n // We replace just the role in `request.user`, all the rest is untouched\n this.user = {\n // ...request.user,\n [roleKey]: this.headers['x-platformatic-role'] ? [this.headers['x-platformatic-role']] : [PLT_ADMIN_ROLE]\n }\n }\n }\n\n app.addHook('onReady', async function () {\n const logToRules = await composeLogToRules();\n\n app.platformaticLogTo.rules = logToRules;\n\n // TODO validate that there is at most a rule for a given role\n const entityRules = {};\n for (let i = 0; i < logToRules.length; i++) {\n const rule = logToRules[i]\n\n let ruleEntities = null\n if (rule.entity) {\n ruleEntities = [rule.entity]\n } else if (rule.entities) {\n ruleEntities = [...rule.entities]\n } else {\n throw new Error(`Missing entity in authorization rule ${i}`)\n }\n\n for (const ruleEntity of ruleEntities) {\n const newRule = { ...rule, entity: ruleEntity, entities: undefined }\n if (!app.platformatic.entities[newRule.entity]) {\n throw new Error(`Unknown entity '${ruleEntity}' in authorization rule ${i}`)\n }\n\n if (!entityRules[ruleEntity]) {\n entityRules[ruleEntity] = []\n }\n entityRules[ruleEntity].push(newRule)\n }\n }\n\n for (const entityKey of Object.keys(app.platformatic.entities)) {\n const rules = entityRules[entityKey] || []\n const type = app.platformatic.entities[entityKey]\n\n // We have subscriptions!\n let userPropToFillForPublish\n const topicsWithoutChecks = false\n\n // mqtt\n // if (app.platformatic.mq) {\n // for (const rule of rules) {\n // const checks = rule.find?.checks\n // if (typeof checks !== 'object') {\n // topicsWithoutChecks = !!rule.find\n // continue\n // }\n // const keys = Object.keys(checks)\n // if (keys.length !== 1) {\n // throw new Error(`Subscription requires that the role \"${rule.role}\" has only one check in the find rule for entity \"${rule.entity}\"`)\n // }\n // const key = keys[0]\n\n // const val = typeof checks[key] === 'object' ? checks[key].eq : checks[key]\n // if (userPropToFillForPublish && userPropToFillForPublish.val !== val) {\n // throw new Error('Unable to configure subscriptions and authorization due to multiple check clauses in find')\n // }\n // userPropToFillForPublish = { key, val }\n // }\n // }\n\n if (userPropToFillForPublish && topicsWithoutChecks) {\n throw new Error(`Subscription for entity \"${entityKey}\" have conflictling rules across roles`)\n }\n\n // MUST set this after doing the security checks on the subscriptions\n if (adminSecret) {\n rules.push({\n role: PLT_ADMIN_ROLE,\n find: true,\n save: true,\n delete: true,\n updateMany: true\n })\n }\n\n // If we have `fields` in save rules, we need to check if all the not-nullable\n // fields are specified\n checkSaveMandatoryFieldsInRules(type, rules)\n\n function useOriginal(ctx: PlatformaticContext) {\n return !ctx\n }\n\n app.platformatic.addEntityHooks(entityKey, {\n async find(originalFind, { where, ctx, fields, ...restOpts } = {}) {\n if (useOriginal(ctx)) {\n return originalFind({ ...restOpts, where, ctx, fields })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n checkFieldsFromRule(rule.find, fields || Object.keys(app.platformatic.entities[entityKey].fields))\n where = await fromRuleToWhere(ctx, rule.find, where, request.user)\n\n return originalFind({ ...restOpts, where, ctx, fields })\n },\n async save(originalSave, { input, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalSave({ ctx, input, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n if (!rule.save) {\n throw new Unauthorized()\n }\n checkFieldsFromRule(rule.save, fields)\n checkInputFromRuleFields(rule.save, input)\n\n if (rule.defaults) {\n for (const key of Object.keys(rule.defaults)) {\n const defaults = rule.defaults[key]\n if (typeof defaults === 'function') {\n input[key] = await defaults({ user: request.user, ctx, input })\n } else {\n input[key] = request.user[defaults]\n }\n }\n }\n\n const hasAllPrimaryKeys = input[type.primaryKey] !== undefined;\n const whereConditions = {}\n whereConditions[type.primaryKey] = { eq: input[type.primaryKey] }\n\n if (hasAllPrimaryKeys) {\n const where = await fromRuleToWhere(ctx, rule.save, whereConditions, request.user)\n\n const found = await type.find({\n where,\n ctx,\n fields,\n })\n\n if (found.length === 0) {\n throw new Unauthorized()\n }\n\n return originalSave({ input, ctx, fields, ...restOpts })\n }\n\n return originalSave({ input, ctx, fields, ...restOpts })\n },\n\n async insert(originalInsert, { inputs, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalInsert({ inputs, ctx, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n if (!rule.save) {\n throw new Unauthorized()\n }\n\n checkFieldsFromRule(rule.save, fields)\n checkInputFromRuleFields(rule.save, inputs)\n\n /* istanbul ignore else */\n if (rule.defaults) {\n for (const input of inputs) {\n for (const key of Object.keys(rule.defaults)) {\n const defaults = rule.defaults[key]\n if (typeof defaults === 'function') {\n input[key] = await defaults({ user: request.user, ctx, input })\n } else {\n input[key] = request.user[defaults]\n }\n }\n }\n }\n\n return originalInsert({ inputs, ctx, fields, ...restOpts })\n },\n\n async delete(originalDelete, { where, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalDelete({ where, ctx, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n where = await fromRuleToWhere(ctx, rule.delete, where, request.user)\n\n return originalDelete({ where, ctx, fields, ...restOpts })\n },\n\n async updateMany(originalUpdateMany, { where, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalUpdateMany({ ...restOpts, where, ctx, fields })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n where = await fromRuleToWhere(ctx, rule.updateMany, where, request.user)\n\n return originalUpdateMany({ ...restOpts, where, ctx, fields })\n },\n })\n }\n })\n}, { name: '@albirex/platformatic-logto' });\n\nasync function fromRuleToWhere(ctx: PlatformaticContext, rule, where, user) {\n if (!rule) {\n throw new Unauthorized()\n }\n const request = getRequestFromContext(ctx)\n /* istanbul ignore next */\n where = where || {}\n\n if (typeof rule === 'object') {\n const { checks } = rule\n\n /* istanbul ignore else */\n if (checks) {\n for (const key of Object.keys(checks)) {\n const clauses = checks[key]\n if (typeof clauses === 'string') {\n // case: \"userId\": \"X-PLATFORMATIC-USER-ID\"\n where[key] = {\n eq: request.user[clauses],\n }\n } else {\n // case:\n // userId: {\n // eq: 'X-PLATFORMATIC-USER-ID'\n // }\n for (const clauseKey of Object.keys(clauses)) {\n const clause = clauses[clauseKey]\n where[key] = {\n [clauseKey]: request.user[clause],\n }\n }\n }\n }\n }\n } else if (typeof rule === 'function') {\n where = await rule({ user, ctx, where })\n }\n return where\n}\n\nexport async function findRuleForRequestUser(ctx: PlatformaticContext, rules: PlatformaticRule[], roleKey: string, anonymousRole: string, isRolePath = false) {\n const request = getRequestFromContext(ctx)\n await request.setupDBAuthorizationUser()\n const roles = getRoles(request, roleKey, anonymousRole, isRolePath)\n const rule = findRule(rules, roles)\n if (!rule) {\n ctx.reply.request.log.warn({ roles, rules }, 'no rule for roles')\n throw new Unauthorized()\n }\n ctx.reply.request.log.trace({ roles, rule }, 'found rule')\n return rule\n}\n\nexport function checkFieldsFromRule(rule, fields) {\n if (!rule) {\n throw new Unauthorized()\n }\n const { fields: fieldsFromRule } = rule\n /* istanbul ignore else */\n if (fieldsFromRule) {\n for (const field of fields) {\n if (!fieldsFromRule.includes(field)) {\n throw new UnauthorizedField(field)\n }\n }\n }\n}\n\nconst validateInputs = (inputs, fieldsFromRule) => {\n for (const input of inputs) {\n const inputFields = Object.keys(input)\n for (const inputField of inputFields) {\n if (!fieldsFromRule.includes(inputField)) {\n throw new UnauthorizedField(inputField)\n }\n }\n }\n}\n\nfunction checkInputFromRuleFields(rule, inputs) {\n const { fields: fieldsFromRule } = rule\n /* istanbul ignore else */\n if (fieldsFromRule) {\n if (!Array.isArray(inputs)) {\n // save\n validateInputs([inputs], fieldsFromRule)\n } else {\n // insert\n validateInputs(inputs, fieldsFromRule)\n }\n }\n}\n\nfunction checkSaveMandatoryFieldsInRules(type: Entity, rules) {\n // List of not nullable, not PKs field to validate save/insert when allowed fields are specified on the rule\n const mandatoryFields =\n Object.values(type.fields)\n .filter(k => (!k.isNullable && !k.primaryKey))\n .map(({ camelcase }) => (camelcase))\n\n for (const rule of rules) {\n const { entity, save } = rule\n if (save && save.fields) {\n const fields = save.fields\n for (const mField of mandatoryFields) {\n if (!fields.includes(mField)) {\n throw new MissingNotNullableError(mField, entity)\n }\n }\n }\n }\n}\n\n/**\n * Check the permissions version\n * @throws PermissionsOutdated if versions don't match\n */\nasync function checkPermissionsVersion(app: FastifyInstance, opts: PlatformaticLogtoAuthOptions, user = null) {\n\n if (!opts.enableTokenVersionCheck || !opts.redis || !app.redis || !user) {\n return;\n }\n\n const sessionVersionKey = opts.sessionVersionKey || 'version'\n const tokenVersion = user?.[sessionVersionKey];\n const userId = user?.sub;\n\n try {\n const redisKey = `permissions:version:${userId}`;\n const currentVersionStr = await app.redis.get(redisKey);\n\n if (currentVersionStr === null) {\n await app.redis.set(redisKey, tokenVersion.toString());\n app.log.debug({ userId, version: tokenVersion }, 'Initialized permissions version in Redis');\n return;\n }\n\n const currentVersion = parseInt(currentVersionStr, 10);\n\n // Compare versions\n if (currentVersion !== tokenVersion) {\n app.log.warn({\n userId,\n tokenVersion,\n currentVersion\n }, 'Permissions version mismatch detected');\n throw new PermissionsOutdated();\n }\n\n app.log.trace({ userId, version: tokenVersion }, 'Token version check passed');\n } catch (error) {\n if (error.name === 'FastifyError' && error.code === 'PLT_DB_AUTH_VERSION_OUTDATED') {\n throw error;\n }\n app.log.error({ err: error, userId }, 'Error checking token version');\n }\n}\n\nexport default platformaticLogto;\n\ndeclare module 'fastify' {\n interface FastifyInstance {\n platformaticLogTo: {\n opts: PlatformaticLogtoAuthOptions,\n rules?: PlatformaticRule[]\n }\n }\n}","'use strict'\n\nimport { PlatformaticRule } from '../index.js'\n\nfunction findRule(rules: PlatformaticRule[], roles: string[]) {\n let found = null\n for (const rule of rules) {\n for (const role of roles) {\n if (rule.role === role) {\n found = rule\n break\n }\n }\n if (found) {\n break\n }\n }\n return found\n}\n\nexport default findRule\n","'use strict'\n\nimport createError from '@fastify/error'\n\nconst ERROR_PREFIX = 'PLT_DB_AUTH'\n\nexport const Unauthorized = createError(`${ERROR_PREFIX}_UNAUTHORIZED`, 'operation not allowed', 401)\nexport const UnauthorizedField = createError(`${ERROR_PREFIX}_FIELD_UNAUTHORIZED`, 'field not allowed: %s', 401)\nexport const MissingNotNullableError = createError(`${ERROR_PREFIX}_NOT_NULLABLE_MISSING`, 'missing not nullable field: \"%s\" in save rule for entity \"%s\"')\nexport const PermissionsOutdated = createError(`${ERROR_PREFIX}_VERSION_OUTDATED`, 'Verision has been updated. Please logout and login again.', 403)\n","'use strict'\n\nimport type { FastifyInstance } from 'fastify'\n\n/**\n * Increment the permissions version\n * @param app - Fastify instance with Redis client and Logto\n * @param userId - User ID\n * @returns New version number\n */\nexport async function incrementPermissionsVersion(app: FastifyInstance, userId: string): Promise<number> {\n if (!app.logto) {\n throw new Error('Logto client not available')\n }\n\n const userResp = await app.logto.callAPI(`/api/users/${userId}`, 'GET')\n const userData = await userResp.json()\n const existingCustomData = userData.customData || {}\n const currentVersion = existingCustomData.sessionVersion || 0\n const newVersion = currentVersion + 1\n\n await app.logto.callAPI(`/api/users/${userId}`, 'PATCH', JSON.stringify({ customData: { ...existingCustomData, sessionVersion: newVersion } }))\n\n if (app.redis) {\n const redisKey = `permissions:version:${userId}`\n await app.redis.set(redisKey, newVersion.toString())\n }\n\n return newVersion\n}\n\n/**\n * Delete the permissions version for a user\n * @param app - Fastify instance with Redis client\n * @param userId - User ID\n */\nexport async function deletePermissionsVersion(app: FastifyInstance, userId: string): Promise<void> {\n if (!app.redis) {\n throw new Error('Redis client not available')\n }\n\n const redisKey = `permissions:version:${userId}`\n await app.redis.del(redisKey)\n}\n\n","'use strict'\n\nexport function getRequestFromContext (ctx) {\n if (ctx && !ctx.reply) {\n throw new Error('Missing reply in context. You should call this function with { ctx: { reply }}')\n }\n return ctx.reply.request\n}\n\nexport function getRoles (request, roleKey, anonymousRole, isRolePath = false) {\n let output = []\n const user = request.user\n if (!user) {\n output.push(anonymousRole)\n return output\n }\n\n let rolesRaw\n if (isRolePath) {\n const roleKeys = roleKey.split('.')\n rolesRaw = user\n for (const key of roleKeys) {\n rolesRaw = rolesRaw[key]\n }\n } else {\n rolesRaw = user[roleKey]\n }\n\n if (typeof rolesRaw === 'string') {\n output = rolesRaw.split(',')\n } else if (Array.isArray(rolesRaw)) {\n output = rolesRaw\n }\n if (output.length === 0) {\n output.push(anonymousRole)\n }\n\n return output\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAAe;AACf,kBAA6B;;;ACG7B,SAAS,SAAS,OAA2B,OAAiB;AAC5D,MAAI,QAAQ;AACZ,aAAW,QAAQ,OAAO;AACxB,eAAW,QAAQ,OAA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,IAAI,SAAS,CAAC,MAAM;AACjE;AAAA,EACR;AAEA,QAAM,oBAAoB,KAAK,qBAAqB;AACpD,QAAM,eAAe,OAAO,iBAAiB;AAC7C,QAAM,SAAS,MAAM;AAErB,MAAI;AACA,UAAM,WAAW,uBAAuB,MAAM;AAC9C,UAAM,oBAAoB,MAAM,IAAI,MAAM,IAAI,QAAQ;AAEtD,QAAI,sBAAsB,MAAM;AAC5B,YAAM,IAAI,MAAM,IAAI,UAAU,aAAa,SAAS,CAAC;AACrD,UAAI,IAAI,MAAM,EAAE,QAAQ,SAAS,aAAa,GAAG,0CAA0C;AAC3F;AAAA,IACJ;AAEA,UAAM,iBAAiB,SAAS,mBAAmB,EAAE;AAGrD,QAAI,mBAAmB,cAAc;AACjC,UAAI,IAAI,KAAK;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,MACJ,GAAG,uCAAuC;AAC1C,YAAM,IAAI,oBAAoB;AAAA,IAClC;AAEA,QAAI,IAAI,MAAM,EAAE,QAAQ,SAAS,aAAa,GAAG,4BAA4B;AAAA,EACjF,SAAS,OAAO;AACZ,QAAI,MAAM,SAAS,kBAAkB,MAAM,SAAS,gCAAgC;AAChF,YAAM;AAAA,IACV;AACA,QAAI,IAAI,MAAM,EAAE,KAAK,OAAO,OAAO,GAAG,8BAA8B;AAAA,EACxE;AACJ;AAEA,IAAO,gBAAQ;","names":["createError","import_fastify_logto","fp","fastifyRedis","fastifyLogto"]}
|
package/lib/index.d.cts
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
|
-
import { FastifyPluginAsync } from 'fastify';
|
|
1
|
+
import { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
|
2
2
|
import { FastifyUserPluginOptions } from 'fastify-user';
|
|
3
3
|
import { PlatformaticContext } from '@platformatic/sql-mapper';
|
|
4
4
|
export { fastifyLogto } from '@albirex/fastify-logto';
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Increment the permissions version
|
|
8
|
+
* @param app - Fastify instance with Redis client and Logto
|
|
9
|
+
* @param userId - User ID
|
|
10
|
+
* @returns New version number
|
|
11
|
+
*/
|
|
12
|
+
declare function incrementPermissionsVersion(app: FastifyInstance, userId: string): Promise<number>;
|
|
13
|
+
/**
|
|
14
|
+
* Delete the permissions version for a user
|
|
15
|
+
* @param app - Fastify instance with Redis client
|
|
16
|
+
* @param userId - User ID
|
|
17
|
+
*/
|
|
18
|
+
declare function deletePermissionsVersion(app: FastifyInstance, userId: string): Promise<void>;
|
|
19
|
+
|
|
6
20
|
declare function getRequestFromContext(ctx: any): any;
|
|
7
21
|
declare function getRoles(request: any, roleKey: any, anonymousRole: any, isRolePath?: boolean): any[];
|
|
8
22
|
|
|
@@ -17,6 +31,13 @@ type PlatformaticRule = {
|
|
|
17
31
|
delete?: boolean;
|
|
18
32
|
[action: string]: unknown;
|
|
19
33
|
};
|
|
34
|
+
type RedisConfig = {
|
|
35
|
+
host?: string;
|
|
36
|
+
port?: number;
|
|
37
|
+
password?: string;
|
|
38
|
+
username?: string;
|
|
39
|
+
db?: number;
|
|
40
|
+
};
|
|
20
41
|
type PlatformaticLogtoAuthOptions = {
|
|
21
42
|
logtoBaseUrl?: string;
|
|
22
43
|
logtoAppId?: string;
|
|
@@ -31,6 +52,9 @@ type PlatformaticLogtoAuthOptions = {
|
|
|
31
52
|
checks?: boolean;
|
|
32
53
|
defaults?: boolean;
|
|
33
54
|
jwtPlugin: FastifyUserPluginOptions;
|
|
55
|
+
redis?: RedisConfig;
|
|
56
|
+
enableTokenVersionCheck?: boolean;
|
|
57
|
+
sessionVersionKey?: string;
|
|
34
58
|
};
|
|
35
59
|
declare const platformaticLogto: FastifyPluginAsync<PlatformaticLogtoAuthOptions>;
|
|
36
60
|
declare function findRuleForRequestUser(ctx: PlatformaticContext, rules: PlatformaticRule[], roleKey: string, anonymousRole: string, isRolePath?: boolean): Promise<any>;
|
|
@@ -45,4 +69,4 @@ declare module 'fastify' {
|
|
|
45
69
|
}
|
|
46
70
|
}
|
|
47
71
|
|
|
48
|
-
export { type PlatformaticLogtoAuthOptions, type PlatformaticRule, checkFieldsFromRule, platformaticLogto as default, findRuleForRequestUser, getRequestFromContext, getRoles, platformaticLogto };
|
|
72
|
+
export { type PlatformaticLogtoAuthOptions, type PlatformaticRule, type RedisConfig, checkFieldsFromRule, platformaticLogto as default, deletePermissionsVersion, findRuleForRequestUser, getRequestFromContext, getRoles, incrementPermissionsVersion, platformaticLogto };
|
package/lib/index.d.ts
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
|
-
import { FastifyPluginAsync } from 'fastify';
|
|
1
|
+
import { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
|
2
2
|
import { FastifyUserPluginOptions } from 'fastify-user';
|
|
3
3
|
import { PlatformaticContext } from '@platformatic/sql-mapper';
|
|
4
4
|
export { fastifyLogto } from '@albirex/fastify-logto';
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Increment the permissions version
|
|
8
|
+
* @param app - Fastify instance with Redis client and Logto
|
|
9
|
+
* @param userId - User ID
|
|
10
|
+
* @returns New version number
|
|
11
|
+
*/
|
|
12
|
+
declare function incrementPermissionsVersion(app: FastifyInstance, userId: string): Promise<number>;
|
|
13
|
+
/**
|
|
14
|
+
* Delete the permissions version for a user
|
|
15
|
+
* @param app - Fastify instance with Redis client
|
|
16
|
+
* @param userId - User ID
|
|
17
|
+
*/
|
|
18
|
+
declare function deletePermissionsVersion(app: FastifyInstance, userId: string): Promise<void>;
|
|
19
|
+
|
|
6
20
|
declare function getRequestFromContext(ctx: any): any;
|
|
7
21
|
declare function getRoles(request: any, roleKey: any, anonymousRole: any, isRolePath?: boolean): any[];
|
|
8
22
|
|
|
@@ -17,6 +31,13 @@ type PlatformaticRule = {
|
|
|
17
31
|
delete?: boolean;
|
|
18
32
|
[action: string]: unknown;
|
|
19
33
|
};
|
|
34
|
+
type RedisConfig = {
|
|
35
|
+
host?: string;
|
|
36
|
+
port?: number;
|
|
37
|
+
password?: string;
|
|
38
|
+
username?: string;
|
|
39
|
+
db?: number;
|
|
40
|
+
};
|
|
20
41
|
type PlatformaticLogtoAuthOptions = {
|
|
21
42
|
logtoBaseUrl?: string;
|
|
22
43
|
logtoAppId?: string;
|
|
@@ -31,6 +52,9 @@ type PlatformaticLogtoAuthOptions = {
|
|
|
31
52
|
checks?: boolean;
|
|
32
53
|
defaults?: boolean;
|
|
33
54
|
jwtPlugin: FastifyUserPluginOptions;
|
|
55
|
+
redis?: RedisConfig;
|
|
56
|
+
enableTokenVersionCheck?: boolean;
|
|
57
|
+
sessionVersionKey?: string;
|
|
34
58
|
};
|
|
35
59
|
declare const platformaticLogto: FastifyPluginAsync<PlatformaticLogtoAuthOptions>;
|
|
36
60
|
declare function findRuleForRequestUser(ctx: PlatformaticContext, rules: PlatformaticRule[], roleKey: string, anonymousRole: string, isRolePath?: boolean): Promise<any>;
|
|
@@ -45,4 +69,4 @@ declare module 'fastify' {
|
|
|
45
69
|
}
|
|
46
70
|
}
|
|
47
71
|
|
|
48
|
-
export { type PlatformaticLogtoAuthOptions, type PlatformaticRule, checkFieldsFromRule, platformaticLogto as default, findRuleForRequestUser, getRequestFromContext, getRoles, platformaticLogto };
|
|
72
|
+
export { type PlatformaticLogtoAuthOptions, type PlatformaticRule, type RedisConfig, checkFieldsFromRule, platformaticLogto as default, deletePermissionsVersion, findRuleForRequestUser, getRequestFromContext, getRoles, incrementPermissionsVersion, platformaticLogto };
|
package/lib/index.js
CHANGED
|
@@ -26,11 +26,38 @@ var ERROR_PREFIX = "PLT_DB_AUTH";
|
|
|
26
26
|
var Unauthorized = createError(`${ERROR_PREFIX}_UNAUTHORIZED`, "operation not allowed", 401);
|
|
27
27
|
var UnauthorizedField = createError(`${ERROR_PREFIX}_FIELD_UNAUTHORIZED`, "field not allowed: %s", 401);
|
|
28
28
|
var MissingNotNullableError = createError(`${ERROR_PREFIX}_NOT_NULLABLE_MISSING`, 'missing not nullable field: "%s" in save rule for entity "%s"');
|
|
29
|
+
var PermissionsOutdated = createError(`${ERROR_PREFIX}_VERSION_OUTDATED`, "Verision has been updated. Please logout and login again.", 403);
|
|
29
30
|
|
|
30
31
|
// src/index.ts
|
|
31
32
|
import fastifyLogto from "@albirex/fastify-logto";
|
|
33
|
+
import fastifyRedis from "@fastify/redis";
|
|
32
34
|
import { fastifyLogto as fastifyLogto2 } from "@albirex/fastify-logto";
|
|
33
35
|
|
|
36
|
+
// src/utils/permissions-version.ts
|
|
37
|
+
async function incrementPermissionsVersion(app, userId) {
|
|
38
|
+
if (!app.logto) {
|
|
39
|
+
throw new Error("Logto client not available");
|
|
40
|
+
}
|
|
41
|
+
const userResp = await app.logto.callAPI(`/api/users/${userId}`, "GET");
|
|
42
|
+
const userData = await userResp.json();
|
|
43
|
+
const existingCustomData = userData.customData || {};
|
|
44
|
+
const currentVersion = existingCustomData.sessionVersion || 0;
|
|
45
|
+
const newVersion = currentVersion + 1;
|
|
46
|
+
await app.logto.callAPI(`/api/users/${userId}`, "PATCH", JSON.stringify({ customData: { ...existingCustomData, sessionVersion: newVersion } }));
|
|
47
|
+
if (app.redis) {
|
|
48
|
+
const redisKey = `permissions:version:${userId}`;
|
|
49
|
+
await app.redis.set(redisKey, newVersion.toString());
|
|
50
|
+
}
|
|
51
|
+
return newVersion;
|
|
52
|
+
}
|
|
53
|
+
async function deletePermissionsVersion(app, userId) {
|
|
54
|
+
if (!app.redis) {
|
|
55
|
+
throw new Error("Redis client not available");
|
|
56
|
+
}
|
|
57
|
+
const redisKey = `permissions:version:${userId}`;
|
|
58
|
+
await app.redis.del(redisKey);
|
|
59
|
+
}
|
|
60
|
+
|
|
34
61
|
// src/utils/utils.ts
|
|
35
62
|
function getRequestFromContext(ctx) {
|
|
36
63
|
if (ctx && !ctx.reply) {
|
|
@@ -72,6 +99,16 @@ var platformaticLogto = fp(async (app, opts) => {
|
|
|
72
99
|
app.decorate("platformaticLogTo", {
|
|
73
100
|
opts
|
|
74
101
|
});
|
|
102
|
+
if (opts.redis) {
|
|
103
|
+
await app.register(fastifyRedis, {
|
|
104
|
+
host: opts.redis.host || "127.0.0.1",
|
|
105
|
+
port: opts.redis.port || 6379,
|
|
106
|
+
password: opts.redis.password,
|
|
107
|
+
username: opts.redis.username,
|
|
108
|
+
db: opts.redis.db || 0
|
|
109
|
+
});
|
|
110
|
+
app.log.info("Redis client registered for permissions version check");
|
|
111
|
+
}
|
|
75
112
|
app.register(fastifyLogto, {
|
|
76
113
|
endpoint: opts.logtoBaseUrl || "https://auth.example.com",
|
|
77
114
|
appId: opts.logtoAppId || "your-app-id",
|
|
@@ -198,6 +235,8 @@ var platformaticLogto = fp(async (app, opts) => {
|
|
|
198
235
|
}
|
|
199
236
|
});
|
|
200
237
|
}
|
|
238
|
+
} else {
|
|
239
|
+
await checkPermissionsVersion(app, opts, this.user);
|
|
201
240
|
}
|
|
202
241
|
if (forceAdminRole) {
|
|
203
242
|
this.user = {
|
|
@@ -437,14 +476,48 @@ function checkSaveMandatoryFieldsInRules(type, rules) {
|
|
|
437
476
|
}
|
|
438
477
|
}
|
|
439
478
|
}
|
|
479
|
+
async function checkPermissionsVersion(app, opts, user = null) {
|
|
480
|
+
if (!opts.enableTokenVersionCheck || !opts.redis || !app.redis || !user) {
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const sessionVersionKey = opts.sessionVersionKey || "version";
|
|
484
|
+
const tokenVersion = user?.[sessionVersionKey];
|
|
485
|
+
const userId = user?.sub;
|
|
486
|
+
try {
|
|
487
|
+
const redisKey = `permissions:version:${userId}`;
|
|
488
|
+
const currentVersionStr = await app.redis.get(redisKey);
|
|
489
|
+
if (currentVersionStr === null) {
|
|
490
|
+
await app.redis.set(redisKey, tokenVersion.toString());
|
|
491
|
+
app.log.debug({ userId, version: tokenVersion }, "Initialized permissions version in Redis");
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
const currentVersion = parseInt(currentVersionStr, 10);
|
|
495
|
+
if (currentVersion !== tokenVersion) {
|
|
496
|
+
app.log.warn({
|
|
497
|
+
userId,
|
|
498
|
+
tokenVersion,
|
|
499
|
+
currentVersion
|
|
500
|
+
}, "Permissions version mismatch detected");
|
|
501
|
+
throw new PermissionsOutdated();
|
|
502
|
+
}
|
|
503
|
+
app.log.trace({ userId, version: tokenVersion }, "Token version check passed");
|
|
504
|
+
} catch (error) {
|
|
505
|
+
if (error.name === "FastifyError" && error.code === "PLT_DB_AUTH_VERSION_OUTDATED") {
|
|
506
|
+
throw error;
|
|
507
|
+
}
|
|
508
|
+
app.log.error({ err: error, userId }, "Error checking token version");
|
|
509
|
+
}
|
|
510
|
+
}
|
|
440
511
|
var index_default = platformaticLogto;
|
|
441
512
|
export {
|
|
442
513
|
checkFieldsFromRule,
|
|
443
514
|
index_default as default,
|
|
515
|
+
deletePermissionsVersion,
|
|
444
516
|
fastifyLogto2 as fastifyLogto,
|
|
445
517
|
findRuleForRequestUser,
|
|
446
518
|
getRequestFromContext,
|
|
447
519
|
getRoles,
|
|
520
|
+
incrementPermissionsVersion,
|
|
448
521
|
platformaticLogto
|
|
449
522
|
};
|
|
450
523
|
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/utils/find-rule.ts","../src/utils/errors.ts","../src/utils/utils.ts"],"sourcesContent":["import fp from 'fastify-plugin'\nimport * as fastifyUser from 'fastify-user'\n\nimport findRule from './utils/find-rule.js'\nimport { Unauthorized, UnauthorizedField, MissingNotNullableError } from './utils/errors.js'\nimport fastifyLogto from '@albirex/fastify-logto';\nimport { FastifyInstance, FastifyPluginAsync } from 'fastify'\nimport type { FastifyUserPluginOptions } from 'fastify-user';\nimport type { Entity, PlatformaticContext } from '@platformatic/sql-mapper'\nexport { fastifyLogto } from '@albirex/fastify-logto';\n\nimport { getRequestFromContext, getRoles } from './utils/utils.js'\nexport { getRequestFromContext, getRoles } from './utils/utils.js'\n\nconst PLT_ADMIN_ROLE = 'platformatic-admin'\n\nexport type PlatformaticRule = {\n role: string;\n entity?: string;\n entities?: string[];\n defaults?: Record<string, string>;\n checks?: boolean;\n find?: boolean;\n save?: boolean;\n delete?: boolean;\n [action: string]: unknown;\n};\n\nexport type PlatformaticLogtoAuthOptions = {\n logtoBaseUrl?: string;\n logtoAppId?: string;\n logtoAppSecret?: string;\n adminSecret?: string;\n rolePath?: string;\n roleKey?: string;\n userPath?: string;\n userKey?: string;\n anonymousRole?: string;\n allowAnonymous?: boolean;\n checks?: boolean;\n defaults?: boolean;\n jwtPlugin: FastifyUserPluginOptions\n};\n\nexport const platformaticLogto: FastifyPluginAsync<PlatformaticLogtoAuthOptions> = fp(async (app: FastifyInstance, opts: PlatformaticLogtoAuthOptions) => {\n app.decorate('platformaticLogTo', {\n opts\n })\n\n app.register(fastifyLogto, {\n endpoint: opts.logtoBaseUrl || 'https://auth.example.com',\n appId: opts.logtoAppId || 'your-app-id',\n appSecret: opts.logtoAppSecret || 'your-app-secret',\n });\n\n await app.register(fastifyUser as unknown as FastifyPluginAsync, opts.jwtPlugin);\n\n const adminSecret = opts.adminSecret\n const roleKey = opts.rolePath || opts.roleKey || 'X-PLATFORMATIC-ROLE'\n const userKey = opts.userPath || opts.userKey || 'X-PLATFORMATIC-USER-ID'\n const isRolePath = !!opts.rolePath // if `true` the role is intepreted as path like `user.role`\n const anonymousRole = opts.anonymousRole || 'anonymous'\n\n async function composeLogToRules() {\n const rolesResp = await app.logto.callAPI('/api/roles?type=User', 'GET');\n\n if (!rolesResp.ok) {\n throw rolesResp;\n }\n\n const roles = await rolesResp.json();\n const rules: PlatformaticRule[] = [{\n role: anonymousRole,\n entities: Object.keys(app.platformatic.entities),\n find: opts.allowAnonymous,\n save: opts.allowAnonymous,\n delete: opts.allowAnonymous,\n }];\n\n for (const role of roles) {\n const scopesResp = await app.logto.callAPI(`/api/roles/${role.id}/scopes`, 'GET');\n\n if (!scopesResp.ok) {\n throw scopesResp;\n }\n\n const scopes = await scopesResp.json();\n\n for (const scope of scopes) {\n const roleName = role.name;\n // eslint-disable-next-line prefer-const\n let [scopeAction, entity] = scope.name.split(':');\n\n if (!app.platformatic.entities[entity]) {\n app.log.debug(`Unknown entity '${entity}' in authorization rule`)\n continue;\n }\n\n switch (scopeAction) {\n case 'create':\n scopeAction = 'save'\n break;\n case 'read':\n scopeAction = 'find'\n break;\n case 'update':\n scopeAction = 'updateMany'\n break;\n }\n\n const checkExists = rules.find(r => r.role === roleName && r.entity === entity);\n if (checkExists) {\n if (opts.checks) {\n checkExists[scopeAction] = {\n checks: {\n userId: userKey\n }\n };\n } else {\n checkExists[scopeAction] = true;\n }\n } else {\n const newRule: PlatformaticRule = {\n role: roleName,\n entity,\n };\n\n if (opts.checks) {\n newRule[scopeAction] = {\n checks: {\n userId: userKey\n }\n };\n } else {\n newRule[scopeAction] = true;\n }\n\n if (opts.defaults) {\n newRule.defaults = {\n userId: userKey\n };\n }\n\n rules.push(newRule);\n }\n }\n }\n\n const logRules = rules.reduce((prev, curr) => {\n (prev[curr['role']] ??= []).push(curr);\n return prev;\n }, {})\n\n for (const key in logRules) {\n app.log.info(`Rules set for role ${key}`);\n\n for (const element of logRules[key]) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { entity, entities, role, ...other } = element;\n app.log.info(`\\t${entity ?? entities.join(',')}: ${JSON.stringify(other)}`);\n }\n }\n\n const missingEntities = Object.keys(app.platformatic.entities).filter((e) => !rules.map((r) => r.entity).includes(e));\n\n if (missingEntities.length) {\n app.log.warn(`Missing rules for entities: ${missingEntities.join(', ')}`);\n }\n\n app.log.debug('LogTo calculated rules');\n app.log.debug(rules);\n return rules;\n }\n\n app.decorateRequest('setupDBAuthorizationUser', setupUser)\n\n async function setupUser() {\n // if (!adminSecret) {\n await this.extractUser()\n // }\n\n let forceAdminRole = false\n if (adminSecret && this.headers['x-platformatic-admin-secret'] === adminSecret) {\n if (opts.jwtPlugin.jwt) {\n forceAdminRole = true\n } else {\n this.log.info('admin secret is valid')\n this.user = new Proxy(this.headers, {\n get: (target, key) => {\n let value;\n if (!target[key.toString()]) {\n const newKey = key.toString().toLowerCase()\n value = target[newKey]\n } else {\n value = target[key.toString()]\n }\n\n if (!value && key.toString().toLowerCase() === roleKey.toLowerCase()) {\n value = PLT_ADMIN_ROLE\n }\n return value\n },\n })\n }\n }\n\n if (forceAdminRole) {\n // We replace just the role in `request.user`, all the rest is untouched\n this.user = {\n // ...request.user,\n [roleKey]: this.headers['x-platformatic-role'] ? [this.headers['x-platformatic-role']] : [PLT_ADMIN_ROLE]\n }\n }\n }\n\n app.addHook('onReady', async function () {\n const logToRules = await composeLogToRules();\n\n app.platformaticLogTo.rules = logToRules;\n\n // TODO validate that there is at most a rule for a given role\n const entityRules = {};\n for (let i = 0; i < logToRules.length; i++) {\n const rule = logToRules[i]\n\n let ruleEntities = null\n if (rule.entity) {\n ruleEntities = [rule.entity]\n } else if (rule.entities) {\n ruleEntities = [...rule.entities]\n } else {\n throw new Error(`Missing entity in authorization rule ${i}`)\n }\n\n for (const ruleEntity of ruleEntities) {\n const newRule = { ...rule, entity: ruleEntity, entities: undefined }\n if (!app.platformatic.entities[newRule.entity]) {\n throw new Error(`Unknown entity '${ruleEntity}' in authorization rule ${i}`)\n }\n\n if (!entityRules[ruleEntity]) {\n entityRules[ruleEntity] = []\n }\n entityRules[ruleEntity].push(newRule)\n }\n }\n\n for (const entityKey of Object.keys(app.platformatic.entities)) {\n const rules = entityRules[entityKey] || []\n const type = app.platformatic.entities[entityKey]\n\n // We have subscriptions!\n let userPropToFillForPublish\n const topicsWithoutChecks = false\n\n // mqtt\n // if (app.platformatic.mq) {\n // for (const rule of rules) {\n // const checks = rule.find?.checks\n // if (typeof checks !== 'object') {\n // topicsWithoutChecks = !!rule.find\n // continue\n // }\n // const keys = Object.keys(checks)\n // if (keys.length !== 1) {\n // throw new Error(`Subscription requires that the role \"${rule.role}\" has only one check in the find rule for entity \"${rule.entity}\"`)\n // }\n // const key = keys[0]\n\n // const val = typeof checks[key] === 'object' ? checks[key].eq : checks[key]\n // if (userPropToFillForPublish && userPropToFillForPublish.val !== val) {\n // throw new Error('Unable to configure subscriptions and authorization due to multiple check clauses in find')\n // }\n // userPropToFillForPublish = { key, val }\n // }\n // }\n\n if (userPropToFillForPublish && topicsWithoutChecks) {\n throw new Error(`Subscription for entity \"${entityKey}\" have conflictling rules across roles`)\n }\n\n // MUST set this after doing the security checks on the subscriptions\n if (adminSecret) {\n rules.push({\n role: PLT_ADMIN_ROLE,\n find: true,\n save: true,\n delete: true,\n updateMany: true\n })\n }\n\n // If we have `fields` in save rules, we need to check if all the not-nullable\n // fields are specified\n checkSaveMandatoryFieldsInRules(type, rules)\n\n function useOriginal(ctx: PlatformaticContext) {\n return !ctx\n }\n\n app.platformatic.addEntityHooks(entityKey, {\n async find(originalFind, { where, ctx, fields, ...restOpts } = {}) {\n if (useOriginal(ctx)) {\n return originalFind({ ...restOpts, where, ctx, fields })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n checkFieldsFromRule(rule.find, fields || Object.keys(app.platformatic.entities[entityKey].fields))\n where = await fromRuleToWhere(ctx, rule.find, where, request.user)\n\n return originalFind({ ...restOpts, where, ctx, fields })\n },\n async save(originalSave, { input, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalSave({ ctx, input, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n if (!rule.save) {\n throw new Unauthorized()\n }\n checkFieldsFromRule(rule.save, fields)\n checkInputFromRuleFields(rule.save, input)\n\n if (rule.defaults) {\n for (const key of Object.keys(rule.defaults)) {\n const defaults = rule.defaults[key]\n if (typeof defaults === 'function') {\n input[key] = await defaults({ user: request.user, ctx, input })\n } else {\n input[key] = request.user[defaults]\n }\n }\n }\n\n const hasAllPrimaryKeys = input[type.primaryKey] !== undefined;\n const whereConditions = {}\n whereConditions[type.primaryKey] = { eq: input[type.primaryKey] }\n\n if (hasAllPrimaryKeys) {\n const where = await fromRuleToWhere(ctx, rule.save, whereConditions, request.user)\n\n const found = await type.find({\n where,\n ctx,\n fields,\n })\n\n if (found.length === 0) {\n throw new Unauthorized()\n }\n\n return originalSave({ input, ctx, fields, ...restOpts })\n }\n\n return originalSave({ input, ctx, fields, ...restOpts })\n },\n\n async insert(originalInsert, { inputs, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalInsert({ inputs, ctx, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n if (!rule.save) {\n throw new Unauthorized()\n }\n\n checkFieldsFromRule(rule.save, fields)\n checkInputFromRuleFields(rule.save, inputs)\n\n /* istanbul ignore else */\n if (rule.defaults) {\n for (const input of inputs) {\n for (const key of Object.keys(rule.defaults)) {\n const defaults = rule.defaults[key]\n if (typeof defaults === 'function') {\n input[key] = await defaults({ user: request.user, ctx, input })\n } else {\n input[key] = request.user[defaults]\n }\n }\n }\n }\n\n return originalInsert({ inputs, ctx, fields, ...restOpts })\n },\n\n async delete(originalDelete, { where, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalDelete({ where, ctx, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n where = await fromRuleToWhere(ctx, rule.delete, where, request.user)\n\n return originalDelete({ where, ctx, fields, ...restOpts })\n },\n\n async updateMany(originalUpdateMany, { where, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalUpdateMany({ ...restOpts, where, ctx, fields })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n where = await fromRuleToWhere(ctx, rule.updateMany, where, request.user)\n\n return originalUpdateMany({ ...restOpts, where, ctx, fields })\n },\n })\n }\n })\n}, { name: '@albirex/platformatic-logto' });\n\nasync function fromRuleToWhere(ctx: PlatformaticContext, rule, where, user) {\n if (!rule) {\n throw new Unauthorized()\n }\n const request = getRequestFromContext(ctx)\n /* istanbul ignore next */\n where = where || {}\n\n if (typeof rule === 'object') {\n const { checks } = rule\n\n /* istanbul ignore else */\n if (checks) {\n for (const key of Object.keys(checks)) {\n const clauses = checks[key]\n if (typeof clauses === 'string') {\n // case: \"userId\": \"X-PLATFORMATIC-USER-ID\"\n where[key] = {\n eq: request.user[clauses],\n }\n } else {\n // case:\n // userId: {\n // eq: 'X-PLATFORMATIC-USER-ID'\n // }\n for (const clauseKey of Object.keys(clauses)) {\n const clause = clauses[clauseKey]\n where[key] = {\n [clauseKey]: request.user[clause],\n }\n }\n }\n }\n }\n } else if (typeof rule === 'function') {\n where = await rule({ user, ctx, where })\n }\n return where\n}\n\nexport async function findRuleForRequestUser(ctx: PlatformaticContext, rules: PlatformaticRule[], roleKey: string, anonymousRole: string, isRolePath = false) {\n const request = getRequestFromContext(ctx)\n await request.setupDBAuthorizationUser()\n const roles = getRoles(request, roleKey, anonymousRole, isRolePath)\n const rule = findRule(rules, roles)\n if (!rule) {\n ctx.reply.request.log.warn({ roles, rules }, 'no rule for roles')\n throw new Unauthorized()\n }\n ctx.reply.request.log.trace({ roles, rule }, 'found rule')\n return rule\n}\n\nexport function checkFieldsFromRule(rule, fields) {\n if (!rule) {\n throw new Unauthorized()\n }\n const { fields: fieldsFromRule } = rule\n /* istanbul ignore else */\n if (fieldsFromRule) {\n for (const field of fields) {\n if (!fieldsFromRule.includes(field)) {\n throw new UnauthorizedField(field)\n }\n }\n }\n}\n\nconst validateInputs = (inputs, fieldsFromRule) => {\n for (const input of inputs) {\n const inputFields = Object.keys(input)\n for (const inputField of inputFields) {\n if (!fieldsFromRule.includes(inputField)) {\n throw new UnauthorizedField(inputField)\n }\n }\n }\n}\n\nfunction checkInputFromRuleFields(rule, inputs) {\n const { fields: fieldsFromRule } = rule\n /* istanbul ignore else */\n if (fieldsFromRule) {\n if (!Array.isArray(inputs)) {\n // save\n validateInputs([inputs], fieldsFromRule)\n } else {\n // insert\n validateInputs(inputs, fieldsFromRule)\n }\n }\n}\n\nfunction checkSaveMandatoryFieldsInRules(type: Entity, rules) {\n // List of not nullable, not PKs field to validate save/insert when allowed fields are specified on the rule\n const mandatoryFields =\n Object.values(type.fields)\n .filter(k => (!k.isNullable && !k.primaryKey))\n .map(({ camelcase }) => (camelcase))\n\n for (const rule of rules) {\n const { entity, save } = rule\n if (save && save.fields) {\n const fields = save.fields\n for (const mField of mandatoryFields) {\n if (!fields.includes(mField)) {\n throw new MissingNotNullableError(mField, entity)\n }\n }\n }\n }\n}\n\nexport default platformaticLogto;\n\ndeclare module 'fastify' {\n interface FastifyInstance {\n platformaticLogTo: {\n opts: PlatformaticLogtoAuthOptions,\n rules?: PlatformaticRule[]\n }\n }\n}","'use strict'\n\nimport { PlatformaticRule } from '../index.js'\n\nfunction findRule(rules: PlatformaticRule[], roles: string[]) {\n let found = null\n for (const rule of rules) {\n for (const role of roles) {\n if (rule.role === role) {\n found = rule\n break\n }\n }\n if (found) {\n break\n }\n }\n return found\n}\n\nexport default findRule\n","'use strict'\n\nimport createError from '@fastify/error'\n\nconst ERROR_PREFIX = 'PLT_DB_AUTH'\n\nexport const Unauthorized = createError(`${ERROR_PREFIX}_UNAUTHORIZED`, 'operation not allowed', 401)\nexport const UnauthorizedField = createError(`${ERROR_PREFIX}_FIELD_UNAUTHORIZED`, 'field not allowed: %s', 401)\nexport const MissingNotNullableError = createError(`${ERROR_PREFIX}_NOT_NULLABLE_MISSING`, 'missing not nullable field: \"%s\" in save rule for entity \"%s\"')\n","'use strict'\n\nexport function getRequestFromContext (ctx) {\n if (ctx && !ctx.reply) {\n throw new Error('Missing reply in context. You should call this function with { ctx: { reply }}')\n }\n return ctx.reply.request\n}\n\nexport function getRoles (request, roleKey, anonymousRole, isRolePath = false) {\n let output = []\n const user = request.user\n if (!user) {\n output.push(anonymousRole)\n return output\n }\n\n let rolesRaw\n if (isRolePath) {\n const roleKeys = roleKey.split('.')\n rolesRaw = user\n for (const key of roleKeys) {\n rolesRaw = rolesRaw[key]\n }\n } else {\n rolesRaw = user[roleKey]\n }\n\n if (typeof rolesRaw === 'string') {\n output = rolesRaw.split(',')\n } else if (Array.isArray(rolesRaw)) {\n output = rolesRaw\n }\n if (output.length === 0) {\n output.push(anonymousRole)\n }\n\n return output\n}\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,YAAY,iBAAiB;;;ACG7B,SAAS,SAAS,OAA2B,OAAiB;AAC5D,MAAI,QAAQ;AACZ,aAAW,QAAQ,OAAO;AACxB,eAAW,QAAQ,OAAO;AACxB,UAAI,KAAK,SAAS,MAAM;AACtB,gBAAQ;AACR;AAAA,MACF;AAAA,IACF;AACA,QAAI,OAAO;AACT;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,IAAO,oBAAQ;;;AClBf,OAAO,iBAAiB;AAExB,IAAM,eAAe;AAEd,IAAM,eAAe,YAAY,GAAG,YAAY,iBAAiB,yBAAyB,GAAG;AAC7F,IAAM,oBAAoB,YAAY,GAAG,YAAY,uBAAuB,yBAAyB,GAAG;AACxG,IAAM,0BAA0B,YAAY,GAAG,YAAY,yBAAyB,+DAA+D;;;AFH1J,OAAO,kBAAkB;AAIzB,SAAS,gBAAAA,qBAAoB;;;AGPtB,SAAS,sBAAuB,KAAK;AAC1C,MAAI,OAAO,CAAC,IAAI,OAAO;AACrB,UAAM,IAAI,MAAM,gFAAgF;AAAA,EAClG;AACA,SAAO,IAAI,MAAM;AACnB;AAEO,SAAS,SAAU,SAAS,SAAS,eAAe,aAAa,OAAO;AAC7E,MAAI,SAAS,CAAC;AACd,QAAM,OAAO,QAAQ;AACrB,MAAI,CAAC,MAAM;AACT,WAAO,KAAK,aAAa;AACzB,WAAO;AAAA,EACT;AAEA,MAAI;AACJ,MAAI,YAAY;AACd,UAAM,WAAW,QAAQ,MAAM,GAAG;A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AAC,EAAE,UAAU,MAAO,SAAU;AAE3C,aAAW,QAAQ,OAAO;AACtB,UAAM,EAAE,QAAQ,KAAK,IAAI;AACzB,QAAI,QAAQ,KAAK,QAAQ;AACrB,YAAM,SAAS,KAAK;AACpB,iBAAW,UAAU,iBAAiB;AAClC,YAAI,CAAC,OAAO,SAAS,MAAM,GAAG;AAC1B,gBAAM,IAAI,wBAAwB,QAAQ,MAAM;AAAA,QACpD;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;AAEA,IAAO,gBAAQ;","names":["fastifyLogto"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/utils/find-rule.ts","../src/utils/errors.ts","../src/utils/permissions-version.ts","../src/utils/utils.ts"],"sourcesContent":["import fp from 'fastify-plugin'\nimport * as fastifyUser from 'fastify-user'\n\nimport findRule from './utils/find-rule.js'\nimport { Unauthorized, UnauthorizedField, MissingNotNullableError, PermissionsOutdated } from './utils/errors.js'\nimport fastifyLogto from '@albirex/fastify-logto';\nimport fastifyRedis from '@fastify/redis';\nimport { FastifyInstance, FastifyPluginAsync } from 'fastify'\nimport type { FastifyUserPluginOptions } from 'fastify-user';\nimport type { Entity, PlatformaticContext } from '@platformatic/sql-mapper'\n\nexport { fastifyLogto } from '@albirex/fastify-logto';\nexport { incrementPermissionsVersion, deletePermissionsVersion } from './utils/permissions-version.js';\n\nimport { getRequestFromContext, getRoles } from './utils/utils.js'\nexport { getRequestFromContext, getRoles } from './utils/utils.js'\n\nconst PLT_ADMIN_ROLE = 'platformatic-admin'\n\nexport type PlatformaticRule = {\n role: string;\n entity?: string;\n entities?: string[];\n defaults?: Record<string, string>;\n checks?: boolean;\n find?: boolean;\n save?: boolean;\n delete?: boolean;\n [action: string]: unknown;\n};\n\nexport type RedisConfig = {\n host?: string;\n port?: number;\n password?: string;\n username?: string;\n db?: number;\n};\n\nexport type PlatformaticLogtoAuthOptions = {\n logtoBaseUrl?: string;\n logtoAppId?: string;\n logtoAppSecret?: string;\n adminSecret?: string;\n rolePath?: string;\n roleKey?: string;\n userPath?: string;\n userKey?: string;\n anonymousRole?: string;\n allowAnonymous?: boolean;\n checks?: boolean;\n defaults?: boolean;\n jwtPlugin: FastifyUserPluginOptions;\n redis?: RedisConfig;\n enableTokenVersionCheck?: boolean;\n sessionVersionKey?: string;\n};\n\nexport const platformaticLogto: FastifyPluginAsync<PlatformaticLogtoAuthOptions> = fp(async (app: FastifyInstance, opts: PlatformaticLogtoAuthOptions) => {\n app.decorate('platformaticLogTo', {\n opts\n })\n\n // Register Redis if configured\n if (opts.redis) {\n await app.register(fastifyRedis, {\n host: opts.redis.host || '127.0.0.1',\n port: opts.redis.port || 6379,\n password: opts.redis.password,\n username: opts.redis.username,\n db: opts.redis.db || 0,\n });\n app.log.info('Redis client registered for permissions version check');\n }\n\n app.register(fastifyLogto, {\n endpoint: opts.logtoBaseUrl || 'https://auth.example.com',\n appId: opts.logtoAppId || 'your-app-id',\n appSecret: opts.logtoAppSecret || 'your-app-secret',\n });\n\n await app.register(fastifyUser as unknown as FastifyPluginAsync, opts.jwtPlugin);\n\n const adminSecret = opts.adminSecret\n const roleKey = opts.rolePath || opts.roleKey || 'X-PLATFORMATIC-ROLE'\n const userKey = opts.userPath || opts.userKey || 'X-PLATFORMATIC-USER-ID'\n const isRolePath = !!opts.rolePath // if `true` the role is intepreted as path like `user.role`\n const anonymousRole = opts.anonymousRole || 'anonymous'\n\n async function composeLogToRules() {\n const rolesResp = await app.logto.callAPI('/api/roles?type=User', 'GET');\n\n if (!rolesResp.ok) {\n throw rolesResp;\n }\n\n const roles = await rolesResp.json();\n const rules: PlatformaticRule[] = [{\n role: anonymousRole,\n entities: Object.keys(app.platformatic.entities),\n find: opts.allowAnonymous,\n save: opts.allowAnonymous,\n delete: opts.allowAnonymous,\n }];\n\n for (const role of roles) {\n const scopesResp = await app.logto.callAPI(`/api/roles/${role.id}/scopes`, 'GET');\n\n if (!scopesResp.ok) {\n throw scopesResp;\n }\n\n const scopes = await scopesResp.json();\n\n for (const scope of scopes) {\n const roleName = role.name;\n // eslint-disable-next-line prefer-const\n let [scopeAction, entity] = scope.name.split(':');\n\n if (!app.platformatic.entities[entity]) {\n app.log.debug(`Unknown entity '${entity}' in authorization rule`)\n continue;\n }\n\n switch (scopeAction) {\n case 'create':\n scopeAction = 'save'\n break;\n case 'read':\n scopeAction = 'find'\n break;\n case 'update':\n scopeAction = 'updateMany'\n break;\n }\n\n const checkExists = rules.find(r => r.role === roleName && r.entity === entity);\n if (checkExists) {\n if (opts.checks) {\n checkExists[scopeAction] = {\n checks: {\n userId: userKey\n }\n };\n } else {\n checkExists[scopeAction] = true;\n }\n } else {\n const newRule: PlatformaticRule = {\n role: roleName,\n entity,\n };\n\n if (opts.checks) {\n newRule[scopeAction] = {\n checks: {\n userId: userKey\n }\n };\n } else {\n newRule[scopeAction] = true;\n }\n\n if (opts.defaults) {\n newRule.defaults = {\n userId: userKey\n };\n }\n\n rules.push(newRule);\n }\n }\n }\n\n const logRules = rules.reduce((prev, curr) => {\n (prev[curr['role']] ??= []).push(curr);\n return prev;\n }, {})\n\n for (const key in logRules) {\n app.log.info(`Rules set for role ${key}`);\n\n for (const element of logRules[key]) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { entity, entities, role, ...other } = element;\n app.log.info(`\\t${entity ?? entities.join(',')}: ${JSON.stringify(other)}`);\n }\n }\n\n const missingEntities = Object.keys(app.platformatic.entities).filter((e) => !rules.map((r) => r.entity).includes(e));\n\n if (missingEntities.length) {\n app.log.warn(`Missing rules for entities: ${missingEntities.join(', ')}`);\n }\n\n app.log.debug('LogTo calculated rules');\n app.log.debug(rules);\n return rules;\n }\n\n app.decorateRequest('setupDBAuthorizationUser', setupUser)\n\n async function setupUser() {\n // if (!adminSecret) {\n await this.extractUser()\n // }\n\n let forceAdminRole = false\n if (adminSecret && this.headers['x-platformatic-admin-secret'] === adminSecret) {\n if (opts.jwtPlugin.jwt) {\n forceAdminRole = true\n } else {\n this.log.info('admin secret is valid')\n this.user = new Proxy(this.headers, {\n get: (target, key) => {\n let value;\n if (!target[key.toString()]) {\n const newKey = key.toString().toLowerCase()\n value = target[newKey]\n } else {\n value = target[key.toString()]\n }\n\n if (!value && key.toString().toLowerCase() === roleKey.toLowerCase()) {\n value = PLT_ADMIN_ROLE\n }\n return value\n },\n })\n }\n } else {\n await checkPermissionsVersion(app, opts, this.user)\n }\n\n if (forceAdminRole) {\n // We replace just the role in `request.user`, all the rest is untouched\n this.user = {\n // ...request.user,\n [roleKey]: this.headers['x-platformatic-role'] ? [this.headers['x-platformatic-role']] : [PLT_ADMIN_ROLE]\n }\n }\n }\n\n app.addHook('onReady', async function () {\n const logToRules = await composeLogToRules();\n\n app.platformaticLogTo.rules = logToRules;\n\n // TODO validate that there is at most a rule for a given role\n const entityRules = {};\n for (let i = 0; i < logToRules.length; i++) {\n const rule = logToRules[i]\n\n let ruleEntities = null\n if (rule.entity) {\n ruleEntities = [rule.entity]\n } else if (rule.entities) {\n ruleEntities = [...rule.entities]\n } else {\n throw new Error(`Missing entity in authorization rule ${i}`)\n }\n\n for (const ruleEntity of ruleEntities) {\n const newRule = { ...rule, entity: ruleEntity, entities: undefined }\n if (!app.platformatic.entities[newRule.entity]) {\n throw new Error(`Unknown entity '${ruleEntity}' in authorization rule ${i}`)\n }\n\n if (!entityRules[ruleEntity]) {\n entityRules[ruleEntity] = []\n }\n entityRules[ruleEntity].push(newRule)\n }\n }\n\n for (const entityKey of Object.keys(app.platformatic.entities)) {\n const rules = entityRules[entityKey] || []\n const type = app.platformatic.entities[entityKey]\n\n // We have subscriptions!\n let userPropToFillForPublish\n const topicsWithoutChecks = false\n\n // mqtt\n // if (app.platformatic.mq) {\n // for (const rule of rules) {\n // const checks = rule.find?.checks\n // if (typeof checks !== 'object') {\n // topicsWithoutChecks = !!rule.find\n // continue\n // }\n // const keys = Object.keys(checks)\n // if (keys.length !== 1) {\n // throw new Error(`Subscription requires that the role \"${rule.role}\" has only one check in the find rule for entity \"${rule.entity}\"`)\n // }\n // const key = keys[0]\n\n // const val = typeof checks[key] === 'object' ? checks[key].eq : checks[key]\n // if (userPropToFillForPublish && userPropToFillForPublish.val !== val) {\n // throw new Error('Unable to configure subscriptions and authorization due to multiple check clauses in find')\n // }\n // userPropToFillForPublish = { key, val }\n // }\n // }\n\n if (userPropToFillForPublish && topicsWithoutChecks) {\n throw new Error(`Subscription for entity \"${entityKey}\" have conflictling rules across roles`)\n }\n\n // MUST set this after doing the security checks on the subscriptions\n if (adminSecret) {\n rules.push({\n role: PLT_ADMIN_ROLE,\n find: true,\n save: true,\n delete: true,\n updateMany: true\n })\n }\n\n // If we have `fields` in save rules, we need to check if all the not-nullable\n // fields are specified\n checkSaveMandatoryFieldsInRules(type, rules)\n\n function useOriginal(ctx: PlatformaticContext) {\n return !ctx\n }\n\n app.platformatic.addEntityHooks(entityKey, {\n async find(originalFind, { where, ctx, fields, ...restOpts } = {}) {\n if (useOriginal(ctx)) {\n return originalFind({ ...restOpts, where, ctx, fields })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n checkFieldsFromRule(rule.find, fields || Object.keys(app.platformatic.entities[entityKey].fields))\n where = await fromRuleToWhere(ctx, rule.find, where, request.user)\n\n return originalFind({ ...restOpts, where, ctx, fields })\n },\n async save(originalSave, { input, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalSave({ ctx, input, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n if (!rule.save) {\n throw new Unauthorized()\n }\n checkFieldsFromRule(rule.save, fields)\n checkInputFromRuleFields(rule.save, input)\n\n if (rule.defaults) {\n for (const key of Object.keys(rule.defaults)) {\n const defaults = rule.defaults[key]\n if (typeof defaults === 'function') {\n input[key] = await defaults({ user: request.user, ctx, input })\n } else {\n input[key] = request.user[defaults]\n }\n }\n }\n\n const hasAllPrimaryKeys = input[type.primaryKey] !== undefined;\n const whereConditions = {}\n whereConditions[type.primaryKey] = { eq: input[type.primaryKey] }\n\n if (hasAllPrimaryKeys) {\n const where = await fromRuleToWhere(ctx, rule.save, whereConditions, request.user)\n\n const found = await type.find({\n where,\n ctx,\n fields,\n })\n\n if (found.length === 0) {\n throw new Unauthorized()\n }\n\n return originalSave({ input, ctx, fields, ...restOpts })\n }\n\n return originalSave({ input, ctx, fields, ...restOpts })\n },\n\n async insert(originalInsert, { inputs, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalInsert({ inputs, ctx, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n if (!rule.save) {\n throw new Unauthorized()\n }\n\n checkFieldsFromRule(rule.save, fields)\n checkInputFromRuleFields(rule.save, inputs)\n\n /* istanbul ignore else */\n if (rule.defaults) {\n for (const input of inputs) {\n for (const key of Object.keys(rule.defaults)) {\n const defaults = rule.defaults[key]\n if (typeof defaults === 'function') {\n input[key] = await defaults({ user: request.user, ctx, input })\n } else {\n input[key] = request.user[defaults]\n }\n }\n }\n }\n\n return originalInsert({ inputs, ctx, fields, ...restOpts })\n },\n\n async delete(originalDelete, { where, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalDelete({ where, ctx, fields, ...restOpts })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n where = await fromRuleToWhere(ctx, rule.delete, where, request.user)\n\n return originalDelete({ where, ctx, fields, ...restOpts })\n },\n\n async updateMany(originalUpdateMany, { where, ctx, fields, ...restOpts }) {\n if (useOriginal(ctx)) {\n return originalUpdateMany({ ...restOpts, where, ctx, fields })\n }\n const request = getRequestFromContext(ctx)\n const rule = await findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath)\n\n where = await fromRuleToWhere(ctx, rule.updateMany, where, request.user)\n\n return originalUpdateMany({ ...restOpts, where, ctx, fields })\n },\n })\n }\n })\n}, { name: '@albirex/platformatic-logto' });\n\nasync function fromRuleToWhere(ctx: PlatformaticContext, rule, where, user) {\n if (!rule) {\n throw new Unauthorized()\n }\n const request = getRequestFromContext(ctx)\n /* istanbul ignore next */\n where = where || {}\n\n if (typeof rule === 'object') {\n const { checks } = rule\n\n /* istanbul ignore else */\n if (checks) {\n for (const key of Object.keys(checks)) {\n const clauses = checks[key]\n if (typeof clauses === 'string') {\n // case: \"userId\": \"X-PLATFORMATIC-USER-ID\"\n where[key] = {\n eq: request.user[clauses],\n }\n } else {\n // case:\n // userId: {\n // eq: 'X-PLATFORMATIC-USER-ID'\n // }\n for (const clauseKey of Object.keys(clauses)) {\n const clause = clauses[clauseKey]\n where[key] = {\n [clauseKey]: request.user[clause],\n }\n }\n }\n }\n }\n } else if (typeof rule === 'function') {\n where = await rule({ user, ctx, where })\n }\n return where\n}\n\nexport async function findRuleForRequestUser(ctx: PlatformaticContext, rules: PlatformaticRule[], roleKey: string, anonymousRole: string, isRolePath = false) {\n const request = getRequestFromContext(ctx)\n await request.setupDBAuthorizationUser()\n const roles = getRoles(request, roleKey, anonymousRole, isRolePath)\n const rule = findRule(rules, roles)\n if (!rule) {\n ctx.reply.request.log.warn({ roles, rules }, 'no rule for roles')\n throw new Unauthorized()\n }\n ctx.reply.request.log.trace({ roles, rule }, 'found rule')\n return rule\n}\n\nexport function checkFieldsFromRule(rule, fields) {\n if (!rule) {\n throw new Unauthorized()\n }\n const { fields: fieldsFromRule } = rule\n /* istanbul ignore else */\n if (fieldsFromRule) {\n for (const field of fields) {\n if (!fieldsFromRule.includes(field)) {\n throw new UnauthorizedField(field)\n }\n }\n }\n}\n\nconst validateInputs = (inputs, fieldsFromRule) => {\n for (const input of inputs) {\n const inputFields = Object.keys(input)\n for (const inputField of inputFields) {\n if (!fieldsFromRule.includes(inputField)) {\n throw new UnauthorizedField(inputField)\n }\n }\n }\n}\n\nfunction checkInputFromRuleFields(rule, inputs) {\n const { fields: fieldsFromRule } = rule\n /* istanbul ignore else */\n if (fieldsFromRule) {\n if (!Array.isArray(inputs)) {\n // save\n validateInputs([inputs], fieldsFromRule)\n } else {\n // insert\n validateInputs(inputs, fieldsFromRule)\n }\n }\n}\n\nfunction checkSaveMandatoryFieldsInRules(type: Entity, rules) {\n // List of not nullable, not PKs field to validate save/insert when allowed fields are specified on the rule\n const mandatoryFields =\n Object.values(type.fields)\n .filter(k => (!k.isNullable && !k.primaryKey))\n .map(({ camelcase }) => (camelcase))\n\n for (const rule of rules) {\n const { entity, save } = rule\n if (save && save.fields) {\n const fields = save.fields\n for (const mField of mandatoryFields) {\n if (!fields.includes(mField)) {\n throw new MissingNotNullableError(mField, entity)\n }\n }\n }\n }\n}\n\n/**\n * Check the permissions version\n * @throws PermissionsOutdated if versions don't match\n */\nasync function checkPermissionsVersion(app: FastifyInstance, opts: PlatformaticLogtoAuthOptions, user = null) {\n\n if (!opts.enableTokenVersionCheck || !opts.redis || !app.redis || !user) {\n return;\n }\n\n const sessionVersionKey = opts.sessionVersionKey || 'version'\n const tokenVersion = user?.[sessionVersionKey];\n const userId = user?.sub;\n\n try {\n const redisKey = `permissions:version:${userId}`;\n const currentVersionStr = await app.redis.get(redisKey);\n\n if (currentVersionStr === null) {\n await app.redis.set(redisKey, tokenVersion.toString());\n app.log.debug({ userId, version: tokenVersion }, 'Initialized permissions version in Redis');\n return;\n }\n\n const currentVersion = parseInt(currentVersionStr, 10);\n\n // Compare versions\n if (currentVersion !== tokenVersion) {\n app.log.warn({\n userId,\n tokenVersion,\n currentVersion\n }, 'Permissions version mismatch detected');\n throw new PermissionsOutdated();\n }\n\n app.log.trace({ userId, version: tokenVersion }, 'Token version check passed');\n } catch (error) {\n if (error.name === 'FastifyError' && error.code === 'PLT_DB_AUTH_VERSION_OUTDATED') {\n throw error;\n }\n app.log.error({ err: error, userId }, 'Error checking token version');\n }\n}\n\nexport default platformaticLogto;\n\ndeclare module 'fastify' {\n interface FastifyInstance {\n platformaticLogTo: {\n opts: PlatformaticLogtoAuthOptions,\n rules?: PlatformaticRule[]\n }\n }\n}","'use strict'\n\nimport { PlatformaticRule } from '../index.js'\n\nfunction findRule(rules: PlatformaticRule[], roles: string[]) {\n let found = null\n for (const rule of rules) {\n for (const role of roles) {\n if (rule.role === role) {\n found = rule\n break\n }\n }\n if (found) {\n break\n }\n }\n return found\n}\n\nexport default findRule\n","'use strict'\n\nimport createError from '@fastify/error'\n\nconst ERROR_PREFIX = 'PLT_DB_AUTH'\n\nexport const Unauthorized = createError(`${ERROR_PREFIX}_UNAUTHORIZED`, 'operation not allowed', 401)\nexport const UnauthorizedField = createError(`${ERROR_PREFIX}_FIELD_UNAUTHORIZED`, 'field not allowed: %s', 401)\nexport const MissingNotNullableError = createError(`${ERROR_PREFIX}_NOT_NULLABLE_MISSING`, 'missing not nullable field: \"%s\" in save rule for entity \"%s\"')\nexport const PermissionsOutdated = createError(`${ERROR_PREFIX}_VERSION_OUTDATED`, 'Verision has been updated. Please logout and login again.', 403)\n","'use strict'\n\nimport type { FastifyInstance } from 'fastify'\n\n/**\n * Increment the permissions version\n * @param app - Fastify instance with Redis client and Logto\n * @param userId - User ID\n * @returns New version number\n */\nexport async function incrementPermissionsVersion(app: FastifyInstance, userId: string): Promise<number> {\n if (!app.logto) {\n throw new Error('Logto client not available')\n }\n\n const userResp = await app.logto.callAPI(`/api/users/${userId}`, 'GET')\n const userData = await userResp.json()\n const existingCustomData = userData.customData || {}\n const currentVersion = existingCustomData.sessionVersion || 0\n const newVersion = currentVersion + 1\n\n await app.logto.callAPI(`/api/users/${userId}`, 'PATCH', JSON.stringify({ customData: { ...existingCustomData, sessionVersion: newVersion } }))\n\n if (app.redis) {\n const redisKey = `permissions:version:${userId}`\n await app.redis.set(redisKey, newVersion.toString())\n }\n\n return newVersion\n}\n\n/**\n * Delete the permissions version for a user\n * @param app - Fastify instance with Redis client\n * @param userId - User ID\n */\nexport async function deletePermissionsVersion(app: FastifyInstance, userId: string): Promise<void> {\n if (!app.redis) {\n throw new Error('Redis client not available')\n }\n\n const redisKey = `permissions:version:${userId}`\n await app.redis.del(redisKey)\n}\n\n","'use strict'\n\nexport function getRequestFromContext (ctx) {\n if (ctx && !ctx.reply) {\n throw new Error('Missing reply in context. You should call this function with { ctx: { reply }}')\n }\n return ctx.reply.request\n}\n\nexport function getRoles (request, roleKey, anonymousRole, isRolePath = false) {\n let output = []\n const user = request.user\n if (!user) {\n output.push(anonymousRole)\n return output\n }\n\n let rolesRaw\n if (isRolePath) {\n const roleKeys = roleKey.split('.')\n rolesRaw = user\n for (const key of roleKeys) {\n rolesRaw = rolesRaw[key]\n }\n } else {\n rolesRaw = user[roleKey]\n }\n\n if (typeof rolesRaw === 'string') {\n output = rolesRaw.split(',')\n } else if (Array.isArray(rolesRaw)) {\n output = rolesRaw\n }\n if (output.length === 0) {\n output.push(anonymousRole)\n }\n\n return output\n}\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,YAAY,iBAAiB;;;ACG7B,SAAS,SAAS,OAA2B,OAAiB;AAC5D,MAAI,QAAQ;AACZ,aAAW,QAAQ,OAAO;AACxB,eAAW,QAAQ,OAAO;AACxB,UAAI,KAAK,SAAS,MAAM;AACtB,gBAAQ;AACR;AAAA,MACF;AAAA,IACF;AACA,QAAI,OAAO;AACT;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEA,IAAO,oBAAQ;;;AClBf,OAAO,iBAAiB;AAExB,IAAM,eAAe;AAEd,IAAM,eAAe,YAAY,GAAG,YAAY,iBAAiB,yBAAyB,GAAG;AAC7F,IAAM,oBAAoB,YAAY,GAAG,YAAY,uBAAuB,yBAAyB,GAAG;AACxG,IAAM,0BAA0B,YAAY,GAAG,YAAY,yBAAyB,+DAA+D;AACnJ,IAAM,sBAAsB,YAAY,GAAG,YAAY,qBAAqB,6DAA6D,GAAG;;;AFJnJ,OAAO,kBAAkB;AACzB,OAAO,kBAAkB;AAKzB,SAAS,gBA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AA,MACJ,GAAG,uCAAuC;AAC1C,YAAM,IAAI,oBAAoB;AAAA,IAClC;AAEA,QAAI,IAAI,MAAM,EAAE,QAAQ,SAAS,aAAa,GAAG,4BAA4B;AAAA,EACjF,SAAS,OAAO;AACZ,QAAI,MAAM,SAAS,kBAAkB,MAAM,SAAS,gCAAgC;AAChF,YAAM;AAAA,IACV;AACA,QAAI,IAAI,MAAM,EAAE,KAAK,OAAO,OAAO,GAAG,8BAA8B;AAAA,EACxE;AACJ;AAEA,IAAO,gBAAQ;","names":["fastifyLogto"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@albirex/platformatic-logto",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.1",
|
|
4
4
|
"description": "LogTo roles and scopes integrated in Platformatic authorization",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/index.cjs",
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
"dependencies": {
|
|
40
40
|
"@albirex/fastify-logto": "^1.3.6",
|
|
41
41
|
"@fastify/error": "^4.1.0",
|
|
42
|
+
"@fastify/redis": "^7.2.0",
|
|
42
43
|
"@logto/js": "^5.1.1",
|
|
43
44
|
"@logto/node": "^3.1.4",
|
|
44
45
|
"@platformatic/db-authorization": "^2.66.0",
|