node-server-engine 1.1.5 → 1.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.env.example +0 -38
  2. package/.nycrc +9 -3
  3. package/README.md +2 -3
  4. package/dist/const/tokenIssuer.d.ts +2 -4
  5. package/dist/const/tokenIssuer.js +0 -1
  6. package/dist/const/tokenIssuer.js.map +1 -1
  7. package/dist/entities/Endpoint/Endpoint.types.d.ts +2 -19
  8. package/dist/entities/Endpoint/Endpoint.types.js +1 -8
  9. package/dist/entities/Endpoint/Endpoint.types.js.map +1 -1
  10. package/dist/middleware/index.d.ts +0 -1
  11. package/dist/middleware/index.js +0 -11
  12. package/dist/middleware/index.js.map +1 -1
  13. package/dist/utils/index.d.ts +0 -1
  14. package/dist/utils/index.js +0 -11
  15. package/dist/utils/index.js.map +1 -1
  16. package/dist/utils/jwt/jwt.d.ts +0 -1
  17. package/dist/utils/jwt/jwt.js +2 -23
  18. package/dist/utils/jwt/jwt.js.map +1 -1
  19. package/dist/utils/report/report.js +1 -2
  20. package/dist/utils/report/report.js.map +1 -1
  21. package/package.json +8 -7
  22. package/src/const/tokenIssuer.ts +1 -3
  23. package/src/entities/Endpoint/Endpoint.test.ts +0 -89
  24. package/src/entities/Endpoint/Endpoint.types.ts +3 -30
  25. package/src/entities/KeySet/KeySet.test.ts +1 -1
  26. package/src/middleware/index.ts +0 -1
  27. package/src/utils/index.ts +0 -1
  28. package/src/utils/jwt/jwt.test.ts +0 -13
  29. package/src/utils/jwt/jwt.ts +2 -25
  30. package/src/utils/report/report.ts +1 -2
  31. package/test/env.ts +0 -5
  32. package/test/hooks.ts +0 -2
  33. package/dist/middleware/authAdmin/authAdmin.d.ts +0 -4
  34. package/dist/middleware/authAdmin/authAdmin.js +0 -105
  35. package/dist/middleware/authAdmin/authAdmin.js.map +0 -1
  36. package/dist/middleware/authAdmin/authAdmin.types.d.ts +0 -16
  37. package/dist/middleware/authAdmin/authAdmin.types.js +0 -2
  38. package/dist/middleware/authAdmin/authAdmin.types.js.map +0 -1
  39. package/dist/middleware/authAdmin/index.d.ts +0 -2
  40. package/dist/middleware/authAdmin/index.js +0 -28
  41. package/dist/middleware/authAdmin/index.js.map +0 -1
  42. package/dist/utils/getDynamicLink/getDynamicLink.d.ts +0 -3
  43. package/dist/utils/getDynamicLink/getDynamicLink.js +0 -28
  44. package/dist/utils/getDynamicLink/getDynamicLink.js.map +0 -1
  45. package/dist/utils/getDynamicLink/getDynamicLink.types.d.ts +0 -10
  46. package/dist/utils/getDynamicLink/getDynamicLink.types.js +0 -2
  47. package/dist/utils/getDynamicLink/getDynamicLink.types.js.map +0 -1
  48. package/dist/utils/getDynamicLink/getDynamicLink.validate.d.ts +0 -2
  49. package/dist/utils/getDynamicLink/getDynamicLink.validate.js +0 -14
  50. package/dist/utils/getDynamicLink/getDynamicLink.validate.js.map +0 -1
  51. package/dist/utils/getDynamicLink/index.d.ts +0 -2
  52. package/dist/utils/getDynamicLink/index.js +0 -28
  53. package/dist/utils/getDynamicLink/index.js.map +0 -1
  54. package/src/middleware/authAdmin/authAdmin.test.ts +0 -199
  55. package/src/middleware/authAdmin/authAdmin.ts +0 -114
  56. package/src/middleware/authAdmin/authAdmin.types.ts +0 -19
  57. package/src/middleware/authAdmin/index.ts +0 -2
  58. package/src/utils/getDynamicLink/getDynamicLink.test.ts +0 -51
  59. package/src/utils/getDynamicLink/getDynamicLink.ts +0 -28
  60. package/src/utils/getDynamicLink/getDynamicLink.types.ts +0 -11
  61. package/src/utils/getDynamicLink/getDynamicLink.validate.ts +0 -6
  62. package/src/utils/getDynamicLink/index.ts +0 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "node-server-engine",
3
- "version": "1.1.5",
3
+ "version": "1.1.7",
4
4
  "description": "Framework used to develop backend services. This package ships with a lot of features to standardize the creation of services, letting you focus on the business logic.",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -9,10 +9,11 @@
9
9
  "lint": "eslint ./src",
10
10
  "lint:fix": "eslint ./src --fix",
11
11
  "prepublish": "npm run build",
12
+ "prepublishOnly": "npm run build",
12
13
  "test": "cross-env NODE_ENV=test nyc --reporter=none mocha test/hooks.ts \"src/**/*.test.ts\"",
13
- "coverage": "nyc report --reporter=text",
14
+ "test:file": "cross-env NODE_ENV=test nyc --reporter=none mocha test/hooks.ts",
15
+ "coverage": "nyc report --report-dir=./.test-coverage --reporter=html --reporter=text",
14
16
  "coverage:ci": "nyc report --reporter=text-summary",
15
- "prepublishOnly": "npm run build",
16
17
  "test:ci": "npm run test -- --reporter spec",
17
18
  "test:compose": "docker-compose up --abort-on-container-exit --build"
18
19
  },
@@ -44,7 +45,7 @@
44
45
  "@google/generative-ai": "^0.21.0",
45
46
  "ajv": "^8.17.1",
46
47
  "axios": "^1.7.9",
47
- "backend-test-tools": "^1.0.3",
48
+ "backend-test-tools": "^1.0.6",
48
49
  "body-parser": "^1.20.3",
49
50
  "busboy": "^1.6.0",
50
51
  "callsite": "^1.0.0",
@@ -130,8 +131,8 @@
130
131
  "@typescript-eslint/eslint-plugin": "^8.18.1",
131
132
  "babel-plugin-istanbul": "^7.0.0",
132
133
  "babel-plugin-module-resolver": "^5.0.2",
133
- "chai": "^5.1.2",
134
- "chai-as-promised": "^8.0.1",
134
+ "chai": "^4.5.0",
135
+ "chai-as-promised": "^7.1.2",
135
136
  "cross-env": "^7.0.3",
136
137
  "eslint": "^9.17.0",
137
138
  "factory-waifu": "^1.0.1",
@@ -147,7 +148,7 @@
147
148
  "rimraf": "^6.0.1",
148
149
  "shx": "^0.3.4",
149
150
  "sinon": "^19.0.2",
150
- "sinon-chai": "^4.0.0",
151
+ "sinon-chai": "^3.5.0",
151
152
  "supertest": "^7.0.0",
152
153
  "tmp": "^0.2.3",
153
154
  "ts-node": "^10.9.2",
@@ -1,9 +1,7 @@
1
1
  /** Enum to identify access tokens JWT issuers */
2
2
  export enum TokenIssuer {
3
3
  /** For tokens issued by the auth service */
4
- AUTH_SERVICE,
5
- /** For tokens issued by the admin API */
6
- ADMIN_API
4
+ AUTH_SERVICE
7
5
  }
8
6
 
9
7
  export const TOKEN_ISSUERS = Object.values(TokenIssuer);
@@ -176,95 +176,6 @@ describe('Entity - Endpoint', () => {
176
176
  await server.shutdown();
177
177
  });
178
178
 
179
- // AUTH ADMIN
180
-
181
- it('it should authenticate with authAdmin middleware', async () => {
182
- const email = faker.internet.email();
183
- const permission = faker.lorem.word();
184
- const token = generateAccessToken(
185
- email,
186
- {
187
- audience: [process.env.ADMIN_API_ACCESS_TOKEN_AUDIENCE as string],
188
- issuer: process.env.ADMIN_ACCESS_TOKEN_ISSUER as string
189
- },
190
- { per: permission }
191
- );
192
- const endpoint = new Endpoint({
193
- ...config,
194
- authType: EndpointAuthType.ADMIN,
195
- authParams: { permission },
196
- handler: (req: Request, res: Response) => {
197
- res.sendStatus(200);
198
- }
199
- } as EndpointOptions<EndpointAuthType.ADMIN>);
200
-
201
- endpoint.register(app);
202
- await request(app)
203
- .get(PATH)
204
- .set('Authorization', 'Bearer ' + token)
205
- .expect(200);
206
- });
207
-
208
- it('it should authenticate with authAdmin middleware and check permission', async () => {
209
- const email = faker.internet.email();
210
- const permission = faker.lorem.word();
211
- const token = generateAccessToken(
212
- email,
213
- {
214
- audience: [process.env.ADMIN_API_ACCESS_TOKEN_AUDIENCE as string],
215
- issuer: process.env.ADMIN_ACCESS_TOKEN_ISSUER as string
216
- },
217
- { per: permission }
218
- );
219
-
220
- const endpoint = new Endpoint({
221
- ...config,
222
- authType: EndpointAuthType.ADMIN,
223
- authParams: { permission },
224
- handler: (req: Request, res: Response) => {
225
- res.sendStatus(200);
226
- }
227
- } as EndpointOptions<EndpointAuthType.ADMIN>);
228
-
229
- endpoint.register(app);
230
- await request(app)
231
- .get(PATH)
232
- .set('Authorization', 'Bearer ' + token)
233
- .expect(200);
234
- });
235
-
236
- it('it should authenticate with authAdmin middleware and check permissions', async () => {
237
- const email = faker.internet.email();
238
- const permissions = [
239
- faker.lorem.word(),
240
- faker.lorem.word(),
241
- faker.lorem.word()
242
- ];
243
- const token = generateAccessToken(
244
- email,
245
- {
246
- audience: [process.env.ADMIN_API_ACCESS_TOKEN_AUDIENCE as string],
247
- issuer: process.env.ADMIN_ACCESS_TOKEN_ISSUER as string
248
- },
249
- { per: permissions }
250
- );
251
-
252
- const endpoint = new Endpoint({
253
- ...config,
254
- authType: EndpointAuthType.ADMIN,
255
- authParams: { permission: permissions[1] },
256
- handler: (req: Request, res: Response) => {
257
- res.sendStatus(200);
258
- }
259
- } as EndpointOptions<EndpointAuthType.ADMIN>);
260
-
261
- endpoint.register(app);
262
- await request(app)
263
- .get(PATH)
264
- .set('Authorization', 'Bearer ' + token)
265
- .expect(200);
266
- });
267
-
268
179
  it('it should reject if the user has no valid JWT', async () => {
269
180
  const endpoint = new Endpoint({
270
181
  ...config,
@@ -15,9 +15,7 @@ import {
15
15
  authHmac,
16
16
  authTls,
17
17
  authStatic,
18
- authAdmin,
19
- FileUploaderConfig,
20
- RequestAdminProps
18
+ FileUploaderConfig
21
19
  } from 'middleware';
22
20
 
23
21
  export enum EndpointMethod {
@@ -37,8 +35,7 @@ export enum EndpointAuthType {
37
35
  JWT = 'jwt',
38
36
  TLS = 'tls',
39
37
  HMAC = 'hmac',
40
- STATIC = 'static',
41
- ADMIN = 'admin'
38
+ STATIC = 'static'
42
39
  }
43
40
 
44
41
  export const EndpointAuthTypes = Object.values(EndpointAuthType);
@@ -54,12 +51,6 @@ export type MiddlewareChainElement<T extends EndpointAuthType> =
54
51
  | Middleware<T>
55
52
  | any;
56
53
 
57
- /** Auth related parameters used with Admin authentication */
58
- interface EndpointAuthAdminParams {
59
- /** [Admin] User permission required to use this endpoint */
60
- permission: string;
61
- }
62
-
63
54
  /** Auth related parameters used with HMAC authentication */
64
55
  interface EndpointAuthHmacParams {
65
56
  /** [HMAC] Secret used for signature */
@@ -86,8 +77,6 @@ interface EndpointAuthSpecificParams {
86
77
  [EndpointAuthType.HMAC]: EndpointAuthHmacParams;
87
78
  /** Auth parameters for static authentication */
88
79
  [EndpointAuthType.STATIC]: any;
89
- /** Auth parameters for admin token authentication */
90
- [EndpointAuthType.ADMIN]: EndpointAuthAdminParams;
91
80
  }
92
81
 
93
82
  export type EndpointAuthParams<T extends EndpointAuthType> =
@@ -114,9 +103,7 @@ export const EndpointAuthHandlers = {
114
103
  /** Auth handler for HMAC authentication */
115
104
  [EndpointAuthType.HMAC]: authHmac,
116
105
  /** Auth handler for static authentication */
117
- [EndpointAuthType.STATIC]: authStatic,
118
- /** Auth handler for admin token authentication */
119
- [EndpointAuthType.ADMIN]: authAdmin
106
+ [EndpointAuthType.STATIC]: authStatic
120
107
  };
121
108
 
122
109
  export type EndpointHandler<T extends EndpointAuthType> = (
@@ -172,18 +159,6 @@ export interface TlsRequest<
172
159
  hosts: Array<string>;
173
160
  }
174
161
 
175
- /** Request type when using HMAC authentication */
176
- export interface AdminRequest<
177
- P = ParamsDictionary,
178
- ResBody = any,
179
- ReqBody = any,
180
- ReqQuery = ParsedQs,
181
- Locals extends Record<string, any> = Record<string, any>
182
- > extends Request<P, ResBody, ReqBody, ReqQuery, Locals> {
183
- /** User that identified using a JWT */
184
- admin: RequestAdminProps;
185
- }
186
-
187
162
  /** Mapping of request types in endpoints based on auth type used */
188
163
  export interface EndpointRequestType {
189
164
  /** Request type for no authentication */
@@ -196,8 +171,6 @@ export interface EndpointRequestType {
196
171
  [EndpointAuthType.HMAC]: Request;
197
172
  /** Auth handler for static authentication */
198
173
  [EndpointAuthType.STATIC]: Request;
199
- /** Auth handler for admin token authentication */
200
- [EndpointAuthType.ADMIN]: AdminRequest;
201
174
  }
202
175
 
203
176
  export type SafeMiddleWareChain = Array<
@@ -100,7 +100,7 @@ describe('Entity - KeySet', function () {
100
100
 
101
101
  it('should read a key from a PEM string', async () => {
102
102
  const pem = await readFile(
103
- process.env.ADMIN_API_ECDSA_PUBLIC_KEY as string,
103
+ process.env.ECDSA_PUBLIC_KEY as string,
104
104
  'utf-8'
105
105
  );
106
106
 
@@ -12,6 +12,5 @@ export * from './fileUploader';
12
12
  export * from './metrics';
13
13
  export * from './requestMetrics';
14
14
  export * from './version';
15
- export * from './authAdmin';
16
15
  export * from './geminiFileUploader';
17
16
  export * from './checkPermission';
@@ -19,7 +19,6 @@ export * from './request';
19
19
  export * from './tlsConfig';
20
20
  export * from './tlsRequest';
21
21
  export * from './sendPush';
22
- export * from './getDynamicLink';
23
22
  export * from './sendEmail';
24
23
 
25
24
  // String manipulation
@@ -25,17 +25,4 @@ describe('Utils - JWT', () => {
25
25
  const result = await jwtVerify(token, TokenIssuer.AUTH_SERVICE);
26
26
  expect(result.sub).to.equal(id);
27
27
  });
28
-
29
- it('should pass a token with one correct audience [Admin-API]', async () => {
30
- const id = randomUUID();
31
- const token = generateAccessToken(id, {
32
- audience: [
33
- process.env.ADMIN_API_ACCESS_TOKEN_AUDIENCE as string,
34
- faker.lorem.word()
35
- ],
36
- issuer: process.env.ADMIN_ACCESS_TOKEN_ISSUER
37
- });
38
- const result = await jwtVerify(token, TokenIssuer.ADMIN_API);
39
- expect(result.sub).to.equal(id);
40
- });
41
28
  });
@@ -7,7 +7,6 @@ import {
7
7
  sign
8
8
  } from 'jsonwebtoken';
9
9
  import fs from 'fs';
10
- import path from 'path';
11
10
  import { UserTokenPayload } from './jwt.types';
12
11
  import { TokenIssuer } from 'const';
13
12
  import { EngineError } from 'entities/EngineError';
@@ -18,7 +17,6 @@ import { envAssert } from 'utils/envAssert';
18
17
  import { reportDebug } from 'utils/report';
19
18
 
20
19
  export let keySet: KeySet | undefined;
21
- export let adminKeySet: KeySet | undefined;
22
20
 
23
21
  const namespace = 'engine:utils:jwt';
24
22
 
@@ -50,24 +48,12 @@ export async function initKeySets(): Promise<void> {
50
48
  }
51
49
  const promise = [keySet.init.bind(keySet)()];
52
50
 
53
- // Load the key set for the admin api
54
- if (!process.env.ADMIN_API_ECDSA_PUBLIC_KEY)
55
- throw new EngineError({
56
- message:
57
- "Admin API's authentication JWT signing public key is not defined"
58
- });
59
- adminKeySet = new KeySet(process.env.ADMIN_API_ECDSA_PUBLIC_KEY, {
60
- pem: true
61
- });
62
- promise.push(adminKeySet.init.bind(adminKeySet)());
63
-
64
51
  await Promise.all(promise);
65
52
  }
66
53
 
67
54
  /** Stop fetching keys regularly */
68
55
  export function shutdownKeySets(): void {
69
56
  if (keySet) keySet.shutdown.bind(keySet)();
70
- if (adminKeySet) adminKeySet.shutdown.bind(adminKeySet)();
71
57
  }
72
58
 
73
59
  /** Get the JWT public key */
@@ -78,7 +64,7 @@ function jwtGetKey(header: JwtHeader, callback: SigningKeyCallback): void {
78
64
  return;
79
65
  }
80
66
  // Check that KeySet has been initialized
81
- if (!keySet || !adminKeySet) {
67
+ if (!keySet) {
82
68
  callback(new EngineError({ message: 'KeySet has not been initialized' }));
83
69
  return;
84
70
  }
@@ -139,9 +125,7 @@ export async function jwtVerify(
139
125
  }
140
126
  assertEnvironment({
141
127
  ACCESS_TOKEN_AUDIENCE: envAssert.isString(),
142
- ACCESS_TOKEN_ISSUER: envAssert.isString(),
143
- ADMIN_API_ACCESS_TOKEN_AUDIENCE: envAssert.isString(),
144
- ADMIN_ACCESS_TOKEN_ISSUER: envAssert.isString()
128
+ ACCESS_TOKEN_ISSUER: envAssert.isString()
145
129
  });
146
130
  let options: VerifyOptions | undefined;
147
131
 
@@ -153,13 +137,6 @@ export async function jwtVerify(
153
137
  algorithms
154
138
  };
155
139
  break;
156
- case TokenIssuer.ADMIN_API:
157
- options = {
158
- audience: [process.env.ADMIN_API_ACCESS_TOKEN_AUDIENCE as string],
159
- issuer: [process.env.ADMIN_ACCESS_TOKEN_ISSUER as string],
160
- algorithms
161
- };
162
- break;
163
140
  default:
164
141
  throw new EngineError({
165
142
  message: `Invalid token issuer specified "${issuer as string}"`
@@ -8,7 +8,6 @@ import { WebError } from 'entities/WebError';
8
8
  import {} from 'middleware/authHmac/authHmac.types';
9
9
  import {} from 'middleware/authJwt/authJwt.types';
10
10
  import {} from 'middleware/authTls/authTls.types';
11
- import {} from 'middleware/authAdmin/authAdmin.types';
12
11
 
13
12
  /** Default generic logger */
14
13
  export function reportInfo(data: InfoLogEntry | string): FullLogEntry {
@@ -62,7 +61,7 @@ export function reportError(
62
61
  ...logEntry,
63
62
  context: {
64
63
  user:
65
- request.user?.id ?? request.hosts?.join(',') ?? request.admin?.email,
64
+ request.user?.id ?? request.hosts?.join(','),
66
65
  httpRequest: {
67
66
  url: request.originalUrl,
68
67
  method: request.method,
package/test/env.ts CHANGED
@@ -15,10 +15,7 @@ process.env = {
15
15
  PAYLOAD_SIGNATURE_SECRET: faker.lorem.word(),
16
16
  ACCESS_TOKEN_AUDIENCE: audience,
17
17
  ACCESS_TOKEN_ISSUER: faker.lorem.word(),
18
- ADMIN_API_ACCESS_TOKEN_AUDIENCE: audience,
19
- ADMIN_ACCESS_TOKEN_ISSUER: faker.lorem.word(),
20
18
  AUTH_SERVICE_PUBLIC_URL: faker.internet.url(),
21
- ADMIN_API_PUBLIC_URL: faker.internet.url(),
22
19
  VALID_IPS: '::ffff:127.0.0.1,127.0.0.1,::1',
23
20
  REDIS_HOST: process.env.REDIS_HOST ?? '127.0.0.1',
24
21
  REDIS_PORT: '6379',
@@ -33,9 +30,7 @@ process.env = {
33
30
  TLS_REQUEST_KEY_PASSPHRASE: path.resolve('certs/ecdsa.key.pub'),
34
31
  ECDSA_PRIVATE_KEY: path.resolve('certs/ecdsa.key'),
35
32
  ECDSA_PUBLIC_KEY: path.resolve('certs/ecdsa.key.pub'),
36
- ADMIN_API_ECDSA_PUBLIC_KEY: path.resolve('certs/ecdsa.key.pub'),
37
33
  GITHUB_WEBHOOK_SECRET: faker.lorem.word(),
38
- LINKS_SERVICE_URL: faker.internet.url(),
39
34
  STATIC_TOKEN: faker.lorem.word(),
40
35
  HOSTNAME: faker.lorem.slug(),
41
36
  ELASTIC_SEARCH_HOST:
package/test/hooks.ts CHANGED
@@ -27,8 +27,6 @@ before(async () => {
27
27
 
28
28
  beforeEach(async () => {
29
29
  process.env = { ...savedEnv };
30
- sequelize.init();
31
- sequelize.addModels(modelArray);
32
30
  });
33
31
 
34
32
  afterEach(async () => {
@@ -1,4 +0,0 @@
1
- import { Request, Response, NextFunction } from 'express';
2
- import { EndpointAuthParams, EndpointAuthType } from '../../entities/Endpoint';
3
- /** Generate a middleware to authenticate the client connection with a Admin api */
4
- export declare function authAdmin(options: EndpointAuthParams<EndpointAuthType.ADMIN>): (request: Request, response: Response, next: NextFunction) => Promise<void>;
@@ -1,105 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.authAdmin = authAdmin;
7
- var _const = require("../../const");
8
- var _EngineError = require("../../entities/EngineError");
9
- var _WebError = require("../../entities/WebError");
10
- var _utils = require("../../utils");
11
- require("./authAdmin.types");
12
- const namespace = 'engine:middleware:authAdmin';
13
-
14
- /** Generate a middleware to authenticate the client connection with a Admin api */
15
- function authAdmin(options) {
16
- if (!options.permission) throw new _EngineError.EngineError({
17
- message: 'Endpoint using admin auth type must specify permission'
18
- });
19
- return async (request, response, next) => {
20
- const [scheme, credentials] = request.headers?.authorization?.split(' ') ?? [];
21
- // No bearer token has been sent
22
- if (!credentials || scheme.toLowerCase() !== 'bearer') {
23
- throw new _WebError.WebError({
24
- errorCode: 'unauthorized',
25
- statusCode: 401,
26
- message: 'No bearer token found',
27
- data: {
28
- authorization: request.headers?.authorization
29
- }
30
- });
31
- }
32
- (0, _utils.reportDebug)({
33
- namespace,
34
- message: 'Performing JWT authentication',
35
- data: {
36
- scheme,
37
- credentials
38
- }
39
- });
40
- // Verify token and extract its payload
41
- const payload = await (0, _utils.jwtVerify)(credentials, _const.TokenIssuer.ADMIN_API);
42
- (0, _utils.reportDebug)({
43
- namespace,
44
- message: 'Extracted user data from JWT',
45
- data: {
46
- payload,
47
- credentials
48
- }
49
- });
50
- if (!payload.per) throw new _WebError.WebError({
51
- errorCode: 'unauthorized',
52
- statusCode: 401,
53
- message: `User token does not contain any permission claim`
54
- });
55
-
56
- // User Permission
57
- const permissions = payload.per;
58
- const userPermissions = permissions instanceof Array ? permissions : [permissions];
59
- (0, _utils.reportDebug)({
60
- namespace,
61
- message: 'Performing Admin Permission check',
62
- data: {
63
- permissions,
64
- endpointPermission: options.permission,
65
- adminPermissions: userPermissions
66
- }
67
- });
68
- if (!checkUserPermissions(userPermissions, options.permission)) {
69
- throw new _WebError.WebError({
70
- errorCode: 'unauthorized',
71
- statusCode: 401,
72
- message: `User does not have required permission "${options.permission}"`,
73
- data: {
74
- userPermissions
75
- }
76
- });
77
- }
78
-
79
- // The user object on the request is hydrated with data from the token
80
- request.admin = {
81
- ...request.admin,
82
- email: payload.sub,
83
- permissions: userPermissions
84
- };
85
- next();
86
- };
87
- }
88
-
89
- /** */
90
- function checkUserPermissions(userPermissions, endpointPermission) {
91
- const endpointPermissionParts = endpointPermission.split(':');
92
- userPermissionLoop: for (const permission of userPermissions) {
93
- const permissionParts = permission.split(':');
94
-
95
- // Ignore if both are not same length
96
- if (permissionParts.length !== endpointPermissionParts.length) continue userPermissionLoop;
97
- for (let i = 0; i < permissionParts.length; i++) {
98
- // Wildcards get automatic validation, otherwise it must match with the same part of the endpoint permission
99
- if (permissionParts[i] !== '*' && permissionParts[i] !== endpointPermissionParts[i]) continue userPermissionLoop;
100
- }
101
- return true;
102
- }
103
- return false;
104
- }
105
- //# sourceMappingURL=authAdmin.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"authAdmin.js","names":["_const","require","_EngineError","_WebError","_utils","namespace","authAdmin","options","permission","EngineError","message","request","response","next","scheme","credentials","headers","authorization","split","toLowerCase","WebError","errorCode","statusCode","data","reportDebug","payload","jwtVerify","TokenIssuer","ADMIN_API","per","permissions","userPermissions","Array","endpointPermission","adminPermissions","checkUserPermissions","admin","email","sub","endpointPermissionParts","userPermissionLoop","permissionParts","length","i"],"sources":["../../../src/middleware/authAdmin/authAdmin.ts"],"sourcesContent":["import { Request, Response, NextFunction } from 'express';\nimport { TokenIssuer } from 'const';\nimport { EndpointAuthParams, EndpointAuthType } from 'entities/Endpoint';\nimport { EngineError } from 'entities/EngineError';\nimport { WebError } from 'entities/WebError';\nimport { reportDebug, jwtVerify } from 'utils';\nimport {} from './authAdmin.types';\n\nconst namespace = 'engine:middleware:authAdmin';\n\n/** Generate a middleware to authenticate the client connection with a Admin api */\nexport function authAdmin(\n options: EndpointAuthParams<EndpointAuthType.ADMIN>\n): (request: Request, response: Response, next: NextFunction) => Promise<void> {\n if (!options.permission)\n throw new EngineError({\n message: 'Endpoint using admin auth type must specify permission'\n });\n return async (\n request: Request,\n response: Response,\n next: NextFunction\n ): Promise<void> => {\n const [scheme, credentials] =\n request.headers?.authorization?.split(' ') ?? [];\n // No bearer token has been sent\n if (!credentials || scheme.toLowerCase() !== 'bearer') {\n throw new WebError({\n errorCode: 'unauthorized',\n statusCode: 401,\n message: 'No bearer token found',\n data: { authorization: request.headers?.authorization }\n });\n }\n reportDebug({\n namespace,\n message: 'Performing JWT authentication',\n data: { scheme, credentials }\n });\n // Verify token and extract its payload\n const payload = await jwtVerify(credentials, TokenIssuer.ADMIN_API);\n reportDebug({\n namespace,\n message: 'Extracted user data from JWT',\n data: { payload, credentials }\n });\n\n if (!payload.per)\n throw new WebError({\n errorCode: 'unauthorized',\n statusCode: 401,\n message: `User token does not contain any permission claim`\n });\n\n // User Permission\n const permissions = payload.per;\n const userPermissions =\n permissions instanceof Array ? permissions : [permissions];\n\n reportDebug({\n namespace,\n message: 'Performing Admin Permission check',\n data: {\n permissions,\n endpointPermission: options.permission,\n adminPermissions: userPermissions\n }\n });\n\n if (!checkUserPermissions(userPermissions, options.permission)) {\n throw new WebError({\n errorCode: 'unauthorized',\n statusCode: 401,\n message: `User does not have required permission \"${options.permission}\"`,\n data: { userPermissions }\n });\n }\n\n // The user object on the request is hydrated with data from the token\n request.admin = {\n ...request.admin,\n email: payload.sub,\n permissions: userPermissions\n };\n\n next();\n };\n}\n\n/** */\nfunction checkUserPermissions(\n userPermissions: Array<string>,\n endpointPermission: string\n): boolean {\n const endpointPermissionParts = endpointPermission.split(':');\n userPermissionLoop: for (const permission of userPermissions) {\n const permissionParts = permission.split(':');\n\n // Ignore if both are not same length\n if (permissionParts.length !== endpointPermissionParts.length)\n continue userPermissionLoop;\n\n for (let i = 0; i < permissionParts.length; i++) {\n // Wildcards get automatic validation, otherwise it must match with the same part of the endpoint permission\n if (\n permissionParts[i] !== '*' &&\n permissionParts[i] !== endpointPermissionParts[i]\n )\n continue userPermissionLoop;\n }\n return true;\n }\n return false;\n}\n"],"mappings":"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","ignoreList":[]}
@@ -1,16 +0,0 @@
1
- declare global {
2
- namespace Express {
3
- /** Express request object */
4
- interface Request {
5
- /** User that identified using a JWT */
6
- admin?: RequestAdminProps;
7
- }
8
- }
9
- }
10
- /** Admin auth properties of the request */
11
- export interface RequestAdminProps {
12
- /** Email address of the user */
13
- email: string;
14
- /** List of permissions that the user has */
15
- permissions: Array<string>;
16
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- //# sourceMappingURL=authAdmin.types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"authAdmin.types.js","names":[],"sources":["../../../src/middleware/authAdmin/authAdmin.types.ts"],"sourcesContent":["// Override the Express request object to add the files\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace Express {\n /** Express request object */\n interface Request {\n /** User that identified using a JWT */\n admin?: RequestAdminProps;\n }\n }\n}\n\n/** Admin auth properties of the request */\nexport interface RequestAdminProps {\n /** Email address of the user */\n email: string;\n /** List of permissions that the user has */\n permissions: Array<string>;\n}\n"],"mappings":"","ignoreList":[]}
@@ -1,2 +0,0 @@
1
- export * from './authAdmin';
2
- export * from './authAdmin.types';
@@ -1,28 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- var _authAdmin = require("./authAdmin");
7
- Object.keys(_authAdmin).forEach(function (key) {
8
- if (key === "default" || key === "__esModule") return;
9
- if (key in exports && exports[key] === _authAdmin[key]) return;
10
- Object.defineProperty(exports, key, {
11
- enumerable: true,
12
- get: function () {
13
- return _authAdmin[key];
14
- }
15
- });
16
- });
17
- var _authAdmin2 = require("./authAdmin.types");
18
- Object.keys(_authAdmin2).forEach(function (key) {
19
- if (key === "default" || key === "__esModule") return;
20
- if (key in exports && exports[key] === _authAdmin2[key]) return;
21
- Object.defineProperty(exports, key, {
22
- enumerable: true,
23
- get: function () {
24
- return _authAdmin2[key];
25
- }
26
- });
27
- });
28
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":["_authAdmin","require","Object","keys","forEach","key","exports","defineProperty","enumerable","get","_authAdmin2"],"sources":["../../../src/middleware/authAdmin/index.ts"],"sourcesContent":["export * from './authAdmin';\nexport * from './authAdmin.types';\n"],"mappings":";;;;;AAAA,IAAAA,UAAA,GAAAC,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAH,UAAA,EAAAI,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAL,UAAA,CAAAK,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAT,UAAA,CAAAK,GAAA;IAAA;EAAA;AAAA;AACA,IAAAK,WAAA,GAAAT,OAAA;AAAAC,MAAA,CAAAC,IAAA,CAAAO,WAAA,EAAAN,OAAA,WAAAC,GAAA;EAAA,IAAAA,GAAA,kBAAAA,GAAA;EAAA,IAAAA,GAAA,IAAAC,OAAA,IAAAA,OAAA,CAAAD,GAAA,MAAAK,WAAA,CAAAL,GAAA;EAAAH,MAAA,CAAAK,cAAA,CAAAD,OAAA,EAAAD,GAAA;IAAAG,UAAA;IAAAC,GAAA,WAAAA,CAAA;MAAA,OAAAC,WAAA,CAAAL,GAAA;IAAA;EAAA;AAAA","ignoreList":[]}
@@ -1,3 +0,0 @@
1
- import { getDynamicLinksOptions } from './getDynamicLink.types';
2
- /** Fetch a dynamic link from the links service */
3
- export declare function getDynamicLink(path: string, options?: getDynamicLinksOptions): Promise<string>;
@@ -1,28 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.getDynamicLink = getDynamicLink;
7
- var _getDynamicLink = require("./getDynamicLink.validate");
8
- var _tlsRequest = require("../tlsRequest");
9
- /** Fetch a dynamic link from the links service */
10
- async function getDynamicLink(path, options = {}) {
11
- (0, _getDynamicLink.validateDynamicLinkEnvironment)();
12
- const option = {
13
- method: 'get',
14
- url: '/link',
15
- baseURL: process.env.LINKS_SERVICE_URL,
16
- params: {
17
- path,
18
- short: options.short ?? true
19
- }
20
- };
21
- const {
22
- data: {
23
- link
24
- }
25
- } = await (0, _tlsRequest.tlsRequest)(option);
26
- return link;
27
- }
28
- //# sourceMappingURL=getDynamicLink.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"getDynamicLink.js","names":["_getDynamicLink","require","_tlsRequest","getDynamicLink","path","options","validateDynamicLinkEnvironment","option","method","url","baseURL","process","env","LINKS_SERVICE_URL","params","short","data","link","tlsRequest"],"sources":["../../../src/utils/getDynamicLink/getDynamicLink.ts"],"sourcesContent":["import { AxiosRequestConfig } from 'axios';\nimport {\n getDynamicLinksOptions,\n DynamicLinkResponseBody\n} from './getDynamicLink.types';\nimport { validateDynamicLinkEnvironment } from './getDynamicLink.validate';\nimport { tlsRequest } from 'utils/tlsRequest';\n\n/** Fetch a dynamic link from the links service */\nexport async function getDynamicLink(\n path: string,\n options: getDynamicLinksOptions = {}\n): Promise<string> {\n validateDynamicLinkEnvironment();\n const option: AxiosRequestConfig = {\n method: 'get',\n url: '/link',\n baseURL: process.env.LINKS_SERVICE_URL,\n params: {\n path,\n short: options.short ?? true\n }\n };\n const {\n data: { link }\n } = await tlsRequest<DynamicLinkResponseBody>(option);\n return link;\n}\n"],"mappings":";;;;;;AAKA,IAAAA,eAAA,GAAAC,OAAA;AACA,IAAAC,WAAA,GAAAD,OAAA;AAEA;AACO,eAAeE,cAAcA,CAClCC,IAAY,EACZC,OAA+B,GAAG,CAAC,CAAC,EACnB;EACjB,IAAAC,8CAA8B,EAAC,CAAC;EAChC,MAAMC,MAA0B,GAAG;IACjCC,MAAM,EAAE,KAAK;IACbC,GAAG,EAAE,OAAO;IACZC,OAAO,EAAEC,OAAO,CAACC,GAAG,CAACC,iBAAiB;IACtCC,MAAM,EAAE;MACNV,IAAI;MACJW,KAAK,EAAEV,OAAO,CAACU,KAAK,IAAI;IAC1B;EACF,CAAC;EACD,MAAM;IACJC,IAAI,EAAE;MAAEC;IAAK;EACf,CAAC,GAAG,MAAM,IAAAC,sBAAU,EAA0BX,MAAM,CAAC;EACrD,OAAOU,IAAI;AACb","ignoreList":[]}
@@ -1,10 +0,0 @@
1
- /** Options to fetch dynamic links */
2
- export interface getDynamicLinksOptions {
3
- /** Make a shortened link */
4
- short?: boolean;
5
- }
6
- /** Dynamic link query server response */
7
- export interface DynamicLinkResponseBody {
8
- /** The generated dynamic link */
9
- link: string;
10
- }
@@ -1,2 +0,0 @@
1
- "use strict";
2
- //# sourceMappingURL=getDynamicLink.types.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"getDynamicLink.types.js","names":[],"sources":["../../../src/utils/getDynamicLink/getDynamicLink.types.ts"],"sourcesContent":["/** Options to fetch dynamic links */\nexport interface getDynamicLinksOptions {\n /** Make a shortened link */\n short?: boolean;\n}\n\n/** Dynamic link query server response */\nexport interface DynamicLinkResponseBody {\n /** The generated dynamic link */\n link: string;\n}\n"],"mappings":"","ignoreList":[]}