@albirex/platformatic-logto 1.3.4 → 1.3.5

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/package.json CHANGED
@@ -1,23 +1,11 @@
1
1
  {
2
2
  "name": "@albirex/platformatic-logto",
3
- "version": "1.3.4",
3
+ "version": "1.3.5",
4
4
  "description": "LogTo roles and scopes integrated in Platformatic authorization",
5
5
  "type": "module",
6
- "main": "./lib/index.cjs",
6
+ "main": "./lib/index.js",
7
7
  "module": "./lib/index.js",
8
8
  "types": "./lib/index.d.ts",
9
- "exports": {
10
- ".": {
11
- "import": {
12
- "types": "./lib/index.d.ts",
13
- "default": "./lib/index.js"
14
- },
15
- "require": {
16
- "types": "./lib/index.d.cts",
17
- "default": "./lib/index.cjs"
18
- }
19
- }
20
- },
21
9
  "files": [
22
10
  "lib"
23
11
  ],
package/lib/index.cjs DELETED
@@ -1,437 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __export = (target, all) => {
8
- for (var name in all)
9
- __defProp(target, name, { get: all[name], enumerable: true });
10
- };
11
- var __copyProps = (to, from, except, desc) => {
12
- if (from && typeof from === "object" || typeof from === "function") {
13
- for (let key of __getOwnPropNames(from))
14
- if (!__hasOwnProp.call(to, key) && key !== except)
15
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
- }
17
- return to;
18
- };
19
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
- // If the importer is in node compatibility mode or this is not an ESM
21
- // file that has been converted to a CommonJS file using a Babel-
22
- // compatible transform (i.e. "__esModule" has not been set), then set
23
- // "default" to the CommonJS "module.exports" for node compatibility.
24
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
- mod
26
- ));
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
-
29
- // src/index.ts
30
- var index_exports = {};
31
- __export(index_exports, {
32
- default: () => index_default
33
- });
34
- module.exports = __toCommonJS(index_exports);
35
- var import_fastify_plugin = __toESM(require("fastify-plugin"), 1);
36
- var import_leven = __toESM(require("leven"), 1);
37
- var fastifyUser = __toESM(require("fastify-user"), 1);
38
-
39
- // src/utils/find-rule.ts
40
- function findRule(rules, roles) {
41
- let found = null;
42
- for (const rule of rules) {
43
- for (const role of roles) {
44
- if (rule.role === role) {
45
- found = rule;
46
- break;
47
- }
48
- }
49
- if (found) {
50
- break;
51
- }
52
- }
53
- return found;
54
- }
55
- var find_rule_default = findRule;
56
-
57
- // src/utils/utils.ts
58
- function getRequestFromContext(ctx) {
59
- if (ctx && !ctx.reply) {
60
- throw new Error("Missing reply in context. You should call this function with { ctx: { reply }}");
61
- }
62
- return ctx.reply.request;
63
- }
64
- function getRoles(request, roleKey, anonymousRole, isRolePath = false) {
65
- let output = [];
66
- const user = request.user;
67
- if (!user) {
68
- output.push(anonymousRole);
69
- return output;
70
- }
71
- let rolesRaw;
72
- if (isRolePath) {
73
- const roleKeys = roleKey.split(".");
74
- rolesRaw = user;
75
- for (const key of roleKeys) {
76
- rolesRaw = rolesRaw[key];
77
- }
78
- } else {
79
- rolesRaw = user[roleKey];
80
- }
81
- if (typeof rolesRaw === "string") {
82
- output = rolesRaw.split(",");
83
- } else if (Array.isArray(rolesRaw)) {
84
- output = rolesRaw;
85
- }
86
- if (output.length === 0) {
87
- output.push(anonymousRole);
88
- }
89
- return output;
90
- }
91
-
92
- // src/utils/errors.ts
93
- var import_error = __toESM(require("@fastify/error"), 1);
94
- var ERROR_PREFIX = "PLT_DB_AUTH";
95
- var Unauthorized = (0, import_error.default)(`${ERROR_PREFIX}_UNAUTHORIZED`, "operation not allowed", 401);
96
- var UnauthorizedField = (0, import_error.default)(`${ERROR_PREFIX}_FIELD_UNAUTHORIZED`, "field not allowed: %s", 401);
97
- var MissingNotNullableError = (0, import_error.default)(`${ERROR_PREFIX}_NOT_NULLABLE_MISSING`, 'missing not nullable field: "%s" in save rule for entity "%s"');
98
-
99
- // src/index.ts
100
- var import_fastify_logto = __toESM(require("@albirex/fastify-logto"), 1);
101
- var PLT_ADMIN_ROLE = "platformatic-admin";
102
- var auth = async (app, opts) => {
103
- app.register(import_fastify_logto.default, {
104
- endpoint: opts.logtoBaseUrl || "https://auth.example.com",
105
- appId: opts.logtoAppId || "your-app-id",
106
- appSecret: opts.logtoAppSecret || "your-app-secret"
107
- });
108
- await app.register(fastifyUser, opts.jwtPlugin);
109
- const adminSecret = opts.adminSecret;
110
- const roleKey = opts.rolePath || opts.roleKey || "X-PLATFORMATIC-ROLE";
111
- const userKey = opts.userPath || opts.userKey || "X-PLATFORMATIC-USER-ID";
112
- const isRolePath = !!opts.rolePath;
113
- const anonymousRole = opts.anonymousRole || "anonymous";
114
- async function composeLogToRules() {
115
- const rolesResp = await app.logto.callAPI("/api/roles?type=User", "GET");
116
- if (!rolesResp.ok) {
117
- throw rolesResp;
118
- }
119
- const roles = await rolesResp.json();
120
- const rules = [{
121
- role: anonymousRole,
122
- entities: Object.keys(app.platformatic.entities),
123
- find: opts.allowAnonymous,
124
- save: opts.allowAnonymous,
125
- delete: opts.allowAnonymous
126
- }];
127
- for (const role of roles) {
128
- const scopesResp = await app.logto.callAPI(`/api/roles/${role.id}/scopes`, "GET");
129
- if (!scopesResp.ok) {
130
- throw scopesResp;
131
- }
132
- const scopes = await scopesResp.json();
133
- for (const scope of scopes) {
134
- const roleName = role.name;
135
- const [scopeAction, entity] = scope.name.split(":");
136
- if (!app.platformatic.entities[entity]) {
137
- const nearest = findNearestEntity(entity);
138
- app.log.warn(`Unknown entity '${entity}' in authorization rule. Did you mean '${nearest.entity}'?`);
139
- continue;
140
- }
141
- const checkExists = rules.find((r) => r.role === roleName && r.entity === entity);
142
- if (checkExists) {
143
- if (opts.checks) {
144
- checkExists[scopeAction] = {
145
- checks: {
146
- userId: userKey
147
- }
148
- };
149
- } else {
150
- checkExists[scopeAction] = true;
151
- }
152
- } else {
153
- const newRule = {
154
- role: roleName,
155
- entity
156
- };
157
- if (opts.checks) {
158
- newRule[scopeAction] = {
159
- checks: {
160
- userId: userKey
161
- }
162
- };
163
- } else {
164
- newRule[scopeAction] = true;
165
- }
166
- if (opts.defaults) {
167
- newRule.defaults = {
168
- userId: userKey
169
- };
170
- }
171
- rules.push(newRule);
172
- }
173
- }
174
- }
175
- app.log.debug("LogTo calculated rules");
176
- app.log.debug(rules);
177
- return rules;
178
- }
179
- app.decorateRequest("setupDBAuthorizationUser", setupUser);
180
- async function setupUser() {
181
- await this.extractUser();
182
- let forceAdminRole = false;
183
- if (adminSecret && this.headers["x-platformatic-admin-secret"] === adminSecret) {
184
- if (opts.jwtPlugin.jwt) {
185
- forceAdminRole = true;
186
- } else {
187
- this.log.info("admin secret is valid");
188
- this.user = new Proxy(this.headers, {
189
- get: (target, key) => {
190
- let value;
191
- if (!target[key.toString()]) {
192
- const newKey = key.toString().toLowerCase();
193
- value = target[newKey];
194
- } else {
195
- value = target[key.toString()];
196
- }
197
- if (!value && key.toString().toLowerCase() === roleKey.toLowerCase()) {
198
- value = PLT_ADMIN_ROLE;
199
- }
200
- return value;
201
- }
202
- });
203
- }
204
- }
205
- if (forceAdminRole) {
206
- this.user = {
207
- // ...request.user,
208
- [roleKey]: PLT_ADMIN_ROLE
209
- };
210
- }
211
- }
212
- function findNearestEntity(ruleEntity) {
213
- const entities = Object.keys(app.platformatic.entities);
214
- const nearest = entities.reduce((acc, entity) => {
215
- const distance = (0, import_leven.default)(ruleEntity, entity);
216
- if (distance < acc.distance) {
217
- acc.distance = distance;
218
- acc.entity = entity;
219
- }
220
- return acc;
221
- }, { distance: Infinity, entity: null });
222
- return nearest;
223
- }
224
- app.addHook("onReady", async function() {
225
- const rules = await composeLogToRules();
226
- const entityRules = {};
227
- for (let i = 0; i < rules.length; i++) {
228
- const rule = rules[i];
229
- let ruleEntities = null;
230
- if (rule.entity) {
231
- ruleEntities = [rule.entity];
232
- } else if (rule.entities) {
233
- ruleEntities = [...rule.entities];
234
- } else {
235
- throw new Error(`Missing entity in authorization rule ${i}`);
236
- }
237
- for (const ruleEntity of ruleEntities) {
238
- const newRule = { ...rule, entity: ruleEntity, entities: void 0 };
239
- if (!app.platformatic.entities[newRule.entity]) {
240
- const nearest = findNearestEntity(ruleEntity);
241
- throw new Error(`Unknown entity '${ruleEntity}' in authorization rule ${i}. Did you mean '${nearest.entity}'?`);
242
- }
243
- if (!entityRules[ruleEntity]) {
244
- entityRules[ruleEntity] = [];
245
- }
246
- entityRules[ruleEntity].push(newRule);
247
- }
248
- }
249
- for (const entityKey of Object.keys(app.platformatic.entities)) {
250
- const rules2 = entityRules[entityKey] || [];
251
- const type = app.platformatic.entities[entityKey];
252
- let userPropToFillForPublish;
253
- const topicsWithoutChecks = false;
254
- if (userPropToFillForPublish && topicsWithoutChecks) {
255
- throw new Error(`Subscription for entity "${entityKey}" have conflictling rules across roles`);
256
- }
257
- if (adminSecret) {
258
- rules2.push({
259
- role: PLT_ADMIN_ROLE,
260
- find: true,
261
- save: true,
262
- delete: true
263
- });
264
- }
265
- checkSaveMandatoryFieldsInRules(type, rules2);
266
- app.platformatic.addEntityHooks(entityKey, {
267
- async find(originalFind, { where, ctx, fields, ...restOpts } = {}) {
268
- const request = getRequestFromContext(ctx);
269
- const rule = await findRuleForRequestUser(ctx, rules2, roleKey, anonymousRole, isRolePath);
270
- checkFieldsFromRule(rule.find, fields || Object.keys(app.platformatic.entities[entityKey].fields));
271
- where = await fromRuleToWhere(ctx, rule.find, where, request.user);
272
- return originalFind({ ...restOpts, where, ctx, fields });
273
- },
274
- async save(originalSave, { input, ctx, fields, ...restOpts }) {
275
- const request = getRequestFromContext(ctx);
276
- const rule = await findRuleForRequestUser(ctx, rules2, roleKey, anonymousRole, isRolePath);
277
- if (!rule.save) {
278
- throw new Unauthorized();
279
- }
280
- checkFieldsFromRule(rule.save, fields);
281
- checkInputFromRuleFields(rule.save, input);
282
- if (rule.defaults) {
283
- for (const key of Object.keys(rule.defaults)) {
284
- const defaults = rule.defaults[key];
285
- if (typeof defaults === "function") {
286
- input[key] = await defaults({ user: request.user, ctx, input });
287
- } else {
288
- input[key] = request.user[defaults];
289
- }
290
- }
291
- }
292
- const hasAllPrimaryKeys = input[type.primaryKey] !== void 0;
293
- const whereConditions = {};
294
- whereConditions[type.primaryKey] = { eq: input[type.primaryKey] };
295
- if (hasAllPrimaryKeys) {
296
- const where = await fromRuleToWhere(ctx, rule.save, whereConditions, request.user);
297
- const found = await type.find({
298
- where,
299
- ctx,
300
- fields
301
- });
302
- if (found.length === 0) {
303
- throw new Unauthorized();
304
- }
305
- return originalSave({ input, ctx, fields, ...restOpts });
306
- }
307
- return originalSave({ input, ctx, fields, ...restOpts });
308
- },
309
- async insert(originalInsert, { inputs, ctx, fields, ...restOpts }) {
310
- const request = getRequestFromContext(ctx);
311
- const rule = await findRuleForRequestUser(ctx, rules2, roleKey, anonymousRole, isRolePath);
312
- if (!rule.save) {
313
- throw new Unauthorized();
314
- }
315
- checkFieldsFromRule(rule.save, fields);
316
- checkInputFromRuleFields(rule.save, inputs);
317
- if (rule.defaults) {
318
- for (const input of inputs) {
319
- for (const key of Object.keys(rule.defaults)) {
320
- const defaults = rule.defaults[key];
321
- if (typeof defaults === "function") {
322
- input[key] = await defaults({ user: request.user, ctx, input });
323
- } else {
324
- input[key] = request.user[defaults];
325
- }
326
- }
327
- }
328
- }
329
- return originalInsert({ inputs, ctx, fields, ...restOpts });
330
- },
331
- async delete(originalDelete, { where, ctx, fields, ...restOpts }) {
332
- const request = getRequestFromContext(ctx);
333
- const rule = await findRuleForRequestUser(ctx, rules2, roleKey, anonymousRole, isRolePath);
334
- where = await fromRuleToWhere(ctx, rule.delete, where, request.user);
335
- return originalDelete({ where, ctx, fields, ...restOpts });
336
- },
337
- async updateMany(originalUpdateMany, { where, ctx, fields, ...restOpts }) {
338
- const request = getRequestFromContext(ctx);
339
- const rule = await findRuleForRequestUser(ctx, rules2, roleKey, anonymousRole, isRolePath);
340
- where = await fromRuleToWhere(ctx, rule.updateMany, where, request.user);
341
- return originalUpdateMany({ ...restOpts, where, ctx, fields });
342
- }
343
- });
344
- }
345
- });
346
- };
347
- async function fromRuleToWhere(ctx, rule, where, user) {
348
- if (!rule) {
349
- throw new Unauthorized();
350
- }
351
- const request = getRequestFromContext(ctx);
352
- where = where || {};
353
- if (typeof rule === "object") {
354
- const { checks } = rule;
355
- if (checks) {
356
- for (const key of Object.keys(checks)) {
357
- const clauses = checks[key];
358
- if (typeof clauses === "string") {
359
- where[key] = {
360
- eq: request.user[clauses]
361
- };
362
- } else {
363
- for (const clauseKey of Object.keys(clauses)) {
364
- const clause = clauses[clauseKey];
365
- where[key] = {
366
- [clauseKey]: request.user[clause]
367
- };
368
- }
369
- }
370
- }
371
- }
372
- } else if (typeof rule === "function") {
373
- where = await rule({ user, ctx, where });
374
- }
375
- return where;
376
- }
377
- async function findRuleForRequestUser(ctx, rules, roleKey, anonymousRole, isRolePath = false) {
378
- const request = getRequestFromContext(ctx);
379
- await request.setupDBAuthorizationUser();
380
- const roles = getRoles(request, roleKey, anonymousRole, isRolePath);
381
- const rule = find_rule_default(rules, roles);
382
- if (!rule) {
383
- ctx.reply.request.log.warn({ roles, rules }, "no rule for roles");
384
- throw new Unauthorized();
385
- }
386
- ctx.reply.request.log.trace({ roles, rule }, "found rule");
387
- return rule;
388
- }
389
- function checkFieldsFromRule(rule, fields) {
390
- if (!rule) {
391
- throw new Unauthorized();
392
- }
393
- const { fields: fieldsFromRule } = rule;
394
- if (fieldsFromRule) {
395
- for (const field of fields) {
396
- if (!fieldsFromRule.includes(field)) {
397
- throw new UnauthorizedField(field);
398
- }
399
- }
400
- }
401
- }
402
- var validateInputs = (inputs, fieldsFromRule) => {
403
- for (const input of inputs) {
404
- const inputFields = Object.keys(input);
405
- for (const inputField of inputFields) {
406
- if (!fieldsFromRule.includes(inputField)) {
407
- throw new UnauthorizedField(inputField);
408
- }
409
- }
410
- }
411
- };
412
- function checkInputFromRuleFields(rule, inputs) {
413
- const { fields: fieldsFromRule } = rule;
414
- if (fieldsFromRule) {
415
- if (!Array.isArray(inputs)) {
416
- validateInputs([inputs], fieldsFromRule);
417
- } else {
418
- validateInputs(inputs, fieldsFromRule);
419
- }
420
- }
421
- }
422
- function checkSaveMandatoryFieldsInRules(type, rules) {
423
- const mandatoryFields = Object.values(type.fields).filter((k) => !k.isNullable && !k.primaryKey).map(({ camelcase }) => camelcase);
424
- for (const rule of rules) {
425
- const { entity, save } = rule;
426
- if (save && save.fields) {
427
- const fields = save.fields;
428
- for (const mField of mandatoryFields) {
429
- if (!fields.includes(mField)) {
430
- throw new MissingNotNullableError(mField, entity);
431
- }
432
- }
433
- }
434
- }
435
- }
436
- var index_default = (0, import_fastify_plugin.default)(auth, { name: "@albirex/platformatic-logto" });
437
- //# sourceMappingURL=index.cjs.map
package/lib/index.cjs.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts","../src/utils/find-rule.ts","../src/utils/utils.ts","../src/utils/errors.ts"],"sourcesContent":["import fp from 'fastify-plugin'\nimport leven from 'leven'\nimport * as fastifyUser from 'fastify-user'\n\nimport findRule from './utils/find-rule.js'\nimport { getRequestFromContext, getRoles } from './utils/utils.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'\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\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\nconst auth: FastifyPluginAsync<PlatformaticLogtoAuthOptions> = async (app: FastifyInstance, opts: PlatformaticLogtoAuthOptions) => {\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await app.register(fastifyUser as any, 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 const [scopeAction, entity] = scope.name.split(':');\n\n if (!app.platformatic.entities[entity]) {\n const nearest = findNearestEntity(entity)\n app.log.warn(`Unknown entity '${entity}' in authorization rule. Did you mean '${nearest.entity}'?`)\n continue;\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 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]: PLT_ADMIN_ROLE,\n }\n }\n }\n\n function findNearestEntity(ruleEntity) {\n // There is an unknown entity. Let's find out the nearest one for a nice error message\n const entities = Object.keys(app.platformatic.entities)\n\n const nearest = entities.reduce((acc, entity) => {\n\n const distance = leven(ruleEntity, entity)\n if (distance < acc.distance) {\n acc.distance = distance\n acc.entity = entity\n }\n return acc\n }, { distance: Infinity, entity: null })\n return nearest\n }\n\n app.addHook('onReady', async function () {\n const rules = await composeLogToRules();\n\n // TODO validate that there is at most a rule for a given role\n const entityRules = {};\n for (let i = 0; i < rules.length; i++) {\n const rule = rules[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 const nearest = findNearestEntity(ruleEntity)\n throw new Error(`Unknown entity '${ruleEntity}' in authorization rule ${i}. Did you mean '${nearest.entity}'?`)\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 })\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(skipAuth: boolean, ctx: PlatformaticContext) {\n // if (skipAuth === false && !ctx) {\n // throw new Error('Cannot set skipAuth to `false` without ctx')\n // }\n\n // return skipAuth || !ctx\n // }\n\n app.platformatic.addEntityHooks(entityKey, {\n async find(originalFind, { where, ctx, fields, ...restOpts } = {}) {\n // if (useOriginal(skipAuth, 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(skipAuth, 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(skipAuth, 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(skipAuth, 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(skipAuth, 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}\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\nasync 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\nfunction 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 fp(auth, {name: '@albirex/platformatic-logto'})\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\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","'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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA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,QAAQ,MAAM;AAAA,QACpD;AAAA,MACJ;AAAA,IACJ;AAAA,EACJ;AACJ;AAEA,IAAO,oBAAQ,sBAAAC,SAAG,MAAM,EAAC,MAAM,8BAA6B,CAAC;","names":["createError","fastifyLogto","leven","rules","fp"]}
package/lib/index.d.cts DELETED
@@ -1,31 +0,0 @@
1
- import { FastifyPluginAsync } from 'fastify';
2
- import { FastifyUserPluginOptions } from 'fastify-user';
3
-
4
- type PlatformaticRule = {
5
- role: string;
6
- entity?: string;
7
- entities?: string[];
8
- defaults?: Record<string, string>;
9
- checks?: boolean;
10
- find?: boolean;
11
- save?: boolean;
12
- delete?: boolean;
13
- };
14
- type PlatformaticLogtoAuthOptions = {
15
- logtoBaseUrl?: string;
16
- logtoAppId?: string;
17
- logtoAppSecret?: string;
18
- adminSecret?: string;
19
- rolePath?: string;
20
- roleKey?: string;
21
- userPath?: string;
22
- userKey?: string;
23
- anonymousRole?: string;
24
- allowAnonymous?: boolean;
25
- checks?: boolean;
26
- defaults?: boolean;
27
- jwtPlugin: FastifyUserPluginOptions;
28
- };
29
- declare const _default: FastifyPluginAsync<PlatformaticLogtoAuthOptions>;
30
-
31
- export { type PlatformaticLogtoAuthOptions, type PlatformaticRule, _default as default };