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